code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import pygame import pygame.mixer pygame.mixer.init() WINDOW_HEIGHT = 720 WINDOW_WIDTH = 1008 WINDOW_SCREEN = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) MAP_HEIGHT = 720 MAP_WIDTH = 672 WINDOW_OFFSET = WINDOW_WIDTH - MAP_WIDTH WORLD_CEILING = -30 FPS = 60 #COLORS BLACK = (0, 0, 0) RED = (255, 0, 0) YELL...
CONSTS.py
import pygame import pygame.mixer pygame.mixer.init() WINDOW_HEIGHT = 720 WINDOW_WIDTH = 1008 WINDOW_SCREEN = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) MAP_HEIGHT = 720 MAP_WIDTH = 672 WINDOW_OFFSET = WINDOW_WIDTH - MAP_WIDTH WORLD_CEILING = -30 FPS = 60 #COLORS BLACK = (0, 0, 0) RED = (255, 0, 0) YELL...
0.229708
0.086671
import sqlite3 db = sqlite3.connect('C:/Users/lapri/PycharmProjects/Practica1.Libros/app/data/prueba.db') cursor = db.cursor() tablas = [ """ CREATE TABLE IF NOT EXISTS Libro( LSBN INTEGER PRIMARY KEY, AUTOR TEXT NOT NULL, CANTIDADP INTEGER NOT NULL, PUBLICACION INTEGER NOT NULL, NOMBRELIBRO ...
Practica1.Libros/app/__init__.py
import sqlite3 db = sqlite3.connect('C:/Users/lapri/PycharmProjects/Practica1.Libros/app/data/prueba.db') cursor = db.cursor() tablas = [ """ CREATE TABLE IF NOT EXISTS Libro( LSBN INTEGER PRIMARY KEY, AUTOR TEXT NOT NULL, CANTIDADP INTEGER NOT NULL, PUBLICACION INTEGER NOT NULL, NOMBRELIBRO ...
0.063671
0.07843
import datetime import json import time import twitter import pyperclip from datastructures.priority_queue import PriorityQueue from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.commo...
wordle_solve.py
import datetime import json import time import twitter import pyperclip from datastructures.priority_queue import PriorityQueue from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.commo...
0.317638
0.080213
__author__ = "Anvesh" __version__ = "0.1" import ctypes import io import logging import os import requests from PIL import Image, ImageFilter from screeninfo import get_monitors from config import curr_dir, client_id, url logging.basicConfig(filename="src/moody-desktop.log", forma...
main.py
__author__ = "Anvesh" __version__ = "0.1" import ctypes import io import logging import os import requests from PIL import Image, ImageFilter from screeninfo import get_monitors from config import curr_dir, client_id, url logging.basicConfig(filename="src/moody-desktop.log", forma...
0.267313
0.064742
import sys import numpy from OpenGL.GL import * from OpenGL.GLU import * from OpenGL import GLX import pyopencl as cl class raycl(object): def __init__(self, texture, tex_dim, world): self.tex_dim = tex_dim self.world = world self.clinit() self.loadProgram("raytrace.cl") ...
raycl.py
import sys import numpy from OpenGL.GL import * from OpenGL.GLU import * from OpenGL import GLX import pyopencl as cl class raycl(object): def __init__(self, texture, tex_dim, world): self.tex_dim = tex_dim self.world = world self.clinit() self.loadProgram("raytrace.cl") ...
0.281406
0.165492
import logging import os from sys import platform import numpy as np import yaml import igibson from igibson.envs.igibson_env import iGibsonEnv from igibson.objects.articulated_object import URDFObject from igibson.objects.ycb_object import YCBObject from igibson.render.mesh_renderer.mesh_renderer_cpu import MeshRend...
igibson/examples/objects/load_objects.py
import logging import os from sys import platform import numpy as np import yaml import igibson from igibson.envs.igibson_env import iGibsonEnv from igibson.objects.articulated_object import URDFObject from igibson.objects.ycb_object import YCBObject from igibson.render.mesh_renderer.mesh_renderer_cpu import MeshRend...
0.439747
0.306735
import gym import numpy as np from ray.rllib import SampleBatch from ray.rllib.agents.impala import vtrace from ray.rllib.agents.impala.vtrace_policy import _make_time_major, BEHAVIOUR_LOGITS from ray.rllib.models import ModelCatalog from ray.rllib.models.tf.tf_action_dist import MultiActionDistribution, Categorical fr...
func-approx/agents/impala_cpc_ma_comm.py
import gym import numpy as np from ray.rllib import SampleBatch from ray.rllib.agents.impala import vtrace from ray.rllib.agents.impala.vtrace_policy import _make_time_major, BEHAVIOUR_LOGITS from ray.rllib.models import ModelCatalog from ray.rllib.models.tf.tf_action_dist import MultiActionDistribution, Categorical fr...
0.883123
0.175097
import sys from com.l2jfrozen.gameserver.model.quest import State from com.l2jfrozen.gameserver.model.quest import QuestState from com.l2jfrozen.gameserver.model.quest.jython import QuestJython as JQuest qn = "247_PossessorOfAPreciousSoul_4" #NPC CARADINE = 31740 LADY_OF_LAKE = 31745 #QUEST ITEM CARADINE_LETTER_LAST...
datapack/data/scripts/quests/247_PossessorOfAPreciousSoul_4/__init__.py
import sys from com.l2jfrozen.gameserver.model.quest import State from com.l2jfrozen.gameserver.model.quest import QuestState from com.l2jfrozen.gameserver.model.quest.jython import QuestJython as JQuest qn = "247_PossessorOfAPreciousSoul_4" #NPC CARADINE = 31740 LADY_OF_LAKE = 31745 #QUEST ITEM CARADINE_LETTER_LAST...
0.201735
0.142978
import argparse from conjur.argument_parser.parser_utils import command_description, command_epilog, formatter, \ title_formatter from conjur.wrapper.argparse_wrapper import ArgparseWrapper # pylint: disable=too-few-public-methods class ListParser: """Partial class of the ArgParseBuilder. This class add th...
conjur/argument_parser/_list_parser.py
import argparse from conjur.argument_parser.parser_utils import command_description, command_epilog, formatter, \ title_formatter from conjur.wrapper.argparse_wrapper import ArgparseWrapper # pylint: disable=too-few-public-methods class ListParser: """Partial class of the ArgParseBuilder. This class add th...
0.63341
0.08886
import os import sys import reframe as rfm import reframe.utility.sanity as sn sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../common'))) # noqa: E402 import sphexa.hooks as hooks # {{{ class SphExa_STAT_Check @rfm.simple_test class SphExa_STAT_Check(rfm.RegressionTest, h...
reframechecks/debug/cray_stat.py
import os import sys import reframe as rfm import reframe.utility.sanity as sn sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../common'))) # noqa: E402 import sphexa.hooks as hooks # {{{ class SphExa_STAT_Check @rfm.simple_test class SphExa_STAT_Check(rfm.RegressionTest, h...
0.140897
0.214527
from settings import * import numpy as np import struct def _bool2int(x, dw): y = 0 for i,j in enumerate(x): y += j<<(i * dw) return y def _quantize(mat, dw, dq, is_complement=True): FIX_POINT_MAX = 2 ** (dw - 1) - 1 FIX_POINT_MIN = - 2 ** (dw - 1) FIX_POINT_SCALE = 2 ** dq UINT_M...
util/data.py
from settings import * import numpy as np import struct def _bool2int(x, dw): y = 0 for i,j in enumerate(x): y += j<<(i * dw) return y def _quantize(mat, dw, dq, is_complement=True): FIX_POINT_MAX = 2 ** (dw - 1) - 1 FIX_POINT_MIN = - 2 ** (dw - 1) FIX_POINT_SCALE = 2 ** dq UINT_M...
0.346652
0.355523
from __future__ import unicode_literals from django.db import migrations, models import django.contrib.gis.db.models.fields import common.models.base import django.utils.timezone import django.db.models.deletion from django.conf import settings import mfl_gis.models import uuid class Migration(migrations.Migration):...
admin_offices/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import migrations, models import django.contrib.gis.db.models.fields import common.models.base import django.utils.timezone import django.db.models.deletion from django.conf import settings import mfl_gis.models import uuid class Migration(migrations.Migration):...
0.549641
0.105027
""" Tools for annotating an input image """ from collections import OrderedDict import logging import cv2 import numpy as np logger = logging.getLogger(__name__) # pylint: disable=invalid-name class Annotate(): """ Annotate an input image """ def __init__(self, image, alignments, original_roi=None): ...
faceswap/tools/alignments/annotate.py
""" Tools for annotating an input image """ from collections import OrderedDict import logging import cv2 import numpy as np logger = logging.getLogger(__name__) # pylint: disable=invalid-name class Annotate(): """ Annotate an input image """ def __init__(self, image, alignments, original_roi=None): ...
0.907469
0.264056
from enum import Enum from __about__ import __date__, __summary__, __title__, __version__ class Args(Enum): BACKEND = "backend" BV = "bv" CORES = "cores" DEBUG = "debug" FAIR = "fair" CORES_FROM = "from" KEEP_FILES = "keep_files" INCLUDE = "include" PROPERTY = "property" NO_PR...
cli.py
from enum import Enum from __about__ import __date__, __summary__, __title__, __version__ class Args(Enum): BACKEND = "backend" BV = "bv" CORES = "cores" DEBUG = "debug" FAIR = "fair" CORES_FROM = "from" KEEP_FILES = "keep_files" INCLUDE = "include" PROPERTY = "property" NO_PR...
0.835249
0.136752
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class ContrastiveLoss(nn.Module): """ Contrastive loss Takes embeddings of two samples and a target label == 1 if samples are from the same class and label == 0 otherwise """ def __init__(self, margin): ...
netharn/criterions/losses.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class ContrastiveLoss(nn.Module): """ Contrastive loss Takes embeddings of two samples and a target label == 1 if samples are from the same class and label == 0 otherwise """ def __init__(self, margin): ...
0.93835
0.699043
import numpy as np def check_gaps(loc_t_arr, t_thresh, verbose=False): """ """ # If the masked array contains gaps larger than the thresh # split the mask and take the submask which corresponds to # the largest duration subarray. # If there's not enough evnets for a gap, exit if loc_t_...
src/stay_classification/gap_tools.py
import numpy as np def check_gaps(loc_t_arr, t_thresh, verbose=False): """ """ # If the masked array contains gaps larger than the thresh # split the mask and take the submask which corresponds to # the largest duration subarray. # If there's not enough evnets for a gap, exit if loc_t_...
0.368974
0.683056
import re import csv import ipaddress __version__ = 1.0 # Each route will have the following values class Route_Template(object): def __init__(self): self.route = {} self.protocol = [] self.metric = [] self.next_hop = [] self.age = [] self.interface = [] def __r...
route_parse_nxos.py
import re import csv import ipaddress __version__ = 1.0 # Each route will have the following values class Route_Template(object): def __init__(self): self.route = {} self.protocol = [] self.metric = [] self.next_hop = [] self.age = [] self.interface = [] def __r...
0.522933
0.118768
# Import python modules. from __future__ import absolute_import import json import logging import os # Import external modules. import requests log = logging.getLogger(__name__) class PluginCache(object): """Manages the list of plugins available in the update center.""" PLUGINS_URL="https://updates.jenkins-ci...
_states/jenkins_plugin.py
# Import python modules. from __future__ import absolute_import import json import logging import os # Import external modules. import requests log = logging.getLogger(__name__) class PluginCache(object): """Manages the list of plugins available in the update center.""" PLUGINS_URL="https://updates.jenkins-ci...
0.768646
0.134009
import pygame from typing import Dict import settings import scoreboard class Display: ''' Display object has fields and methods to draw objects to the screen and display different game states Args: surface (pygame.Surface): game screen logo (pygame.Surface): game logo ...
game/display.py
import pygame from typing import Dict import settings import scoreboard class Display: ''' Display object has fields and methods to draw objects to the screen and display different game states Args: surface (pygame.Surface): game screen logo (pygame.Surface): game logo ...
0.780997
0.367469
import logging import signal import subprocess import sys import os import psutil import cook import cook.io_helper as cio def launch_process(command, environment): """Launches the process using the command and specified environment. Parameters ---------- command: string The command to exe...
executor/cook/subprocess.py
import logging import signal import subprocess import sys import os import psutil import cook import cook.io_helper as cio def launch_process(command, environment): """Launches the process using the command and specified environment. Parameters ---------- command: string The command to exe...
0.547706
0.338268
import datetime import math from bson.objectid import ObjectId from mongoschema.bson_utils import get_dtype, _get_int class TestMapper(object): def test_for_null_one(self): assert get_dtype(None) == "null" def test_for_null_two(self): assert get_dtype("") != "null" def test_for_null_th...
tests/test_bson_utils.py
import datetime import math from bson.objectid import ObjectId from mongoschema.bson_utils import get_dtype, _get_int class TestMapper(object): def test_for_null_one(self): assert get_dtype(None) == "null" def test_for_null_two(self): assert get_dtype("") != "null" def test_for_null_th...
0.385259
0.506591
import sys import xapian # We require at least two command line arguments. if len(sys.argv) < 3: print >> sys.stderr, "Usage: %s PATH_TO_DATABASE QUERY [-- [DOCID...]]" % sys.argv[0] sys.exit(1) try: # Open the database for searching. database = xapian.Database(sys.argv[1]) # Start an enquire se...
docs/examples/simpleexpand.py
import sys import xapian # We require at least two command line arguments. if len(sys.argv) < 3: print >> sys.stderr, "Usage: %s PATH_TO_DATABASE QUERY [-- [DOCID...]]" % sys.argv[0] sys.exit(1) try: # Open the database for searching. database = xapian.Database(sys.argv[1]) # Start an enquire se...
0.259732
0.291926
class PrettyTable(list): """ Overridden list class which takes a 2-dimensional list of the form [[1,2,3],[4,5,6]], and renders HTML and LaTeX Table in IPython Notebook. For LaTeX export two styles can be chosen.""" def __init__(self, initlist=[], extra_header=None, print_latex_longtable=True,...
src/PrettyTable.py
class PrettyTable(list): """ Overridden list class which takes a 2-dimensional list of the form [[1,2,3],[4,5,6]], and renders HTML and LaTeX Table in IPython Notebook. For LaTeX export two styles can be chosen.""" def __init__(self, initlist=[], extra_header=None, print_latex_longtable=True,...
0.580233
0.523603
import esphome.codegen as cg import esphome.config_validation as cv from esphome import automation from esphome.components import time from esphome.const import CONF_TIME_ID, CONF_ID, CONF_TRIGGER_ID from esphome.py_compat import string_types sun_ns = cg.esphome_ns.namespace('sun') Sun = sun_ns.class_('Sun') SunTrigg...
esphome/components/sun/__init__.py
import esphome.codegen as cg import esphome.config_validation as cv from esphome import automation from esphome.components import time from esphome.const import CONF_TIME_ID, CONF_ID, CONF_TRIGGER_ID from esphome.py_compat import string_types sun_ns = cg.esphome_ns.namespace('sun') Sun = sun_ns.class_('Sun') SunTrigg...
0.46393
0.224533
from numpy import mean, zeros from copy import deepcopy class Ensemble(object): """ Class represents ensemble learning technique. In short, ensemble techniques predict output over a meta learner that it self is supplied with output of a number of base learners. Attributes: base_learner: Base l...
src/algorithms/common/ensemble.py
from numpy import mean, zeros from copy import deepcopy class Ensemble(object): """ Class represents ensemble learning technique. In short, ensemble techniques predict output over a meta learner that it self is supplied with output of a number of base learners. Attributes: base_learner: Base l...
0.943387
0.488039
from flask_restx import Api as BaseApi from collections import OrderedDict from werkzeug.datastructures import MultiDict from flask_restx.reqparse import Argument class Api(BaseApi): """Custom Flask-RESTPlus Api subclass for overriding default root route NOTE: endpoint of route '/' must be named 'root':: ...
qwc_services_core/api.py
from flask_restx import Api as BaseApi from collections import OrderedDict from werkzeug.datastructures import MultiDict from flask_restx.reqparse import Argument class Api(BaseApi): """Custom Flask-RESTPlus Api subclass for overriding default root route NOTE: endpoint of route '/' must be named 'root':: ...
0.809615
0.17172
from copy import deepcopy class TwoTeamsGame: def __init__(self, team1, team2, player_selector): """ :param team1: array of easyAI-supported objects. See Player module :param team2: array of easyAI-supported objects. :param player_selector constructor for objects of type AbstractO...
easyAI/TwoTeamsGame.py
from copy import deepcopy class TwoTeamsGame: def __init__(self, team1, team2, player_selector): """ :param team1: array of easyAI-supported objects. See Player module :param team2: array of easyAI-supported objects. :param player_selector constructor for objects of type AbstractO...
0.772445
0.459015
from world import * from maingui import * from colors import * import numpy import sys try: # i386-only optimization with Psyco # NOT TESTED: May be a memory hog and compilation may be a time hog as well! import psyco psyco.full() except ImportError: pass """ The main entry point of the simula...
main.py
from world import * from maingui import * from colors import * import numpy import sys try: # i386-only optimization with Psyco # NOT TESTED: May be a memory hog and compilation may be a time hog as well! import psyco psyco.full() except ImportError: pass """ The main entry point of the simula...
0.341253
0.492615
from pathlib import Path import re INPUTFILE = "input.txt" SAMPLE_CASES = [ ("1 + 2 * 3 + 4 * 5 + 6", 71), ("1 + (2 * 3) + (4 * (5 + 6))", 51), ("2 * 3 + (4 * 5)", 26), ("5 + (8 * 3 + 9 + 3 * 4 * 3)", 437), ("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))", 12240), ("((2 + 4 * 9) * (6 + 9 * 8 + 6) ...
day18/day18.py
from pathlib import Path import re INPUTFILE = "input.txt" SAMPLE_CASES = [ ("1 + 2 * 3 + 4 * 5 + 6", 71), ("1 + (2 * 3) + (4 * (5 + 6))", 51), ("2 * 3 + (4 * 5)", 26), ("5 + (8 * 3 + 9 + 3 * 4 * 3)", 437), ("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))", 12240), ("((2 + 4 * 9) * (6 + 9 * 8 + 6) ...
0.553505
0.379695
import sys import fileinput import operator users = 1800000 def init_dict(dict_data): global users for i in range(users): dict_data[i] = 0 def print_dict(dict_type, dict_data): print(dict_type) for key, value in sorted(dict_data.items()): print(key, value) print("\n") def pri...
scripts/pq-data-process.py
import sys import fileinput import operator users = 1800000 def init_dict(dict_data): global users for i in range(users): dict_data[i] = 0 def print_dict(dict_type, dict_data): print(dict_type) for key, value in sorted(dict_data.items()): print(key, value) print("\n") def pri...
0.064087
0.203688
import numpy as np from sklearn.base import BaseEstimator, TransformerMixin class TrfJitter(BaseEstimator, TransformerMixin): def __init__(self, snrdb, p=1, verbose=0): self.snrdb = snrdb self.snr = 10 ** (self.snrdb/10) self.p = p self.verbose = verbose def fit(self, X, y=None...
code/data_tools/pipelines/augmentation.py
import numpy as np from sklearn.base import BaseEstimator, TransformerMixin class TrfJitter(BaseEstimator, TransformerMixin): def __init__(self, snrdb, p=1, verbose=0): self.snrdb = snrdb self.snr = 10 ** (self.snrdb/10) self.p = p self.verbose = verbose def fit(self, X, y=None...
0.624752
0.28736
import enum class Instruction(enum.Enum): load = 0 send_short = 1 send_medium = 2 send_long = 3 start_timer = 4 stop_timer = 5 barrier_send = 6 recv_medium = 7 end = 8 barrier_wait = 9 send_long_fifo = 10 send_medium_fifo = 11 read_local = 12 class Instructions(obje...
tests/hls_kernel_data.py
import enum class Instruction(enum.Enum): load = 0 send_short = 1 send_medium = 2 send_long = 3 start_timer = 4 stop_timer = 5 barrier_send = 6 recv_medium = 7 end = 8 barrier_wait = 9 send_long_fifo = 10 send_medium_fifo = 11 read_local = 12 class Instructions(obje...
0.281406
0.136033
import sys import os import re import datetime def main(args): if len(args) < 3: print("Usage: {} <ifile> <odir>".format(args[0])) return -1 ifile = args[1] odir = args[2] with open(ifile) as ifh: lines = [l.rstrip().strip() for l in ifh] papers = [] current_paper ...
scripts/parse_talks.py
import sys import os import re import datetime def main(args): if len(args) < 3: print("Usage: {} <ifile> <odir>".format(args[0])) return -1 ifile = args[1] odir = args[2] with open(ifile) as ifh: lines = [l.rstrip().strip() for l in ifh] papers = [] current_paper ...
0.076965
0.123049
from pathlib import Path import base64 import datetime as dt import dateutil import json import requests from O365 import Account CONFIG_FILE = 'calendar_sync_garoon_outlook.json' WEEKS = 2 MAX_EVENT_NUM = 100 def get_period(): now = dt.datetime.now().astimezone() #print(now.tzinfo, now.isoformat()) end =...
calendar_sync_garoon_outlook.py
from pathlib import Path import base64 import datetime as dt import dateutil import json import requests from O365 import Account CONFIG_FILE = 'calendar_sync_garoon_outlook.json' WEEKS = 2 MAX_EVENT_NUM = 100 def get_period(): now = dt.datetime.now().astimezone() #print(now.tzinfo, now.isoformat()) end =...
0.210766
0.070752
import json from os import listdir from os.path import isfile, join import random # read all the tasks and make sure that they're following the right pattern tasks_path = 'tasks/' expected_keys = [ "Definition", "Positive Examples", "Negative Examples", "Instances", 'Contributors', 'Categories...
src/test_all.py
import json from os import listdir from os.path import isfile, join import random # read all the tasks and make sure that they're following the right pattern tasks_path = 'tasks/' expected_keys = [ "Definition", "Positive Examples", "Negative Examples", "Instances", 'Contributors', 'Categories...
0.376852
0.511961
import dataclasses import unittest import twitterbyconfig as tbc @dataclasses.dataclass class PythonTwitterList: id: int = None name: str = None mode: str = None @dataclasses.dataclass class PythonTwitterUser: id: int = None screen_name: str = None class TestTwitterList(unittest.TestCase): def test_T...
tests/test_twitter_list.py
import dataclasses import unittest import twitterbyconfig as tbc @dataclasses.dataclass class PythonTwitterList: id: int = None name: str = None mode: str = None @dataclasses.dataclass class PythonTwitterUser: id: int = None screen_name: str = None class TestTwitterList(unittest.TestCase): def test_T...
0.499512
0.315762
import numpy as np import Kinematic.forward as forward import Optimizer.objectives as obj from Optimizer import feasibility_check, path def get_feasible_optimum(*, q, par, q_close=None, status=None, verbose=0, return_cost=False): if status is None: status...
Optimizer/choose_optimum.py
import numpy as np import Kinematic.forward as forward import Optimizer.objectives as obj from Optimizer import feasibility_check, path def get_feasible_optimum(*, q, par, q_close=None, status=None, verbose=0, return_cost=False): if status is None: status...
0.511717
0.399519
import torch import torch.nn as nn from src.backbones.convlstm import ConvLSTM, BConvLSTM from src.backbones.ltae import LTAE2d class UTAE(nn.Module): def __init__( self, input_dim, encoder_widths=[64, 64, 64, 128], decoder_widths=[32, 32, 64, 128], out_conv=[32, 20], ...
src/backbones/utae.py
import torch import torch.nn as nn from src.backbones.convlstm import ConvLSTM, BConvLSTM from src.backbones.ltae import LTAE2d class UTAE(nn.Module): def __init__( self, input_dim, encoder_widths=[64, 64, 64, 128], decoder_widths=[32, 32, 64, 128], out_conv=[32, 20], ...
0.946498
0.449453
import os import re import click from crontab import CronTab from .helpers import validate_time from .methods import archie_reboot @click.group(name='reboot') def reboot(): """Reboot""" pass @click.command(name="now") @click.pass_context def reboot_now(ctx): """Reboot router""" archie_reboot(ctx....
archie_cli/reboot.py
import os import re import click from crontab import CronTab from .helpers import validate_time from .methods import archie_reboot @click.group(name='reboot') def reboot(): """Reboot""" pass @click.command(name="now") @click.pass_context def reboot_now(ctx): """Reboot router""" archie_reboot(ctx....
0.280222
0.070977
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import random from memory import BatchMaker from config import gamma, lambda_gae, epsilon_clip, ciritic_coefficient, entropy_coefficient, epoch_k, batch_size import warnings class PPO(nn.Module): def __init__(self, num_inputs,...
PG/7-PPO/model.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import random from memory import BatchMaker from config import gamma, lambda_gae, epsilon_clip, ciritic_coefficient, entropy_coefficient, epoch_k, batch_size import warnings class PPO(nn.Module): def __init__(self, num_inputs,...
0.944125
0.561275
import numpy as np import cv2 from PIL import Image import os def cv2_imread(file_path): cv_img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1) return cv_img def read_img_string(img_str): img_array = img_str.split('_') img_array = list(map(int, img_array)) return img_arr...
mask-prediction/get_envelope.py
import numpy as np import cv2 from PIL import Image import os def cv2_imread(file_path): cv_img = cv2.imdecode(np.fromfile(file_path, dtype=np.uint8), -1) return cv_img def read_img_string(img_str): img_array = img_str.split('_') img_array = list(map(int, img_array)) return img_arr...
0.156041
0.187746
from sqlite3 import Error as SQLiteError from vsutillib.sql import SqlDb from .. import config class SqlJobsTable(SqlDb): """ SqlJobsDB class to access sqlite database for saving jobs Args: **dbFile** (str, pathlib.Path): database file. """ def __init__(self, dbFile=None): # ini...
MKVBatchMultiplex/jobs/SqlJobsTable.py
from sqlite3 import Error as SQLiteError from vsutillib.sql import SqlDb from .. import config class SqlJobsTable(SqlDb): """ SqlJobsDB class to access sqlite database for saving jobs Args: **dbFile** (str, pathlib.Path): database file. """ def __init__(self, dbFile=None): # ini...
0.667148
0.070816
import pygame, random from settings import * vec = pygame.math.Vector2 class Enemy: def __init__(self, app, position, index): self.app = app self.grid_position = position self.pixel_position = self.get_pixel_position() self.starting_position = [position.x, position.y] self....
enemy.py
import pygame, random from settings import * vec = pygame.math.Vector2 class Enemy: def __init__(self, app, position, index): self.app = app self.grid_position = position self.pixel_position = self.get_pixel_position() self.starting_position = [position.x, position.y] self....
0.589244
0.18909
from nose.tools import assert_equal from networkx import asyn_lpa, Graph def test_empty_graph(): # empty graph test = Graph() # ground truth ground_truth = set() communities = asyn_lpa.asyn_lpa_communities(test) result = {frozenset(c) for c in communities} assert_equal(result, ground_tru...
networkx/algorithms/community/tests/test_asyn_lpa.py
from nose.tools import assert_equal from networkx import asyn_lpa, Graph def test_empty_graph(): # empty graph test = Graph() # ground truth ground_truth = set() communities = asyn_lpa.asyn_lpa_communities(test) result = {frozenset(c) for c in communities} assert_equal(result, ground_tru...
0.762159
0.629162
__all__ = ['SubpixelAlignment', 'PairwiseDistance', 'PRTF', 'PSD', 'EigenMode'] import itertools from tqdm import tqdm import numpy as np from numpy.linalg import svd from scipy.ndimage import fourier_shift from skimage.registration import phase_cross_correlation def SubpixelAlignment(input, error = None, ref = None...
PRModule/eval.py
__all__ = ['SubpixelAlignment', 'PairwiseDistance', 'PRTF', 'PSD', 'EigenMode'] import itertools from tqdm import tqdm import numpy as np from numpy.linalg import svd from scipy.ndimage import fourier_shift from skimage.registration import phase_cross_correlation def SubpixelAlignment(input, error = None, ref = None...
0.744378
0.465327
import pandas as pd import requests as rq import os from time import sleep baseURL = "https://maps.googleapis.com/maps/api/streetview?" size = "size=640x480&" location = "location=" keyfrag = "&key=" imgDir = "../streetview/PPImages/" logFile = "dlLog.log" def getDownloadedList(): files = os.listdir(imgDir) ...
scripts/crawlPlacepulse.py
import pandas as pd import requests as rq import os from time import sleep baseURL = "https://maps.googleapis.com/maps/api/streetview?" size = "size=640x480&" location = "location=" keyfrag = "&key=" imgDir = "../streetview/PPImages/" logFile = "dlLog.log" def getDownloadedList(): files = os.listdir(imgDir) ...
0.056659
0.064007
from eadapi import scrapead import os.path as path_os from json import loads, dumps DIR_NAME, _ = path_os.split(path_os.abspath(__file__)) session = None ## Code for fun from time import sleep import sys TIME_LESS = 0.05 TIME = 0.07 TIME_MORE = 0.1 WAIT_TIME = 1 def print_letra(letra): sys.stdout.write(letra)...
main.py
from eadapi import scrapead import os.path as path_os from json import loads, dumps DIR_NAME, _ = path_os.split(path_os.abspath(__file__)) session = None ## Code for fun from time import sleep import sys TIME_LESS = 0.05 TIME = 0.07 TIME_MORE = 0.1 WAIT_TIME = 1 def print_letra(letra): sys.stdout.write(letra)...
0.106319
0.147986
import datetime from google.appengine.ext import ndb START_SKIP = 60 LEARN_FACTOR = 5 MAX_MINUTES = 60 * 24 * 365 * 2 def fix_datetime(d): for k in d: if isinstance(d[k], datetime.datetime): d[k] = d[k].isoformat() return d class JsonModel(ndb.Model): def to_jdict(self): d...
sil_model.py
import datetime from google.appengine.ext import ndb START_SKIP = 60 LEARN_FACTOR = 5 MAX_MINUTES = 60 * 24 * 365 * 2 def fix_datetime(d): for k in d: if isinstance(d[k], datetime.datetime): d[k] = d[k].isoformat() return d class JsonModel(ndb.Model): def to_jdict(self): d...
0.459804
0.117547
from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Needed for projection='3d' from sklearn.manifold import TSNE from pylmnn import LargeMarginNeare...
examples/demo_plot_features.py
from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.datasets import load_iris from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Needed for projection='3d' from sklearn.manifold import TSNE from pylmnn import LargeMarginNeare...
0.953449
0.837088
import os import json import argparse import numpy as np from PIL import Image from tqdm import tqdm import torch from torchvision import models, transforms import torch.nn.functional as F from skimage.measure import compare_ssim as ssim import torch.nn as nn frame2file = {1: 'disc_dataset_first_frame.json...
eval_scripts/eval_disc_dataset.py
import os import json import argparse import numpy as np from PIL import Image from tqdm import tqdm import torch from torchvision import models, transforms import torch.nn.functional as F from skimage.measure import compare_ssim as ssim import torch.nn as nn frame2file = {1: 'disc_dataset_first_frame.json...
0.644337
0.335569
# ./libCommon.py from glob import glob from json import dumps, load, loads from os import path, environ, remove, stat, mkdir as MKDIR import logging import pandas as PD from sys import version_info from time import time, sleep from traceback import print_exc try : if version_info.major ==3 : fr...
libCommon.py
# ./libCommon.py from glob import glob from json import dumps, load, loads from os import path, environ, remove, stat, mkdir as MKDIR import logging import pandas as PD from sys import version_info from time import time, sleep from traceback import print_exc try : if version_info.major ==3 : fr...
0.141193
0.06236
import pytest from textwrap import dedent @pytest.mark.alac def test_alac_1(db_empty, cards_cli): """ Starting from an empty list. 1. Add 3 items 2. Make sure they show up in the list. 3. Change the owner on a card. Verify change. 4. Change the done state on a card. Verify change. 5. Chang...
tests/cli/test_alac.py
import pytest from textwrap import dedent @pytest.mark.alac def test_alac_1(db_empty, cards_cli): """ Starting from an empty list. 1. Add 3 items 2. Make sure they show up in the list. 3. Change the owner on a card. Verify change. 4. Change the done state on a card. Verify change. 5. Chang...
0.634204
0.523177
import xml.etree.ElementTree as ET class brocade_preprovision(object): """Auto generated class. """ def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def preprovision_rbridge_id_rbridge_id(self, **kwargs): """Auto Generated Code """ con...
pynos/versions/ver_7/ver_7_1_0/yang/brocade_preprovision.py
import xml.etree.ElementTree as ET class brocade_preprovision(object): """Auto generated class. """ def __init__(self, **kwargs): self._callback = kwargs.pop('callback') def preprovision_rbridge_id_rbridge_id(self, **kwargs): """Auto Generated Code """ con...
0.501953
0.062189
import eel import os import glob import shutil import codecs from OpenGL.GL import * from OpenGL.WGL import * from ctypes import * import numpy import pyaudio import array import re class FileSystem(): def __init__(self): self.categoryDir = './category' self.extension = '.glsl' ...
main.py
import eel import os import glob import shutil import codecs from OpenGL.GL import * from OpenGL.WGL import * from ctypes import * import numpy import pyaudio import array import re class FileSystem(): def __init__(self): self.categoryDir = './category' self.extension = '.glsl' ...
0.205296
0.073364
from matplotlib.pyplot import axis import numpy as np import cv2 from PIL import Image import torch IMAGENET_MEAN, IMAGENET_STD = np.array( [0.485, 0.456, 0.406]), np.array([0.229, 0.224, 0.225]) def crop_image(image, bbox): """Crops area from image specified as bbox. Always returns area of size as bbox fil...
mvn/utils/img.py
from matplotlib.pyplot import axis import numpy as np import cv2 from PIL import Image import torch IMAGENET_MEAN, IMAGENET_STD = np.array( [0.485, 0.456, 0.406]), np.array([0.229, 0.224, 0.225]) def crop_image(image, bbox): """Crops area from image specified as bbox. Always returns area of size as bbox fil...
0.907588
0.70246
from greww.data.mysql import (databases, tables, make_database, make_table, remove_database, remove_table, table_primary_start) from greww....
greww/data/mysql/_zilean/build.py
from greww.data.mysql import (databases, tables, make_database, make_table, remove_database, remove_table, table_primary_start) from greww....
0.275617
0.169612
import project_config import psycopg2 try: conn = psycopg2.connect(dbname=project_config.dbname, user=project_config.user, host=project_config.host, password=project_config.password) print("connected to db") except: print("I am unable to connect to the database") cur = conn.cursor() # this query...
bike_grid_calc.py
import project_config import psycopg2 try: conn = psycopg2.connect(dbname=project_config.dbname, user=project_config.user, host=project_config.host, password=project_config.password) print("connected to db") except: print("I am unable to connect to the database") cur = conn.cursor() # this query...
0.248443
0.325092
def serialize(root, A): #code here # vals = [] def doit(node): nonlocal A if node: A.append(node.data) doit(node.left) doit(node.right) else: A.append('#') # print(vals) doit(root) return A #Function to des...
Amazon/Serialize and Deserialize.py
def serialize(root, A): #code here # vals = [] def doit(node): nonlocal A if node: A.append(node.data) doit(node.left) doit(node.right) else: A.append('#') # print(vals) doit(root) return A #Function to des...
0.280222
0.304752
import matplotlib.pyplot as plt import numpy as np from distributions import Binomial_distribution, Discrete_uniform_distribution def plotDistributeBar(ax, data, label='', width=0.3, offset=0, title='Probability Distribution of true'): ax.bar(np.arange(len(data))+offset,data,width=width,label=label) fontSize ...
src/KL_divergence.py
import matplotlib.pyplot as plt import numpy as np from distributions import Binomial_distribution, Discrete_uniform_distribution def plotDistributeBar(ax, data, label='', width=0.3, offset=0, title='Probability Distribution of true'): ax.bar(np.arange(len(data))+offset,data,width=width,label=label) fontSize ...
0.539469
0.612281
import pytest from os_tornado.settings import Settings @pytest.fixture(scope="function") def settings(): return Settings() def test_get_tornado_app_settings(settings): from os_tornado.settings import TORNADO_APP_SETTINGS_PREFIX from os_tornado.settings import get_tornado_app_settings key = TORNADO_A...
tests/test_settings.py
import pytest from os_tornado.settings import Settings @pytest.fixture(scope="function") def settings(): return Settings() def test_get_tornado_app_settings(settings): from os_tornado.settings import TORNADO_APP_SETTINGS_PREFIX from os_tornado.settings import get_tornado_app_settings key = TORNADO_A...
0.382026
0.458531
from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship import urllib.error from app.api.bootstrap import api from app.api.helpers.db import safe_query from app.api.helpers.exceptions import UnprocessableEntity from app.api.schema.event_topics import EventTopicSchema from app.models import db...
app/api/event_topics.py
from flask_rest_jsonapi import ResourceDetail, ResourceList, ResourceRelationship import urllib.error from app.api.bootstrap import api from app.api.helpers.db import safe_query from app.api.helpers.exceptions import UnprocessableEntity from app.api.schema.event_topics import EventTopicSchema from app.models import db...
0.505127
0.064095
import flask_login from sqlalchemy import ( Boolean, Column, DateTime, ForeignKey, Integer, String, Text ) from sqlalchemy.orm import declarative_base, relationship from sqlalchemy.schema import Table Base = declarative_base() class User(flask_login.UserMixin): """User model.""" pass class Conference(...
mngt/models.py
import flask_login from sqlalchemy import ( Boolean, Column, DateTime, ForeignKey, Integer, String, Text ) from sqlalchemy.orm import declarative_base, relationship from sqlalchemy.schema import Table Base = declarative_base() class User(flask_login.UserMixin): """User model.""" pass class Conference(...
0.845017
0.245458
from __future__ import unicode_literals from django.contrib import messages from django.http import HttpResponseRedirect from django.shortcuts import render from webscanners.models import burp_scan_result_db, \ acunetix_scan_db, acunetix_scan_result_db from jiraticketing.models import jirasetting import hashlib ...
webscanners/acunetixscanner/views.py
from __future__ import unicode_literals from django.contrib import messages from django.http import HttpResponseRedirect from django.shortcuts import render from webscanners.models import burp_scan_result_db, \ acunetix_scan_db, acunetix_scan_result_db from jiraticketing.models import jirasetting import hashlib ...
0.413832
0.04365
import numpy as np import cv2 class colorcheck(): def __init__(self): #self.r = 0 #self.g = 0 #self.b = 0 #self.shape = (0, 0, 0) self.size = 10 def checkcamera(self): try: cap = cv2.VideoCapture(1) except: cap = cv2.Vid...
camera.py
import numpy as np import cv2 class colorcheck(): def __init__(self): #self.r = 0 #self.g = 0 #self.b = 0 #self.shape = (0, 0, 0) self.size = 10 def checkcamera(self): try: cap = cv2.VideoCapture(1) except: cap = cv2.Vid...
0.072608
0.184878
import os import sys import pickle import argparse import numpy as np sys.path.append(os.getcwd()) from solnml.bandits.second_layer_bandit import SecondLayerBandit from solnml.components.utils.constants import MULTICLASS_CLS, BINARY_CLS, REGRESSION, CLS_TASKS from solnml.datasets.utils import load_train_test_data from...
scripts/create_algorithm_meta_info.py
import os import sys import pickle import argparse import numpy as np sys.path.append(os.getcwd()) from solnml.bandits.second_layer_bandit import SecondLayerBandit from solnml.components.utils.constants import MULTICLASS_CLS, BINARY_CLS, REGRESSION, CLS_TASKS from solnml.datasets.utils import load_train_test_data from...
0.310904
0.103477
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import * from django.db import transaction from django.contrib.auth.models import Use...
test_project/personnel/tests/django_auth_user_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() from builtins import * from django.db import transaction from django.contrib.auth.models import Use...
0.640523
0.116312
import logging from .config import config_manager # deprecated CONFIG_MANAGER = config_manager def block_processor(*args, **kwargs): # pragma: no cover import vpype_cli logging.warning( "!!! `@vpype.block_processor` is deprecated, " "use `@vpype_cli.block_processor` instead." ) ret...
vpype/_deprecated.py
import logging from .config import config_manager # deprecated CONFIG_MANAGER = config_manager def block_processor(*args, **kwargs): # pragma: no cover import vpype_cli logging.warning( "!!! `@vpype.block_processor` is deprecated, " "use `@vpype_cli.block_processor` instead." ) ret...
0.500977
0.109944
import pandas as pd import seaborn as sns df = pd.read_csv('data/src/iris.csv', index_col=0) # df = sns.load_dataset("iris") print(df.head()) # sepal_length sepal_width petal_length petal_width species # 0 5.1 3.5 1.4 0.2 setosa # 1 4.9 3.0 1....
notebook/seaborn_pairplot.py
import pandas as pd import seaborn as sns df = pd.read_csv('data/src/iris.csv', index_col=0) # df = sns.load_dataset("iris") print(df.head()) # sepal_length sepal_width petal_length petal_width species # 0 5.1 3.5 1.4 0.2 setosa # 1 4.9 3.0 1....
0.351756
0.192369
from django import forms from django.db import models from django.db.models import CASCADE from users.models import ProgramType, DisciplineType, HostelType import enum # model for leave from django.urls import reverse class PlaceType(enum.Enum): NAT = 'Native' OTH = 'Other' class LeaveStatus...
app/models.py
from django import forms from django.db import models from django.db.models import CASCADE from users.models import ProgramType, DisciplineType, HostelType import enum # model for leave from django.urls import reverse class PlaceType(enum.Enum): NAT = 'Native' OTH = 'Other' class LeaveStatus...
0.203945
0.08733
r"""A module for finding the differences between two HDF5 log files. Compares two log files (referred to as A and B) for differences. Provides functions for generating a human-readable summary. Log files are represented as a dict whose values are either numpy.ndarray objects or dict objects that are similarly struct...
analysis/util/h5comp.py
r"""A module for finding the differences between two HDF5 log files. Compares two log files (referred to as A and B) for differences. Provides functions for generating a human-readable summary. Log files are represented as a dict whose values are either numpy.ndarray objects or dict objects that are similarly struct...
0.639061
0.520253
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import copy import math import torch from torch import nn import torch.nn.functional as F from torch.autograd import Function from model.decode import generic_decode from utils.image import...
src/lib/model/networks/base_model.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import copy import math import torch from torch import nn import torch.nn.functional as F from torch.autograd import Function from model.decode import generic_decode from utils.image import...
0.904421
0.281856
import numpy as np def solve_power(self, LUT, Rs): """Solve EEC to achieve given input / output power with respect to voltage and current constraints Parameters ---------- self : ElecLUTdq a ElecLUTdq object LUT : LUTdq Calculated look-up table Rs: float Stator phase r...
pyleecan/Methods/Simulation/ElecLUTdq/solve_power.py
import numpy as np def solve_power(self, LUT, Rs): """Solve EEC to achieve given input / output power with respect to voltage and current constraints Parameters ---------- self : ElecLUTdq a ElecLUTdq object LUT : LUTdq Calculated look-up table Rs: float Stator phase r...
0.866387
0.488588
from collections import OrderedDict from enum import Enum from .base import Message from ..bot import Bot class AtableMessage(Message): def __init__(self, msgtype: str, atMobiles: list = None, isAtAll: bool = None): super(AtableMessage, self).__init__(msgtype) if atMobiles or isAtAll: ...
dtb/message/message.py
from collections import OrderedDict from enum import Enum from .base import Message from ..bot import Bot class AtableMessage(Message): def __init__(self, msgtype: str, atMobiles: list = None, isAtAll: bool = None): super(AtableMessage, self).__init__(msgtype) if atMobiles or isAtAll: ...
0.541651
0.453806
from django.views.generic import View, FormView, TemplateView, UpdateView, CreateView, ListView from django.contrib.messages.views import SuccessMessageMixin from django.contrib.auth.mixins import PermissionRequiredMixin from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, ...
user/views.py
from django.views.generic import View, FormView, TemplateView, UpdateView, CreateView, ListView from django.contrib.messages.views import SuccessMessageMixin from django.contrib.auth.mixins import PermissionRequiredMixin from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login, ...
0.393968
0.077797
import copy import pytest from p2p.exceptions import ( HandshakeFailure, HandshakeFailureTooManyPeers, MalformedMessage, NoMatchingPeerCapabilities, ) from p2p.peer_pool import COMMON_PEER_CONNECTION_EXCEPTIONS from p2p.tracking.connection import ( get_timeout_for_failure, register_error, ) ...
tests/p2p/test_connection_tracker_timeout_for_failure.py
import copy import pytest from p2p.exceptions import ( HandshakeFailure, HandshakeFailureTooManyPeers, MalformedMessage, NoMatchingPeerCapabilities, ) from p2p.peer_pool import COMMON_PEER_CONNECTION_EXCEPTIONS from p2p.tracking.connection import ( get_timeout_for_failure, register_error, ) ...
0.505127
0.250959
import oecs.priority_queue class EntityManager(object): def __init__(self): #This allows access to specific entities #sEntityType:(sEntityName:entity) self._dEntities = {} #This orders the entities so that the ones with the highest draw # priority will be first in the lis...
oecs/entity_manager.py
import oecs.priority_queue class EntityManager(object): def __init__(self): #This allows access to specific entities #sEntityType:(sEntityName:entity) self._dEntities = {} #This orders the entities so that the ones with the highest draw # priority will be first in the lis...
0.5144
0.327265
import numpy as np import tensorflow as tf import hetu as ht def test_embedding(executor_ctx=ht.gpu(0)): embedding = ht.Variable('embeddingtable', value=np.random.rand(5, 5)) index = ht.Variable(name="index") ids = [[0, 1], [0, 1]] ids = np.array(ids) ids = ht.array(ids, ctx=executor_ctx) y = ...
tests/test_embedding_op.py
import numpy as np import tensorflow as tf import hetu as ht def test_embedding(executor_ctx=ht.gpu(0)): embedding = ht.Variable('embeddingtable', value=np.random.rand(5, 5)) index = ht.Variable(name="index") ids = [[0, 1], [0, 1]] ids = np.array(ids) ids = ht.array(ids, ctx=executor_ctx) y = ...
0.486088
0.532425
import warnings import csv import collections from functools import reduce import itertools import pandas as pd import numpy as np import yfinance as yf import matplotlib.pyplot as plt import sklearn import pmdarima as pm import arch from arch.__future__ import reindexing from sklearn.decomposition import PCA from skl...
front_end/static/backtest.py
import warnings import csv import collections from functools import reduce import itertools import pandas as pd import numpy as np import yfinance as yf import matplotlib.pyplot as plt import sklearn import pmdarima as pm import arch from arch.__future__ import reindexing from sklearn.decomposition import PCA from skl...
0.451689
0.315578
from __future__ import unicode_literals import sys from curtsies.fmtfuncs import bold, green, magenta, cyan, red, plain from bpython.curtsiesfrontend import interpreter from bpython._py3compat import py3 from bpython.test import mock, unittest pypy = 'PyPy' in sys.version class TestInterpreter(unittest.TestCase)...
env/lib/python2.7/site-packages/bpython/test/test_interpreter.py
from __future__ import unicode_literals import sys from curtsies.fmtfuncs import bold, green, magenta, cyan, red, plain from bpython.curtsiesfrontend import interpreter from bpython._py3compat import py3 from bpython.test import mock, unittest pypy = 'PyPy' in sys.version class TestInterpreter(unittest.TestCase)...
0.548674
0.286038
import os import pdb import torch import torch.nn as nn import torchvision.models as models from . import util # https://pytorch.org/docs/stable/torchvision/models.html # models.resnet50((pretrained=True, progress=True)), resnet18, inception_v3 #-----------------------------------------------------------------...
src/models.py
import os import pdb import torch import torch.nn as nn import torchvision.models as models from . import util # https://pytorch.org/docs/stable/torchvision/models.html # models.resnet50((pretrained=True, progress=True)), resnet18, inception_v3 #-----------------------------------------------------------------...
0.750004
0.287104
from __future__ import absolute_import import sys import weakref # weak reference to installed hooks _IMPORT_HOOKS = weakref.WeakValueDictionary() # must have _IMPORT_HOOKS to bootstrap hook disabling from .inhibit import DISABLED_TYPES def path(file_path): """ Include module code from a file identified by i...
include/__init__.py
from __future__ import absolute_import import sys import weakref # weak reference to installed hooks _IMPORT_HOOKS = weakref.WeakValueDictionary() # must have _IMPORT_HOOKS to bootstrap hook disabling from .inhibit import DISABLED_TYPES def path(file_path): """ Include module code from a file identified by i...
0.665411
0.214547
import textwrap from json.decoder import JSONDecodeError from typing import Dict, Iterator from yaml import YAMLError from .jsonutil import loadjson_all, dumpjson from .nodes import Constant, Empty, Node from .parser import Parser, Environment from .util import treat from .value import Value from .yamlutil import dum...
jinsi/api.py
import textwrap from json.decoder import JSONDecodeError from typing import Dict, Iterator from yaml import YAMLError from .jsonutil import loadjson_all, dumpjson from .nodes import Constant, Empty, Node from .parser import Parser, Environment from .util import treat from .value import Value from .yamlutil import dum...
0.675122
0.306345
import logging import os from django.apps import AppConfig from django.conf import settings VERSION = (0, 8, 2) __version__ = '.'.join((str(i) for i in VERSION)) default_app_config = __name__ + '.App' logger = logging.getLogger(__name__) class App(AppConfig): name = 'theming' class Defaults: THEMI...
theming/__init__.py
import logging import os from django.apps import AppConfig from django.conf import settings VERSION = (0, 8, 2) __version__ = '.'.join((str(i) for i in VERSION)) default_app_config = __name__ + '.App' logger = logging.getLogger(__name__) class App(AppConfig): name = 'theming' class Defaults: THEMI...
0.179531
0.041211
import re import enum import requests from abc import * from urllib.parse import urlparse, parse_qs from bs4 import BeautifulSoup from requests import HTTPError class MediaSourceType(enum.Enum): NONE = 0 ARTICLE = 1 YOUTUBE = 2 class CardViewInfo: def __init__(self, ms_type=MediaSourceType.NONE, ur...
preview_card/cardview.py
import re import enum import requests from abc import * from urllib.parse import urlparse, parse_qs from bs4 import BeautifulSoup from requests import HTTPError class MediaSourceType(enum.Enum): NONE = 0 ARTICLE = 1 YOUTUBE = 2 class CardViewInfo: def __init__(self, ms_type=MediaSourceType.NONE, ur...
0.560974
0.102484
from mozurestsdk.mozuclient import default as default_client from mozurestsdk.mozuurl import MozuUrl; from mozurestsdk.urllocation import UrlLocation class PublicCard(object): def __init__(self, mozuClient = None): self.client = mozuClient or default_client(); def create(self,request, responseFields = None)...
mozurestsdk/commerce/payments/publiccard.py
from mozurestsdk.mozuclient import default as default_client from mozurestsdk.mozuurl import MozuUrl; from mozurestsdk.urllocation import UrlLocation class PublicCard(object): def __init__(self, mozuClient = None): self.client = mozuClient or default_client(); def create(self,request, responseFields = None)...
0.512693
0.104843
from tango import AttrWriteType, DevState, DispLevel from tango.server import Device, attribute, command, device_property from time import sleep import serial class AgilisAGP(Device): """AgilisAGP This controls an Agilis Conex AGP actuator """ Port = device_property(dtype='str', default_value='/...
AgilisAGP.py
from tango import AttrWriteType, DevState, DispLevel from tango.server import Device, attribute, command, device_property from time import sleep import serial class AgilisAGP(Device): """AgilisAGP This controls an Agilis Conex AGP actuator """ Port = device_property(dtype='str', default_value='/...
0.419053
0.093017
from math import ceil from re import findall from selenium.webdriver.common.keys import Keys from .time_util import sleep def get_links_for_tag(browser, tag, amount): """Fetches the number of links specified by amount and returns a list of links""" browser.get('https://www.instagram.com/explore/tags/' ...
instapy/like_util.py
from math import ceil from re import findall from selenium.webdriver.common.keys import Keys from .time_util import sleep def get_links_for_tag(browser, tag, amount): """Fetches the number of links specified by amount and returns a list of links""" browser.get('https://www.instagram.com/explore/tags/' ...
0.509032
0.085939
from os import system, path from kafka_cli.create_service import CreateService import yaml from time import sleep class RunKafka: def __init__(self, parser): self._parser = parser self._setting = None self._args = None def __call__(self, args): self._args = args # make...
src/kafka_bus/kafka_cli/run_kafka.py
from os import system, path from kafka_cli.create_service import CreateService import yaml from time import sleep class RunKafka: def __init__(self, parser): self._parser = parser self._setting = None self._args = None def __call__(self, args): self._args = args # make...
0.16492
0.095518
from tensorflow import make_tensor_proto from tensorflow_serving.apis import prediction_log_pb2 from tensorflow_serving.apis import predict_pb2 from datetime import datetime import subprocess import os import tensorflow as tf import pickle from tensorflow.keras.regularizers import L2 import faiss import tensorflow as t...
mind/v1/main.py
from tensorflow import make_tensor_proto from tensorflow_serving.apis import prediction_log_pb2 from tensorflow_serving.apis import predict_pb2 from datetime import datetime import subprocess import os import tensorflow as tf import pickle from tensorflow.keras.regularizers import L2 import faiss import tensorflow as t...
0.611962
0.130784
from datetime import datetime from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class UserProfile(AbstractUser): """ 用户 """ GRADE_TYPE = ( (1, "大学一年级"), (2, "大学二年级"), (3, "大学三年级"), (4, "大学四年级"), ) name =...
apps/user/models.py
from datetime import datetime from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class UserProfile(AbstractUser): """ 用户 """ GRADE_TYPE = ( (1, "大学一年级"), (2, "大学二年级"), (3, "大学三年级"), (4, "大学四年级"), ) name =...
0.466359
0.158728
import json from behave import when import pubnub from pubnub.exceptions import PubNubException def execute_pam_call(context): context.grant_result = context.peer.grant_token().channels( list(context.resources_to_grant["CHANNEL"].values()) ).groups( list(context.resources_to_grant["CHANNEL_GR...
tests/acceptance/pam/steps/when_steps.py
import json from behave import when import pubnub from pubnub.exceptions import PubNubException def execute_pam_call(context): context.grant_result = context.peer.grant_token().channels( list(context.resources_to_grant["CHANNEL"].values()) ).groups( list(context.resources_to_grant["CHANNEL_GR...
0.347869
0.157137
from lxml import etree from span_data import Cspan class Ccoreference: """ This class encapsulates a coreference object in KAF/NAF """ def __init__(self,node=None,type='NAF'): """ Constructor of the object @type node: xml Element or None (to create and empty one) @param ...
KafNafParserPy/coreference_data.py
from lxml import etree from span_data import Cspan class Ccoreference: """ This class encapsulates a coreference object in KAF/NAF """ def __init__(self,node=None,type='NAF'): """ Constructor of the object @type node: xml Element or None (to create and empty one) @param ...
0.753557
0.365174
from functools import singledispatch from typing import (Any, Callable, Iterable, Sequence, Tuple, TypeVar, Union) from bentley_ottmann.planar import segments_cross_or_overlap from ground.base import...
tests/utils.py
from functools import singledispatch from typing import (Any, Callable, Iterable, Sequence, Tuple, TypeVar, Union) from bentley_ottmann.planar import segments_cross_or_overlap from ground.base import...
0.83752
0.374733
import numpy as np from scipy.special import logsumexp, gammaln from astropy import constants, units as au from astropy.units import Quantity Gauss = 1e-4 * au.T au.set_enabled_equivalencies(au.dimensionless_angles()) def pad_with_absorbing_boundary_conditions(k2, k02, N, *coords, dn_max=0.05): if dn_max is None...
born_rime/potentials.py
import numpy as np from scipy.special import logsumexp, gammaln from astropy import constants, units as au from astropy.units import Quantity Gauss = 1e-4 * au.T au.set_enabled_equivalencies(au.dimensionless_angles()) def pad_with_absorbing_boundary_conditions(k2, k02, N, *coords, dn_max=0.05): if dn_max is None...
0.791861
0.424352
import numpy as np import pandas as pd from matplotlib import dates from scipy.interpolate import interp1d class System: ''' Class of whole system ''' def __init__(self, farms, c_matrix,delta_time,temperature_input =None,inital_start=0): ''' :params: farms Ein list...
Simulator_engine/System_3_FO.py
import numpy as np import pandas as pd from matplotlib import dates from scipy.interpolate import interp1d class System: ''' Class of whole system ''' def __init__(self, farms, c_matrix,delta_time,temperature_input =None,inital_start=0): ''' :params: farms Ein list...
0.075952
0.382401
from rest_app.domain import Book, BookUpdate, BookNotFoundException from typing import List, Optional from datetime import date import re class MemoryBookStorage: """Base storage for books that save data in memory.""" def __init__(self): self.id_counter = 0 self.books = [] @staticmetho...
src/rest_app/storage/memory.py
from rest_app.domain import Book, BookUpdate, BookNotFoundException from typing import List, Optional from datetime import date import re class MemoryBookStorage: """Base storage for books that save data in memory.""" def __init__(self): self.id_counter = 0 self.books = [] @staticmetho...
0.844216
0.258882
import io import gzip import argparse import os from str_utils import * import pickle from time import time, strftime class FreebaseDumpFilter: def __init__(self, fbids_filename, map_fbid_nodeindex_filename): self.now = strftime("%Y_%m_%d_%H_%M") self.fbid_nodeindex_map = self.load_nodes(fbids_fil...
src/fb_dump_filter.py
import io import gzip import argparse import os from str_utils import * import pickle from time import time, strftime class FreebaseDumpFilter: def __init__(self, fbids_filename, map_fbid_nodeindex_filename): self.now = strftime("%Y_%m_%d_%H_%M") self.fbid_nodeindex_map = self.load_nodes(fbids_fil...
0.306942
0.12921
def tests_compiler(): """Test Compiler""" import platform import subprocess from compilertools.compilers._core import _get_arch_and_cpu from compilertools.compilers.llvm import Compiler cmd = { "python": "", "--version": "", "-dumpversion": "", "not_found": False...
tests/test_compilers_llvm.py
def tests_compiler(): """Test Compiler""" import platform import subprocess from compilertools.compilers._core import _get_arch_and_cpu from compilertools.compilers.llvm import Compiler cmd = { "python": "", "--version": "", "-dumpversion": "", "not_found": False...
0.430866
0.270556
import unittest from cozy.target_syntax import * from cozy.syntax_tools import mk_lambda, pprint, fresh_var, free_vars, alpha_equivalent from cozy.typecheck import retypecheck from cozy.solver import satisfy, valid from cozy.evaluation import eval, construct_value from cozy.synthesis.acceleration import optimized_in ...
tests/semantics.py
import unittest from cozy.target_syntax import * from cozy.syntax_tools import mk_lambda, pprint, fresh_var, free_vars, alpha_equivalent from cozy.typecheck import retypecheck from cozy.solver import satisfy, valid from cozy.evaluation import eval, construct_value from cozy.synthesis.acceleration import optimized_in ...
0.456168
0.510985
import os import base64 import pygame as pg pg.init() class Cycle(object): ''' Sets the values for the time and season functionality ''' def __init__(self): ''' 6 seconds = 1 day 60 seconds = 10 days 1 maintenance cycle = 3 seconds = 1 day 1 earn cycle = 1/2 mi...
modules/backend.py
import os import base64 import pygame as pg pg.init() class Cycle(object): ''' Sets the values for the time and season functionality ''' def __init__(self): ''' 6 seconds = 1 day 60 seconds = 10 days 1 maintenance cycle = 3 seconds = 1 day 1 earn cycle = 1/2 mi...
0.386995
0.229967