content stringlengths 5 1.05M |
|---|
from typing import Any, Dict, List, Optional, Tuple
from autoPyTorch.pipeline.components.base_choice import autoPyTorchChoice
from autoPyTorch.pipeline.components.preprocessing.tabular_preprocessing.TabularColumnTransformer import \
TabularColumnTransformer
from autoPyTorch.pipeline.components.preprocessing.tabula... |
#!/usr/bin/python
"""This is the flask server of the a windows VM
It accepts the requests in the form of protobufs
and executes the same in the specified path
"""
import argparse
import logging
import os
from pathlib import Path
import shutil
import subprocess
import threading
import timeit
import sys
import reque... |
# Tai Sakuma <[email protected]>
import ipywidgets as widgets
from IPython.display import display
from .base import Presentation
##__________________________________________________________________||
class ProgressBarJupyter(Presentation):
def __init__(self):
super().__init__()
self.interval = ... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import print_function, unicode_literals
import frappe
def execute():
frappe.reload_doc("accounts", "doctype", "account")
account_table_columns = frappe.db.get_table_columns... |
#!/usr/bin/python
import os.path
import cppcodebase
import random
def CreateLibMakefile(lib_number, classes):
os.chdir(cppcodebase.lib_name(lib_number))
handle = file("Makefile", "w");
handle.write ("""COMPILER = g++
INC = -I..
CCFLAGS = -Wall $(INC)
ARCHIVE = ar
DEPEND = makedepend
.SUFFIXES: .o .cpp
... |
import tensorflow as tf
import tensorflow_hub as hub
from PIL import Image
import numpy as np
def load_model(model_path):
reloaded_model = tf.keras.models.load_model(model_path, custom_objects={'KerasLayer':hub.KerasLayer})
return reloaded_model
def load_process_image(image_path, image_size):
# Open ... |
from py2neo import Node, Relationship, Graph, authenticate
from py2neo.ogm import GraphObject, Label, Property, RelatedFrom, RelatedTo
# from py2neo import Database
# basic Node, Relationship constructor
a = Node("Freelancer",
name="dono",
email="[email protected]",
noTelp="081081081081"
... |
#!/usr/bin/python
# encoding=utf-8
import sys
if sys.version_info[0] == 2:
# Python2
import core.AepSdkRequestSend as AepSdkRequestSend
else:
# Python3
from apis.core import AepSdkRequestSend
#参数productId: 类型long, 参数不可以为空
# 描述:
def QueryProduct(appKey, appSecret, productId):
path = '/aep_produc... |
#!/usr/bin/env python
import sys
if sys.version < '2.6':
raise ImportError("Python versions older than 2.6 are not supported.")
import glob
import os.path
from setuptools import (setup, find_packages)
# set basic metadata
PACKAGENAME = 'JLAB_TESS'
DISTNAME = 'JLAB_TESS'
AUTHOR = 'Kevin Burdge'
AUTHOR_EMAIL = 'k... |
from firedrake import *
from firedrake.norms import errornorm
import os
## Class to solve an Elasticity problem of a bending rod.
#
# This class solves the Elasticity problem \f$-\nabla\cdot \sigma = f\f$ for a long
# rod under gravity load with
# \f$P_k\f$-finite elements in each component.
class ElasticRod:
... |
from selenium import webdriver
from facebook_credentials import username,password
from time import sleep
class TinderBot():
def __init__(self):
self.driver = webdriver.Chrome()
def login(self):
self.driver.get('https://tinder.com')
sleep(5)
fb_btn = self.driver.find_element_b... |
from merkki import Sprite
class Liikkuja(Sprite):
def __init__(self, x, y, merkki, taso):
print("liikkuja init")
super(Liikkuja, self).__init__(x, y, merkki)
self.taso = taso
def liiku(self, suunta):
print("liikkuja liiku")
uusix = self.x + suunta[0]
uusiy = sel... |
# Save to HDF because cPickle fails with very large arrays
# https://github.com/numpy/numpy/issues/2396
import h5py
import numpy as np
import tempfile
import unittest
def dict_to_hdf(fname, d):
"""
Save a dict-of-dict datastructure where values are numpy arrays
to a .hdf5 file
"""
with h5py.File(fn... |
# !/usr/bin/hfo_env python3
# encoding utf-8
import argparse
import os
import pickle
import numpy as np
from agents.plastic_dqn_v1.agent.replay_buffer import ExperienceBuffer, \
LearnBuffer
from agents.plastic_dqn_v1 import config
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.... |
from python.code_challenges.linked_list.linked_list.linked_list import Linked_list
class Hashtable(Linked_list):
def __init__(self, size=1024, prime=564):
self.size = size
self.array = [None] * size
self.prime = prime
def add(self, key, value):
index = self.hash(key)
i... |
from pathlib import Path
import pandas as pd
from matplotlib import pyplot as plt
from scipy import stats
from settings import PROJECT_ID
REPLICATION_DIR = Path('./ai2_replication')
BQ_EXPORT_PATH = REPLICATION_DIR / 'ai_papers_any_author.pkl.gz'
CITATION_COUNT_FIELD = "EstimatedCitation"
FIGURE_PATH = REPLICATION_D... |
#!/usr/bin/python3
import sqlite3
def studentData():
con = sqlite3.connect('student.db')
cur = con.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS student(id INTEGER PRIMARY KEY, StdID text, FirstName text, LastName text, DoB text, Age text, Gender text, Adress text, Mobile text, ImgPath text)")
co... |
import torch
import torch.nn.functional as F
from torch import nn
from torch import sigmoid, tanh, relu_
class LockedDropout(nn.Module):
def __init__(self, dropout):
self.dropout = dropout
super().__init__()
def forward(self, x):
if not self.training or not self.dropout:
... |
import ast
import sys
import os.path
from glob import glob
from collections import defaultdict
class Node(object):
"""Tree structure for managing python dependencies"""
@classmethod
def new_nonleaf(cls):
return Node(False, defaultdict(Node.new_nonleaf))
def __init__(self, isleaf, children_dic... |
import logging
from threading import Event
from __config__ import logging_config as config
from ..global_objects import setup_all
from ..monitors import monitorfactory # do not delete!!
logging.basicConfig(
level=config.level, format=config.loggin_format, filename=config.filename
)
start_event = Event()
__all_... |
import neural_network_lyapunov.lyapunov as lyapunov
import neural_network_lyapunov.hybrid_linear_system as hybrid_linear_system
import neural_network_lyapunov.utils as utils
import neural_network_lyapunov.relu_system as relu_system
import unittest
import numpy as np
import torch
import gurobipy
class TestLyapunovDi... |
from setuptools import setup, find_packages
VERSION = '0.0.1'
DESCRIPTION = 'drawable image creator'
LONG_DESCRIPTION = 'prepare images for use in android studio projects'
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="drimg",
version=VERSION,
descriptio... |
import time
import board
import busio
from adafruit_as726x import Adafruit_AS726x
#maximum value for sensor reading
max_val = 16000
#max number of characters in each graph
max_graph = 80
def graph_map(x):
return min(int(x * max_graph / max_val), max_graph)
# Initialize I2C bus and sensor.
i2c... |
import time
class FPSCounter:
def __init__(self):
self.fps = 0.0
self._last_timestamp = self._millis()
@staticmethod
def _millis():
return time.time() * 1000.0
def reset(self):
self._last_timestamp = self._millis()
def update(self):
ts = self._millis()
... |
# -*- coding: utf-8 -*-
# Copyright (C) 2016-2020 Mag. Christian Tanzer All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. [email protected]
# #*** <License> ************************************************************#
# This module is part of the package CAL.
#
# This module is licensed under the terms o... |
"""Update server attributes"""
import os
from configparser import ConfigParser
from cbw_api_toolbox.cbw_api import CBWApi
CONF = ConfigParser()
CONF.read(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'api.conf'))
CLIENT = CBWApi(CONF.get('cyberwatch', 'url'), CONF.get('cyberwatch', 'api_key'), CONF.g... |
# -*- coding: utf-8 -*-
__version__ = '0.1.2'
__author__ = 'Sedad Delalic'
__email__ = '[email protected]'
from flask import Blueprint, redirect
from flask_security import Security, SQLAlchemyUserDatastore
from flask_admin import Admin
from flask_security import current_user, logout_user
from flask import current_app
f... |
import pytest
from pytest_lazyfixture import lazy_fixture
import numpy as np
from copy import deepcopy
@pytest.mark.parametrize('rf_classifier',
[lazy_fixture('iris_data')],
indirect=True,
ids='clf=rf_{}'.format,
)
@... |
'''
.. console - Comprehensive utility library for ANSI terminals.
.. © 2018, Mike Miller - Released under the LGPL, version 3+.
Experimental terminfo support, under construction.
Enables terminfo sequence lookup with console::
import console.terminfo
or use the environment variable::
... |
#####
from model.Data import UsFo
import re
class UserHelper:
def __init__(self, app):
self.app = app
def Open_home_page(self):
wd = self.app.wd
if not (wd.current_url.endswith("/") and len(wd.find_elements_by_name("searchform")) > 0):
wd.get("http://localhost/addressbook/"... |
import sys
import serial.tools.miniterm
def open_terminal(_port="COM11", reset=1):
control_signal = '0' if reset else '1'
control_signal_b = not reset
sys.argv = [sys.argv[0], _port, '115200', '--dtr='+control_signal, '--rts='+control_signal, '--filter=direct']
serial.tools.miniterm.main(default_port=... |
#!/usr/bin/env python
from __future__ import print_function
import glob
import sys
import time
from k40nano import NanoPlotter, SvgPlotter, PngPlotter, FileWriteConnection, PrintConnection, MockUsb
from EgvParser import parse_egv
from GcodeParser import parse_gcode
from PngParser import parse_png
NANO_VERSION = "0... |
import pytest
from bots.economy.grains import grains_command
@pytest.mark.bots
@pytest.mark.vcr
def test_grains_command(mocker, recorder):
mocker.patch("bots.helpers.uuid_get", return_value="1")
value = grains_command()
recorder.capture(value)
|
from utime import sleep_us
from machine import Pin, PWM, ADC, time_pulse_us
WIFIS = dict({
"": ""})
# directions
STOP = 0
LEFT = 1
RIGHT = 2
FORWARD = 3
BACKWARD = 4
# Battery resistor ladder ratio
BATTERY_COEFF = 2.25
# Ultrasonic sensor calibration
ULTRASONIC_OFFSET = 800
# Servo timing
MOTOR_LEFT_TUNING = 33
MO... |
from psnawp_api import psnawp_exceptions
# Class Search
# Used to search for users from their PSN ID and get their Online ID
class Search:
base_uri = 'https://www.playstation.com'
def __init__(self, request_builder):
self.request_builder = request_builder
def universal_search(self, search_query)... |
import re
def parse(file):
NOTES = 1
DATA = 2
state = NOTES
notes = []
data = []
for row in file:
row = row.strip()
if not row:
continue
if state == NOTES:
if re.match('^Date', row):
state = DATA
else:
# Strip non-ascii characters.
# This should reall... |
from webpie import WPApp, WPHandler, WPStaticHandler
import sys, sqlite3, json, time
class DataHandler(WPHandler):
Bin = {
"y": 3600*24*7,
"m": 3600*24,
"w": 3600,
"d": 1200
}
Window = {
"y": 3600*24*365,
"m": ... |
from math import sqrt
co_xa = float(input("Digite a coordenada de x no ponto a: "))
co_xb = float(input("Digite a coordenada de x no ponto b: "))
co_yb = float(input("Digite a coordenada de y no ponto a: "))
co_yb = float(input("Digite a coordenada de y no ponto b: "))
distancia = sqrt((co_xa - co_xb)**2) + ((co_y... |
import json
data= 'data/spider/dev.json'
table= 'spider/tables.json'
d= open(data)
t=open(table)
queries= json.load(d)
schema=json.load(t)
# function to add to JSON
#value_list=[]
#db_list=['flight_2', 'wta_1']
#db_list=['concert_singer', 'pets_1', 'car_1', 'flight_2', 'cre_Doc_Template_Mgt', 'course_teach', 'world_... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.8 on 2016-08-05 22:17
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migration... |
from pprint import pformat
from lona.view import LonaView
from lona.html import (
TextInput,
CheckBox,
TextArea,
Button,
Select,
HTML,
Div,
H2,
Pre,
)
class DataBindingView(LonaView):
def handle_request(self, request):
check_box = CheckBox(bubble_up=True)
text... |
import LogicPy.main_functions as main_functions
import LogicPy.conversion as conversion
import LogicPy.gates as gates
import LogicPy.flipflops as flipflops
import LogicPy.combination_logic as combination_logic
import LogicPy.display_terminals as display_terminals
import LogicPy.arithematic_circuit as arithematic_circui... |
#!/usr/bin/python
"""Utility to show pywikibot colors."""
#
# (C) Pywikibot team, 2016-2020
#
# Distributed under the terms of the MIT license.
#
import pywikibot
from pywikibot.tools import itergroup
from pywikibot.tools.formatter import color_format
from pywikibot.userinterfaces.terminal_interface_base import colors
... |
import requests
import matplotlib.pyplot as plt
from bs4 import BeautifulSoup
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.font_manager as fm
import os
#사용자 설정에서 폰트 배포 필요
font_location = "C:/Users/rnfek/miniconda3/Lib/site-packages/matplotlib/mpl-data/fonts/tt... |
# -*- coding: utf-8 -*-
from model.contact import Contact
def test_add_contact(app):
app.contact.create(Contact(fname="Albert", sname="Ivanovich", lname="Petrov", address="Nikolaevskiy avenu",
email="[email protected]", tel="+79994447878"))
|
# The example is based on the coco example in
# https://www.dlology.com/blog/how-to-train-detectron2-with-custom-coco-datasets/
import torch # pylint: disable=import-error
import numpy as np
import bentoml
import sys
import traceback
from typing import Dict
from bentoml.frameworks.detectron import DetectronModelArtif... |
import os
r = os.system('./kindlegen ./OEPUB/content.opf') |
import json
from jinja2 import BaseLoader, TemplateNotFound
from sectile import Sectile
class SectileLoader(BaseLoader):
def __init__(self, fragments_dir):
self.sectile = Sectile(fragments=fragments_dir)
self.prepared_path = None
self.prepared_base = None
self.prepared_dimensions ... |
#!/usr/bin/env python3
import numpy as np
# import matplotlib.pyplot as plt
import operator as op
from src.sdesolver import Solver
import time
if __name__ == '__main__':
L = 9
N = 2
T = np.array([[(5, 0), (5, 0)],
[(5, 0), (5, np.inf)],
[(5, -np.inf), (5, 0)],
... |
units = {
1: 'Byte',
2: 'Kylobyte',
3: 'Megabyte',
4: 'Gigabyte',
5: 'Terabyte'
}
class UnitConverter:
def __init__(self) -> None:
self.get_unit_to_provide()
self.get_unit_to_converter()
self.get_value()
self.converter()
def show_units(self) -> None:
... |
import numpy as np
import pytest
import xarray as xr
from pyomeca import Analogs, Angles, Markers, Rototrans
from ._constants import ANALOGS_DATA, EXPECTED_VALUES, MARKERS_DATA
from .utils import is_expected_array
def test_analogs_creation():
dims = ("channel", "time")
array = Analogs()
np.testing.asser... |
from django.apps import AppConfig
class UserUiConfig(AppConfig):
name = 'user_ui'
|
import re
import os
import csv
import sys
import json
import time
import glob
import zipfile
import string
import traceback
from pathlib import Path
from typing import Optional
from .utils import flatten_json, get_nearest_value
import requests
import click
from ..settings import GITHUB_TOKEN
from .utils import write... |
"""
Soundscape information retrieval
Author: Tzu-Hao Harry Lin ([email protected])
"""
import plotly.graph_objects as go
import pandas as pd
def interactive_matrix(input_data, f, vmin=None, vmax=None, x_title=None, y_title=None, x_date=True, figure_title=None, figure_plot=True, html_save=False, html_name='Interacti... |
# From http://wiki.xentax.com/index.php?title=Blender_Import_Guide
bl_info = {
"name": "Name of the add-on",
"author": "Name of the author of the add-on, some of these are optional",
"location": "File > Import > Name of script",
"description": "Description of the add-on",
"category": "Import-Expor... |
import requests
print(requests.__version__)
print(requests.get("http://google.com/"))
x = requests.get("https://raw.github.com/Faiyaz42/CMPUT404/main/script.py")
print(x.text)
|
import pytest
from fastai import *
from fastai.text import *
def text_df(labels):
data = []
texts = ["fast ai is a cool project", "hello world"] * 20
for ind, text in enumerate(texts):
sample = {}
sample["label"] = labels[ind%len(labels)]
sample["text"] = text
data.append(sa... |
#! /usr/bin/env python
#-*- coding:utf-8 -*
from openpyxl.reader.excel import load_workbook
import codecs
import sys
def get_type(i_kind):
if (i_kind == u'应用名称'):
return 'fine'
elif (i_kind == u'泛需求'):
return 'general'
else:
print 'Error' + i_kind
sys.exit()
def print_score(d_score):
print 'Total Score\t' ... |
from time import sleep
import platform
import os
def screen_print(loader=True) -> None:
"""Print title screen with a simple toggle loader"""
intro_text = '- ACME EMPLOYEE PAYMENT CALCULATOR -'
center_values = '*' * ((80 - len(intro_text)) // 2)
print('*' * 80)
print(center_values + intro_text + ce... |
from typing import List, Text, Any
import torch.nn as nn
from models.cell_operations import ResNetBasicblock
from models.cell_infers.cells import InferCell
class DynamicShapeTinyNet(nn.Module):
def __init__(self, channels: List[int], genotype: Any, num_classes: int):
super(DynamicShapeTinyNet, self).__init__(... |
#!/usr/bin/python3
"""
This script adds to an Expression Atlas' EB-eye XML dump tissue and disease information retrieved
from condensed sdrf files.
Author: Robert Petryszak ([email protected])
"""
from xml.dom import minidom
from re import sub, match, IGNORECASE
import os
import sys
import time
import argparse
c... |
import os
import subprocess
from kf_model_omop.utils.db import _select_config
from kf_model_omop.config import MODELS_FILE_PATH, ROOT_DIR
def auto_gen_models(config_name=None, refresh_schema=False,
model_filepath=MODELS_FILE_PATH):
"""
Autogenerate the OMOP SQLAlchemy models
Use sqla... |
from django.db import models
import calendar
from datetime import date
class Utility(models.Model):
name = models.CharField(max_length=1024)
def __str__(self):
return str(self.name)
class Bill(models.Model):
utility = models.ForeignKey(Utility, on_delete=models.CASCADE)
charge = models.Deci... |
"""
© https://sudipghimire.com.np
Create a class Employee that contains different attributes.
- id
- first_name
- last_name
- project
- department
- salary
Make attributes project, department, and salary as private and use getter and setter methods to get and
set respective values
id should be private and can only b... |
import pandas as pd
import numpy as np
import math
def score(data):
score=True
## Calification rules
# Rodilla
max_border_1 = 210 # Max threshold for valid point
min_border_1 = 0 # Min threshold for valid point
min_thr_1 = 120
mid_thr_1 = 110
# Cadera
max_border_2 =... |
# -*- coding: utf-8 -*-
"""
Author: Juliette Monsel
License: GNU GPLv3
Source: https://github.com/j4321/tkColorPicker
Edited by RedFantom for Python 2/3 cross-compatibility and docstring formatting
tkcolorpicker - Alternative to colorchooser for Tkinter.
Copyright 2017 Juliette Monsel <[email protected]>
tkcol... |
import os
import random
from torchelper.utils.dist_util import get_rank
from torchelper.models.model_builder import ModelBuilder
from tqdm import tqdm
import torch
import time
import torch.distributed as dist
import torch.multiprocessing as mp
from torchelper.utils.config import merge_cfg
from torchelper.utils.cls_ut... |
from typing import Callable
from starlette.requests import Request
from starlette.responses import JSONResponse
from app.src.exception import APIException
def http_exception_factory(status_code: int) -> Callable:
def http_exception(_: Request, exception: APIException) -> JSONResponse:
return JSONRespons... |
from abc import ABCMeta
from functools import lru_cache
from PIL import Image
import numpy as np
from torch.utils.data.dataset import Dataset as TorchDataset
from torchvision.transforms import ToTensor, Compose
from utils import coerce_to_path_and_check_exist, use_seed
from utils.path import DATASETS_PATH
class _Ab... |
# Standard Library
import configparser
# Third Party
import pytest
# CrazyHusk
from crazyhusk import config
def test_config_init(empty_parser: config.UnrealConfigParser) -> None:
assert isinstance(empty_parser, configparser.RawConfigParser)
@pytest.mark.parametrize(
"input_string,output_string",
[
... |
import numpy as np
import os
import cPickle as pickle
import seaborn as sns
sns.set(style="white", palette="Set2")
import matplotlib.pyplot as plt
log_dir = "./experiments/log/backprop/"
log_dir = "./experiments/paper/temp/"
# filename = log_dir + "01-11-2016--11-51-41-0.p"
for filename in sorted(os.listdir(log_dir... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from logging import getLogger
from unittest import TestCase
from conda.base.context import context
from conda.common.compat import text_type
from conda.models.channel import Channel
from conda.models.index_record... |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 15 19:59:16 2021
@author: abhay.saini
"""
import argparse
import pandas as pd
import torch
import numpy as np
import datasets
import transformers
from transformers import Trainer, TrainingArguments
import nltk
from pyarrow import csv
from transformers impor... |
'''Example test script.
Basic checks of device before processed
Input Variables:
args - arguments dictionary given to demo tester that may be used to
changed nature of test.
dev - Example device under test
name - Name of test being run.
results - Results map of all tests.
Test Specifi... |
import functools
import inspect
import logging
from concurrent.futures import ProcessPoolExecutor
from fastapi import FastAPI
from fasture import models
from fasture import task_db
from fasture.plugin_mgr import get_plugin_manager
from fasture.routers import jobs, tasks
log = logging.getLogger(__name__)
executor = ... |
import tkinter as tk
from tkinter import Menu, Tk, Text, DISABLED, RAISED,Frame, FLAT, Button, Scrollbar, Canvas, END
from tkinter import messagebox as MessageBox
from tkinter import ttk
from campo import Campo
from arbol import Arbol
import http.client
#Metodo GET para probar peticiones al servidor
def myGET():
... |
""" CISCO_ENTITY_SENSOR_MIB
The CISCO\-ENTITY\-SENSOR\-MIB is used to monitor
the values of sensors in the Entity\-MIB (RFC 2037)
entPhysicalTable.
"""
from collections import OrderedDict
from ydk.types import Entity, EntityPath, Identity, Enum, YType, YLeaf, YLeafList, YList, LeafDataList, Bits, Empty, Decimal64
... |
from django.apps import apps as django_apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
SETTINGS = None
def load_settings():
global SETTINGS
try:
SETTINGS = settings.BASE_BACKEND
except AttributeError:
SETTINGS = {}
load_settings()
def get_... |
# -*- coding: utf-8
from django.apps import AppConfig
class DjangoGrpcConfig(AppConfig):
name = 'django_grpc'
verbose_name = 'Django gRPC server'
|
from datetime import datetime, timedelta
from babel.dates import format_timedelta, format_date
from collections import namedtuple
import pandas as pd
FeedparserTime = namedtuple(
"FeedparserTime",
[
"tm_year",
"tm_mon",
"tm_mday",
"tm_hour",
"tm_min",
"tm_sec",
... |
#!/bin/python
#import numpy
import os
from sklearn.svm.classes import SVC
import cPickle
import sys
import pandas as pd
import numpy as np
# Performs K-means clustering and save the model to a local file
if __name__ == '__main__':
if len(sys.argv) != 5:
print "Usage: {0} event_name feat_dir feat_dim out... |
# MenuTitle: Round All Hint values
# -*- coding: utf-8 -*-
__doc__ = """
Rounds the hints to a whole number for all glyphs in the font.
"""
for g in Glyphs.font.glyphs:
for l in g.layers:
for h in l.hints:
h.position = round(h.position)
h.width = round(h.width)
if h.orig... |
import os
import inspect
from functools import partial
from datasets.voc_sbd import VOCSBDDataset
from datasets.seg_transforms import ConstantPad, ToTensor, Normalize
from test import main
if __name__ == '__main__':
project_dir = os.path.dirname(inspect.getabsfile(main))
exp_name = os.path.splitext(os.path.ba... |
#!/usr/bin/env python
# coding=utf-8
"""Diksiyonaryo CLI (https://github.com/njncalub/diksiyonaryo-ph).
██████╗ ██╗██╗ ██╗ ███████╗██╗ ██╗ ██╗ ██████╗
██╔══██╗██║██║ ██╔╝ ██╔════╝██║ ╚██╗ ██╔╝██╔═══██╗
██║ ██║██║█████╔╝ ██╗ ███████╗██║ ██╗ ╚████╔╝ ██║ ██║
██║ ██║██║██╔═██╗ ╚═╝ ╚════██║██║ ╚═╝ ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-07 18:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0001_initial'),
]
operations = [
migrations.CreateModel(
... |
import sys
from direct.showbase.ShowBase import ShowBase
from pandac.PandaModules import *
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
# quit when esc is pressed
self.accept('escape',sys.exit)
base.disableMouse()
# load the box model
box ... |
"""
2 Beautiful Matrix - https://codeforces.com/problemset/problem/263/A
"""
l = []
for i in range(5):
l.append(list(map(int, input().split())))
# print(l)
for i in range(len(l)):
for j in range(len(l[0])):
if l[i][j] == 1:
x, y = i+1, j+1
break
print(abs(x - 3) + abs... |
from .menu import *
from .stage import *
from .cutscene import *
from .director import Director |
import sys
import unittest
import zeit.content.article.edit.browser.testing
class DivisionBlockTest(
zeit.content.article.edit.browser.testing.EditorTestCase):
@unittest.skipIf(
sys.platform == 'darwin',
'*testing* focus does not work under OSX for reasons unknown')
def test_division_... |
""" $Id: SOAP.py,v 1.2 2000/03/13 22:32:35 kmacleod Exp $
SOAP.py implements the Simple Object Access Protocol
<http://develop.com/SOAP/>
"""
from StringIO import StringIO
from ScarabMarshal import *
from xml.sax import saxlib, saxexts
from types import *
import string
import base64
# just constants
DICT = "dict"
... |
from discord.ext import commands
from discord.ext.commands import BadArgument, CommandError
from cogs.utils.DataBase.Items import Item
from cogs.utils.DataBase.guild import Filter
from cogs.utils.errors import BadListType, BadQueryType
def convert_quantity(text: str) -> int:
allowed_symbols = "1234567890ek.+-*/"... |
from .search.search import Search
|
import praw
import random
import os
from flask import Flask, render_template, redirect, send_from_directory, url_for
from werkzeug.middleware.proxy_fix import ProxyFix
app = Flask(__name__)
app.wsgi_app= ProxyFix(app.wsgi_app)
reddit = praw.Reddit(client_id='pua14mlzkyv5_ZfQ2WmqpQ',
client_sec... |
# Copyright 2021 InterDigital R&D and Télécom Paris.
# Author: Giorgia Cantisani
# License: Apache 2.0
"""Utils for fine tuning
"""
import torch
BN_TYPES = (torch.nn.BatchNorm1d, torch.nn.BatchNorm2d, torch.nn.BatchNorm3d)
def _make_trainable(module):
"""Unfreezes a given module.
Args:
module: The m... |
from datetime import datetime
import pytest
from brewlog.models import BrewerProfile
@pytest.mark.usefixtures('app')
class TestBrewerProfileObject:
def test_create_no_names(self, user_factory):
user = user_factory(first_name=None, last_name=None, nick=None)
assert 'anonymous' in user.name.lower... |
class List(object):
def method(self):
pass
|
""" SamFirm Bot check updates module"""
from asyncio import create_subprocess_shell
from asyncio.subprocess import PIPE
from telethon import events
from samfirm_bot import TG_LOGGER, TG_BOT_ADMINS
from samfirm_bot.samfirm_bot import BOT, SAM_FIRM
from samfirm_bot.utils.checker import is_device, is_region
@BOT.on(ev... |
# -*- coding: utf-8 -*-
# Copyright (2017-2018) Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# U... |
"""
Serializers for low-level elements of the canonical record.
Specifically, this maps concepts in :mod:`.domain` to low-level elements in
:mod:`arxiv.canonical.record` and visa-versa.
"""
from io import BytesIO
from json import dumps, load
from typing import Callable, IO, Tuple
from ..domain import Version, Conten... |
import argparse
import logging
from scraper import Scraper
def parse_args():
"""Parse command line arguments"""
args_parser = argparse.ArgumentParser()
args = args_parser.parse_args()
return args
def main():
args = parse_args()
scraper = Scraper(cache_name=__name__, cache_expiry=36000)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.