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
from ..Framework.SuperResolution import SuperResolution from ..Arch.Residual import msrb import tensorflow as tf def _normalize(inputs): rgb_mean = (0.4488, 0.4371, 0.4040) return inputs / 255 - rgb_mean def _denormalize(inputs): rgb_mean = (0.4488, 0.4371, 0.4040) return (inputs + rgb_mean) * 255 ...
VLLV/Models/Msrn.py
from ..Framework.SuperResolution import SuperResolution from ..Arch.Residual import msrb import tensorflow as tf def _normalize(inputs): rgb_mean = (0.4488, 0.4371, 0.4040) return inputs / 255 - rgb_mean def _denormalize(inputs): rgb_mean = (0.4488, 0.4371, 0.4040) return (inputs + rgb_mean) * 255 ...
0.75401
0.224331
import sys from .node import Node from .Fila import Queue class RB_Tree: def __init__(self): self.TNULL = Node(0) self.TNULL.color = 0 self.TNULL.left = None self.TNULL.right = None self.root = self.TNULL def insert(self, key): node = Node(key) node.p...
AVL/Rubro_Negra_Tree/RB_Tree.py
import sys from .node import Node from .Fila import Queue class RB_Tree: def __init__(self): self.TNULL = Node(0) self.TNULL.color = 0 self.TNULL.left = None self.TNULL.right = None self.root = self.TNULL def insert(self, key): node = Node(key) node.p...
0.325735
0.34443
import os from textwrap import dedent envs = { "api_token": os.getenv("TELEGRAM_API_TOKEN"), "devs": os.getenv("LOG_RECIPIENTS", "").split(","), "asap_freq": int(os.getenv("ASAP_UPDATE_FREQ", 5 * 60)), "pkl_location": os.getenv("BOT_DATA", ".") } strings = { "welcome": dedent("""\ Welcome...
localconfig.py
import os from textwrap import dedent envs = { "api_token": os.getenv("TELEGRAM_API_TOKEN"), "devs": os.getenv("LOG_RECIPIENTS", "").split(","), "asap_freq": int(os.getenv("ASAP_UPDATE_FREQ", 5 * 60)), "pkl_location": os.getenv("BOT_DATA", ".") } strings = { "welcome": dedent("""\ Welcome...
0.378689
0.279945
## Imports from __future__ import annotations from abc import ABC, abstractmethod from enum import IntEnum, auto from typing import Any, TextIO ## Classes class NodeBase(ABC): """AST Base Node""" # -Instance Methods @abstractmethod def compile(self, file: TextIO) -> None: '''Compile the ...
ember/frontend/node.py
## Imports from __future__ import annotations from abc import ABC, abstractmethod from enum import IntEnum, auto from typing import Any, TextIO ## Classes class NodeBase(ABC): """AST Base Node""" # -Instance Methods @abstractmethod def compile(self, file: TextIO) -> None: '''Compile the ...
0.772659
0.227126
from typing import List from tqdm.auto import tqdm from nemo.collections.asr.models.ctc_models import EncDecCTCModel from nemo.utils import logging def transcribe_partial_audio( asr_model, path2manifest: str, batch_size: int = 4, logprobs: bool = False, return_hypotheses: bool = False, num_w...
nemo/collections/asr/parts/utils/transcribe_utils.py
from typing import List from tqdm.auto import tqdm from nemo.collections.asr.models.ctc_models import EncDecCTCModel from nemo.utils import logging def transcribe_partial_audio( asr_model, path2manifest: str, batch_size: int = 4, logprobs: bool = False, return_hypotheses: bool = False, num_w...
0.857768
0.396769
from typing import Dict import numpy as np import scipy import tensorflow as tf from core import BaseDataSource, BaseModel from datasources import UnityEyes import util.gaze class DPG(BaseModel): """Deep Pictorial Gaze architecture as introduced in [Park et al. ECCV'18].""" def __init__(self, tensorflow_se...
src/models/dpg.py
from typing import Dict import numpy as np import scipy import tensorflow as tf from core import BaseDataSource, BaseModel from datasources import UnityEyes import util.gaze class DPG(BaseModel): """Deep Pictorial Gaze architecture as introduced in [Park et al. ECCV'18].""" def __init__(self, tensorflow_se...
0.868465
0.278863
import pprint import re # noqa: F401 import six class PerOperationLimitConstantResponse(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attrib...
tmapi/models/per_operation_limit_constant_response.py
import pprint import re # noqa: F401 import six class PerOperationLimitConstantResponse(object): """NOTE: This class is auto generated by OpenAPI Generator. Ref: https://openapi-generator.tech Do not edit the class manually. """ """ Attributes: openapi_types (dict): The key is attrib...
0.822011
0.090414
import numpy as np import pyarrow from katana import ( OrderedByIntegerMetric, UserContext, do_all, do_all_operator, for_each, for_each_operator, obim_metric, set_active_threads, ) from katana.local import Graph, ReduceMax, ReduceSum, atomic_min from katana.local.datastructures import I...
python/test/lonestar/sssp.py
import numpy as np import pyarrow from katana import ( OrderedByIntegerMetric, UserContext, do_all, do_all_operator, for_each, for_each_operator, obim_metric, set_active_threads, ) from katana.local import Graph, ReduceMax, ReduceSum, atomic_min from katana.local.datastructures import I...
0.233095
0.333639
from dataclasses import dataclass from pants.backend.python.target_types import PythonSourceField from pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints from pants.backend.python.util_rules.pex_environment import PythonExecutable from pants.core.util_rules.source_files import Sourc...
src/python/pants/backend/python/dependency_inference/import_parser.py
from dataclasses import dataclass from pants.backend.python.target_types import PythonSourceField from pants.backend.python.util_rules.interpreter_constraints import InterpreterConstraints from pants.backend.python.util_rules.pex_environment import PythonExecutable from pants.core.util_rules.source_files import Sourc...
0.558809
0.175927
try: from mock import MagicMock, patch has_mock = True except ImportError: has_mock = False patch = lambda x: lambda y: None from saltunittest import TestCase, skipIf from salt.modules import pip pip.__salt__ = {"cmd.which_bin":lambda _:"pip"} @skipIf(has_mock is False, "mock python module is unavail...
tests/unit/modules/pip_test.py
try: from mock import MagicMock, patch has_mock = True except ImportError: has_mock = False patch = lambda x: lambda y: None from saltunittest import TestCase, skipIf from salt.modules import pip pip.__salt__ = {"cmd.which_bin":lambda _:"pip"} @skipIf(has_mock is False, "mock python module is unavail...
0.518059
0.159414
from alerta.models.alert import Alert from alerta.webhooks import WebhookBase import json class AzureMonitorWebhook(WebhookBase): def incoming(self, query_string, payload): # Environment is not avaible in the payload, use request param. try: environment = query_string['enviro...
webhooks/azuremonitor/alerta_azuremonitor.py
from alerta.models.alert import Alert from alerta.webhooks import WebhookBase import json class AzureMonitorWebhook(WebhookBase): def incoming(self, query_string, payload): # Environment is not avaible in the payload, use request param. try: environment = query_string['enviro...
0.317638
0.125199
import pytz import json from tzlocal import get_localzone from datetime import datetime, timedelta from django.core import serializers from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from orchestrator.models import * def redirect_overview(request): return re...
automation_orchestrator/dashboard/views.py
import pytz import json from tzlocal import get_localzone from datetime import datetime, timedelta from django.core import serializers from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from orchestrator.models import * def redirect_overview(request): return re...
0.375134
0.20951
import pytest from os.path import join from numpy import zeros, exp, pi, real, meshgrid, mean from multiprocessing import cpu_count from numpy.testing import assert_array_almost_equal from SciDataTool import DataTime, VectorField, Data1D import csv import numpy as np import matplotlib.pyplot as plt from pyleecan.Clas...
Tests/Validation/Force/test_ForceTensor.py
import pytest from os.path import join from numpy import zeros, exp, pi, real, meshgrid, mean from multiprocessing import cpu_count from numpy.testing import assert_array_almost_equal from SciDataTool import DataTime, VectorField, Data1D import csv import numpy as np import matplotlib.pyplot as plt from pyleecan.Clas...
0.588534
0.55652
"""Client used or interacting with our language identification api""" import json from .generic_api_client import GenericApiClient from .models import LanguageIdentificationJob, LanguageIdentificationResult try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin class Language...
src/rev_ai/language_identification_client.py
"""Client used or interacting with our language identification api""" import json from .generic_api_client import GenericApiClient from .models import LanguageIdentificationJob, LanguageIdentificationResult try: from urllib.parse import urljoin except ImportError: from urlparse import urljoin class Language...
0.881398
0.136292
import time import unittest from hashlib import sha1, sha256 as sha2 from rnglib import SimpleRNG from xlcrypto import XLFilterError from xlcrypto.filters import CountingBloom, KeySelector RNG = SimpleRNG(time.time()) class TestCountingBloom(unittest.TestCase): """ Exercise the CountingBloom filter. """ de...
tests/test_counting_bloom.py
import time import unittest from hashlib import sha1, sha256 as sha2 from rnglib import SimpleRNG from xlcrypto import XLFilterError from xlcrypto.filters import CountingBloom, KeySelector RNG = SimpleRNG(time.time()) class TestCountingBloom(unittest.TestCase): """ Exercise the CountingBloom filter. """ de...
0.36659
0.474388
import threading from datetime import datetime from azure.iot.device import IoTHubModuleClient import json import logging class ListenThread(threading.Thread): def __init__(self, infer_cache): super().__init__() self.infer_cache = infer_cache self.daemon = True self.module_client = ...
deploy/edge/http-cpu/app/listen_thread.py
import threading from datetime import datetime from azure.iot.device import IoTHubModuleClient import json import logging class ListenThread(threading.Thread): def __init__(self, infer_cache): super().__init__() self.infer_cache = infer_cache self.daemon = True self.module_client = ...
0.354992
0.110208
import os import numpy as np from .base_dataset import BaseDataset from ltr.data.image_loader import default_image_loader import xml.etree.ElementTree as ET import glob import json from collections import OrderedDict import nltk from nltk.corpus import wordnet from ltr.admin.environment import env_settings class Imag...
PaddleCV/tracking/ltr/dataset/imagenetdet.py
import os import numpy as np from .base_dataset import BaseDataset from ltr.data.image_loader import default_image_loader import xml.etree.ElementTree as ET import glob import json from collections import OrderedDict import nltk from nltk.corpus import wordnet from ltr.admin.environment import env_settings class Imag...
0.618204
0.215021
import os import pickle import tqdm import pandas as pd from data_setting import * def F1_score(detected_communities, ground_truth_communities): precision = calculate_precision(detected_communities, ground_truth_communities) recall = calculate_recall(detected_communities, ground_truth_communities) if pre...
evaluate_community.py
import os import pickle import tqdm import pandas as pd from data_setting import * def F1_score(detected_communities, ground_truth_communities): precision = calculate_precision(detected_communities, ground_truth_communities) recall = calculate_recall(detected_communities, ground_truth_communities) if pre...
0.341253
0.300771
import six from ecl.tests.functional import base class TestOperation(base.BaseFunctionalTest): @classmethod def setUpClass(cls): super(TestOperation, cls).setUpClass() mcics = list(cls.conn.connectivity.mcics()) cls.one_mcic = None cls.one_operation = None cls.one_c...
ecl/tests/functional/connectivity/v1/test_operation.py
import six from ecl.tests.functional import base class TestOperation(base.BaseFunctionalTest): @classmethod def setUpClass(cls): super(TestOperation, cls).setUpClass() mcics = list(cls.conn.connectivity.mcics()) cls.one_mcic = None cls.one_operation = None cls.one_c...
0.323166
0.317916
import chainer import torch from e2e_asr_attctc_th import torch_is_old import lm_chainer import lm_pytorch def transfer_lstm(ch_lstm, th_lstm): ch_lstm.upward.W.data[:] = 1 th_lstm.weight_ih.data[:] = torch.from_numpy(ch_lstm.upward.W.data) ch_lstm.upward.b.data[:] = 1 th_lstm.bias_hh.data[:] = torch...
test/test_lm.py
import chainer import torch from e2e_asr_attctc_th import torch_is_old import lm_chainer import lm_pytorch def transfer_lstm(ch_lstm, th_lstm): ch_lstm.upward.W.data[:] = 1 th_lstm.weight_ih.data[:] = torch.from_numpy(ch_lstm.upward.W.data) ch_lstm.upward.b.data[:] = 1 th_lstm.bias_hh.data[:] = torch...
0.564219
0.454048
import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt import os import sys import argparse import glob import re from collections import OrderedDict # Import global variables SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR)) from g...
train/plot_training_progress.py
import matplotlib matplotlib.use('Agg') import numpy as np import matplotlib.pyplot as plt import os import sys import argparse import glob import re from collections import OrderedDict # Import global variables SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR)) from g...
0.545044
0.371564
import argparse import pylab as pl import neurom as nm from neurom.io.utils import get_morph_files def parse_args(): '''Parse command line arguments''' parser = argparse.ArgumentParser(description='Feature Comparison Between Different Cells') parser.add_argument('-d', '--datapath...
examples/features_graph_table.py
import argparse import pylab as pl import neurom as nm from neurom.io.utils import get_morph_files def parse_args(): '''Parse command line arguments''' parser = argparse.ArgumentParser(description='Feature Comparison Between Different Cells') parser.add_argument('-d', '--datapath...
0.705379
0.349366
import nltk import argparse import pickle from collections import Counter import string import os import os.path as osp from data_utils import get_karpathy_split, get_refcoco_captions from vocab import Vocabulary def build_vocab(caption_list, threshold): """Build a simple vocabulary wrapper.""" vocab = Voca...
build_vocab.py
import nltk import argparse import pickle from collections import Counter import string import os import os.path as osp from data_utils import get_karpathy_split, get_refcoco_captions from vocab import Vocabulary def build_vocab(caption_list, threshold): """Build a simple vocabulary wrapper.""" vocab = Voca...
0.479747
0.166269
# Part of the PsychoPy library # Copyright (C) 2002-2018 <NAME> (C) 2019-2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import os import subprocess import sys import wx from psychopy.app.colorpicker import PsychoColorPicker from psychopy.app.dialogs import ListWi...
venv/Lib/site-packages/psychopy/app/builder/dialogs/paramCtrls.py
# Part of the PsychoPy library # Copyright (C) 2002-2018 <NAME> (C) 2019-2021 Open Science Tools Ltd. # Distributed under the terms of the GNU General Public License (GPL). import os import subprocess import sys import wx from psychopy.app.colorpicker import PsychoColorPicker from psychopy.app.dialogs import ListWi...
0.558688
0.110208
#-------------------- # System wide imports # ------------------- from __future__ import generators # needs to be at the top of your module import os import os.path import sys import argparse import sqlite3 import os import os.path import datetime as Datetime # Access template withing the package from pkg_res...
tdbtool/s4a.py
#-------------------- # System wide imports # ------------------- from __future__ import generators # needs to be at the top of your module import os import os.path import sys import argparse import sqlite3 import os import os.path import datetime as Datetime # Access template withing the package from pkg_res...
0.358915
0.10026
import re from collections import namedtuple from .utils import sort_callbacks Message = namedtuple( "Message", "text attachments from_id peer_id date raw_update" ) Message.__doc__ = """ Text message with possible attachments. :param text: text message of update :param attachments: tuple of instances of :...
kutana/plugin.py
import re from collections import namedtuple from .utils import sort_callbacks Message = namedtuple( "Message", "text attachments from_id peer_id date raw_update" ) Message.__doc__ = """ Text message with possible attachments. :param text: text message of update :param attachments: tuple of instances of :...
0.852414
0.214537
import json import csv import os import sqlite3 as db from openpyxl import Workbook #mencari home direktori def home(): """cari alamat HOME""" if os.name == 'nt': try: result = os.path.join(os.environ["HOMEPATH"], "My Documents") except Exception: result =...
absensi/output.py
import json import csv import os import sqlite3 as db from openpyxl import Workbook #mencari home direktori def home(): """cari alamat HOME""" if os.name == 'nt': try: result = os.path.join(os.environ["HOMEPATH"], "My Documents") except Exception: result =...
0.105821
0.081228
import numpy as np from .base_fitter import BaseFitter, reload_scans from .results import FitResult, FitResultSeries from ..models import DefaultTrainedModel from ..xrrloader import FioLoader, NotReflectivityScanError class FioFitter(BaseFitter): @property def file_stem(self): return self._file_name...
mlreflect/curve_fitter/fio_fitter.py
import numpy as np from .base_fitter import BaseFitter, reload_scans from .results import FitResult, FitResultSeries from ..models import DefaultTrainedModel from ..xrrloader import FioLoader, NotReflectivityScanError class FioFitter(BaseFitter): @property def file_stem(self): return self._file_name...
0.872761
0.527012
from __future__ import absolute_import from __future__ import division from __future__ import print_function import io import os import urllib import zipfile import numpy as np import pandas from sklearn import preprocessing def load_synthetic_data(data_name, dict_no, seed=0): """Generates synthetic datasets. T...
rllim/data_loading.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import io import os import urllib import zipfile import numpy as np import pandas from sklearn import preprocessing def load_synthetic_data(data_name, dict_no, seed=0): """Generates synthetic datasets. T...
0.727007
0.394434
from __future__ import absolute_import as _ import os import re import datetime from inquirer import prompt, Text, List, Checkbox from .config import get_config_file from .licenses import LICENSES from .classifiers import PLATFORMS from .changelog import get_changelog_content from .manifest import get_manifest_content...
pystart/cmd.py
from __future__ import absolute_import as _ import os import re import datetime from inquirer import prompt, Text, List, Checkbox from .config import get_config_file from .licenses import LICENSES from .classifiers import PLATFORMS from .changelog import get_changelog_content from .manifest import get_manifest_content...
0.443841
0.056783
load( "//configs/dependency-tracking:ubuntu1604.bzl", BAZEL_LATEST = "bazel", ) load( "//rules/rbe_repo:build_gen.bzl", "create_alias_platform", "create_config_aliases", "create_export_platform", "create_external_repo_platform", "create_java_runtime", ) load( "//rules/rbe_repo:checke...
rules/rbe_repo.bzl
load( "//configs/dependency-tracking:ubuntu1604.bzl", BAZEL_LATEST = "bazel", ) load( "//rules/rbe_repo:build_gen.bzl", "create_alias_platform", "create_config_aliases", "create_export_platform", "create_external_repo_platform", "create_java_runtime", ) load( "//rules/rbe_repo:checke...
0.40439
0.12932
import unittest import unicodedata from cltk.corpus.middle_high_german.alphabet import normalize_middle_high_german from cltk.stem.middle_high_german.stem import stemmer_middle_high_german as middle_high_german_stemmer from cltk.stop.middle_high_german.stops import STOPS_LIST as MIDDLE_HIGH_GERMAN_STOPS from cltk.pho...
cltk/tests/test_test_middle_high_german.py
import unittest import unicodedata from cltk.corpus.middle_high_german.alphabet import normalize_middle_high_german from cltk.stem.middle_high_german.stem import stemmer_middle_high_german as middle_high_german_stemmer from cltk.stop.middle_high_german.stops import STOPS_LIST as MIDDLE_HIGH_GERMAN_STOPS from cltk.pho...
0.530966
0.377426
from osgeo import gdal import rasterio from affine import Affine import numpy as np import logging from ..utils.raster import reorder_axes from ..utils.log import _get_logging_level import os def get_geo_transform(raster_src): """Get the geotransform for a raster image source. Arguments --------- ras...
solaris/raster/image.py
from osgeo import gdal import rasterio from affine import Affine import numpy as np import logging from ..utils.raster import reorder_axes from ..utils.log import _get_logging_level import os def get_geo_transform(raster_src): """Get the geotransform for a raster image source. Arguments --------- ras...
0.86342
0.534916
import sys from subprocess import Popen PORT = 7531 if sys.version_info[0] < 3: # python 2 import BaseHTTPServer import urlparse class CompatibilityMixin: def send_body(self, msg): self.wfile.write(msg+'\n') self.wfile.close() else: # python 3 import http.server as B...
play_with_mpv.py
import sys from subprocess import Popen PORT = 7531 if sys.version_info[0] < 3: # python 2 import BaseHTTPServer import urlparse class CompatibilityMixin: def send_body(self, msg): self.wfile.write(msg+'\n') self.wfile.close() else: # python 3 import http.server as B...
0.186539
0.051797
import pytest import numpy as np from . import variables from .variables import wrap_arg def test_softmax_categorical_deterministic() -> None: token = variables.SoftmaxCategorical(["blu", "blublu", "blublublu"], deterministic=True) assert token.data_to_arguments([1, 1, 1.01], deterministic=False) == wrap_arg...
nevergrad/instrumentation/test_variables.py
import pytest import numpy as np from . import variables from .variables import wrap_arg def test_softmax_categorical_deterministic() -> None: token = variables.SoftmaxCategorical(["blu", "blublu", "blublublu"], deterministic=True) assert token.data_to_arguments([1, 1, 1.01], deterministic=False) == wrap_arg...
0.7324
0.708414
from telemetry.value import scalar from metrics import memory from metrics import Metric class SystemMemoryMetric(Metric): """SystemMemoryMetric gathers system memory statistic. This metric collects system memory stats per test. It reports the difference (delta) in system memory starts from the start of the...
tools/perf/metrics/system_memory.py
from telemetry.value import scalar from metrics import memory from metrics import Metric class SystemMemoryMetric(Metric): """SystemMemoryMetric gathers system memory statistic. This metric collects system memory stats per test. It reports the difference (delta) in system memory starts from the start of the...
0.93086
0.516656
import numpy as np from numpy.testing import assert_allclose import openpnm as op class TransientFickianDiffusionTest: def setup_class(self): np.random.seed(0) self.net = op.network.Cubic(shape=[4, 3, 1], spacing=1.0) self.geo = op.geometry.GenericGeometry(network=self.net, ...
tests/unit/algorithms/TransientFickianDiffusionTest.py
import numpy as np from numpy.testing import assert_allclose import openpnm as op class TransientFickianDiffusionTest: def setup_class(self): np.random.seed(0) self.net = op.network.Cubic(shape=[4, 3, 1], spacing=1.0) self.geo = op.geometry.GenericGeometry(network=self.net, ...
0.600774
0.478407
from . import util IMAGES = { # Used to build Flutter_Android in Debian9, since the underlying build # scripts require jdk8. 'Debian9': ( 'gcr.io/skia-public/debian9@sha256:' '5541f5674eee0a1558f1335c711f674f85f96b9ae8fb6c289f42dd81479a768e'), } def compile_fn(api, checkout_root, out_dir)...
infra/bots/recipe_modules/build/flutter.py
from . import util IMAGES = { # Used to build Flutter_Android in Debian9, since the underlying build # scripts require jdk8. 'Debian9': ( 'gcr.io/skia-public/debian9@sha256:' '5541f5674eee0a1558f1335c711f674f85f96b9ae8fb6c289f42dd81479a768e'), } def compile_fn(api, checkout_root, out_dir)...
0.381104
0.081739
import numpy as np def pointless_sort(x): """ This function always returns the same values to show how testing works, check out the `test/test_alg.py` file to see. """ return np.array([1,2,3]) def insertionsort(x): """ input: insertsion sort takes in a list or numpy array output: retur...
scripts/algs.py
import numpy as np def pointless_sort(x): """ This function always returns the same values to show how testing works, check out the `test/test_alg.py` file to see. """ return np.array([1,2,3]) def insertionsort(x): """ input: insertsion sort takes in a list or numpy array output: retur...
0.542863
0.846514
import unittest import numpy as np from io import BytesIO import h5py from exetera.core import session from exetera.core import fields from exetera.core import dataframe from exetera.core import persistence as per from exetera.core import utils from exetera.core import field_importers as fi class TestCreateThenLoa...
tests/test_session.py
import unittest import numpy as np from io import BytesIO import h5py from exetera.core import session from exetera.core import fields from exetera.core import dataframe from exetera.core import persistence as per from exetera.core import utils from exetera.core import field_importers as fi class TestCreateThenLoa...
0.524882
0.50769
import types from googlecloudsdk.api_lib.test import arg_file from googlecloudsdk.api_lib.test import arg_validate from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.core import log def AddCommonTestRunArgs(parser): """Register args which are common to all 'gcloud test run' commands. Args: ...
google-cloud-sdk/.install/.backup/lib/googlecloudsdk/api_lib/test/arg_util.py
import types from googlecloudsdk.api_lib.test import arg_file from googlecloudsdk.api_lib.test import arg_validate from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.core import log def AddCommonTestRunArgs(parser): """Register args which are common to all 'gcloud test run' commands. Args: ...
0.606964
0.147832
import logging from e2e.utils.cognito_bootstrap import common from e2e.utils.aws.acm import AcmCertificate from e2e.utils.aws.cognito import CustomDomainCognitoUserPool from e2e.utils.aws.route53 import Route53HostedZone from e2e.utils.utils import print_banner, load_yaml_file from e2e.utils.load_balancer.lb_resources...
tests/e2e/utils/cognito_bootstrap/cognito_resources_cleanup.py
import logging from e2e.utils.cognito_bootstrap import common from e2e.utils.aws.acm import AcmCertificate from e2e.utils.aws.cognito import CustomDomainCognitoUserPool from e2e.utils.aws.route53 import Route53HostedZone from e2e.utils.utils import print_banner, load_yaml_file from e2e.utils.load_balancer.lb_resources...
0.300643
0.08389
VERSION_PROCESSING = 3 VERSION_METADATA = 'beta' VERSION = "0.4.1-{m}".format(m=VERSION_METADATA) __author__ = "<NAME>" __copyright__ = "Copyright 2017, The Regents of the University of California, through Lawrence Berkeley National Laboratory" __credits__ = ["<NAME> <<EMAIL>>", "<NAME> <<EMAIL>>", ...
oneflux/__init__.py
VERSION_PROCESSING = 3 VERSION_METADATA = 'beta' VERSION = "0.4.1-{m}".format(m=VERSION_METADATA) __author__ = "<NAME>" __copyright__ = "Copyright 2017, The Regents of the University of California, through Lawrence Berkeley National Laboratory" __credits__ = ["<NAME> <<EMAIL>>", "<NAME> <<EMAIL>>", ...
0.301156
0.070752
from PWGJE.EMCALJetTasks.Tracks.analysis.base.Graphics import TwoPanelPlot, GraphicsObject, Style, Frame from PWGJE.EMCALJetTasks.Tracks.analysis.base.SpectrumFitter import SpectrumFitter from PWGJE.EMCALJetTasks.Tracks.analysis.base.DataCollection import DataCollection, Datapoint from copy import deepcopy from ROOT im...
PWGJE/EMCALJetTasks/Tracks/analysis/plots/TrackYieldEventPlot.py
from PWGJE.EMCALJetTasks.Tracks.analysis.base.Graphics import TwoPanelPlot, GraphicsObject, Style, Frame from PWGJE.EMCALJetTasks.Tracks.analysis.base.SpectrumFitter import SpectrumFitter from PWGJE.EMCALJetTasks.Tracks.analysis.base.DataCollection import DataCollection, Datapoint from copy import deepcopy from ROOT im...
0.749729
0.252836
import torch.nn as nn from .lightcnn import LightCNN, LowHead from .at import ( ContextBlock, StripPooling, ) def getATModule(at_type): if at_type == 'CB': return ContextBlock if at_type == 'SP': return StripPooling raise NotImplementedError('{} not implemented'.format(at_type)) ...
models/lightcnn_at.py
import torch.nn as nn from .lightcnn import LightCNN, LowHead from .at import ( ContextBlock, StripPooling, ) def getATModule(at_type): if at_type == 'CB': return ContextBlock if at_type == 'SP': return StripPooling raise NotImplementedError('{} not implemented'.format(at_type)) ...
0.883701
0.341802
# General imports import os import numpy as np import cv2 from utils import conv2d from utils import atranspose import torch from models.network_dncnn import DnCNN as net def mace(LR,numagents,c,args): ''' This is a Python implementation of the MACE framework written about in 4D X-Ray CT Reconstruction using...
demos/MDF/utils/maceutils.py
# General imports import os import numpy as np import cv2 from utils import conv2d from utils import atranspose import torch from models.network_dncnn import DnCNN as net def mace(LR,numagents,c,args): ''' This is a Python implementation of the MACE framework written about in 4D X-Ray CT Reconstruction using...
0.526586
0.706524
import os.path from data.base_dataset import BaseDataset from data.image_folder import make_dataset import pandas as pd from util import pose_utils import numpy as np import torch from tqdm import tqdm class HMUBIDataset(BaseDataset): @staticmethod def modify_commandline_options(parser, is_train): pa...
models/Global-Flow-Local-Attention/data/hmubi_dataset.py
import os.path from data.base_dataset import BaseDataset from data.image_folder import make_dataset import pandas as pd from util import pose_utils import numpy as np import torch from tqdm import tqdm class HMUBIDataset(BaseDataset): @staticmethod def modify_commandline_options(parser, is_train): pa...
0.276984
0.115686
from pathlib import Path import dash_core_components as dcc import dash_html_components as html from ...api_doc import ApiDoc from ...helpers import ExampleContainer, HighlightedSource from ...metadata import get_component_metadata from .button import spinners as spinners_button from .grow import spinners as spinners...
docs/components_page/components/spinner/__init__.py
from pathlib import Path import dash_core_components as dcc import dash_html_components as html from ...api_doc import ApiDoc from ...helpers import ExampleContainer, HighlightedSource from ...metadata import get_component_metadata from .button import spinners as spinners_button from .grow import spinners as spinners...
0.754282
0.225566
from .framework import (Framework, Keys, main) from Box2D import (b2EdgeShape, b2FixtureDef, b2PolygonShape, b2_dynamicBody, b2_kinematicBody, b2_staticBody) class BodyTypes(Framework): name = "Body Types" description = "Change body type keys: (d) dynamic, (s) static, (k) kinematic" sp...
examples/body_types.py
from .framework import (Framework, Keys, main) from Box2D import (b2EdgeShape, b2FixtureDef, b2PolygonShape, b2_dynamicBody, b2_kinematicBody, b2_staticBody) class BodyTypes(Framework): name = "Body Types" description = "Change body type keys: (d) dynamic, (s) static, (k) kinematic" sp...
0.756627
0.431105
from twisted.cred import checkers, portal from twisted.test import proto_helpers from twisted.words.protocols import irc from twisted.words.service import InMemoryWordsRealm, IRCFactory, IRCUser from twisted.words.test.test_irc import IRCTestCase class IRCUserTests(IRCTestCase): """ Isolated tests for L{IRCUs...
src/twisted/words/test/test_irc_service.py
from twisted.cred import checkers, portal from twisted.test import proto_helpers from twisted.words.protocols import irc from twisted.words.service import InMemoryWordsRealm, IRCFactory, IRCUser from twisted.words.test.test_irc import IRCTestCase class IRCUserTests(IRCTestCase): """ Isolated tests for L{IRCUs...
0.558086
0.231918
import fastapi import uvicorn from fastapi import status from sqlalchemy.orm import Session from starlette.staticfiles import StaticFiles from db.base import Base from db.crud.allergies import create_allergie from db.crud.cuisine import create_cuisine from db.database import engine from schemes import Allergies from s...
app/main.py
import fastapi import uvicorn from fastapi import status from sqlalchemy.orm import Session from starlette.staticfiles import StaticFiles from db.base import Base from db.crud.allergies import create_allergie from db.crud.cuisine import create_cuisine from db.database import engine from schemes import Allergies from s...
0.604749
0.071559
from discord.ext import commands from disnake.ext import commands as commandsnake import aiohttp from typing import Union import asyncio from .modules import Bots, Servers, Users class BoticordClient: """ This class is used to make it much easier to use the Boticord API. You can pass `lib` parameter to...
boticordpy/client.py
from discord.ext import commands from disnake.ext import commands as commandsnake import aiohttp from typing import Union import asyncio from .modules import Bots, Servers, Users class BoticordClient: """ This class is used to make it much easier to use the Boticord API. You can pass `lib` parameter to...
0.875135
0.182062
import numpy as np from math import sqrt from anim_utils.animation_data.utils import convert_quaternion_frame_to_cartesian_frame, align_point_clouds_2D, transform_point_cloud, calculate_point_cloud_distance from .keyframe_constraint_base import KeyframeConstraintBase from .. import SPATIAL_CONSTRAINT_TYPE_KEYFRAME_POSE...
morphablegraphs/constraints/spatial_constraints/keyframe_constraints/pose_constraint.py
import numpy as np from math import sqrt from anim_utils.animation_data.utils import convert_quaternion_frame_to_cartesian_frame, align_point_clouds_2D, transform_point_cloud, calculate_point_cloud_distance from .keyframe_constraint_base import KeyframeConstraintBase from .. import SPATIAL_CONSTRAINT_TYPE_KEYFRAME_POSE...
0.800809
0.427576
import os import platform import shutil from subprocess import Popen, PIPE from eplaunch.workflows.base import BaseEPLaunchWorkflow1, EPLaunchWorkflowResponse1 class ColumnNames(object): AverageSurfTemp = 'Avg Surf Temp [C]' AmplitudeSurfTemp = 'Amp Surf Temp [C]' PhaseConstant = 'Phase Constant [days]' ...
energyplus/EnergyPlus-9-0-1/workflows/calc_soil_surface_temp.py
import os import platform import shutil from subprocess import Popen, PIPE from eplaunch.workflows.base import BaseEPLaunchWorkflow1, EPLaunchWorkflowResponse1 class ColumnNames(object): AverageSurfTemp = 'Avg Surf Temp [C]' AmplitudeSurfTemp = 'Amp Surf Temp [C]' PhaseConstant = 'Phase Constant [days]' ...
0.297266
0.140749
from __future__ import unicode_literals import codecs import json from ..utils import check_executable, to_str from ..compat import compat_str from subprocess import Popen, PIPE from os.path import join # (mostly joke) wrappers for NodeJS WebSocket packages if check_executable('node', ['-v']) and check_executable(...
yt_dlp/websocket/nodejs.py
from __future__ import unicode_literals import codecs import json from ..utils import check_executable, to_str from ..compat import compat_str from subprocess import Popen, PIPE from os.path import join # (mostly joke) wrappers for NodeJS WebSocket packages if check_executable('node', ['-v']) and check_executable(...
0.389314
0.184272
from billy.scrape import ScrapeError, NoDataForPeriod from billy.scrape.legislators import LegislatorScraper, Legislator from billy.scrape.committees import Committee import lxml.html import re, contextlib HI_BASE_URL = "http://capitol.hawaii.gov" def get_legislator_listing_url(chamber): chamber = {"lower": "...
openstates/openstates-master/openstates/hi/legislators.py
from billy.scrape import ScrapeError, NoDataForPeriod from billy.scrape.legislators import LegislatorScraper, Legislator from billy.scrape.committees import Committee import lxml.html import re, contextlib HI_BASE_URL = "http://capitol.hawaii.gov" def get_legislator_listing_url(chamber): chamber = {"lower": "...
0.225076
0.175874
import numpy as np import pytest from l5kit.data import ( ChunkedDataset, filter_agents_by_frames, filter_agents_by_track_id, get_agents_slice_from_frames, get_frames_slice_from_scenes, get_tl_faces_slice_from_frames, ) @pytest.mark.parametrize("frame_bound", [0, 10, 50, 100]) def test_get_fr...
l5kit/l5kit/tests/data/filter_test.py
import numpy as np import pytest from l5kit.data import ( ChunkedDataset, filter_agents_by_frames, filter_agents_by_track_id, get_agents_slice_from_frames, get_frames_slice_from_scenes, get_tl_faces_slice_from_frames, ) @pytest.mark.parametrize("frame_bound", [0, 10, 50, 100]) def test_get_fr...
0.648689
0.656059
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pants.backend.graph_info.subsystems.cloc_binary import ClocBinary from pants.base.build_environment import get_buildroot from pants.base.exceptions im...
src/python/pants/backend/graph_info/tasks/cloc.py
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pants.backend.graph_info.subsystems.cloc_binary import ClocBinary from pants.base.build_environment import get_buildroot from pants.base.exceptions im...
0.499268
0.098729
import rospy import math import numpy as np from geometry_msgs.msg import Twist, Point, Quaternion from tf.transformations import euler_from_quaternion from gazebo_msgs.msg import LinkStates from geometry_msgs.msg import Pose class MeasureAreaCovered: def __init__(self): self.link_name = 'turtlebot3_burg...
part2/python/measure_coverage.py
import rospy import math import numpy as np from geometry_msgs.msg import Twist, Point, Quaternion from tf.transformations import euler_from_quaternion from gazebo_msgs.msg import LinkStates from geometry_msgs.msg import Pose class MeasureAreaCovered: def __init__(self): self.link_name = 'turtlebot3_burg...
0.5083
0.349935
import json import pygame from drawable import Drawable class Tile(Drawable): COLOR_UNREVEALED = (193, 192, 193) COLOR_REVEALED = (193, 192, 193) COLOR_REVEALED_MINE = (255, 192, 193) MINE_DANGER = 9 # Load indicative 'danger level' colors from external json file with open('json/colors_dang...
tile.py
import json import pygame from drawable import Drawable class Tile(Drawable): COLOR_UNREVEALED = (193, 192, 193) COLOR_REVEALED = (193, 192, 193) COLOR_REVEALED_MINE = (255, 192, 193) MINE_DANGER = 9 # Load indicative 'danger level' colors from external json file with open('json/colors_dang...
0.490236
0.145206
try: import numeric SIMPLEGUICS2PYGAME = False except ImportError: import SimpleGUICS2Pygame.numeric as numeric SIMPLEGUICS2PYGAME = True if SIMPLEGUICS2PYGAME: from sys import version as python_version PYTHON_VERSION = 'Python ' + python_version.split()[0] else: PYTHON_VERSION = 'CodeS...
venv/lib/python2.7/site-packages/SimpleGUICS2Pygame/test/test_numeric.py
try: import numeric SIMPLEGUICS2PYGAME = False except ImportError: import SimpleGUICS2Pygame.numeric as numeric SIMPLEGUICS2PYGAME = True if SIMPLEGUICS2PYGAME: from sys import version as python_version PYTHON_VERSION = 'Python ' + python_version.split()[0] else: PYTHON_VERSION = 'CodeS...
0.394667
0.599133
from __future__ import absolute_import from xml.etree import ElementTree import six.moves.urllib.request, six.moves.urllib.parse, six.moves.urllib.error from . import plexapp from . import plexconnection from . import plexserver from . import myplexrequest from . import callback from . import util class MyPlexManage...
lib/_included_packages/plexnet/myplexmanager.py
from __future__ import absolute_import from xml.etree import ElementTree import six.moves.urllib.request, six.moves.urllib.parse, six.moves.urllib.error from . import plexapp from . import plexconnection from . import plexserver from . import myplexrequest from . import callback from . import util class MyPlexManage...
0.320821
0.046595
import sys import pygame from time import sleep from settings import Settings from ship import Ship from bullet import Bullet from alien import Alien from game_stats import GameStats from button import Button from scoreboard import Scoreboard from difficulty import Difficulty class AlienInvasion: '''docs...
alien_invasion/alien_invasion.py
import sys import pygame from time import sleep from settings import Settings from ship import Ship from bullet import Bullet from alien import Alien from game_stats import GameStats from button import Button from scoreboard import Scoreboard from difficulty import Difficulty class AlienInvasion: '''docs...
0.1151
0.05848
import csv, json, time, collections ds_pass_msg = dict( error_severity='na', error_message='No handle registry errors detected' ) input_dataset_list = 'c3s34g_pids_qcTest_Oct2020.txt' major_error_codes = {'ERROR.ds.0900'} major_error_codes = set() minor_error_codes = {'ERROR.ds.0040'} CHECK_MASKS = False class Jpre...
scripts/jprep_handle.py
import csv, json, time, collections ds_pass_msg = dict( error_severity='na', error_message='No handle registry errors detected' ) input_dataset_list = 'c3s34g_pids_qcTest_Oct2020.txt' major_error_codes = {'ERROR.ds.0900'} major_error_codes = set() minor_error_codes = {'ERROR.ds.0040'} CHECK_MASKS = False class Jpre...
0.112539
0.24335
from watson_developer_cloud import NaturalLanguageUnderstandingV1 from watson_developer_cloud.natural_language_understanding_v1 import \ Features, EntitiesOptions, KeywordsOptions, CategoriesOptions class NLUUtils: """NLUUtils class defines connection to NLU service and provides a way to analyze text sentimen...
cloud/applications/cars-4-you/nlu_utils.py
from watson_developer_cloud import NaturalLanguageUnderstandingV1 from watson_developer_cloud.natural_language_understanding_v1 import \ Features, EntitiesOptions, KeywordsOptions, CategoriesOptions class NLUUtils: """NLUUtils class defines connection to NLU service and provides a way to analyze text sentimen...
0.778397
0.290515
AUTO_STOP=False DATADIR='data' SHORTCUT_PREFIX='s' OUTDIR='render' TASKFN='task.org' BACKLOG='Backlog' STORY_SEPARATOR='/' STATUSES=['REVIEW','DOING','TODO','DONE','DUPE','POSTPONED','CANCELLED', 'PARENT', 'STORAGE'] DONESTATES=['DONE','DUPE','CANCELLED','POSTPONED'] DOINGSTATES=['REVIEW','DOING'] DEFAULT_STATUS='TODO...
config.py
AUTO_STOP=False DATADIR='data' SHORTCUT_PREFIX='s' OUTDIR='render' TASKFN='task.org' BACKLOG='Backlog' STORY_SEPARATOR='/' STATUSES=['REVIEW','DOING','TODO','DONE','DUPE','POSTPONED','CANCELLED', 'PARENT', 'STORAGE'] DONESTATES=['DONE','DUPE','CANCELLED','POSTPONED'] DOINGSTATES=['REVIEW','DOING'] DEFAULT_STATUS='TODO...
0.199932
0.081009
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import time class OneAndOneResources: firewall_policy = 'firewall_policy' load_balancer = 'load_balancer' monitoring_policy = 'monitoring_policy' private_network = 'private_network' public_ip = 'public_ip' ...
Collections-a-installer/community-general-2.4.0/plugins/module_utils/oneandone.py
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import time class OneAndOneResources: firewall_policy = 'firewall_policy' load_balancer = 'load_balancer' monitoring_policy = 'monitoring_policy' private_network = 'private_network' public_ip = 'public_ip' ...
0.688154
0.077797
from datasette import hookimpl import click import json from subprocess import call from .common import ( add_common_publish_arguments_and_options, fail_if_publish_binary_not_installed, ) from ..utils import temporary_docker_directory @hookimpl def publish_subcommand(publish): @publish.command() @add...
datasette/publish/now.py
from datasette import hookimpl import click import json from subprocess import call from .common import ( add_common_publish_arguments_and_options, fail_if_publish_binary_not_installed, ) from ..utils import temporary_docker_directory @hookimpl def publish_subcommand(publish): @publish.command() @add...
0.27338
0.096408
import logging import gobject from datetime import datetime, timedelta # Victron packages from ve_utils import exit_on_error from delegates.base import SystemCalcDelegate # Path constants BLPATH = "/Settings/CGwacs/BatteryLife"; STATE_PATH = BLPATH + "/State"; FLAGS_PATH = BLPATH + "/Flags"; SOC_LIMIT_PATH = BLPATH +...
delegates/batterylife.py
import logging import gobject from datetime import datetime, timedelta # Victron packages from ve_utils import exit_on_error from delegates.base import SystemCalcDelegate # Path constants BLPATH = "/Settings/CGwacs/BatteryLife"; STATE_PATH = BLPATH + "/State"; FLAGS_PATH = BLPATH + "/Flags"; SOC_LIMIT_PATH = BLPATH +...
0.469763
0.15704
from __future__ import print_function import idc import idaapi import idautils import flare_emu tests = {"from MultiByteToWideChar\r\n":["this is a test".encode("utf-16"), 15], "from WideCharToMultiByte\r\n":["this is a test", 15], "truncated MultiByteToWideChar":["this".encode("utf-16"),...
tests/flare_emu_test_hooks.py
from __future__ import print_function import idc import idaapi import idautils import flare_emu tests = {"from MultiByteToWideChar\r\n":["this is a test".encode("utf-16"), 15], "from WideCharToMultiByte\r\n":["this is a test", 15], "truncated MultiByteToWideChar":["this".encode("utf-16"),...
0.293202
0.25678
from tenzing.core.models import tenzing_model, model_relation from tenzing.core.mixins import optionMixin from tenzing.utils import singleton, test_utils from tenzing.core import plotting from tenzing.core.summary import create_frequency_table import os import logging import pandas.api.types as pdt import pandas as pd ...
src/tenzing/core/model_implementations/types.py
from tenzing.core.models import tenzing_model, model_relation from tenzing.core.mixins import optionMixin from tenzing.utils import singleton, test_utils from tenzing.core import plotting from tenzing.core.summary import create_frequency_table import os import logging import pandas.api.types as pdt import pandas as pd ...
0.832407
0.636466
from keras.layers import Input, merge, Dropout, Dense, Lambda, Flatten, Activation from keras.layers.normalization import BatchNormalization from keras.layers.convolutional import MaxPooling2D, Convolution2D, AveragePooling2D from keras.models import Model from keras import backend as K import warnings warnings.filte...
inception_resnet_v1.py
from keras.layers import Input, merge, Dropout, Dense, Lambda, Flatten, Activation from keras.layers.normalization import BatchNormalization from keras.layers.convolutional import MaxPooling2D, Convolution2D, AveragePooling2D from keras.models import Model from keras import backend as K import warnings warnings.filte...
0.946287
0.685581
import sys import cv2 import numpy as np from PyQt4 import QtGui, QtCore, Qt from ui import Ui_MainWindow class Video(): def __init__(self,capture): self.capture = capture self.currentFrame=np.array([]) def captureFrame(self): """ capture frame and return captured frame ...
webcam_qt/qtcvmain.py
import sys import cv2 import numpy as np from PyQt4 import QtGui, QtCore, Qt from ui import Ui_MainWindow class Video(): def __init__(self,capture): self.capture = capture self.currentFrame=np.array([]) def captureFrame(self): """ capture frame and return captured frame ...
0.186502
0.128034
from __future__ import absolute_import import struct import pytest import os import sys try: import simplejson as json except ImportError: import json # pyflakes.ignore # shunt '..' into sys.path since we are in a 'tests' subdirectory base_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(_...
tests/test_command.py
from __future__ import absolute_import import struct import pytest import os import sys try: import simplejson as json except ImportError: import json # pyflakes.ignore # shunt '..' into sys.path since we are in a 'tests' subdirectory base_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(_...
0.323273
0.111338
def create_rf_estimator(verbose, random_state, n_jobs): from sklearn.ensemble import RandomForestClassifier return RandomForestClassifier(n_estimators=50, min_samples_split=2, min_samples_leaf=2, max_features='auto', max_depth=30, bootstrap=False, ...
notebooks/lib/classifiers.py
def create_rf_estimator(verbose, random_state, n_jobs): from sklearn.ensemble import RandomForestClassifier return RandomForestClassifier(n_estimators=50, min_samples_split=2, min_samples_leaf=2, max_features='auto', max_depth=30, bootstrap=False, ...
0.834137
0.286034
import ctypes import random import string from binascii import unhexlify, hexlify from libnacl import crypto_box_SECRETKEYBYTES, nacl, crypto_box_PUBLICKEYBYTES from common.exceptions import PlenumValueError from stp_core.crypto.nacl_wrappers import Signer # TODO: move it to crypto repo # TODO returning a None when...
stp_core/crypto/util.py
import ctypes import random import string from binascii import unhexlify, hexlify from libnacl import crypto_box_SECRETKEYBYTES, nacl, crypto_box_PUBLICKEYBYTES from common.exceptions import PlenumValueError from stp_core.crypto.nacl_wrappers import Signer # TODO: move it to crypto repo # TODO returning a None when...
0.367497
0.214034
from gamelogic import constants from gamelogic.bubblesort import BubbleSort from gamelogic.rngsus import RNGsus class GameState(): def __init__(self, word=""): self.__word = word self.__state = word self.__sorter = BubbleSort(self.__word) self.__curr_state = 0 self.__frame...
gamelogic/gamestate.py
from gamelogic import constants from gamelogic.bubblesort import BubbleSort from gamelogic.rngsus import RNGsus class GameState(): def __init__(self, word=""): self.__word = word self.__state = word self.__sorter = BubbleSort(self.__word) self.__curr_state = 0 self.__frame...
0.487795
0.201204
from __future__ import absolute_import, print_function, division from sklearn.decomposition import TruncatedSVD from sklearn.utils import check_array import numpy as np from .solver import Solver from .common import masked_mae F32PREC = np.finfo(np.float32).eps class IterativeSVD(Solver): def __init__( ...
fancyimpute/iterative_svd.py
from __future__ import absolute_import, print_function, division from sklearn.decomposition import TruncatedSVD from sklearn.utils import check_array import numpy as np from .solver import Solver from .common import masked_mae F32PREC = np.finfo(np.float32).eps class IterativeSVD(Solver): def __init__( ...
0.863176
0.248568
import datetime from dateutil.relativedelta import relativedelta import re import math from typing import Tuple, Union def today() -> str: """ Returns 'yyyy-mm-dd' date for today >>> today() == datetime.date.today().strftime('%Y-%m-%d') True """ return datetime.date.today().strftime("%Y-%m-%d...
yyyy_mm_dd/__init__.py
import datetime from dateutil.relativedelta import relativedelta import re import math from typing import Tuple, Union def today() -> str: """ Returns 'yyyy-mm-dd' date for today >>> today() == datetime.date.today().strftime('%Y-%m-%d') True """ return datetime.date.today().strftime("%Y-%m-%d...
0.819605
0.336059
load("//tools/bzl:maven_jar.bzl", "maven_jar") def declare_nongoogle_deps(): """loads dependencies that are not used at Google. Changes to versions are exempt from library compliance review. New dependencies must pass through library compliance review. This is enforced by //lib:nongoogle_test. """...
tools/nongoogle.bzl
load("//tools/bzl:maven_jar.bzl", "maven_jar") def declare_nongoogle_deps(): """loads dependencies that are not used at Google. Changes to versions are exempt from library compliance review. New dependencies must pass through library compliance review. This is enforced by //lib:nongoogle_test. """...
0.374333
0.155944
""" 根据WSGI协议 仅需要应用开发者实现一个函数来响应HTTP请求。 例如: def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return '<h1>Hello, web!</h1>' 该application函数便是一个复合WSGI标准的应用函数: 它接收两个参数environ、start_response. environ:是一个包含所有HTTP请求信息的dict对象,由web服务器提供给后端应用。 start_response:一个由服务器提供的发送HTT...
Application.py
""" 根据WSGI协议 仅需要应用开发者实现一个函数来响应HTTP请求。 例如: def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) return '<h1>Hello, web!</h1>' 该application函数便是一个复合WSGI标准的应用函数: 它接收两个参数environ、start_response. environ:是一个包含所有HTTP请求信息的dict对象,由web服务器提供给后端应用。 start_response:一个由服务器提供的发送HTT...
0.123247
0.347454
import os from django import VERSION as DJANGO_VERSION from django.conf.global_settings import * # NOQA from wagtail import VERSION as WAGTAIL_VERSION DEBUG = True SITE_ID = 1 TIME_ZONE = 'Europe/London' USE_TZ = True USE_I18N = True USE_L10N = True LANGUAGE_CODE = 'en' INSTALLED_APPS = ( 'wagtailmenus', ...
wagtailmenus/settings/base.py
import os from django import VERSION as DJANGO_VERSION from django.conf.global_settings import * # NOQA from wagtail import VERSION as WAGTAIL_VERSION DEBUG = True SITE_ID = 1 TIME_ZONE = 'Europe/London' USE_TZ = True USE_I18N = True USE_L10N = True LANGUAGE_CODE = 'en' INSTALLED_APPS = ( 'wagtailmenus', ...
0.194291
0.053974
import boto3 import termcolor # Create an S3 client s3 = boto3.resource("s3") s3_client = boto3.client("s3") GROUPS_TO_CHECK = { "http://acs.amazonaws.com/groups/global/AllUsers": "Everyone", "http://acs.amazonaws.com/groups/global/AuthenticatedUsers": "Authenticated AWS users" } BUCKETS_TO_SKIP = { } ...
s3Scan.py
import boto3 import termcolor # Create an S3 client s3 = boto3.resource("s3") s3_client = boto3.client("s3") GROUPS_TO_CHECK = { "http://acs.amazonaws.com/groups/global/AllUsers": "Everyone", "http://acs.amazonaws.com/groups/global/AuthenticatedUsers": "Authenticated AWS users" } BUCKETS_TO_SKIP = { } ...
0.33112
0.103794
import xarray as xr import numpy as np from scipy import stats # compute the Pearson's r coefficient between x and y along time dimension # valid for 1D xarrays of same shape # TODO: check it for ND xarrays def correlation_1D_1D_time(x, y): anom_xy = (x-x.mean(dim='time'))*(y-y.mean(dim='time')) anom_xx =...
processing/processing/utils/math.py
import xarray as xr import numpy as np from scipy import stats # compute the Pearson's r coefficient between x and y along time dimension # valid for 1D xarrays of same shape # TODO: check it for ND xarrays def correlation_1D_1D_time(x, y): anom_xy = (x-x.mean(dim='time'))*(y-y.mean(dim='time')) anom_xx =...
0.374791
0.83868
from varben.common.bamobject import SV import pysam import traceback def check_sv(sv_info, chrom_len): min_size = 100 chr_id, start_id, end_id, type_id, freq_id = 0, 1, 2, 3, 4 trans_chr_id, trans_start_id, trans_end_id = 5, 6, 7 cnv_type_id, dup_num_id = 5, 5 try: chrom, star...
varben/deal_sv/checkSVInput.py
from varben.common.bamobject import SV import pysam import traceback def check_sv(sv_info, chrom_len): min_size = 100 chr_id, start_id, end_id, type_id, freq_id = 0, 1, 2, 3, 4 trans_chr_id, trans_start_id, trans_end_id = 5, 6, 7 cnv_type_id, dup_num_id = 5, 5 try: chrom, star...
0.152947
0.135489
import pysendsms from tests.tools import raise_error def test_invalid_number(): error_message = 'Bad number input: Ex."277-453-2453"' assert raise_error(ValueError, pysendsms.Contact, '702851171', 'AT&T', msg=error_message) # Short assert raise_error(ValueError, pysendsms.Contact, '702851171100...
tests/test_contact.py
import pysendsms from tests.tools import raise_error def test_invalid_number(): error_message = 'Bad number input: Ex."277-453-2453"' assert raise_error(ValueError, pysendsms.Contact, '702851171', 'AT&T', msg=error_message) # Short assert raise_error(ValueError, pysendsms.Contact, '702851171100...
0.767254
0.360573
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import scipy.signal from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.utils.annotations import DeveloperAPI def discount(x, gamma): return scipy.signal.lfilter([1], [...
rllib/evaluation/postprocessing.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import scipy.signal from ray.rllib.policy.sample_batch import SampleBatch from ray.rllib.utils.annotations import DeveloperAPI def discount(x, gamma): return scipy.signal.lfilter([1], [...
0.861378
0.324556
from .defaults import DEFAULT_NAMESPACE, DEFAULT_CRD_API_VERSION from .exceptions import UnrecognisedObjectKindError from .api_version_parser import ApiVersionParser from kubernetes.client.rest import ApiException from openshift.dynamic.exceptions import api_exception, NotFoundError import kubernetes.client as kubernet...
kubedriver/kubeclient/api_ctl.py
from .defaults import DEFAULT_NAMESPACE, DEFAULT_CRD_API_VERSION from .exceptions import UnrecognisedObjectKindError from .api_version_parser import ApiVersionParser from kubernetes.client.rest import ApiException from openshift.dynamic.exceptions import api_exception, NotFoundError import kubernetes.client as kubernet...
0.408395
0.079675
import pyverdict import argparse import logging import os import time import pandas as pd import pickle import re parser = argparse.ArgumentParser() parser.add_argument('-s','-sampling_ratio',help='sampling ratio',dest='sampling_ratio',required=True) args = parser.parse_args() print(args.sampling_ratio) sampling_ra...
code/Accuracy/verdict_runner_instacart.py
import pyverdict import argparse import logging import os import time import pandas as pd import pickle import re parser = argparse.ArgumentParser() parser.add_argument('-s','-sampling_ratio',help='sampling ratio',dest='sampling_ratio',required=True) args = parser.parse_args() print(args.sampling_ratio) sampling_ra...
0.17621
0.076891
import json from hashlib import md5 from io import StringIO from pathlib import Path from unittest.mock import patch from django.core.management import call_command import pytest def _call_build_command(*args, **kwargs) -> str: stdout = StringIO() stderr = StringIO() call_command( "build", ...
tests/management/commands/build_command/test_build_command.py
import json from hashlib import md5 from io import StringIO from pathlib import Path from unittest.mock import patch from django.core.management import call_command import pytest def _call_build_command(*args, **kwargs) -> str: stdout = StringIO() stderr = StringIO() call_command( "build", ...
0.409339
0.180179
import torch import torch.nn as nn import torch.nn.functional as F from ..submodules import word_module from ..submodules import post_module __author__ = "<NAME>" class HierarchicalTransformer(nn.Module): @staticmethod def init_weights(layer): if type(layer) == nn.Linear: nn.init.xavier_n...
sgnlp/models/rumour_detection_twitter/modules/transformer/hierarchical_transformer.py
import torch import torch.nn as nn import torch.nn.functional as F from ..submodules import word_module from ..submodules import post_module __author__ = "<NAME>" class HierarchicalTransformer(nn.Module): @staticmethod def init_weights(layer): if type(layer) == nn.Linear: nn.init.xavier_n...
0.915942
0.183484
import logging from threading import RLock from blatann.services.glucose.data_types import GlucoseMeasurement from blatann.services.glucose.racp import RacpResponseCode logger = logging.getLogger(__name__) class IGlucoseDatabase(object): """ Defines the interface required for the Glucose Service ...
blatann/services/glucose/database.py
import logging from threading import RLock from blatann.services.glucose.data_types import GlucoseMeasurement from blatann.services.glucose.racp import RacpResponseCode logger = logging.getLogger(__name__) class IGlucoseDatabase(object): """ Defines the interface required for the Glucose Service ...
0.685423
0.398348
import random import six import lmdb from torch.utils.data import Dataset, ConcatDataset, Subset from torch.nn import functional as F from PIL import Image import numpy as np class DataItemKeys: """ Keys, returned in dict by all dataset classes, to avoid misprints """ IMAGE = "image" IMAGE_WIDTH = ...
recognition/src/data/dataset.py
import random import six import lmdb from torch.utils.data import Dataset, ConcatDataset, Subset from torch.nn import functional as F from PIL import Image import numpy as np class DataItemKeys: """ Keys, returned in dict by all dataset classes, to avoid misprints """ IMAGE = "image" IMAGE_WIDTH = ...
0.789761
0.307436
from datetime import date import model from modules import query_sql def profile(user_id): # Запрос текущего веса пользователя (c) query_real_weight = query_sql.real_weight_user(user_id) # Запрос данных пользователя profile_query = model.Profiles.query.filter_by(user_id=user_id).first() return pr...
modules/profile_user.py
from datetime import date import model from modules import query_sql def profile(user_id): # Запрос текущего веса пользователя (c) query_real_weight = query_sql.real_weight_user(user_id) # Запрос данных пользователя profile_query = model.Profiles.query.filter_by(user_id=user_id).first() return pr...
0.392919
0.452173
from django.db import migrations, models import django.db.models.deletion import ietf.utils.models class Migration(migrations.Migration): dependencies = [ ('doc', '0009_move_non_url_externalurls_to_uploaded_filename'), ('name', '0005_reviewassignmentstatename'), ('person', '0008_auto_20...
ietf/review/migrations/0009_refactor_review_request.py
from django.db import migrations, models import django.db.models.deletion import ietf.utils.models class Migration(migrations.Migration): dependencies = [ ('doc', '0009_move_non_url_externalurls_to_uploaded_filename'), ('name', '0005_reviewassignmentstatename'), ('person', '0008_auto_20...
0.484136
0.138171
import numpy as np import matplotlib.pyplot as plt import mir3.modules.tool.wav2spectrogram as wav2spec eps = np.finfo(float).eps def inDb(a): return 20 * np.log10(a + eps) def saveBMP(data, filename): pass def remove_random_noise(spectrogram, plot=False, outputPngName=None, filter_compensation='log10', pas...
remove_random_noise.py
import numpy as np import matplotlib.pyplot as plt import mir3.modules.tool.wav2spectrogram as wav2spec eps = np.finfo(float).eps def inDb(a): return 20 * np.log10(a + eps) def saveBMP(data, filename): pass def remove_random_noise(spectrogram, plot=False, outputPngName=None, filter_compensation='log10', pas...
0.332852
0.367554
from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import uuid import variants.models class Migration(migrations.Migration): dependenc...
importer/migrations/0005_auto_20200129_1600.py
from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion import uuid import variants.models class Migration(migrations.Migration): dependenc...
0.534612
0.139924
DEPLOY_MSG = \ """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:met="http://soap.sforce.com/2006/04/metadata"> <soapenv:Header> <met:CallOptions> <met:client>{client}</met:client> </met:CallOptions> <met:SessionHeader> <met:s...
simple_salesforce/messages.py
DEPLOY_MSG = \ """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:met="http://soap.sforce.com/2006/04/metadata"> <soapenv:Header> <met:CallOptions> <met:client>{client}</met:client> </met:CallOptions> <met:SessionHeader> <met:s...
0.241489
0.064624
import unittest from pydeequ.profiles import ColumnProfilerRunBuilder, ColumnProfilerRunner from pydeequ.analyzers import KLLParameters from pyspark.sql import SparkSession, Row class TestProfiles(unittest.TestCase): @classmethod def setUpClass(cls): deequ_maven_coord = "com.amazon.deequ:deequ:1.0.3" ...
tests/test_profiles.py
import unittest from pydeequ.profiles import ColumnProfilerRunBuilder, ColumnProfilerRunner from pydeequ.analyzers import KLLParameters from pyspark.sql import SparkSession, Row class TestProfiles(unittest.TestCase): @classmethod def setUpClass(cls): deequ_maven_coord = "com.amazon.deequ:deequ:1.0.3" ...
0.644784
0.386532
import torch as th from torch.nn.functional import relu def intensity_at_t(mu, alpha, sequences_padded, mask, t): """Finds the hawkes intensity: mu + alpha * sum( np.exp(-(t-s)) for s in points if s<=t ) Args: mu: float alpha: float sequences_padded: 2d numpy array mask: ...
tpp/processes/hawkes.py
import torch as th from torch.nn.functional import relu def intensity_at_t(mu, alpha, sequences_padded, mask, t): """Finds the hawkes intensity: mu + alpha * sum( np.exp(-(t-s)) for s in points if s<=t ) Args: mu: float alpha: float sequences_padded: 2d numpy array mask: ...
0.935722
0.755299