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 random from .operators import prod from numpy import array, float64, ndarray import numba MAX_DIMS = 32 class IndexingError(RuntimeError): "Exception raised for indexing errors." pass def index_to_position(index, strides): """ Converts a multidimensional tensor `index` into a single-dimensio...
jtorch/tensor_data.py
import random from .operators import prod from numpy import array, float64, ndarray import numba MAX_DIMS = 32 class IndexingError(RuntimeError): "Exception raised for indexing errors." pass def index_to_position(index, strides): """ Converts a multidimensional tensor `index` into a single-dimensio...
0.886076
0.61806
import datetime import logging from decimal import Decimal from typing import Optional from money import Money from tau.core import HistoricNetworkScheduler, NetworkScheduler from serenity.strategy.api import StrategyContext, TradingContext, Tradable, Transaction, TradingCostCalculator, \ PricingContext, PriceFie...
src/serenity/strategy/historical.py
import datetime import logging from decimal import Decimal from typing import Optional from money import Money from tau.core import HistoricNetworkScheduler, NetworkScheduler from serenity.strategy.api import StrategyContext, TradingContext, Tradable, Transaction, TradingCostCalculator, \ PricingContext, PriceFie...
0.893635
0.179513
from unittest import mock from ironic_python_agent import agent from ironic_python_agent import errors from ironic_python_agent.extensions import poll from ironic_python_agent import hardware from ironic_python_agent.tests.unit import base class TestPollExtension(base.IronicAgentTest): def setUp(self): ...
ironic_python_agent/tests/unit/extensions/test_poll.py
from unittest import mock from ironic_python_agent import agent from ironic_python_agent import errors from ironic_python_agent.extensions import poll from ironic_python_agent import hardware from ironic_python_agent.tests.unit import base class TestPollExtension(base.IronicAgentTest): def setUp(self): ...
0.695338
0.188884
from roboter.models import ranking from roboter.views import console DEFAULT_ROBOT_NAME = 'Roboko' class Robot(object): """Base model for Robot.""" def __init__(self, name=DEFAULT_ROBOT_NAME, user_name='', speak_color='green'): self.name = name self.user_name = user_name ...
python_programming_demo_app-0.0.1/roboter/models/robot.py
from roboter.models import ranking from roboter.views import console DEFAULT_ROBOT_NAME = 'Roboko' class Robot(object): """Base model for Robot.""" def __init__(self, name=DEFAULT_ROBOT_NAME, user_name='', speak_color='green'): self.name = name self.user_name = user_name ...
0.844553
0.154472
import hashlib import binascii import sys import bisect import hmac import itertools import os import sys import unicodedata # Word list comes from here: # https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt text_file = open("wordList.txt", "r") wordList = text_file.read().split(',') text_file.close() u...
generator.py
import hashlib import binascii import sys import bisect import hmac import itertools import os import sys import unicodedata # Word list comes from here: # https://github.com/bitcoin/bips/blob/master/bip-0039/english.txt text_file = open("wordList.txt", "r") wordList = text_file.read().split(',') text_file.close() u...
0.450359
0.273111
import uuid from neutron_lib.placement import utils as place_utils from neutron_lib.tests import _base as base class TestPlacementUtils(base.BaseTestCase): def setUp(self): super(TestPlacementUtils, self).setUp() self._uuid_ns = uuid.UUID('94fedd4d-1ce0-4bb3-9c9a-c9c0f56de154') def test_p...
neutron_lib/tests/unit/placement/test_utils.py
import uuid from neutron_lib.placement import utils as place_utils from neutron_lib.tests import _base as base class TestPlacementUtils(base.BaseTestCase): def setUp(self): super(TestPlacementUtils, self).setUp() self._uuid_ns = uuid.UUID('94fedd4d-1ce0-4bb3-9c9a-c9c0f56de154') def test_p...
0.679498
0.229384
import os import sys import inspect import argparse import keyword import vapoursynth from typing import Dict, List, Optional, Sequence, Union, NamedTuple parser = argparse.ArgumentParser() parser.add_argument("plugins", type=str, nargs="*", help="Only generate stubs for and inject specified plugin namespaces.") pars...
vsgenstubs/__init__.py
import os import sys import inspect import argparse import keyword import vapoursynth from typing import Dict, List, Optional, Sequence, Union, NamedTuple parser = argparse.ArgumentParser() parser.add_argument("plugins", type=str, nargs="*", help="Only generate stubs for and inject specified plugin namespaces.") pars...
0.615088
0.158207
import sqlite3 import logging import os from db.peers import Peers from db.commands import Commands class LightningDB: """DB-dependent wrapper around SQLite3. Runs migration if `user_version` is older than `MAX_VERSION` and register a trigger for automated orphan removal. """ MAX_VERSION = 1 ...
db/__init__.py
import sqlite3 import logging import os from db.peers import Peers from db.commands import Commands class LightningDB: """DB-dependent wrapper around SQLite3. Runs migration if `user_version` is older than `MAX_VERSION` and register a trigger for automated orphan removal. """ MAX_VERSION = 1 ...
0.543833
0.070176
from __future__ import unicode_literals import datetime from decimal import Decimal from django.test import TestCase from django.test.utils import skipUnless from six.moves import StringIO from django.utils.translation import gettext_lazy from rest_framework_xml.renderers import XMLRenderer from rest_framework_xml.pa...
tests/test_renderers.py
from __future__ import unicode_literals import datetime from decimal import Decimal from django.test import TestCase from django.test.utils import skipUnless from six.moves import StringIO from django.utils.translation import gettext_lazy from rest_framework_xml.renderers import XMLRenderer from rest_framework_xml.pa...
0.685844
0.30632
import re import os from typing import TextIO, List, Tuple, Optional, Dict # name, default value, description Entity = Tuple[str, str, str] # https://regex101.com/r/R6iogw/12 cmake_option_regex: str = r"^\s*option\s*\(([A-Z_0-9${}]+)\s*(?:\"((?:.|\n)*?)\")?\s*(.*)?\).*$" ch_master_url: str = "https://github.com/clic...
docs/tools/cmake_in_clickhouse_generator.py
import re import os from typing import TextIO, List, Tuple, Optional, Dict # name, default value, description Entity = Tuple[str, str, str] # https://regex101.com/r/R6iogw/12 cmake_option_regex: str = r"^\s*option\s*\(([A-Z_0-9${}]+)\s*(?:\"((?:.|\n)*?)\")?\s*(.*)?\).*$" ch_master_url: str = "https://github.com/clic...
0.667581
0.187579
from dataclasses import dataclass from pms import InconsistentObservation from pms.sensor import base from . import pms3003 commands = base.Commands( passive_read=base.Cmd(b"\x42\x4D\xE2\x00\x00\x01\x71", b"\x42\x4D\x00\x1c", 32), passive_mode=base.Cmd(b"\x42\x4D\xE1\x00\x00\x01\x70", b"\x42\x4D\x00\x04", 8)...
src/pms/sensor/plantower/pmsx003.py
from dataclasses import dataclass from pms import InconsistentObservation from pms.sensor import base from . import pms3003 commands = base.Commands( passive_read=base.Cmd(b"\x42\x4D\xE2\x00\x00\x01\x71", b"\x42\x4D\x00\x1c", 32), passive_mode=base.Cmd(b"\x42\x4D\xE1\x00\x00\x01\x70", b"\x42\x4D\x00\x04", 8)...
0.715722
0.328112
import smart_imports smart_imports.all() class PrototypeTests(utils_testcase.TestCase): def setUp(self): super(PrototypeTests, self).setUp() self.date = datetime.datetime.now() self.timedelta = datetime.timedelta(microseconds=1) def test_create(self): with self.check_delta(...
src/the_tale/the_tale/statistics/tests/test_prototypes.py
import smart_imports smart_imports.all() class PrototypeTests(utils_testcase.TestCase): def setUp(self): super(PrototypeTests, self).setUp() self.date = datetime.datetime.now() self.timedelta = datetime.timedelta(microseconds=1) def test_create(self): with self.check_delta(...
0.606265
0.575349
import pymongo def get_connection(): return pymongo.MongoClient().demo_oauth_provider class Model(dict): @classmethod def get_collection(cls): conn = get_connection() return conn[cls.table] @classmethod def find_one(cls, attrs): return cls.get_collection().find_o...
examples/mongo_demoprovider/models.py
import pymongo def get_connection(): return pymongo.MongoClient().demo_oauth_provider class Model(dict): @classmethod def get_collection(cls): conn = get_connection() return conn[cls.table] @classmethod def find_one(cls, attrs): return cls.get_collection().find_o...
0.637257
0.136493
import argparse import time def main() -> None: """"Execute the main routine.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--module", help="name of the module to import", choices=[ "functions_100_with_no_contract", ...
benchmarks/import_cost/measure.py
import argparse import time def main() -> None: """"Execute the main routine.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--module", help="name of the module to import", choices=[ "functions_100_with_no_contract", ...
0.412294
0.353903
import typing as T import voluptuous as vol from ... import common from .base import ActorBase ALLOWED_VALUE_TYPES = (float, int, str, type(None)) ALLOWED_VALUE_TYPES_T = T.Union[float, int, str, None] # pylint: disable=invalid-name VALUE_DEF_SCHEMA = vol.Schema( vol.All( lambda v: v or {}, { ...
hass_apps/schedy/actor/generic.py
import typing as T import voluptuous as vol from ... import common from .base import ActorBase ALLOWED_VALUE_TYPES = (float, int, str, type(None)) ALLOWED_VALUE_TYPES_T = T.Union[float, int, str, None] # pylint: disable=invalid-name VALUE_DEF_SCHEMA = vol.Schema( vol.All( lambda v: v or {}, { ...
0.690246
0.142351
import os import shutil import subprocess import traceback from pathlib import Path from termcolor import colored os.system("color") print( colored( """ ooooo ooo ooooo ooooo ooooooo ooooo `888' `8' `888' `888' `8888 d8' 888 8 888 888 Y888..8P...
export_game.py
import os import shutil import subprocess import traceback from pathlib import Path from termcolor import colored os.system("color") print( colored( """ ooooo ooo ooooo ooooo ooooooo ooooo `888' `8' `888' `888' `8888 d8' 888 8 888 888 Y888..8P...
0.276691
0.18101
"""Base settings shared by all environments""" # Import global settings to make it easier to extend settings. from django.conf.global_settings import * # pylint: disable=W0614,W0401 from django.template.defaultfilters import slugify #============================================================================== # ...
umap/settings/base.py
"""Base settings shared by all environments""" # Import global settings to make it easier to extend settings. from django.conf.global_settings import * # pylint: disable=W0614,W0401 from django.template.defaultfilters import slugify #============================================================================== # ...
0.427038
0.053949
import os.path import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import random class Critic(nn.Module): def __init__(self, input_size, output_size, hidden_size): super().__init__() self.input_size = input_size self.output_size = output_size ...
course_competition/rl_trainer/dqn.py
import os.path import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import random class Critic(nn.Module): def __init__(self, input_size, output_size, hidden_size): super().__init__() self.input_size = input_size self.output_size = output_size ...
0.864525
0.410874
import types class OidMap: ''' Create OidMap ''' def __init__(self): self.map = {} def get_oid_map(self): return self.map def map_objs(self,**kwobjs): ''' Usually use to update the map. Sample usage: cl...
rock4/common/dev/idleshell/diyoid.py
import types class OidMap: ''' Create OidMap ''' def __init__(self): self.map = {} def get_oid_map(self): return self.map def map_objs(self,**kwobjs): ''' Usually use to update the map. Sample usage: cl...
0.219338
0.116036
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Plink', fields=[ (...
plink/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Plink', fields=[ (...
0.617974
0.159839
import requests import hmac from hashlib import sha1 import json try: from urllib.parse import urlencode except ImportError: # python2 from urllib import urlencode CS_URL = "https://hapi.couchsurfing.com" PRIVATE_KEY = "<KEY>" class AuthError(Exception): """ Authentication error """ def _...
couchsurfing/api.py
import requests import hmac from hashlib import sha1 import json try: from urllib.parse import urlencode except ImportError: # python2 from urllib import urlencode CS_URL = "https://hapi.couchsurfing.com" PRIVATE_KEY = "<KEY>" class AuthError(Exception): """ Authentication error """ def _...
0.491456
0.140218
import json import re import shutil import uuid import htcondor from .utilities import run def rerun_workflow(self, username, groups, email, workflow_id): """ Re-run any failed jobs from a completed workflow """ schedd = htcondor.Schedd() constraint = 'ProminenceIdentity =?= "%s" && ClusterId ==...
frontend/prominence/backend/rerun_workflow.py
import json import re import shutil import uuid import htcondor from .utilities import run def rerun_workflow(self, username, groups, email, workflow_id): """ Re-run any failed jobs from a completed workflow """ schedd = htcondor.Schedd() constraint = 'ProminenceIdentity =?= "%s" && ClusterId ==...
0.309963
0.093678
import abc import typing import grpclib.const import grpclib.client if typing.TYPE_CHECKING: import grpclib.server from . import backups_pb2 from . import mutations_pb2 class MutationsBase(abc.ABC): @abc.abstractmethod async def FlattenMutations(self, stream: 'grpclib.server.Stream[mutations_pb2.Mutati...
dbots/protos/mutations_grpc.py
import abc import typing import grpclib.const import grpclib.client if typing.TYPE_CHECKING: import grpclib.server from . import backups_pb2 from . import mutations_pb2 class MutationsBase(abc.ABC): @abc.abstractmethod async def FlattenMutations(self, stream: 'grpclib.server.Stream[mutations_pb2.Mutati...
0.528533
0.082549
import click import os import subprocess import sys from augur.runtime import pass_application from augur.util import logger @click.group('util', short_help='Miscellaneous utilities') def cli(): pass @cli.command('shell', short_help='Drop into a shell') @pass_application def shell(app): app.shell() @cli.comm...
augur/cli/util.py
import click import os import subprocess import sys from augur.runtime import pass_application from augur.util import logger @click.group('util', short_help='Miscellaneous utilities') def cli(): pass @cli.command('shell', short_help='Drop into a shell') @pass_application def shell(app): app.shell() @cli.comm...
0.265785
0.065038
import numpy as np class CountFeaturesExtractor(object): def __init__(self, stream): self.stream = stream def __iter__(self): for variant_label, alleles, genotypes in self.stream: chrom, pos = variant_label ref_column = [0.] * len(genotypes) alt_column = [0....
asaph/feature_extraction.py
import numpy as np class CountFeaturesExtractor(object): def __init__(self, stream): self.stream = stream def __iter__(self): for variant_label, alleles, genotypes in self.stream: chrom, pos = variant_label ref_column = [0.] * len(genotypes) alt_column = [0....
0.534612
0.340184
import os import re import sys import time import errno import signal import select from botnet import Command # Helpers def popen(*args, **keys): import subprocess defaults = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "stdin": subprocess.PIPE, "close_fds": True...
abusehelper/tools/botnet/commands.py
import os import re import sys import time import errno import signal import select from botnet import Command # Helpers def popen(*args, **keys): import subprocess defaults = { "stdout": subprocess.PIPE, "stderr": subprocess.PIPE, "stdin": subprocess.PIPE, "close_fds": True...
0.268078
0.096365
from ._base import NumpyBaseLinearRegressor, TFBaseLinearRegressor, TorchBaseLinearRegressor import numpy as np import tensorflow as tf import torch class NumpyLWLR(NumpyBaseLinearRegressor): """Locally Weighted Linear Regression model with Numpy, explicitly inherits from NumpyBaseLinearRegressor already...
LossJLearn/linear_model/_lwlr.py
from ._base import NumpyBaseLinearRegressor, TFBaseLinearRegressor, TorchBaseLinearRegressor import numpy as np import tensorflow as tf import torch class NumpyLWLR(NumpyBaseLinearRegressor): """Locally Weighted Linear Regression model with Numpy, explicitly inherits from NumpyBaseLinearRegressor already...
0.933529
0.587559
import serial import adafruit_board_toolkit.circuitpython_serial from animatedgif import AnimatedGif import pygame port = None def detect_port(): """ Detect the port automatically """ comports = adafruit_board_toolkit.circuitpython_serial.data_comports() ports = [comport.device for comport in com...
Raspberry_Pi_Animated_Gif_Player/pygame_player.py
import serial import adafruit_board_toolkit.circuitpython_serial from animatedgif import AnimatedGif import pygame port = None def detect_port(): """ Detect the port automatically """ comports = adafruit_board_toolkit.circuitpython_serial.data_comports() ports = [comport.device for comport in com...
0.581897
0.230324
from django.shortcuts import render,redirect from .models import Profile,Project from django.contrib.auth.decorators import login_required from .forms import ProjectForm,VoteForm,EditProfile from rest_framework.response import Response from rest_framework.views import APIView from .serializer import ProjectSerializer,P...
awards/views.py
from django.shortcuts import render,redirect from .models import Profile,Project from django.contrib.auth.decorators import login_required from .forms import ProjectForm,VoteForm,EditProfile from rest_framework.response import Response from rest_framework.views import APIView from .serializer import ProjectSerializer,P...
0.31321
0.072014
import numpy as np import pandas as pd from hics.slice_similarity import continuous_similarity_matrix, categorical_similarity_matrix from hics.slice_selection import select_by_similarity class ScoredSlices: def __init__(self, categorical, continuous, to_keep=5, threshold=None): self.continuous = {feature:...
hics/scored_slices.py
import numpy as np import pandas as pd from hics.slice_similarity import continuous_similarity_matrix, categorical_similarity_matrix from hics.slice_selection import select_by_similarity class ScoredSlices: def __init__(self, categorical, continuous, to_keep=5, threshold=None): self.continuous = {feature:...
0.638272
0.568895
import pytest import sru import torch @pytest.mark.parametrize( "cuda", [ False, pytest.param( True, marks=pytest.mark.skipif( not torch.cuda.is_available(), reason="no cuda available" ), ), ], ) @pytest.mark.parametrize("with_gra...
test/sru/test_sru.py
import pytest import sru import torch @pytest.mark.parametrize( "cuda", [ False, pytest.param( True, marks=pytest.mark.skipif( not torch.cuda.is_available(), reason="no cuda available" ), ), ], ) @pytest.mark.parametrize("with_gra...
0.706899
0.616532
from __future__ import absolute_import, print_function import datetime as dt import logging import time import re import ujson from pyclickhouse.FilterableCache import FilterableCache from pyclickhouse.formatter import TabSeparatedWithNamesAndTypesFormatter, NestingLevelTooHigh class Cursor(object): """ Due...
pyclickhouse/Cursor.py
from __future__ import absolute_import, print_function import datetime as dt import logging import time import re import ujson from pyclickhouse.FilterableCache import FilterableCache from pyclickhouse.formatter import TabSeparatedWithNamesAndTypesFormatter, NestingLevelTooHigh class Cursor(object): """ Due...
0.780412
0.366987
# ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- import numpy as np from SUAVE.Core import Units # ---------------------------------------------------------------------- # Expand State # ---------------------...
SUAVE/SUAVE-2.5.0/trunk/SUAVE/Methods/Missions/Segments/Descent/Constant_Speed_Constant_Angle_Noise.py
# ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- import numpy as np from SUAVE.Core import Units # ---------------------------------------------------------------------- # Expand State # ---------------------...
0.87766
0.647241
from scrapy import Spider from scrapy.http import Request from firmware.items import FirmwareImage from firmware.loader import FirmwareLoader import urllib.parse class AsusSpider(Spider): name = "asus-old" region = "en" allowed_domains = ["asus.com"] start_urls = ["https://www.asus.com/support/"] ...
sources/scraper/firmware/spiders/asus-old.py
from scrapy import Spider from scrapy.http import Request from firmware.items import FirmwareImage from firmware.loader import FirmwareLoader import urllib.parse class AsusSpider(Spider): name = "asus-old" region = "en" allowed_domains = ["asus.com"] start_urls = ["https://www.asus.com/support/"] ...
0.272025
0.083217
import serial class SerialDriver: """ | A driver for the serial port that simply wraps around the standard pyserial python module. | On init it stores the values passed as parameters and | opens the connection. Args: This are the exact same that pyserial uses """ def __i...
MTP/drivers/SerialDriver.py
import serial class SerialDriver: """ | A driver for the serial port that simply wraps around the standard pyserial python module. | On init it stores the values passed as parameters and | opens the connection. Args: This are the exact same that pyserial uses """ def __i...
0.743541
0.293784
from __future__ import absolute_import __all__ = ('BroadPhase',) __version__ = "$Revision: 342 $" __date__ = "$Date: 2011-06-07 17:05:00 -0400 (Tue, 07 Jun 2011) $" # $Source$ from .dynamictree import DynamicTree class BroadPhase(object): """ The broad-phase is used for computing pairs and perfo...
pypybox2d/broadphase.py
from __future__ import absolute_import __all__ = ('BroadPhase',) __version__ = "$Revision: 342 $" __date__ = "$Date: 2011-06-07 17:05:00 -0400 (Tue, 07 Jun 2011) $" # $Source$ from .dynamictree import DynamicTree class BroadPhase(object): """ The broad-phase is used for computing pairs and perfo...
0.833291
0.242935
from mapreduce import mapreduce import json from collections import defaultdict from tssb_miner.edit_abstraction import abstract_edit_script def label_instance(slc): labels = ["ALL"] if slc["likely_bug"]: labels.append("BUGGY") if not slc["comodified"]: labels.append("NOCOMODIFIED"...
stats.py
from mapreduce import mapreduce import json from collections import defaultdict from tssb_miner.edit_abstraction import abstract_edit_script def label_instance(slc): labels = ["ALL"] if slc["likely_bug"]: labels.append("BUGGY") if not slc["comodified"]: labels.append("NOCOMODIFIED"...
0.335895
0.119408
from keras import backend as K from keras.engine.topology import Layer import numpy as np import tensorflow as tf from keras import regularizers, constraints, initializers, activations class Dense_New(Layer): def __init__(self, units, activation=None, use_bias=True, # ...
LSTM/dense_new.py
from keras import backend as K from keras.engine.topology import Layer import numpy as np import tensorflow as tf from keras import regularizers, constraints, initializers, activations class Dense_New(Layer): def __init__(self, units, activation=None, use_bias=True, # ...
0.839471
0.409575
from typing import Iterator, List, Tuple import abc from datetime import datetime from PiCN.Layers.ICNLayer.ForwardingInformationBase import BaseForwardingInformationBase, ForwardingInformationBaseEntry from PiCN.Packets import Name class BaseRoutingInformationBase(abc.ABC): """ Abstract base class to be im...
PiCN/Layers/RoutingLayer/RoutingInformationBase/BaseRoutingInformationBase.py
from typing import Iterator, List, Tuple import abc from datetime import datetime from PiCN.Layers.ICNLayer.ForwardingInformationBase import BaseForwardingInformationBase, ForwardingInformationBaseEntry from PiCN.Packets import Name class BaseRoutingInformationBase(abc.ABC): """ Abstract base class to be im...
0.884264
0.26486
from random import choice from string import ascii_uppercase import logging import time # logging.basicConfig(level=logging.INFO) def timeit(method): """Calculates time taken to run a function when called""" def timed(*args, **kw): t1 = time.time() result = method(*args, **kw) print '...
boggle.py
from random import choice from string import ascii_uppercase import logging import time # logging.basicConfig(level=logging.INFO) def timeit(method): """Calculates time taken to run a function when called""" def timed(*args, **kw): t1 = time.time() result = method(*args, **kw) print '...
0.518302
0.338842
from hsml.connection import CONNECTION_SAAS_HOSTNAME from hsml.client.hopsworks import base as hw_base from hsml.client.hopsworks import internal as hw_internal from hsml.client.hopsworks import external as hw_external from hsml.client.istio import base as ist_base from hsml.client.istio import internal as ist_inter...
python/hsml/client/__init__.py
from hsml.connection import CONNECTION_SAAS_HOSTNAME from hsml.client.hopsworks import base as hw_base from hsml.client.hopsworks import internal as hw_internal from hsml.client.hopsworks import external as hw_external from hsml.client.istio import base as ist_base from hsml.client.istio import internal as ist_inter...
0.406155
0.04075
import numpy as np import math from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QiskitError from qiskit.compiler import assemble from qiskit.providers.aer import QasmSimulator from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.synthesis import two_qubit_cnot_decompose ...
test/benchmark/fusion_benchmarks.py
import numpy as np import math from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, QiskitError from qiskit.compiler import assemble from qiskit.providers.aer import QasmSimulator from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info.synthesis import two_qubit_cnot_decompose ...
0.661923
0.605303
import numpy as np class Statistic: def __init__(self, data=None): if data is not None: self._data = list(data) else: self._data = [] def append(self, value): self._data.append(value) def extend(self, data): self._data.extend(data) ...
pydesim/statistics.py
import numpy as np class Statistic: def __init__(self, data=None): if data is not None: self._data = list(data) else: self._data = [] def append(self, value): self._data.append(value) def extend(self, data): self._data.extend(data) ...
0.492676
0.442817
import argparse import datetime from remove_space import remove_space from model_test import Tester # Allows a model to be tested from the terminal. dataset = 'REDD' # dataset = 'UKDALE' # dataset = 'REFIT' # You need to input your test data directory # appliances = ['microwave','fridge','dishwasher','washingmachine'...
test_transfer.py
import argparse import datetime from remove_space import remove_space from model_test import Tester # Allows a model to be tested from the terminal. dataset = 'REDD' # dataset = 'UKDALE' # dataset = 'REFIT' # You need to input your test data directory # appliances = ['microwave','fridge','dishwasher','washingmachine'...
0.400163
0.229794
import re import cfgrib from metpy.units import units def open_datasets(filepath_template, **kwargs): """Open collection of datasets from grib file defined by template and args.""" return cfgrib.open_datasets( filepath_template.format(**kwargs), backend_kwargs={'indexpath': ''} ) def s...
lib/grib.py
import re import cfgrib from metpy.units import units def open_datasets(filepath_template, **kwargs): """Open collection of datasets from grib file defined by template and args.""" return cfgrib.open_datasets( filepath_template.format(**kwargs), backend_kwargs={'indexpath': ''} ) def s...
0.68658
0.354154
import sqlite3 def add_data(atr, connection): with connection: c = connection.cursor() c.execute("INSERT INTO tempos_atr_2019 (IDAtracacao," "TEsperaAtracacao," "TEsperaInicioOp," "TOperacao," "TEsperaDesatracacao," ...
Main/database/connectors.py
import sqlite3 def add_data(atr, connection): with connection: c = connection.cursor() c.execute("INSERT INTO tempos_atr_2019 (IDAtracacao," "TEsperaAtracacao," "TEsperaInicioOp," "TOperacao," "TEsperaDesatracacao," ...
0.134861
0.237255
import warnings import argparse import json from pandas.io.json import json_normalize from categories import Categories import sys from nltk.corpus import wordnet as wn import pandas as pd from tqdm import tqdm import os import re warnings.filterwarnings( "ignore", message="numpy.dtype size changed, may indic...
match_synsets_to_categories.py
import warnings import argparse import json from pandas.io.json import json_normalize from categories import Categories import sys from nltk.corpus import wordnet as wn import pandas as pd from tqdm import tqdm import os import re warnings.filterwarnings( "ignore", message="numpy.dtype size changed, may indic...
0.448185
0.299176
import shutil import time SECONDS_IN_HOUR = 3600 SECONDS_IN_MINUTE = 60 SHORTEST_AMOUNT_OF_TIME = 0 class InvalidTimeParameterError(Exception): pass def _get_delay_time(session): """ Helper function to extract the delay time from the session. :param session: Pytest session object. :return: Ret...
src/pytest_stress/pytest_stress.py
import shutil import time SECONDS_IN_HOUR = 3600 SECONDS_IN_MINUTE = 60 SHORTEST_AMOUNT_OF_TIME = 0 class InvalidTimeParameterError(Exception): pass def _get_delay_time(session): """ Helper function to extract the delay time from the session. :param session: Pytest session object. :return: Ret...
0.730578
0.372819
from sqlalchemy import * # noqa def test_first(dbs, TestModelA): dbs.add(TestModelA(title="Lorem")) dbs.add(TestModelA(title="Ipsum")) dbs.add(TestModelA(title="Sit")) dbs.commit() obj = dbs.first(TestModelA) assert obj.title == "Lorem" def test_create(dbs, TestModelA): dbs.create(Test...
tests/test_session.py
from sqlalchemy import * # noqa def test_first(dbs, TestModelA): dbs.add(TestModelA(title="Lorem")) dbs.add(TestModelA(title="Ipsum")) dbs.add(TestModelA(title="Sit")) dbs.commit() obj = dbs.first(TestModelA) assert obj.title == "Lorem" def test_create(dbs, TestModelA): dbs.create(Test...
0.503906
0.543651
import json class row: def __init__( self=None, id=None, contract=None, name=None, addr=None, geo=None, bank=None, bonus=None, status=None, update=None, conn=None, overflow=None, shape=None, totalst=None, mainst=None, overflowst=None ): self.id = id; self.contract = contract; self.name = name ...
execute/support/station.py
import json class row: def __init__( self=None, id=None, contract=None, name=None, addr=None, geo=None, bank=None, bonus=None, status=None, update=None, conn=None, overflow=None, shape=None, totalst=None, mainst=None, overflowst=None ): self.id = id; self.contract = contract; self.name = name ...
0.463201
0.089614
import asyncio import contextlib import itertools class ExpiringDict: def __init__(self, loop, seconds): self._loop = loop self._seconds = seconds self._store = {} def __getitem__(self, key): return self._store[key][0] def __setitem__(self, key, value): def delet...
aioftps3/server_utils.py
import asyncio import contextlib import itertools class ExpiringDict: def __init__(self, loop, seconds): self._loop = loop self._seconds = seconds self._store = {} def __getitem__(self, key): return self._store[key][0] def __setitem__(self, key, value): def delet...
0.601008
0.241512
try: from urllib2 import urlopen from urllib2 import URLError, HTTPError except ImportError: from urllib.request import urlopen from urllib.error import URLError, HTTPError import json import socket import codecs from ..tq_common_lib import fixurl, decode_utf_8, get_variable identifier="openthesaurus...
autoload/thesaurus_query/backends/openthesaurus_de_lookup.py
try: from urllib2 import urlopen from urllib2 import URLError, HTTPError except ImportError: from urllib.request import urlopen from urllib.error import URLError, HTTPError import json import socket import codecs from ..tq_common_lib import fixurl, decode_utf_8, get_variable identifier="openthesaurus...
0.347426
0.185467
import math import os import sys from typing import List, Callable import numpy as np class TrustRegion: UNIFORM_MIN = 10 UNIFORM_MAX = 1000 DELTA_0 = 1 DELTA_MAX = 10000 EPSILON = 10 ** -8 TOLERANCE = 10 ** -12 def __init__(self, n: int): """ :param n: Dimension of ...
hw/hw03/src/trust_region.py
import math import os import sys from typing import List, Callable import numpy as np class TrustRegion: UNIFORM_MIN = 10 UNIFORM_MAX = 1000 DELTA_0 = 1 DELTA_MAX = 10000 EPSILON = 10 ** -8 TOLERANCE = 10 ** -12 def __init__(self, n: int): """ :param n: Dimension of ...
0.715623
0.662169
from datetime import datetime, timedelta from logging import getLogger # Third party library # Local library from warehouse.server.config.globals import M def decode_cookie(request): my_cookie = request.get_secure_cookie("session", max_age_days=1) try: curr_uuid = my_cookie.decode("ascii") except ...
warehouse/server/util.py
from datetime import datetime, timedelta from logging import getLogger # Third party library # Local library from warehouse.server.config.globals import M def decode_cookie(request): my_cookie = request.get_secure_cookie("session", max_age_days=1) try: curr_uuid = my_cookie.decode("ascii") except ...
0.695855
0.182098
import abc import gym import logging from typing import Any, Dict, List, Tuple from ray.tune.registry import RLLIB_CONNECTOR, _global_registry from ray.rllib.policy.policy import Policy from ray.rllib.policy.view_requirement import ViewRequirement from ray.rllib.utils.annotations import DeveloperAPI from ray.rllib.uti...
rllib/connectors/connector.py
import abc import gym import logging from typing import Any, Dict, List, Tuple from ray.tune.registry import RLLIB_CONNECTOR, _global_registry from ray.rllib.policy.policy import Policy from ray.rllib.policy.view_requirement import ViewRequirement from ray.rllib.utils.annotations import DeveloperAPI from ray.rllib.uti...
0.84941
0.354084
import json import os import pandas as pd from interfaces.fileimport import MultiFileDataImporter class DatasetDescription: """ Manages a set of files containing data that is be split up into files containing different time periods. Such a dataset is described in a JSON description file which is loaded ...
cmscalibration/importers/dataset_import.py
import json import os import pandas as pd from interfaces.fileimport import MultiFileDataImporter class DatasetDescription: """ Manages a set of files containing data that is be split up into files containing different time periods. Such a dataset is described in a JSON description file which is loaded ...
0.814533
0.347039
from __future__ import unicode_literals from django.apps import AppConfig from django.contrib.auth import get_user_model from django.db.models import signals from django_fsm import signals as fsm_signals from nodeconductor.core.models import SshPublicKey from nodeconductor.quotas import handlers as quotas_handlers fr...
nodeconductor/structure/apps.py
from __future__ import unicode_literals from django.apps import AppConfig from django.contrib.auth import get_user_model from django.db.models import signals from django_fsm import signals as fsm_signals from nodeconductor.core.models import SshPublicKey from nodeconductor.quotas import handlers as quotas_handlers fr...
0.589953
0.067026
import time import Command import ResetNone class ResetNonConst(ResetNone.ResetNone): def __init__(self): self.is_move_detected = False self.is_target_speed_detected = False self.is_constant = False self.target_speed = 0.0 self.previous_speed = 0.0 self.move_step_q...
ResetNonConst.py
import time import Command import ResetNone class ResetNonConst(ResetNone.ResetNone): def __init__(self): self.is_move_detected = False self.is_target_speed_detected = False self.is_constant = False self.target_speed = 0.0 self.previous_speed = 0.0 self.move_step_q...
0.243552
0.09451
import json import pickle import logging from os import path, makedirs from datetime import datetime timeformat = '%Y-%m-%d %H.%M.%S %z' def time_to_str(time): if isinstance(time, str): return time return time.strftime(timeformat) def str_to_time(time): if isinstance(time, str): return date...
util.py
import json import pickle import logging from os import path, makedirs from datetime import datetime timeformat = '%Y-%m-%d %H.%M.%S %z' def time_to_str(time): if isinstance(time, str): return time return time.strftime(timeformat) def str_to_time(time): if isinstance(time, str): return date...
0.20142
0.084078
import numpy as np import matplotlib as mpl import matplotlib.cm as cm import matplotlib.pyplot as plt def logistic(z: np.ndarray, a: float, b: float) -> np.ndarray: """ Compute logistic function Inputs: a: exponential parameter b: exponential prefactor z: numpy array; domain ...
static/epa1316-2020/labs/lab-06/hw-solutions/exercise1.py
import numpy as np import matplotlib as mpl import matplotlib.cm as cm import matplotlib.pyplot as plt def logistic(z: np.ndarray, a: float, b: float) -> np.ndarray: """ Compute logistic function Inputs: a: exponential parameter b: exponential prefactor z: numpy array; domain ...
0.825132
0.760673
import argparse import pathlib import gym import numpy as np import torch as th import matplotlib.pyplot as plt from tqdm import tqdm from stable_baselines3 import SAC, PPO from ail.agents import ALGO from ail.common.utils import set_random_seed from ail.common.env_utils import maybe_make_env try: from icecream ...
scripts/evaluate_expert.py
import argparse import pathlib import gym import numpy as np import torch as th import matplotlib.pyplot as plt from tqdm import tqdm from stable_baselines3 import SAC, PPO from ail.agents import ALGO from ail.common.utils import set_random_seed from ail.common.env_utils import maybe_make_env try: from icecream ...
0.537527
0.25448
import json import activity from boto.s3.connection import S3Connection from activity_ConvertJATS import activity_ConvertJATS as ConvertJATS """ ScheduleDownstream.py activity """ class activity_ScheduleDownstream(activity.activity): def __init__(self, settings, logger, conn=None, token=None, activity_task=Non...
activity/activity_ScheduleDownstream.py
import json import activity from boto.s3.connection import S3Connection from activity_ConvertJATS import activity_ConvertJATS as ConvertJATS """ ScheduleDownstream.py activity """ class activity_ScheduleDownstream(activity.activity): def __init__(self, settings, logger, conn=None, token=None, activity_task=Non...
0.339171
0.089097
from scipy.spatial.distance import pdist class DBSCAN(object): def __init__(self, eps, min_neighbors, metric='euclidean'): """ A re-creation of the DBSCAN algorithm, using only scipy as a dependency. :param eps: Epsilon, aka the distance between two points to be considered 'neighbors'. ...
DBSCAN/DBSCAN.py
from scipy.spatial.distance import pdist class DBSCAN(object): def __init__(self, eps, min_neighbors, metric='euclidean'): """ A re-creation of the DBSCAN algorithm, using only scipy as a dependency. :param eps: Epsilon, aka the distance between two points to be considered 'neighbors'. ...
0.93954
0.795618
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Models and helper classes for style-controlled generation. """ import random import numpy as np import torch from torch import nn as nn f...
projects/style_gen/modules.py
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ Models and helper classes for style-controlled generation. """ import random import numpy as np import torch from torch import nn as nn f...
0.878242
0.299553
import os import imp import re import codecs protocol = imp.load_source('protocol', '../protocol.py') nxDSCLog = imp.load_source('nxDSCLog', '../nxDSCLog.py') LG = nxDSCLog.DSCLog rsyslog_conf_path = '/etc/rsyslog.conf' rsyslog_inc_conf_path = '/etc/rsyslog.d/95-omsagent.conf' syslog_ng_conf_path = '/etc/syslog-ng/s...
Providers/Scripts/2.6x-2.7x/Scripts/nxOMSSyslog.py
import os import imp import re import codecs protocol = imp.load_source('protocol', '../protocol.py') nxDSCLog = imp.load_source('nxDSCLog', '../nxDSCLog.py') LG = nxDSCLog.DSCLog rsyslog_conf_path = '/etc/rsyslog.conf' rsyslog_inc_conf_path = '/etc/rsyslog.d/95-omsagent.conf' syslog_ng_conf_path = '/etc/syslog-ng/s...
0.150778
0.0538
from __future__ import annotations import numpy as np import pandas as pd from numpy.typing import DTypeLike, NDArray from .base import Generator class Category(Generator): """Recommended for string data of few different values. Can be used to replicate, e.g. category or status. Draws values based on th...
duper/generator/category.py
from __future__ import annotations import numpy as np import pandas as pd from numpy.typing import DTypeLike, NDArray from .base import Generator class Category(Generator): """Recommended for string data of few different values. Can be used to replicate, e.g. category or status. Draws values based on th...
0.955037
0.518241
from jinja2 import nodes, TemplateSyntaxError, Environment from jinja2.ext import Extension from jinja2.lexer import Token def fail_template(stream, message): raise TemplateSyntaxError( message, stream.current.lineno, stream.name, stream.filename ) class SqlvmExtension(Extension): """The SqlvmEx...
extension.py
from jinja2 import nodes, TemplateSyntaxError, Environment from jinja2.ext import Extension from jinja2.lexer import Token def fail_template(stream, message): raise TemplateSyntaxError( message, stream.current.lineno, stream.name, stream.filename ) class SqlvmExtension(Extension): """The SqlvmEx...
0.801819
0.341061
import os from datetime import datetime from discord import Embed from discord_slash.utils.manage_commands import create_option, SlashCommandOptionType from data import get_modcases_by_user_and_guild from helpers import get_prefix from .infrastructure import record_usage, CommandDefinition async def create_embed_fo...
discordbot/src/commands/cases.py
import os from datetime import datetime from discord import Embed from discord_slash.utils.manage_commands import create_option, SlashCommandOptionType from data import get_modcases_by_user_and_guild from helpers import get_prefix from .infrastructure import record_usage, CommandDefinition async def create_embed_fo...
0.192919
0.09611
import sys import os from ctypes import Structure, c_int32, c_int, c_char_p,\ create_string_buffer, memmove,\ c_void_p, POINTER, byref, c_double, cdll from ctypes.util import find_library from kivy.core.image import ImageData from kivy.graphics.texture import Texture current_dir =...
kivyic/working/pdfwidget.py
import sys import os from ctypes import Structure, c_int32, c_int, c_char_p,\ create_string_buffer, memmove,\ c_void_p, POINTER, byref, c_double, cdll from ctypes.util import find_library from kivy.core.image import ImageData from kivy.graphics.texture import Texture current_dir =...
0.313735
0.114121
import unittest from hamcrest.library.text.isequal_ignoring_whitespace import * from hamcrest_unit_test.matcher_test import MatcherTest __author__ = "<NAME>" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" matcher = equal_to_ignoring_whitespace("Hello World how\n are we? ") cl...
tests/hamcrest_unit_test/text/isequal_ignoring_whitespace_test.py
import unittest from hamcrest.library.text.isequal_ignoring_whitespace import * from hamcrest_unit_test.matcher_test import MatcherTest __author__ = "<NAME>" __copyright__ = "Copyright 2011 hamcrest.org" __license__ = "BSD, see License.txt" matcher = equal_to_ignoring_whitespace("Hello World how\n are we? ") cl...
0.603231
0.619586
"""Tests for accela_records.py""" import os import json import pytest from falcon import testing import service.microservice CLIENT_HEADERS = { "ACCESS_KEY": "1234567" } @pytest.fixture() def client(): """ client fixture """ CLIENT_HEADERS['ACCESS_KEY'] = os.environ.get('ACCESS_KEY') CLIENT_HEADERS['X...
tests/test_accela_records_update.py
"""Tests for accela_records.py""" import os import json import pytest from falcon import testing import service.microservice CLIENT_HEADERS = { "ACCESS_KEY": "1234567" } @pytest.fixture() def client(): """ client fixture """ CLIENT_HEADERS['ACCESS_KEY'] = os.environ.get('ACCESS_KEY') CLIENT_HEADERS['X...
0.392919
0.232964
import time from multiprocessing import Queue, Process, cpu_count from typing import Iterator def pick_student(stu_queue: Queue, dorm: str, num_workers: int) -> Iterator[str]: print("pick_student: started") picked_num = 0 with open(dorm, "rt", encoding="utf8") as fin: for student in fin: ...
m4_multi_process_workers.py
import time from multiprocessing import Queue, Process, cpu_count from typing import Iterator def pick_student(stu_queue: Queue, dorm: str, num_workers: int) -> Iterator[str]: print("pick_student: started") picked_num = 0 with open(dorm, "rt", encoding="utf8") as fin: for student in fin: ...
0.387343
0.151938
import os from functools import partial from typing import NamedTuple from datetime import datetime os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.7" import jax import optax import haiku as hk import jax.numpy as jnp from tqdm import tqdm # fmt: off import tensorflow as tf tf.config.set_visible_devices([], "GPU")...
baseline.py
import os from functools import partial from typing import NamedTuple from datetime import datetime os.environ["XLA_PYTHON_CLIENT_MEM_FRACTION"] = "0.7" import jax import optax import haiku as hk import jax.numpy as jnp from tqdm import tqdm # fmt: off import tensorflow as tf tf.config.set_visible_devices([], "GPU")...
0.777427
0.270327
import subprocess import sys import json import requests import json import config from tests.utils import * # DEFAULTS request_timeout = config.http_request_timeout useragent = config.useragent css_review_group_errors = config.css_review_group_errors review_show_improvements_only = config.review_show_improvements_onl...
tests/w3c_base.py
import subprocess import sys import json import requests import json import config from tests.utils import * # DEFAULTS request_timeout = config.http_request_timeout useragent = config.useragent css_review_group_errors = config.css_review_group_errors review_show_improvements_only = config.review_show_improvements_onl...
0.076987
0.095265
import argparse import json import os import subprocess import tempfile import zipfile from pathlib import Path import cog import kaldiio import numpy as np import pyworld as pw import resampy import soundfile as sf import torch from model_decoder import Decoder_ac from model_encoder import Encoder, Encoder_lf0 from ...
predict.py
import argparse import json import os import subprocess import tempfile import zipfile from pathlib import Path import cog import kaldiio import numpy as np import pyworld as pw import resampy import soundfile as sf import torch from model_decoder import Decoder_ac from model_encoder import Encoder, Encoder_lf0 from ...
0.501709
0.210949
import pandas as pd from django.db.models import F from flaim.database import models class ReportData: def __init__(self): self.df = self._get_data() def _get_data(self): products = models.Product nutrition_facts = models.NutritionFacts df1 = pd.DataFrame(list(products.object...
flaim/reports/data.py
import pandas as pd from django.db.models import F from flaim.database import models class ReportData: def __init__(self): self.df = self._get_data() def _get_data(self): products = models.Product nutrition_facts = models.NutritionFacts df1 = pd.DataFrame(list(products.object...
0.366023
0.112405
import sqlite3 import glob import sys import shutil # Set documentation directory and docset name if len(sys.argv) == 3: docname = sys.argv[1] docsdir = sys.argv[2] else: print("You must enter exactly two arguments: name of the docset to create and relative or absolute path to the directory where ROBODoc ...
robodocset.py
import sqlite3 import glob import sys import shutil # Set documentation directory and docset name if len(sys.argv) == 3: docname = sys.argv[1] docsdir = sys.argv[2] else: print("You must enter exactly two arguments: name of the docset to create and relative or absolute path to the directory where ROBODoc ...
0.145813
0.156878
import pathlib import subprocess import time import os import sys import argparse import logging import threading from services import registry logging.basicConfig(level=10, format="%(asctime)s - [%(levelname)8s] - %(name)s - %(message)s") log = logging.getLogger("run_basic_service") def main(): parser = argpar...
Services/JSON-RPC/Basic_Template/run_basic_services.py
import pathlib import subprocess import time import os import sys import argparse import logging import threading from services import registry logging.basicConfig(level=10, format="%(asctime)s - [%(levelname)8s] - %(name)s - %(message)s") log = logging.getLogger("run_basic_service") def main(): parser = argpar...
0.259732
0.064594
import logging import time import ccxt from dynaconf import settings from liqui import Liqui from binance.client import Client from strategies.analyser import Analyser logger = logging.getLogger(__name__) class Order: def __init__(self, market, id, type, start_amount, remaining_amount, price, status): se...
strategies/trader.py
import logging import time import ccxt from dynaconf import settings from liqui import Liqui from binance.client import Client from strategies.analyser import Analyser logger = logging.getLogger(__name__) class Order: def __init__(self, market, id, type, start_amount, remaining_amount, price, status): se...
0.539954
0.16944
import json import xml.etree.ElementTree as ET from cafe.engine.models.base import \ AutoMarshallingModel, AutoMarshallingListModel from cloudcafe.networking.lbaas.common.constants import Constants from cloudcafe.networking.lbaas.lbaas_api.session_persistence.response \ import SessionPersistence class Pools(...
cloudcafe/networking/lbaas/lbaas_api/pool/response.py
import json import xml.etree.ElementTree as ET from cafe.engine.models.base import \ AutoMarshallingModel, AutoMarshallingListModel from cloudcafe.networking.lbaas.common.constants import Constants from cloudcafe.networking.lbaas.lbaas_api.session_persistence.response \ import SessionPersistence class Pools(...
0.603581
0.138666
from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class TransferRecord(models.Model): original_type = models.ForeignKey( ContentType, related_name='transfer', on_delete=models.DO_NOTHING) original_id...
Seeder/legacy_db/models.py
from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType class TransferRecord(models.Model): original_type = models.ForeignKey( ContentType, related_name='transfer', on_delete=models.DO_NOTHING) original_id...
0.623606
0.213439
from numpy import conjugate, transpose, dot, sqrt, array, repeat from WaveBlocksND.Observables import Observables __all__ = ["ObservablesLCWP"] class ObservablesLCWP(Observables): r"""This class implements observable computation for linear combinations :math:`\Upsilon` of wavepackets :math:`\Psi_j`. There a...
WaveBlocksND/ObservablesLCWP.py
from numpy import conjugate, transpose, dot, sqrt, array, repeat from WaveBlocksND.Observables import Observables __all__ = ["ObservablesLCWP"] class ObservablesLCWP(Observables): r"""This class implements observable computation for linear combinations :math:`\Upsilon` of wavepackets :math:`\Psi_j`. There a...
0.928591
0.757077
import signal import logging import os import shutil import csv import json import datetime import pickle import gensim from django.core.management.base import BaseCommand, CommandError from django.conf import settings from rdflib.namespace import split_uri from os import listdir from os.path import isfile, join, sp...
api/management/commands/traindl2vec.py
import signal import logging import os import shutil import csv import json import datetime import pickle import gensim from django.core.management.base import BaseCommand, CommandError from django.conf import settings from rdflib.namespace import split_uri from os import listdir from os.path import isfile, join, sp...
0.260295
0.08472
import socket import struct import codecs,sys import threading import random import time import os ##===##=== LOGIN password ="<PASSWORD>" for i in range(3): pwd = input("[•] Password : ") j=3 if(pwd==password): time.sleep(5) print("[•] Please Wait!!! ") break ...
B-TEAM.py
import socket import struct import codecs,sys import threading import random import time import os ##===##=== LOGIN password ="<PASSWORD>" for i in range(3): pwd = input("[•] Password : ") j=3 if(pwd==password): time.sleep(5) print("[•] Please Wait!!! ") break ...
0.050144
0.078289
from logging import getLogger from pathlib import Path from typing import Optional, Set from recording_script_generator.app.io import * from recording_script_generator.core.exporting import (SortingMode, df_to_consecutive_txt, ...
src/recording_script_generator/app/exporting.py
from logging import getLogger from pathlib import Path from typing import Optional, Set from recording_script_generator.app.io import * from recording_script_generator.core.exporting import (SortingMode, df_to_consecutive_txt, ...
0.755096
0.090173
import asyncio import logging import pytz from tabulate import tabulate from libs.ac_libs import AcManager, help_str logger = logging.getLogger('gradiusbot') logger.info("[Public Plugin] <animal_crossing.py> Provides tools for the game Animal Crossing.") DISPLAY_CHAR_LIMIT = 32 ac_manager = AcManager() @asyncio.co...
public_plugins/animal_crossing/animal_crossing.py
import asyncio import logging import pytz from tabulate import tabulate from libs.ac_libs import AcManager, help_str logger = logging.getLogger('gradiusbot') logger.info("[Public Plugin] <animal_crossing.py> Provides tools for the game Animal Crossing.") DISPLAY_CHAR_LIMIT = 32 ac_manager = AcManager() @asyncio.co...
0.467089
0.464962
from itertools import combinations import numpy as np from . strategy import Strategy class LocalOptimisation(Strategy): """Implements the local optimisation algorithm using the Strategy interface """ def _sample(self, input_sample, num_samples, num_params, k_choices, num_groups=None): ...
src/SALib/sample/morris/local.py
from itertools import combinations import numpy as np from . strategy import Strategy class LocalOptimisation(Strategy): """Implements the local optimisation algorithm using the Strategy interface """ def _sample(self, input_sample, num_samples, num_params, k_choices, num_groups=None): ...
0.837885
0.645427
from __future__ import absolute_import from __future__ import print_function from __future__ import division import warnings from tensorforce import TensorForceError from tensorforce.agents import MemoryAgent from tensorforce.models import QModel class DDQNAgent(MemoryAgent): """ Double DQN Agent based on [...
tensorforce/agents/ddqn_agent.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division import warnings from tensorforce import TensorForceError from tensorforce.agents import MemoryAgent from tensorforce.models import QModel class DDQNAgent(MemoryAgent): """ Double DQN Agent based on [...
0.835484
0.233008
""" Fast digest handlers """ from datetime import datetime import itertools from werkzeug import exceptions from google.appengine.api import mail from ggrc import db from ggrc import rbac from ggrc import settings from ggrc.notifications import common from ggrc.notifications import data_handlers from ggrc.notifica...
src/ggrc/notifications/fast_digest.py
""" Fast digest handlers """ from datetime import datetime import itertools from werkzeug import exceptions from google.appengine.api import mail from ggrc import db from ggrc import rbac from ggrc import settings from ggrc.notifications import common from ggrc.notifications import data_handlers from ggrc.notifica...
0.489259
0.107437
from osmnx import graph_from_bbox, graph_to_gdfs from osmnx.distance import nearest_nodes, add_edge_lengths from osmnx.utils_graph import remove_isolated_nodes from geopandas import GeoDataFrame from pandas import concat from networkx import single_source_dijkstra_path_length from .mask import Base from multiprocessi...
maskmypy/street.py
from osmnx import graph_from_bbox, graph_to_gdfs from osmnx.distance import nearest_nodes, add_edge_lengths from osmnx.utils_graph import remove_isolated_nodes from geopandas import GeoDataFrame from pandas import concat from networkx import single_source_dijkstra_path_length from .mask import Base from multiprocessi...
0.492676
0.335841
import sys sys.path.append("../../Cleaner") import sqlite3 import cleaner import logging, threading class Sqlite3Manger: def __init__(self, sqlite_file, commit_period=50): self.conn = sqlite3.connect(sqlite_file) self.logger = logging.getLogger(__name__) self.lock = threading.Lock() ...
Scraper/src/sql_db_manager.py
import sys sys.path.append("../../Cleaner") import sqlite3 import cleaner import logging, threading class Sqlite3Manger: def __init__(self, sqlite_file, commit_period=50): self.conn = sqlite3.connect(sqlite_file) self.logger = logging.getLogger(__name__) self.lock = threading.Lock() ...
0.248899
0.118768
import collections from typing import Dict, List, Set INPUT_FILE = 'data/day_07.txt' def bags_colors_contained(contained: List[str], color: str) -> Set[str]: """Determine bags colors that can contain a bag of a color.""" bags = set() if color in contained: for contained_bag in contained[color]: ...
advent_of_code/2020/day_07.py
import collections from typing import Dict, List, Set INPUT_FILE = 'data/day_07.txt' def bags_colors_contained(contained: List[str], color: str) -> Set[str]: """Determine bags colors that can contain a bag of a color.""" bags = set() if color in contained: for contained_bag in contained[color]: ...
0.769946
0.333883
from copy import deepcopy from functools import partial from slm_lab.agent import net, memory from slm_lab.agent.algorithm import math_util, policy_util from slm_lab.agent.algorithm.actor_critic import ActorCritic from slm_lab.agent.net import net_util from slm_lab.lib import logger, util from slm_lab.lib.decorator imp...
slm_lab/agent/algorithm/sil.py
from copy import deepcopy from functools import partial from slm_lab.agent import net, memory from slm_lab.agent.algorithm import math_util, policy_util from slm_lab.agent.algorithm.actor_critic import ActorCritic from slm_lab.agent.net import net_util from slm_lab.lib import logger, util from slm_lab.lib.decorator imp...
0.852844
0.226302
from __future__ import absolute_import __author__ = 'katharine' import socket import struct import websocket from .. import BaseTransport, MessageTarget, MessageTargetWatch from .protocol import WebSocketRelayToWatch, WebSocketRelayFromWatch, endpoints, from_watch from libpebble2.exceptions import ConnectionError, P...
libpebble2/communication/transports/websocket/__init__.py
from __future__ import absolute_import __author__ = 'katharine' import socket import struct import websocket from .. import BaseTransport, MessageTarget, MessageTargetWatch from .protocol import WebSocketRelayToWatch, WebSocketRelayFromWatch, endpoints, from_watch from libpebble2.exceptions import ConnectionError, P...
0.662032
0.10961
from unittest import mock import pytest from snakeoil.process import CommandNotFound from pkgcore.sync import base, cvs class TestCVSSyncer(object): @pytest.fixture(autouse=True) def _setup(self, tmp_path): self.repo_path = tmp_path / 'repo' def test_uri_parse(self): # external binary...
tests/module/sync/test_cvs.py
from unittest import mock import pytest from snakeoil.process import CommandNotFound from pkgcore.sync import base, cvs class TestCVSSyncer(object): @pytest.fixture(autouse=True) def _setup(self, tmp_path): self.repo_path = tmp_path / 'repo' def test_uri_parse(self): # external binary...
0.494141
0.36659
import re import pickle from collections import defaultdict import discord import ladder_manager_base as base from ladder_manager_base import DirectedMessage from ladder_manager_base import Team class InvalidUserInput(Exception): """Called when the user input is invalid.""" pass class Challe...
ladder_manager_challenges.py
import re import pickle from collections import defaultdict import discord import ladder_manager_base as base from ladder_manager_base import DirectedMessage from ladder_manager_base import Team class InvalidUserInput(Exception): """Called when the user input is invalid.""" pass class Challe...
0.67694
0.162746
from typing import Optional, Type from sqlalchemy.orm import Session, Query, exc from sqlalchemy.ext.declarative import DeclarativeMeta from entity_framework.repository import EntityType, IdentityType from entity_framework.storages.sqlalchemy.populating_aggregates.visitor import PopulatingAggregateVisitor from entity...
entity_framework/storages/sqlalchemy/__init__.py
from typing import Optional, Type from sqlalchemy.orm import Session, Query, exc from sqlalchemy.ext.declarative import DeclarativeMeta from entity_framework.repository import EntityType, IdentityType from entity_framework.storages.sqlalchemy.populating_aggregates.visitor import PopulatingAggregateVisitor from entity...
0.690663
0.302262
# In[656]: from pypinyin import pinyin, lazy_pinyin, Style import sys import math import itertools import pickle import os ''' @liushaohua 本更改仅限个人使用,仅仅使用编码方式,对拼音进行一个统一编码 ''' # In[657]: work_dir = os.path.abspath(__file__) indexOfLastSlash = work_dir.rfind("/") work_dir = work_dir[0:indexOfLastSlash]+"/"...
code/dimsim/build/lib/dimsim/dimsim.py
# In[656]: from pypinyin import pinyin, lazy_pinyin, Style import sys import math import itertools import pickle import os ''' @liushaohua 本更改仅限个人使用,仅仅使用编码方式,对拼音进行一个统一编码 ''' # In[657]: work_dir = os.path.abspath(__file__) indexOfLastSlash = work_dir.rfind("/") work_dir = work_dir[0:indexOfLastSlash]+"/"...
0.163713
0.234549
from base64 import b64encode from enum import IntEnum from typing import Tuple import requests from iolite_client.exceptions import IOLiteError class Temperature: BASE_TEMP = 14 MAX_TEMP = 30 @staticmethod def within_range(temperature: float) -> bool: return Temperature.BASE_TEMP <= tempera...
iolite_client/heating_scheduler.py
from base64 import b64encode from enum import IntEnum from typing import Tuple import requests from iolite_client.exceptions import IOLiteError class Temperature: BASE_TEMP = 14 MAX_TEMP = 30 @staticmethod def within_range(temperature: float) -> bool: return Temperature.BASE_TEMP <= tempera...
0.943001
0.33062
from __future__ import annotations from abc import ABC, abstractmethod from typing import Callable, Generic, TypeVar import gpflow import tensorflow as tf from typing_extensions import Protocol, runtime_checkable from ..data import Dataset from ..types import TensorType from ..utils import DEFAULTS ProbabilisticMo...
trieste/models/interfaces.py
from __future__ import annotations from abc import ABC, abstractmethod from typing import Callable, Generic, TypeVar import gpflow import tensorflow as tf from typing_extensions import Protocol, runtime_checkable from ..data import Dataset from ..types import TensorType from ..utils import DEFAULTS ProbabilisticMo...
0.972402
0.718594