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
This material was prepared as an account of work sponsored by an agency of the United States Government. Neither the United States Government nor the United States Department of Energy, nor Battelle, nor any of their employees, nor any jurisdiction or organization that has cooperated in the development of these mat...
volttrontesting/zmq/test_zmq.py
This material was prepared as an account of work sponsored by an agency of the United States Government. Neither the United States Government nor the United States Department of Energy, nor Battelle, nor any of their employees, nor any jurisdiction or organization that has cooperated in the development of these mat...
0.293303
0.179638
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Frequency' db.create_table('qa_frequency', ( ('id', self.gf('django.db.models.fields.AutoField')(primary...
qatrack/qa/migrations/0001_initial.py
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Frequency' db.create_table('qa_frequency', ( ('id', self.gf('django.db.models.fields.AutoField')(primary...
0.619932
0.096195
# node class for BST class Node(object): # initializes node def __init__(self, key, data = None): self.key = key if data is None: self.data = key else: self.data = data self.left_child = None self.right_child = None # iterator generator for ...
binary_search_tree.py
# node class for BST class Node(object): # initializes node def __init__(self, key, data = None): self.key = key if data is None: self.data = key else: self.data = data self.left_child = None self.right_child = None # iterator generator for ...
0.798383
0.335106
import re import os import logging import traceback from functools import wraps from django.db import connection, models from django.conf import settings logger = logging.getLogger(__name__) def debug_pg_notices(f): @wraps(f) def wrapped(*args, **kwargs): before = len(connection.connection.notices...
geotrek/common/utils/postgresql.py
import re import os import logging import traceback from functools import wraps from django.db import connection, models from django.conf import settings logger = logging.getLogger(__name__) def debug_pg_notices(f): @wraps(f) def wrapped(*args, **kwargs): before = len(connection.connection.notices...
0.212968
0.075858
import numpy as np import numpy.linalg as LA from sklearn.neighbors import KDTree import torch from torch import nn import config # https://stackoverflow.com/questions/47060685/chamfer-distance-between-two-point-clouds-in-tensorflow def array2samples_distance(array1, array2): """ arguments: array1: th...
chamfer_loss.py
import numpy as np import numpy.linalg as LA from sklearn.neighbors import KDTree import torch from torch import nn import config # https://stackoverflow.com/questions/47060685/chamfer-distance-between-two-point-clouds-in-tensorflow def array2samples_distance(array1, array2): """ arguments: array1: th...
0.808974
0.715747
import torch import logging from typing import Union from torch import nn from towhee.models.clip4clip.until_module import PreTrainedModel, CrossEn from towhee.models.clip import CLIP, get_configs logger = logging.getLogger(__name__) class CLIP4ClipPreTrainedModel(PreTrainedModel, nn.Module): """ An abstract cl...
towhee/models/clip4clip/clip4clip.py
import torch import logging from typing import Union from torch import nn from towhee.models.clip4clip.until_module import PreTrainedModel, CrossEn from towhee.models.clip import CLIP, get_configs logger = logging.getLogger(__name__) class CLIP4ClipPreTrainedModel(PreTrainedModel, nn.Module): """ An abstract cl...
0.909033
0.408749
import os import sys import ceph_pool from mock.mock import patch sys.path.append('./library') fake_user = 'client.admin' fake_user_key = '/etc/ceph/ceph.client.admin.keyring' fake_pool_name = 'foo' fake_cluster_name = 'ceph' fake_container_image_name = 'quay.ceph.io/ceph-ci/daemon:latest-luminous' @patch.dict(os.en...
tests/library/test_ceph_pool.py
import os import sys import ceph_pool from mock.mock import patch sys.path.append('./library') fake_user = 'client.admin' fake_user_key = '/etc/ceph/ceph.client.admin.keyring' fake_pool_name = 'foo' fake_cluster_name = 'ceph' fake_container_image_name = 'quay.ceph.io/ceph-ci/daemon:latest-luminous' @patch.dict(os.en...
0.255251
0.10316
from scipy.spatial import distance_matrix import numpy as np import cv2 def px_dist_matches(kpts1, kpts2, geo_info, thresh): """ Inputs: kpts1: np.array (Nx2) of keypoint coordinates from image 1 kpts2: np.array (Mx2) of keypoint coordinates from image 2 Returns: """ ...
python/bench/pixel_distance.py
from scipy.spatial import distance_matrix import numpy as np import cv2 def px_dist_matches(kpts1, kpts2, geo_info, thresh): """ Inputs: kpts1: np.array (Nx2) of keypoint coordinates from image 1 kpts2: np.array (Mx2) of keypoint coordinates from image 2 Returns: """ ...
0.672547
0.742375
# -------------------------------------------------------------------------- # because it is also executed from setup.py, make sure # that it imports only modules, that for sure will exist at setup.py execution # TRY TO KEEP IMPORTS TO MINIMUM # -------------------------------------------------------------------------...
azure/Kqlmagic/_require.py
# -------------------------------------------------------------------------- # because it is also executed from setup.py, make sure # that it imports only modules, that for sure will exist at setup.py execution # TRY TO KEEP IMPORTS TO MINIMUM # -------------------------------------------------------------------------...
0.329607
0.212763
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import qdarkstyle from PyQt5.QtSql import * import time class dropBookDialog(QDialog): drop_book_successful_signal=pyqtSignal() def __init__(self, parent=None): super(dropBookDialog, self).__init__(parent) ...
dropBookDialog.py
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import qdarkstyle from PyQt5.QtSql import * import time class dropBookDialog(QDialog): drop_book_successful_signal=pyqtSignal() def __init__(self, parent=None): super(dropBookDialog, self).__init__(parent) ...
0.153327
0.100746
from __future__ import print_function from bcc import BPF from time import sleep, strftime from struct import pack from socket import inet_ntop, AF_INET, AF_INET6 from struct import pack import argparse examples = """examples: ./tcpcong # show tcp congestion status duration ./tcpcong 1 10 ...
tools/tcpcong.py
from __future__ import print_function from bcc import BPF from time import sleep, strftime from struct import pack from socket import inet_ntop, AF_INET, AF_INET6 from struct import pack import argparse examples = """examples: ./tcpcong # show tcp congestion status duration ./tcpcong 1 10 ...
0.400515
0.123313
import logging import os import sys import tempfile import unittest # TODO: No idea why pytype cannot find names from this module. # pytype: disable=name-error import iree.compiler.tools.tflite if not iree.compiler.tools.tflite.is_available(): print(f"Skipping test {__file__} because the IREE TFLite compiler " ...
llvm-external-projects/iree-compiler-api/unittests/tools/compiler_tflite_test.py
import logging import os import sys import tempfile import unittest # TODO: No idea why pytype cannot find names from this module. # pytype: disable=name-error import iree.compiler.tools.tflite if not iree.compiler.tools.tflite.is_available(): print(f"Skipping test {__file__} because the IREE TFLite compiler " ...
0.157622
0.339007
# encoding: utf-8 ''' @author: <NAME> @license: (C) Copyright @ <NAME> @contact: <EMAIL> @file: 227.py @time: 2019/6/8 17:11 @desc: ''' import collections class Solution: def calculate(self, s: str) -> int: stack = collections.deque() i = 0 while i < len(s): if s[i] == '...
227.py
# encoding: utf-8 ''' @author: <NAME> @license: (C) Copyright @ <NAME> @contact: <EMAIL> @file: 227.py @time: 2019/6/8 17:11 @desc: ''' import collections class Solution: def calculate(self, s: str) -> int: stack = collections.deque() i = 0 while i < len(s): if s[i] == '...
0.204342
0.226153
import os import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset from torch import optim from torch.utils.tensorboard import SummaryWriter import copy from .oadam import OAdam from .rbflayer import RBF from .utilities import dprint # TODO. This epsilon is used onl...
mliv/neuralnet/agmm_earlystop.py
import os import numpy as np import torch import torch.nn as nn from torch.utils.data import DataLoader, TensorDataset from torch import optim from torch.utils.tensorboard import SummaryWriter import copy from .oadam import OAdam from .rbflayer import RBF from .utilities import dprint # TODO. This epsilon is used onl...
0.59972
0.401834
import os import numpy as np from matplotlib.image import imread from falco.mask import falco_gen_pupil_Roman_CGI_20200513 from falco.util import pad_crop, bin_downsample def test_translation(): Nbeam = 100 centering = 'pixel' pupil = falco_gen_pupil_Roman_CGI_20200513(Nbeam, centering) changes = {"...
tests/unit/test_mask_pupil_Roman.py
import os import numpy as np from matplotlib.image import imread from falco.mask import falco_gen_pupil_Roman_CGI_20200513 from falco.util import pad_crop, bin_downsample def test_translation(): Nbeam = 100 centering = 'pixel' pupil = falco_gen_pupil_Roman_CGI_20200513(Nbeam, centering) changes = {"...
0.502197
0.439928
import json import time import boto3 import os textract = boto3.client('textract') s3 = boto3.client('s3') def handler(event, context): message = json.loads(event['Records'][0]['Sns']['Message']) jobId = message['JobId'] print("JobId="+jobId) output_bucket = os.environ["OUT_PUT_S3_BUCKET"] status...
src/lambda/extract_text_from_textract_async_job_output.py
import json import time import boto3 import os textract = boto3.client('textract') s3 = boto3.client('s3') def handler(event, context): message = json.loads(event['Records'][0]['Sns']['Message']) jobId = message['JobId'] print("JobId="+jobId) output_bucket = os.environ["OUT_PUT_S3_BUCKET"] status...
0.134037
0.07627
import collections import dataclasses import functools import inspect import re import types from typing import Any import numpy as np import torch import torchdynamo from .. import mutation_guard from .. import skipfiles from ..allowed_functions import is_allowed from ..allowed_functions import is_builtin from ..al...
torchdynamo/variables/builder.py
import collections import dataclasses import functools import inspect import re import types from typing import Any import numpy as np import torch import torchdynamo from .. import mutation_guard from .. import skipfiles from ..allowed_functions import is_allowed from ..allowed_functions import is_builtin from ..al...
0.583203
0.095223
import arkit import sys import os import argparse import shutil import subprocess from collections import OrderedDict import struct from paths import * from linux_utils import run_shell_command_as_user from debug import get_logger log = get_logger("moddodo") SERVER_MOD_DIRECTORY = "ShooterGame/Content/Mods" STEAMC...
moddodo.py
import arkit import sys import os import argparse import shutil import subprocess from collections import OrderedDict import struct from paths import * from linux_utils import run_shell_command_as_user from debug import get_logger log = get_logger("moddodo") SERVER_MOD_DIRECTORY = "ShooterGame/Content/Mods" STEAMC...
0.176636
0.058132
from AccessControl.class_init import InitializeClass from AccessControl.SecurityInfo import ClassSecurityInfo from Products.PageTemplates.PageTemplateFile import PageTemplateFile from zope.interface import Interface from ..interfaces.plugins import ICredentialsResetPlugin from ..interfaces.plugins import ICredentialsU...
src/Products/PluggableAuthService/plugins/SessionAuthHelper.py
from AccessControl.class_init import InitializeClass from AccessControl.SecurityInfo import ClassSecurityInfo from Products.PageTemplates.PageTemplateFile import PageTemplateFile from zope.interface import Interface from ..interfaces.plugins import ICredentialsResetPlugin from ..interfaces.plugins import ICredentialsU...
0.45641
0.050214
from __future__ import annotations import datetime import functools import typing import json from vuakhter.utils.constants import DEFAULT_CHUNK_SIZE, INT_RE, FLOAT_RE, UUID_RE, LOGGING_CONFIG if typing.TYPE_CHECKING: from vuakhter.utils.types import DateOrDatetime, RequestEntry def chunks( iterable: typin...
vuakhter/utils/helpers.py
from __future__ import annotations import datetime import functools import typing import json from vuakhter.utils.constants import DEFAULT_CHUNK_SIZE, INT_RE, FLOAT_RE, UUID_RE, LOGGING_CONFIG if typing.TYPE_CHECKING: from vuakhter.utils.types import DateOrDatetime, RequestEntry def chunks( iterable: typin...
0.634883
0.122733
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from sib_api_v3_sdk.api_client import ApiClient class ProcessApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. ...
sib_api_v3_sdk/api/process_api.py
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from sib_api_v3_sdk.api_client import ApiClient class ProcessApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. ...
0.7011
0.050988
import os from peewee import * from NavigationDB.Marker.MarkerDB import Marker def MarkerAdd(): ''' # Помощь для генерации маркеров for id, val in enumerate([(490, 900), (700, 900), (450, 1158), (767, 1158), (790, 1573), (767, 1884), (975, 1900), (1100, 1792), (1100, 1594), (1100, 1490), (1050, 1370), ...
BSTU App/BSTU App/Database/DatabaseManagement/NavigationDB/Marker/GUK/Stage_1.py
import os from peewee import * from NavigationDB.Marker.MarkerDB import Marker def MarkerAdd(): ''' # Помощь для генерации маркеров for id, val in enumerate([(490, 900), (700, 900), (450, 1158), (767, 1158), (790, 1573), (767, 1884), (975, 1900), (1100, 1792), (1100, 1594), (1100, 1490), (1050, 1370), ...
0.124639
0.222162
import json import argparse def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument("--scenario", type=str, default="hangzhou_1x1_bc-tyc_18041607_1h") parser.add_argument("--num_step", type=int, default=3600) return parser.parse_args() def parse_roadnet(roadnetFile): roadne...
Single_Agent/ScalableArchitecture/utility.py
import json import argparse def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument("--scenario", type=str, default="hangzhou_1x1_bc-tyc_18041607_1h") parser.add_argument("--num_step", type=int, default=3600) return parser.parse_args() def parse_roadnet(roadnetFile): roadne...
0.401219
0.127273
from datetime import timedelta import json from homeassistant.components.metoffice.const import DOMAIN from homeassistant.const import STATE_UNAVAILABLE from homeassistant.util import utcnow from . import NewDateTime from .const import ( METOFFICE_CONFIG_KINGSLYNN, METOFFICE_CONFIG_WAVERTREE, WAVERTREE_SE...
tests/components/metoffice/test_weather.py
from datetime import timedelta import json from homeassistant.components.metoffice.const import DOMAIN from homeassistant.const import STATE_UNAVAILABLE from homeassistant.util import utcnow from . import NewDateTime from .const import ( METOFFICE_CONFIG_KINGSLYNN, METOFFICE_CONFIG_WAVERTREE, WAVERTREE_SE...
0.695441
0.264542
from setuptools import setup, find_packages import io VERSION = '1.0.8' NAME = 'canaro' AUTHOR = '<NAME>' AUTHOR_EMAIL = '<EMAIL>' AUTHOR_LONG = AUTHOR + ' <' + AUTHOR_EMAIL + '>' LICENSE = 'MIT' URL = 'https://github.com/jasmcaus/canaro' DOWNLOAD_URL = 'https://pypi.org/project/canaro/' PACKAGES = find_packages() D...
setup.py
from setuptools import setup, find_packages import io VERSION = '1.0.8' NAME = 'canaro' AUTHOR = '<NAME>' AUTHOR_EMAIL = '<EMAIL>' AUTHOR_LONG = AUTHOR + ' <' + AUTHOR_EMAIL + '>' LICENSE = 'MIT' URL = 'https://github.com/jasmcaus/canaro' DOWNLOAD_URL = 'https://pypi.org/project/canaro/' PACKAGES = find_packages() D...
0.489503
0.170456
from typing import Callable import aesara.tensor as aet import numpy as np from aesara.tensor.random.utils import RandomStream from aesara.tensor.var import TensorVariable from aehmc import hmc, integrators, metrics from aehmc.termination import iterative_uturn from aehmc.trajectory import dynamic_integration, multip...
aehmc/nuts.py
from typing import Callable import aesara.tensor as aet import numpy as np from aesara.tensor.random.utils import RandomStream from aesara.tensor.var import TensorVariable from aehmc import hmc, integrators, metrics from aehmc.termination import iterative_uturn from aehmc.trajectory import dynamic_integration, multip...
0.926416
0.81457
import pytest import numpy as np from pytest import approx from datetime import datetime import gemini3d.msis as gp @pytest.mark.skipif( gp.get_msis_exe() is None, reason="need to build msis_setup by gemini3d.setup_libs()", ) @pytest.mark.parametrize("version", [0, 20]) def test_msis(version, tmp_path): ...
src/gemini3d/tests/intg/test_msis.py
import pytest import numpy as np from pytest import approx from datetime import datetime import gemini3d.msis as gp @pytest.mark.skipif( gp.get_msis_exe() is None, reason="need to build msis_setup by gemini3d.setup_libs()", ) @pytest.mark.parametrize("version", [0, 20]) def test_msis(version, tmp_path): ...
0.435421
0.617051
"""Inception - reduced version of keras/applications/inception_v3.py .""" from kws_streaming.layers import modes from kws_streaming.layers import speech_features from kws_streaming.layers.compat import tf import kws_streaming.models.model_utils as utils def model_parameters(parser_nn): """Inception model parameter...
kws_streaming/models/inception.py
"""Inception - reduced version of keras/applications/inception_v3.py .""" from kws_streaming.layers import modes from kws_streaming.layers import speech_features from kws_streaming.layers.compat import tf import kws_streaming.models.model_utils as utils def model_parameters(parser_nn): """Inception model parameter...
0.954308
0.274372
from skorch.net import NeuralNet from ray_skorch.utils import insert_before_substring _docstring_neural_net_ray_args = """ num_workers : int Number of Ray Train workers to use. """ _docstring_neural_net_ray_worker_dataset = """ worker_dataset : torch Dataset (default=skorch.dataset.Dataset) Same a...
ray_skorch/docs.py
from skorch.net import NeuralNet from ray_skorch.utils import insert_before_substring _docstring_neural_net_ray_args = """ num_workers : int Number of Ray Train workers to use. """ _docstring_neural_net_ray_worker_dataset = """ worker_dataset : torch Dataset (default=skorch.dataset.Dataset) Same a...
0.924488
0.419113
import os import sys import argparse import traceback import signal from datetime import datetime, timedelta from functools import wraps from typing import TypeVar from .constants import (DEVICE_TYPES, BAUDRATE_LIST, INTERFACES) from .utils.print import print_red from .utils.resource import is_dev_mode T = TypeVar('T...
src/aceinna/framework/decorator.py
import os import sys import argparse import traceback import signal from datetime import datetime, timedelta from functools import wraps from typing import TypeVar from .constants import (DEVICE_TYPES, BAUDRATE_LIST, INTERFACES) from .utils.print import print_red from .utils.resource import is_dev_mode T = TypeVar('T...
0.468061
0.09709
import os import json from collect.configV2 import * from collect.code_processing_all import get_buggy_path def get_trigger_path(path_projects, name_list): """ return path list """ res = [] for name in name_list: tmp = path_projects + name + '/trigger_tests' res.append(tmp) ret...
collect/save_test_case.py
import os import json from collect.configV2 import * from collect.code_processing_all import get_buggy_path def get_trigger_path(path_projects, name_list): """ return path list """ res = [] for name in name_list: tmp = path_projects + name + '/trigger_tests' res.append(tmp) ret...
0.150871
0.105948
from django.db import models from django.contrib import admin import datetime from decimal import Decimal # Create your models here. class Curso(models.Model): nome = models.CharField("Nome", max_length=50) carga_horaria = models.IntegerField("Carga Horária") professor = models.CharField("Coordenador", max...
core/models.py
from django.db import models from django.contrib import admin import datetime from decimal import Decimal # Create your models here. class Curso(models.Model): nome = models.CharField("Nome", max_length=50) carga_horaria = models.IntegerField("Carga Horária") professor = models.CharField("Coordenador", max...
0.564939
0.156588
__copyright__ = 'Copyright (c) 2016, V-Squared, Portland State University' __license__ = 'CreativeCommons' import sys from os import path, mkdir import logging import pprint import time import argparse import whemulator def main(): emu = whemulator.Emu(**vars(parse_args())) emu.run() def parse_args(): ...
whSGD/main.py
__copyright__ = 'Copyright (c) 2016, V-Squared, Portland State University' __license__ = 'CreativeCommons' import sys from os import path, mkdir import logging import pprint import time import argparse import whemulator def main(): emu = whemulator.Emu(**vars(parse_args())) emu.run() def parse_args(): ...
0.334698
0.093182
import copy import numpy as nu from galpy.actionAngle_src.actionAngle import actionAngle from galpy.potential import IsochronePotential class actionAngleIsochrone(object): """Action-angle formalism for the isochrone potential, on the Jphi, Jtheta system of Binney & Tremaine (2008)""" def __init__(self,*args,**k...
galpy/actionAngle_src/actionAngleIsochrone.py
import copy import numpy as nu from galpy.actionAngle_src.actionAngle import actionAngle from galpy.potential import IsochronePotential class actionAngleIsochrone(object): """Action-angle formalism for the isochrone potential, on the Jphi, Jtheta system of Binney & Tremaine (2008)""" def __init__(self,*args,**k...
0.569015
0.26866
import collections from enum import Enum from vtypes import ( VString, VInt, VBool, VUnsignedInt, VDict, VValidatorDict, VList, VDate, VDateTime, VTime, VEnum, Validator, ) class Props(object): @classmethod def _attrs(cls): return [name for name in dir(...
mythtv_client/models.py
import collections from enum import Enum from vtypes import ( VString, VInt, VBool, VUnsignedInt, VDict, VValidatorDict, VList, VDate, VDateTime, VTime, VEnum, Validator, ) class Props(object): @classmethod def _attrs(cls): return [name for name in dir(...
0.667473
0.115112
import json import dash import dash_core_components as dcc import dash_html_components as html import dash_leaflet as dl import settings from dash.dependencies import Output, Input # Mapbox setup mapbox_url = "https://api.mapbox.com/styles/v1/mapbox/{id}/tiles/{{z}}/{{x}}/{{y}}{{r}}?access_token={access_token}" mapbo...
usage_gallery.py
import json import dash import dash_core_components as dcc import dash_html_components as html import dash_leaflet as dl import settings from dash.dependencies import Output, Input # Mapbox setup mapbox_url = "https://api.mapbox.com/styles/v1/mapbox/{id}/tiles/{{z}}/{{x}}/{{y}}{{r}}?access_token={access_token}" mapbo...
0.599837
0.240251
import unittest from backward import Backward # --------------------------------------------------------------------- class TestRead(unittest.TestCase): def test_empty(self): ctx = Backward() ans = ctx.read("") self.assertEqual(str(ans), "[]") def test_atom(self): ctx = Ba...
tests/test_read.py
import unittest from backward import Backward # --------------------------------------------------------------------- class TestRead(unittest.TestCase): def test_empty(self): ctx = Backward() ans = ctx.read("") self.assertEqual(str(ans), "[]") def test_atom(self): ctx = Ba...
0.683525
0.489137
import os import types import base64 import datetime import time import hashlib import hmac import urllib2 import httplib import ast import sys from xml.dom import minidom from azure.http import HTTPError, HTTPResponse from azure import _USER_AGENT_STRING class _HTTPClient: ''' Takes the request and sends it...
azure/http/httpclient.py
import os import types import base64 import datetime import time import hashlib import hmac import urllib2 import httplib import ast import sys from xml.dom import minidom from azure.http import HTTPError, HTTPResponse from azure import _USER_AGENT_STRING class _HTTPClient: ''' Takes the request and sends it...
0.266357
0.060641
from . import types import abc import logging import functools logger = logging.getLogger(__name__) def cache(function=None, *, types=None): ''' This decorator will store the results of a visitor method in self.cache and retrieve it if the id of a new object matches one in the cache. This simult...
align/schema/visitor.py
from . import types import abc import logging import functools logger = logging.getLogger(__name__) def cache(function=None, *, types=None): ''' This decorator will store the results of a visitor method in self.cache and retrieve it if the id of a new object matches one in the cache. This simult...
0.610802
0.462291
import pygame import sys import random areaSize = 30 tileSize = 20 headColor = (0, 100, 0) bodyColor = (0, 200, 0) foodColor = (200, 0, 0) gameSpeed = 10 class Snake(): def __init__(self): self.head = [5, 5] self.body = [[self.head[0], self.head[1]], [5, 6], [5, 7], [6, 8]] self.direction ...
Snake Game (Python)/snake.pyw
import pygame import sys import random areaSize = 30 tileSize = 20 headColor = (0, 100, 0) bodyColor = (0, 200, 0) foodColor = (200, 0, 0) gameSpeed = 10 class Snake(): def __init__(self): self.head = [5, 5] self.body = [[self.head[0], self.head[1]], [5, 6], [5, 7], [6, 8]] self.direction ...
0.262275
0.238151
import numpy as np import matplotlib.pyplot as plt from scipy.signal import bilinear_zpk, unit_impulse, sos2zpk, zpk2sos,\ sosfilt, sosfreqz from matplotlib.ticker import MultipleLocator from util import low_shelving_2nd_cascade, shelving_filter_parameters,\ db, set_rcparams, s...
python/mkfig-digital-3db-per-octave-shelving-filter.py
import numpy as np import matplotlib.pyplot as plt from scipy.signal import bilinear_zpk, unit_impulse, sos2zpk, zpk2sos,\ sosfilt, sosfreqz from matplotlib.ticker import MultipleLocator from util import low_shelving_2nd_cascade, shelving_filter_parameters,\ db, set_rcparams, s...
0.619011
0.3671
import datetime from dateutil.relativedelta import relativedelta from django import forms from django.templatetags.static import static class BulkSchedCreateForm(forms.Form): """Form for bulk_sched.""" error_css_class = "is-invalid" required_css_class = "required" EVENT_CHOICES = ( (None, "...
bulk_sched/forms.py
import datetime from dateutil.relativedelta import relativedelta from django import forms from django.templatetags.static import static class BulkSchedCreateForm(forms.Form): """Form for bulk_sched.""" error_css_class = "is-invalid" required_css_class = "required" EVENT_CHOICES = ( (None, "...
0.526343
0.213193
import sys import re def score_entities(tokens, key_extents, response_extents, key_attrs, response_attrs): fh1 = open(tokens) fh2 = open(key_extents) fh3 = open(response_extents) fh4 = open(key_attrs) fh5 = open(response_attrs) scores = Scores() for line in fh1: try: ...
extras/score_entities.py
import sys import re def score_entities(tokens, key_extents, response_extents, key_attrs, response_attrs): fh1 = open(tokens) fh2 = open(key_extents) fh3 = open(response_extents) fh4 = open(key_attrs) fh5 = open(response_attrs) scores = Scores() for line in fh1: try: ...
0.19521
0.174481
import streamlit as st try: from keywords import * from colored_expanders import add_color_to_expanders from render_to_do_list import to_do_list_from_lines from render_true_or_false import true_or_false_from_lines from render_multiple_choice import multiple_choice_from_lines from render_single_...
streamlit_book/render.py
import streamlit as st try: from keywords import * from colored_expanders import add_color_to_expanders from render_to_do_list import to_do_list_from_lines from render_true_or_false import true_or_false_from_lines from render_multiple_choice import multiple_choice_from_lines from render_single_...
0.17849
0.121217
import numpy as np import matplotlib.pylab as plt from netCDF4 import Dataset import matplotlib import cartopy.crs as ccrs import seaborn as sns from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import matplotlib.ticker as mticker import math from numba import jit import cartopy.mpl.ticker as ct...
figures/figure3/figure3 5subfig.py
import numpy as np import matplotlib.pylab as plt from netCDF4 import Dataset import matplotlib import cartopy.crs as ccrs import seaborn as sns from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER import matplotlib.ticker as mticker import math from numba import jit import cartopy.mpl.ticker as ct...
0.27048
0.418816
import asyncio import collections import pytest import prpc @pytest.mark.async_test async def test_properties(event_loop, rpc_local): "Check connection public properties and (very) basic state transitions." rpc = rpc_local(None, None, event_loop) assert not rpc.client_connection.connected assert n...
prpc/test/test_connection.py
import asyncio import collections import pytest import prpc @pytest.mark.async_test async def test_properties(event_loop, rpc_local): "Check connection public properties and (very) basic state transitions." rpc = rpc_local(None, None, event_loop) assert not rpc.client_connection.connected assert n...
0.572484
0.413832
from PySide2 import QtCore from PySide2.QtCore import Slot from eventnodes.base import ComputeNode from eventnodes.params import StringParam, IntParam, PARAM, EnumParam from eventnodes.signal import Signal, INPUT_PLUG, OUTPUT_PLUG from eventnodes.image.imageparam import ImageParam import sys from PIL import Image ...
nodes/camera.py
from PySide2 import QtCore from PySide2.QtCore import Slot from eventnodes.base import ComputeNode from eventnodes.params import StringParam, IntParam, PARAM, EnumParam from eventnodes.signal import Signal, INPUT_PLUG, OUTPUT_PLUG from eventnodes.image.imageparam import ImageParam import sys from PIL import Image ...
0.594669
0.207155
__author__="ymotongpoo <<EMAIL>>" __date__ ="$2009/02/01 18:30:41$" __version__="$Revision: 0.10" __credits__="0x7d8 -- programming training" import urllib from HTMLParser import HTMLParser, HTMLParseError import re # temporary for invalid HTML of hatena bookmark web page class ExtractEntryInfo(HTMLParser): def ...
0x7d8/Yonda/Buzzurl.py
__author__="ymotongpoo <<EMAIL>>" __date__ ="$2009/02/01 18:30:41$" __version__="$Revision: 0.10" __credits__="0x7d8 -- programming training" import urllib from HTMLParser import HTMLParser, HTMLParseError import re # temporary for invalid HTML of hatena bookmark web page class ExtractEntryInfo(HTMLParser): def ...
0.193071
0.111531
from django.core.urlresolvers import reverse from communique.utils.utils_tests import ViewsTestCase from medical.models import MedicalReport, MedicalReportType from patients.models import Patient class MedicalReportTypeListViewTestCase(ViewsTestCase): """ Test cases for the view that lists report types ...
medical/tests/test_views.py
from django.core.urlresolvers import reverse from communique.utils.utils_tests import ViewsTestCase from medical.models import MedicalReport, MedicalReportType from patients.models import Patient class MedicalReportTypeListViewTestCase(ViewsTestCase): """ Test cases for the view that lists report types ...
0.583085
0.354238
import matplotlib.pyplot as plt import os import numpy as np colors = [ 'orange', 'green', 'royalblue', 'purple', 'red', 'gold' ] def get_data(metric, run_id=None, run_path=None): if run_path is not None: metric_file_path = run_path + '/metric-' + metric + '.txt' else: ...
graphs/fid_graph.py
import matplotlib.pyplot as plt import os import numpy as np colors = [ 'orange', 'green', 'royalblue', 'purple', 'red', 'gold' ] def get_data(metric, run_id=None, run_path=None): if run_path is not None: metric_file_path = run_path + '/metric-' + metric + '.txt' else: ...
0.390708
0.285086
import uuid from typing import List, Dict import unittest from selfhost_client import SelfHostClient, UserType, PolicyType, UserTokenType, CreatedUserTokenResponse class TestIntegrationUsersClient(unittest.TestCase): """ Run these tests individually because Self-Host will return HTTP 429 Too Many Requests o...
test/integration_tests/test_integration_users_client.py
import uuid from typing import List, Dict import unittest from selfhost_client import SelfHostClient, UserType, PolicyType, UserTokenType, CreatedUserTokenResponse class TestIntegrationUsersClient(unittest.TestCase): """ Run these tests individually because Self-Host will return HTTP 429 Too Many Requests o...
0.732974
0.245108
from PySide2.QtGui import QColor from PySide2.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QListWidget, QListView, QStackedWidget, QWidget, \ QGroupBox, QLabel, QCheckBox, QPushButton, QLineEdit, QListWidgetItem, QScrollArea, QFrame, QComboBox, QSizePolicy from PySide2.QtCore import QSize from ..widgets.qco...
angrmanagement/ui/dialogs/preferences.py
from PySide2.QtGui import QColor from PySide2.QtWidgets import QDialog, QVBoxLayout, QHBoxLayout, QListWidget, QListView, QStackedWidget, QWidget, \ QGroupBox, QLabel, QCheckBox, QPushButton, QLineEdit, QListWidgetItem, QScrollArea, QFrame, QComboBox, QSizePolicy from PySide2.QtCore import QSize from ..widgets.qco...
0.379493
0.066327
import torch from torch import nn import torch.nn.functional as F from typing import List class CrossModalAttentionLayer(nn.Module): # y attends x def __init__(self, k, x_channels: int, y_size: int, spatial=True): super(CrossModalAttentionLayer, self).__init__() self.k = k self.spatial...
src/models/attention_block.py
import torch from torch import nn import torch.nn.functional as F from typing import List class CrossModalAttentionLayer(nn.Module): # y attends x def __init__(self, k, x_channels: int, y_size: int, spatial=True): super(CrossModalAttentionLayer, self).__init__() self.k = k self.spatial...
0.939157
0.65166
from google.appengine.ext import db class ChoiceProperty(db.IntegerProperty): """A property for efficiently storing choices made from a finite set. This works by mapping each choice to an integer. The choices must be hashable (so that they can be efficiently mapped back to their corresponding index). """ ...
catnado/properties/choice_property.py
from google.appengine.ext import db class ChoiceProperty(db.IntegerProperty): """A property for efficiently storing choices made from a finite set. This works by mapping each choice to an integer. The choices must be hashable (so that they can be efficiently mapped back to their corresponding index). """ ...
0.712232
0.338309
from collections import ChainMap import pathlib import re from pybtex.database import parse_string from pydictionaria.sfm_lib import Database as SFM, Entry from pydictionaria import sfm2cldf from cldfbench import CLDFSpec, Dataset as BaseDataset EID_PATTERN = re.compile('(?P<eid>TSE[0-9]+)') def reorganize(sfm): ...
cldfbench_tseltal.py
from collections import ChainMap import pathlib import re from pybtex.database import parse_string from pydictionaria.sfm_lib import Database as SFM, Entry from pydictionaria import sfm2cldf from cldfbench import CLDFSpec, Dataset as BaseDataset EID_PATTERN = re.compile('(?P<eid>TSE[0-9]+)') def reorganize(sfm): ...
0.568775
0.166675
COMMENTS = 'comments = null : varchar(4000)' DESCRIPTION = 'description = null : varchar(4000) # (detailed) description' PRIMARY_NAME = '{name} : <lookupname> # {comment}' TAGS = 'tags = null : <tags> # comma-separated tags' DICTTAGS = 'dict = null: <dicttags> # comma-separated tags with key=value format' NEURAL_RECORD...
loris/database/table_mixin.py
COMMENTS = 'comments = null : varchar(4000)' DESCRIPTION = 'description = null : varchar(4000) # (detailed) description' PRIMARY_NAME = '{name} : <lookupname> # {comment}' TAGS = 'tags = null : <tags> # comma-separated tags' DICTTAGS = 'dict = null: <dicttags> # comma-separated tags with key=value format' NEURAL_RECORD...
0.679285
0.181372
import logging import datajoint as dj import hashlib log = logging.getLogger(__name__) # safe-guard in case `custom` is not provided if 'custom' not in dj.config: dj.config['custom'] = {} def get_schema_name(name): try: return dj.config['custom']['{}.database'.format(name)] except KeyError: ...
pipeline/__init__.py
import logging import datajoint as dj import hashlib log = logging.getLogger(__name__) # safe-guard in case `custom` is not provided if 'custom' not in dj.config: dj.config['custom'] = {} def get_schema_name(name): try: return dj.config['custom']['{}.database'.format(name)] except KeyError: ...
0.585457
0.153074
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Writes a .json file with the per-apk details for an incremental install.""" import argparse import json import os import sys sys.path.append(os.path.jo...
src/build/android/incremental_install/write_installer_json.py
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Writes a .json file with the per-apk details for an incremental install.""" import argparse import json import os import sys sys.path.append(os.path.jo...
0.685213
0.089177
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
benchmarks/SimResults/micro_pinned_train_combos/cmpB_sjengpovrayomnetppmilc/power.py
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
0.608012
0.291605
"""This module contains Google Drive sensors.""" from typing import Optional, Sequence, Union from airflow.providers.google.suite.hooks.drive import GoogleDriveHook from airflow.sensors.base_sensor_operator import BaseSensorOperator from airflow.utils.decorators import apply_defaults class GoogleDriveFileExistenceS...
airflow/providers/google/suite/sensors/drive.py
"""This module contains Google Drive sensors.""" from typing import Optional, Sequence, Union from airflow.providers.google.suite.hooks.drive import GoogleDriveHook from airflow.sensors.base_sensor_operator import BaseSensorOperator from airflow.utils.decorators import apply_defaults class GoogleDriveFileExistenceS...
0.930813
0.392803
from __future__ import absolute_import # so we can import root 'aria' from aria.parser.loading import LiteralLocation from aria.parser.consumption import ( ConsumptionContext, ConsumerChain, Read, Validate, ServiceTemplate ) from aria.utils.imports import import_fullname from . import (Parser, P...
tests/mechanisms/parsing/aria.py
from __future__ import absolute_import # so we can import root 'aria' from aria.parser.loading import LiteralLocation from aria.parser.consumption import ( ConsumptionContext, ConsumerChain, Read, Validate, ServiceTemplate ) from aria.utils.imports import import_fullname from . import (Parser, P...
0.620622
0.057308
import numpy as np class Projectile(): def __init__(self,server, pid, x, y, vx, vy): self.server=server self.pid=pid self.kind='Projectile' self.x=x self.y=y self.vx=vx self.vy=vy self.tick=0 self.event='None' self.r=5 def...
server/main/projectile.py
import numpy as np class Projectile(): def __init__(self,server, pid, x, y, vx, vy): self.server=server self.pid=pid self.kind='Projectile' self.x=x self.y=y self.vx=vx self.vy=vy self.tick=0 self.event='None' self.r=5 def...
0.226869
0.113629
import tensorflow as tf import numpy as np import pickle import json import cv2 import sys import os import time sys.path.append(os.path.abspath(os.path.join('..', '3rd_party'))) from ServiceMTCNN import detect_face as lib def extract_faces_from_image(input_img, pnet, rnet, onet): # sess = tf.Session() # pne...
src/face_extraction.py
import tensorflow as tf import numpy as np import pickle import json import cv2 import sys import os import time sys.path.append(os.path.abspath(os.path.join('..', '3rd_party'))) from ServiceMTCNN import detect_face as lib def extract_faces_from_image(input_img, pnet, rnet, onet): # sess = tf.Session() # pne...
0.283583
0.253601
from bokeh.models.mappers import CategoricalColorMapper,LinearColorMapper from bokeh.models import (GMapOptions, Patches,GMapPlot,Range1d,ColorBar, WheelZoomTool,PanTool,TapTool,ColumnDataSource, Circle,FixedTicker) import dill from bokeh.plotting import gmap from bokeh.models.glyphs import Mul...
static/Subway.py
from bokeh.models.mappers import CategoricalColorMapper,LinearColorMapper from bokeh.models import (GMapOptions, Patches,GMapPlot,Range1d,ColorBar, WheelZoomTool,PanTool,TapTool,ColumnDataSource, Circle,FixedTicker) import dill from bokeh.plotting import gmap from bokeh.models.glyphs import Mul...
0.489259
0.382257
import cv2 import numpy as np from matplotlib import pylab as plt # Camera internals focal_length = 718.856 center = (607.1928, 185.2157) camera_matrix = np.array( [[focal_length, 0, center[0]], [0, focal_length, center[1]], [0, 0, 1]], dtype...
tools/testPoseEstimation.py
import cv2 import numpy as np from matplotlib import pylab as plt # Camera internals focal_length = 718.856 center = (607.1928, 185.2157) camera_matrix = np.array( [[focal_length, 0, center[0]], [0, focal_length, center[1]], [0, 0, 1]], dtype...
0.458349
0.433082
from ..biotools import windows_overlap import itertools import numpy as np class MutationChoice: """Represent a segment of a sequence with several possible variants. Parameters ---------- segment A pair (start, end) indicating the range of nucleotides concerned. We are applying Python ra...
dnachisel/MutationSpace/MutationChoice.py
from ..biotools import windows_overlap import itertools import numpy as np class MutationChoice: """Represent a segment of a sequence with several possible variants. Parameters ---------- segment A pair (start, end) indicating the range of nucleotides concerned. We are applying Python ra...
0.850018
0.487673
import pandas as pd import numpy as np from sklearn.linear_model import ElasticNet, ElasticNetCV from sklearn.model_selection import RepeatedKFold, GridSearchCV from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score from scripts.python.routines.betas import betas_drop_na import pickle import rand...
scripts/python/dataset_specific/GSEUNN/tasks/020_agena.py
import pandas as pd import numpy as np from sklearn.linear_model import ElasticNet, ElasticNetCV from sklearn.model_selection import RepeatedKFold, GridSearchCV from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score from scripts.python.routines.betas import betas_drop_na import pickle import rand...
0.643329
0.271095
import uuid import django_filters import taggit from django import forms from django.conf import settings as django_settings from django.contrib import auth from django.contrib.contenttypes.models import ContentType from django.core import exceptions from django.db.models import Q from django.db.models.functions impor...
src/waldur_core/structure/filters.py
import uuid import django_filters import taggit from django import forms from django.conf import settings as django_settings from django.contrib import auth from django.contrib.contenttypes.models import ContentType from django.core import exceptions from django.db.models import Q from django.db.models.functions impor...
0.529993
0.092893
import os import asyncio import logging import logging.handlers from dotenv import load_dotenv import discord from discord.ext import commands import utils # Establish Project Directories BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ASSETS_DIR = os.path.join(BASE_DIR, 'assets') LOGS_DIR =...
src/bot.py
import os import asyncio import logging import logging.handlers from dotenv import load_dotenv import discord from discord.ext import commands import utils # Establish Project Directories BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ASSETS_DIR = os.path.join(BASE_DIR, 'assets') LOGS_DIR =...
0.385837
0.054024
import unittest import unittest.mock as um import pytest from mmda.parsers.grobid_parser import GrobidHeaderParser XML_OK = open("tests/fixtures/grobid-tei-maml-header.xml").read() XML_NO_TITLE = open("tests/fixtures/grobid-tei-no-title.xml").read() XML_NO_ABS = open("tests/fixtures/grobid-tei-no-abstract.xml").read(...
tests/test_parsers/test_grobid_header_parser.py
import unittest import unittest.mock as um import pytest from mmda.parsers.grobid_parser import GrobidHeaderParser XML_OK = open("tests/fixtures/grobid-tei-maml-header.xml").read() XML_NO_TITLE = open("tests/fixtures/grobid-tei-no-title.xml").read() XML_NO_ABS = open("tests/fixtures/grobid-tei-no-abstract.xml").read(...
0.634656
0.290396
import logging import requests import argparse import os from bot.vpn_bot import VPNBot from telegram.ext import Updater, CommandHandler, MessageHandler, ConversationHandler, Filters requests.packages.urllib3.disable_warnings() TOKEN = os.getenv('TELEGRAM_TOKEN') VPN_LIMIT_GB = 10 def launch(): argparse.Argum...
vpn_bot/main.py
import logging import requests import argparse import os from bot.vpn_bot import VPNBot from telegram.ext import Updater, CommandHandler, MessageHandler, ConversationHandler, Filters requests.packages.urllib3.disable_warnings() TOKEN = os.getenv('TELEGRAM_TOKEN') VPN_LIMIT_GB = 10 def launch(): argparse.Argum...
0.407923
0.047914
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def drinks_wages(path): """Elderton and Pearson's (1910) data on drinking and wages In 1910, <...
observations/r/drinks_wages.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def drinks_wages(path): """Elderton and Pearson's (1910) data on drinking and wages In 1910, <...
0.667039
0.508605
import unittest class TestTopic(unittest.TestCase): PROJECT = 'PROJECT' TOPIC_NAME = 'topic_name' TOPIC_PATH = 'projects/%s/topics/%s' % (PROJECT, TOPIC_NAME) def _getTargetClass(self): from google.cloud.pubsub.topic import Topic return Topic def _makeOne(self, *args, **kw): ...
unit_tests/pubsub/test_topic.py
import unittest class TestTopic(unittest.TestCase): PROJECT = 'PROJECT' TOPIC_NAME = 'topic_name' TOPIC_PATH = 'projects/%s/topics/%s' % (PROJECT, TOPIC_NAME) def _getTargetClass(self): from google.cloud.pubsub.topic import Topic return Topic def _makeOne(self, *args, **kw): ...
0.455441
0.206464
from types import FunctionType from typing import Any, Optional, Tuple import torch from torch import Tensor from torch.utils.data import DataLoader, Dataset, TensorDataset class BatchDataset(Dataset): def __init__(self, dataset: Dataset, batch_size: int) -> None: self.dataset = dataset self.batc...
src/utils/data/dataset.py
from types import FunctionType from typing import Any, Optional, Tuple import torch from torch import Tensor from torch.utils.data import DataLoader, Dataset, TensorDataset class BatchDataset(Dataset): def __init__(self, dataset: Dataset, batch_size: int) -> None: self.dataset = dataset self.batc...
0.933218
0.695765
# Lint as: python3 """Utility functions for membership inference attacks.""" from typing import Text, Dict, Union, List, Any, Tuple import numpy as np import scipy.special from sklearn import metrics import tensorflow.compat.v1 as tf ArrayDict = Dict[Text, np.ndarray] Dataset = Tuple[Tuple[np.ndarray, np.ndarray], ...
privacy/tensorflow_privacy/privacy/membership_inference_attack/utils.py
# Lint as: python3 """Utility functions for membership inference attacks.""" from typing import Text, Dict, Union, List, Any, Tuple import numpy as np import scipy.special from sklearn import metrics import tensorflow.compat.v1 as tf ArrayDict = Dict[Text, np.ndarray] Dataset = Tuple[Tuple[np.ndarray, np.ndarray], ...
0.967625
0.662858
import os from flask import Flask, request, jsonify from mongoengine import * import datetime app = Flask(__name__) mongodb_uri = os.environ.get('MONGODB_URI', 'localhost:27017') connect("pokerstats", host=mongodb_uri) class Player(Document): name = StringField(required=True, unique=True, max_length=200) class R...
app.py
import os from flask import Flask, request, jsonify from mongoengine import * import datetime app = Flask(__name__) mongodb_uri = os.environ.get('MONGODB_URI', 'localhost:27017') connect("pokerstats", host=mongodb_uri) class Player(Document): name = StringField(required=True, unique=True, max_length=200) class R...
0.088835
0.052473
import logging import os import subprocess import time from urllib.parse import unquote_plus from oic.utils.http_util import ServiceError from otest.proc import isrunning from otest.rp.setup import read_path2port_map logger = logging.getLogger(__name__) class Application(object): def __init__(self, test_script,...
src/oidctest/tt/app.py
import logging import os import subprocess import time from urllib.parse import unquote_plus from oic.utils.http_util import ServiceError from otest.proc import isrunning from otest.rp.setup import read_path2port_map logger = logging.getLogger(__name__) class Application(object): def __init__(self, test_script,...
0.167491
0.092811
import numpy as np import gym ''' conda create -n reinforce python=3.6 anaconda conda activate reinforce conda install -c conda-forge tensorflow=1.14,gym,pybox2d,opencv pip install roboschool(does not work in windows) python <script_name>.py conda deactivate ''' """ cd "C:\Users\HP\Desktop\RL\Chapter-3\policyIteration....
Ch-3/policyIteration.py
import numpy as np import gym ''' conda create -n reinforce python=3.6 anaconda conda activate reinforce conda install -c conda-forge tensorflow=1.14,gym,pybox2d,opencv pip install roboschool(does not work in windows) python <script_name>.py conda deactivate ''' """ cd "C:\Users\HP\Desktop\RL\Chapter-3\policyIteration....
0.290477
0.301645
import datetime from colorama import Fore, Style from tabulate import tabulate from common.helpers import Helpers as helper class MesosMetrics(object): resources_master_cpus_percent = None resources_master_cpus_total = None resources_master_cpus_used = None resources_master_mem_percent = None r...
mesos_metrics.py
import datetime from colorama import Fore, Style from tabulate import tabulate from common.helpers import Helpers as helper class MesosMetrics(object): resources_master_cpus_percent = None resources_master_cpus_total = None resources_master_cpus_used = None resources_master_mem_percent = None r...
0.240418
0.319227
from __future__ import absolute_import from collections import defaultdict from random import randint, sample import pytest from kafka.structs import TopicPartition from kafka.coordinator.assignors.range import RangePartitionAssignor from kafka.coordinator.assignors.roundrobin import RoundRobinPartitionAssignor from...
test/test_assignors.py
from __future__ import absolute_import from collections import defaultdict from random import randint, sample import pytest from kafka.structs import TopicPartition from kafka.coordinator.assignors.range import RangePartitionAssignor from kafka.coordinator.assignors.roundrobin import RoundRobinPartitionAssignor from...
0.745861
0.460046
from nose import with_setup # optional import logging from pympler import tracker memory_tracker = tracker.SummaryTracker() logger = logging.getLogger(__name__) def setup_module(): """ | **@author:** <NAME> | | DL Module Setup - Called when this module is initialized - First Call """ pass ...
tests/test_memory_leak.py
from nose import with_setup # optional import logging from pympler import tracker memory_tracker = tracker.SummaryTracker() logger = logging.getLogger(__name__) def setup_module(): """ | **@author:** <NAME> | | DL Module Setup - Called when this module is initialized - First Call """ pass ...
0.700997
0.428054
import pprint import json import itertools import random def flatten(l): if isinstance(l, str): yield l else: for el in l: if not isinstance(el, str): for sub in flatten(el): yield sub else: yield el def score_group(grp1, grp2, numbers): # if isinstance(grp1, tuple)...
build_tree.py
import pprint import json import itertools import random def flatten(l): if isinstance(l, str): yield l else: for el in l: if not isinstance(el, str): for sub in flatten(el): yield sub else: yield el def score_group(grp1, grp2, numbers): # if isinstance(grp1, tuple)...
0.181444
0.122444
from datetime import datetime, timedelta from django.contrib.auth import get_user_model from django.utils import timezone from django.shortcuts import get_object_or_404 from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.views import stat...
ihub/duties/views/api.py
from datetime import datetime, timedelta from django.contrib.auth import get_user_model from django.utils import timezone from django.shortcuts import get_object_or_404 from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.views import stat...
0.50293
0.087369
import os import boto3 from boto3.dynamodb.conditions import Attr, Key from botocore.exceptions import ClientError # Connection Info TABLES = { 'products': { 'table_name': os.environ.get("DB_PRODUCTS"), }, 'orders': { 'table_name': os.environ.get("DB_ORDERS"), }, } ENDPOINT_URL = os.e...
papertesla/data.py
import os import boto3 from boto3.dynamodb.conditions import Attr, Key from botocore.exceptions import ClientError # Connection Info TABLES = { 'products': { 'table_name': os.environ.get("DB_PRODUCTS"), }, 'orders': { 'table_name': os.environ.get("DB_ORDERS"), }, } ENDPOINT_URL = os.e...
0.47098
0.113924
from sys import version_info as _swig_python_version_info if _swig_python_version_info < (2, 7, 0): raise RuntimeError("Python 2.7 or later required") # Import the low-level C/C++ module if __package__ or "." in __name__: from . import _bilinearform else: import _bilinearform try: import builtins as ...
mfem/_par/bilinearform.py
from sys import version_info as _swig_python_version_info if _swig_python_version_info < (2, 7, 0): raise RuntimeError("Python 2.7 or later required") # Import the low-level C/C++ module if __package__ or "." in __name__: from . import _bilinearform else: import _bilinearform try: import builtins as ...
0.428712
0.095645
import numpy as np from sklearn.neighbors import KNeighborsRegressor from algorithms.general_method import GeneralMethod from simulators.ode_simulator import calculate_fitness class DE(GeneralMethod): def __init__(self, config_method, config_model): super().__init__(config_method, config_model) ...
algorithms/population_optimization_algorithms.py
import numpy as np from sklearn.neighbors import KNeighborsRegressor from algorithms.general_method import GeneralMethod from simulators.ode_simulator import calculate_fitness class DE(GeneralMethod): def __init__(self, config_method, config_model): super().__init__(config_method, config_model) ...
0.760562
0.528959
from frsaccess import * from frscommon import * from frsclient.param import * from frsclient.result import * from frsclient.service import * class FrsClient(object): """ Creates a FRS(Face Recognize Service) frsclient with Initializing account information. Service kinds: Service Query (Service...
frsclient/frs_client.py
from frsaccess import * from frscommon import * from frsclient.param import * from frsclient.result import * from frsclient.service import * class FrsClient(object): """ Creates a FRS(Face Recognize Service) frsclient with Initializing account information. Service kinds: Service Query (Service...
0.827201
0.184584
from sys import argv import datetime import agg0, agg1, agg2, agg3 from pympler import asizeof def test(time_range): tree_conf = { "name":"1second", "range":"1s", "delta":"1s" } params_conf = [ [ "src", "dst", [ "src", "dst" ] ...
tests/test_args.py
from sys import argv import datetime import agg0, agg1, agg2, agg3 from pympler import asizeof def test(time_range): tree_conf = { "name":"1second", "range":"1s", "delta":"1s" } params_conf = [ [ "src", "dst", [ "src", "dst" ] ...
0.191933
0.300168
from time import sleep import numpy as np import pandas as pd from rx.disposable import Disposable from scipy import signal from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds from rx.subject import BehaviorSubject MIN_READ_BUFFER_DEPTH = 50 SAMPLING_RATE = 250 NUM_CHANNELS = 8 def n...
src/sensor/sensor_wrapper.py
from time import sleep import numpy as np import pandas as pd from rx.disposable import Disposable from scipy import signal from brainflow.board_shim import BoardShim, BrainFlowInputParams, LogLevels, BoardIds from rx.subject import BehaviorSubject MIN_READ_BUFFER_DEPTH = 50 SAMPLING_RATE = 250 NUM_CHANNELS = 8 def n...
0.629433
0.209631
import numpy as np from scipy import ndimage from scipy.interpolate import spline from scipy.ndimage.filters import gaussian_filter from scipy.spatial import ConvexHull from scipy.spatial import Delaunay from cheshire.Grid import * class Potential(object): """ A potential object containing information about t...
cheshire/Potential.py
import numpy as np from scipy import ndimage from scipy.interpolate import spline from scipy.ndimage.filters import gaussian_filter from scipy.spatial import ConvexHull from scipy.spatial import Delaunay from cheshire.Grid import * class Potential(object): """ A potential object containing information about t...
0.932176
0.661242
import re import discord import discord.utils from typing import Tuple, Optional, Iterator, Union, TypedDict, Protocol, cast import discord_client import util.db.kv import util.discord import util.frozen_dict import plugins.commands import plugins.privileges class MessageReactions(TypedDict): guild: str channe...
plugins/rolereactions.py
import re import discord import discord.utils from typing import Tuple, Optional, Iterator, Union, TypedDict, Protocol, cast import discord_client import util.db.kv import util.discord import util.frozen_dict import plugins.commands import plugins.privileges class MessageReactions(TypedDict): guild: str channe...
0.637482
0.077553
import sys import numpy as np import pandas as pd from scipy.spatial import distance import umap import category_encoders as ce import seaborn as sns import matplotlib.pyplot as plt import sh from tqdm import tqdm from loguru import logger sns.set_context('talk') def analyze_results( df, df_trans, df_dists,...
projects/29/src/distance_computations.py
import sys import numpy as np import pandas as pd from scipy.spatial import distance import umap import category_encoders as ce import seaborn as sns import matplotlib.pyplot as plt import sh from tqdm import tqdm from loguru import logger sns.set_context('talk') def analyze_results( df, df_trans, df_dists,...
0.410756
0.383006
import logging import textwrap from typing import Callable, List, Tuple, Union import numpy as np import torch from PIL import Image from torchvision import transforms from torchvision.datasets import VisionDataset from composer.core.types import Batch __all__ = [ "add_vision_dataset_transform", "Normalizati...
composer/datasets/utils.py
import logging import textwrap from typing import Callable, List, Tuple, Union import numpy as np import torch from PIL import Image from torchvision import transforms from torchvision.datasets import VisionDataset from composer.core.types import Batch __all__ = [ "add_vision_dataset_transform", "Normalizati...
0.941895
0.647102
import atexit import logging import os import signal import sys import threading import traceback import time import openerp from . import Command __author__ = openerp.release.author __version__ = openerp.release.version # Also use the `openerp` logger for the main script. _logger = logging.getLogger('openerp') de...
web/openerp/cli/server.py
import atexit import logging import os import signal import sys import threading import traceback import time import openerp from . import Command __author__ = openerp.release.author __version__ = openerp.release.version # Also use the `openerp` logger for the main script. _logger = logging.getLogger('openerp') de...
0.259732
0.053477
import FWCore.ParameterSet.Config as cms process = cms.Process("TEST") process.load("FWCore.Framework.test.cmsExceptionsFatal_cff") process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi") process.load("PhysicsTools.HepMCCandAlgos.genParticles_cfi") process.source = cms.Source("EmptySource") from GeneratorInterface....
GeneratorInterface/EvtGenInterface/test/Py8_tt_evtgen1_cfg.py
import FWCore.ParameterSet.Config as cms process = cms.Process("TEST") process.load("FWCore.Framework.test.cmsExceptionsFatal_cff") process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi") process.load("PhysicsTools.HepMCCandAlgos.genParticles_cfi") process.source = cms.Source("EmptySource") from GeneratorInterface....
0.439266
0.150403
import numpy as np from random import shuffle class Japanese: def question_hiragana(self, number_answers): hiragana = [ # a ('あ', 'a'), ('か', 'ka'), ('が', 'ga'), ('さ', 'sa'), ('ざ', 'za'), ('た', 'ta'), ('だ', 'da'), ('な', 'na'), ...
japanese.py
import numpy as np from random import shuffle class Japanese: def question_hiragana(self, number_answers): hiragana = [ # a ('あ', 'a'), ('か', 'ka'), ('が', 'ga'), ('さ', 'sa'), ('ざ', 'za'), ('た', 'ta'), ('だ', 'da'), ('な', 'na'), ...
0.228587
0.085978
import json import trt_pose.coco import torch from torch2trt import TRTModule import trt_pose.models import cv2 import torchvision.transforms as transforms import PIL.Image from trt_pose.draw_objects import DrawObjects from trt_pose.parse_objects import ParseObjects import argparse def preprocess(image): global ...
tasks/fork_lift/detect.py
import json import trt_pose.coco import torch from torch2trt import TRTModule import trt_pose.models import cv2 import torchvision.transforms as transforms import PIL.Image from trt_pose.draw_objects import DrawObjects from trt_pose.parse_objects import ParseObjects import argparse def preprocess(image): global ...
0.460289
0.268216
from openquake.hazardlib.gsim.edwards_fah_2013a import ( EdwardsFah2013Alpine10Bars, EdwardsFah2013Alpine20Bars, EdwardsFah2013Alpine30Bars, EdwardsFah2013Alpine50Bars, EdwardsFah2013Alpine60Bars, EdwardsFah2013Alpine75Bars, EdwardsFah2013Alpine90Bars, EdwardsFah2013Alpine120Bars ) from...
openquake/hazardlib/tests/gsim/edwards_faeh_2013_alpine_test.py
from openquake.hazardlib.gsim.edwards_fah_2013a import ( EdwardsFah2013Alpine10Bars, EdwardsFah2013Alpine20Bars, EdwardsFah2013Alpine30Bars, EdwardsFah2013Alpine50Bars, EdwardsFah2013Alpine60Bars, EdwardsFah2013Alpine75Bars, EdwardsFah2013Alpine90Bars, EdwardsFah2013Alpine120Bars ) from...
0.635222
0.291617
import os import re import sys from signal import SIG_DFL, SIGPIPE, signal from subprocess import PIPE, Popen from docopt import docopt from vcfkit.utils.vcf import * signal(SIGPIPE, SIG_DFL) # Info r_info = re.compile(r'''\#\#INFO=< ID=(?P<id>[^,]+), Number=(?P<number>-?\d+|\.|[AG]), Type=(?P<type>Integer|Flo...
vcfkit/vcf2tsv.py
import os import re import sys from signal import SIG_DFL, SIGPIPE, signal from subprocess import PIPE, Popen from docopt import docopt from vcfkit.utils.vcf import * signal(SIGPIPE, SIG_DFL) # Info r_info = re.compile(r'''\#\#INFO=< ID=(?P<id>[^,]+), Number=(?P<number>-?\d+|\.|[AG]), Type=(?P<type>Integer|Flo...
0.094929
0.201401
import sys from torch.utils.data import Dataset, DataLoader import os import glob import numpy as np import random import cv2 import json import h5py import torch sys.path.append('./src') from util import calc_aabb, cut_image, flip_image, draw_lsp_14kp__bone, rectangle_intersect, get_rectangle_intersect_ratio, conver...
pytorch_src/dataloader/hum36m_dataloader.py
import sys from torch.utils.data import Dataset, DataLoader import os import glob import numpy as np import random import cv2 import json import h5py import torch sys.path.append('./src') from util import calc_aabb, cut_image, flip_image, draw_lsp_14kp__bone, rectangle_intersect, get_rectangle_intersect_ratio, conver...
0.391871
0.332907