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 from game_binary_search import try_guest_hacker, init_game class GameMatrix: def create_game(self): self.create_matrix() self.position_init_player() self.position_init_hacker() def create_matrix(self, matrix_width: int = 0, matrix_height: int = 0): ''' 1: ...
python/binary_search/game_matrix.py
import numpy from game_binary_search import try_guest_hacker, init_game class GameMatrix: def create_game(self): self.create_matrix() self.position_init_player() self.position_init_hacker() def create_matrix(self, matrix_width: int = 0, matrix_height: int = 0): ''' 1: ...
0.338733
0.272835
from . import ProgressiveTest from progressivis.core import aio from progressivis import Every from progressivis.stats.blobs_table import BlobsTable, MVBlobsTable from progressivis.stats.random_table import RandomTable from progressivis.linalg import Add import numpy as np from progressivis.io import CSVLoader def prin...
tests/test_03_blobs_table.py
from . import ProgressiveTest from progressivis.core import aio from progressivis import Every from progressivis.stats.blobs_table import BlobsTable, MVBlobsTable from progressivis.stats.random_table import RandomTable from progressivis.linalg import Add import numpy as np from progressivis.io import CSVLoader def prin...
0.403214
0.40751
class CustomGlyph(object): def __init__(self, prefix, name, opts=None): self._prefix = prefix self._name = name self._opts = opts @property def value(self): if type(self._name) is tuple or type(self._name) is list: return " ".join("%s-%s" % (self._prefix, self...
igdectk/bootstrap/customglyph.py
class CustomGlyph(object): def __init__(self, prefix, name, opts=None): self._prefix = prefix self._name = name self._opts = opts @property def value(self): if type(self._name) is tuple or type(self._name) is list: return " ".join("%s-%s" % (self._prefix, self...
0.731922
0.075961
import tensorflow as tf import math num_classes = 85742 # 10572 initializer = 'glorot_normal' # initializer = tf.keras.initializers.TruncatedNormal( # mean=0.0, stddev=0.05, seed=None) # initializer = tf.keras.initializers.VarianceScaling( # scale=0.05, mode='fan_avg', distribution='normal', seed=None) clas...
model/arcface/arcface.py
import tensorflow as tf import math num_classes = 85742 # 10572 initializer = 'glorot_normal' # initializer = tf.keras.initializers.TruncatedNormal( # mean=0.0, stddev=0.05, seed=None) # initializer = tf.keras.initializers.VarianceScaling( # scale=0.05, mode='fan_avg', distribution='normal', seed=None) clas...
0.790652
0.364523
from math import ceil S0 = [ 0x3E, 0x72, 0x5B, 0x47, 0xCA, 0xE0, 0x00, 0x33, 0x04, 0xD1, 0x54, 0x98, 0x09, 0xB9, 0x6D, 0xCB, 0x7B, 0x1B, 0xF9, 0x32, 0xAF, 0x9D, 0x6A, 0xA5, 0xB8, 0x2D, 0xFC, 0x1D, 0x08, 0x53, 0x03, 0x90, 0x4D, 0x4E, 0x84, 0x99, 0xE4, 0xCE, 0xD9, 0x91, 0xDD, 0xB6, 0x85, 0x48, 0x8B, 0x29, 0...
pysmx/ZUC/_ZUC.py
from math import ceil S0 = [ 0x3E, 0x72, 0x5B, 0x47, 0xCA, 0xE0, 0x00, 0x33, 0x04, 0xD1, 0x54, 0x98, 0x09, 0xB9, 0x6D, 0xCB, 0x7B, 0x1B, 0xF9, 0x32, 0xAF, 0x9D, 0x6A, 0xA5, 0xB8, 0x2D, 0xFC, 0x1D, 0x08, 0x53, 0x03, 0x90, 0x4D, 0x4E, 0x84, 0x99, 0xE4, 0xCE, 0xD9, 0x91, 0xDD, 0xB6, 0x85, 0x48, 0x8B, 0x29, 0...
0.118627
0.582343
import itertools import json import os import uuid import begin import yaml def apt_get(*packages): return ('apt-get update && apt-get install --no-install-recommends --yes' ' {}'.format(' '.join(packages))) TOOLS = [apt_get('git')] @begin.start def main(config='.travis.yml', destdir='.'): c...
travis_runner/generate.py
import itertools import json import os import uuid import begin import yaml def apt_get(*packages): return ('apt-get update && apt-get install --no-install-recommends --yes' ' {}'.format(' '.join(packages))) TOOLS = [apt_get('git')] @begin.start def main(config='.travis.yml', destdir='.'): c...
0.275032
0.082217
import json class MatchDto: def __init__(self, jsonData): #self.jsonData = jsonData # self.seasonId = jsonData["seasonId"] if "seasonId" in jsonData else None self.queueId = jsonData["queueId"] if "queueId" in jsonData else None self.gameId = jsonData["gameId"] if "gameId" in jsonDa...
Python/Src/lolData/matchData.py
import json class MatchDto: def __init__(self, jsonData): #self.jsonData = jsonData # self.seasonId = jsonData["seasonId"] if "seasonId" in jsonData else None self.queueId = jsonData["queueId"] if "queueId" in jsonData else None self.gameId = jsonData["gameId"] if "gameId" in jsonDa...
0.145783
0.055387
"""Unit tests for PreviewItem.""" from __future__ import unicode_literals import unittest from mock import mock from collections import OrderedDict import pywikibot from wikidatastuff.preview_item import PreviewItem from wikidatastuff.qualifier import Qualifier # replace with mocks from wikidatastuff.statement impo...
tests/test_preview_item.py
"""Unit tests for PreviewItem.""" from __future__ import unicode_literals import unittest from mock import mock from collections import OrderedDict import pywikibot from wikidatastuff.preview_item import PreviewItem from wikidatastuff.qualifier import Qualifier # replace with mocks from wikidatastuff.statement impo...
0.864654
0.44903
import numpy as np import mxnet as mx from .stationary import StationaryKernel class Matern(StationaryKernel): """ Matern kernel: .. math:: k(r^2) = \\sigma^2 \\exp \\bigg(- \\frac{1}{2} r^2 \\bigg) :param input_dim: the number of dimensions of the kernel. (The total number of active dimens...
mxfusion/components/distributions/gp/kernels/matern.py
import numpy as np import mxnet as mx from .stationary import StationaryKernel class Matern(StationaryKernel): """ Matern kernel: .. math:: k(r^2) = \\sigma^2 \\exp \\bigg(- \\frac{1}{2} r^2 \\bigg) :param input_dim: the number of dimensions of the kernel. (The total number of active dimens...
0.922474
0.740433
import requests import json import sqlite3 import datetime import mysql.connector import os, shutil, datetime, sys import csv, json import codecs import time from threading import Thread # Creates database on Amazon MySQL RDS if does not exist def create_Database(): cnx = mysql.connector.Connect(user='root', pass...
dublin_bikes/src/DataRetrieval.py
import requests import json import sqlite3 import datetime import mysql.connector import os, shutil, datetime, sys import csv, json import codecs import time from threading import Thread # Creates database on Amazon MySQL RDS if does not exist def create_Database(): cnx = mysql.connector.Connect(user='root', pass...
0.250821
0.239344
import pprint import re # noqa: F401 import six class TpoDataDTOsERXPatientPrescriptionsActivityDispenseTrackDTO(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attri...
swagger_client/models/tpo_data_dt_os_erx_patient_prescriptions_activity_dispense_track_dto.py
import pprint import re # noqa: F401 import six class TpoDataDTOsERXPatientPrescriptionsActivityDispenseTrackDTO(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attri...
0.610686
0.135632
from pathlib import Path import shutil from tempfile import TemporaryFile from archive import Archive from archive.tools import tmp_chdir import pytest from conftest import * # Setup a directory with some test data to be put into an archive. # Make sure that we have all kind of different things in there. testdata = [...
tests/test_04_cli_diff.py
from pathlib import Path import shutil from tempfile import TemporaryFile from archive import Archive from archive.tools import tmp_chdir import pytest from conftest import * # Setup a directory with some test data to be put into an archive. # Make sure that we have all kind of different things in there. testdata = [...
0.295027
0.418578
import unittest from . import util from coloraide import Color class TestLabInputOutput(util.ColorAsserts, unittest.TestCase): """Test Lab.""" def test_input_raw(self): """Test raw input.""" self.assertColorEqual(Color("lab", [20, 10, -30]), Color('lab(20% 10 -30)')) def test_color_clas...
tests/test_lab.py
import unittest from . import util from coloraide import Color class TestLabInputOutput(util.ColorAsserts, unittest.TestCase): """Test Lab.""" def test_input_raw(self): """Test raw input.""" self.assertColorEqual(Color("lab", [20, 10, -30]), Color('lab(20% 10 -30)')) def test_color_clas...
0.828002
0.835215
import sys import logging import numpy as np import matplotlib.pyplot as plt from pathlib import Path from beyond.orbits.listeners import LightListener from beyond.errors import UnknownFrameError from .utils import circle, docopt, parse_date, parse_timedelta from .station import StationDb from .sat import Sat log =...
space/passes.py
import sys import logging import numpy as np import matplotlib.pyplot as plt from pathlib import Path from beyond.orbits.listeners import LightListener from beyond.errors import UnknownFrameError from .utils import circle, docopt, parse_date, parse_timedelta from .station import StationDb from .sat import Sat log =...
0.523664
0.344278
import pygame, sys, random skier_images=["skier_down.png", "skier_right1.png", "skier_right2.png", "skier_left2.png", "skier_left1.png"] class SkierClass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("skier_down.png") self.rect...
dxj/skier.py
import pygame, sys, random skier_images=["skier_down.png", "skier_right1.png", "skier_right2.png", "skier_left2.png", "skier_left1.png"] class SkierClass(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("skier_down.png") self.rect...
0.228931
0.521654
from __future__ import division, print_function # Import Python modules import os import sys # Import Broadband modules from install_cfg import InstallCfg import bband_utils import plot_seismograms # ------------------------------------------------------------------------------ # Constants # ------------------------...
bbp/comps/bbp_tools.py
from __future__ import division, print_function # Import Python modules import os import sys # Import Broadband modules from install_cfg import InstallCfg import bband_utils import plot_seismograms # ------------------------------------------------------------------------------ # Constants # ------------------------...
0.331444
0.184106
from sqlalchemy import func from sqlalchemy.exc import SQLAlchemyError from flask_sqlalchemy import SQLAlchemy from sqlalchemy import and_ from common.database import db import uuid class TreeManager: def __init__(self, model_obj=None, session=None): self.__model = model_obj self.__session = sess...
api/common/satree.py
from sqlalchemy import func from sqlalchemy.exc import SQLAlchemyError from flask_sqlalchemy import SQLAlchemy from sqlalchemy import and_ from common.database import db import uuid class TreeManager: def __init__(self, model_obj=None, session=None): self.__model = model_obj self.__session = sess...
0.398992
0.106365
from . AnalyserBase import AnalyserBaseClass import functools import logging import os import re import yaml _logger = logging.getLogger(__name__) class SymbooglixAnalyser(AnalyserBaseClass): def __init__(self, resultDict): super(SymbooglixAnalyser, self).__init__(resultDict) assert 'backend_timeout' in sel...
BoogieRunner/Analysers/Symbooglix.py
from . AnalyserBase import AnalyserBaseClass import functools import logging import os import re import yaml _logger = logging.getLogger(__name__) class SymbooglixAnalyser(AnalyserBaseClass): def __init__(self, resultDict): super(SymbooglixAnalyser, self).__init__(resultDict) assert 'backend_timeout' in sel...
0.237311
0.1526
import agentos import numpy as np import tensorflow as tf from tensorflow import keras import tensorflow_probability as tfp class Policy: def __init__(self): self.nn = keras.Sequential( [ keras.layers.Dense(4, activation="relu", input_shape=(4,)), keras.layers.D...
example_agents/rl_agents/reinforce_agent.py
import agentos import numpy as np import tensorflow as tf from tensorflow import keras import tensorflow_probability as tfp class Policy: def __init__(self): self.nn = keras.Sequential( [ keras.layers.Dense(4, activation="relu", input_shape=(4,)), keras.layers.D...
0.860061
0.297036
import jsonschema2md class TestParser: test_schema = { "$id": "https://example.com/arrays.schema.json", "$schema": "http://json-schema.org/draft-07/schema#", "description": "Vegetable preferences", "type": "object", "properties": { "fruits": {"type": "array", "i...
tests/test_jsonschema2md.py
import jsonschema2md class TestParser: test_schema = { "$id": "https://example.com/arrays.schema.json", "$schema": "http://json-schema.org/draft-07/schema#", "description": "Vegetable preferences", "type": "object", "properties": { "fruits": {"type": "array", "i...
0.841793
0.555978
from tensorflow.keras.callbacks import Callback import tensorflow.keras.backend as K import numpy as np class CosineAnnealingScheduler(Callback): def __init__(self, cycle_iterations, min_lr, t_mu=2, start_iteration=0): self.iteration_id = 0 self.start_iteration = start_iteration self.cycle...
callbacks.py
from tensorflow.keras.callbacks import Callback import tensorflow.keras.backend as K import numpy as np class CosineAnnealingScheduler(Callback): def __init__(self, cycle_iterations, min_lr, t_mu=2, start_iteration=0): self.iteration_id = 0 self.start_iteration = start_iteration self.cycle...
0.774882
0.163345
import os import numpy as np import scipy.sparse as sp import scipy.io as sio import sys import re from utility import * def parse_arg(): """ utility function to parse argument from command line """ parser = optparse.OptionParser() parser.add_option('-k', dest='K', default=None, help='# of polarized commun...
sbm_groundtruth.py
import os import numpy as np import scipy.sparse as sp import scipy.io as sio import sys import re from utility import * def parse_arg(): """ utility function to parse argument from command line """ parser = optparse.OptionParser() parser.add_option('-k', dest='K', default=None, help='# of polarized commun...
0.238462
0.244104
from odoo import api, fields, models from odoo.addons.onesphere_assembly_industry.constants import ASSEMBLY_TOOLS_TECH_NAME, TIGHTENING_TEST_TYPE from odoo.exceptions import ValidationError class MrpWorkcenterGroup(models.Model): _inherit = 'mrp.workcenter.group' # 创建工作中心组时更新拧紧工具组数据 @api.model...
server/onesphere/onesphere_assembly_industry/models/mrp_workcenter_group_tool.py
from odoo import api, fields, models from odoo.addons.onesphere_assembly_industry.constants import ASSEMBLY_TOOLS_TECH_NAME, TIGHTENING_TEST_TYPE from odoo.exceptions import ValidationError class MrpWorkcenterGroup(models.Model): _inherit = 'mrp.workcenter.group' # 创建工作中心组时更新拧紧工具组数据 @api.model...
0.208662
0.059784
from pathlib import Path import pytest from unittest.mock import patch, call, Mock from typing import Union, List, Tuple from boar.__init__ import Notebook, BoarError @pytest.mark.ut @pytest.mark.parametrize("counts,expected_cell_counts", [ ([None], []), ([None, None, None], []), ([None, 3, None], [(2, ...
tests/utils/test_parse.py
from pathlib import Path import pytest from unittest.mock import patch, call, Mock from typing import Union, List, Tuple from boar.__init__ import Notebook, BoarError @pytest.mark.ut @pytest.mark.parametrize("counts,expected_cell_counts", [ ([None], []), ([None, None, None], []), ([None, 3, None], [(2, ...
0.854688
0.704236
import numpy as np from matplotlib import pyplot as plt c=2.99e+08 #speed of light in m/s mhz=1.0e+06 def createFrequency(numin=700.,numax=1800.,nchan=100.): # Create an array of evenly spaced frequencies # numin and numax are in [MHz] # =========================================== numax=numax*mhz ...
create_spectrum.py
import numpy as np from matplotlib import pyplot as plt c=2.99e+08 #speed of light in m/s mhz=1.0e+06 def createFrequency(numin=700.,numax=1800.,nchan=100.): # Create an array of evenly spaced frequencies # numin and numax are in [MHz] # =========================================== numax=numax*mhz ...
0.252845
0.444143
from .e2Enum import E2Enum import gi gi.require_version('Atspi', '2.0') from gi.repository import Atspi class E2Role(E2Enum): INVALID = (hash(Atspi.Role(0)), Atspi.Role.get_name(Atspi.Role(0))) ACCELERATOR_LABEL = (hash(Atspi.Role(1)), Atspi.Role.get_name(Atspi.Role(1))) ALERT = (hash(Atspi.Role(2)), Atspi...
py2End/Enums/e2Role.py
from .e2Enum import E2Enum import gi gi.require_version('Atspi', '2.0') from gi.repository import Atspi class E2Role(E2Enum): INVALID = (hash(Atspi.Role(0)), Atspi.Role.get_name(Atspi.Role(0))) ACCELERATOR_LABEL = (hash(Atspi.Role(1)), Atspi.Role.get_name(Atspi.Role(1))) ALERT = (hash(Atspi.Role(2)), Atspi...
0.303732
0.151938
from django.conf import settings from userservice.user import UserService from uw_sws_graderoster.models import GradingScale from course_grader.dao.person import person_display_name from course_grader.dao.term import ( submission_deadline_warning, is_grading_period_open) from course_grader.views.rest_dispatch impo...
course_grader/views/api/__init__.py
from django.conf import settings from userservice.user import UserService from uw_sws_graderoster.models import GradingScale from course_grader.dao.person import person_display_name from course_grader.dao.term import ( submission_deadline_warning, is_grading_period_open) from course_grader.views.rest_dispatch impo...
0.346873
0.144149
from django.core.validators import RegexValidator validate_slug = RegexValidator( regex=r'^[a-z0-9-]+$', message='The slug may only contain lower case letters (a–z), numbers (0–9) and dashes (-).', code='invalid_slug', ) validate_path = RegexValidator( regex=r'^/[a-z0-9-/]+$', message='The path m...
backend/edegal/models/common.py
from django.core.validators import RegexValidator validate_slug = RegexValidator( regex=r'^[a-z0-9-]+$', message='The slug may only contain lower case letters (a–z), numbers (0–9) and dashes (-).', code='invalid_slug', ) validate_path = RegexValidator( regex=r'^/[a-z0-9-/]+$', message='The path m...
0.540924
0.368747
import json data = [] with open('company-officers.json') as f: for line in f: data.append(json.loads(line)) #%% REFORMATTING DATA FOR SIMPLER MANIPULATION all_company_numbers_lst = [] all_officer_names_lst = [] all_first_names_lst = [] all_active_inactive_flags = [] for row in range(len(data)): ...
companies-house-api/vk/company_officer_gender.py
import json data = [] with open('company-officers.json') as f: for line in f: data.append(json.loads(line)) #%% REFORMATTING DATA FOR SIMPLER MANIPULATION all_company_numbers_lst = [] all_officer_names_lst = [] all_first_names_lst = [] all_active_inactive_flags = [] for row in range(len(data)): ...
0.068238
0.100392
import os, sys sys.path.append('tools') from get_iEEG_data import get_iEEG_data from plot_iEEG_data import plot_iEEG_data from line_length import line_length from get_iEEG_duration import get_iEEG_duration from pull_sz_starts import pull_sz_starts from pull_sz_ends import pull_sz_ends import json import numpy as np ...
code/02-get_features.py
import os, sys sys.path.append('tools') from get_iEEG_data import get_iEEG_data from plot_iEEG_data import plot_iEEG_data from line_length import line_length from get_iEEG_duration import get_iEEG_duration from pull_sz_starts import pull_sz_starts from pull_sz_ends import pull_sz_ends import json import numpy as np ...
0.538255
0.271167
import unittest import numpy as np from intfft import fft, ifft class TestFFT(unittest.TestCase): # confirm the input arguments . def _test_fft_input_type(self, dtype): xr1 = np.arange(2**7, dtype=dtype) xi1 = np.arange(2**7, dtype=dtype) _, _ = fft(xr1, xi1) def test_fft_input_type...
test_fft.py
import unittest import numpy as np from intfft import fft, ifft class TestFFT(unittest.TestCase): # confirm the input arguments . def _test_fft_input_type(self, dtype): xr1 = np.arange(2**7, dtype=dtype) xi1 = np.arange(2**7, dtype=dtype) _, _ = fft(xr1, xi1) def test_fft_input_type...
0.310067
0.414543
from __future__ import print_function import os import textwrap import xml.etree.ElementTree as ET def join_all_element_text(el, sep=""): bits = [] for txt in el.itertext(): bits.append(txt) return sep.join(bits) def remove_empty_header_or_footer_lines(lines): while lines and not lines[0].str...
tools/doxygen_utils.py
from __future__ import print_function import os import textwrap import xml.etree.ElementTree as ET def join_all_element_text(el, sep=""): bits = [] for txt in el.itertext(): bits.append(txt) return sep.join(bits) def remove_empty_header_or_footer_lines(lines): while lines and not lines[0].str...
0.306008
0.099077
from functools import partial import numpy as np import pandas as pd import random import json import os import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import random_split import torchvision import torchvision.transfor...
Simulations/train_eval_pocnn.py
from functools import partial import numpy as np import pandas as pd import random import json import os import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import random_split import torchvision import torchvision.transfor...
0.790813
0.286612
import os from opsbro.httpclient import get_http_exceptions, httper from opsbro.hostingdrivermanager import InterfaceHostingDriver, HOSTING_DRIVER_LAYER_CLOUD from opsbro.jsonmgr import jsoner class GoogleCloudHostingDriver(InterfaceHostingDriver): name = 'google-cloud' layer = HOSTING_DRIVER_LAYER_CLOUD ...
data/global-configuration/packs/google-cloud/hostingdrivers/hostingdriver_googlecloud.py
import os from opsbro.httpclient import get_http_exceptions, httper from opsbro.hostingdrivermanager import InterfaceHostingDriver, HOSTING_DRIVER_LAYER_CLOUD from opsbro.jsonmgr import jsoner class GoogleCloudHostingDriver(InterfaceHostingDriver): name = 'google-cloud' layer = HOSTING_DRIVER_LAYER_CLOUD ...
0.227469
0.117953
from kubernetes import client, config, watch import logging RESTART_POLICY = "Never" class AccessModes(object): READ_WRITE_MANY = "ReadWriteMany" READ_WRITE_ONCE = "ReadWriteOnce" READ_ONLY_MANY = "ReadOnlyMany" class JobConditionType(object): COMPLETE = "Complete" FAILED = "Failed" class Eve...
lando/k8s/cluster.py
from kubernetes import client, config, watch import logging RESTART_POLICY = "Never" class AccessModes(object): READ_WRITE_MANY = "ReadWriteMany" READ_WRITE_ONCE = "ReadWriteOnce" READ_ONLY_MANY = "ReadOnlyMany" class JobConditionType(object): COMPLETE = "Complete" FAILED = "Failed" class Eve...
0.65368
0.161816
import json import sqlite3 class SqliteDatabase(object): def __init__(self, filename="ladon.db"): self.connection = sqlite3.connect(filename) c = self.connection.cursor() c.execute( "CREATE TABLE IF NOT EXISTS providers (" "name TEXT UNIQUE NOT NULL," "i...
src/ladon/database.py
import json import sqlite3 class SqliteDatabase(object): def __init__(self, filename="ladon.db"): self.connection = sqlite3.connect(filename) c = self.connection.cursor() c.execute( "CREATE TABLE IF NOT EXISTS providers (" "name TEXT UNIQUE NOT NULL," "i...
0.438785
0.117547
import os import numpy as np from locs.utils.flags import build_flags import locs.models.model_builder as model_builder from locs.datasets.ind_data import IndData, ind_collate_fn import locs.training.train_dynamicvars as train import locs.training.train_utils as train_utils import locs.training.evaluate as evaluate i...
locs/experiments/ind_experiment.py
import os import numpy as np from locs.utils.flags import build_flags import locs.models.model_builder as model_builder from locs.datasets.ind_data import IndData, ind_collate_fn import locs.training.train_dynamicvars as train import locs.training.train_utils as train_utils import locs.training.evaluate as evaluate i...
0.275714
0.137648
import inspect import socket from uuid import UUID from importlib import import_module from types import GeneratorType from typing import ( List, Dict, ForwardRef, Text, Tuple, Set, Type, _GenericAlias as GenericAlias, Callable ) from copy import deepcopy DictKeySet = type({}.keys()) DictValueSet = type({}....
ravel/util/misc_functions.py
import inspect import socket from uuid import UUID from importlib import import_module from types import GeneratorType from typing import ( List, Dict, ForwardRef, Text, Tuple, Set, Type, _GenericAlias as GenericAlias, Callable ) from copy import deepcopy DictKeySet = type({}.keys()) DictValueSet = type({}....
0.730386
0.184565
from optparse import OptionParser import numpy as np from scipy import sparse from scipy.special import expit from sklearn.linear_model import LogisticRegression import lrb def main(): usage = "%prog" parser = OptionParser(usage=usage) parser.add_option('--elim', action="store_true", dest="elimination",...
test_lrb.py
from optparse import OptionParser import numpy as np from scipy import sparse from scipy.special import expit from sklearn.linear_model import LogisticRegression import lrb def main(): usage = "%prog" parser = OptionParser(usage=usage) parser.add_option('--elim', action="store_true", dest="elimination",...
0.672977
0.20345
from numpy import pi PI_FRAC_DICT = { 'zero': 0.0, 'piHalf3': 1.5, 'pi': 1.0, 'piHalf': 0.5, 'piQuad': 0.25, 'piOct': 0.125, 'piPent': 0.2, 'piHex': 1. / 6, 'piHept': 1. / 7, 'piNon': 1. / 9, 'piDec': 0.1, 'piUndec': 1. / 11, 'piDodec': 1. / 12, 'piTridec': 1. / ...
qdicts.py
from numpy import pi PI_FRAC_DICT = { 'zero': 0.0, 'piHalf3': 1.5, 'pi': 1.0, 'piHalf': 0.5, 'piQuad': 0.25, 'piOct': 0.125, 'piPent': 0.2, 'piHex': 1. / 6, 'piHept': 1. / 7, 'piNon': 1. / 9, 'piDec': 0.1, 'piUndec': 1. / 11, 'piDodec': 1. / 12, 'piTridec': 1. / ...
0.510741
0.268405
import argparse from collections import Counter def parse_args(): parser = argparse.ArgumentParser(description='Clean dataset') parser.add_argument('-f1', '--file1', help='file1') parser.add_argument('-f2', '--file2', help='file2') return parser.parse_args() def save_output(fname, data): with o...
DeepLearningExamples/PyTorch/Translation/GNMT/scripts/filter_dataset.py
import argparse from collections import Counter def parse_args(): parser = argparse.ArgumentParser(description='Clean dataset') parser.add_argument('-f1', '--file1', help='file1') parser.add_argument('-f2', '--file2', help='file2') return parser.parse_args() def save_output(fname, data): with o...
0.446253
0.407923
""" Contains classes that implement the trivial-tasklet-elimination transformation. """ from dace import data, registry from dace.sdfg import nodes from dace.sdfg import utils as sdutil from dace.transformation import transformation from dace.properties import make_properties @make_properties class TrivialTaskletEli...
dace/transformation/dataflow/trivial_tasklet_elimination.py
""" Contains classes that implement the trivial-tasklet-elimination transformation. """ from dace import data, registry from dace.sdfg import nodes from dace.sdfg import utils as sdutil from dace.transformation import transformation from dace.properties import make_properties @make_properties class TrivialTaskletEli...
0.719482
0.466238
from __future__ import unicode_literals, division, absolute_import import argparse import cgi import copy from datetime import datetime from json import JSONEncoder from builtins import * # pylint: disable=unused-import, redefined-builtin from flask import jsonify, Response from flask import request from queue impor...
flexget/api/tasks.py
from __future__ import unicode_literals, division, absolute_import import argparse import cgi import copy from datetime import datetime from json import JSONEncoder from builtins import * # pylint: disable=unused-import, redefined-builtin from flask import jsonify, Response from flask import request from queue impor...
0.53777
0.056993
import os import re import sys import subprocess versions = [] def success_message(string): print('\n\033[92m %s \033[0m \n' % (string)) def error_message(string): print('\033[91m %s \033[0m \n' % (string)) def runCommand(command): try: process = subprocess.Popen(command, stdout=subprocess.P...
switcher.py
import os import re import sys import subprocess versions = [] def success_message(string): print('\n\033[92m %s \033[0m \n' % (string)) def error_message(string): print('\033[91m %s \033[0m \n' % (string)) def runCommand(command): try: process = subprocess.Popen(command, stdout=subprocess.P...
0.075361
0.053059
import sys from functools import partial from emmental.scorer import Scorer from emmental.task import EmmentalTask from modules.bert_module import BertModule from modules.wsc_module import SpanClassifierModule from task_config import SuperGLUE_TASK_METRIC_MAPPING from torch import nn from . import utils sys.path.app...
superglue/models/wsc.py
import sys from functools import partial from emmental.scorer import Scorer from emmental.task import EmmentalTask from modules.bert_module import BertModule from modules.wsc_module import SpanClassifierModule from task_config import SuperGLUE_TASK_METRIC_MAPPING from torch import nn from . import utils sys.path.app...
0.40439
0.125039
from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division import numpy as np from scipy.constants import mu_0, pi, epsilon_0 from scipy.special import erfc, erf from SimPEG import Utils # TODO: # r = lambda dx, dy, dz: np.sqrt( ...
em_examples/TDEMDipolarfields.py
from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division import numpy as np from scipy.constants import mu_0, pi, epsilon_0 from scipy.special import erfc, erf from SimPEG import Utils # TODO: # r = lambda dx, dy, dz: np.sqrt( ...
0.630912
0.513607
from django.db import connection from django.urls import reverse from rest_framework.test import APITestCase from citizens.models import Citizen from webinar_helps.tests.factories import CitizenFactory class TestCitizenListAPIView(APITestCase): def setUp(self): self.citizen_judy = CitizenFactory( ...
webinar_helps/_versions/test02.py
from django.db import connection from django.urls import reverse from rest_framework.test import APITestCase from citizens.models import Citizen from webinar_helps.tests.factories import CitizenFactory class TestCitizenListAPIView(APITestCase): def setUp(self): self.citizen_judy = CitizenFactory( ...
0.479991
0.218294
import matplotlib.pylab as plt import numpy as np import pandas as pd import xgboost as xgb from sklearn import metrics from sklearn.model_selection import GridSearchCV, train_test_split from xgboost.sklearn import XGBClassifier import gc def multiple_run(model, dtrain, predictors, cv_folds=4, early_stopping_rounds=1...
PSSDP/src/xgb.py
import matplotlib.pylab as plt import numpy as np import pandas as pd import xgboost as xgb from sklearn import metrics from sklearn.model_selection import GridSearchCV, train_test_split from xgboost.sklearn import XGBClassifier import gc def multiple_run(model, dtrain, predictors, cv_folds=4, early_stopping_rounds=1...
0.734024
0.502686
import discord from datetime import datetime import os import reminder client = discord.Client() target_timing = [ 'day', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'weekday', 'weekend' ] @client.event async def on_ready(): print('Logged in as') print(client.user.n...
main.py
import discord from datetime import datetime import os import reminder client = discord.Client() target_timing = [ 'day', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'weekday', 'weekend' ] @client.event async def on_ready(): print('Logged in as') print(client.user.n...
0.252845
0.075312
from helper import log, status, settings, sequence from abc import abstractmethod, ABCMeta from ctypes import * import os EXTENSION_NAME = "some extension" class Shim(metaclass=ABCMeta): def __init__(self): lib = cdll.LoadLibrary(os.path.dirname(__file__) + "/main.so") self.status = status.Status(...
shim/shim.py
from helper import log, status, settings, sequence from abc import abstractmethod, ABCMeta from ctypes import * import os EXTENSION_NAME = "some extension" class Shim(metaclass=ABCMeta): def __init__(self): lib = cdll.LoadLibrary(os.path.dirname(__file__) + "/main.so") self.status = status.Status(...
0.459804
0.04123
import numpy as np import neutrons class TopologyError(Exception): pass class Uranium: """Generates Uranium Object, can be 1D or 3D based on 'cubey'. arg: l: float: length of 1D strip, side lengths of U-235 object in 'm', radius of sphere. kwarg: shape="line": string: defined which of the ...
uranium_sim.py
import numpy as np import neutrons class TopologyError(Exception): pass class Uranium: """Generates Uranium Object, can be 1D or 3D based on 'cubey'. arg: l: float: length of 1D strip, side lengths of U-235 object in 'm', radius of sphere. kwarg: shape="line": string: defined which of the ...
0.779196
0.708016
import os import struct import numpy as np import pickle def load_mnist(root): """Load MNIST data from `root`""" labels_path = os.path.join(root, "train-labels-idx1-ubyte") images_path = os.path.join(root, "train-images-idx3-ubyte") test_label_path = os.path.join(root, "t10k-labels-idx1-ubyte") ...
data_loader.py
import os import struct import numpy as np import pickle def load_mnist(root): """Load MNIST data from `root`""" labels_path = os.path.join(root, "train-labels-idx1-ubyte") images_path = os.path.join(root, "train-images-idx3-ubyte") test_label_path = os.path.join(root, "t10k-labels-idx1-ubyte") ...
0.357007
0.406921
def main(): import sys from scripts.plot_utils import measure_list import scripts.plot_utils as pu import argparse parser = argparse.ArgumentParser() parser.add_argument('--data-file', type=str, default='summary.csv', help='Input data file name') parser.add_argument('--tgs', default=False, action='store_...
scripts/plot.py
def main(): import sys from scripts.plot_utils import measure_list import scripts.plot_utils as pu import argparse parser = argparse.ArgumentParser() parser.add_argument('--data-file', type=str, default='summary.csv', help='Input data file name') parser.add_argument('--tgs', default=False, action='store_...
0.351645
0.251028
from DB.db import MySQLDB, MySQLTESTDB, DB import json """ The Bot Data Access Object is responsible for accessing the data stored in the DB Mysql """ class BotDAO(): def __init__(self, test_db=None): self.db = DB() if not test_db else DB(test_db) def insert_discord_user(self, user_id): sql = f"INSERT IGNORE...
DAO/BotDAO.py
from DB.db import MySQLDB, MySQLTESTDB, DB import json """ The Bot Data Access Object is responsible for accessing the data stored in the DB Mysql """ class BotDAO(): def __init__(self, test_db=None): self.db = DB() if not test_db else DB(test_db) def insert_discord_user(self, user_id): sql = f"INSERT IGNORE...
0.29747
0.106691
import dicom import cv2 import numpy as np import os from multiprocessing.pool import ThreadPool class Reader: ''' 读取各文件夹下的图像文件进行操作 ''' dcm_paths = [] png_paths = [] def __init__(self): ''' Constructor ''' def scan_pic(self, path='../data/source/train'): ...
seg/src/code/reader.py
import dicom import cv2 import numpy as np import os from multiprocessing.pool import ThreadPool class Reader: ''' 读取各文件夹下的图像文件进行操作 ''' dcm_paths = [] png_paths = [] def __init__(self): ''' Constructor ''' def scan_pic(self, path='../data/source/train'): ...
0.174656
0.105625
import telebot import cherrypy import config import sqlite3 import datetime import tempfile import os from jinja2 import Template import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') import matplotlib.pyplot as plt bot = telebot.TeleBot(config.token) class Webh...
bot_webhook.py
import telebot import cherrypy import config import sqlite3 import datetime import tempfile import os from jinja2 import Template import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') import matplotlib.pyplot as plt bot = telebot.TeleBot(config.token) class Webh...
0.083094
0.074164
from typing import Optional import dgl import torch import torch.nn from dgl import DGLGraph from dgl.nn import GraphConv from torch import Tensor class GraphConvWithDropout(GraphConv): """ A GraphConv followed by a Dropout. """ def __init__(self, in_feats, out_feats, dropout=0.3, norm='both', weight...
examples/pytorch/gxn/layers.py
from typing import Optional import dgl import torch import torch.nn from dgl import DGLGraph from dgl.nn import GraphConv from torch import Tensor class GraphConvWithDropout(GraphConv): """ A GraphConv followed by a Dropout. """ def __init__(self, in_feats, out_feats, dropout=0.3, norm='both', weight...
0.957477
0.624294
from abc import ABCMeta, abstractmethod from aliquotmaf.converters.builder import get_builder from aliquotmaf.logger import Logger class BaseMafRecordMerger(metaclass=ABCMeta): def __init__(self, scheme): """ Initialize the MAF record merging object which has the main `merge_records` func...
aliquotmaf/merging/record_merger/base.py
from abc import ABCMeta, abstractmethod from aliquotmaf.converters.builder import get_builder from aliquotmaf.logger import Logger class BaseMafRecordMerger(metaclass=ABCMeta): def __init__(self, scheme): """ Initialize the MAF record merging object which has the main `merge_records` func...
0.884064
0.464659
import time import requests import json from tqdm import tqdm import pandas as pd import re from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expe...
Visualize/website/crawler.py
import time import requests import json from tqdm import tqdm import pandas as pd import re from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expe...
0.149873
0.050424
from __future__ import absolute_import from __future__ import unicode_literals __all__ = ["distribute"] import logging import functools from buckshot import contexts LOG = logging.getLogger(__name__) def distribute(*func, **opts): """Decorator which distributes the wrapped function across multiple proces...
buckshot/decorators.py
from __future__ import absolute_import from __future__ import unicode_literals __all__ = ["distribute"] import logging import functools from buckshot import contexts LOG = logging.getLogger(__name__) def distribute(*func, **opts): """Decorator which distributes the wrapped function across multiple proces...
0.839273
0.408867
import json import logging import re from contextlib import closing, suppress, contextmanager from pathlib import Path from traceback import format_exception from typing import List, Dict, Any from model_analyzer.model_complexity import ModelComputationalComplexity from model_analyzer.model_metadata import ModelMetaDa...
wb/main/jobs/models/analyze_model_job.py
import json import logging import re from contextlib import closing, suppress, contextmanager from pathlib import Path from traceback import format_exception from typing import List, Dict, Any from model_analyzer.model_complexity import ModelComputationalComplexity from model_analyzer.model_metadata import ModelMetaDa...
0.773772
0.102934
import datetime from unittest.mock import MagicMock import pytest from ts_sdk.task.__util_datalake import Datalake, InvalidPathException from ts_sdk.task.__util_metadata import FIELDS def test_datalake_update_metadata_tags(): d = Datalake('http://localhost:4569/') d.s3.head_object = MagicMock(return_value={...
__tests__/unit/test_datalake.py
import datetime from unittest.mock import MagicMock import pytest from ts_sdk.task.__util_datalake import Datalake, InvalidPathException from ts_sdk.task.__util_metadata import FIELDS def test_datalake_update_metadata_tags(): d = Datalake('http://localhost:4569/') d.s3.head_object = MagicMock(return_value={...
0.422743
0.185781
from flask import Blueprint, redirect, render_template, request, session, \ url_for from dietr.models import model from dietr.utils import login_required blueprint = Blueprint('roommate', __name__) @blueprint.route('/roommate/add', methods=['GET', 'POST']) @login_required def add(): """The add...
dietr/views/roommate.py
from flask import Blueprint, redirect, render_template, request, session, \ url_for from dietr.models import model from dietr.utils import login_required blueprint = Blueprint('roommate', __name__) @blueprint.route('/roommate/add', methods=['GET', 'POST']) @login_required def add(): """The add...
0.674158
0.121895
import importlib import logging import facepy from facepy.exceptions import FacebookError from django.conf import settings from django.utils import timezone def get_class(class_name): module_name, class_name = class_name.rsplit(".", 1) module = importlib.import_module(module_name) return getattr(module...
facebook_auth/graph_api.py
import importlib import logging import facepy from facepy.exceptions import FacebookError from django.conf import settings from django.utils import timezone def get_class(class_name): module_name, class_name = class_name.rsplit(".", 1) module = importlib.import_module(module_name) return getattr(module...
0.552298
0.074097
import numpy as np import scipy.special import torch import torch.nn as nn import torch.nn.functional as F from scipy import optimize from scipy.special import factorial, gamma, hermitenorm from ssqueezepy import Wavelet from timm.models.layers.conv2d_same import conv2d_same # https://github.com/tomrunia/PyTorchWavel...
datasaurus/src/cwt.py
import numpy as np import scipy.special import torch import torch.nn as nn import torch.nn.functional as F from scipy import optimize from scipy.special import factorial, gamma, hermitenorm from ssqueezepy import Wavelet from timm.models.layers.conv2d_same import conv2d_same # https://github.com/tomrunia/PyTorchWavel...
0.926711
0.616359
import datetime from api.lib.database import Model from api.extensions import db # template class RelationType(Model): __tablename__ = "c_relation_types" name = db.Column(db.String(16), index=True) class CITypeGroup(Model): __tablename__ = "c_ci_type_groups" name = db.Column(db.String(32)) c...
api/models/cmdb.py
import datetime from api.lib.database import Model from api.extensions import db # template class RelationType(Model): __tablename__ = "c_relation_types" name = db.Column(db.String(16), index=True) class CITypeGroup(Model): __tablename__ = "c_ci_type_groups" name = db.Column(db.String(32)) c...
0.441673
0.066176
from class_imbalance import * DROP_COLUMNS = [ 'id', 'date_account_created', 'timestamp_first_active', 'date_first_booking', 'gender', 'age', 'signup_method', 'signup_flow', 'language', 'affiliate_channel', 'affiliate_provider', 'first_affiliate_tracked', 'signup_a...
settings.py
from class_imbalance import * DROP_COLUMNS = [ 'id', 'date_account_created', 'timestamp_first_active', 'date_first_booking', 'gender', 'age', 'signup_method', 'signup_flow', 'language', 'affiliate_channel', 'affiliate_provider', 'first_affiliate_tracked', 'signup_a...
0.354768
0.172433
from __future__ import absolute_import, division, print_function import math import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' import datetime import time import numpy as np import scipy.misc import tensorflow as tf from tensorflow.contrib import layers from tensorflow.contrib import losses from tensorflow.contrib...
workloads/tensorflow/image_generation/main.py
from __future__ import absolute_import, division, print_function import math import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' import datetime import time import numpy as np import scipy.misc import tensorflow as tf from tensorflow.contrib import layers from tensorflow.contrib import losses from tensorflow.contrib...
0.642769
0.127653
from tweetloader import TweetLoader import matplotlib.pyplot as plt import matplotlib.dates as dates import pandas as pd import matplotlib.patches as mpatches def count_and_plot(raw, ax, start='2016-1-1', end='2016-6-24', freq='D', color='blue'): df = raw.copy() df.index = pd.DatetimeIndex(df['created_at']) ...
scripts/twitter_sampling.py
from tweetloader import TweetLoader import matplotlib.pyplot as plt import matplotlib.dates as dates import pandas as pd import matplotlib.patches as mpatches def count_and_plot(raw, ax, start='2016-1-1', end='2016-6-24', freq='D', color='blue'): df = raw.copy() df.index = pd.DatetimeIndex(df['created_at']) ...
0.658088
0.318936
from src import tool if __name__=='__main__': tool.check() import json from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions from config import url from config import path from config import conf...
discovery.py
from src import tool if __name__=='__main__': tool.check() import json from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions from config import url from config import path from config import conf...
0.124798
0.058966
import amulet import requests import urllib2 import time from charmhelpers.contrib.openstack.amulet.deployment import ( OpenStackAmuletDeployment ) from charmhelpers.contrib.openstack.amulet.utils import ( OpenStackAmuletUtils, DEBUG, # ERROR ) from charmhelpers.core.decorators import ( retry_on...
tests/basic_deployment.py
import amulet import requests import urllib2 import time from charmhelpers.contrib.openstack.amulet.deployment import ( OpenStackAmuletDeployment ) from charmhelpers.contrib.openstack.amulet.utils import ( OpenStackAmuletUtils, DEBUG, # ERROR ) from charmhelpers.core.decorators import ( retry_on...
0.627723
0.237002
""" """ from Queue import Empty from config import msgs from hashwrappy.wrapper import Backbone __author__ = 'donal' __project__ = 'hashwrappy' # ======================= # MAIN CLASS: Hashcat CPU # ======================= class HCWrapper(Backbone): def __init__(self, *args, **kwargs): super(HCWrapper, s...
hashwrappy/wrapper_hc.py
""" """ from Queue import Empty from config import msgs from hashwrappy.wrapper import Backbone __author__ = 'donal' __project__ = 'hashwrappy' # ======================= # MAIN CLASS: Hashcat CPU # ======================= class HCWrapper(Backbone): def __init__(self, *args, **kwargs): super(HCWrapper, s...
0.691602
0.285752
author_xpaths = [ '//*[(self::a or self::address or self::link or self::p or self::span)][@rel="author" or @class="author" or rel="me"]|//author', '//*[(self::a or self::span)][contains(@class, "authors") or contains(@class, "author") or contains(@class, "posted-by") or contains(@itemprop, "author")]', '/...
trafilatura/metaxpaths.py
author_xpaths = [ '//*[(self::a or self::address or self::link or self::p or self::span)][@rel="author" or @class="author" or rel="me"]|//author', '//*[(self::a or self::span)][contains(@class, "authors") or contains(@class, "author") or contains(@class, "posted-by") or contains(@itemprop, "author")]', '/...
0.387227
0.077553
import re import pytest from context import esperanto_analyzer from esperanto_analyzer.speech import Word from esperanto_analyzer.speech import Adverb from esperanto_analyzer.speech import Adjective from esperanto_analyzer.speech import Article, InvalidArticleError from esperanto_analyzer.speech import Conjunction f...
tests/test_morphological_sentence_analyzer.py
import re import pytest from context import esperanto_analyzer from esperanto_analyzer.speech import Word from esperanto_analyzer.speech import Adverb from esperanto_analyzer.speech import Adjective from esperanto_analyzer.speech import Article, InvalidArticleError from esperanto_analyzer.speech import Conjunction f...
0.533397
0.575349
""" Collection related functions """ import bpy import xrs.filename import xrs.log import xrs.mode import xrs.object import xrs.select def collection_has_objects(name): """ True if the given Collection exists and contains objects """ if name not in bpy.data.collections: return False if len(bpy.data.collectio...
blender-add-on/xrs/collection.py
""" Collection related functions """ import bpy import xrs.filename import xrs.log import xrs.mode import xrs.object import xrs.select def collection_has_objects(name): """ True if the given Collection exists and contains objects """ if name not in bpy.data.collections: return False if len(bpy.data.collectio...
0.508788
0.504516
import sys from micropython import const from stylization import style_func_stream CRITICAL = const(50) ERROR = const(40) WARNING = const(30) INFO = const(20) DEBUG = const(10) NOTSET = const(0) _level_dict = { CRITICAL: "CRIT", ERROR: "ERROR", WARNING: "WARN", INFO: "INFO", DEBUG: "DEBUG", } _st...
logging/logging.py
import sys from micropython import const from stylization import style_func_stream CRITICAL = const(50) ERROR = const(40) WARNING = const(30) INFO = const(20) DEBUG = const(10) NOTSET = const(0) _level_dict = { CRITICAL: "CRIT", ERROR: "ERROR", WARNING: "WARN", INFO: "INFO", DEBUG: "DEBUG", } _st...
0.576661
0.166032
import torch from .detector3d_template import Detector3DTemplate from ...ops.iou3d_nms import iou3d_nms_utils from ...ops.roiaware_pool3d import roiaware_pool3d_utils class Point3DSSD(Detector3DTemplate): def __init__(self, model_cfg, num_class, dataset): super().__init__(model_cfg=model_cfg, num_class=n...
build/lib.linux-x86_64-3.8/pcdet/models/detectors/point_3dssd.py
import torch from .detector3d_template import Detector3DTemplate from ...ops.iou3d_nms import iou3d_nms_utils from ...ops.roiaware_pool3d import roiaware_pool3d_utils class Point3DSSD(Detector3DTemplate): def __init__(self, model_cfg, num_class, dataset): super().__init__(model_cfg=model_cfg, num_class=n...
0.691393
0.239727
from digsandpaper.sandpaper_utils import load_json_file import requests from etk.extractors.glossary_extractor import GlossaryExtractor from etk.crf_tokenizer import CrfTokenizer import uuid __name__ = "ConstraintReMapping" name = __name__ class ConstraintReMapSimilarity(object): name = "ConstraintReMapSimilarit...
digsandpaper/coarse/preprocess/constraint_remap_factory.py
from digsandpaper.sandpaper_utils import load_json_file import requests from etk.extractors.glossary_extractor import GlossaryExtractor from etk.crf_tokenizer import CrfTokenizer import uuid __name__ = "ConstraintReMapping" name = __name__ class ConstraintReMapSimilarity(object): name = "ConstraintReMapSimilarit...
0.568536
0.108001
class LinkedList: def __init__(self, value=None): self.value = value self.next = None self._len = 1 if value is not None else 0 def __getitem__(self, item): if 0 <= item < self._len: t = self for _ in range(item): t = t.next re...
types/LinkedList.py
class LinkedList: def __init__(self, value=None): self.value = value self.next = None self._len = 1 if value is not None else 0 def __getitem__(self, item): if 0 <= item < self._len: t = self for _ in range(item): t = t.next re...
0.68342
0.223589
""" Indexer functions for ELMo-style character embeddings. """ from typing import Dict, List, Callable, Any import torch PADDING_VALUE = 0 def _make_bos_eos( character: int, padding_character: int, beginning_of_word_character: int, end_of_word_character: int, max_word_length:...
utils/character_cnn.py
""" Indexer functions for ELMo-style character embeddings. """ from typing import Dict, List, Callable, Any import torch PADDING_VALUE = 0 def _make_bos_eos( character: int, padding_character: int, beginning_of_word_character: int, end_of_word_character: int, max_word_length:...
0.860134
0.382574
import copy import numpy as np import pints from scipy.integrate import solve_ivp class ForwardModel(pints.ForwardModel): """ Abstract base class for forward models. Extends :class:`pints.ForwardModel`. """ def __init__(self): super(ForwardModel, self).__init__() def n_outputs(self...
seirmo/_models.py
import copy import numpy as np import pints from scipy.integrate import solve_ivp class ForwardModel(pints.ForwardModel): """ Abstract base class for forward models. Extends :class:`pints.ForwardModel`. """ def __init__(self): super(ForwardModel, self).__init__() def n_outputs(self...
0.899213
0.623535
import os import numpy as np from scipy import ndimage from scipy import fftpack as fp from matplotlib import pyplot, cm from PIL import Image from flask import Blueprint, render_template, url_for, send_file from flask import redirect, request, g, current_app from .util import get_image_path, get_no_image_path, cl...
app/main/views.py
import os import numpy as np from scipy import ndimage from scipy import fftpack as fp from matplotlib import pyplot, cm from PIL import Image from flask import Blueprint, render_template, url_for, send_file from flask import redirect, request, g, current_app from .util import get_image_path, get_no_image_path, cl...
0.431345
0.162912
from hfc.fabric import Client from time import sleep import pymongo from bson.py3compat import (_unicode) database_host = "mongo:27017" # cli = Client(net_profile="test/fixtures/network.json") cli = Client(net_profile="test/fixtures/network-k8s.json") org1_admin = cli.get_user(org_name='org1.example.com', name='Admin'...
polling.py
from hfc.fabric import Client from time import sleep import pymongo from bson.py3compat import (_unicode) database_host = "mongo:27017" # cli = Client(net_profile="test/fixtures/network.json") cli = Client(net_profile="test/fixtures/network-k8s.json") org1_admin = cli.get_user(org_name='org1.example.com', name='Admin'...
0.262936
0.107531
import flask import loguru class Logger: def __init__(self): self.logger = self._init_logger() @staticmethod def _init_logger(): loguru.logger.add( "../logs/debug.log", format="{time} {level} {message}", filter=lambda record: record["level"].name == "DE...
src/_logger.py
import flask import loguru class Logger: def __init__(self): self.logger = self._init_logger() @staticmethod def _init_logger(): loguru.logger.add( "../logs/debug.log", format="{time} {level} {message}", filter=lambda record: record["level"].name == "DE...
0.568176
0.12031
import sys sys.path.append("..") import pytest import numpy as np import iSBatch as rqs def write_cost_to_file(fct_name, param, *args): fname = ":".join(fct_name.split("_")[1:]) with open("metrics.perf", 'a') as fp: fp.write("cost %s %s %s\n" % ( fname, str(param), ' '.join([st...
benchmarks/benchmark.py
import sys sys.path.append("..") import pytest import numpy as np import iSBatch as rqs def write_cost_to_file(fct_name, param, *args): fname = ":".join(fct_name.split("_")[1:]) with open("metrics.perf", 'a') as fp: fp.write("cost %s %s %s\n" % ( fname, str(param), ' '.join([st...
0.263789
0.417034
import csv import pandas as pd import numpy as np # Decorator for printing function results. We return a results value to enable # automated testing of the methods upon refactoring. def output_decorator(func): def inner(*args, **kwargs): print(f'{func.__name__} is now started') t = func(*args, **k...
samples/Test_Procedures.py
import csv import pandas as pd import numpy as np # Decorator for printing function results. We return a results value to enable # automated testing of the methods upon refactoring. def output_decorator(func): def inner(*args, **kwargs): print(f'{func.__name__} is now started') t = func(*args, **k...
0.358465
0.313394
from tests import TestBase import json, os, uuid """ Authentication flow and Account registration test Testing flow: 3 testing classes: login: - failed testcase 1: user doe not exist - failed testcase 2: user doe not exist and missing required columns - failed testcase 3: user exists but missing require...
backend/tests/test_auth_user.py
from tests import TestBase import json, os, uuid """ Authentication flow and Account registration test Testing flow: 3 testing classes: login: - failed testcase 1: user doe not exist - failed testcase 2: user doe not exist and missing required columns - failed testcase 3: user exists but missing require...
0.275032
0.461259
import os ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) USER_EMOJI = [':smiley_cat:', ':smiling_imp:', ':panda_face:', ':dog:'] FONT_DIR = os.path.join(ROOT_DIR, "font", "Fira_Code", "static") IMAGE_DIR = os.path.join(ROOT_DIR, "images") FONT_PATH = os.path.join(FONT_DIR, "FiraCode-Medium.ttf") COLOR = ['alice...
settings.py
import os ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) USER_EMOJI = [':smiley_cat:', ':smiling_imp:', ':panda_face:', ':dog:'] FONT_DIR = os.path.join(ROOT_DIR, "font", "Fira_Code", "static") IMAGE_DIR = os.path.join(ROOT_DIR, "images") FONT_PATH = os.path.join(FONT_DIR, "FiraCode-Medium.ttf") COLOR = ['alice...
0.328637
0.118589
from threading import Thread,currentThread, Lock, RLock, Semaphore import requests import os semaphore = Semaphore(0) hasilperhitungan=0 class zanwarRewrite (Thread): def __init__(self,name,thread_number,filename): Thread.__init__(self) self.threadLock = Lock() self.name = name self...
Chapter02/ZanwarDua1184050.py
from threading import Thread,currentThread, Lock, RLock, Semaphore import requests import os semaphore = Semaphore(0) hasilperhitungan=0 class zanwarRewrite (Thread): def __init__(self,name,thread_number,filename): Thread.__init__(self) self.threadLock = Lock() self.name = name self...
0.213869
0.06832
from .PyPolyBoRi import (Monomial, random_set, Polynomial, set_random_seed, ll_red_nf_redsb, Variable) from .ll import ll_encode from random import Random from pprint import pformat from .blocks import declare_ring def gen_random_poly(ring, l, deg, vars_set, seed=123): """ Generate a ...
src/sage/rings/polynomial/pbori/randompoly.py
from .PyPolyBoRi import (Monomial, random_set, Polynomial, set_random_seed, ll_red_nf_redsb, Variable) from .ll import ll_encode from random import Random from pprint import pformat from .blocks import declare_ring def gen_random_poly(ring, l, deg, vars_set, seed=123): """ Generate a ...
0.667473
0.574216
from math import sin, cos, asin, atan, atan2, sqrt, pi, degrees import array try: import utime as time except ImportError: import time class D3D: def __init__(self, timediff=None): pass def getAngleXYZ(self, acceleration, magnetic): AccX, AccY, AccZ = acceleration magX, magY, magZ = magnetic...
assets/py/tools/d3d.py
from math import sin, cos, asin, atan, atan2, sqrt, pi, degrees import array try: import utime as time except ImportError: import time class D3D: def __init__(self, timediff=None): pass def getAngleXYZ(self, acceleration, magnetic): AccX, AccY, AccZ = acceleration magX, magY, magZ = magnetic...
0.757256
0.600716
from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from jobs import utils as jobs_utils from . import serializers class CreateChannelView(APIView): """ Handles channel creation in Django models. """ def post(self, request, *args, **...
services/app/src/channels_app/views.py
from rest_framework import status from rest_framework.response import Response from rest_framework.views import APIView from jobs import utils as jobs_utils from . import serializers class CreateChannelView(APIView): """ Handles channel creation in Django models. """ def post(self, request, *args, **...
0.85269
0.108001
from pyomo.environ import * model = m = ConcreteModel() m.b1 = Var(within=Binary,bounds=(0,1),initialize=0) m.b2 = Var(within=Binary,bounds=(0,1),initialize=0) m.b3 = Var(within=Binary,bounds=(0,1),initialize=0) m.b4 = Var(within=Binary,bounds=(0,1),initialize=0) m.b5 = Var(within=Binary,bounds=(0,1),initialize=0)...
tests/examples/minlplib/graphpart_3pm-0244-0244.py
from pyomo.environ import * model = m = ConcreteModel() m.b1 = Var(within=Binary,bounds=(0,1),initialize=0) m.b2 = Var(within=Binary,bounds=(0,1),initialize=0) m.b3 = Var(within=Binary,bounds=(0,1),initialize=0) m.b4 = Var(within=Binary,bounds=(0,1),initialize=0) m.b5 = Var(within=Binary,bounds=(0,1),initialize=0)...
0.620162
0.25801
from typing import Iterable, Tuple from bitarray import bitarray from . import TimestampsEncoder from . import ValuesEncoder from .result import PairsGorillaContent class PairsEncoder: """Gorilla Pairs (Timestamp-Value) Encoder. Parameters ---------- float_format : {{'f64', 'f32', 'f16'}}, default '...
src/gorillacompression/encode.py
from typing import Iterable, Tuple from bitarray import bitarray from . import TimestampsEncoder from . import ValuesEncoder from .result import PairsGorillaContent class PairsEncoder: """Gorilla Pairs (Timestamp-Value) Encoder. Parameters ---------- float_format : {{'f64', 'f32', 'f16'}}, default '...
0.954212
0.583203
"""Tests for pytestrunner.py""" # Standard library imports import os import os.path as osp # Third party imports import pytest from qtpy.QtCore import QByteArray # Local imports from spyder_unittest.backend.pytestrunner import (PyTestRunner, logreport_to_testresult) ...
spyder_unittest/backend/tests/test_pytestrunner.py
"""Tests for pytestrunner.py""" # Standard library imports import os import os.path as osp # Third party imports import pytest from qtpy.QtCore import QByteArray # Local imports from spyder_unittest.backend.pytestrunner import (PyTestRunner, logreport_to_testresult) ...
0.602062
0.50415
import abc from neutron.api import extensions from neutron.api.v2 import attributes as attr from neutron.api.v2 import base from neutron.common import exceptions from neutron import manager # Attribute Map RESOURCE_NAME = 'availability_zone' AVAILABILITY_ZONES = 'availability_zones' # name: name of availability zon...
neutron/extensions/availability_zone.py
import abc from neutron.api import extensions from neutron.api.v2 import attributes as attr from neutron.api.v2 import base from neutron.common import exceptions from neutron import manager # Attribute Map RESOURCE_NAME = 'availability_zone' AVAILABILITY_ZONES = 'availability_zones' # name: name of availability zon...
0.802168
0.07393
import time import logging try: from fortrace.core.vmm import Vmm from fortrace.utility.logger_helper import create_logger from fortrace.core.vmm import GuestListener from fortrace.core.reporter import Reporter import fortrace.utility.scenarioHelper as scenH except ImportError as ie: print("Imp...
examples/ModuleTests/008_mailClientThunderbird.py
import time import logging try: from fortrace.core.vmm import Vmm from fortrace.utility.logger_helper import create_logger from fortrace.core.vmm import GuestListener from fortrace.core.reporter import Reporter import fortrace.utility.scenarioHelper as scenH except ImportError as ie: print("Imp...
0.178204
0.067301
from dataclasses import dataclass from typing import List, Dict from discord.ext import commands from bs4 import BeautifulSoup import bs4 import discord from bot.bot_client import Bot from bot.utils.context import Context @dataclass class PlayerData: rank: int name: str exp_gained: int @dataclass clas...
bot/cogs/runeclan.py
from dataclasses import dataclass from typing import List, Dict from discord.ext import commands from bs4 import BeautifulSoup import bs4 import discord from bot.bot_client import Bot from bot.utils.context import Context @dataclass class PlayerData: rank: int name: str exp_gained: int @dataclass clas...
0.705886
0.169784
import os import sys import logging import argparse from importlib import import_module import multiprocessing import numpy import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as pyplot import matplotlib_extras.colors import h5py # avoid gdal loading incompatible HDF5 library from eewperformance import ...
analyzer.py
import os import sys import logging import argparse from importlib import import_module import multiprocessing import numpy import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as pyplot import matplotlib_extras.colors import h5py # avoid gdal loading incompatible HDF5 library from eewperformance import ...
0.535098
0.146667
from tasks.hierarchy import (DenormalizedHierarchy, Hierarchy, HierarchyChildParentsUnion, HierarchyInfoUnion, HierarchyChildParent, GetParentsFunction, LevelHierarchy, LevelInfo) from tasks.ca.statcan.geo import (GEO_PR, GEO_CD, GEO_FSA, GEO_CMA, GEO_CSD, GEO_DA, GEO_CT, GEO_DB, ...
tasks/ca/hierarchy.py
from tasks.hierarchy import (DenormalizedHierarchy, Hierarchy, HierarchyChildParentsUnion, HierarchyInfoUnion, HierarchyChildParent, GetParentsFunction, LevelHierarchy, LevelInfo) from tasks.ca.statcan.geo import (GEO_PR, GEO_CD, GEO_FSA, GEO_CMA, GEO_CSD, GEO_DA, GEO_CT, GEO_DB, ...
0.780244
0.440469