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 numpy as np import argparse class Env(): def __init__(self, W, F, K, Dn, Cn, f, dist, pn, pi): # W 带宽 10 MHz # F 边缘服务器总计算能力 # K 用户数量 # Dn, Cn 任务量大小,所需cpu周期数, (300~500kb), (900, 1100)兆周期数 1Mhz = 1000khz = 1000*1000hz # f 用户本地计算能力 1GHz/s | [0.5, 1.5]GHz/s (1000*1000*10...
mec.py
import numpy as np import argparse class Env(): def __init__(self, W, F, K, Dn, Cn, f, dist, pn, pi): # W 带宽 10 MHz # F 边缘服务器总计算能力 # K 用户数量 # Dn, Cn 任务量大小,所需cpu周期数, (300~500kb), (900, 1100)兆周期数 1Mhz = 1000khz = 1000*1000hz # f 用户本地计算能力 1GHz/s | [0.5, 1.5]GHz/s (1000*1000*10...
0.215846
0.284635
import pytest import redis import random from threading import Thread from time import sleep from utils import Env, Refresh_Cluster from test_helper_classes import _get_series_value, calc_rule, ALLOWED_ERROR, _insert_data, \ _get_ts_info, _insert_agg_data from includes import * def testLibmrFail(): env = Env(...
tests/flow/test_ts_libmr_failiure.py
import pytest import redis import random from threading import Thread from time import sleep from utils import Env, Refresh_Cluster from test_helper_classes import _get_series_value, calc_rule, ALLOWED_ERROR, _insert_data, \ _get_ts_info, _insert_agg_data from includes import * def testLibmrFail(): env = Env(...
0.275422
0.322873
from __future__ import print_function import unittest import uuid from biggraphite import metric as bg_metric from biggraphite.drivers import _downsampling as bg_ds from tests import test_utils test_utils.setup_logging() class TestDownsampler(unittest.TestCase): METRIC_NAME_SUM = "test.metric.sum" METRIC_...
tests/drivers/test_drivers_downsampling.py
from __future__ import print_function import unittest import uuid from biggraphite import metric as bg_metric from biggraphite.drivers import _downsampling as bg_ds from tests import test_utils test_utils.setup_logging() class TestDownsampler(unittest.TestCase): METRIC_NAME_SUM = "test.metric.sum" METRIC_...
0.916332
0.456289
import reframe.utility.sanity as sn import reframe as rfm @rfm.parameterized_test(['peerAccess'], ['noPeerAccess']) class P2pBandwidthCheck(rfm.RegressionTest): def __init__(self, peerAccess): self.valid_systems = ['cannon:local-gpu','cannon:gpu_test','fasse:fasse_gpu','test:gpu'] self.valid_prog...
checks/microbenchmarks/gpu/memory_bandwidth/p2p_bandwidth.py
import reframe.utility.sanity as sn import reframe as rfm @rfm.parameterized_test(['peerAccess'], ['noPeerAccess']) class P2pBandwidthCheck(rfm.RegressionTest): def __init__(self, peerAccess): self.valid_systems = ['cannon:local-gpu','cannon:gpu_test','fasse:fasse_gpu','test:gpu'] self.valid_prog...
0.426799
0.227695
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys if sys.version_info < (2, 7): pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") from ansible.module_utils.basic import AnsibleModule from ansible_collec...
venv/lib/python3.6/site-packages/ansible_collections/f5networks/f5_modules/tests/unit/modules/network/f5/test_bigip_dns_cache_resolver.py
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import json import pytest import sys if sys.version_info < (2, 7): pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7") from ansible.module_utils.basic import AnsibleModule from ansible_collec...
0.505859
0.226473
import subprocess from charmhelpers.core import hookenv def generate_selfsigned(keyfile, certfile, keysize="1024", config=None, subject=None, cn=None): """Generate selfsigned SSL key pair You must provide one of the 3 optional arguments: config, subject or cn If more than one is provided the leftmos...
charmhelpers/contrib/ssl/__init__.py
import subprocess from charmhelpers.core import hookenv def generate_selfsigned(keyfile, certfile, keysize="1024", config=None, subject=None, cn=None): """Generate selfsigned SSL key pair You must provide one of the 3 optional arguments: config, subject or cn If more than one is provided the leftmos...
0.518546
0.134349
from __future__ import annotations from homeassistant.components.sensor import ( DEVICE_CLASS_TEMPERATURE, STATE_CLASS_MEASUREMENT, SensorEntity, ) from homeassistant.const import TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistan...
custom_components/senz/sensor.py
from __future__ import annotations from homeassistant.components.sensor import ( DEVICE_CLASS_TEMPERATURE, STATE_CLASS_MEASUREMENT, SensorEntity, ) from homeassistant.const import TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers.entity import DeviceInfo from homeassistan...
0.84572
0.119794
import json class InvalidTypeException(Exception): pass class ConfigField: def __init__(self, name, default, type): self.name = name self.default = default self.type = type self.value = default @property def value(self): return self._value @value.setter ...
modular_conf/fields.py
import json class InvalidTypeException(Exception): pass class ConfigField: def __init__(self, name, default, type): self.name = name self.default = default self.type = type self.value = default @property def value(self): return self._value @value.setter ...
0.652795
0.124719
import argparse from decomp import main as decomp, _str2bool from sample import main as sample from draw import main as draw from vocab import vocab def get_parser(): parser = argparse.ArgumentParser( description= 'tool for analyze (parallel / non-parallel) translation corpus.') subparsers = ...
textprep.py
import argparse from decomp import main as decomp, _str2bool from sample import main as sample from draw import main as draw from vocab import vocab def get_parser(): parser = argparse.ArgumentParser( description= 'tool for analyze (parallel / non-parallel) translation corpus.') subparsers = ...
0.582847
0.081813
import numpy as np import glob import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator import warnings warnings.filterwarnings("ignore") import matplotlib mpl.rcParams.update({ "font.size": 34.0, "axes.titlesize": 34.0, "axes.labelsize": 34.0, ...
output/python/plot_schwarzschild.py
import numpy as np import glob import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator import warnings warnings.filterwarnings("ignore") import matplotlib mpl.rcParams.update({ "font.size": 34.0, "axes.titlesize": 34.0, "axes.labelsize": 34.0, ...
0.402275
0.455441
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import textwrap from twitter.common.confluence import Confluence, ConfluenceError from pants.backend.core.targets.doc import Page from pants.backend.core....
src/python/pants/backend/core/tasks/confluence_publish.py
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import textwrap from twitter.common.confluence import Confluence, ConfluenceError from pants.backend.core.targets.doc import Page from pants.backend.core....
0.44553
0.140013
import tensorflow as tf import numpy as np import base64 from tensorflow.saved_model import simple_save from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.saved_model.signature_def_utils\ import predict_signature_def from tensorflow.python.saved_model.tag_constants impo...
face_detector.py
import tensorflow as tf import numpy as np import base64 from tensorflow.saved_model import simple_save from tensorflow.python.saved_model import builder as saved_model_builder from tensorflow.python.saved_model.signature_def_utils\ import predict_signature_def from tensorflow.python.saved_model.tag_constants impo...
0.681409
0.288964
from . import db from werkzeug.security import generate_password_hash,check_password_hash from flask_login import UserMixin from . import login_manager from datetime import datetime from sqlalchemy import desc @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(UserMi...
app/models.py
from . import db from werkzeug.security import generate_password_hash,check_password_hash from flask_login import UserMixin from . import login_manager from datetime import datetime from sqlalchemy import desc @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(UserMi...
0.418459
0.053428
import json import os import time import threading from collections import namedtuple from types import FunctionType from mindspore import log as logger from mindspore._c_expression import MSContext, ms_ctx_param from mindspore._checkparam import args_type_check, Validator, args_unreset_check from mindspore.parallel._...
mindspore/context.py
import json import os import time import threading from collections import namedtuple from types import FunctionType from mindspore import log as logger from mindspore._c_expression import MSContext, ms_ctx_param from mindspore._checkparam import args_type_check, Validator, args_unreset_check from mindspore.parallel._...
0.667473
0.101456
"""Tests for substrate.""" import dataclasses from absl.testing import absltest from absl.testing import parameterized import dm_env import numpy as np from meltingpot.python import substrate REWARD_SPEC = dm_env.specs.Array(shape=[], dtype=np.float64, name='REWARD') ACTION_SPEC = dm_env.specs.DiscreteArray( nu...
meltingpot/python/substrate_test.py
"""Tests for substrate.""" import dataclasses from absl.testing import absltest from absl.testing import parameterized import dm_env import numpy as np from meltingpot.python import substrate REWARD_SPEC = dm_env.specs.Array(shape=[], dtype=np.float64, name='REWARD') ACTION_SPEC = dm_env.specs.DiscreteArray( nu...
0.641422
0.464112
import sys import numpy as np import matplotlib.pyplot as plt import matplotlib import seaborn as sns PI = 3.1415926535897 def main(): K = int(args[2]) cancer_type_list = load_types(args[1]) cancer_type_num = [] for x in cancer_type_list: File = open('data/data' + args[1] + '_' + x + '.txt', '...
Drawing/draw_alpha.py
import sys import numpy as np import matplotlib.pyplot as plt import matplotlib import seaborn as sns PI = 3.1415926535897 def main(): K = int(args[2]) cancer_type_list = load_types(args[1]) cancer_type_num = [] for x in cancer_type_list: File = open('data/data' + args[1] + '_' + x + '.txt', '...
0.075833
0.28951
import os import xgboost as xgb from time_series_detector.feature import feature_service from time_series_detector.common.tsd_errorcode import * from time_series_detector.common.tsd_common import * MODEL_PATH = os.path.join(os.path.dirname(__file__), '../model/') DEFAULT_MODEL = MODEL_PATH + "xgb_default_model" class...
time_series_detector/algorithm/xgboosting.py
import os import xgboost as xgb from time_series_detector.feature import feature_service from time_series_detector.common.tsd_errorcode import * from time_series_detector.common.tsd_common import * MODEL_PATH = os.path.join(os.path.dirname(__file__), '../model/') DEFAULT_MODEL = MODEL_PATH + "xgb_default_model" class...
0.741112
0.461502
import torch """ checkpoint and state generation """ from ..databases.restarter import Restartable DEFAULT_STRUCTURE_FNAME= 'experiment_structure.pt' def create_state(model,controller,metric_tracker): """ Create an experiment state dictionary. :param model: :param controller: :param metric_tracke...
hippynn/experiment/serialization.py
import torch """ checkpoint and state generation """ from ..databases.restarter import Restartable DEFAULT_STRUCTURE_FNAME= 'experiment_structure.pt' def create_state(model,controller,metric_tracker): """ Create an experiment state dictionary. :param model: :param controller: :param metric_tracke...
0.851459
0.472927
from collections import defaultdict, deque import datetime import logging import threading import weakref import tornado.locks from tornado import gen from .core import CommClosedError from .utils import sync from .protocol.serialize import to_serialize logger = logging.getLogger(__name__) class PubSubSchedulerExt...
distributed/pubsub.py
from collections import defaultdict, deque import datetime import logging import threading import weakref import tornado.locks from tornado import gen from .core import CommClosedError from .utils import sync from .protocol.serialize import to_serialize logger = logging.getLogger(__name__) class PubSubSchedulerExt...
0.487551
0.07971
import itertools from typing import Dict, Iterator, Optional, Tuple, Type, TypeVar, Union from .. import ( SPECIFIED_DIRECTIVES, Directive, EnumType, Field, GraphQLType, InputObjectType, InterfaceType, ListType, NamedType, NonNullType, ObjectType, Schema, UnionType, ...
src/py_gql/schema/differ/__init__.py
import itertools from typing import Dict, Iterator, Optional, Tuple, Type, TypeVar, Union from .. import ( SPECIFIED_DIRECTIVES, Directive, EnumType, Field, GraphQLType, InputObjectType, InterfaceType, ListType, NamedType, NonNullType, ObjectType, Schema, UnionType, ...
0.743727
0.224565
from __future__ import print_function import os import numpy as np import networkx as nx from utils import common_utils def read_graph(dataset, is_weighted, is_directed, num_classes): ''' Reads the graph structure using networkx. # Arguments dataset: Name of the dataset is_weighted: set ...
src/utils/graph_utils.py
from __future__ import print_function import os import numpy as np import networkx as nx from utils import common_utils def read_graph(dataset, is_weighted, is_directed, num_classes): ''' Reads the graph structure using networkx. # Arguments dataset: Name of the dataset is_weighted: set ...
0.743634
0.486027
class InputStream: def __init__(self, _input): self.input = _input self.pos = 0 self.line = 1 self.col = 0 def next(self): ch = self.input[self.pos] self.pos += 1 if ch == '\n': self.line += 1 self.col = 0 else: ...
python/parser.py
class InputStream: def __init__(self, _input): self.input = _input self.pos = 0 self.line = 1 self.col = 0 def next(self): ch = self.input[self.pos] self.pos += 1 if ch == '\n': self.line += 1 self.col = 0 else: ...
0.529263
0.339992
import pytest from bondhon import bijoy_classic def test_swap_kar_location(): assert bijoy_classic.swap_kar_location('আমি') == 'আিম' @pytest.mark.parametrize('given,expected', [ ('১', '1'), ('২', '2'), ('৩', '3'), ('৪', '4'), ('৫', '5'), ('৬', '6'), ('৭', '7'), ('৮', '8'), (...
tests/test_bijoy_from_unicode.py
import pytest from bondhon import bijoy_classic def test_swap_kar_location(): assert bijoy_classic.swap_kar_location('আমি') == 'আিম' @pytest.mark.parametrize('given,expected', [ ('১', '1'), ('২', '2'), ('৩', '3'), ('৪', '4'), ('৫', '5'), ('৬', '6'), ('৭', '7'), ('৮', '8'), (...
0.343562
0.402333
from dash.dependencies import Input, Output # Plotly graph objects to render graph plots import plotly.graph_objects as go import plotly.express as px from plotly.subplots import make_subplots # Import dash html, bootstrap components, and tables for datatables from dash import html import dash_bootstrap_components as...
callbacks.py
from dash.dependencies import Input, Output # Plotly graph objects to render graph plots import plotly.graph_objects as go import plotly.express as px from plotly.subplots import make_subplots # Import dash html, bootstrap components, and tables for datatables from dash import html import dash_bootstrap_components as...
0.711331
0.371707
import datetime from oslo_serialization import jsonutils import six from manila.scheduler import scheduler_options from manila import test class FakeSchedulerOptions(scheduler_options.SchedulerOptions): def __init__(self, last_checked, now, file_old, file_now, data, filedata): super(FakeSchedulerOptions...
manila/tests/scheduler/test_scheduler_options.py
import datetime from oslo_serialization import jsonutils import six from manila.scheduler import scheduler_options from manila import test class FakeSchedulerOptions(scheduler_options.SchedulerOptions): def __init__(self, last_checked, now, file_old, file_now, data, filedata): super(FakeSchedulerOptions...
0.511473
0.3229
from azure.cli.core.commands import CliCommandType def load_command_table(self, _): from azext_diskpool.generated._client_factory import cf_disk_pool diskpool_disk_pool = CliCommandType( operations_tmpl='azext_diskpool.vendored_sdks.storagepool.operations._disk_pools_operations#DiskPoolsOperations' ...
src/diskpool/azext_diskpool/generated/commands.py
from azure.cli.core.commands import CliCommandType def load_command_table(self, _): from azext_diskpool.generated._client_factory import cf_disk_pool diskpool_disk_pool = CliCommandType( operations_tmpl='azext_diskpool.vendored_sdks.storagepool.operations._disk_pools_operations#DiskPoolsOperations' ...
0.442516
0.061904
import tinctest import os from mpp.models import SQLTestCase from tinctest.lib import run_shell_command, local_path, Gpdiff from mpp.lib.PSQL import PSQL MYD = os.path.abspath(os.path.dirname(__file__)) GPHOME = os.environ['GPHOME'] class EnhancedTableFunctionTest(SQLTestCase): """ @description This contai...
src/test/tinc/tincrepo/mpp/gpdb/tests/catalog/schema_topology/test_ST_EnhancedTableFunctionTest.py
import tinctest import os from mpp.models import SQLTestCase from tinctest.lib import run_shell_command, local_path, Gpdiff from mpp.lib.PSQL import PSQL MYD = os.path.abspath(os.path.dirname(__file__)) GPHOME = os.environ['GPHOME'] class EnhancedTableFunctionTest(SQLTestCase): """ @description This contai...
0.296756
0.185246
import argparse import logging import os import sys import OpenSSL import zope.component from letsencrypt import account from letsencrypt import configuration from letsencrypt import constants from letsencrypt import colored_logging from letsencrypt import cli from letsencrypt import client from letsencrypt import cr...
letsencrypt/renewer.py
import argparse import logging import os import sys import OpenSSL import zope.component from letsencrypt import account from letsencrypt import configuration from letsencrypt import constants from letsencrypt import colored_logging from letsencrypt import cli from letsencrypt import client from letsencrypt import cr...
0.309441
0.099426
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability class IfPerfHourlyRemote(RemoteModel): """ This table list out the entries of interface hourly performance. | ``DataSourceID:`` The internal NetMRI identifier for the collector NetMRI that collected this...
infoblox_netmri/api/remote/models/if_perf_hourly_remote.py
from ..remote import RemoteModel from infoblox_netmri.utils.utils import check_api_availability class IfPerfHourlyRemote(RemoteModel): """ This table list out the entries of interface hourly performance. | ``DataSourceID:`` The internal NetMRI identifier for the collector NetMRI that collected this...
0.691289
0.582194
from lark import Lark, Transformer, Tree, Token from collections import namedtuple import typing import json BNF = r''' OCTALDIGIT: "0..7" IDENT: ( "_" )* LETTER ( LETTER | DECIMALDIGIT | "_" )* FULLIDENT: IDENT ( "." IDENT )* MESSAGENAME: IDENT ENUMNAME: IDENT FIELDNAME: IDENT ONEOFNAME: IDENT MAPNAME: IDENT SERVICEN...
protoparser/parser.py
from lark import Lark, Transformer, Tree, Token from collections import namedtuple import typing import json BNF = r''' OCTALDIGIT: "0..7" IDENT: ( "_" )* LETTER ( LETTER | DECIMALDIGIT | "_" )* FULLIDENT: IDENT ( "." IDENT )* MESSAGENAME: IDENT ENUMNAME: IDENT FIELDNAME: IDENT ONEOFNAME: IDENT MAPNAME: IDENT SERVICEN...
0.562297
0.113236
from functools import wraps from itertools import takewhile class Combinators(object): def __init__(self, value): self._value = value def K(self, f, *args, **kwargs): """The Kestrel combinator, invokes a method, and returns the original value""" if callable(f): f(self._va...
combinators.py
from functools import wraps from itertools import takewhile class Combinators(object): def __init__(self, value): self._value = value def K(self, f, *args, **kwargs): """The Kestrel combinator, invokes a method, and returns the original value""" if callable(f): f(self._va...
0.661048
0.227255
"""Generate pynessie docs script.""" import os from pathlib import Path from typing import IO, List, Optional from click import Group from click.testing import CliRunner from pynessie import cli PATH_DOCS = "docs" def generate_docs() -> None: """Generate all the commands docs.""" print("Generating docs.......
python/tools/generate_docs.py
"""Generate pynessie docs script.""" import os from pathlib import Path from typing import IO, List, Optional from click import Group from click.testing import CliRunner from pynessie import cli PATH_DOCS = "docs" def generate_docs() -> None: """Generate all the commands docs.""" print("Generating docs.......
0.778649
0.279122
import numpy as np import matplotlib.pyplot as plt from matplotlib.mlab import csv2rec import scipy.stats.distributions as dist from nitime.timeseries import TimeSeries from nitime import utils import nitime.algorithms as alg import nitime.viz from nitime.viz import drawmatrix_channels from nitime.analysis import Cohe...
doc/examples/multi_taper_coh.py
import numpy as np import matplotlib.pyplot as plt from matplotlib.mlab import csv2rec import scipy.stats.distributions as dist from nitime.timeseries import TimeSeries from nitime import utils import nitime.algorithms as alg import nitime.viz from nitime.viz import drawmatrix_channels from nitime.analysis import Cohe...
0.657209
0.741768
import logging from fvcore.common.config import CfgNode as _CfgNode class CfgNode(_CfgNode): """ The same as `fvcore.common.config.CfgNode`, but different in: 1. Use unsafe yaml loading by default. Note that this may lead to arbitrary code execution: you must not load a config file from untr...
detectron2/config/config.py
import logging from fvcore.common.config import CfgNode as _CfgNode class CfgNode(_CfgNode): """ The same as `fvcore.common.config.CfgNode`, but different in: 1. Use unsafe yaml loading by default. Note that this may lead to arbitrary code execution: you must not load a config file from untr...
0.75101
0.192824
import pytest import pybnesian as pbn from pybnesian import FactorType, Factor def test_factor_type(): lg1 = pbn.LinearGaussianCPD("a", []) lg2 = pbn.LinearGaussianCPD("b", ["a"]) lg3 = pbn.LinearGaussianCPD("c", ["b", "a"]) assert lg1.type() == pbn.LinearGaussianCPDType() assert lg1.type() == lg2...
tests/factors/factor_type_test.py
import pytest import pybnesian as pbn from pybnesian import FactorType, Factor def test_factor_type(): lg1 = pbn.LinearGaussianCPD("a", []) lg2 = pbn.LinearGaussianCPD("b", ["a"]) lg3 = pbn.LinearGaussianCPD("c", ["b", "a"]) assert lg1.type() == pbn.LinearGaussianCPDType() assert lg1.type() == lg2...
0.79166
0.844697
import argparse import os import re import glob import shutil import subprocess as sp from tempfile import TemporaryDirectory from contextlib import contextmanager # YAML imports try: import yaml # PyYAML loader = yaml.load except ImportError: try: import ruamel_yaml as yaml # Ruamel YAML exce...
devtools/scripts/create_conda_env.py
import argparse import os import re import glob import shutil import subprocess as sp from tempfile import TemporaryDirectory from contextlib import contextmanager # YAML imports try: import yaml # PyYAML loader = yaml.load except ImportError: try: import ruamel_yaml as yaml # Ruamel YAML exce...
0.446495
0.114567
from hashlib import sha512 from openprocurement.api.utils import ( json_view, APIResource, save_tender, ROUTE_PREFIX, context_unpack ) from openprocurement.tender.openeu.utils import qualifications_resource from openprocurement.relocation.api.utils import ( extract_transfer, update_ownership, sa...
openprocurement/relocation/api/views/qualification_complaint.py
from hashlib import sha512 from openprocurement.api.utils import ( json_view, APIResource, save_tender, ROUTE_PREFIX, context_unpack ) from openprocurement.tender.openeu.utils import qualifications_resource from openprocurement.relocation.api.utils import ( extract_transfer, update_ownership, sa...
0.388038
0.106784
import os import platform import shutil import typer import flybirds.template as template import flybirds.utils.flybirds_log as log from flybirds.utils.file_helper import get_files_from_dir, \ get_paths_from_dir, \ replace_file_content, update, update_json_data from flybirds.utils.pkg_helper import find_packa...
flybirds/cli/create_project.py
import os import platform import shutil import typer import flybirds.template as template import flybirds.utils.flybirds_log as log from flybirds.utils.file_helper import get_files_from_dir, \ get_paths_from_dir, \ replace_file_content, update, update_json_data from flybirds.utils.pkg_helper import find_packa...
0.160595
0.077553
from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import os import re import librosa from magenta.models.onsets_frames_transcription import create_dataset_util from magenta.music import audio_io from magenta.music import midi_io from magenta.music...
magenta/models/onsets_frames_transcription/onsets_frames_transcription_create_dataset.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import os import re import librosa from magenta.models.onsets_frames_transcription import create_dataset_util from magenta.music import audio_io from magenta.music import midi_io from magenta.music...
0.727685
0.124745
from __future__ import absolute_import, print_function import tensorflow as tf from tensorflow.contrib.layers.python.layers import regularizers from niftynet.network.vnet import VNet from tests.niftynet_testcase import NiftyNetTestCase class VNetTest(NiftyNetTestCase): def test_3d_shape(self): input_sha...
tests/vnet_test.py
from __future__ import absolute_import, print_function import tensorflow as tf from tensorflow.contrib.layers.python.layers import regularizers from niftynet.network.vnet import VNet from tests.niftynet_testcase import NiftyNetTestCase class VNetTest(NiftyNetTestCase): def test_3d_shape(self): input_sha...
0.537527
0.253503
import os import os.path as op from subprocess import check_output from six.moves import urllib from zipfile import ZipFile import tarfile import logging from math import log, ceil import time import sys import shutil import tempfile import ftplib from functools import partial from tqdm import tqdm if sys.version_info...
python/download/download.py
import os import os.path as op from subprocess import check_output from six.moves import urllib from zipfile import ZipFile import tarfile import logging from math import log, ceil import time import sys import shutil import tempfile import ftplib from functools import partial from tqdm import tqdm if sys.version_info...
0.451327
0.22595
import os import sys import pandas as pd import numpy as np from sklearn.decomposition import IncrementalPCA, PCA import random import pickle import matplotlib.pyplot as plt import time from multiprocessing import Process, Manager import subprocess # input_path = "/shares/perception-temp/voxceleb2/facemesh/train/" # o...
bert/preprocess/convert_pca.py
import os import sys import pandas as pd import numpy as np from sklearn.decomposition import IncrementalPCA, PCA import random import pickle import matplotlib.pyplot as plt import time from multiprocessing import Process, Manager import subprocess # input_path = "/shares/perception-temp/voxceleb2/facemesh/train/" # o...
0.252016
0.189427
import dbutils import htmlutils import page.utils def renderSearch(req, db, user): summary_value = req.getParameter("summary", None) summary_mode_value = req.getParameter("summarymode", None) branch_value = req.getParameter("branch", None) owner_value = req.getParameter("owner", None) path_value =...
page/search.py
import dbutils import htmlutils import page.utils def renderSearch(req, db, user): summary_value = req.getParameter("summary", None) summary_mode_value = req.getParameter("summarymode", None) branch_value = req.getParameter("branch", None) owner_value = req.getParameter("owner", None) path_value =...
0.352425
0.064212
import discord import os import traceback import sys from discord.ext import commands from utils import usefull # Based off of https://github.com/AlexFlipnote/discord_bot.py/blob/master/utils/permissions.py owners = [os.getenv("OWNER_ID")] c = usefull.colors def is_owner(ctx): return ctx.author.id in owners # Cus...
utils/permissions.py
import discord import os import traceback import sys from discord.ext import commands from utils import usefull # Based off of https://github.com/AlexFlipnote/discord_bot.py/blob/master/utils/permissions.py owners = [os.getenv("OWNER_ID")] c = usefull.colors def is_owner(ctx): return ctx.author.id in owners # Cus...
0.371707
0.258891
import json import sys import unittest from contextlib import contextmanager if sys.version_info[0] < 3: from StringIO import StringIO else: from io import StringIO from mock import patch from auth0_client.Auth0Client import Auth0Client as class_to_test @contextmanager def captured_output(): new_out, new...
test/test_rules_config.py
import json import sys import unittest from contextlib import contextmanager if sys.version_info[0] < 3: from StringIO import StringIO else: from io import StringIO from mock import patch from auth0_client.Auth0Client import Auth0Client as class_to_test @contextmanager def captured_output(): new_out, new...
0.14069
0.065485
from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.event import listens_for from indico.core.db import db from indico.core.db.sqlalchemy import PyIntEnum from indico.core.db.sqlalchemy.descriptions import DescriptionMixin, RenderMode from indico.modules.events.surveys.fields import get_field_types from ...
indico/modules/events/surveys/models/items.py
from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.event import listens_for from indico.core.db import db from indico.core.db.sqlalchemy import PyIntEnum from indico.core.db.sqlalchemy.descriptions import DescriptionMixin, RenderMode from indico.modules.events.surveys.fields import get_field_types from ...
0.743447
0.138753
import logging import torch class Client(object): """Simulated federated learning client.""" def __init__(self, client_id): self.client_id = client_id def __repr__(self): return 'Client #{}: {} samples in labels: {}'.format( self.client_id, len(self.data), set([label for _, l...
simulation/client.py
import logging import torch class Client(object): """Simulated federated learning client.""" def __init__(self, client_id): self.client_id = client_id def __repr__(self): return 'Client #{}: {} samples in labels: {}'.format( self.client_id, len(self.data), set([label for _, l...
0.741861
0.243294
"""Library of compiler functions for usage in the native execution context.""" from absl import logging from tensorflow_federated.python.core.api import computation_base from tensorflow_federated.python.core.impl import computation_impl from tensorflow_federated.python.core.impl.compiler import building_blocks from t...
tensorflow_federated/python/core/backends/native/compiler.py
"""Library of compiler functions for usage in the native execution context.""" from absl import logging from tensorflow_federated.python.core.api import computation_base from tensorflow_federated.python.core.impl import computation_impl from tensorflow_federated.python.core.impl.compiler import building_blocks from t...
0.955569
0.520435
from collections import Counter from pathlib import Path from random import Random from typing import List, Tuple, Iterable import tqdm from dp.model.model import ModelType from dp.preprocessing.text import Preprocessor from dp.utils.io import read_config, pickle_binary from dp.utils.logging import get_logger logger...
dp/preprocess.py
from collections import Counter from pathlib import Path from random import Random from typing import List, Tuple, Iterable import tqdm from dp.model.model import ModelType from dp.preprocessing.text import Preprocessor from dp.utils.io import read_config, pickle_binary from dp.utils.logging import get_logger logger...
0.829181
0.383786
import os.path as osp from datasets.roidb import Roidb from datasets.refer import Refer from opt import parse_opt import json import io opt = parse_opt() opt = vars(opt) class Refvg(object): def __init__(self, split, model_method): self._dataset = 'refvg' self._imageset = 'vg' self._spli...
lib/datasets/refvg.py
import os.path as osp from datasets.roidb import Roidb from datasets.refer import Refer from opt import parse_opt import json import io opt = parse_opt() opt = vars(opt) class Refvg(object): def __init__(self, split, model_method): self._dataset = 'refvg' self._imageset = 'vg' self._spli...
0.548915
0.275094
import asyncio import logging import voluptuous as vol from aiohttp import web from homeassistant.components.climate import ATTR_CURRENT_TEMPERATURE from homeassistant.components.http import HomeAssistantView from homeassistant.const import ( EVENT_STATE_CHANGED, TEMP_FAHRENHEIT, CONTENT_TYPE_TEXT_PLAIN, ATTR...
homeassistant/components/prometheus.py
import asyncio import logging import voluptuous as vol from aiohttp import web from homeassistant.components.climate import ATTR_CURRENT_TEMPERATURE from homeassistant.components.http import HomeAssistantView from homeassistant.const import ( EVENT_STATE_CHANGED, TEMP_FAHRENHEIT, CONTENT_TYPE_TEXT_PLAIN, ATTR...
0.609059
0.122078
from time import time, sleep from datetime import datetime, timezone, timedelta import json import re import random import configparser import telegram from telegram.error import NetworkError, Unauthorized import cotoha class TelegramBot: def __init__(self): self.REPLY_SETTINGS = './reply.json'...
autoreply.py
from time import time, sleep from datetime import datetime, timezone, timedelta import json import re import random import configparser import telegram from telegram.error import NetworkError, Unauthorized import cotoha class TelegramBot: def __init__(self): self.REPLY_SETTINGS = './reply.json'...
0.285571
0.042029
import typing from typing import List, Optional from uuid import UUID from marshmallow import fields from commercetools import schemas, types from commercetools.services import abstract from commercetools.typing import OptionalListStr __all__ = ["ProductService"] class ProductDeleteSchema(abstract.AbstractDeleteSc...
src/commercetools/services/products.py
import typing from typing import List, Optional from uuid import UUID from marshmallow import fields from commercetools import schemas, types from commercetools.services import abstract from commercetools.typing import OptionalListStr __all__ = ["ProductService"] class ProductDeleteSchema(abstract.AbstractDeleteSc...
0.791539
0.219819
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from absl import app from absl import flags import absl.logging as _logging # pylint: disable=unused-import import tensorflow as tf import inception_preprocessing import vgg_preprocessin...
models/experimental/inception/inception_v3.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import time from absl import app from absl import flags import absl.logging as _logging # pylint: disable=unused-import import tensorflow as tf import inception_preprocessing import vgg_preprocessin...
0.680772
0.200812
import tensorflow as tf import awesome_gans.modules as t tf.set_random_seed(777) # reproducibility class LSGAN: def __init__( self, s, batch_size=64, height=32, width=32, channel=3, n_classes=10, sample_num=10 * 10, sample_size=10, ...
awesome_gans/lsgan/lsgan_model.py
import tensorflow as tf import awesome_gans.modules as t tf.set_random_seed(777) # reproducibility class LSGAN: def __init__( self, s, batch_size=64, height=32, width=32, channel=3, n_classes=10, sample_num=10 * 10, sample_size=10, ...
0.845113
0.328826
import numpy as np import acl import atlas_utils.utils as utils from atlas_utils.acl_image import AclImage from atlas_utils.acl_logger import log_error, log_info from atlas_utils.resource_list import resource_list import atlas_utils.constants as constants class Dvpp(object): """ dvpp class """ def _...
3_inference/code/src/atlas_utils/acl_dvpp.py
import numpy as np import acl import atlas_utils.utils as utils from atlas_utils.acl_image import AclImage from atlas_utils.acl_logger import log_error, log_info from atlas_utils.resource_list import resource_list import atlas_utils.constants as constants class Dvpp(object): """ dvpp class """ def _...
0.683102
0.117623
from numpy import ndarray from livia.input.FrameInput import FrameInput from livia.output.FrameOutput import FrameOutput from livia.process.FrameProcessor import FrameProcessor from livia.process.analyzer.FrameAnalyzer import FrameAnalyzer from livia.process.analyzer.listener.FrameAnalyzerChangeEvent import FrameAnaly...
livia/process/analyzer/AnalyzerFrameProcessor.py
from numpy import ndarray from livia.input.FrameInput import FrameInput from livia.output.FrameOutput import FrameOutput from livia.process.FrameProcessor import FrameProcessor from livia.process.analyzer.FrameAnalyzer import FrameAnalyzer from livia.process.analyzer.listener.FrameAnalyzerChangeEvent import FrameAnaly...
0.768863
0.280358
from contextlib import suppress from urllib.parse import quote, urljoin import pytz from django.conf import settings from django.shortcuts import get_object_or_404, redirect, reverse from django.urls import resolve from django.utils import timezone, translation from django.utils.translation.trans_real import ( get...
src/pretalx/common/middleware/event.py
from contextlib import suppress from urllib.parse import quote, urljoin import pytz from django.conf import settings from django.shortcuts import get_object_or_404, redirect, reverse from django.urls import resolve from django.utils import timezone, translation from django.utils.translation.trans_real import ( get...
0.563858
0.089614
import unittest import shutil import os import logging import pxelinux_cfg import network_manager import hw_node logging.basicConfig(format='%(asctime)s | %(name)s | %(message)s', level=logging.DEBUG) tftp_cfg_dir = '/tmp/tftp' pxelinux_cfg_dir = '/tmp/tftp/pxelinux_cfg' class PxelinuxCfgTest(un...
test/test_pxelinux_cfg.py
import unittest import shutil import os import logging import pxelinux_cfg import network_manager import hw_node logging.basicConfig(format='%(asctime)s | %(name)s | %(message)s', level=logging.DEBUG) tftp_cfg_dir = '/tmp/tftp' pxelinux_cfg_dir = '/tmp/tftp/pxelinux_cfg' class PxelinuxCfgTest(un...
0.122839
0.158467
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) 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_in...
cmdb_sdk/api/instance/search_total_pb2.py
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) 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_in...
0.257952
0.111895
from __future__ import unicode_literals from snapshottest import GenericRepr, Snapshot snapshots = Snapshot() snapshots['TestCreate.test[uvloop-none] 1'] = { 'all_read': True, 'all_write': True, 'created_at': '2015-10-06T20:00:00Z', 'files': [ { 'id': 'test.fq' } ], ...
tests/samples/snapshots/snap_test_api.py
from __future__ import unicode_literals from snapshottest import GenericRepr, Snapshot snapshots = Snapshot() snapshots['TestCreate.test[uvloop-none] 1'] = { 'all_read': True, 'all_write': True, 'created_at': '2015-10-06T20:00:00Z', 'files': [ { 'id': 'test.fq' } ], ...
0.411111
0.22213
import shutil from typing import Mapping, Tuple, Optional from rlbot.parsing.bot_config_bundle import BotConfigBundle from rlbot.setup_manager import setup_manager_context from rlbot.training.training import Fail from rlbottraining.exercise_runner import run_playlist, RenderPolicy from bots import BotID from match im...
autoleague/match_runner.py
import shutil from typing import Mapping, Tuple, Optional from rlbot.parsing.bot_config_bundle import BotConfigBundle from rlbot.setup_manager import setup_manager_context from rlbot.training.training import Fail from rlbottraining.exercise_runner import run_playlist, RenderPolicy from bots import BotID from match im...
0.68215
0.242834
import Queue import logging import traceback import threading import pprint import os import ambari_simplejson as json import time from AgentException import AgentException from LiveStatus import LiveStatus from ActualConfigHandler import ActualConfigHandler from CommandStatusDict import CommandStatusDict from Custom...
ambari-agent/src/main/python/ambari_agent/ActionQueue.py
import Queue import logging import traceback import threading import pprint import os import ambari_simplejson as json import time from AgentException import AgentException from LiveStatus import LiveStatus from ActualConfigHandler import ActualConfigHandler from CommandStatusDict import CommandStatusDict from Custom...
0.25618
0.045058
import random import numpy as np from sklearn.model_selection import train_test_split def get_square(img, pos): """Extract a left or a right square from ndarray shape : (H, W, C))""" h = img.shape[0] if pos == 0: return img[:, :h] else: return img[:, -h:] def split_img_into_squares(img...
models/unet/utils/utils.py
import random import numpy as np from sklearn.model_selection import train_test_split def get_square(img, pos): """Extract a left or a right square from ndarray shape : (H, W, C))""" h = img.shape[0] if pos == 0: return img[:, :h] else: return img[:, -h:] def split_img_into_squares(img...
0.664214
0.491029
import numpy as np import matplotlib.pyplot as plt from .. import fig_to_dict from numpy.testing import assert_equal def test_line(): fig, ax = plt.subplots() ax.plot(np.arange(10), np.random.random(10), '--k', alpha=0.3, zorder=10, lw=2) rep = fig_to_dict(fig) axrep = rep['axes'][0] l...
mpld3/tests/test_elements.py
import numpy as np import matplotlib.pyplot as plt from .. import fig_to_dict from numpy.testing import assert_equal def test_line(): fig, ax = plt.subplots() ax.plot(np.arange(10), np.random.random(10), '--k', alpha=0.3, zorder=10, lw=2) rep = fig_to_dict(fig) axrep = rep['axes'][0] l...
0.649245
0.786848
import unittest import os import json from io import open import warnings from pymatgen.electronic_structure.bandstructure import Kpoint from pymatgen import Lattice from pymatgen.electronic_structure.core import Spin, Orbital from pymatgen.io.vasp import BSVasprun from pymatgen.electronic_structure.bandstructure im...
pymatgen/electronic_structure/tests/test_bandstructure.py
import unittest import os import json from io import open import warnings from pymatgen.electronic_structure.bandstructure import Kpoint from pymatgen import Lattice from pymatgen.electronic_structure.core import Spin, Orbital from pymatgen.io.vasp import BSVasprun from pymatgen.electronic_structure.bandstructure im...
0.557845
0.570271
import requests import sys import urllib.parse class StreamCamel: def __fetch(self, url): max_retry = 3 attempt = 1 while True: try: print("Fetch URL: {}".format(url)) r = requests.get(url = url, timeout=10) break excep...
streamcamel.py
import requests import sys import urllib.parse class StreamCamel: def __fetch(self, url): max_retry = 3 attempt = 1 while True: try: print("Fetch URL: {}".format(url)) r = requests.get(url = url, timeout=10) break excep...
0.262464
0.089654
# Import Python libs import logging import time logger = logging.getLogger(__name__) logging.getLogger('boto').setLevel(logging.INFO) # Import third party libs try: import boto import boto.dynamodb2 from boto.dynamodb2.fields import HashKey, RangeKey from boto.dynamodb2.fields import AllIndex, GlobalA...
salt/modules/boto_dynamodb.py
# Import Python libs import logging import time logger = logging.getLogger(__name__) logging.getLogger('boto').setLevel(logging.INFO) # Import third party libs try: import boto import boto.dynamodb2 from boto.dynamodb2.fields import HashKey, RangeKey from boto.dynamodb2.fields import AllIndex, GlobalA...
0.396419
0.113826
import numpy as np import re import csv class Data(object): """ Class to handle loading and processing of raw datasets. """ def __init__(self, data_source, alphabet="abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\"/\\|_@#$%^&*~`+-=<>()[]{}", input_size=1014, num_of_clas...
data_utils.py
import numpy as np import re import csv class Data(object): """ Class to handle loading and processing of raw datasets. """ def __init__(self, data_source, alphabet="abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\"/\\|_@#$%^&*~`+-=<>()[]{}", input_size=1014, num_of_clas...
0.84556
0.489626
import logging from typing import TYPE_CHECKING, Tuple from synapse.api.errors import Codes, ShadowBanError, SynapseError from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.http.server import HttpServer from synapse.http.servlet import ( RestServlet, assert_params_in_dict, parse_json_o...
synapse/rest/client/room_upgrade_rest_servlet.py
import logging from typing import TYPE_CHECKING, Tuple from synapse.api.errors import Codes, ShadowBanError, SynapseError from synapse.api.room_versions import KNOWN_ROOM_VERSIONS from synapse.http.server import HttpServer from synapse.http.servlet import ( RestServlet, assert_params_in_dict, parse_json_o...
0.652795
0.133105
# vim: tabstop=4 shiftwidth=4 softtabstop=4 import unittest import logging from nose.tools import * from ryu.base import app_manager from ryu.controller import ofp_event from ryu.controller.handler import ( set_ev_cls, MAIN_DISPATCHER, ) from ryu.lib.packet import vlan, ethernet, ipv4 from ryu.lib.ofp_pktin...
ryu/tests/unit/lib/test_ofp_pktinfilter.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 import unittest import logging from nose.tools import * from ryu.base import app_manager from ryu.controller import ofp_event from ryu.controller.handler import ( set_ev_cls, MAIN_DISPATCHER, ) from ryu.lib.packet import vlan, ethernet, ipv4 from ryu.lib.ofp_pktin...
0.494873
0.117243
import os from contextlib import contextmanager from funcy import get_in from dvc.exceptions import DvcException class SCMError(DvcException): """Base class for source control management errors.""" class FileNotInRepoError(SCMError): """Thrown when trying to find .gitignore for a file that is not in a sc...
dvc/scm/base.py
import os from contextlib import contextmanager from funcy import get_in from dvc.exceptions import DvcException class SCMError(DvcException): """Base class for source control management errors.""" class FileNotInRepoError(SCMError): """Thrown when trying to find .gitignore for a file that is not in a sc...
0.867219
0.101947
import os from ruamel import yaml import great_expectations as ge from great_expectations.core.batch import BatchRequest context = ge.get_context() datasource_yaml = f""" name: taxi_datasource class_name: Datasource module_name: great_expectations.datasource execution_engine: module_name: great_expectations.execu...
tests/integration/docusaurus/connecting_to_your_data/how_to_introspect_and_partition_your_data/files/yaml_example.py
import os from ruamel import yaml import great_expectations as ge from great_expectations.core.batch import BatchRequest context = ge.get_context() datasource_yaml = f""" name: taxi_datasource class_name: Datasource module_name: great_expectations.datasource execution_engine: module_name: great_expectations.execu...
0.624637
0.420838
from __future__ import unicode_literals # Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import time import json import boto3 from botocore.exceptions import ClientError import sure # noqa from moto import mock_ec2, mock_iam, mock_cloudformation def quick_instance_creation(): imag...
tests/test_ec2/test_iam_instance_profile_associations.py
from __future__ import unicode_literals # Ensure 'pytest.raises' context manager support for Python 2.6 import pytest import time import json import boto3 from botocore.exceptions import ClientError import sure # noqa from moto import mock_ec2, mock_iam, mock_cloudformation def quick_instance_creation(): imag...
0.606615
0.137619
import sys, os, os.path, re __all__ = ['require'] _top = os.path.dirname(os.path.abspath(os.path.normpath(__file__))) _pkg_cache = None _import_cache = {} _pat = re.compile('^([a-z]+)-([0-9]+).([0-9]+)$') def _load_pkg_cache(): global _pkg_cache if _pkg_cache is not None: return _pkg_cache _pkg_...
python/pkgloader.py
import sys, os, os.path, re __all__ = ['require'] _top = os.path.dirname(os.path.abspath(os.path.normpath(__file__))) _pkg_cache = None _import_cache = {} _pat = re.compile('^([a-z]+)-([0-9]+).([0-9]+)$') def _load_pkg_cache(): global _pkg_cache if _pkg_cache is not None: return _pkg_cache _pkg_...
0.098285
0.072538
import os from datetime import datetime, timedelta import numpy def salishseacast_paths(timestart, timeend, path, filetype): """Generate paths for Salish Seacast forcing :arg timestart: date from when to start concatenating :type string: :py:class:'str' :arg timeend: date at which to stop concatena...
scripts/make-hdf5/forcing_paths.py
import os from datetime import datetime, timedelta import numpy def salishseacast_paths(timestart, timeend, path, filetype): """Generate paths for Salish Seacast forcing :arg timestart: date from when to start concatenating :type string: :py:class:'str' :arg timeend: date at which to stop concatena...
0.647464
0.480235
import numpy as np from sklearn.preprocessing import MaxAbsScaler, MinMaxScaler from sklearn.preprocessing import RobustScaler, StandardScaler from ..algebra.onnx_ops import OnnxSub, OnnxDiv, OnnxCast from ..common._registration import register_converter from ..common.data_types import guess_numpy_type, guess_proto_t...
skl2onnx/operator_converters/scaler_op.py
import numpy as np from sklearn.preprocessing import MaxAbsScaler, MinMaxScaler from sklearn.preprocessing import RobustScaler, StandardScaler from ..algebra.onnx_ops import OnnxSub, OnnxDiv, OnnxCast from ..common._registration import register_converter from ..common.data_types import guess_numpy_type, guess_proto_t...
0.709019
0.262529
import numpy as np from scipy.optimize import curve_fit def sigmoid_fxn(x, b, r, m): """x can be a single value or a numpy array of x_values; b is the steepness; r is the max y_value of the curve; m is the x_value where the curve is at 50% height. The equation has been constrained such that the lower y_bound is al...
navargator_resources/curve_fitting.py
import numpy as np from scipy.optimize import curve_fit def sigmoid_fxn(x, b, r, m): """x can be a single value or a numpy array of x_values; b is the steepness; r is the max y_value of the curve; m is the x_value where the curve is at 50% height. The equation has been constrained such that the lower y_bound is al...
0.836988
0.771801
from typing import Optional, Tuple import torch import torch.nn as nn from kornia.testing import KORNIA_CHECK_SHAPE def match_nn( desc1: torch.Tensor, desc2: torch.Tensor, dm: Optional[torch.Tensor] = None ) -> Tuple[torch.Tensor, torch.Tensor]: r"""Function, which finds nearest neighbors in desc2 for each ...
kornia/feature/matching.py
from typing import Optional, Tuple import torch import torch.nn as nn from kornia.testing import KORNIA_CHECK_SHAPE def match_nn( desc1: torch.Tensor, desc2: torch.Tensor, dm: Optional[torch.Tensor] = None ) -> Tuple[torch.Tensor, torch.Tensor]: r"""Function, which finds nearest neighbors in desc2 for each ...
0.967884
0.782496
from django.core.management.base import BaseCommand, CommandError from api.models import Subject, Course, Campus import xml.etree.ElementTree as ET import os class Command(BaseCommand): help = 'Populates the subjects table' def handle(self, *args, **options): dirr = os.path.dirname(__file__) f...
api/management/commands/populatedb.py
from django.core.management.base import BaseCommand, CommandError from api.models import Subject, Course, Campus import xml.etree.ElementTree as ET import os class Command(BaseCommand): help = 'Populates the subjects table' def handle(self, *args, **options): dirr = os.path.dirname(__file__) f...
0.257765
0.10725
import json import numpy as np from collections import OrderedDict from src.evaluation.summary_loader import load_processed_dataset import seaborn as sns import matplotlib.pyplot as plt import pandas as pd sns.set() sns.set_style("darkgrid") videos = {} x_axis = [] y_axis = [] original_splits = '../../results/TVSum...
src/visualization/visualize_fscores_differences.py
import json import numpy as np from collections import OrderedDict from src.evaluation.summary_loader import load_processed_dataset import seaborn as sns import matplotlib.pyplot as plt import pandas as pd sns.set() sns.set_style("darkgrid") videos = {} x_axis = [] y_axis = [] original_splits = '../../results/TVSum...
0.22093
0.3217
from . import epanet2 from .objectcollection import ObjectCollection from .baseobject import BaseObject, lazy_property from .pattern import Pattern class Node(BaseObject): """ Base EPANET Node class """ static_properties = {'elevation': epanet2.EN_ELEVATION} properties = {'head': epanet2.EN_HEAD, 'pressur...
epynet/node.py
from . import epanet2 from .objectcollection import ObjectCollection from .baseobject import BaseObject, lazy_property from .pattern import Pattern class Node(BaseObject): """ Base EPANET Node class """ static_properties = {'elevation': epanet2.EN_ELEVATION} properties = {'head': epanet2.EN_HEAD, 'pressur...
0.722037
0.207014
import re import mindspore.nn as nn from mindspore import context from mindspore.ops import operations as P from mindspore.ops import functional as F from mindspore.ops import composite as C from mindspore.common.tensor import Tensor from mindspore.common import dtype as mstype from mindspore.common.parameter import Pa...
model_zoo/official/nlp/tinybert/src/tinybert_for_gd_td.py
import re import mindspore.nn as nn from mindspore import context from mindspore.ops import operations as P from mindspore.ops import functional as F from mindspore.ops import composite as C from mindspore.common.tensor import Tensor from mindspore.common import dtype as mstype from mindspore.common.parameter import Pa...
0.859251
0.328099
import netmiko # configure command line arguements import argparse parser=argparse.ArgumentParser(description='Switch on and off preconfigured edge router firewall rules from command line') parser.add_argument('-t', '--target', type=str, metavar='', required=False, help='The user being targeted') group = parser.add_mu...
build/lib/venv/fireControlPkg/fireControl.py
import netmiko # configure command line arguements import argparse parser=argparse.ArgumentParser(description='Switch on and off preconfigured edge router firewall rules from command line') parser.add_argument('-t', '--target', type=str, metavar='', required=False, help='The user being targeted') group = parser.add_mu...
0.270769
0.108472
"""Builder function for image resizing operations.""" import functools import tensorflow.compat.v1 as tf from object_detection.core import preprocessor from object_detection.protos import image_resizer_pb2 def _tf_resize_method(resize_method): """Maps image resize method from enumeration type to TensorFlow. Arg...
src/object_detection/builders/image_resizer_builder.py
"""Builder function for image resizing operations.""" import functools import tensorflow.compat.v1 as tf from object_detection.core import preprocessor from object_detection.protos import image_resizer_pb2 def _tf_resize_method(resize_method): """Maps image resize method from enumeration type to TensorFlow. Arg...
0.946782
0.436922
from parglare import Parser, Grammar from utils.rvs.expressions import RVFuncs ### Production rules for outer expressions, inner expressions, and events expression_terminals = r""" variable: /[#]?[a-zA-Z_$][a-zA-Z_$0-9]*/; number: /\d+(\.\d+)?/; """ expression_productions = r""" expr : term | expr '+' term | ...
Python/utils/rvs/parser.py
from parglare import Parser, Grammar from utils.rvs.expressions import RVFuncs ### Production rules for outer expressions, inner expressions, and events expression_terminals = r""" variable: /[#]?[a-zA-Z_$][a-zA-Z_$0-9]*/; number: /\d+(\.\d+)?/; """ expression_productions = r""" expr : term | expr '+' term | ...
0.355775
0.544922
import sys import os import glob import datetime import time import yaml from functools import cmp_to_key from optparse import OptionParser from urllib.parse import urlparse, urljoin from util import CONFIG_YML, \ STANDARD_YML, \ AIRPORTS_YML, \ BADGES_YML, \ ...
bin/preprocess.py
import sys import os import glob import datetime import time import yaml from functools import cmp_to_key from optparse import OptionParser from urllib.parse import urlparse, urljoin from util import CONFIG_YML, \ STANDARD_YML, \ AIRPORTS_YML, \ BADGES_YML, \ ...
0.391406
0.140189
import os import sys import json import pygal import re import urllib.request USER = os.popen('cat ./_user.db').read() # Create _user.db with your username inside PASS = os.popen('cat ./_pass.db').read() # Create _pass.db with your password inside SVCGRP ...
api_example_python.py
import os import sys import json import pygal import re import urllib.request USER = os.popen('cat ./_user.db').read() # Create _user.db with your username inside PASS = os.popen('cat ./_pass.db').read() # Create _pass.db with your password inside SVCGRP ...
0.211906
0.051774
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Provider' db.create_table('activitysync_provider', ( ('name', self.gf('django.db.models.fields.C...
activitysync/migrations/0002_auto__add_provider__add_field_activity_provider.py
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Provider' db.create_table('activitysync_provider', ( ('name', self.gf('django.db.models.fields.C...
0.353428
0.073897
from __future__ import print_function import numpy as np from wisdem.commonse.utilities import nodal2sectional import openmdao.api as om class CylindricalShellProperties(om.ExplicitComponent): """ OpenMDAO wrapper for tube class to obtain cylindrical sheel properties. Parameters ---------- d : nu...
wisdem/commonse/cross_sections.py
from __future__ import print_function import numpy as np from wisdem.commonse.utilities import nodal2sectional import openmdao.api as om class CylindricalShellProperties(om.ExplicitComponent): """ OpenMDAO wrapper for tube class to obtain cylindrical sheel properties. Parameters ---------- d : nu...
0.918475
0.467332
import os import re from testrunner.local import testsuite from testrunner.objects import testcase ANY_JS = ".any.js" WPT_ROOT = "/wasm/jsapi/" META_SCRIPT_REGEXP = re.compile(r"META:\s*script=(.*)") META_TIMEOUT_REGEXP = re.compile(r"META:\s*timeout=(.*)") proposal_flags = [{ 'name': 'js-types'...
test/wasm-js/testcfg.py
import os import re from testrunner.local import testsuite from testrunner.objects import testcase ANY_JS = ".any.js" WPT_ROOT = "/wasm/jsapi/" META_SCRIPT_REGEXP = re.compile(r"META:\s*script=(.*)") META_TIMEOUT_REGEXP = re.compile(r"META:\s*timeout=(.*)") proposal_flags = [{ 'name': 'js-types'...
0.444565
0.126111
import unittest from collections import OrderedDict import numpy as np from test_util import GenArgList, type_name_to_flow_type import oneflow as flow import oneflow.unittest from oneflow.test_utils.automated_test_util import * def _test_argsort(test_case, data_shape, axis, descending, data_type, device): inpu...
python/oneflow/test/modules/test_argsort.py
import unittest from collections import OrderedDict import numpy as np from test_util import GenArgList, type_name_to_flow_type import oneflow as flow import oneflow.unittest from oneflow.test_utils.automated_test_util import * def _test_argsort(test_case, data_shape, axis, descending, data_type, device): inpu...
0.54359
0.665302
import re class MetaOperation(type): """ Metaclasse qui permet l'enregistrement de tous les classes qui héritent de la classe Operation. À noter qu'il faut les importer avant MetaOperation pour qu'elles soient disponibles dans le registre """ registry = {} def __new__(cls, clsname, bases...
simulation/kanban.py
import re class MetaOperation(type): """ Metaclasse qui permet l'enregistrement de tous les classes qui héritent de la classe Operation. À noter qu'il faut les importer avant MetaOperation pour qu'elles soient disponibles dans le registre """ registry = {} def __new__(cls, clsname, bases...
0.274838
0.166641
# Export this package's modules as members: from ._enums import * from .afd_custom_domain import * from .afd_endpoint import * from .afd_origin import * from .afd_origin_group import * from .custom_domain import * from .endpoint import * from .get_afd_custom_domain import * from .get_afd_endpoint import * from .get_af...
sdk/python/pulumi_azure_native/cdn/v20200901/__init__.py
# Export this package's modules as members: from ._enums import * from .afd_custom_domain import * from .afd_endpoint import * from .afd_origin import * from .afd_origin_group import * from .custom_domain import * from .endpoint import * from .get_afd_custom_domain import * from .get_afd_endpoint import * from .get_af...
0.399577
0.042842
from collections import OrderedDict import pytest from pandas.util._validators import validate_args_and_kwargs _fname = "func" def test_invalid_total_length_max_length_one(): compat_args = ("foo",) kwargs = {"foo": "FOO"} args = ("FoO", "BaZ") min_fname_arg_count = 0 max_length = len(compat_ar...
pandas/tests/util/test_validate_args_and_kwargs.py
from collections import OrderedDict import pytest from pandas.util._validators import validate_args_and_kwargs _fname = "func" def test_invalid_total_length_max_length_one(): compat_args = ("foo",) kwargs = {"foo": "FOO"} args = ("FoO", "BaZ") min_fname_arg_count = 0 max_length = len(compat_ar...
0.703957
0.313906
import tifffile import tqdm import os import numpy as np import sys from scandir import scandir from multiprocessing import Pool def split_image(img, psplit, add_bg): img_int = img.astype(int) img_int[img_int<0] = 0 return np.random.binomial(img_int, psplit) + np.random.poisson(add_bg*psplit,size=img.sha...
python/utils/tiff_split_signal_photons.py
import tifffile import tqdm import os import numpy as np import sys from scandir import scandir from multiprocessing import Pool def split_image(img, psplit, add_bg): img_int = img.astype(int) img_int[img_int<0] = 0 return np.random.binomial(img_int, psplit) + np.random.poisson(add_bg*psplit,size=img.sha...
0.138491
0.157234
import sys from pathlib import Path from unittest import TestCase import pytest import yaml from click.testing import CliRunner from peekingduck.cli import cli DEFAULT_NODES = ["input.visual", "model.yolo", "draw.bbox", "output.screen"] GOOD_SUBDIR = "custom_nodes" GOOD_TYPE = "dabble" GOOD_NAME = "name" PROJECT_DI...
tests/cli/test_cli_create_node.py
import sys from pathlib import Path from unittest import TestCase import pytest import yaml from click.testing import CliRunner from peekingduck.cli import cli DEFAULT_NODES = ["input.visual", "model.yolo", "draw.bbox", "output.screen"] GOOD_SUBDIR = "custom_nodes" GOOD_TYPE = "dabble" GOOD_NAME = "name" PROJECT_DI...
0.322099
0.212732
import urllib3 import json import nb_log import decorator_libs # https://www.cnblogs.com/YrRoom/p/14054282.html """ -p 18083 服务器启动端口 -p 1882 TCP端口 -p 8083 WS端口 -p 8084 WSS端口 -p 8883 SSL端口 """ """ 非常适合 前端订阅唯一uuid的topic 然后表单中带上这个topic名字请求python接口 -> 接口中发布任务到rabbitmq或redis消息队列 -> 后台消费进程执行任务消费,并将结果发布到mqtt的那个唯一uuid的topic...
funboost/utils/mqtt_util.py
import urllib3 import json import nb_log import decorator_libs # https://www.cnblogs.com/YrRoom/p/14054282.html """ -p 18083 服务器启动端口 -p 1882 TCP端口 -p 8083 WS端口 -p 8084 WSS端口 -p 8883 SSL端口 """ """ 非常适合 前端订阅唯一uuid的topic 然后表单中带上这个topic名字请求python接口 -> 接口中发布任务到rabbitmq或redis消息队列 -> 后台消费进程执行任务消费,并将结果发布到mqtt的那个唯一uuid的topic...
0.199308
0.124612
import subprocess from unittest.mock import MagicMock import pytest from briefcase.exceptions import BriefcaseCommandError, InvalidDeviceError from briefcase.integrations.android_sdk import ADB def test_force_stop_app(mock_sdk, capsys): """Invoking `force_stop_app()` calls `run()` with the appropriate param...
tests/integrations/android_sdk/ADB/test_force_stop_app.py
import subprocess from unittest.mock import MagicMock import pytest from briefcase.exceptions import BriefcaseCommandError, InvalidDeviceError from briefcase.integrations.android_sdk import ADB def test_force_stop_app(mock_sdk, capsys): """Invoking `force_stop_app()` calls `run()` with the appropriate param...
0.823683
0.350505
import argparse import sys import Cerbrutus banner = """ \t================================================================ \t __ ___ ____ ____ ____ __ __ ______ __ __ _____ \t / ] / _]| \ | \ | \| | || || | |/ ___/ \t / / / [_ | D )| o )| D ) | || || | ...
cerbrutus.py
import argparse import sys import Cerbrutus banner = """ \t================================================================ \t __ ___ ____ ____ ____ __ __ ______ __ __ _____ \t / ] / _]| \ | \ | \| | || || | |/ ___/ \t / / / [_ | D )| o )| D ) | || || | ...
0.13569
0.150809