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 from keras.models import Sequential from keras.layers import Flatten, Conv2D, MaxPooling2D, Dense, Activation from keras.optimizers import RMSprop from keras.callbacks import Callback def catdog(optimizer, objective): model = Sequential() # Fill in the gaps so that this code runs! # la...
DogCatClassifier/classifier.py
import numpy as np from keras.models import Sequential from keras.layers import Flatten, Conv2D, MaxPooling2D, Dense, Activation from keras.optimizers import RMSprop from keras.callbacks import Callback def catdog(optimizer, objective): model = Sequential() # Fill in the gaps so that this code runs! # la...
0.889481
0.3325
import pytest from stp_zmq.test.helper import create_and_prep_stacks, \ check_stacks_communicating, add_counters_to_ping_pong def sent_ping_counts(*stacks): return {s.name: s.sent_ping_count for s in stacks} def sent_pong_counts(*stacks): return {s.name: s.sent_pong_count for s in stacks} def recv_pi...
stp_zmq/test/test_heartbeats.py
import pytest from stp_zmq.test.helper import create_and_prep_stacks, \ check_stacks_communicating, add_counters_to_ping_pong def sent_ping_counts(*stacks): return {s.name: s.sent_ping_count for s in stacks} def sent_pong_counts(*stacks): return {s.name: s.sent_pong_count for s in stacks} def recv_pi...
0.610453
0.427217
import os import fastestimator as fe from fastestimator.architecture.tensorflow import LeNet from fastestimator.dataset.data import mnist from fastestimator.op.numpyop.univariate import ExpandDims, Minmax from fastestimator.op.tensorop.loss import CrossEntropy from fastestimator.op.tensorop.model import ModelOp, Updat...
sagemaker/FE1.2/Search/mnist_tf.py
import os import fastestimator as fe from fastestimator.architecture.tensorflow import LeNet from fastestimator.dataset.data import mnist from fastestimator.op.numpyop.univariate import ExpandDims, Minmax from fastestimator.op.tensorop.loss import CrossEntropy from fastestimator.op.tensorop.model import ModelOp, Updat...
0.685844
0.289742
import RPi.GPIO as GPIO import Adafruit_DHT import requests import time import salumipi import numpy as np from simple_pid import PID from settings import * ambient = salumipi.TH_Sensor(21) chamber = salumipi.TH_Sensor(20) # PID setup heat_pid = PID(Heat_Kp, Heat_Ki, Heat_Kp, setpoint=Tset) t0 = time.time() def se...
main.py
import RPi.GPIO as GPIO import Adafruit_DHT import requests import time import salumipi import numpy as np from simple_pid import PID from settings import * ambient = salumipi.TH_Sensor(21) chamber = salumipi.TH_Sensor(20) # PID setup heat_pid = PID(Heat_Kp, Heat_Ki, Heat_Kp, setpoint=Tset) t0 = time.time() def se...
0.188212
0.160496
import unittest from pathlib import Path import os import subprocess import threading from garage import scripts class ScriptsTest(unittest.TestCase): def test_ensure_path(self): self.assertEqual(Path('/a/b/c'), scripts.ensure_path(Path('/a/b/c'))) self.assertEqual(Path('/a/b/c'), scripts.ensur...
py/garage/tests/test_scripts.py
import unittest from pathlib import Path import os import subprocess import threading from garage import scripts class ScriptsTest(unittest.TestCase): def test_ensure_path(self): self.assertEqual(Path('/a/b/c'), scripts.ensure_path(Path('/a/b/c'))) self.assertEqual(Path('/a/b/c'), scripts.ensur...
0.384103
0.373933
import dash_core_components as dcc from dash_docs import styles from dash_docs import reusable_components layout = [reusable_components.Markdown(''' # Deploying Dash Apps By default, Dash apps run on `localhost` - you can only access them on your own machine. To share a Dash app, you need to "deploy" your Dash app to...
dash_docs/tutorial/deployment.py
import dash_core_components as dcc from dash_docs import styles from dash_docs import reusable_components layout = [reusable_components.Markdown(''' # Deploying Dash Apps By default, Dash apps run on `localhost` - you can only access them on your own machine. To share a Dash app, you need to "deploy" your Dash app to...
0.756942
0.727407
import tempfile from importlib import reload import os import io import sys import src.frontend as app path = os.path.dirname(os.path.abspath(__file__)) # test that command invalid when user is logged in def test_r2_1(capsys): helper( capsys=capsys, terminal_input=[ "login", ...
test_frontend/test_R2.py
import tempfile from importlib import reload import os import io import sys import src.frontend as app path = os.path.dirname(os.path.abspath(__file__)) # test that command invalid when user is logged in def test_r2_1(capsys): helper( capsys=capsys, terminal_input=[ "login", ...
0.261802
0.215083
import logging import subprocess from os.path import expanduser import pymongo from deprecation import deprecated from ..version import __version__ from .errors import ConfigError PYMONGO_2 = pymongo.version_tuple[0] == 2 logger = logging.getLogger(__name__) AUTH_NONE = "none" AUTH_SCRAM_SHA_1 = "SCRAM-SHA-1" AUTH...
signac/common/connection.py
import logging import subprocess from os.path import expanduser import pymongo from deprecation import deprecated from ..version import __version__ from .errors import ConfigError PYMONGO_2 = pymongo.version_tuple[0] == 2 logger = logging.getLogger(__name__) AUTH_NONE = "none" AUTH_SCRAM_SHA_1 = "SCRAM-SHA-1" AUTH...
0.434461
0.123603
import hashlib import json import logging import os from .base import BaseSnitcher from cloud_snitch.models import ConfigfileEntity from cloud_snitch.models import EnvironmentEntity from cloud_snitch.models import HostEntity logger = logging.getLogger(__name__) class ConfigfileSnitcher(BaseSnitcher): """Models ...
cloud_snitch/snitchers/configfile.py
import hashlib import json import logging import os from .base import BaseSnitcher from cloud_snitch.models import ConfigfileEntity from cloud_snitch.models import EnvironmentEntity from cloud_snitch.models import HostEntity logger = logging.getLogger(__name__) class ConfigfileSnitcher(BaseSnitcher): """Models ...
0.52902
0.072505
import random import re import nltk.data nltk.download('punkt') accented_chars_vietnamese = [ ['a', 'á', 'à', 'ả', 'ã', 'ạ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ'], ['o', 'ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ', 'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ'], ['e', 'é', 'è', 'ẻ', 'ẽ', 'ẹ...
vnsc/scripts/vn_utils.py
import random import re import nltk.data nltk.download('punkt') accented_chars_vietnamese = [ ['a', 'á', 'à', 'ả', 'ã', 'ạ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ'], ['o', 'ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ', 'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ'], ['e', 'é', 'è', 'ẻ', 'ẽ', 'ẹ...
0.306735
0.308073
layout = BoolScalar("layout", False) # NHWC # TEST 1: ROI_POOLING_1, outputShape = [2, 2], spatialScale = [0.5, 0.5] i1 = Input("in", "TENSOR_FLOAT32", "{1, 4, 4, 1}") roi1 = Input("roi", "TENSOR_FLOAT32", "{5, 4}") o1 = Output("out", "TENSOR_FLOAT32", "{5, 2, 2, 1}") Model().Operation("ROI_POOLING", i1, roi1, [0, 0,...
tests/nnapi/specs/skip/V1_2/roi_pooling.mod.py
layout = BoolScalar("layout", False) # NHWC # TEST 1: ROI_POOLING_1, outputShape = [2, 2], spatialScale = [0.5, 0.5] i1 = Input("in", "TENSOR_FLOAT32", "{1, 4, 4, 1}") roi1 = Input("roi", "TENSOR_FLOAT32", "{5, 4}") o1 = Output("out", "TENSOR_FLOAT32", "{5, 2, 2, 1}") Model().Operation("ROI_POOLING", i1, roi1, [0, 0,...
0.501221
0.582788
import os import unittest import numpy as np from ..label.io import group_and_sort, load, load_label_config from ..unittest.util import get_test_file from .mot import acc_single_video_mot, evaluate_track class TestBDD100KMotEval(unittest.TestCase): """Test cases for BDD100K MOT evaluation.""" cur_dir = os....
scalabel/eval/mot_test.py
import os import unittest import numpy as np from ..label.io import group_and_sort, load, load_label_config from ..unittest.util import get_test_file from .mot import acc_single_video_mot, evaluate_track class TestBDD100KMotEval(unittest.TestCase): """Test cases for BDD100K MOT evaluation.""" cur_dir = os....
0.557123
0.463809
import os import yaml import argparse from datetime import datetime import torch import random import metaworld from garage.experiment.deterministic import set_seed from src.env import make_env from src.algorithm import SAC from src.agent import Agent def run(args): set_seed(args.seed) with open(args.config)...
train.py
import os import yaml import argparse from datetime import datetime import torch import random import metaworld from garage.experiment.deterministic import set_seed from src.env import make_env from src.algorithm import SAC from src.agent import Agent def run(args): set_seed(args.seed) with open(args.config)...
0.405096
0.133868
import datetime as _datetime import os as _os import unittest from unittest import mock import retry.api from flyteidl.plugins.sagemaker.training_job_pb2 import TrainingJobResourceConfig as _pb2_TrainingJobResourceConfig from google.protobuf.json_format import ParseDict from flytekit.common import constants as _commo...
tests/flytekit/unit/sdk/tasks/test_sagemaker_tasks.py
import datetime as _datetime import os as _os import unittest from unittest import mock import retry.api from flyteidl.plugins.sagemaker.training_job_pb2 import TrainingJobResourceConfig as _pb2_TrainingJobResourceConfig from google.protobuf.json_format import ParseDict from flytekit.common import constants as _commo...
0.441432
0.304817
import cv2 import numpy as np index = 28 c_index_start = 231 c_index_end = 323 s_index_start = 204 s_index_end = 309 a_index_start = 986 a_index_end = 1052 c_x = 210 c_y = 772 c_w = 90 c_h = 80 s_x = 216 s_y = 761 s_w = 100 s_h = 102 a_x = 193 a_y = 219 a_w = 121 a_h = 114 c_xray = np.zeros(shape=(c_h, c_w, ...
test/crop_multiple_images.py
import cv2 import numpy as np index = 28 c_index_start = 231 c_index_end = 323 s_index_start = 204 s_index_end = 309 a_index_start = 986 a_index_end = 1052 c_x = 210 c_y = 772 c_w = 90 c_h = 80 s_x = 216 s_y = 761 s_w = 100 s_h = 102 a_x = 193 a_y = 219 a_w = 121 a_h = 114 c_xray = np.zeros(shape=(c_h, c_w, ...
0.179531
0.244217
from typing import Tuple from typing import Optional import torch import numpy as np from nncf.common.graph.graph import NNCFGraph from nncf.common.graph.graph import NNCFNode from nncf.layers import NNCF_DECONV_MODULES_DICT from nncf.dynamic_graph.graph import PTNNCFNode from nncf.dynamic_graph.context import Scope ...
nncf/pruning/utils.py
from typing import Tuple from typing import Optional import torch import numpy as np from nncf.common.graph.graph import NNCFGraph from nncf.common.graph.graph import NNCFNode from nncf.layers import NNCF_DECONV_MODULES_DICT from nncf.dynamic_graph.graph import PTNNCFNode from nncf.dynamic_graph.context import Scope ...
0.926988
0.303556
import asyncio from datetime import date, datetime, timezone from azure_devtools.perfstress_tests import PerfStressTest from azure.monitor.query import LogsQueryClient as SyncLogsQueryClient, LogsQueryRequest from azure.monitor.query.aio import LogsQueryClient as AsyncLogsQueryClient from azure.identity import Defau...
sdk/monitor/azure-monitor-query/tests/perfstress_tests/batch_query.py
import asyncio from datetime import date, datetime, timezone from azure_devtools.perfstress_tests import PerfStressTest from azure.monitor.query import LogsQueryClient as SyncLogsQueryClient, LogsQueryRequest from azure.monitor.query.aio import LogsQueryClient as AsyncLogsQueryClient from azure.identity import Defau...
0.596903
0.141875
from core.plugins import Visualizer, PluginRegistry, Parser, ParsedData import numpy as np from PyQt5 import QtGui, QtWidgets @PluginRegistry.visualizer class ArrayVisualizer(Visualizer): def __init__(self): self._autoresize_checkbox = None @staticmethod def get_ui_name(): return "Array" ...
plugins/array.py
from core.plugins import Visualizer, PluginRegistry, Parser, ParsedData import numpy as np from PyQt5 import QtGui, QtWidgets @PluginRegistry.visualizer class ArrayVisualizer(Visualizer): def __init__(self): self._autoresize_checkbox = None @staticmethod def get_ui_name(): return "Array" ...
0.421671
0.152726
import json import sys import re config = {} General = {} Proxy = {} Rule = {} DOMAINKEYWORD = {} DOMAINSUFFIX = {} IPCIDR = {} def fread(file): dict = {} i = 0 for line in file: i = i+ 1 print ++i if re.match('#', line): print "# and pass" continue if re.match('//', line): print "// and pass" ...
Surf-Mac/genjson.py
import json import sys import re config = {} General = {} Proxy = {} Rule = {} DOMAINKEYWORD = {} DOMAINSUFFIX = {} IPCIDR = {} def fread(file): dict = {} i = 0 for line in file: i = i+ 1 print ++i if re.match('#', line): print "# and pass" continue if re.match('//', line): print "// and pass" ...
0.030272
0.052158
from .integ_base import IntegBase, TelemetryServer class TestTelemetryContract(IntegBase): """ Validates the basic tenets/contract Telemetry module needs to adhere to """ def test_must_not_send_metrics_if_disabled_using_envvar(self): """ No metrics should be sent if "Enabled via Confi...
tests/integration/telemetry/test_telemetry_contract.py
from .integ_base import IntegBase, TelemetryServer class TestTelemetryContract(IntegBase): """ Validates the basic tenets/contract Telemetry module needs to adhere to """ def test_must_not_send_metrics_if_disabled_using_envvar(self): """ No metrics should be sent if "Enabled via Confi...
0.649912
0.095139
from __future__ import print_function, division, absolute_import from .. import imgaug as ia from .. import parameters as iap import numpy as np import six.moves as sm from . import meta from .meta import Augmenter # TODO rename to Resize to avoid confusion with Affine's scale class Scale(Augmenter): """ Augm...
imgaug/augmenters/size.py
from __future__ import print_function, division, absolute_import from .. import imgaug as ia from .. import parameters as iap import numpy as np import six.moves as sm from . import meta from .meta import Augmenter # TODO rename to Resize to avoid confusion with Affine's scale class Scale(Augmenter): """ Augm...
0.660282
0.636748
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import griddata from time import time import pickle dx = 0.01 dy = 0.01 N = 80##nombre de formes aléatoires dir_vtu = 'D:/DS0/vtus/' dir_matrices = 'D:/DataUnet/' def read_scalar(champ, fichier): start = fichier[fichie...
prepare_matrices.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import griddata from time import time import pickle dx = 0.01 dy = 0.01 N = 80##nombre de formes aléatoires dir_vtu = 'D:/DS0/vtus/' dir_matrices = 'D:/DataUnet/' def read_scalar(champ, fichier): start = fichier[fichie...
0.19475
0.381565
from typing import Optional import arrow from hypothesis import given, infer, settings from hypothesis.provisional import urls from hypothesis.strategies import builds, fixed_dictionaries, lists, none, text from pydantic import HttpUrl, ValidationError from rsserpent.models.rss import Category, Enclosure, Feed, Guid,...
tests/models/test_rss.py
from typing import Optional import arrow from hypothesis import given, infer, settings from hypothesis.provisional import urls from hypothesis.strategies import builds, fixed_dictionaries, lists, none, text from pydantic import HttpUrl, ValidationError from rsserpent.models.rss import Category, Enclosure, Feed, Guid,...
0.926537
0.579222
import unittest import numpy as np import numpy.testing as npt from caffe2.python import core, schema, workspace from ml.rl.models.output_transformer import ( ActorOutputTransformer, DiscreteActionOutputTransformer, ParametricActionOutputTransformer, ) class DiscreteActionOutputTransformerTest(unittest....
ml/rl/test/models/test_output_transformer.py
import unittest import numpy as np import numpy.testing as npt from caffe2.python import core, schema, workspace from ml.rl.models.output_transformer import ( ActorOutputTransformer, DiscreteActionOutputTransformer, ParametricActionOutputTransformer, ) class DiscreteActionOutputTransformerTest(unittest....
0.796253
0.579847
import os from argparse import ArgumentParser, Namespace from collections import OrderedDict import torch import torch.nn.functional as F import torch.nn.parallel import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler import torch.utils.data import torch.utils.data.distributed import torchvision.d...
pl_examples/domain_templates/imagenet.py
import os from argparse import ArgumentParser, Namespace from collections import OrderedDict import torch import torch.nn.functional as F import torch.nn.parallel import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler import torch.utils.data import torch.utils.data.distributed import torchvision.d...
0.924675
0.433382
Accepted ''' class Solution: class Graph: adjacency = None vertices = None def __init__(self): self.adjacency = {} # mapping each vertex to its adjacent vertices self.vertices = set() def add_vertex(self, i, j): self.vertices.add((i, j)) ...
LeetCode/top_google/medium/battleships_in_a_board.py
Accepted ''' class Solution: class Graph: adjacency = None vertices = None def __init__(self): self.adjacency = {} # mapping each vertex to its adjacent vertices self.vertices = set() def add_vertex(self, i, j): self.vertices.add((i, j)) ...
0.782953
0.432003
import onlinejudge import onlinejudge.implementation.utils as utils import onlinejudge.implementation.logging as log import sys import os import os.path import re import glob import collections from typing import Dict, List, Match, Optional def glob_with_format(directory: str, format: str) -> List[str]: table = {}...
onlinejudge/implementation/command/utils.py
import onlinejudge import onlinejudge.implementation.utils as utils import onlinejudge.implementation.logging as log import sys import os import os.path import re import glob import collections from typing import Dict, List, Match, Optional def glob_with_format(directory: str, format: str) -> List[str]: table = {}...
0.359814
0.286891
import pandas as pd import re from .constants import * import logging _log = logging.getLogger(__name__) _OXFORD_PATH = 'https://oxcgrtportal.azurewebsites.net/api/CSVDownload' COLUMN_NAMES = { 'School closing': 'npi_school_closing', 'Workplace closing': 'npi_workplace_closing', 'Cancel public events': ...
covid19_datasets/oxford_government_policy.py
import pandas as pd import re from .constants import * import logging _log = logging.getLogger(__name__) _OXFORD_PATH = 'https://oxcgrtportal.azurewebsites.net/api/CSVDownload' COLUMN_NAMES = { 'School closing': 'npi_school_closing', 'Workplace closing': 'npi_workplace_closing', 'Cancel public events': ...
0.528533
0.292703
from __future__ import annotations from enum import Enum from typing import Iterable from pants.base import deprecated from pants.engine.rules import Rule, collect_rules, rule from pants.util.memo import memoized_classproperty from pants.util.osutil import get_normalized_arch_name, get_normalized_os_name class Pla...
src/python/pants/engine/platform.py
from __future__ import annotations from enum import Enum from typing import Iterable from pants.base import deprecated from pants.engine.rules import Rule, collect_rules, rule from pants.util.memo import memoized_classproperty from pants.util.osutil import get_normalized_arch_name, get_normalized_os_name class Pla...
0.774071
0.165526
import logging import sys import pyqtgraph as pq from PySide2.QtWidgets import QApplication, QMainWindow from pattern import SLM, AnnularMask, Field, Objective from .controller import SLMController from .dialog import Ui_Dialog __all__ = ["Dialog"] logger = logging.getLogger(__name__) def connect_s...
pattern/gui/view.py
import logging import sys import pyqtgraph as pq from PySide2.QtWidgets import QApplication, QMainWindow from pattern import SLM, AnnularMask, Field, Objective from .controller import SLMController from .dialog import Ui_Dialog __all__ = ["Dialog"] logger = logging.getLogger(__name__) def connect_s...
0.298185
0.083516
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from de...
pybind/slxos/v16r_1_00b/sysmon/sfm_walk/__init__.py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from de...
0.517327
0.064831
import json import uuid from typing import Dict, List, Optional, Tuple, Union import redis from .com import Message, decrement_msg_id class admin: def __init__(self, link: redis.Redis) -> None: self.link: redis.Redis = link def get_streams(self, match: None = None) -> List["Stream"]: match ...
telstar/admin.py
import json import uuid from typing import Dict, List, Optional, Tuple, Union import redis from .com import Message, decrement_msg_id class admin: def __init__(self, link: redis.Redis) -> None: self.link: redis.Redis = link def get_streams(self, match: None = None) -> List["Stream"]: match ...
0.818338
0.156781
import os import cohmo from cohmo import app import unittest import tempfile from unittest.mock import * import time from base64 import b64encode from flask import json, jsonify from cohmo.table import Table, TableStatus from cohmo.history import HistoryManager from cohmo.authentication_manager import AuthenticationMa...
tests/cohmo_integration_test.py
import os import cohmo from cohmo import app import unittest import tempfile from unittest.mock import * import time from base64 import b64encode from flask import json, jsonify from cohmo.table import Table, TableStatus from cohmo.history import HistoryManager from cohmo.authentication_manager import AuthenticationMa...
0.410047
0.254457
# This is kinda tricky... # pylint: disable=C0103 # pylint: disable=E1101 # pylint: disable=E0602 # pylint: disable=R0903 # pylint: disable=R0904 # pylint: disable= # pylint: disable= from django import VERSION from django.test import TestCase from django.db import models from closuretree.models import ClosureModel im...
closuretree/tests.py
# This is kinda tricky... # pylint: disable=C0103 # pylint: disable=E1101 # pylint: disable=E0602 # pylint: disable=R0903 # pylint: disable=R0904 # pylint: disable= # pylint: disable= from django import VERSION from django.test import TestCase from django.db import models from closuretree.models import ClosureModel im...
0.625209
0.215464
from collections import defaultdict from datetime import timedelta, datetime, timezone import re import time from .parser import max_kleene, cat, alt, token, drop_token, natural, maybe, eos, map, EOS from .sentinel import Sentinel RE = re.compile(r'((?P<hours>\d+?)h)?((?P<minutes>\d+?)m)?((?P<seconds>\d+?)s)?') def ...
werewolf/schedule.py
from collections import defaultdict from datetime import timedelta, datetime, timezone import re import time from .parser import max_kleene, cat, alt, token, drop_token, natural, maybe, eos, map, EOS from .sentinel import Sentinel RE = re.compile(r'((?P<hours>\d+?)h)?((?P<minutes>\d+?)m)?((?P<seconds>\d+?)s)?') def ...
0.715325
0.442817
import os import yaml import click @click.command() @click.option( "--benchmark", "-b", "benchmark_file", required=True, help="The csv file from which to extract the benchmark results", ) @click.option( "--design", "-d", required=True, help="The design to compare for between the t...
scripts/compare_regression_design.py
import os import yaml import click @click.command() @click.option( "--benchmark", "-b", "benchmark_file", required=True, help="The csv file from which to extract the benchmark results", ) @click.option( "--design", "-d", required=True, help="The design to compare for between the t...
0.361052
0.334888
import torch from .fasterRCNN_resnet import fasterrcnn_resnet50_fpn from .residualUNet import ResidualUNet from torchvision.models.detection.anchor_utils import AnchorGenerator def copy_parameters(init_model, pretrained_model): init_params = dict(init_model.named_parameters()) params_not_to_copy = tuple(['rpn...
src/models/models.py
import torch from .fasterRCNN_resnet import fasterrcnn_resnet50_fpn from .residualUNet import ResidualUNet from torchvision.models.detection.anchor_utils import AnchorGenerator def copy_parameters(init_model, pretrained_model): init_params = dict(init_model.named_parameters()) params_not_to_copy = tuple(['rpn...
0.642432
0.178812
import json from mock import patch from nose.tools import eq_ import validator from validator import constants from validator.validate import validate from .helper import TestCase class TestValidate(TestCase): def validate(self, path, **kwargs): self.output = validate(path=path, **kwargs) def tes...
tests/test_validate.py
import json from mock import patch from nose.tools import eq_ import validator from validator import constants from validator.validate import validate from .helper import TestCase class TestValidate(TestCase): def validate(self, path, **kwargs): self.output = validate(path=path, **kwargs) def tes...
0.833325
0.294621
import operator s = {} s['malediction'] = {} s['malediction']['name'] = 'Malediction' s['malediction']['low'] = 33.0 # signature radius s['malediction']['big'] = 70.1 # signature radius with MWD s['malediction']['slow'] = 760.0 # base speed with MWD off s['malediction']['fast'] = 5407.5 # mwd speed (+5%, base is 515...
missile.py
import operator s = {} s['malediction'] = {} s['malediction']['name'] = 'Malediction' s['malediction']['low'] = 33.0 # signature radius s['malediction']['big'] = 70.1 # signature radius with MWD s['malediction']['slow'] = 760.0 # base speed with MWD off s['malediction']['fast'] = 5407.5 # mwd speed (+5%, base is 515...
0.258794
0.155335
import sys import logging from ncclient import manager log = logging.getLogger(__name__) # Various IOS Snippets CREATE_VRF = """ <config> <cli-config-data> <cmd>ip routing</cmd> <cmd>ip vrf %s</cmd> </cli-config-data> </config> """ REMOVE_VRF = """ <config> <cli-con...
examples/csr1000v_example.py
import sys import logging from ncclient import manager log = logging.getLogger(__name__) # Various IOS Snippets CREATE_VRF = """ <config> <cli-config-data> <cmd>ip routing</cmd> <cmd>ip vrf %s</cmd> </cli-config-data> </config> """ REMOVE_VRF = """ <config> <cli-con...
0.232223
0.056133
from PySide6.QtWidgets import QTableWidget,QTableWidgetItem, QStyledItemDelegate class db_tables(object): def __init__(self,my_self): self.VAnalysisSamples = None self.AnalysisSamples = None self.AnalysisSamples_Base = None self.VAnalysis_Sections = None self.Analysis_S...
helpers/helpers1.py
from PySide6.QtWidgets import QTableWidget,QTableWidgetItem, QStyledItemDelegate class db_tables(object): def __init__(self,my_self): self.VAnalysisSamples = None self.AnalysisSamples = None self.AnalysisSamples_Base = None self.VAnalysis_Sections = None self.Analysis_S...
0.454472
0.139484
from FinalLogger import logger from DatabaseController import DatabaseController import sys if sys.platform == 'win32': from ctp_win32 import ApiStruct, TraderApi elif sys.platform == 'linux2' : from ctp_linux64 import ApiStruct, TraderApi class TraderDelegate(TraderApi): def __init__(self, broker_id='', ...
TraderDelegate.py
from FinalLogger import logger from DatabaseController import DatabaseController import sys if sys.platform == 'win32': from ctp_win32 import ApiStruct, TraderApi elif sys.platform == 'linux2' : from ctp_linux64 import ApiStruct, TraderApi class TraderDelegate(TraderApi): def __init__(self, broker_id='', ...
0.240953
0.051296
import torch from .utils import log_dens, pyramid, upsample from .utils import softmin_grid as softmin def barycenter_iteration(f_k, g_k, d_log, eps, p, ak_log, w_k): # Sinkhorn "pseudo-step" - from the measures to the barycenter: ft_k = softmin(eps, p, ak_log + g_k / eps) / eps # (B,K,n,n) # Update the...
geomloss/wasserstein_barycenter_images.py
import torch from .utils import log_dens, pyramid, upsample from .utils import softmin_grid as softmin def barycenter_iteration(f_k, g_k, d_log, eps, p, ak_log, w_k): # Sinkhorn "pseudo-step" - from the measures to the barycenter: ft_k = softmin(eps, p, ak_log + g_k / eps) / eps # (B,K,n,n) # Update the...
0.844762
0.263487
import hashlib import json import time from io import BytesIO import requests from websocket import create_connection, ABNF import lib.streaming_converter as streaming_converter from lib.yandex.stt_grpc import yandex_stt_grpc from utils import REQUEST_ERRORS, RuntimeErrorTrace, url_builder_cached from .audio_utils im...
src/lib/STT.py
import hashlib import json import time from io import BytesIO import requests from websocket import create_connection, ABNF import lib.streaming_converter as streaming_converter from lib.yandex.stt_grpc import yandex_stt_grpc from utils import REQUEST_ERRORS, RuntimeErrorTrace, url_builder_cached from .audio_utils im...
0.508544
0.099164
from contextlib import suppress from urllib.parse import urlparse import os from termcolor import colored import click import s3fs from c10_tools.common import C10, FileProgress, fmt_number, fmt_size, \ fmt_table, walk_packets TYPES = ( 'Computer Generated', 'PCM', 'Time', 'Mil-STD-1553', 'A...
c10_tools/stat.py
from contextlib import suppress from urllib.parse import urlparse import os from termcolor import colored import click import s3fs from c10_tools.common import C10, FileProgress, fmt_number, fmt_size, \ fmt_table, walk_packets TYPES = ( 'Computer Generated', 'PCM', 'Time', 'Mil-STD-1553', 'A...
0.583441
0.114963
import codecs from django.core.files.base import ContentFile from django.urls import reverse from accounts.utils import get_imported_user from annotations.model_utils import AnnotationAreaUtils from annotations.models import Annotation from images.model_utils import PointGen from images.models import Point from lib....
project/upload/tests/test_annotations.py
import codecs from django.core.files.base import ContentFile from django.urls import reverse from accounts.utils import get_imported_user from annotations.model_utils import AnnotationAreaUtils from annotations.models import Annotation from images.model_utils import PointGen from images.models import Point from lib....
0.63409
0.286518
from ursina import * if __name__ == '__main__': app = Ursina() camera.orthographic = True camera.fov = 4 camera.position = (1, 1) Text.default_resolution *= 2 player = Entity(name='o', color=color.azure) cursor = Tooltip(player.name, color=player.color, origin=(0,0), scale=4, enabled=True) cursor.background.colo...
samples/tic_tac_toe.py
from ursina import * if __name__ == '__main__': app = Ursina() camera.orthographic = True camera.fov = 4 camera.position = (1, 1) Text.default_resolution *= 2 player = Entity(name='o', color=color.azure) cursor = Tooltip(player.name, color=player.color, origin=(0,0), scale=4, enabled=True) cursor.background.colo...
0.337422
0.327695
import pandas as pd import numpy as np import matplotlib.pyplot as plt from linearmodels import PanelOLS import statsmodels.api as sm import econtools as econ import econtools.metrics as mt import math from statsmodels.stats.outliers_influence import variance_inflation_factor from auxiliary.prepare import * from auxil...
auxiliary/table7.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt from linearmodels import PanelOLS import statsmodels.api as sm import econtools as econ import econtools.metrics as mt import math from statsmodels.stats.outliers_influence import variance_inflation_factor from auxiliary.prepare import * from auxil...
0.280419
0.357203
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['FaqArgs', 'Faq'] @pulumi.input_type class FaqArgs: def __init__(__self__, *, ...
sdk/python/pulumi_aws_native/kendra/faq.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._enums import * from ._inputs import * __all__ = ['FaqArgs', 'Faq'] @pulumi.input_type class FaqArgs: def __init__(__self__, *, ...
0.798501
0.054475
import sys import pyecore.ecore as Ecore from pyecore.ecore import EObject, EAttribute, EString, EEnum, EReference, \ MetaEClass, EInteger name = 'library' nsPrefix = 'lib' nsURI = 'http://emf.wikipedia.org/2011/Library' # Do not remove eClass = Ecore.EPackage(name=name, nsURI=nsURI, nsPrefi...
examples/wikilibrary/static/library.py
import sys import pyecore.ecore as Ecore from pyecore.ecore import EObject, EAttribute, EString, EEnum, EReference, \ MetaEClass, EInteger name = 'library' nsPrefix = 'lib' nsURI = 'http://emf.wikipedia.org/2011/Library' # Do not remove eClass = Ecore.EPackage(name=name, nsURI=nsURI, nsPrefi...
0.284775
0.163713
from Billboard import Hot100Chart, Song from datetime import date, timedelta import html from plotly import __version__ from plotly import offline from plotly import graph_objs # download all charts for 2017 charts = [] lists = [] d = date(month=1, day=7, year=2017) delta = timedelta(days=7) while d.year == 2017: ...
src/run.py
from Billboard import Hot100Chart, Song from datetime import date, timedelta import html from plotly import __version__ from plotly import offline from plotly import graph_objs # download all charts for 2017 charts = [] lists = [] d = date(month=1, day=7, year=2017) delta = timedelta(days=7) while d.year == 2017: ...
0.374562
0.153771
"""Tests metadata flags feature by testing wait-for-ready semantics""" import time import weakref import unittest import threading import logging import socket from six.moves import queue import grpc from tests.unit import test_common from tests.unit.framework.common import test_constants import tests.unit.framework...
src/python/grpcio_tests/tests/unit/_metadata_flags_test.py
"""Tests metadata flags feature by testing wait-for-ready semantics""" import time import weakref import unittest import threading import logging import socket from six.moves import queue import grpc from tests.unit import test_common from tests.unit.framework.common import test_constants import tests.unit.framework...
0.536556
0.150778
from PIL import Image import os import sys class Pix(): def __init__(self, x, y): self.coor = (x, y) self.pere = self self.taille = 1 def __repr__(self): return str(self.coor)+" "+str(self.taille) def photo_to_list(path): """ Ouvre l'image et renvoi la liste de...
Main.py
from PIL import Image import os import sys class Pix(): def __init__(self, x, y): self.coor = (x, y) self.pere = self self.taille = 1 def __repr__(self): return str(self.coor)+" "+str(self.taille) def photo_to_list(path): """ Ouvre l'image et renvoi la liste de...
0.126677
0.272753
import sys from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtWidgets import QMenu, QAction from wizard.prefs.user import user from wizard.vars import defaults def launch_stray(widget, app, title = 'Wizard'): main = widget main.setWindowTitle(title) main.setStyleSheet(load_stylesheet()) tra...
App/gui/build.py
import sys from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtWidgets import QMenu, QAction from wizard.prefs.user import user from wizard.vars import defaults def launch_stray(widget, app, title = 'Wizard'): main = widget main.setWindowTitle(title) main.setStyleSheet(load_stylesheet()) tra...
0.154344
0.063395
import os import copy import pandas as pd from config import * def main(): image_paths = find_image_paths(PHOTOS_DIR) image_list = list() yaw_list = list() pitch_list = list() roll_list = list() for path in image_paths: yaw, pitch, roll = find_metadata(path) # Prepare values ...
ypr_extraction.py
import os import copy import pandas as pd from config import * def main(): image_paths = find_image_paths(PHOTOS_DIR) image_list = list() yaw_list = list() pitch_list = list() roll_list = list() for path in image_paths: yaw, pitch, roll = find_metadata(path) # Prepare values ...
0.428233
0.223398
import os import tempfile import shutil import urllib import sys import subprocess from .custom_exceptions import CalledProcessError import tarfile from .config import (CLANG_FORMAT_VERSION, CLANG_FORMAT_HTTP_LINUX_CACHE, CLANG_FORMAT_HTTP_DARWIN_CACHE, CLAN...
scripts/clang_git_format/clang_git_format/utils.py
import os import tempfile import shutil import urllib import sys import subprocess from .custom_exceptions import CalledProcessError import tarfile from .config import (CLANG_FORMAT_VERSION, CLANG_FORMAT_HTTP_LINUX_CACHE, CLANG_FORMAT_HTTP_DARWIN_CACHE, CLAN...
0.420838
0.083928
import re XRI_AUTHORITIES = ['!', '=', '@', '+', '$', '('] try: unichr(0x10000) except ValueError: # narrow python build UCSCHAR = [ (0xA0, 0xD7FF), (0xF900, 0xFDCF), (0xFDF0, 0xFFEF), ] IPRIVATE = [ (0xE000, 0xF8FF), ] else: UCSCHAR = [ (0x...
libs/external_libs/python-yadis-1.1.0/yadis/xri.py
import re XRI_AUTHORITIES = ['!', '=', '@', '+', '$', '('] try: unichr(0x10000) except ValueError: # narrow python build UCSCHAR = [ (0xA0, 0xD7FF), (0xF900, 0xFDCF), (0xFDF0, 0xFFEF), ] IPRIVATE = [ (0xE000, 0xF8FF), ] else: UCSCHAR = [ (0x...
0.608827
0.330687
import pytest from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By @pytest.fixture def driver(request): wd = webdriver.Chrome() request.addfinalizer(wd.quit) ret...
test_task_9.py
import pytest from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By @pytest.fixture def driver(request): wd = webdriver.Chrome() request.addfinalizer(wd.quit) ret...
0.250913
0.132515
from django.contrib.auth import get_user_model from django.shortcuts import get_object_or_404 from django.views.generic.base import View from rest_framework.permissions import IsAuthenticated from rest_framework import generics, status from rest_framework.decorators import action from rest_framework.mixins import ( ...
itez/users/api/views.py
from django.contrib.auth import get_user_model from django.shortcuts import get_object_or_404 from django.views.generic.base import View from rest_framework.permissions import IsAuthenticated from rest_framework import generics, status from rest_framework.decorators import action from rest_framework.mixins import ( ...
0.578805
0.081228
from taurex.core import Singleton from taurex.log import Logger import inspect import pkg_resources class ClassFactory(Singleton): """ A factory the discovers new classes from plugins """ def init(self): self.log = Logger('ClassFactory') self.extension_paths = [] self.rel...
taurex/parameter/classfactory.py
from taurex.core import Singleton from taurex.log import Logger import inspect import pkg_resources class ClassFactory(Singleton): """ A factory the discovers new classes from plugins """ def init(self): self.log = Logger('ClassFactory') self.extension_paths = [] self.rel...
0.496338
0.111531
from msrest.serialization import Model class ComponentsschemasmicrosoftGraphContactallof1(Model): """contact. :param parent_folder_id: :type parent_folder_id: str :param birthday: :type birthday: datetime :param file_as: :type file_as: str :param display_name: :type display_name:...
src/users/models/componentsschemasmicrosoft_graph_contactallof1.py
from msrest.serialization import Model class ComponentsschemasmicrosoftGraphContactallof1(Model): """contact. :param parent_folder_id: :type parent_folder_id: str :param birthday: :type birthday: datetime :param file_as: :type file_as: str :param display_name: :type display_name:...
0.762291
0.371365
import sys import os import importlib import inspect import numpy as np from functools import lru_cache from mpi4py import MPI from sympy import Mul, Tuple from sympy import Mod as sy_Mod, Abs, Range, Symbol, Max from sympy import Function, Integer from psydac.pyccel.ast.core import Variable, IndexedVariable fr...
psydac/api/ast/linalg.py
import sys import os import importlib import inspect import numpy as np from functools import lru_cache from mpi4py import MPI from sympy import Mul, Tuple from sympy import Mod as sy_Mod, Abs, Range, Symbol, Max from sympy import Function, Integer from psydac.pyccel.ast.core import Variable, IndexedVariable fr...
0.433502
0.189746
import pickle obj = pickle.load(open('hindencorp05.p','rb')) english_corpus = obj['X'] hindi_corpus = obj['Y'] temp_english_corpus = english_corpus[:5000] temp_hindi_corpus = hindi_corpus[:5000] temp_hindi_transliteral_corpus = open('trasnliterate.txt','r',encoding='utf-8').read() temp_hindi_transliteral_co...
src/baseline.py
import pickle obj = pickle.load(open('hindencorp05.p','rb')) english_corpus = obj['X'] hindi_corpus = obj['Y'] temp_english_corpus = english_corpus[:5000] temp_hindi_corpus = hindi_corpus[:5000] temp_hindi_transliteral_corpus = open('trasnliterate.txt','r',encoding='utf-8').read() temp_hindi_transliteral_co...
0.121009
0.238173
import numpy as np import mindspore.context as context from mindspore import Tensor, Parameter from mindspore.nn import Cell from mindspore.nn._graph_kernels import LambUpdateWithLR, LambNextMV class LambNet(Cell): def __init__(self, i2, i5, x6): super(LambNet, self).__init__() self.i2 = Paramete...
tests/st/ops/graph_kernel/test_lamb.py
import numpy as np import mindspore.context as context from mindspore import Tensor, Parameter from mindspore.nn import Cell from mindspore.nn._graph_kernels import LambUpdateWithLR, LambNextMV class LambNet(Cell): def __init__(self, i2, i5, x6): super(LambNet, self).__init__() self.i2 = Paramete...
0.601711
0.389721
from typing import Any, Set, Tuple, Union, Optional from pathlib import Path from collections import defaultdict from html.parser import HTMLParser import pytest from anndata import AnnData import numpy as np import xarray as xr from imageio import imread, imsave import tifffile from squidpy.im import ImageContaine...
tests/image/test_container.py
from typing import Any, Set, Tuple, Union, Optional from pathlib import Path from collections import defaultdict from html.parser import HTMLParser import pytest from anndata import AnnData import numpy as np import xarray as xr from imageio import imread, imsave import tifffile from squidpy.im import ImageContaine...
0.805747
0.563978
from keras.models import load_model from keras.models import Model from keras import backend as K from PIL import Image import numpy as np import os import csv LETTERSTR = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ" def toonehot(text): labellist = [] for letter in text: onehot = [0 for _ in range(34)] ...
demo_cnn.py
from keras.models import load_model from keras.models import Model from keras import backend as K from PIL import Image import numpy as np import os import csv LETTERSTR = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ" def toonehot(text): labellist = [] for letter in text: onehot = [0 for _ in range(34)] ...
0.281307
0.294986
import logging from django.core.exceptions import ValidationError from django.forms import widgets, BooleanField, ChoiceField from django.utils.html import format_html from django.utils.translation import gettext_lazy as _ from entangled.forms import EntangledModelFormMixin from cms.plugin_pool import plugin_pool from ...
cmsplugin_cascade/bootstrap4/jumbotron.py
import logging from django.core.exceptions import ValidationError from django.forms import widgets, BooleanField, ChoiceField from django.utils.html import format_html from django.utils.translation import gettext_lazy as _ from entangled.forms import EntangledModelFormMixin from cms.plugin_pool import plugin_pool from ...
0.640523
0.094052
import pandas as pd import scipy.stats as stats import math import numpy as np import warnings warnings.filterwarnings('ignore') #Sample_Size sample_size=2000 #Z_Critical Score z_critical = stats.norm.ppf(q = 0.95) # path [File location variable] data= pd.read_csv(path) #Code starts here dat...
Banking-Inferences/code.py
import pandas as pd import scipy.stats as stats import math import numpy as np import warnings warnings.filterwarnings('ignore') #Sample_Size sample_size=2000 #Z_Critical Score z_critical = stats.norm.ppf(q = 0.95) # path [File location variable] data= pd.read_csv(path) #Code starts here dat...
0.249356
0.28301
from .buttons import create_toggle_button from numpy import ceil from ipywidgets import GridspecLayout import pandas as pd from typing import List # A simple class for creating a grid of toggle buttons # It has some additional utilities such as # get_values or load_values methods class ToggleGrid: """ A cla...
image_inspector/utils/toggle_grid.py
from .buttons import create_toggle_button from numpy import ceil from ipywidgets import GridspecLayout import pandas as pd from typing import List # A simple class for creating a grid of toggle buttons # It has some additional utilities such as # get_values or load_values methods class ToggleGrid: """ A cla...
0.881373
0.472136
from voluptuous import All, Optional, Range, Schema from .config_logging import SCHEMA as LOGGING_SCHEMA, LoggingConfig SCHEMA = Schema( { Optional("lookback", default=5): All(int, Range(min=0)), Optional("timeout", default=10): All(int, Range(min=0)), Optional("retain", default=7): All(in...
viseron/config/config_recorder.py
from voluptuous import All, Optional, Range, Schema from .config_logging import SCHEMA as LOGGING_SCHEMA, LoggingConfig SCHEMA = Schema( { Optional("lookback", default=5): All(int, Range(min=0)), Optional("timeout", default=10): All(int, Range(min=0)), Optional("retain", default=7): All(in...
0.896529
0.079639
import copy import csv import json import pathlib from typing import Optional from telethon.tl.types import Message from translitua import translit channel_name = 'air_alert_ua' final_filename = pathlib.Path(__file__).parent.resolve() / '../datasets/full_data.csv' states_filename = pathlib.Path(__file__).parent.reso...
processors/full_data.py
import copy import csv import json import pathlib from typing import Optional from telethon.tl.types import Message from translitua import translit channel_name = 'air_alert_ua' final_filename = pathlib.Path(__file__).parent.resolve() / '../datasets/full_data.csv' states_filename = pathlib.Path(__file__).parent.reso...
0.556159
0.225491
import argparse from collections import deque import json from pathlib import Path from ignite.engine import ( Events, create_supervised_evaluator, create_supervised_trainer) from ignite.metrics import Loss import json_log_plots import pandas as pd import numpy as np import torch from torch import nn, optim from t...
kuzushiji/lm/main.py
import argparse from collections import deque import json from pathlib import Path from ignite.engine import ( Events, create_supervised_evaluator, create_supervised_trainer) from ignite.metrics import Loss import json_log_plots import pandas as pd import numpy as np import torch from torch import nn, optim from t...
0.728169
0.121607
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import MySQLdb >>> #1. Connection creatio >>> #1. Connection creation >>> db=MYSQLdb.connect("localhost","monika","rootroot","lpu") Traceback (most rece...
New folder/database.py
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import MySQLdb >>> #1. Connection creatio >>> #1. Connection creation >>> db=MYSQLdb.connect("localhost","monika","rootroot","lpu") Traceback (most rece...
0.212232
0.210138
import base64 from datetime import datetime import json import os from patchlib.resources import validate_patch class Patch: def __init__(self, data, validate=True, server=None): """Object representing a Patch Definition :param data: Must either be the path to an existing patch definition ...
patchlib/models.py
import base64 from datetime import datetime import json import os from patchlib.resources import validate_patch class Patch: def __init__(self, data, validate=True, server=None): """Object representing a Patch Definition :param data: Must either be the path to an existing patch definition ...
0.811825
0.292684
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import pytest import time import ray from ray.cluster_utils import Cluster @pytest.fixture(params=[(1, 4), (4, 4)]) def ray_start_combination(request): num_nodes = request.param[0] ...
python/ray/tests/test_stress.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import pytest import time import ray from ray.cluster_utils import Cluster @pytest.fixture(params=[(1, 4), (4, 4)]) def ray_start_combination(request): num_nodes = request.param[0] ...
0.61832
0.350644
import json import itertools # change both values today = '4/14/2020' yesterday = '4/13/2020' states_list = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado", "Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois", "Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","...
time_series/updater_states.py
import json import itertools # change both values today = '4/14/2020' yesterday = '4/13/2020' states_list = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado", "Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois", "Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","...
0.023509
0.193719
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_devtestlabenvironment version_added: "2.8" short_...
library/azure_rm_devtestlabenvironment.py
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_devtestlabenvironment version_added: "2.8" short_...
0.757974
0.200127
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from spinnaker_swagger_client.api_client import ApiClient class TaskControllerApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the cl...
spinnaker_swagger_client/api/task_controller_api.py
from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility library import six from spinnaker_swagger_client.api_client import ApiClient class TaskControllerApi(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the cl...
0.662687
0.049314
import os from textwrap import dedent __version__ = "0.0.1" def shp_static_path(app): static_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "_static")) app.config.html_static_path.append(static_path) def activate_comments(app, pagename, templatename, context, doctree): """Activate comm...
sphinx_comments/__init__.py
import os from textwrap import dedent __version__ = "0.0.1" def shp_static_path(app): static_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "_static")) app.config.html_static_path.append(static_path) def activate_comments(app, pagename, templatename, context, doctree): """Activate comm...
0.453504
0.092852
from copy import deepcopy from typing import Iterable import graphene from django.core.exceptions import ValidationError from django.core.validators import validate_email from ...account.models import User from ...core.permissions import GiftcardPermissions from ...core.tracing import traced_atomic_transaction from ....
saleor/graphql/giftcard/mutations.py
from copy import deepcopy from typing import Iterable import graphene from django.core.exceptions import ValidationError from django.core.validators import validate_email from ...account.models import User from ...core.permissions import GiftcardPermissions from ...core.tracing import traced_atomic_transaction from ....
0.713631
0.139455
from typing import Iterable import pytest from faker import Faker from gotrue import SyncGoTrueClient from gotrue.exceptions import APIError from gotrue.types import User GOTRUE_URL = "http://localhost:9999" TEST_TWILIO = False @pytest.fixture(name="client") def create_client() -> Iterable[SyncGoTrueClient]: w...
tests/_sync/test_client_with_auto_confirm_disabled.py
from typing import Iterable import pytest from faker import Faker from gotrue import SyncGoTrueClient from gotrue.exceptions import APIError from gotrue.types import User GOTRUE_URL = "http://localhost:9999" TEST_TWILIO = False @pytest.fixture(name="client") def create_client() -> Iterable[SyncGoTrueClient]: w...
0.568296
0.314761
from collections import defaultdict from .._compat import with_metaclass, iteritems from .._gae import gae from ..helpers._internals import Dispatcher parsers = Dispatcher("parser") class for_type(object): def __init__(self, field_type): self.field_type = field_type def __call__(self, f): s...
gluon/packages/dal/pydal/parsers/__init__.py
from collections import defaultdict from .._compat import with_metaclass, iteritems from .._gae import gae from ..helpers._internals import Dispatcher parsers = Dispatcher("parser") class for_type(object): def __init__(self, field_type): self.field_type = field_type def __call__(self, f): s...
0.649912
0.073397
import os import sys import time import gzip import pprint import keras import numpy as np import tensorflow as tf from absl import app from lib.config import REPLAYS_PARSED_DIR from data import simulation_pb2 def load_batch(replay_parsed_files, indices = [], capped_batch = 1000, run = 0, lastindex = 0, train = Tr...
bin/load_batch.py
import os import sys import time import gzip import pprint import keras import numpy as np import tensorflow as tf from absl import app from lib.config import REPLAYS_PARSED_DIR from data import simulation_pb2 def load_batch(replay_parsed_files, indices = [], capped_batch = 1000, run = 0, lastindex = 0, train = Tr...
0.196094
0.402627
from IntervalReport import * class BindingPatterns(IntervalTracker): '''output summary counts of binding patterns. The empty pattern is excluded. ''' pattern = "(.*)_binding" def __call__(self, track): return self.getAll( """SELECT pattern, COUNT(*) as counts ...
cgatpipelines/tools/pipeline_docs/pipeline_motifs/trackers/Binding.py
from IntervalReport import * class BindingPatterns(IntervalTracker): '''output summary counts of binding patterns. The empty pattern is excluded. ''' pattern = "(.*)_binding" def __call__(self, track): return self.getAll( """SELECT pattern, COUNT(*) as counts ...
0.739705
0.30365
from typing import Dict, Union, Any from e2e.Libs.BLS import Signature from e2e.Classes.Consensus.Element import Element, SignedElement from e2e.Classes.Consensus.Verification import Verification, SignedVerification from e2e.Classes.Consensus.SendDifficulty import SendDifficulty, SignedSendDifficulty from e2e.Classes...
e2e/Classes/Consensus/MeritRemoval.py
from typing import Dict, Union, Any from e2e.Libs.BLS import Signature from e2e.Classes.Consensus.Element import Element, SignedElement from e2e.Classes.Consensus.Verification import Verification, SignedVerification from e2e.Classes.Consensus.SendDifficulty import SendDifficulty, SignedSendDifficulty from e2e.Classes...
0.761982
0.332825
"""Utility functions for Aer job management.""" import uuid import copy from math import ceil from functools import singledispatch, update_wrapper, wraps from concurrent.futures import ThreadPoolExecutor from qiskit.qobj import QasmQobj, PulseQobj from qiskit.providers import JobError DEFAULT_EXECUTOR = ThreadPoolEx...
qiskit/providers/aer/jobs/utils.py
"""Utility functions for Aer job management.""" import uuid import copy from math import ceil from functools import singledispatch, update_wrapper, wraps from concurrent.futures import ThreadPoolExecutor from qiskit.qobj import QasmQobj, PulseQobj from qiskit.providers import JobError DEFAULT_EXECUTOR = ThreadPoolEx...
0.843911
0.192312
from day07 import calculate_max_thruster, calculate_optimized_thruster class TestDay07: def test_calculate_max_thruster_sample_1(self): input = [3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0] expected = 43210 result = calculate_max_thruster(input) assert result == ...
tests/test_day07.py
from day07 import calculate_max_thruster, calculate_optimized_thruster class TestDay07: def test_calculate_max_thruster_sample_1(self): input = [3, 15, 3, 16, 1002, 16, 10, 16, 1, 16, 15, 15, 4, 15, 99, 0, 0] expected = 43210 result = calculate_max_thruster(input) assert result == ...
0.68437
0.67451
from collections import defaultdict from libs.core.Log import Log from prettytable import PrettyTable from libs.Exceptions import EntryNotFound, TableManagerNotFound, TableNotFound class TableEntry: """ This class represents a table entry, which can be written to a switch """ def __init__(self, switc...
Controller-Implementation/libs/TableEntryManager.py
from collections import defaultdict from libs.core.Log import Log from prettytable import PrettyTable from libs.Exceptions import EntryNotFound, TableManagerNotFound, TableNotFound class TableEntry: """ This class represents a table entry, which can be written to a switch """ def __init__(self, switc...
0.872157
0.218232
import unicodecsv try: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO except ImportError: from io import StringIO from fieldnames import get_canonical_name,types from log import logger as global_logger class MissingFieldsException(Exception): de...
dwca/delimited.py
import unicodecsv try: try: from cStringIO import StringIO except ImportError: from StringIO import StringIO except ImportError: from io import StringIO from fieldnames import get_canonical_name,types from log import logger as global_logger class MissingFieldsException(Exception): de...
0.35209
0.109849
import matplotlib.axes import matplotlib.pyplot as plt import pytest from floodlight.core.pitch import Pitch # Test def from_template classmethod for all templates @pytest.mark.unit def test_template_dfl() -> None: # Arrange pitch = Pitch.from_template("dfl", length=110, width=68) # Assert with pyte...
tests/test_core/test_pitch.py
import matplotlib.axes import matplotlib.pyplot as plt import pytest from floodlight.core.pitch import Pitch # Test def from_template classmethod for all templates @pytest.mark.unit def test_template_dfl() -> None: # Arrange pitch = Pitch.from_template("dfl", length=110, width=68) # Assert with pyte...
0.734976
0.822439
from __future__ import division from pyomo.environ import Binary, Constraint, RangeSet, Var from pyomo.gdp import Disjunction from . import common def build_single_module(cafaro_approx, num_stages): return build_model(cafaro_approx, num_stages) def build_model(use_cafaro_approximation, num_stages): """Bui...
gdplib/mod_hens/modular_discrete_single_module.py
from __future__ import division from pyomo.environ import Binary, Constraint, RangeSet, Var from pyomo.gdp import Disjunction from . import common def build_single_module(cafaro_approx, num_stages): return build_model(cafaro_approx, num_stages) def build_model(use_cafaro_approximation, num_stages): """Bui...
0.687315
0.345547
import argparse import os import random parser = argparse.ArgumentParser( description='Split data into train, test and validation sets.') parser.add_argument('in_folder', type=str, help='Input folder where data is stored.') parser_nval = parser.add_mutually_exclusive_group(required=True) parse...
scripts/create_split.py
import argparse import os import random parser = argparse.ArgumentParser( description='Split data into train, test and validation sets.') parser.add_argument('in_folder', type=str, help='Input folder where data is stored.') parser_nval = parser.add_mutually_exclusive_group(required=True) parse...
0.277375
0.133274
import homeassistant.components.dynalite.const as dynalite from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, CONF_ROOM from homeassistant.setup import async_setup_component from tests.async_mock import call, patch from tests.common import MockConfigEntry async def test_empty_config(hass): """Test ...
tests/components/dynalite/test_init.py
import homeassistant.components.dynalite.const as dynalite from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT, CONF_ROOM from homeassistant.setup import async_setup_component from tests.async_mock import call, patch from tests.common import MockConfigEntry async def test_empty_config(hass): """Test ...
0.643217
0.403332
from __future__ import absolute_import from __future__ import print_function import io import re from glob import glob from os.path import basename from os.path import dirname from os.path import join from os.path import splitext from setuptools import find_packages from setuptools import setup def read(*names, **...
evaluation/setup.py
from __future__ import absolute_import from __future__ import print_function import io import re from glob import glob from os.path import basename from os.path import dirname from os.path import join from os.path import splitext from setuptools import find_packages from setuptools import setup def read(*names, **...
0.571049
0.155399
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations ...
texaslan/applications/migrations/0001_initial.py
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations ...
0.576542
0.16975
def convert_to_mandarin(us_num): ''' us_num, a string representing a US number 0 to 99 returns the string mandarin representation of us_num ''' trans = {'0':'ling', '1':'yi', '2':'er', '3':'san', '4': 'si', '5':'wu', '6':'liu', '7':'qi', '8':'ba', '9':'jiu', '10': 'shi'} usInt = int(us_num) ...
Final Exam/problems.py
def convert_to_mandarin(us_num): ''' us_num, a string representing a US number 0 to 99 returns the string mandarin representation of us_num ''' trans = {'0':'ling', '1':'yi', '2':'er', '3':'san', '4': 'si', '5':'wu', '6':'liu', '7':'qi', '8':'ba', '9':'jiu', '10': 'shi'} usInt = int(us_num) ...
0.492676
0.484746
from flask import Flask, request, jsonify import json import logging import os import random import string import sys import sentencepiece as spm import torch import torchaudio import numpy as np from fairseq import options, progress_bar, utils, tasks from fairseq.meters import StopwatchMeter, TimeMeter from fairseq....
asr-demo/app.py
Namespace(beam=40, bpe=None, cpu=False, criterion='cross_entropy', ctc=False, data='./data', dataset_impl=None, diverse_bea m_groups=-1, diverse_beam_strength=0.5, force_anneal=None, fp16=False, fp16_init_scale=128, fp16_scale_tolerance=0.0, fp16_ scale_window=None, gen_subset='test', kspmodel=None, lenpen=1, lm_weight...
0.529993
0.249396
import json import random import pickle import numpy as np from nltk.stem import WordNetLemmatizer from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation, Dropout from tensorflow.keras.optimizers import SGD import nltk lemmatizer = WordNetLemmatizer() intents = json.loads(...
Jarvis/features/training.py
import json import random import pickle import numpy as np from nltk.stem import WordNetLemmatizer from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Activation, Dropout from tensorflow.keras.optimizers import SGD import nltk lemmatizer = WordNetLemmatizer() intents = json.loads(...
0.481698
0.119408
from lewis.adapters.stream import StreamInterface, Cmd from ..chopper_type import ChopperType def filled_int(val, length): """ Takes a value and returns a zero padded representation of the integer component. :param val: The original value. :param length: Minimum length of the returned string :ret...
lewis_emulators/mk2_chopper/interfaces/stream_interface.py
from lewis.adapters.stream import StreamInterface, Cmd from ..chopper_type import ChopperType def filled_int(val, length): """ Takes a value and returns a zero padded representation of the integer component. :param val: The original value. :param length: Minimum length of the returned string :ret...
0.710829
0.407569
from .resource import Resource class Snapshot(Resource): """Snapshot resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Resource Id :vartype id: str :ivar name:...
azure-mgmt-compute/azure/mgmt/compute/v2017_03_30/models/snapshot.py
from .resource import Resource class Snapshot(Resource): """Snapshot resource. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar id: Resource Id :vartype id: str :ivar name:...
0.83025
0.201283