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 torch import tqdm import numpy as np from models import build_model_and_tokenizer from dataset.tianchi_2020_dataset import get_test_dataloader def _batch_trans(batch, device): batch = tuple(t.to(device) for t in batch) batch_data ={ 'input_ids': batch[0], 'attention_mask': batch[1], ...
tools/infer.py
import torch import tqdm import numpy as np from models import build_model_and_tokenizer from dataset.tianchi_2020_dataset import get_test_dataloader def _batch_trans(batch, device): batch = tuple(t.to(device) for t in batch) batch_data ={ 'input_ids': batch[0], 'attention_mask': batch[1], ...
0.498047
0.248762
import logging from typing import Any, List, Optional, Union from eth_typing import URI from web3 import HTTPProvider from web3._utils.rpc_abi import RPC from web3.middleware.geth_poa import geth_poa_cleanup from web3.types import RPCEndpoint, RPCResponse logger = logging.getLogger(__name__) class NoActiveProviderE...
web3_multi_provider/multi_http_provider.py
import logging from typing import Any, List, Optional, Union from eth_typing import URI from web3 import HTTPProvider from web3._utils.rpc_abi import RPC from web3.middleware.geth_poa import geth_poa_cleanup from web3.types import RPCEndpoint, RPCResponse logger = logging.getLogger(__name__) class NoActiveProviderE...
0.769124
0.126623
__author__ = 'luckydonald' from . import encoding from .utils import escape # validate_input from .exceptions import ArgumentParseError from os import path # file checking. import logging logger = logging.getLogger(__name__) class Argument(object): def __init__(self, name, optional=False, multible=False): self.n...
pytg2/argument_types.py
__author__ = 'luckydonald' from . import encoding from .utils import escape # validate_input from .exceptions import ArgumentParseError from os import path # file checking. import logging logger = logging.getLogger(__name__) class Argument(object): def __init__(self, name, optional=False, multible=False): self.n...
0.401453
0.258081
import os import importlib import argparse COLLATE_FN_REGISTRY = {} def register_collate_fn(name): def register_collate_fn_method(f): if name in COLLATE_FN_REGISTRY: raise ValueError( "Cannot register duplicate collate function ({})".format(name) ) COLLATE...
data/collate_fns/__init__.py
import os import importlib import argparse COLLATE_FN_REGISTRY = {} def register_collate_fn(name): def register_collate_fn_method(f): if name in COLLATE_FN_REGISTRY: raise ValueError( "Cannot register duplicate collate function ({})".format(name) ) COLLATE...
0.374219
0.101679
import re from pywriter.html.html_file import HtmlFile from pywriter.model.splitter import Splitter class HtmlProof(HtmlFile): """HTML proof reading file representation. Import a manuscript with visibly tagged chapters and scenes. """ DESCRIPTION = 'Tagged manuscript for proofing' SUFF...
src/pywriter/html/html_proof.py
import re from pywriter.html.html_file import HtmlFile from pywriter.model.splitter import Splitter class HtmlProof(HtmlFile): """HTML proof reading file representation. Import a manuscript with visibly tagged chapters and scenes. """ DESCRIPTION = 'Tagged manuscript for proofing' SUFF...
0.469277
0.155142
from sqlalchemy import orm from infosystem.database import db from infosystem.common.subsystem import entity class TimelineEvent(entity.Entity, db.Model): LIMIT_SEARCH = 30 attributes = ['domain_id', 'event_at', 'event_by', 'lat', 'lon', 'description', 'entity', 'entity_id'] attributes...
infosystem/subsystem/timeline_event/resource.py
from sqlalchemy import orm from infosystem.database import db from infosystem.common.subsystem import entity class TimelineEvent(entity.Entity, db.Model): LIMIT_SEARCH = 30 attributes = ['domain_id', 'event_at', 'event_by', 'lat', 'lon', 'description', 'entity', 'entity_id'] attributes...
0.58818
0.057493
import os import re from typing import Optional, Sequence from magmap.io import export_regions from magmap.settings import config from magmap.stats import vols _logger = config.logger.getChild(__name__) def build_labels_diff_images(paths: Optional[Sequence[str]] = None): """Build labels difference images for g...
magmap/atlas/reg_tasks.py
import os import re from typing import Optional, Sequence from magmap.io import export_regions from magmap.settings import config from magmap.stats import vols _logger = config.logger.getChild(__name__) def build_labels_diff_images(paths: Optional[Sequence[str]] = None): """Build labels difference images for g...
0.897746
0.36108
from __future__ import absolute_import, division from functools import partial from python_lib.shell_command_helper import ShellCommandHelper from utils import get_logger class OvsHelper: """Class to build OVS bridges, VxLANs and other network components""" DEFAULT_VXLAN_PORT = 4789 VXLAN_CMD_FMT = 'ip ...
device_coupler/ovs_helper.py
from __future__ import absolute_import, division from functools import partial from python_lib.shell_command_helper import ShellCommandHelper from utils import get_logger class OvsHelper: """Class to build OVS bridges, VxLANs and other network components""" DEFAULT_VXLAN_PORT = 4789 VXLAN_CMD_FMT = 'ip ...
0.69233
0.093595
from math import radians import bpy import os from mathutils import Vector, Matrix def get_max(ob): mx = Vector((-1000., -1000., -1000.)) for vx in ob.data.vertices: p = ob.matrix_world * vx.co mx.x = max(mx.x, p.x) mx.y = max(mx.y, p.y) mx.z = max(mx.z, p.z) return m...
imapper/blender/replace_objects_w_models.py
from math import radians import bpy import os from mathutils import Vector, Matrix def get_max(ob): mx = Vector((-1000., -1000., -1000.)) for vx in ob.data.vertices: p = ob.matrix_world * vx.co mx.x = max(mx.x, p.x) mx.y = max(mx.y, p.y) mx.z = max(mx.z, p.z) return m...
0.466359
0.363816
import datetime import json import pathlib import re import sys from vaccine_feed_ingest_schema import location as schema from vaccine_feed_ingest.utils.log import getLogger from vaccine_feed_ingest.utils.normalize import normalize_phone, normalize_url logger = getLogger(__file__) def _get_id(site: dict) -> str: ...
vaccine_feed_ingest/runners/nc/myspot_gov/normalize.py
import datetime import json import pathlib import re import sys from vaccine_feed_ingest_schema import location as schema from vaccine_feed_ingest.utils.log import getLogger from vaccine_feed_ingest.utils.normalize import normalize_phone, normalize_url logger = getLogger(__file__) def _get_id(site: dict) -> str: ...
0.361165
0.183466
import uuid from pyvultr.base_api import SupportHttpMethod from pyvultr.v2 import StartupScript from pyvultr.v2.enums import StartupScriptType from tests.v2 import BaseTestV2 class TestStartupScript(BaseTestV2): def test_list(self): """Test list scripts.""" with self._get("response/startup_script...
tests/v2/test_startup_script.py
import uuid from pyvultr.base_api import SupportHttpMethod from pyvultr.v2 import StartupScript from pyvultr.v2.enums import StartupScriptType from tests.v2 import BaseTestV2 class TestStartupScript(BaseTestV2): def test_list(self): """Test list scripts.""" with self._get("response/startup_script...
0.68721
0.201833
# Add Kitchen assets adept_envs/ folder to the python path. import sys import os parent_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(parent_dir, "kitchen_assets/adept_envs")) import time import numpy as np import mujoco_py import copy from adept_envs.franka.kitchen_multitask_v0 impor...
envs/kitchen.py
# Add Kitchen assets adept_envs/ folder to the python path. import sys import os parent_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(parent_dir, "kitchen_assets/adept_envs")) import time import numpy as np import mujoco_py import copy from adept_envs.franka.kitchen_multitask_v0 impor...
0.524882
0.389837
import os, uuid, subprocess, logging, time, re from .db_utils import DBUtils from CTFd import utils from .models import ADAChallenge, GlowwormContainers, GlowwormCheckLog, GlowwormAttacks from .extensions import get_round from CTFd.utils.logging import log from CTFd.models import db, Users, Teams from .extensions impor...
CTFd/plugins/ctfd_glowworm/docker_utils.py
import os, uuid, subprocess, logging, time, re from .db_utils import DBUtils from CTFd import utils from .models import ADAChallenge, GlowwormContainers, GlowwormCheckLog, GlowwormAttacks from .extensions import get_round from CTFd.utils.logging import log from CTFd.models import db, Users, Teams from .extensions impor...
0.159577
0.050331
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import tensorflow as tf from tf_agents.agents.dqn import dqn_agent from tf_agents.environments import time_step as ts from tf_agents.networks import network from tf_agent...
tf_agents/agents/dqn/dqn_agent_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import tensorflow as tf from tf_agents.agents.dqn import dqn_agent from tf_agents.environments import time_step as ts from tf_agents.networks import network from tf_agent...
0.723798
0.308242
from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descrip...
resultstoresearch/server/resultstoresearch/resultstoresearchapi/coverage_pb2.py
from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descrip...
0.29584
0.113383
from __future__ import unicode_literals import frappe import erpnext import unittest from frappe.utils import nowdate, add_days from erpnext.tests.utils import create_test_contact_and_address from erpnext.stock.doctype.delivery_trip.delivery_trip import notify_customers, get_contact_and_address class TestDeliveryTrip...
frappe-bench/apps/erpnext/erpnext/stock/doctype/delivery_trip/test_delivery_trip.py
from __future__ import unicode_literals import frappe import erpnext import unittest from frappe.utils import nowdate, add_days from erpnext.tests.utils import create_test_contact_and_address from erpnext.stock.doctype.delivery_trip.delivery_trip import notify_customers, get_contact_and_address class TestDeliveryTrip...
0.298798
0.114492
import os import sys import math import tensorflow as tf import model_helper as _mh from pathlib import Path PROJECT_PATH = Path(__file__).absolute().parent sys.path.insert(0, str(PROJECT_PATH)) from utils.log import log_info as _info from utils.log import log_error as _error def tranformer_model(input_tensor, ...
transformer.py
import os import sys import math import tensorflow as tf import model_helper as _mh from pathlib import Path PROJECT_PATH = Path(__file__).absolute().parent sys.path.insert(0, str(PROJECT_PATH)) from utils.log import log_info as _info from utils.log import log_error as _error def tranformer_model(input_tensor, ...
0.756987
0.342091
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='Category', fields=[ ...
patients/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='Category', fields=[ ...
0.617628
0.196017
# isort: FIRSTPARTY from dbus_client_gen import DbusClientUniqueResultError # isort: LOCAL from stratis_cli import StratisCliErrorCodes from .._misc import RUNNER, TEST_RUNNER, SimTestCase, device_name_list _DEVICE_STRATEGY = device_name_list(1) class ListTestCase(SimTestCase): """ Test listing devices for...
tests/whitebox/integration/physical/test_list.py
# isort: FIRSTPARTY from dbus_client_gen import DbusClientUniqueResultError # isort: LOCAL from stratis_cli import StratisCliErrorCodes from .._misc import RUNNER, TEST_RUNNER, SimTestCase, device_name_list _DEVICE_STRATEGY = device_name_list(1) class ListTestCase(SimTestCase): """ Test listing devices for...
0.421314
0.143848
from collections import OrderedDict import os import pathlib import re import xml.etree.ElementTree as et def get_filename(element): return element.attrib['filename'] def get_name(element): return element.attrib['name'] def get_value(element): return int(element.attrib['value'], 0) def get_start(elemen...
src/intel/genxml/gen_sort_tags.py
from collections import OrderedDict import os import pathlib import re import xml.etree.ElementTree as et def get_filename(element): return element.attrib['filename'] def get_name(element): return element.attrib['name'] def get_value(element): return int(element.attrib['value'], 0) def get_start(elemen...
0.584271
0.306177
import kol.Error as Error from .GenericRequest import GenericRequest from kol.manager import PatternManager from kol.util import ParseResponseUtils class CafeRequest(GenericRequest): "Purchases items from a cafe." CHEZ_SNOOTEE ='1' MICROBREWERY = '2' HELLS_KITCHEN = '3' def __init__(self, session...
kol/request/CafeConsumeRequest.py
import kol.Error as Error from .GenericRequest import GenericRequest from kol.manager import PatternManager from kol.util import ParseResponseUtils class CafeRequest(GenericRequest): "Purchases items from a cafe." CHEZ_SNOOTEE ='1' MICROBREWERY = '2' HELLS_KITCHEN = '3' def __init__(self, session...
0.4436
0.063106
import os, sys import subprocess import time from termcolor import colored def getCol(col, line): p1 = line.find(col) if p1<0 : return "" p2 = p1 + len(col) + 1 p3 = line.find('"',p2+1) return line[p2+1:p3] def updateCamera(): print " -> Update device rules: eye(s)..." try: res...
src/nimbro/scripts/set_camera.py
import os, sys import subprocess import time from termcolor import colored def getCol(col, line): p1 = line.find(col) if p1<0 : return "" p2 = p1 + len(col) + 1 p3 = line.find('"',p2+1) return line[p2+1:p3] def updateCamera(): print " -> Update device rules: eye(s)..." try: res...
0.060218
0.148664
from to_python.core.types import FunctionType, \ FunctionArgument, \ FunctionArgumentValues, \ FunctionReturnTypes, \ FunctionSignature, \ FunctionDoc, \ FunctionOOP, \ FunctionOOPField, \ CompoundOOPData, \ FunctionData, \ CompoundFunctionData DUMP_PARTIAL = [ CompoundOOPDa...
oops/ped_functions.py
from to_python.core.types import FunctionType, \ FunctionArgument, \ FunctionArgumentValues, \ FunctionReturnTypes, \ FunctionSignature, \ FunctionDoc, \ FunctionOOP, \ FunctionOOPField, \ CompoundOOPData, \ FunctionData, \ CompoundFunctionData DUMP_PARTIAL = [ CompoundOOPDa...
0.698741
0.438424
import json import os import pkgutil import tempfile import dataset import jsonpointer from flattentool import unflatten from jsonschema import FormatChecker from jsonschema.validators import Draft4Validator, RefResolver from ocdsmerge.util import get_release_schema_url, get_tags from scrapy.exceptions import DropItem...
kingfisher_scrapy/pipelines.py
import json import os import pkgutil import tempfile import dataset import jsonpointer from flattentool import unflatten from jsonschema import FormatChecker from jsonschema.validators import Draft4Validator, RefResolver from ocdsmerge.util import get_release_schema_url, get_tags from scrapy.exceptions import DropItem...
0.439507
0.095983
from __future__ import annotations from dataclasses import dataclass, field from typing import List, Dict, TYPE_CHECKING from reamber.base.Map import Map from reamber.base.lists import TimedList from reamber.sm.SMBpm import SMBpm from reamber.sm.SMConst import SMConst from reamber.sm.SMFake import SMFake from reamber...
reamber/sm/SMMap.py
from __future__ import annotations from dataclasses import dataclass, field from typing import List, Dict, TYPE_CHECKING from reamber.base.Map import Map from reamber.base.lists import TimedList from reamber.sm.SMBpm import SMBpm from reamber.sm.SMConst import SMConst from reamber.sm.SMFake import SMFake from reamber...
0.814459
0.361756
import pyecharts.options as opts from pyecharts.charts import Line, Page from pyecharts.commons.utils import JsCode from pyecharts.faker import Collector, Faker C = Collector() @C.funcs def line_base() -> Line: c = ( Line() .add_xaxis(Faker.choose()) .add_yaxis("商家A", Faker.values()) ...
example/line_example.py
import pyecharts.options as opts from pyecharts.charts import Line, Page from pyecharts.commons.utils import JsCode from pyecharts.faker import Collector, Faker C = Collector() @C.funcs def line_base() -> Line: c = ( Line() .add_xaxis(Faker.choose()) .add_yaxis("商家A", Faker.values()) ...
0.431345
0.245469
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from hubspot.automation.actions.api_client import ApiClient from hubspot.automation.actions.exceptions import ApiTypeError, ApiValueError # noqa: F401 class FunctionsApi(object): """NOTE: Th...
hubspot/automation/actions/api/functions_api.py
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from hubspot.automation.actions.api_client import ApiClient from hubspot.automation.actions.exceptions import ApiTypeError, ApiValueError # noqa: F401 class FunctionsApi(object): """NOTE: Th...
0.764584
0.06832
from os import access, R_OK from django.core.management.base import BaseCommand from canary_log_api.models import CanaryLogItem from canary_utils.lib.util import SSLVerify, print_error class Command(BaseCommand): help = "Check certificate validity." def add_arguments(self, parser): parser.add_argu...
toucan/canary_utils/management/commands/ssl_check.py
from os import access, R_OK from django.core.management.base import BaseCommand from canary_log_api.models import CanaryLogItem from canary_utils.lib.util import SSLVerify, print_error class Command(BaseCommand): help = "Check certificate validity." def add_arguments(self, parser): parser.add_argu...
0.364551
0.090977
import os import sys import textwrap from typing import Set, List, Optional from extract_wheels.lib import wheel def pkg_resources_style_namespace_packages(wheel_dir: str) -> Set[str]: """Discovers namespace packages implemented using the 'pkg_resources-style namespace packages' method. "While this approach...
extract_wheels/lib/namespace_pkgs.py
import os import sys import textwrap from typing import Set, List, Optional from extract_wheels.lib import wheel def pkg_resources_style_namespace_packages(wheel_dir: str) -> Set[str]: """Discovers namespace packages implemented using the 'pkg_resources-style namespace packages' method. "While this approach...
0.753648
0.216198
from datetime import date, datetime import jsonpickle from bson import ObjectId from cryptodataaccess.Transactions.TransactionRepository import TransactionRepository from cryptodataaccess.Transactions.TransactionMongoStore import TransactionMongoStore from cryptodataaccess.Users.UsersMongoStore import UsersMongoStore ...
CryptoCalculatorService/tests/BalanceService_test.py
from datetime import date, datetime import jsonpickle from bson import ObjectId from cryptodataaccess.Transactions.TransactionRepository import TransactionRepository from cryptodataaccess.Transactions.TransactionMongoStore import TransactionMongoStore from cryptodataaccess.Users.UsersMongoStore import UsersMongoStore ...
0.513912
0.131062
import unittest import os import json import sppas from sppas import sppasTypeError, u from ..fileref import sppasAttribute, FileReference from ..filedata import FileData from ..filebase import States # --------------------------------------------------------------------------- class TestsppasAttribute(unittest.Tes...
sppas/sppas/src/files/tests/test_filedata.py
import unittest import os import json import sppas from sppas import sppasTypeError, u from ..fileref import sppasAttribute, FileReference from ..filedata import FileData from ..filebase import States # --------------------------------------------------------------------------- class TestsppasAttribute(unittest.Tes...
0.445288
0.369969
from noOD import No class ListaLigada: def __init__(self): self.cabeca = None self._tamanho = 0 def append(self, cdX, cdY, IDpessoa): if self.cabeca: atual = self.cabeca while atual.prox is not None and (atual.coordenada_dX != cdX or atual.coordenada_dY != cdY)...
Algoritmos e Estruturas de Dados II/EP1/ListaODsimples.py
from noOD import No class ListaLigada: def __init__(self): self.cabeca = None self._tamanho = 0 def append(self, cdX, cdY, IDpessoa): if self.cabeca: atual = self.cabeca while atual.prox is not None and (atual.coordenada_dX != cdX or atual.coordenada_dY != cdY)...
0.318485
0.519826
import sys sys.path.append('../') def ImportAriesByScenario(scenarioName, start_date, end_date, Area, CorpID = ['ALL']): from Model import BPXDatabase as bpxdb from Model import QueryFile as qf import pandas as pd #Create ODS and EDW objects Success = True Messages = [] combined...
local/Model/ImportUtility.py
import sys sys.path.append('../') def ImportAriesByScenario(scenarioName, start_date, end_date, Area, CorpID = ['ALL']): from Model import BPXDatabase as bpxdb from Model import QueryFile as qf import pandas as pd #Create ODS and EDW objects Success = True Messages = [] combined...
0.247351
0.136177
from itertools import chain from logzero import logger import pandas as pd from intervaltree import Interval, IntervalTree import pysam from . import data, genes, settings from .exceptions import ExcovisException from .cache import cache @cache.memoize() def load_all_data(): """Load all meta data information fr...
excovis/store.py
from itertools import chain from logzero import logger import pandas as pd from intervaltree import Interval, IntervalTree import pysam from . import data, genes, settings from .exceptions import ExcovisException from .cache import cache @cache.memoize() def load_all_data(): """Load all meta data information fr...
0.616012
0.409693
import base64 import os import re import subprocess import yaml SHELF = os.path.expanduser('~/.config/easy2fa/accounts') TYPES = ['counter', 'timer'] class AccountStorage(object): def __init__(self, filename=SHELF): self.filename = filename self._safety_check() self.shelf = None ...
easy2fa/storage.py
import base64 import os import re import subprocess import yaml SHELF = os.path.expanduser('~/.config/easy2fa/accounts') TYPES = ['counter', 'timer'] class AccountStorage(object): def __init__(self, filename=SHELF): self.filename = filename self._safety_check() self.shelf = None ...
0.320396
0.223631
from F2x.parser import tree class VarDecl(tree.VarDecl): """ A variable declaration. The following properties are available: - name: The symbolic name of the variable. - type: The C type of this variable. This might be a basic type (REAL, INTEGER, LOGICAL) or TYPE(C) for any other ty...
src/F2x/parser/plyplus/tree.py
from F2x.parser import tree class VarDecl(tree.VarDecl): """ A variable declaration. The following properties are available: - name: The symbolic name of the variable. - type: The C type of this variable. This might be a basic type (REAL, INTEGER, LOGICAL) or TYPE(C) for any other ty...
0.475118
0.217691
import numpy as np import matplotlib.pyplot as plt from pandas import DataFrame, Series def get_expression_value_fracs(expression: np.ndarray, max_val: int = 10, round: int = 3): expression = np.array(expression) n_transcripts_per_gene = expression.flatten().astype(int) n_transcripts_per_gene = n_transcri...
src/count_matrix_metrics.py
import numpy as np import matplotlib.pyplot as plt from pandas import DataFrame, Series def get_expression_value_fracs(expression: np.ndarray, max_val: int = 10, round: int = 3): expression = np.array(expression) n_transcripts_per_gene = expression.flatten().astype(int) n_transcripts_per_gene = n_transcri...
0.543833
0.745422
import torch import torch.nn as nn from onmt.Models import EncoderBase, RNNDecoderBase, NMTModel def multimodal_model_class_by_key(key): d = { 'hsm': HiddenStateMergeLayerMMM, 'fvtl': FirstViewThenListenMMM, 'gm': GeneratorMergeMMM, 'fvtl+gm': FirstViewThenListenFinallyViewMMM ...
onmt/modules/MultiModalModel.py
import torch import torch.nn as nn from onmt.Models import EncoderBase, RNNDecoderBase, NMTModel def multimodal_model_class_by_key(key): d = { 'hsm': HiddenStateMergeLayerMMM, 'fvtl': FirstViewThenListenMMM, 'gm': GeneratorMergeMMM, 'fvtl+gm': FirstViewThenListenFinallyViewMMM ...
0.961858
0.633977
import pytest from MusicXMLSynthesizer.utils import parse_notes_meta_to_list from MusicXMLSynthesizer.Synthesizer import Synthesizer from utility.testHelper import create_synthesizer import numpy as np from lxml import etree as ET # # Naming convention: test_[CLASS_NAME]_[FUNCTION_NAME]_[CONDITION] # def test_Synth...
tests/test_unit_Synthesizer.py
import pytest from MusicXMLSynthesizer.utils import parse_notes_meta_to_list from MusicXMLSynthesizer.Synthesizer import Synthesizer from utility.testHelper import create_synthesizer import numpy as np from lxml import etree as ET # # Naming convention: test_[CLASS_NAME]_[FUNCTION_NAME]_[CONDITION] # def test_Synth...
0.272702
0.399548
import os import requests from packaging.specifiers import SpecifierSet, InvalidSpecifier from packaging.version import Version, InvalidVersion DL_ZIPBALL = "https://github.com/{0}/{1}/archive/{2}.zip" API_RELEASES = "https://api.github.com/repos/{0}/{1}/releases" COMMIT_RELEASES = "https://api.github.com/repos/{0}/{...
lambentlight/github.py
import os import requests from packaging.specifiers import SpecifierSet, InvalidSpecifier from packaging.version import Version, InvalidVersion DL_ZIPBALL = "https://github.com/{0}/{1}/archive/{2}.zip" API_RELEASES = "https://api.github.com/repos/{0}/{1}/releases" COMMIT_RELEASES = "https://api.github.com/repos/{0}/{...
0.432183
0.214671
from accounts.models import Role, User, UserRole class TestData(object): public_users = [] core_members = [] collaborators = [] public_users_usernames = [ 'public_user_1', 'public_user_2', 'public_user_3', ] core_members_usernames = [ 'core_member_1', ...
dwfcommon/tests/utils.py
from accounts.models import Role, User, UserRole class TestData(object): public_users = [] core_members = [] collaborators = [] public_users_usernames = [ 'public_user_1', 'public_user_2', 'public_user_3', ] core_members_usernames = [ 'core_member_1', ...
0.516595
0.169819
from aiogram import types from state_manager import Depends from state_manager.models.dependencys.aiogram import AiogramStateManager from state_manager.routes.aiogram import AiogramRouter from app.db.enum import City, Representation from app.db.repositories.settings import SettingsRepository from app.db.repositories.u...
app/handlers/start.py
from aiogram import types from state_manager import Depends from state_manager.models.dependencys.aiogram import AiogramStateManager from state_manager.routes.aiogram import AiogramRouter from app.db.enum import City, Representation from app.db.repositories.settings import SettingsRepository from app.db.repositories.u...
0.439026
0.165897
import time class TransactionListener: def __init__(self, client, blockchain_mode=None, start_block=None, end_block=None, only_ops=True): self.client = client self.blockchain_mode = blockchain_mode or "irreversible" self.start_block = start_block ...
lightsteem/helpers/event_listener.py
import time class TransactionListener: def __init__(self, client, blockchain_mode=None, start_block=None, end_block=None, only_ops=True): self.client = client self.blockchain_mode = blockchain_mode or "irreversible" self.start_block = start_block ...
0.562537
0.113432
quotes = [ { "headline": "<NAME> über schlechte Chancen", "content": "Wenn etwas wichtig genug ist, dann mach es, auch wenn alle Chancen gegen dich stehen." }, { "headline": "<NAME> über den Aufbau einer Firma", "content": "Eine Firma aufzubauen ist wie Kuchen backen. Man bra...
skill/quotes.py
quotes = [ { "headline": "<NAME> über schlechte Chancen", "content": "Wenn etwas wichtig genug ist, dann mach es, auch wenn alle Chancen gegen dich stehen." }, { "headline": "<NAME> über den Aufbau einer Firma", "content": "Eine Firma aufzubauen ist wie Kuchen backen. Man bra...
0.233706
0.298794
import netCDF4 as nc4 def create_monthly_file(writefile,vars_out_salin,vars_out_non_salin,salinity_values,parameters): '''Creates netCDF dataset for monthly mean output data with all required variables and dimensions. Output variables have two dimensions: a record dimension (with associated month, year and buoy n...
nc_functions.py
import netCDF4 as nc4 def create_monthly_file(writefile,vars_out_salin,vars_out_non_salin,salinity_values,parameters): '''Creates netCDF dataset for monthly mean output data with all required variables and dimensions. Output variables have two dimensions: a record dimension (with associated month, year and buoy n...
0.399812
0.384854
import twitter from .config import CONSUMER_KEY, CONSUMER_SECRET class twitter_api: def request_token(self, hosturl, token_filename=None, open_browser=True): oc = hosturl + 'oauth_callback' tw = twitter.Twitter( auth=twitter.OAuth('', '', CONSUMER_KEY, CONSUMER_SECRET), fo...
view/twmng.py
import twitter from .config import CONSUMER_KEY, CONSUMER_SECRET class twitter_api: def request_token(self, hosturl, token_filename=None, open_browser=True): oc = hosturl + 'oauth_callback' tw = twitter.Twitter( auth=twitter.OAuth('', '', CONSUMER_KEY, CONSUMER_SECRET), fo...
0.150465
0.083516
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( ...
workspaces/migrations/0001_initial.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( ...
0.523177
0.135346
import cv2 import numpy as np from PIL import Image import PIL.Image import PIL.ImageFont import PIL.ImageOps import PIL.ImageDraw import os class fragile(object): class Break(Exception): """Break out of the with statement""" def __init__(self, value): self.value = value def __enter__(self)...
ascii_art.py
import cv2 import numpy as np from PIL import Image import PIL.Image import PIL.ImageFont import PIL.ImageOps import PIL.ImageDraw import os class fragile(object): class Break(Exception): """Break out of the with statement""" def __init__(self, value): self.value = value def __enter__(self)...
0.439026
0.164449
import socket import sys import getopt import threading import subprocess import getpass from textwrap import dedent from typing import Tuple, Union, List class Helpers: """Static functions, to use as helpers""" @staticmethod def send_data(to_socket: socket.socket, data_stream: bytes, ...
_netcat.py
import socket import sys import getopt import threading import subprocess import getpass from textwrap import dedent from typing import Tuple, Union, List class Helpers: """Static functions, to use as helpers""" @staticmethod def send_data(to_socket: socket.socket, data_stream: bytes, ...
0.52756
0.09314
import sys, os import numpy as np import yaml def detect_images_type(folder): images = [] if not os.path.isdir(folder): raise Exception('{} does not exist'.format(folder)) sys.exit(-1) for root, _, fnames in sorted(os.walk(folder)): for fname in sorted(fnames): tmp_type ...
src/utils.py
import sys, os import numpy as np import yaml def detect_images_type(folder): images = [] if not os.path.isdir(folder): raise Exception('{} does not exist'.format(folder)) sys.exit(-1) for root, _, fnames in sorted(os.walk(folder)): for fname in sorted(fnames): tmp_type ...
0.130368
0.109182
import os import cv2 import pickle import imutils import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import precision_recall_fscore_support as prfs from tensorflow.keras.optimizers import Adam, SGD from tensorflo...
traffic_sign_classifier.py
import os import cv2 import pickle import imutils import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import precision_recall_fscore_support as prfs from tensorflow.keras.optimizers import Adam, SGD from tensorflo...
0.641422
0.368178
from mypkg.db_settings import session from prompt_toolkit.application import Application from prompt_toolkit.layout import HSplit, VSplit, Layout, DummyControl, Window from prompt_toolkit.widgets import Label, TextArea, Frame from prompt_toolkit.styles import Style from prompt_toolkit.key_binding import KeyBinding...
mypkg/prompts/main_prompt.py
from mypkg.db_settings import session from prompt_toolkit.application import Application from prompt_toolkit.layout import HSplit, VSplit, Layout, DummyControl, Window from prompt_toolkit.widgets import Label, TextArea, Frame from prompt_toolkit.styles import Style from prompt_toolkit.key_binding import KeyBinding...
0.225672
0.103703
import os from test.data import TEST_DATA_DIR, bob, cheese, hates, likes, michel, pizza, tarek from rdflib import Dataset, URIRef timblcardn3 = open(os.path.join(TEST_DATA_DIR, "timbl-card.n3")).read() def add_stuff(graph): graph.add((tarek, likes, pizza)) graph.add((tarek, likes, cheese)) graph.add((ta...
test/test_dataset/test_dataset_generators.py
import os from test.data import TEST_DATA_DIR, bob, cheese, hates, likes, michel, pizza, tarek from rdflib import Dataset, URIRef timblcardn3 = open(os.path.join(TEST_DATA_DIR, "timbl-card.n3")).read() def add_stuff(graph): graph.add((tarek, likes, pizza)) graph.add((tarek, likes, cheese)) graph.add((ta...
0.535098
0.448909
from toolbox.AirWatchAPI import AirWatchAPI as airwatch from toolbox.csvReport import csvReport import argparse import sys """ Accepted Arguments """ parser = argparse.ArgumentParser(description='AirWatch Custom Attributes Search') parser.add_argument('name', help='Get list of devices with matching attribute name') p...
searchCustomAttributes.py
from toolbox.AirWatchAPI import AirWatchAPI as airwatch from toolbox.csvReport import csvReport import argparse import sys """ Accepted Arguments """ parser = argparse.ArgumentParser(description='AirWatch Custom Attributes Search') parser.add_argument('name', help='Get list of devices with matching attribute name') p...
0.212477
0.072276
import collectd import sys import time import pynsca from pynsca import NSCANotifier import json import hashlib PLUGIN_NAME = 'collectd_notification' # notitifcation : # severity => NOTIF_FAILURE || NOTIF_WARNING || NOTIF_OKAY, # time => time (), # message => 'status message', # host => $hostname_g, # plugin...
collectd_notification.py
import collectd import sys import time import pynsca from pynsca import NSCANotifier import json import hashlib PLUGIN_NAME = 'collectd_notification' # notitifcation : # severity => NOTIF_FAILURE || NOTIF_WARNING || NOTIF_OKAY, # time => time (), # message => 'status message', # host => $hostname_g, # plugin...
0.159774
0.073796
import tornado.ioloop import tornado.web import tornado.websocket import tornado.httpserver import json import lcm import threading ### SETTINGS import settings import forseti2 LCM_URI = settings.LCM_URI TYPES_ROOT = forseti2 ### END SETTINGS class WSHandler(tornado.websocket.WebSocketHandler): def open(self): ...
src/lcm_ws_bridge.py
import tornado.ioloop import tornado.web import tornado.websocket import tornado.httpserver import json import lcm import threading ### SETTINGS import settings import forseti2 LCM_URI = settings.LCM_URI TYPES_ROOT = forseti2 ### END SETTINGS class WSHandler(tornado.websocket.WebSocketHandler): def open(self): ...
0.389779
0.099208
import sys import os import shutil import tempfile import hashlib import datetime from time import time PY3K = sys.version_info >= (3, 0) if PY3K: import urllib.request as ulib import urllib.parse as urlparse import http.cookiejar as cjar else: import urllib2 as ulib import urlparse import co...
wgetter.py
import sys import os import shutil import tempfile import hashlib import datetime from time import time PY3K = sys.version_info >= (3, 0) if PY3K: import urllib.request as ulib import urllib.parse as urlparse import http.cookiejar as cjar else: import urllib2 as ulib import urlparse import co...
0.416203
0.247521
from math import ceil from functools import cached_property class Paginator: ELLIPSIS = '...' def __init__(self, object_list, per_page, count): """ Pagintator class. :param object_list: Can be any iterable or tortoise queryset. If it's a queryset, tortoise's .offset() and...
tornadmin/utils/paginator.py
from math import ceil from functools import cached_property class Paginator: ELLIPSIS = '...' def __init__(self, object_list, per_page, count): """ Pagintator class. :param object_list: Can be any iterable or tortoise queryset. If it's a queryset, tortoise's .offset() and...
0.805709
0.275127
from typing import Dict, Iterable, Union from operator import attrgetter import numpy as np from numpy import ndarray from netprop.data import Data class DormModel: """ Definition or method model """ def __init__(self, name: str, covs: Iterable[str], ...
src/netprop/dorm_model.py
from typing import Dict, Iterable, Union from operator import attrgetter import numpy as np from numpy import ndarray from netprop.data import Data class DormModel: """ Definition or method model """ def __init__(self, name: str, covs: Iterable[str], ...
0.902074
0.339417
import datetime; import pickle; import re; import sys; try: temp = pickle.load(open('dump.dat'))#created in emailGrab parsed = open("parsed.dat", "w") except IOError: print 'Error opening one or more files.' sys.exit(1); line = '' count = 0 hex = re.compile('[0-9A-F]{2}') #Packet-specific parsers def parsegps...
eon/eon/src/util/vis/Parsing/older/newParse.py
import datetime; import pickle; import re; import sys; try: temp = pickle.load(open('dump.dat'))#created in emailGrab parsed = open("parsed.dat", "w") except IOError: print 'Error opening one or more files.' sys.exit(1); line = '' count = 0 hex = re.compile('[0-9A-F]{2}') #Packet-specific parsers def parsegps...
0.101974
0.119408
import collections import numpy import os import six.moves.urllib import tarfile import texmex_python def get_gmm_random_dataset(k, dimension=100, test_size=5000, train_size=500): def random_gmm(k, n_sample): result = numpy.zeros((n_sample, dimension)) for _ in range(k): cov_source = n...
pqkmeans/evaluation.py
import collections import numpy import os import six.moves.urllib import tarfile import texmex_python def get_gmm_random_dataset(k, dimension=100, test_size=5000, train_size=500): def random_gmm(k, n_sample): result = numpy.zeros((n_sample, dimension)) for _ in range(k): cov_source = n...
0.343672
0.214486
import os import sys import json import numpy as np import dataloader.file_io.get_path as gp import dataloader.definitions.labels_file as lf class DatasetParameterset: """A class that contains all dataset-specific parameters - K: Extrinsic camera matrix as a Numpy array. If not available, take None ...
merged_depth/nets/SGDepth/dataloader/pt_data_loader/dataset_parameterset.py
import os import sys import json import numpy as np import dataloader.file_io.get_path as gp import dataloader.definitions.labels_file as lf class DatasetParameterset: """A class that contains all dataset-specific parameters - K: Extrinsic camera matrix as a Numpy array. If not available, take None ...
0.554229
0.37439
import sys from .bitcoin import Transaction, TransactionInput, TransactionOutput from .users import UserNetwork class TransactionNetwork: """ List of transactions with an unique set of all encountered addresses (as inputs or outputs of all transactions) """ def __init__(self): self.addres...
app/transactions.py
import sys from .bitcoin import Transaction, TransactionInput, TransactionOutput from .users import UserNetwork class TransactionNetwork: """ List of transactions with an unique set of all encountered addresses (as inputs or outputs of all transactions) """ def __init__(self): self.addres...
0.619586
0.415373
from .device import Device from threading import Timer from .const import ( LOGGER, STATUS_RESPONSE_INPUTS, STATUS_RESPONSE_INPUTS_INPUT, STATUS_RESPONSE_INPUTS_EVENT, STATUS_RESPONSE_INPUTS_EVENT_CNT ) class Switch(Device): """Class to represent a power meter value""" def __i...
pyShelly/switch.py
from .device import Device from threading import Timer from .const import ( LOGGER, STATUS_RESPONSE_INPUTS, STATUS_RESPONSE_INPUTS_INPUT, STATUS_RESPONSE_INPUTS_EVENT, STATUS_RESPONSE_INPUTS_EVENT_CNT ) class Switch(Device): """Class to represent a power meter value""" def __i...
0.527073
0.12363
from abc import ABC from video_streaming import settings from video_streaming.celery import celery_app from video_streaming.core.tasks import ChainCallbackMixin from video_streaming.ffmpeg.utils import FfmpegCallback from video_streaming.ffmpeg.constants import TASK_DECORATOR_KWARGS from .base import BaseStreamingTask ...
video-streaming/video_streaming/ffmpeg/tasks/create_playlist.py
from abc import ABC from video_streaming import settings from video_streaming.celery import celery_app from video_streaming.core.tasks import ChainCallbackMixin from video_streaming.ffmpeg.utils import FfmpegCallback from video_streaming.ffmpeg.constants import TASK_DECORATOR_KWARGS from .base import BaseStreamingTask ...
0.550124
0.120853
from scipy.optimize import fsolve def interpolator(value , x_series, y_series): if not(len(x_series) == len(y_series)): print('x and y must have the same lenght') return 'ERR' for i in range(1, len(x_series)): if (value <= x_series[i]) and (value >= x_series[i - 1]): ...
Code/Performance/Functions.py
from scipy.optimize import fsolve def interpolator(value , x_series, y_series): if not(len(x_series) == len(y_series)): print('x and y must have the same lenght') return 'ERR' for i in range(1, len(x_series)): if (value <= x_series[i]) and (value >= x_series[i - 1]): ...
0.316053
0.602997
import argparse from typing import List from pydantic import BaseModel, Field from MHDDoS.methods.methods import Methods class Arguments(BaseModel): targets: List[str] = Field(default=[]) config: str = Field(default=None) config_fetch_interval: float = Field(default=600) attack_methods: List[str] = ...
utils/input_args.py
import argparse from typing import List from pydantic import BaseModel, Field from MHDDoS.methods.methods import Methods class Arguments(BaseModel): targets: List[str] = Field(default=[]) config: str = Field(default=None) config_fetch_interval: float = Field(default=600) attack_methods: List[str] = ...
0.717012
0.201401
import re import io day23 = __import__("day-23") process = day23.process_gen def get_intcode(): with open('day-25.txt', 'r') as f: text = f.read().strip() idata = [int(x) for x in text.split(',')] return idata def parse_output(text): lines = text.split('\n') name, doors, items = None, [],...
day-25.py
import re import io day23 = __import__("day-23") process = day23.process_gen def get_intcode(): with open('day-25.txt', 'r') as f: text = f.read().strip() idata = [int(x) for x in text.split(',')] return idata def parse_output(text): lines = text.split('\n') name, doors, items = None, [],...
0.099607
0.1602
import configparser from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS class PysentelConfig(object): """ Module for handling configs in an easy and objected manner. """ def __init__(self): """ Initialization constructor - create config-...
pysentel/helpers.py
import configparser from influxdb_client import InfluxDBClient from influxdb_client.client.write_api import SYNCHRONOUS class PysentelConfig(object): """ Module for handling configs in an easy and objected manner. """ def __init__(self): """ Initialization constructor - create config-...
0.662141
0.129623
class HiveConnectParams(object): """Implementation of the 'HiveConnectParams' model. Specifies an Object containing information about a registered Hive source. Attributes: hdfs_entity_id (int|long): Specifies the entity id of the HDFS source for this Hive kerberos_princi...
cohesity_management_sdk/models/hive_connect_params.py
class HiveConnectParams(object): """Implementation of the 'HiveConnectParams' model. Specifies an Object containing information about a registered Hive source. Attributes: hdfs_entity_id (int|long): Specifies the entity id of the HDFS source for this Hive kerberos_princi...
0.863363
0.405802
import argparse import sys import tempfile from time import time import random from os import listdir from os.path import isfile, join import pandas import numpy as np import tensorflow as tf from sklearn import metrics # model settings # Static seed to allow for reproducability between training runs tf.set_random_...
Chatbot_KG/stock/MLP.py
import argparse import sys import tempfile from time import time import random from os import listdir from os.path import isfile, join import pandas import numpy as np import tensorflow as tf from sklearn import metrics # model settings # Static seed to allow for reproducability between training runs tf.set_random_...
0.54819
0.419232
import sys from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import matplotlib.pyplot as plt import matplotlib.dates as mda...
Interfaz/PlotWindow.py
import sys from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar import matplotlib.pyplot as plt import matplotlib.dates as mda...
0.542621
0.314702
import argparse import os import sys from enerpi.base import BASE_PATH, DATA_PATH, CONFIG, log, check_resource_files, NGINX_CONFIG_FILE, UWSGI_CONFIG_FILE from enerpi.prettyprinting import print_secc, print_cyan, print_red, print_magenta FLASK_WEBSERVER_PORT = CONFIG.getint('ENERPI_WEBSERVER', 'FLASK_WEBSERVER_PORT',...
enerpiweb/command_enerpiweb.py
import argparse import os import sys from enerpi.base import BASE_PATH, DATA_PATH, CONFIG, log, check_resource_files, NGINX_CONFIG_FILE, UWSGI_CONFIG_FILE from enerpi.prettyprinting import print_secc, print_cyan, print_red, print_magenta FLASK_WEBSERVER_PORT = CONFIG.getint('ENERPI_WEBSERVER', 'FLASK_WEBSERVER_PORT',...
0.212069
0.046812
from .base_options import BaseOptions class TrainOptions(BaseOptions): """This class includes training options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): parser = BaseOptions.initialize(self, parser) # visualization parameters p...
options/train_options.py
from .base_options import BaseOptions class TrainOptions(BaseOptions): """This class includes training options. It also includes shared options defined in BaseOptions. """ def initialize(self, parser): parser = BaseOptions.initialize(self, parser) # visualization parameters p...
0.690455
0.216923
from typing import Tuple, List, Dict, Optional import torch from torch import Tensor from transformers import AutoTokenizer, RobertaTokenizer from torch.utils.data.dataset import Dataset, T_co, TensorDataset class BaseDictCollator: def __init__(self, add_mlm_labels: bool = False, mlm_probability: float = 0.15, t...
dataset/collators/base_collator.py
from typing import Tuple, List, Dict, Optional import torch from torch import Tensor from transformers import AutoTokenizer, RobertaTokenizer from torch.utils.data.dataset import Dataset, T_co, TensorDataset class BaseDictCollator: def __init__(self, add_mlm_labels: bool = False, mlm_probability: float = 0.15, t...
0.940469
0.599895
import base64 import json from copy import deepcopy from typing import Any, Dict, Mapping from flask import Blueprint, current_app, request from mock import patch from eduid_userdb import User from eduid_userdb.fixtures.fido_credentials import u2f_credential, webauthn_credential from eduid_userdb.fixtures.users impor...
src/eduid_common/authn/tests/test_fido_tokens.py
import base64 import json from copy import deepcopy from typing import Any, Dict, Mapping from flask import Blueprint, current_app, request from mock import patch from eduid_userdb import User from eduid_userdb.fixtures.fido_credentials import u2f_credential, webauthn_credential from eduid_userdb.fixtures.users impor...
0.605449
0.118334
from enum import Enum, auto from ..geometry import Position, Vector, Size from ..events import handlers from .core import Align, ZOrder from . import toolkit from . import basic from . import containers from . import decorations from . import renderers class UIWidget: def __init__(self, default_colors, *args,...
rogal/console/widgets.py
from enum import Enum, auto from ..geometry import Position, Vector, Size from ..events import handlers from .core import Align, ZOrder from . import toolkit from . import basic from . import containers from . import decorations from . import renderers class UIWidget: def __init__(self, default_colors, *args,...
0.733261
0.139895
import copy from .. import base __all__ = ['SplitRegressor'] class SplitRegressor(base.Regressor): """Runs a different regressor based on the value of a specified attribute. Parameters: on (str): The feature on which to perform the split. models (dict): A mapping between feature values and...
creme/compose/split.py
import copy from .. import base __all__ = ['SplitRegressor'] class SplitRegressor(base.Regressor): """Runs a different regressor based on the value of a specified attribute. Parameters: on (str): The feature on which to perform the split. models (dict): A mapping between feature values and...
0.878965
0.448426
"""Hyper-parameters support classes for TensorFlow Lattice estimators.""" from distutils.util import strtobool import six from tensorflow_lattice.python.lib import regularizers class PerFeatureHParams(object): """Parameters object with per feature parametrization. Each parameter can be overwritten for specific ...
tensorflow_lattice/python/estimators/hparams.py
"""Hyper-parameters support classes for TensorFlow Lattice estimators.""" from distutils.util import strtobool import six from tensorflow_lattice.python.lib import regularizers class PerFeatureHParams(object): """Parameters object with per feature parametrization. Each parameter can be overwritten for specific ...
0.958499
0.716305
import numpy as np import dolfin as df import ufl import matplotlib.pyplot as plt if __name__ == '__main__': # Number of elements nel = 200 # Local approximation order p = 2 # Strength of nonlinearity a = 10 # Construct mesh on [0,1] mesh = df.IntervalMesh(nel,0,1) ...
newton.py
import numpy as np import dolfin as df import ufl import matplotlib.pyplot as plt if __name__ == '__main__': # Number of elements nel = 200 # Local approximation order p = 2 # Strength of nonlinearity a = 10 # Construct mesh on [0,1] mesh = df.IntervalMesh(nel,0,1) ...
0.743541
0.614365
import pytest from unittest import mock from molly.constants import TOP_20_PORTS, ALL_PORTS, FIRST_1000_PORTS def test_basic_molly(_molly): assert _molly.max_workers == 4 assert _molly.hostname == 'scanme.nmap.org' assert _molly.mode == 'common' _molly.max_workers = 20 _molly.target = 'localhost' ...
molly/tests/test_molly.py
import pytest from unittest import mock from molly.constants import TOP_20_PORTS, ALL_PORTS, FIRST_1000_PORTS def test_basic_molly(_molly): assert _molly.max_workers == 4 assert _molly.hostname == 'scanme.nmap.org' assert _molly.mode == 'common' _molly.max_workers = 20 _molly.target = 'localhost' ...
0.590425
0.482002
import os import subprocess program = lambda num_runs, threshold: f''' #include <vector> #include "llvm/Analysis/InlineCost.h" #include "llvm/IR/Function.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Pass.h" #include "llvm/Support/raw_ostre...
run.py
import os import subprocess program = lambda num_runs, threshold: f''' #include <vector> #include "llvm/Analysis/InlineCost.h" #include "llvm/IR/Function.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Pass.h" #include "llvm/Support/raw_ostre...
0.264833
0.052014
from tqdm import tqdm import numpy as np from typing import Any, Callable, List, Optional, Union from alibi_detect.cd.base_online import BaseUniDriftOnline from alibi_detect.utils.misc import quantile from scipy.stats import hypergeom import numba as nb import warnings class FETDriftOnline(BaseUniDriftOnline): de...
alibi_detect/cd/fet_online.py
from tqdm import tqdm import numpy as np from typing import Any, Callable, List, Optional, Union from alibi_detect.cd.base_online import BaseUniDriftOnline from alibi_detect.utils.misc import quantile from scipy.stats import hypergeom import numba as nb import warnings class FETDriftOnline(BaseUniDriftOnline): de...
0.952849
0.554531
from base64 import b64encode, b64decode from bs4 import BeautifulSoup as soup from bz2 import BZ2File from collections import Counter, OrderedDict from copy import deepcopy from datetime import datetime as dt, timedelta try: from etk.extractors.date_extractor import DateExtractor except OSError: from s...
datamart/materializers/wikitables_downloader/utils.py
from base64 import b64encode, b64decode from bs4 import BeautifulSoup as soup from bz2 import BZ2File from collections import Counter, OrderedDict from copy import deepcopy from datetime import datetime as dt, timedelta try: from etk.extractors.date_extractor import DateExtractor except OSError: from s...
0.328422
0.095097
import os import sys import getopt from pptx import Presentation from pptx.util import Inches def main(): argv = sys.argv[1:] pathtofiles = '.' outputfile = 'test.pptx' templatefile = './template.pptx' sort = 'm' try: opts, args = getopt.getopt(argv,"hfi:o:t:",["imagelocationdirectory=...
photoslides/__main__.py
import os import sys import getopt from pptx import Presentation from pptx.util import Inches def main(): argv = sys.argv[1:] pathtofiles = '.' outputfile = 'test.pptx' templatefile = './template.pptx' sort = 'm' try: opts, args = getopt.getopt(argv,"hfi:o:t:",["imagelocationdirectory=...
0.098957
0.086054
import itertools as itt import os import tempfile from ..biotools import blast_sequence class PostProcessingMixin: def compute_full_assembly_plan(self, id_prefix="S", id_digits=5): """ """ counter = itt.count() def rec(quote): if not quote.accepted: return quo...
dnaweaver/DnaQuote/PostProcessingMixin.py
import itertools as itt import os import tempfile from ..biotools import blast_sequence class PostProcessingMixin: def compute_full_assembly_plan(self, id_prefix="S", id_digits=5): """ """ counter = itt.count() def rec(quote): if not quote.accepted: return quo...
0.529263
0.138666
import logging from typing import Dict, Sequence, Type, Optional, Callable, Union, Any from concord.context import Context from concord.exceptions import ExtensionManagerError from concord.middleware import ( Middleware, MiddlewareChain, chain_of, sequence_of, MiddlewareResult, ) log = logging.ge...
concord/extension.py
import logging from typing import Dict, Sequence, Type, Optional, Callable, Union, Any from concord.context import Context from concord.exceptions import ExtensionManagerError from concord.middleware import ( Middleware, MiddlewareChain, chain_of, sequence_of, MiddlewareResult, ) log = logging.ge...
0.897223
0.220741
import unittest import numpy as np from weis.multifidelity.models.testbed_components import simple_2D_high_model, simple_2D_low_model from weis.multifidelity.methods.base_method import BaseMethod class Test(unittest.TestCase): def test_set_initial_point(self): np.random.seed(13) ...
weis/multifidelity/test/test_base_method.py
import unittest import numpy as np from weis.multifidelity.models.testbed_components import simple_2D_high_model, simple_2D_low_model from weis.multifidelity.methods.base_method import BaseMethod class Test(unittest.TestCase): def test_set_initial_point(self): np.random.seed(13) ...
0.424889
0.595669
from typing import Optional from spectrumdevice import MockSpectrumCard, SpectrumCard from spectrumdevice.devices.measurement import Measurement from spectrumdevice.settings import ( AcquisitionMode, CardType, TriggerSource, ExternalTriggerMode, TriggerSettings, AcquisitionSettings, ) def st...
example_scripts/standard_single_mode.py
from typing import Optional from spectrumdevice import MockSpectrumCard, SpectrumCard from spectrumdevice.devices.measurement import Measurement from spectrumdevice.settings import ( AcquisitionMode, CardType, TriggerSource, ExternalTriggerMode, TriggerSettings, AcquisitionSettings, ) def st...
0.909574
0.166438
import os import unittest from datetime import datetime, timedelta, date from flask import json import sys sys.path.append(".") # Adds higher directory to python modules path. from extensions import db from app import create_app from config import TestConfig from controllers.database.pandemic_whistle import PandemicWh...
tests/test_reports.py
import os import unittest from datetime import datetime, timedelta, date from flask import json import sys sys.path.append(".") # Adds higher directory to python modules path. from extensions import db from app import create_app from config import TestConfig from controllers.database.pandemic_whistle import PandemicWh...
0.296858
0.233335
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('billing', '0001_initial'), ('vendors', '0001_initial'), ('carts', '0002_auto_20200601_2225'), ('orders', '0001_initial'), ...
baby_backend/apps/orders/migrations/0002_auto_20200601_2225.py
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('billing', '0001_initial'), ('vendors', '0001_initial'), ('carts', '0002_auto_20200601_2225'), ('orders', '0001_initial'), ...
0.589362
0.095645
import numpy as np from RecSysFramework.Recommender.MatrixFactorization.MatrixFactorization_Cython import BPR_NNMF, BPRMF, FUNK_NNMF, FunkSVD from RecSysFramework.Recommender.MatrixFactorization.PureSVD import PureSVD from RecSysFramework.Recommender.KNN.ItemKNNCFRecommender import ItemKNNCF from RecSysFramework.Recomm...
RecSysFramework/Experiments/recommended_items_popularity_analysis.py
import numpy as np from RecSysFramework.Recommender.MatrixFactorization.MatrixFactorization_Cython import BPR_NNMF, BPRMF, FUNK_NNMF, FunkSVD from RecSysFramework.Recommender.MatrixFactorization.PureSVD import PureSVD from RecSysFramework.Recommender.KNN.ItemKNNCFRecommender import ItemKNNCF from RecSysFramework.Recomm...
0.539469
0.236494
from json import dumps from unittest import TestCase, mock from unittest.mock import Mock import data_gathering_subsystem.data_modules.air_pollution.air_pollution as air_pollution class TestAirPollution(TestCase): @classmethod def setUp(cls): air_pollution.instance(log_to_stdout=False, log_to_telegr...
data_gathering_subsystem/test/data_modules/test_air_pollution.py
from json import dumps from unittest import TestCase, mock from unittest.mock import Mock import data_gathering_subsystem.data_modules.air_pollution.air_pollution as air_pollution class TestAirPollution(TestCase): @classmethod def setUp(cls): air_pollution.instance(log_to_stdout=False, log_to_telegr...
0.616128
0.525551
import settings from utils import get_most_recent from periscope_client import PeriscopeClient logger = settings.get_logger('unis_client') class UNISInstance: def __init__(self, service): self.service = service self.config = service["properties"]["configurations"] unis_url=self.config["uni...
blipp/unis_client.py
import settings from utils import get_most_recent from periscope_client import PeriscopeClient logger = settings.get_logger('unis_client') class UNISInstance: def __init__(self, service): self.service = service self.config = service["properties"]["configurations"] unis_url=self.config["uni...
0.381911
0.223992
from abc import ABC from nerdchess.config import MOVE_REGEX, letterlist, numbers class Move(ABC): """ Represents a move in a game of chess. Parameters: move(String): A string that's tested with the regex '[a-h][1-8][a-h][1-8]' Attributes: text(String): String re...
nerdchess/move.py
from abc import ABC from nerdchess.config import MOVE_REGEX, letterlist, numbers class Move(ABC): """ Represents a move in a game of chess. Parameters: move(String): A string that's tested with the regex '[a-h][1-8][a-h][1-8]' Attributes: text(String): String re...
0.93627
0.541894
import base64 import endpoints import json import os from google.appengine.api import mail from google.appengine.ext import deferred from google.appengine.ext.webapp import template from models import PrivateKeys from models import Unsubscribed from protorpc import remote from subscribe_api_messages import RequestM...
subscribe_api.py
import base64 import endpoints import json import os from google.appengine.api import mail from google.appengine.ext import deferred from google.appengine.ext.webapp import template from models import PrivateKeys from models import Unsubscribed from protorpc import remote from subscribe_api_messages import RequestM...
0.569853
0.052863
import os import posixpath from typing import Callable from fastapi import APIRouter, File, UploadFile, Depends, Query, Form, Body from fastapi.responses import JSONResponse from utils import http from utils.security import safe_join from ..config import get_upload from ..schemas.upload_schema import UploadSchema ro...
app/file/routes/upload.py
import os import posixpath from typing import Callable from fastapi import APIRouter, File, UploadFile, Depends, Query, Form, Body from fastapi.responses import JSONResponse from utils import http from utils.security import safe_join from ..config import get_upload from ..schemas.upload_schema import UploadSchema ro...
0.503174
0.188735
def logic(*args, **kwargs): # More complicated example of custom method. Allows for adding logic gates. """ Simple logic gate construct that can take any number of inputs :param args: first arg is name of gate, all following args are input values :param kwargs: true=true_condition(default=1) false=fa...
sketchymaths/sketchymathmethods/logic.py
def logic(*args, **kwargs): # More complicated example of custom method. Allows for adding logic gates. """ Simple logic gate construct that can take any number of inputs :param args: first arg is name of gate, all following args are input values :param kwargs: true=true_condition(default=1) false=fa...
0.689096
0.397354
import torch import torch.nn as nn from network.head import * from network.resnet import * import torch.nn.functional as F from scipy.sparse import csr_matrix from scipy.sparse.csgraph import connected_components import numpy as np class ClInfoNCE(nn.Module): def __init__(self, dim_hidden=2048, dim=128, model='res...
network/clinfo.py
import torch import torch.nn as nn from network.head import * from network.resnet import * import torch.nn.functional as F from scipy.sparse import csr_matrix from scipy.sparse.csgraph import connected_components import numpy as np class ClInfoNCE(nn.Module): def __init__(self, dim_hidden=2048, dim=128, model='res...
0.853303
0.45538
from Config import Config from src.orm.SqlUtil import SqlUtil from flask import Flask, request from src.Handler.MetricHandler import MetricHandler from src.Handler.MainHandler import MainHandler from src.Handler.StatusHandler import StatusHandler from src.Handler.GetHandler import GetHandler import os import sys from ...
PrivateMonitorServer/main.py
from Config import Config from src.orm.SqlUtil import SqlUtil from flask import Flask, request from src.Handler.MetricHandler import MetricHandler from src.Handler.MainHandler import MainHandler from src.Handler.StatusHandler import StatusHandler from src.Handler.GetHandler import GetHandler import os import sys from ...
0.197715
0.067393