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 os import pytest from diffsync.exceptions import ObjectNotFound import network_importer.config as config from network_importer.adapters.nautobot_api.models import NautobotInterface, NautobotDevice, NautobotVlan from network_importer.adapters.nautobot_api.exceptions import NautobotObjectNotValid ROOT = os.path...
tests/unit/adapters/nautobot_api/models/test_nautobot_interface.py
import os import pytest from diffsync.exceptions import ObjectNotFound import network_importer.config as config from network_importer.adapters.nautobot_api.models import NautobotInterface, NautobotDevice, NautobotVlan from network_importer.adapters.nautobot_api.exceptions import NautobotObjectNotValid ROOT = os.path...
0.50708
0.426441
import SimpleHTTPServer import SocketServer import os from urlparse import parse_qs from cgi import parse_header import shutil import json from subprocess import Popen, PIPE, STDOUT PORT = 8000 def get_directory(name): return os.path.abspath(os.path.join(os.path.dirname(__file__), '..', name)) # Add the corresp...
srv/server27plain.py
import SimpleHTTPServer import SocketServer import os from urlparse import parse_qs from cgi import parse_header import shutil import json from subprocess import Popen, PIPE, STDOUT PORT = 8000 def get_directory(name): return os.path.abspath(os.path.join(os.path.dirname(__file__), '..', name)) # Add the corresp...
0.143278
0.071332
import math import torch import torch.nn as nn from timm.models.layers import to_2tuple, trunc_normal_ class AttentionWithRelPos(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., attn_map_dim=None, num_cls_tokens=1): super().__i...
regionvit/attention/attention_variants.py
import math import torch import torch.nn as nn from timm.models.layers import to_2tuple, trunc_normal_ class AttentionWithRelPos(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0., attn_map_dim=None, num_cls_tokens=1): super().__i...
0.874225
0.46563
import json from flask import current_app import requests from requests.auth import HTTPBasicAuth class TidePool(): """A handle to the TP backend""" def __init__(self, account: dict): """Init object from env settings""" current_app.logger.info('Called TP init: ' + account['username']) ...
demos/proxy/app/tidepool.py
import json from flask import current_app import requests from requests.auth import HTTPBasicAuth class TidePool(): """A handle to the TP backend""" def __init__(self, account: dict): """Init object from env settings""" current_app.logger.info('Called TP init: ' + account['username']) ...
0.213295
0.049085
import copy import numpy as np import graphgallery as gg def subgraph(graph, *, nodes_to_keep=None, nodes_to_remove=None): r"""Create a graph with the specified subset of nodes. Exactly one of (nodes_to_remove, nodes_to_keep) should be provided, while the other stays None. ...
graphgallery/functional/graph_level/subgraph.py
import copy import numpy as np import graphgallery as gg def subgraph(graph, *, nodes_to_keep=None, nodes_to_remove=None): r"""Create a graph with the specified subset of nodes. Exactly one of (nodes_to_remove, nodes_to_keep) should be provided, while the other stays None. ...
0.40028
0.436862
from office365.runtime.client_result import ClientResult from office365.runtime.client_value_collection import ClientValueCollection from office365.runtime.queries.client_query import ClientQuery from office365.runtime.queries.service_operation_query import ServiceOperationQuery from office365.runtime.resource_path imp...
office365/sharepoint/webs/web.py
from office365.runtime.client_result import ClientResult from office365.runtime.client_value_collection import ClientValueCollection from office365.runtime.queries.client_query import ClientQuery from office365.runtime.queries.service_operation_query import ServiceOperationQuery from office365.runtime.resource_path imp...
0.717111
0.063279
import base64 import json from flask import url_for headers = {"Authorization": "Basic %s" % base64.b64encode(bytes("admin1:pass1", 'ascii')).decode('ascii')} def post_message(client, data): messages = client.post(url_for("messages"), data=json.dumps(data), headers=headers) assert messages.status_code == 200...
tests/test_controllers.py
import base64 import json from flask import url_for headers = {"Authorization": "Basic %s" % base64.b64encode(bytes("admin1:pass1", 'ascii')).decode('ascii')} def post_message(client, data): messages = client.post(url_for("messages"), data=json.dumps(data), headers=headers) assert messages.status_code == 200...
0.318485
0.292498
# -*- coding: utf-8 -*- from contextlib import closing from django.urls import reverse from django.test import TestCase from huxley.core.models import Assignment, Committee, Country, Delegate, School from huxley.utils.test import models, TestFiles class DelegateAdminTest(TestCase): fixtures = ['conference'] ...
huxley/core/tests/admin/test_delegate.py
# -*- coding: utf-8 -*- from contextlib import closing from django.urls import reverse from django.test import TestCase from huxley.core.models import Assignment, Committee, Country, Delegate, School from huxley.utils.test import models, TestFiles class DelegateAdminTest(TestCase): fixtures = ['conference'] ...
0.333937
0.226292
import collections import warnings import imp class Dispatcher(object): """ Construct a Dispatcher from profiles (paths to python modules) TODO: warn on shadowing an existing definition from another module TODO: fix bug - spreading the logic for one action across multiple modules does not wor...
yuuki/dispatch.py
import collections import warnings import imp class Dispatcher(object): """ Construct a Dispatcher from profiles (paths to python modules) TODO: warn on shadowing an existing definition from another module TODO: fix bug - spreading the logic for one action across multiple modules does not wor...
0.222616
0.179836
import click import logging import shutil import os import lmctl.cli.lifecycle as lifecycle_cli import lmctl.project.package.core as pkgs from lmctl.cli.format import determine_format_class from lmctl.cli.cmd_tags import project_tag logger = logging.getLogger(__name__) @project_tag @click.group(short_help='Onboard a ...
lmctl/cli/commands/pkg.py
import click import logging import shutil import os import lmctl.cli.lifecycle as lifecycle_cli import lmctl.project.package.core as pkgs from lmctl.cli.format import determine_format_class from lmctl.cli.cmd_tags import project_tag logger = logging.getLogger(__name__) @project_tag @click.group(short_help='Onboard a ...
0.330687
0.105995
from logging import getLogger from pkg_resources import get_distribution from openprocurement.auctions.core.utils import ( # remove_draft_bids, upload_file as base_upload_file, get_file as base_get_file, API_DOCUMENT_BLACKLISTED_FIELDS as DOCUMENT_BLACKLISTED_FIELDS, context_unpack, calculate_...
openprocurement/auctions/geb/utils.py
from logging import getLogger from pkg_resources import get_distribution from openprocurement.auctions.core.utils import ( # remove_draft_bids, upload_file as base_upload_file, get_file as base_get_file, API_DOCUMENT_BLACKLISTED_FIELDS as DOCUMENT_BLACKLISTED_FIELDS, context_unpack, calculate_...
0.493409
0.157396
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import os import tempfile import unittest from chainer import optimizers from chainer import testin...
tests/agents_tests/test_agents.py
from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import os import tempfile import unittest from chainer import optimizers from chainer import testin...
0.703549
0.406626
import os import os.path import requests from vgazer.command import RunCommand from vgazer.exceptions import CommandError from vgazer.exceptions import InstallError from vgazer.platform import GetInstallPrefix from vgazer.platform import GetPkgConfig from vgazer.platform import GetTriplet from vgazer.st...
vgazer/install/custom_installer/freetype.py
import os import os.path import requests from vgazer.command import RunCommand from vgazer.exceptions import CommandError from vgazer.exceptions import InstallError from vgazer.platform import GetInstallPrefix from vgazer.platform import GetPkgConfig from vgazer.platform import GetTriplet from vgazer.st...
0.134577
0.055413
CORRUPTION_SCORES = {")": 3, "]": 57, "}": 1197, ">": 25137} AUTOCOMPLETION_SCORES = {")": 1, "]": 2, "}": 3, ">": 4} OPENING_BRACKETS = "({[<" OPEN2CLOSE = {"(": ")", "[": "]", "{": "}", "<": ">"} TEST_FILENAME = "test_advent10.txt" def read_input(filename=TEST_FILENAME): """return test data if no file is given"...
10/advent10.py
CORRUPTION_SCORES = {")": 3, "]": 57, "}": 1197, ">": 25137} AUTOCOMPLETION_SCORES = {")": 1, "]": 2, "}": 3, ">": 4} OPENING_BRACKETS = "({[<" OPEN2CLOSE = {"(": ")", "[": "]", "{": "}", "<": ">"} TEST_FILENAME = "test_advent10.txt" def read_input(filename=TEST_FILENAME): """return test data if no file is given"...
0.434941
0.253465
import logging import subprocess # ========== Logging setup ========== syslog = logging.getLogger(__name__) # ========== Classes ========== class RepoAddError(BaseException): """Exception when the repo-add or repo-remove script fails.""" # ========== Functions ========== def db_modify(operation, db, *args): ...
packaging_scripts/repos.py
import logging import subprocess # ========== Logging setup ========== syslog = logging.getLogger(__name__) # ========== Classes ========== class RepoAddError(BaseException): """Exception when the repo-add or repo-remove script fails.""" # ========== Functions ========== def db_modify(operation, db, *args): ...
0.516108
0.171824
import json import re import nibabel import numpy import spire from .. import entrypoint from ..cli import * class TotalField(spire.TaskFactory): """ Unwrapping and total susceptibility field of the MEDI toolbox. """ def __init__( self, magnitude: str, phase: str, f_total: str, medi_tool...
src/erwin/qsm/total_field.py
import json import re import nibabel import numpy import spire from .. import entrypoint from ..cli import * class TotalField(spire.TaskFactory): """ Unwrapping and total susceptibility field of the MEDI toolbox. """ def __init__( self, magnitude: str, phase: str, f_total: str, medi_tool...
0.697197
0.331444
import sys import requests from lxml import etree import json import time class DigCvnt: def __init__(self): self.url = "http://www.rrys2019.com/user/login" self.headers = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.1...
digcvnt.py
import sys import requests from lxml import etree import json import time class DigCvnt: def __init__(self): self.url = "http://www.rrys2019.com/user/login" self.headers = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.1...
0.090552
0.065845
import functools import logging from typing import Dict, Union import attrdict import datasets import numpy as np import transformers import determined.pytorch as det_torch import model_hub.huggingface as hf import model_hub.utils as utils class XNLITrial(hf.BaseTransformerTrial): def __init__(self, context: de...
model_hub/examples/huggingface/text-classification/xnli_trial.py
import functools import logging from typing import Dict, Union import attrdict import datasets import numpy as np import transformers import determined.pytorch as det_torch import model_hub.huggingface as hf import model_hub.utils as utils class XNLITrial(hf.BaseTransformerTrial): def __init__(self, context: de...
0.894209
0.313945
import json import multiprocessing import os import tempfile import tensorflow as tf from sagemaker_tensorflow import PipeModeDataset print("Starting estimator script") ds = PipeModeDataset("elizabeth") class BenchmarkConfig(object): def __init__(self): self.hp = json.load(open('/opt/ml/input/config/hy...
test/integ/scripts/estimator_script.py
import json import multiprocessing import os import tempfile import tensorflow as tf from sagemaker_tensorflow import PipeModeDataset print("Starting estimator script") ds = PipeModeDataset("elizabeth") class BenchmarkConfig(object): def __init__(self): self.hp = json.load(open('/opt/ml/input/config/hy...
0.712532
0.176743
import argparse data_dir = "data/" def get_argparser(experiment="ersstv5"): """ :param experiment: ersstv5, or cnn_data :return: """ parser = argparse.ArgumentParser(description='PyTorch ENSO Time series forecasting') parser.add_argument("--data_dir", type=str, default=r'data/') parser....
hyperparams_and_args.py
import argparse data_dir = "data/" def get_argparser(experiment="ersstv5"): """ :param experiment: ersstv5, or cnn_data :return: """ parser = argparse.ArgumentParser(description='PyTorch ENSO Time series forecasting') parser.add_argument("--data_dir", type=str, default=r'data/') parser....
0.732687
0.121035
import base64 import json import time import sdk.util as util from sdk.data.Mappable import Mappable class CANFrame(Mappable): """CAN Frame data class""" __slots__ = ('timestamp', 'frame_id', 'data', 'response') def __init__(self, frame_id, data): """ :param int frame_id: :param...
python/sdk/data/CANFrame.py
import base64 import json import time import sdk.util as util from sdk.data.Mappable import Mappable class CANFrame(Mappable): """CAN Frame data class""" __slots__ = ('timestamp', 'frame_id', 'data', 'response') def __init__(self, frame_id, data): """ :param int frame_id: :param...
0.486332
0.236307
import shutil, path import names random = names.random random.seed(0) fname = path.Path(__file__).stem root = path.Path(f'{fname}_cases') if not root.exists(): root.mkdir() names_bank = [names.get_full_name() for _ in range(30)] gen_grade = lambda: random.randint(0, 100) gen_sid = lambda: f'520...
codes/20fall/lab08/学生成绩管理程序/lab08_学生成绩管理程序.py
import shutil, path import names random = names.random random.seed(0) fname = path.Path(__file__).stem root = path.Path(f'{fname}_cases') if not root.exists(): root.mkdir() names_bank = [names.get_full_name() for _ in range(30)] gen_grade = lambda: random.randint(0, 100) gen_sid = lambda: f'520...
0.197444
0.124772
from settings import * from PIL import Image from PIL import ImageTk import cv2 import imutils import sys import tkinter as tki from guiManager import GuiManager class MosquitoTracker: def __init__(self, webcamId): # Used to quit running when the GUI thread decides self.running = True ...
mosquitoTracker.py
from settings import * from PIL import Image from PIL import ImageTk import cv2 import imutils import sys import tkinter as tki from guiManager import GuiManager class MosquitoTracker: def __init__(self, webcamId): # Used to quit running when the GUI thread decides self.running = True ...
0.443841
0.130147
import unittest import urllib import os import datetime from dateutil.relativedelta import relativedelta import netCDF4 import numpy as np from ocw.dataset import Dataset import ocw.utils as utils class TestDecodeTimes(unittest.TestCase): test_model = '../ocw-ui/backend/tests/example_data/lat_lon_time.nc' ...
ocw/tests/test_utils.py
import unittest import urllib import os import datetime from dateutil.relativedelta import relativedelta import netCDF4 import numpy as np from ocw.dataset import Dataset import ocw.utils as utils class TestDecodeTimes(unittest.TestCase): test_model = '../ocw-ui/backend/tests/example_data/lat_lon_time.nc' ...
0.587825
0.544741
import os import time import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader import torch.nn.functional as F import warnings from torch.optim import Adam from tqdm import tqdm warnings.simplefilter("ignore") class modelTrainer: def __init__(self, model: nn.Module, criterion: nn.Module...
src/train.py
import os import time import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader import torch.nn.functional as F import warnings from torch.optim import Adam from tqdm import tqdm warnings.simplefilter("ignore") class modelTrainer: def __init__(self, model: nn.Module, criterion: nn.Module...
0.89328
0.31008
{ 'includes': [ 'src/common_settings.gypi', # Common settings ], 'targets': [ { 'target_name': 'auto_tests', 'type': 'none', 'dependencies': [ 'src/voice_engine.gyp:voe_auto_test', 'src/video_engine.gyp:vie_auto_test', ], }, { 'target_name': 'cmd_test'...
webrtc.gyp
{ 'includes': [ 'src/common_settings.gypi', # Common settings ], 'targets': [ { 'target_name': 'auto_tests', 'type': 'none', 'dependencies': [ 'src/voice_engine.gyp:voe_auto_test', 'src/video_engine.gyp:vie_auto_test', ], }, { 'target_name': 'cmd_test'...
0.302082
0.176707
import cherrypy from controllers.base import BaseController import models.dbtool as DB from peewee import IntegrityError import json class SettingsController(BaseController): @cherrypy.expose def index(self): # @TODO display the status of the indexers indexers = DB.Indexers.select() ...
controllers/settings.py
import cherrypy from controllers.base import BaseController import models.dbtool as DB from peewee import IntegrityError import json class SettingsController(BaseController): @cherrypy.expose def index(self): # @TODO display the status of the indexers indexers = DB.Indexers.select() ...
0.284377
0.176991
from typing import Callable, Dict, Optional, Sequence from rnnr.callbacks import save from sacred.run import Run from text2array import Vocab import torch from crf import DepTreeCRF from evaluation import count_correct def set_train_mode(model: torch.nn.Module, training: bool = True) -> Callable[[dict], None]: ...
callbacks.py
from typing import Callable, Dict, Optional, Sequence from rnnr.callbacks import save from sacred.run import Run from text2array import Vocab import torch from crf import DepTreeCRF from evaluation import count_correct def set_train_mode(model: torch.nn.Module, training: bool = True) -> Callable[[dict], None]: ...
0.945362
0.358578
import logging import sys import mcpi from mcpi.minecraft import Minecraft from minecraftstuff import MinecraftDrawing from .renderer import Renderer from mcthings.blocks_memory import BlocksMemory class _Server: """ A Server manages the connection with the Minecraft server. Every World must have a Ser...
mcthings/renderers/raspberry_pi.py
import logging import sys import mcpi from mcpi.minecraft import Minecraft from minecraftstuff import MinecraftDrawing from .renderer import Renderer from mcthings.blocks_memory import BlocksMemory class _Server: """ A Server manages the connection with the Minecraft server. Every World must have a Ser...
0.525125
0.354126
import keras import numpy as np import cv2 import shutil from keras.models import load_model from scan_lib import scan_data as sc def data_generator_declare(): print('Все файлы должны быть в формате - img999.jpg. ' + 'Формат может быть pdf, jpg, png. Каждому скану ' + 'должна соответствовать ф...
scan_lib/nero.py
import keras import numpy as np import cv2 import shutil from keras.models import load_model from scan_lib import scan_data as sc def data_generator_declare(): print('Все файлы должны быть в формате - img999.jpg. ' + 'Формат может быть pdf, jpg, png. Каждому скану ' + 'должна соответствовать ф...
0.449393
0.274306
from datetime import datetime #Fixed deltatime used to geenerate web reports # 2021-05-26 d_periods = { '0t': ['DateTime', '0s', 0], '1t': ['DateTime', '1min', 0], '5t': ['DateTime', '5min', 0], '15t': ['qH', '15min', 0], '1h': ['hour', 'hour', -1], ...
src/susee/see_dict.py
from datetime import datetime #Fixed deltatime used to geenerate web reports # 2021-05-26 d_periods = { '0t': ['DateTime', '0s', 0], '1t': ['DateTime', '1min', 0], '5t': ['DateTime', '5min', 0], '15t': ['qH', '15min', 0], '1h': ['hour', 'hour', -1], ...
0.31321
0.236417
import numpy as np from ote_sdk.entities.annotation import ( Annotation, AnnotationSceneEntity, AnnotationSceneKind, ) from ote_sdk.entities.dataset_item import DatasetItemEntity from ote_sdk.entities.datasets import DatasetEntity from ote_sdk.entities.id import ID from ote_sdk.entities.image import Image ...
external/deep-object-reid/tests/sc_input_params_validation/helpers.py
import numpy as np from ote_sdk.entities.annotation import ( Annotation, AnnotationSceneEntity, AnnotationSceneKind, ) from ote_sdk.entities.dataset_item import DatasetItemEntity from ote_sdk.entities.datasets import DatasetEntity from ote_sdk.entities.id import ID from ote_sdk.entities.image import Image ...
0.601594
0.311165
from abc import ABCMeta, abstractmethod from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops impo...
sequencing/decoders/decoder.py
from abc import ABCMeta, abstractmethod from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_util from tensorflow.python.ops impo...
0.941142
0.389401
import tensorflow as tf import numpy as np import random from collections import deque # Hyper Parameters: FRAME_PER_ACTION = 1 GAMMA = 0.99 # decay rate of past observations OBSERVE = 100. # timesteps to observe before training EXPLORE = 200000. # frames over which to anneal epsilon FINAL_EPSILON = 0#0.001 # fina...
RL Learning/DRL-FlappyBird-master/BrainDQN_Nature.py
import tensorflow as tf import numpy as np import random from collections import deque # Hyper Parameters: FRAME_PER_ACTION = 1 GAMMA = 0.99 # decay rate of past observations OBSERVE = 100. # timesteps to observe before training EXPLORE = 200000. # frames over which to anneal epsilon FINAL_EPSILON = 0#0.001 # fina...
0.46223
0.468
import os from six.moves import configparser from .decorators import suppress_all_exceptions PRIVACY_STATEMENT = """ Welcome to iotedgedev! ------------------------- Telemetry --------- The iotedgedev collects usage data in order to improve your experience. The data is anonymous and does not include commandline argu...
iotedgedev/telemetryconfig.py
import os from six.moves import configparser from .decorators import suppress_all_exceptions PRIVACY_STATEMENT = """ Welcome to iotedgedev! ------------------------- Telemetry --------- The iotedgedev collects usage data in order to improve your experience. The data is anonymous and does not include commandline argu...
0.351979
0.099295
import argparse import csv import re from datetime import ( datetime, ) from itertools import ( chain, ) from os import ( path, ) from typing import ( Iterator, List, NamedTuple, Tuple, TypeVar, ) from git import ( Repo, ) class LogEntry(NamedTuple): """ Represents a log e...
bin/logit.py
import argparse import csv import re from datetime import ( datetime, ) from itertools import ( chain, ) from os import ( path, ) from typing import ( Iterator, List, NamedTuple, Tuple, TypeVar, ) from git import ( Repo, ) class LogEntry(NamedTuple): """ Represents a log e...
0.742795
0.37605
import datetime import json import logging import os import subprocess import time from contextlib import suppress from typing import Any, List, Optional __version__ = '0.0.19' def bash_command(command: list) -> Optional[str]: """ Run external commands. :param command: A list object containing the comma...
modules/core.py
import datetime import json import logging import os import subprocess import time from contextlib import suppress from typing import Any, List, Optional __version__ = '0.0.19' def bash_command(command: list) -> Optional[str]: """ Run external commands. :param command: A list object containing the comma...
0.715623
0.205655
import numpy as np from matplotlib.colors import ListedColormap _lut05 = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
ipychord3/cmaps.py
import numpy as np from matplotlib.colors import ListedColormap _lut05 = np.array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
0.240239
0.107531
from __future__ import unicode_literals from dfdatetime import posix_time as dfdatetime_posix_time from plaso.containers import time_events from plaso.lib import eventdata from plaso.parsers import sqlite from plaso.parsers.sqlite_plugins import interface class TestingFoobarEventData(events.EventData): """testing...
test_data/plaso_testing_sqlite_plugin.py
from __future__ import unicode_literals from dfdatetime import posix_time as dfdatetime_posix_time from plaso.containers import time_events from plaso.lib import eventdata from plaso.parsers import sqlite from plaso.parsers.sqlite_plugins import interface class TestingFoobarEventData(events.EventData): """testing...
0.812533
0.267157
from __future__ import print_function import bpy from bpy.types import Operator, Panel, PropertyGroup, WindowManager from bpy.props import PointerProperty, StringProperty, IntProperty, FloatProperty, BoolProperty import sys paths = [ #PYTHON_PATH, PROJECT_DIR ] for p in paths: sys.path.insert(0, p) from ma...
automask.py
from __future__ import print_function import bpy from bpy.types import Operator, Panel, PropertyGroup, WindowManager from bpy.props import PointerProperty, StringProperty, IntProperty, FloatProperty, BoolProperty import sys paths = [ #PYTHON_PATH, PROJECT_DIR ] for p in paths: sys.path.insert(0, p) from ma...
0.465873
0.26824
import sys import unittest import soundfile from porcupine import Porcupine from util import * class PorcupineTestCase(unittest.TestCase): def test_process(self): porcupine = Porcupine( access_key=sys.argv[1], library_path=pv_library_path('../..'), model_path=pv_model...
binding/python/test_porcupine.py
import sys import unittest import soundfile from porcupine import Porcupine from util import * class PorcupineTestCase(unittest.TestCase): def test_process(self): porcupine = Porcupine( access_key=sys.argv[1], library_path=pv_library_path('../..'), model_path=pv_model...
0.267504
0.209389
import unittest from lxml import etree from recipemd.pieces import * from recipemd.utils import XmlTestMixin from recipemd.serializer.xml import serialize class serializeTests(unittest.TestCase, XmlTestMixin): def test_ingredient_all(self): i = Ingredient('name', 'amount', 'unit') e = etree.Elemen...
tests/test_xml.py
import unittest from lxml import etree from recipemd.pieces import * from recipemd.utils import XmlTestMixin from recipemd.serializer.xml import serialize class serializeTests(unittest.TestCase, XmlTestMixin): def test_ingredient_all(self): i = Ingredient('name', 'amount', 'unit') e = etree.Elemen...
0.489992
0.582966
import json import os import sys from abc import abstractmethod from operations.chain import Chain from operations.command import Command from operations.subtitles import Subtitle class GenerateGifIt(object): def get_instance(self, options={}): instance = self.__create_instance(options) r...
operations/gif_it.py
import json import os import sys from abc import abstractmethod from operations.chain import Chain from operations.command import Command from operations.subtitles import Subtitle class GenerateGifIt(object): def get_instance(self, options={}): instance = self.__create_instance(options) r...
0.294925
0.102215
from typing import TYPE_CHECKING from discord import Member, User from .managerbase import BaseManager if TYPE_CHECKING: from typing import Union from k2modules.util import OptionalMember action_messages = { 'warn': ('\N{WARNING SIGN}', 'Warn', 'warned', {'moderator-logs'}), 'ban': ('\N{NO ENTRY}', ...
k2modules/util/userlog.py
from typing import TYPE_CHECKING from discord import Member, User from .managerbase import BaseManager if TYPE_CHECKING: from typing import Union from k2modules.util import OptionalMember action_messages = { 'warn': ('\N{WARNING SIGN}', 'Warn', 'warned', {'moderator-logs'}), 'ban': ('\N{NO ENTRY}', ...
0.634543
0.099733
from credo.structure.credentials import Credentials, SamlCredentials from credo.structure.repository import Repository from credo.structure.account import Account from credo.structure.user import User import logging import json import os log = logging.getLogger("credo.structure.credential_path") class CredentialPath...
credo/structure/credential_path.py
from credo.structure.credentials import Credentials, SamlCredentials from credo.structure.repository import Repository from credo.structure.account import Account from credo.structure.user import User import logging import json import os log = logging.getLogger("credo.structure.credential_path") class CredentialPath...
0.483161
0.070752
from prune import prune from rest_framework.response import Response from .get_field_keys import get_field_keys from .subpaths import subpaths class FileNameMixin: def get_filename(self, request, response): try: return request.path_info.replace("/", "_").strip("_") except: ...
rest_framework_more/mixins.py
from prune import prune from rest_framework.response import Response from .get_field_keys import get_field_keys from .subpaths import subpaths class FileNameMixin: def get_filename(self, request, response): try: return request.path_info.replace("/", "_").strip("_") except: ...
0.38549
0.067547
import math from .utils import build_mantissa from .mantissa_operation import compare, mantissa_sum, mantissa_sub, mantissa_mul, mantissa_div class FPANumber: def __init__(self, base, exponent, mantissa, sign): self._base = base self._exponent = exponent self._mantissa = mantissa ...
fpa/fpa.py
import math from .utils import build_mantissa from .mantissa_operation import compare, mantissa_sum, mantissa_sub, mantissa_mul, mantissa_div class FPANumber: def __init__(self, base, exponent, mantissa, sign): self._base = base self._exponent = exponent self._mantissa = mantissa ...
0.482917
0.206754
from kivy.clock import Clock from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.lang import Builder from appkit.src.akstatusbar import AKStatusBar from appkit.src.akmenu import AKMenu from appkit.src.akprojects import AKProjects from appkit.src.proj...
src/akappwid.py
from kivy.clock import Clock from kivy.uix.boxlayout import BoxLayout from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.lang import Builder from appkit.src.akstatusbar import AKStatusBar from appkit.src.akmenu import AKMenu from appkit.src.akprojects import AKProjects from appkit.src.proj...
0.434341
0.062189
import ssl import os.path import settings as settings_file def getSslOpts(): ''' Verify the SSL cert exists in the proper place. ''' certpath = './rabbit_pub_cert/' caCert = os.path.abspath(os.path.join(certpath, './cacert.pem')) cert = os.path.abspath(os.path.join(certpath, './cert1.pem')) keyf = os.path.abs...
FetchAgent/MessageSettings.py
import ssl import os.path import settings as settings_file def getSslOpts(): ''' Verify the SSL cert exists in the proper place. ''' certpath = './rabbit_pub_cert/' caCert = os.path.abspath(os.path.join(certpath, './cacert.pem')) cert = os.path.abspath(os.path.join(certpath, './cert1.pem')) keyf = os.path.abs...
0.272605
0.116563
import logging from structlog import wrap_logger logger = wrap_logger(logging.getLogger(__name__)) class PartyServiceMock: def get_business_details(self, business_ids): """Return mock business details""" business_details = [ self._business_details.get(business_id) for bus...
secure_message/api_mocks/party_service_mock.py
import logging from structlog import wrap_logger logger = wrap_logger(logging.getLogger(__name__)) class PartyServiceMock: def get_business_details(self, business_ids): """Return mock business details""" business_details = [ self._business_details.get(business_id) for bus...
0.50293
0.275928
import pytest import smt_switch as ss import pono from typing import Set @pytest.mark.parametrize("create_solver", ss.solvers.values()) def test_fts_unroller(create_solver): solver = create_solver(False) bvsort4 = solver.make_sort(ss.sortkinds.BV, 4) bvsort8 = solver.make_sort(ss.sortkinds.BV, 8) arrs...
tests/python/test_unroller.py
import pytest import smt_switch as ss import pono from typing import Set @pytest.mark.parametrize("create_solver", ss.solvers.values()) def test_fts_unroller(create_solver): solver = create_solver(False) bvsort4 = solver.make_sort(ss.sortkinds.BV, 4) bvsort8 = solver.make_sort(ss.sortkinds.BV, 8) arrs...
0.680985
0.759761
mode: python; py-indent-offset: 4; tab-width: 8; coding:utf-8 ''' from sos_trades_core.sos_processes.processes_factory import SoSProcessFactory from importlib import import_module from os.path import dirname, isdir from os import listdir, makedirs from tempfile import gettempdir class UseCaseFailedException(Exception...
sos_trades_core/sos_processes/run_all_usecases.py
mode: python; py-indent-offset: 4; tab-width: 8; coding:utf-8 ''' from sos_trades_core.sos_processes.processes_factory import SoSProcessFactory from importlib import import_module from os.path import dirname, isdir from os import listdir, makedirs from tempfile import gettempdir class UseCaseFailedException(Exception...
0.407451
0.079068
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np class ImageCoder(object): """Helper class that provides TensorFlow image coding utilities. Taken from https://github.com/tensorflow/models/blob/master/in...
src/datasets/common.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np class ImageCoder(object): """Helper class that provides TensorFlow image coding utilities. Taken from https://github.com/tensorflow/models/blob/master/in...
0.953253
0.562657
import logging from requests.exceptions import HTTPError from rest_framework.status import HTTP_404_NOT_FOUND from django.conf import settings from django.db import transaction from courses.constants import PROGRAM_TEXT_ID_PREFIX from courses.models import ( CourseRunGrade, CourseRunCertificate, ProgramCer...
courses/utils.py
import logging from requests.exceptions import HTTPError from rest_framework.status import HTTP_404_NOT_FOUND from django.conf import settings from django.db import transaction from courses.constants import PROGRAM_TEXT_ID_PREFIX from courses.models import ( CourseRunGrade, CourseRunCertificate, ProgramCer...
0.74158
0.248771
from .. import wire from .. import gate from . import DEC Wire = wire.Wire Bus4 = wire.Bus4 Bus8 = wire.Bus8 Bus16 = wire.Bus16 class Demultiplexer1To2: """Construct a new 1-to-2 demultiplexer. Args: enable: An object of type Wire. Enables the demultiplexer. select: An object of type Wire. T...
bitwise/signal/DEMUX.py
from .. import wire from .. import gate from . import DEC Wire = wire.Wire Bus4 = wire.Bus4 Bus8 = wire.Bus8 Bus16 = wire.Bus16 class Demultiplexer1To2: """Construct a new 1-to-2 demultiplexer. Args: enable: An object of type Wire. Enables the demultiplexer. select: An object of type Wire. T...
0.764012
0.328031
import json import copy from pgadmin.utils.route import BaseTestGenerator from regression.python_test_utils import test_utils as utils class ServersAddTestCase(BaseTestGenerator): """ This class will add the servers under default server group. """ scenarios = [ # Fetch the default url for server obj...
pgAdmin/browser/server_groups/servers/tests/test_server_add.py
import json import copy from pgadmin.utils.route import BaseTestGenerator from regression.python_test_utils import test_utils as utils class ServersAddTestCase(BaseTestGenerator): """ This class will add the servers under default server group. """ scenarios = [ # Fetch the default url for server obj...
0.512449
0.150559
import pygame as pg from pygame.locals import * from blueprints.attribute_blueprint import AttributeBlueprint as AB from blueprints.blueprint import Blueprint from blueprints.character_blueprint import CharacterBlueprint as CB from blueprints.function_blueprint import FunctionBlueprint as FB from blueprints.sprite_blu...
BlueprintsApp/main/gui/forms/blueprint_control_form.py
import pygame as pg from pygame.locals import * from blueprints.attribute_blueprint import AttributeBlueprint as AB from blueprints.blueprint import Blueprint from blueprints.character_blueprint import CharacterBlueprint as CB from blueprints.function_blueprint import FunctionBlueprint as FB from blueprints.sprite_blu...
0.331228
0.104798
r"""Add HuggingFace Datasets. Script to convert code for dataset in HuggingFace to tensorflow datasets To convert a dataset from huggingface, first clone the git repo of huggingface to local device. To clone, copy and execute the following command in terminal git clone https://github.com/huggingface/nlp.git This ...
tensorflow_datasets/scripts/cleanup/convert_nlp.py
r"""Add HuggingFace Datasets. Script to convert code for dataset in HuggingFace to tensorflow datasets To convert a dataset from huggingface, first clone the git repo of huggingface to local device. To clone, copy and execute the following command in terminal git clone https://github.com/huggingface/nlp.git This ...
0.858926
0.4575
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.impo...
pysnmp/RSTONE-RS-AGENTCAP-MIB.py
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.impo...
0.415136
0.163179
from components.build_post_list import build_post_list from components.tweet_cleaning import emoji_free_text, url_free_text # Base and Cleaning import pandas as pd import re import string # Natural Language Processing (NLP) import spacy from spacy.tokenizer import Tokenizer from gensim.corpora import Dictionary from ...
app/components/build_model.py
from components.build_post_list import build_post_list from components.tweet_cleaning import emoji_free_text, url_free_text # Base and Cleaning import pandas as pd import re import string # Natural Language Processing (NLP) import spacy from spacy.tokenizer import Tokenizer from gensim.corpora import Dictionary from ...
0.578091
0.173148
from pydclib.pydclib import bin2hstr from dc.core.State import State from dc.core.StateContainer import StateContainer from dc.core.VoteStats import VoteStats from dc.core.OptimizedAddressState import OptimizedAddressState from dc.core.MultiSigAddressState import MultiSigAddressState from dc.core.misc import logger fr...
src/dc/core/txs/multisig/MultiSigSpend.py
from pydclib.pydclib import bin2hstr from dc.core.State import State from dc.core.StateContainer import StateContainer from dc.core.VoteStats import VoteStats from dc.core.OptimizedAddressState import OptimizedAddressState from dc.core.MultiSigAddressState import MultiSigAddressState from dc.core.misc import logger fr...
0.758421
0.2778
import sys import data import json import pika import time import random import datetime class Feeder(): def __init__(self, fnQuery='query.txt'): self.PATH_CONFIG = './config/' self.queries = [] self.EXCHANGE_NAME = 'e_crawler' self.IN_QUEUE_NAME = 'q_feeds' self.OUT_QUEUE...
2. message queue/mission6/feeder.py
import sys import data import json import pika import time import random import datetime class Feeder(): def __init__(self, fnQuery='query.txt'): self.PATH_CONFIG = './config/' self.queries = [] self.EXCHANGE_NAME = 'e_crawler' self.IN_QUEUE_NAME = 'q_feeds' self.OUT_QUEUE...
0.205376
0.070848
from pydpiper.pipeline import * import networkx as nx def generateFile(i): return("filename_" + str(i) + ".mnc") class TestSgeScript(): def setup_method(self, method): self.p = Pipeline() startFileA = generateFile(1) startFileB = generateFile(5) self.p.addStage(CmdStage(["...
pydpiper_testing/test_sge_script.py
from pydpiper.pipeline import * import networkx as nx def generateFile(i): return("filename_" + str(i) + ".mnc") class TestSgeScript(): def setup_method(self, method): self.p = Pipeline() startFileA = generateFile(1) startFileB = generateFile(5) self.p.addStage(CmdStage(["...
0.376852
0.219819
from django import forms from django.contrib import admin from dynamic_raw_id.widgets import DynamicRawIDWidget class DynamicRawIDFilterForm(forms.Form): """Form for dynamic_raw_id filter.""" def __init__(self, rel, admin_site, field_name, **kwargs): """Construct field for given field rel.""" ...
dynamic_raw_id/filters.py
from django import forms from django.contrib import admin from dynamic_raw_id.widgets import DynamicRawIDWidget class DynamicRawIDFilterForm(forms.Form): """Form for dynamic_raw_id filter.""" def __init__(self, rel, admin_site, field_name, **kwargs): """Construct field for given field rel.""" ...
0.806243
0.116236
from django.db import models from django.contrib.auth.models import User import time import datetime # Create your models here. class Plan(models.Model): price_cents = models.IntegerField() name = models.CharField(max_length=15) num_bots_allowed = models.IntegerField() max_trade_size_usd = mode...
billing/models.py
from django.db import models from django.contrib.auth.models import User import time import datetime # Create your models here. class Plan(models.Model): price_cents = models.IntegerField() name = models.CharField(max_length=15) num_bots_allowed = models.IntegerField() max_trade_size_usd = mode...
0.437343
0.186447
from http import HTTPStatus from aiohttp.web_exceptions import HTTPNotFound, HTTPConflict, HTTPBadRequest from aiohttp.web_response import Response from aiohttp_validate import validate from asyncpg import UniqueViolationError, ForeignKeyViolationError from sqlalchemy import select from storefront.handlers.base impor...
storefront/handlers/employees.py
from http import HTTPStatus from aiohttp.web_exceptions import HTTPNotFound, HTTPConflict, HTTPBadRequest from aiohttp.web_response import Response from aiohttp_validate import validate from asyncpg import UniqueViolationError, ForeignKeyViolationError from sqlalchemy import select from storefront.handlers.base impor...
0.587233
0.150965
## @package helpers # Module caffe2.python.tutorials.helpers from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import skimage.io import skimage.transform def crop_center(img, cropx, cropy): y, x,...
caffe2/python/tutorials/helpers.py
## @package helpers # Module caffe2.python.tutorials.helpers from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import skimage.io import skimage.transform def crop_center(img, cropx, cropy): y, x,...
0.492188
0.364382
import cmd import requests import base64 import re class S4KTJPortal(cmd.Cmd): ''' Srun4K/Tongji.Portal Command Line Tool ''' intro = 'Srun4K/Tongji.Portal Command Line Tool.\nType help or ? to list commands.\n' prompt = '(TJPortal) ' req_url = 'http://192.168.192.10/include/auth_action.p...
tjportal.py
import cmd import requests import base64 import re class S4KTJPortal(cmd.Cmd): ''' Srun4K/Tongji.Portal Command Line Tool ''' intro = 'Srun4K/Tongji.Portal Command Line Tool.\nType help or ? to list commands.\n' prompt = '(TJPortal) ' req_url = 'http://192.168.192.10/include/auth_action.p...
0.105948
0.070432
import SMPythonTesting import os import os.path import sys from paraview import servermanager SMPythonTesting.ProcessCommandLineArguments() servermanager.Connect() sourceProxy = servermanager.sources.RTAnalyticSource() filterProxy = servermanager.filters.ExtractHistogram(Input=sourceProxy) filterProxy.UpdatePipeli...
ParaViewCore/ServerManager/Testing/Python/CSVWriterReader.py
import SMPythonTesting import os import os.path import sys from paraview import servermanager SMPythonTesting.ProcessCommandLineArguments() servermanager.Connect() sourceProxy = servermanager.sources.RTAnalyticSource() filterProxy = servermanager.filters.ExtractHistogram(Input=sourceProxy) filterProxy.UpdatePipeli...
0.126475
0.137475
import base64 import json import tornado.gen as gen from notebook.base.handlers import APIHandler, app_log from jupyterlab_ucaip.service import UCAIPService, ManagementService handlers = {} def _create_handler(req_type, handler): class Handler(APIHandler): """Handles the request types sent from the fronten...
jupyterlab_ucaip/jupyterlab_ucaip/handlers.py
import base64 import json import tornado.gen as gen from notebook.base.handlers import APIHandler, app_log from jupyterlab_ucaip.service import UCAIPService, ManagementService handlers = {} def _create_handler(req_type, handler): class Handler(APIHandler): """Handles the request types sent from the fronten...
0.358578
0.091301
expected_output = { "bytes_available": 13755338752, "bytes_used": 489017344, "files": { 1: { "file_date": "Oct 12 2020 07:23:32 +00:00", "file_length": 4096, "file_name": "/bootflash/" }, 2: { "file_date": "Apr 20 2017 23:08:16 +00:00", ...
src/genie/libs/parser/iosxe/tests/ShowBootflash/cli/equal/golden_output_1_expected.py
expected_output = { "bytes_available": 13755338752, "bytes_used": 489017344, "files": { 1: { "file_date": "Oct 12 2020 07:23:32 +00:00", "file_length": 4096, "file_name": "/bootflash/" }, 2: { "file_date": "Apr 20 2017 23:08:16 +00:00", ...
0.315209
0.3534
import time import copy import numpy as np from dataclasses import dataclass from bayes import LogPosterior from ReflectivitySolver import ReflectivitySolver from utils import save_run, LogWriter as logger class ProposedState(): """ Stores all variables related to a MCMC proposal.""" def __init__(self)...
src/MCMCmethods.py
import time import copy import numpy as np from dataclasses import dataclass from bayes import LogPosterior from ReflectivitySolver import ReflectivitySolver from utils import save_run, LogWriter as logger class ProposedState(): """ Stores all variables related to a MCMC proposal.""" def __init__(self)...
0.869299
0.337176
from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin, ) from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.conf import settings from allauth.account...
systori/apps/user/models.py
from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser, PermissionsMixin, ) from django.core.mail import send_mail from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from django.conf import settings from allauth.account...
0.46393
0.070913
import matplotlib.pyplot as plt import numpy as np from dskc._settings import colors from dskc.visualization.graphs.types.util import set_titles def autolabel(ax, rects, bins, horizontal=False, sum_data=1, percentage=False, value=True, flip=False): """ ...
dskc/visualization/graphs/types/bars/bars_util.py
import matplotlib.pyplot as plt import numpy as np from dskc._settings import colors from dskc.visualization.graphs.types.util import set_titles def autolabel(ax, rects, bins, horizontal=False, sum_data=1, percentage=False, value=True, flip=False): """ ...
0.593845
0.508117
import numpy as np import torch from torch import nn from q_learning.utils import * import torch.nn as nn import torch.nn.functional as F class DQN(nn.Module): def __init__(self, input_shp, out_number): super(DQN, self).__init__() h, w, c_in = input_shp # Q-learning network as described...
Project-Code/q_learning/model.py
import numpy as np import torch from torch import nn from q_learning.utils import * import torch.nn as nn import torch.nn.functional as F class DQN(nn.Module): def __init__(self, input_shp, out_number): super(DQN, self).__init__() h, w, c_in = input_shp # Q-learning network as described...
0.90262
0.457197
import subprocess import os script_location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) def simulate(mdp, top, gro, out, verbose=False, em_energy=False, mpi=False, nprocesses=4, dd=None, restraints=False): """ A wrapper for running GROMACS molecular dynamics simulations :param m...
LLC_Membranes/llclib/gromacs.py
import subprocess import os script_location = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__))) def simulate(mdp, top, gro, out, verbose=False, em_energy=False, mpi=False, nprocesses=4, dd=None, restraints=False): """ A wrapper for running GROMACS molecular dynamics simulations :param m...
0.662469
0.289359
import numpy as np import math import gym from gym import spaces from gym.utils import seeding import matplotlib.pyplot as plt UNIT_H = 20 # pixels SPEED_H = 25 # grid height DISTANCE_W =1299 # grid width UNIT_W=1 class TrainLine(gym.Env): metadata = { 'render.modes': ['human', 'rgb_array'...
dqn_env.py
import numpy as np import math import gym from gym import spaces from gym.utils import seeding import matplotlib.pyplot as plt UNIT_H = 20 # pixels SPEED_H = 25 # grid height DISTANCE_W =1299 # grid width UNIT_W=1 class TrainLine(gym.Env): metadata = { 'render.modes': ['human', 'rgb_array'...
0.438184
0.319413
import typing as t # noqa: E902 import numpy as np from ..activations import identity, relu, sigmoid, softmax from ..base import BaseLayer class Conv(BaseLayer): """2D convolutional layer. Attributes ---------- kernel_size : int Height and Width of the 2D convolution window. stride : in...
mini_keras/layers/conv2D.py
import typing as t # noqa: E902 import numpy as np from ..activations import identity, relu, sigmoid, softmax from ..base import BaseLayer class Conv(BaseLayer): """2D convolutional layer. Attributes ---------- kernel_size : int Height and Width of the 2D convolution window. stride : in...
0.806548
0.592313
import os import sys import numpy import time from subprocess import Popen, PIPE import random GPA = tuple([ 0 + i for i in range(32) ]) GPB = tuple([ 32 + i for i in range(16) ]) GPC = tuple([ 64 + i for i in range(16) ]) GPD = tuple([ 96 + i for i in range(16) ]) GPE = tuple([ 128 + i for i in range(16) ]) GPF = tup...
host/sds.py
import os import sys import numpy import time from subprocess import Popen, PIPE import random GPA = tuple([ 0 + i for i in range(32) ]) GPB = tuple([ 32 + i for i in range(16) ]) GPC = tuple([ 64 + i for i in range(16) ]) GPD = tuple([ 96 + i for i in range(16) ]) GPE = tuple([ 128 + i for i in range(16) ]) GPF = tup...
0.248261
0.305425
import pytest import numpy as np from numpy.testing import assert_equal, assert_allclose from mne_rsa import searchlight, dsm_array, compute_dsm, compute_dsm_cv from mne_rsa.dsm import _ensure_condensed, _n_items_from_dsm class TestDsm: """Test computing a DSM""" def test_basic(self): """Test basic ...
tests/test_dsm.py
import pytest import numpy as np from numpy.testing import assert_equal, assert_allclose from mne_rsa import searchlight, dsm_array, compute_dsm, compute_dsm_cv from mne_rsa.dsm import _ensure_condensed, _n_items_from_dsm class TestDsm: """Test computing a DSM""" def test_basic(self): """Test basic ...
0.816772
0.829077
import sys, os, shutil, time sys.path.append('..\\..\\') import derpapi import pygame import github as git from urllib.request import urlretrieve, urlopen, URLError RUN = False #screen init try: pygame.init() except: pygame.display.init() def install(app_files, name): if os.path.exists('....
DerPi/apps/App Store/main.py
import sys, os, shutil, time sys.path.append('..\\..\\') import derpapi import pygame import github as git from urllib.request import urlretrieve, urlopen, URLError RUN = False #screen init try: pygame.init() except: pygame.display.init() def install(app_files, name): if os.path.exists('....
0.02681
0.050729
from schema_registry.client import schema from tests import data_gen def assertLatest(self, meta_tuple, sid, schema, version): self.assertNotEqual(sid, -1) self.assertNotEqual(version, -1) self.assertEqual(meta_tuple[0], sid) self.assertEqual(meta_tuple[1], schema) self.assertEqual(meta_tuple[2], ...
tests/client/test_schema_registration.py
from schema_registry.client import schema from tests import data_gen def assertLatest(self, meta_tuple, sid, schema, version): self.assertNotEqual(sid, -1) self.assertNotEqual(version, -1) self.assertEqual(meta_tuple[0], sid) self.assertEqual(meta_tuple[1], schema) self.assertEqual(meta_tuple[2], ...
0.688154
0.578151
version = '0.3'; ONE = 1; MAX_WEIGHT = 1000000; MIN_PRECISION = 32; MAX_PRECISION = 127; ''' The values below depend on MAX_PRECISION. If you choose to change it: Apply the same change in file 'PrintIntScalingFactors.py', run it and paste the results below. ''' FIXED_1 = 0x080000000000000000000000000000000; F...
solidity/python/FormulaSolidityPort/__init__.py
version = '0.3'; ONE = 1; MAX_WEIGHT = 1000000; MIN_PRECISION = 32; MAX_PRECISION = 127; ''' The values below depend on MAX_PRECISION. If you choose to change it: Apply the same change in file 'PrintIntScalingFactors.py', run it and paste the results below. ''' FIXED_1 = 0x080000000000000000000000000000000; F...
0.253491
0.3143
from ObjectFactories.ItemFactory import ItemFactory from osOps import * from collectionOps import * from itemOps import * import datetime, argparse CONST_COLLECTIONS_NAME = 'collections' def generateArgumentsFromParser(): parser = parser = argparse.ArgumentParser(description="Runs the PyInventory utility for crea...
main.py
from ObjectFactories.ItemFactory import ItemFactory from osOps import * from collectionOps import * from itemOps import * import datetime, argparse CONST_COLLECTIONS_NAME = 'collections' def generateArgumentsFromParser(): parser = parser = argparse.ArgumentParser(description="Runs the PyInventory utility for crea...
0.452052
0.139338
from argparse import Namespace import GPy import heapq import numpy as np from rdkit import Chem from sklearn.ensemble import RandomForestRegressor import torch.nn as nn from typing import Any, Callable, List, Tuple from .predict import predict from chemprop.data import MoleculeDataset, StandardScaler from chemprop.fe...
chemprop/train/uncertainty_estimator.py
from argparse import Namespace import GPy import heapq import numpy as np from rdkit import Chem from sklearn.ensemble import RandomForestRegressor import torch.nn as nn from typing import Any, Callable, List, Tuple from .predict import predict from chemprop.data import MoleculeDataset, StandardScaler from chemprop.fe...
0.94119
0.624723
import os import pickle import atexit import random from fuzzywuzzy import process from fuzzywuzzy import fuzz import obonet # transforms OBO serialized ontologies in networks, source: https://github.com/dpavot/obonet import networkx # helps in the above # ----------------------------------------------------------...
src/ontology_preprocessing_test.py
import os import pickle import atexit import random from fuzzywuzzy import process from fuzzywuzzy import fuzz import obonet # transforms OBO serialized ontologies in networks, source: https://github.com/dpavot/obonet import networkx # helps in the above # ----------------------------------------------------------...
0.26218
0.296311
import functools import os import tempfile from unittest import mock import gin import tensorflow as tf from dedal import multi_task from dedal import vocabulary from dedal.data import builder from dedal.data import loaders from dedal.models import aligners from dedal.models import dedal from dedal.models import enco...
dedal/train/training_loop_test.py
import functools import os import tempfile from unittest import mock import gin import tensorflow as tf from dedal import multi_task from dedal import vocabulary from dedal.data import builder from dedal.data import loaders from dedal.models import aligners from dedal.models import dedal from dedal.models import enco...
0.547222
0.23316
import unittest from transformers import AutoModel from gr_nlp_toolkit.domain.document import Document from gr_nlp_toolkit.processors.pos import POS from gr_nlp_toolkit.processors.tokenizer import Tokenizer from gr_nlp_toolkit.labels.pos_labels import pos_labels, pos_properties class MyTestCase(unittest.TestCase): ...
test_gr_nlp_toolkit/test_processors/test_pos.py
import unittest from transformers import AutoModel from gr_nlp_toolkit.domain.document import Document from gr_nlp_toolkit.processors.pos import POS from gr_nlp_toolkit.processors.tokenizer import Tokenizer from gr_nlp_toolkit.labels.pos_labels import pos_labels, pos_properties class MyTestCase(unittest.TestCase): ...
0.535827
0.612484
import decimal import unittest from orchid import ( measurement as om, unit_system as units, ) from tests import (custom_matchers as tcm) from hamcrest import assert_that, equal_to class TestUnitSystem(unittest.TestCase): def test_canary(self): assert_that(2 + 2, equal_to(4)) def test_abb...
tests/test_unit_system.py
import decimal import unittest from orchid import ( measurement as om, unit_system as units, ) from tests import (custom_matchers as tcm) from hamcrest import assert_that, equal_to class TestUnitSystem(unittest.TestCase): def test_canary(self): assert_that(2 + 2, equal_to(4)) def test_abb...
0.715523
0.557424
import re def no_process(date_time_str): return date_time_str def fill_minutes(date_time_str): return re.sub(r"(?<![:\d])(\d{1,2})(AM|PM)", r"\1:00\2", date_time_str, 0, re.IGNORECASE) WN_FUNCTION_REGEX = re.compile(r'wn(\s+(?P<year>\d{4}))?' r'(\s+(?P<week_number>\d{1,2}))?'...
date_format_mappings.py
import re def no_process(date_time_str): return date_time_str def fill_minutes(date_time_str): return re.sub(r"(?<![:\d])(\d{1,2})(AM|PM)", r"\1:00\2", date_time_str, 0, re.IGNORECASE) WN_FUNCTION_REGEX = re.compile(r'wn(\s+(?P<year>\d{4}))?' r'(\s+(?P<week_number>\d{1,2}))?'...
0.496582
0.341473
import json import os import random from typing import Tuple import numpy as np import torch from PIL import Image from torchvision.datasets import VisionDataset from torchvision.datasets.folder import is_image_file def read_annotation_file(path, img_root): with open(path) as annotation_file: annotation_...
geo/dataset.py
import json import os import random from typing import Tuple import numpy as np import torch from PIL import Image from torchvision.datasets import VisionDataset from torchvision.datasets.folder import is_image_file def read_annotation_file(path, img_root): with open(path) as annotation_file: annotation_...
0.723505
0.33463
import numpy as np import xml.etree.cElementTree as ET from xml.dom import minidom from ase.data import atomic_masses from ase.units import eV, Hartree, Bohr, Ry, J import os from collections import Iterable, namedtuple from itertools import groupby from TB2J.utils import symbol_number import pickle def write_tom_ucf...
TB2J/io_exchange/io_tomsasd.py
import numpy as np import xml.etree.cElementTree as ET from xml.dom import minidom from ase.data import atomic_masses from ase.units import eV, Hartree, Bohr, Ry, J import os from collections import Iterable, namedtuple from itertools import groupby from TB2J.utils import symbol_number import pickle def write_tom_ucf...
0.226441
0.247044
# Std library imports import os import os.path as osp from setuptools import setup import shutil import sys import subprocess from distutils.command.install_data import install_data # Third party imports # Local imports # ============================================================================= # Constants # ==...
setup.py
# Std library imports import os import os.path as osp from setuptools import setup import shutil import sys import subprocess from distutils.command.install_data import install_data # Third party imports # Local imports # ============================================================================= # Constants # ==...
0.351756
0.093802
from __future__ import print_function from collections import defaultdict from datetime import datetime from tempfile import mkstemp import codecs import gc import logging import os import re import time from praw import Reddit from prawcore.exceptions import RequestException from six import iteritems, text_type as t...
prawtools/stats.py
from __future__ import print_function from collections import defaultdict from datetime import datetime from tempfile import mkstemp import codecs import gc import logging import os import re import time from praw import Reddit from prawcore.exceptions import RequestException from six import iteritems, text_type as t...
0.677261
0.084417
from typing import List, Sequence, Tuple import numpy as np from deepchem.utils.typing import RDKitAtom, RDKitBond, RDKitMol from deepchem.feat.graph_data import GraphData from deepchem.feat.base_classes import MolecularFeaturizer from deepchem.utils.molecule_feature_utils import get_atom_type_one_hot, \ construct_h...
deepchem/feat/molecule_featurizers/mol_graph_conv_featurizer.py
from typing import List, Sequence, Tuple import numpy as np from deepchem.utils.typing import RDKitAtom, RDKitBond, RDKitMol from deepchem.feat.graph_data import GraphData from deepchem.feat.base_classes import MolecularFeaturizer from deepchem.utils.molecule_feature_utils import get_atom_type_one_hot, \ construct_h...
0.960435
0.54353
from h2oaicore.transformer_utils import CustomTransformer import datatable as dt import numpy as np import string class WordBaseTransformer: @staticmethod def get_default_properties(): return dict(col_type="text", min_cols=1, max_cols=1, relative_importance=1) def fit_transform(self, X: dt.Frame,...
transformers/nlp/text_meta_transformers.py
from h2oaicore.transformer_utils import CustomTransformer import datatable as dt import numpy as np import string class WordBaseTransformer: @staticmethod def get_default_properties(): return dict(col_type="text", min_cols=1, max_cols=1, relative_importance=1) def fit_transform(self, X: dt.Frame,...
0.708112
0.542257
import torch from .shape_layer import ShapeLayer from .homogeneous_transform_layer import HomogeneousTransformationLayer class HomogeneousShapeLayer(torch.nn.Module): """ Module to Perform a Shape Prediction (including a global homogeneous transformation) """ def __init__(self, shapes, n_dims, u...
shapenet/layer/homogeneous_shape_layer.py
import torch from .shape_layer import ShapeLayer from .homogeneous_transform_layer import HomogeneousTransformationLayer class HomogeneousShapeLayer(torch.nn.Module): """ Module to Perform a Shape Prediction (including a global homogeneous transformation) """ def __init__(self, shapes, n_dims, u...
0.94502
0.473962
create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,'lid':'1' ,'n1':'B' ,'n2':'B'}) create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,'lid':'2' ,'n1':'+' ,'n2':'B'}) create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,'lid':'3' ,'n1':'B' ,'n2':'+'}) create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,...
testpy/waltzdb_data.py
create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,'lid':'1' ,'n1':'B' ,'n2':'B'}) create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,'lid':'2' ,'n1':'+' ,'n2':'B'}) create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,'lid':'3' ,'n1':'B' ,'n2':'+'}) create_and_assert({'t':'label' ,'j_t':'2j' ,'name':'L' ,...
0.149935
0.184786
from peewee import * from playhouse.migrate import migrate from config import database, migrator import datetime database.connect() def atomic(): ''' To run a bunch of stuff within a transaction; e.g.: with model.atomic() as xact: foo bar baz if error: xact.rollba...
dc_common/model.py
from peewee import * from playhouse.migrate import migrate from config import database, migrator import datetime database.connect() def atomic(): ''' To run a bunch of stuff within a transaction; e.g.: with model.atomic() as xact: foo bar baz if error: xact.rollba...
0.694717
0.170681
lst = [6, 7, 3, 0, 4, 8, 15, 4] # 冒泡排序算法 def bubbleSort(arr): sum = len(arr) for i in range(sum - 1): for j in range(sum - i - 1): if arr[j] < arr[j + 1]: temp = arr[j + 1] arr[j + 1] = arr[j] arr[j] = temp # 插入排序算法 def insertionSort(arr): ...
arithmetic/sort.py
lst = [6, 7, 3, 0, 4, 8, 15, 4] # 冒泡排序算法 def bubbleSort(arr): sum = len(arr) for i in range(sum - 1): for j in range(sum - i - 1): if arr[j] < arr[j + 1]: temp = arr[j + 1] arr[j + 1] = arr[j] arr[j] = temp # 插入排序算法 def insertionSort(arr): ...
0.175856
0.495728