code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from itertools import product from LAMARCK_ML.data_util import IOLabel from LAMARCK_ML.reproduction.methods import Mutation, Recombination, RandomStep from LAMARCK_ML.architectures.losses import Reduce, LossInterface from LAMARCK_ML.architectures.losses import SoftmaxCrossEntropyWithLogits, MeanSquaredError from LAMAR...
LAMARCK_ML/individuals/implementations/weightAgnosticIndividual.py
from itertools import product from LAMARCK_ML.data_util import IOLabel from LAMARCK_ML.reproduction.methods import Mutation, Recombination, RandomStep from LAMARCK_ML.architectures.losses import Reduce, LossInterface from LAMARCK_ML.architectures.losses import SoftmaxCrossEntropyWithLogits, MeanSquaredError from LAMAR...
0.735926
0.377541
import pytest from grunt.db import get_db def test_character_index(client, auth): response = client.get('/') assert b"Log In" in response.data assert b"Register" in response.data auth.login() response = client.get('/') assert b'Log Out' in response.data assert b'test title' in response.da...
tests/test_character.py
import pytest from grunt.db import get_db def test_character_index(client, auth): response = client.get('/') assert b"Log In" in response.data assert b"Register" in response.data auth.login() response = client.get('/') assert b'Log Out' in response.data assert b'test title' in response.da...
0.450601
0.306281
from django.test import TestCase from dcim.models import Platform from netbox_onboarding.onboard import NetdevKeeper, OnboardException class NetdevKeeperTestCase(TestCase): """Test the NetdevKeeper Class.""" def setUp(self): """Create a superuser and token for API calls.""" self.platform1 = ...
netbox_onboarding/tests/test_netdev_keeper.py
from django.test import TestCase from dcim.models import Platform from netbox_onboarding.onboard import NetdevKeeper, OnboardException class NetdevKeeperTestCase(TestCase): """Test the NetdevKeeper Class.""" def setUp(self): """Create a superuser and token for API calls.""" self.platform1 = ...
0.704973
0.293835
"""Tests for xls.tools.delay_info_main.""" import subprocess from xls.common import runfiles from xls.common import test_base DELAY_INFO_MAIN_PATH = runfiles.get_path('xls/tools/delay_info_main') NOT_ADD_IR = """package not_add fn not_add(x: bits[32], y: bits[32]) -> bits[32] { sum: bits[32] = add(x, y) ret no...
xls/tools/delay_info_main_test.py
"""Tests for xls.tools.delay_info_main.""" import subprocess from xls.common import runfiles from xls.common import test_base DELAY_INFO_MAIN_PATH = runfiles.get_path('xls/tools/delay_info_main') NOT_ADD_IR = """package not_add fn not_add(x: bits[32], y: bits[32]) -> bits[32] { sum: bits[32] = add(x, y) ret no...
0.620162
0.282976
from optparse import OptionParser import simplejson import structlog from kafka import KafkaConsumer import pickle import struct import socket import sys import time from kafka.consumer.fetcher import ConsumerRecord from kafka.errors import KafkaError from common.utils.consulhelpers import get_endpoint_from_consul ...
shovel/main.py
from optparse import OptionParser import simplejson import structlog from kafka import KafkaConsumer import pickle import struct import socket import sys import time from kafka.consumer.fetcher import ConsumerRecord from kafka.errors import KafkaError from common.utils.consulhelpers import get_endpoint_from_consul ...
0.444565
0.087994
from __future__ import print_function import os import sys from command import Command from git_config import IsImmutable from git_command import git import gitc_utils from progress import Progress from project import SyncBuffer class Start(Command): common = True helpSummary = "Start a new branch for developmen...
subcmds/start.py
from __future__ import print_function import os import sys from command import Command from git_config import IsImmutable from git_command import git import gitc_utils from progress import Progress from project import SyncBuffer class Start(Command): common = True helpSummary = "Start a new branch for developmen...
0.325735
0.076408
from tasks.tags import SubsectionTags, SectionTags, UnitTags from tasks.meta import (GEOM_REF, current_session, GEOM_NAME, OBSColumn) from tasks.util import ColumnsTask, TableTask, Carto2TempTableTask, MetaWrapper from collections import OrderedDict class ImportThai(Carto2TempTableTask): subdomain = 'solutions' ...
tasks/th/thaipop.py
from tasks.tags import SubsectionTags, SectionTags, UnitTags from tasks.meta import (GEOM_REF, current_session, GEOM_NAME, OBSColumn) from tasks.util import ColumnsTask, TableTask, Carto2TempTableTask, MetaWrapper from collections import OrderedDict class ImportThai(Carto2TempTableTask): subdomain = 'solutions' ...
0.659953
0.349477
import os,sys import datetime import time from schainpy.controller import Project path = '/home/alex/Downloads/NEW_WR2/spc16removeDC' figpath = path desc = "Simulator Test" controllerObj = Project() controllerObj.setup(id='10',name='Test Simulator',description=desc) readUnitConfObj = controllerObj.ad...
schainpy/scripts/test_sim0008.py
import os,sys import datetime import time from schainpy.controller import Project path = '/home/alex/Downloads/NEW_WR2/spc16removeDC' figpath = path desc = "Simulator Test" controllerObj = Project() controllerObj.setup(id='10',name='Test Simulator',description=desc) readUnitConfObj = controllerObj.ad...
0.28577
0.048699
from PIL import Image, ImageOps import numpy as np import skimage.io as io from src.models.class_patcher import patcher from src.utils.imgproc import * from skimage.color import rgb2hsv, hsv2rgb class patcher(patcher): def __init__(self, body='./body/body_kyoko.png', **options): super().__init__('京狐', bod...
src/models/kyoko.py
from PIL import Image, ImageOps import numpy as np import skimage.io as io from src.models.class_patcher import patcher from src.utils.imgproc import * from skimage.color import rgb2hsv, hsv2rgb class patcher(patcher): def __init__(self, body='./body/body_kyoko.png', **options): super().__init__('京狐', bod...
0.383295
0.234056
from __future__ import division import numpy as np from scipy.constants import mu_0, pi, epsilon_0 from scipy.special import erf from SimPEG import utils import warnings def hzAnalyticDipoleF(r, freq, sigma, secondary=True, mu=mu_0): """ The analytical expression is given in Equation 4.56 in Ward and Hohmann,...
SimPEG/electromagnetics/analytics/FDEM.py
from __future__ import division import numpy as np from scipy.constants import mu_0, pi, epsilon_0 from scipy.special import erf from SimPEG import utils import warnings def hzAnalyticDipoleF(r, freq, sigma, secondary=True, mu=mu_0): """ The analytical expression is given in Equation 4.56 in Ward and Hohmann,...
0.648021
0.535098
import numpy, cdtime, vcs from vcs.testing.common import test_values_setting x=vcs.init() x.drawlogooff() p=x.createprojection() assert(p.type == "linear") assert(vcs.queries.isprojection(p)) test_values_setting(p, "type", [-1,-2,-3,'linear', 'albers equal area', 'lambert', 'mercator', 'polar', 'polyconic', 'equid c...
testing/vcs/test_vcs_verify_proj_basics.py
import numpy, cdtime, vcs from vcs.testing.common import test_values_setting x=vcs.init() x.drawlogooff() p=x.createprojection() assert(p.type == "linear") assert(vcs.queries.isprojection(p)) test_values_setting(p, "type", [-1,-2,-3,'linear', 'albers equal area', 'lambert', 'mercator', 'polar', 'polyconic', 'equid c...
0.282493
0.557665
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from toontown.toonbase import ToontownGlobals from toontown.catalog import CatalogItem from toontown.catalog.CatalogItemList import CatalogItemList from toontown.catalog.CatalogPoleItem import Catal...
v2.5.7/toontown/coderedemption/TTCodeRedemptionMgrAI.py
from direct.directnotify import DirectNotifyGlobal from direct.distributed.DistributedObjectAI import DistributedObjectAI from toontown.toonbase import ToontownGlobals from toontown.catalog import CatalogItem from toontown.catalog.CatalogItemList import CatalogItemList from toontown.catalog.CatalogPoleItem import Catal...
0.427636
0.104295
from ghpythonlib.componentbase import dotnetcompiledcomponent as component import Grasshopper, GhPython import System from Grasshopper import DataTree from Grasshopper.Kernel.Data import GH_Path __author__ = "<NAME>" __laboratory__ = "IBOIS, Laboratory for Timber Construction" __university__ = "EPFL, Ecole ...
Gh compilation files/contact.py
from ghpythonlib.componentbase import dotnetcompiledcomponent as component import Grasshopper, GhPython import System from Grasshopper import DataTree from Grasshopper.Kernel.Data import GH_Path __author__ = "<NAME>" __laboratory__ = "IBOIS, Laboratory for Timber Construction" __university__ = "EPFL, Ecole ...
0.397938
0.10004
import json import os from decouple import config DEBUG = False TEMPLATE_DEBUG = False secrets_dir = "/tmp/secrets" db_creds_file = open(f"{secrets_dir}/db.json") env_file = open(f"{secrets_dir}/env.json") db_creds = json.load(db_creds_file)["data"] env = json.load(env_file)["data"]["data"] DATABASES = { "defa...
onlineweb4/settings/zappa.py
import json import os from decouple import config DEBUG = False TEMPLATE_DEBUG = False secrets_dir = "/tmp/secrets" db_creds_file = open(f"{secrets_dir}/db.json") env_file = open(f"{secrets_dir}/env.json") db_creds = json.load(db_creds_file)["data"] env = json.load(env_file)["data"]["data"] DATABASES = { "defa...
0.137475
0.099426
import io import random from tempest.api.compute import base from tempest.common import image as common_image from tempest.common import utils from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib import decorators from tempest.lib import exceptions as lib_exc CONF = config.CONF...
tempest/api/compute/flavors/test_flavors_negative.py
import io import random from tempest.api.compute import base from tempest.common import image as common_image from tempest.common import utils from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib import decorators from tempest.lib import exceptions as lib_exc CONF = config.CONF...
0.403449
0.284576
import random import string import subprocess import sys import tempfile from contextlib import contextmanager from pathlib import Path from textwrap import dedent from typing import List, Tuple from feast import cli from feast.feature_store import FeatureStore def get_example_repo(example_repo_py) -> str: paren...
sdk/python/tests/utils/cli_utils.py
import random import string import subprocess import sys import tempfile from contextlib import contextmanager from pathlib import Path from textwrap import dedent from typing import List, Tuple from feast import cli from feast.feature_store import FeatureStore def get_example_repo(example_repo_py) -> str: paren...
0.511961
0.226912
import scrapy from crawlerbot.items import TgItem import json import re from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import os from crawlerbot.district_names import dist...
crawlerbot/spiders/thrent.py
import scrapy from crawlerbot.items import TgItem import json import re from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import os from crawlerbot.district_names import dist...
0.124559
0.088269
import numpy as np from .core import SpectrumBasedEstimatorBase, ensure_covariance_size def f_bartlett(A, R): r"""Computes the spectrum output of the Bartlett beamformer. .. math:: P_{\mathrm{Bartlett}}(\theta) = \mathbf{a}(\theta)^H \mathbf{R} \mathbf{a}(\theta) Args: A: m x k st...
doatools/estimation/beamforming.py
import numpy as np from .core import SpectrumBasedEstimatorBase, ensure_covariance_size def f_bartlett(A, R): r"""Computes the spectrum output of the Bartlett beamformer. .. math:: P_{\mathrm{Bartlett}}(\theta) = \mathbf{a}(\theta)^H \mathbf{R} \mathbf{a}(\theta) Args: A: m x k st...
0.959639
0.824956
import csv import gzip import casanova import pytest import time import sys from io import StringIO from collections import defaultdict from quenouille import imap_unordered from test.utils import collect_csv from casanova.resuming import ( LastCellComparisonResumer, RowCountResumer, ThreadSafeResumer ) f...
test/enricher_test.py
import csv import gzip import casanova import pytest import time import sys from io import StringIO from collections import defaultdict from quenouille import imap_unordered from test.utils import collect_csv from casanova.resuming import ( LastCellComparisonResumer, RowCountResumer, ThreadSafeResumer ) f...
0.238728
0.25363
import mock from git_stacktrace.tests import base from git_stacktrace import api from git_stacktrace import git class TestApi(base.TestCase): @mock.patch('git_stacktrace.git.convert_since') def test_convert_since(self, mocked_command): expected = "HASH1..HASH2" mocked_command.return_value = ...
git_stacktrace/tests/test_api.py
import mock from git_stacktrace.tests import base from git_stacktrace import api from git_stacktrace import git class TestApi(base.TestCase): @mock.patch('git_stacktrace.git.convert_since') def test_convert_since(self, mocked_command): expected = "HASH1..HASH2" mocked_command.return_value = ...
0.596551
0.404449
import random import math import numpy as np import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from torch.nn.modules.distance import CosineSimilarity from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from model.attention import Attention from model.e...
model/mtl_models.py
import random import math import numpy as np import torch import torch.nn as nn import torch.nn.init as init import torch.nn.functional as F from torch.nn.modules.distance import CosineSimilarity from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from model.attention import Attention from model.e...
0.826887
0.380759
import re import os import json import inflect import nltk import numpy as np inflect_eng = inflect.engine() def get_data_set_info_path(data_folder): """ :param data_folder: name of data folder, e.g. 'dataset1' :return: absolute path to JSON file containing information about data set """ return o...
src/data/dataset.py
import re import os import json import inflect import nltk import numpy as np inflect_eng = inflect.engine() def get_data_set_info_path(data_folder): """ :param data_folder: name of data folder, e.g. 'dataset1' :return: absolute path to JSON file containing information about data set """ return o...
0.385722
0.309806
from __future__ import absolute_import from six.moves import range import os import numpy as np from replay_memory import ReplayMemory from sampler import Sampler, ObsSampler from learner import QLearner, q_cnn from explorer import LinearDecayEGreedyExplorer from trainer import Trainer from validator import Validato...
reinforcement_learning/dqn/train_atari.py
from __future__ import absolute_import from six.moves import range import os import numpy as np from replay_memory import ReplayMemory from sampler import Sampler, ObsSampler from learner import QLearner, q_cnn from explorer import LinearDecayEGreedyExplorer from trainer import Trainer from validator import Validato...
0.650911
0.126353
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os from copy import deepcopy from indra.preassembler.hierarchy_manager import hierarchies, HierarchyManager from indra.statements import get_valid_location, InvalidLocationError, Agent from indra.util import u...
indra/tests/test_hierarchy_manager.py
from __future__ import absolute_import, print_function, unicode_literals from builtins import dict, str import os from copy import deepcopy from indra.preassembler.hierarchy_manager import hierarchies, HierarchyManager from indra.statements import get_valid_location, InvalidLocationError, Agent from indra.util import u...
0.584153
0.478041
import string import numpy as np import re import pandas as pd from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from nltk import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer def preprocess(X): X = X.lower() ...
notebooks/preprocessing.py
import string import numpy as np import re import pandas as pd from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfVectorizer from nltk import word_tokenize from nltk.corpus import stopwords from nltk.stem import WordNetLemmatizer def preprocess(X): X = X.lower() ...
0.269999
0.385606
import logging from rest_framework import exceptions from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.models import AnonymousUser from django.contrib.auth import get_user_model from galaxy.api import serializers from galaxy.api.views import base_views from galaxy.main import models __...
galaxy/api/views/users.py
import logging from rest_framework import exceptions from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.models import AnonymousUser from django.contrib.auth import get_user_model from galaxy.api import serializers from galaxy.api.views import base_views from galaxy.main import models __...
0.481698
0.03605
import json from loaders.base import Loader """ Dump everything in the format: type 0 ascii str - "a:string" type 1 float num - 123 type 2 utf16 str - "u:string" ex: { "some_key": ["u:äöõö", 123, "a:hello", ...], "some_other_key": [956, "a:halo", ...], ... } """ class CSVLoader(Loader): def read(s...
loaders/csv.py
import json from loaders.base import Loader """ Dump everything in the format: type 0 ascii str - "a:string" type 1 float num - 123 type 2 utf16 str - "u:string" ex: { "some_key": ["u:äöõö", 123, "a:hello", ...], "some_other_key": [956, "a:halo", ...], ... } """ class CSVLoader(Loader): def read(s...
0.219505
0.300779
from fastapi.testclient import TestClient import json import pytest from openapi_server.models.user import User def test_create_user(client: TestClient): """Test case for create_user Create user """ user = {"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phon...
samples/server/petstore/python-fastapi/tests/test_user_api.py
from fastapi.testclient import TestClient import json import pytest from openapi_server.models.user import User def test_create_user(client: TestClient): """Test case for create_user Create user """ user = {"first_name":"firstName","last_name":"lastName","password":"password","user_status":6,"phon...
0.497803
0.376652
__author__ = '<NAME> <<EMAIL>>' __copyright__ = 'Copyright (c) 2012, SvartalF' __license__ = 'BSD 3-Clause License' import opuslib.api.decoder import opuslib.api.encoder import opuslib.api.ctl import opuslib.constants class Decoder(object): def __init__(self, fs, channels): """ Parameters: ...
opuslib/classes.py
__author__ = '<NAME> <<EMAIL>>' __copyright__ = 'Copyright (c) 2012, SvartalF' __license__ = 'BSD 3-Clause License' import opuslib.api.decoder import opuslib.api.encoder import opuslib.api.ctl import opuslib.constants class Decoder(object): def __init__(self, fs, channels): """ Parameters: ...
0.761538
0.24434
import os import re __docformat__ = "restructredtext en" # map eland_result.txt sense sense_map = {'F': '+', 'R': '-'} sense_color = {'F': '0,0,255', 'R': '255,255,0'} def create_bed_header(name, description): """ Produce the headerline for a bedfile """ # provide default track names if name is ...
htsworkflow/util/makebed.py
import os import re __docformat__ = "restructredtext en" # map eland_result.txt sense sense_map = {'F': '+', 'R': '-'} sense_color = {'F': '0,0,255', 'R': '255,255,0'} def create_bed_header(name, description): """ Produce the headerline for a bedfile """ # provide default track names if name is ...
0.670608
0.285979
the way.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import json import os import re import shutil from timeit import default_timer as timer import tensorflow as tf import numpy as np from tensorflow.examples.tutorial...
Fashion-MNIST/train_attribution.py
the way.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from datetime import datetime import json import os import re import shutil from timeit import default_timer as timer import tensorflow as tf import numpy as np from tensorflow.examples.tutorial...
0.82425
0.332161
import re import abc import asyncio import logging import websockets from .enums import ReplyCode, EventType from .errors import * from .events import Event from .utils import insort, LineBuffer, SortedHandler, IRCPrefix __all__ = ("Server", "DefaultServer") log = logging.getLogger("airc.server") _cap_subcommands ...
airc/server.py
import re import abc import asyncio import logging import websockets from .enums import ReplyCode, EventType from .errors import * from .events import Event from .utils import insort, LineBuffer, SortedHandler, IRCPrefix __all__ = ("Server", "DefaultServer") log = logging.getLogger("airc.server") _cap_subcommands ...
0.283881
0.101322
import unittest import collections from runtime import env, ast, lib INT_VALUE = env.Value(lib.INTEGER, 1, "x") FLOAT_VALUE = env.Value(lib.FLOAT, 1.0, "y") STRING_VALUE = env.Value(lib.STRING, "Hello", "identifier") LIST_VALUE = env.Value(lib.LIST, ["H", "e", "l", "l", "o"]) SET_VALUE = env.Value(lib.SET, set(LIST_VA...
runtime/test_env.py
import unittest import collections from runtime import env, ast, lib INT_VALUE = env.Value(lib.INTEGER, 1, "x") FLOAT_VALUE = env.Value(lib.FLOAT, 1.0, "y") STRING_VALUE = env.Value(lib.STRING, "Hello", "identifier") LIST_VALUE = env.Value(lib.LIST, ["H", "e", "l", "l", "o"]) SET_VALUE = env.Value(lib.SET, set(LIST_VA...
0.691185
0.393269
def solve_part_1(inputlist : list) -> int: #Current position of the program counter pc = 0 while (pc < len(inputlist) and pc != -1): pc = execute_opcode(inputlist, pc) return inputlist[0] def solve_part_2(inputlist: list) -> int: desired_output = 19690720 for noun in range(...
door_05/solution.py
def solve_part_1(inputlist : list) -> int: #Current position of the program counter pc = 0 while (pc < len(inputlist) and pc != -1): pc = execute_opcode(inputlist, pc) return inputlist[0] def solve_part_2(inputlist: list) -> int: desired_output = 19690720 for noun in range(...
0.373876
0.508849
from __future__ import absolute_import from __future__ import print_function import veriloggen import fsm_state expected_verilog = """ module test; reg CLK; reg RST; wire valid; blinkled uut ( .CLK(CLK), .RST(RST), .valid(valid) ); initial begin CLK = 0; forever begin #5 C...
tests/extension/fsm_/state/test_fsm_state.py
from __future__ import absolute_import from __future__ import print_function import veriloggen import fsm_state expected_verilog = """ module test; reg CLK; reg RST; wire valid; blinkled uut ( .CLK(CLK), .RST(RST), .valid(valid) ); initial begin CLK = 0; forever begin #5 C...
0.344885
0.278459
from __future__ import print_function import os import sys import threading import time from argparse import ArgumentParser from DBSAPI.dbsApi import DbsApi from WMCore.WMSpec.StdSpecs.Harvesting import harvestingWorkload, getTestArguments from WMCore.DataStructs.Run import Run from WMCore.WMBS.File import File from...
etc/harvestingInjector.py
from __future__ import print_function import os import sys import threading import time from argparse import ArgumentParser from DBSAPI.dbsApi import DbsApi from WMCore.WMSpec.StdSpecs.Harvesting import harvestingWorkload, getTestArguments from WMCore.DataStructs.Run import Run from WMCore.WMBS.File import File from...
0.396886
0.070656
import os import sys import argparse import joblib import pandas as pd from azureml.core import Run from azureml.core.run import Run from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.linear_model import LogisticRegression from sklearn.model_selection impor...
src/model1/train_register.py
import os import sys import argparse import joblib import pandas as pd from azureml.core import Run from azureml.core.run import Run from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.linear_model import LogisticRegression from sklearn.model_selection impor...
0.426799
0.172729
import pytest import cocotb from cocotb.queue import LifoQueue, PriorityQueue, Queue, QueueEmpty, QueueFull from cocotb.regression import TestFactory from cocotb.triggers import Combine, NullTrigger async def run_queue_nonblocking_test(dut, queue_type): QUEUE_SIZE = 10 q = queue_type(maxsize=QUEUE_SIZE) ...
tests/test_cases/test_cocotb/test_queues.py
import pytest import cocotb from cocotb.queue import LifoQueue, PriorityQueue, Queue, QueueEmpty, QueueFull from cocotb.regression import TestFactory from cocotb.triggers import Combine, NullTrigger async def run_queue_nonblocking_test(dut, queue_type): QUEUE_SIZE = 10 q = queue_type(maxsize=QUEUE_SIZE) ...
0.496826
0.542803
import time import urllib.parse import json import re # 插件模块 import requests from bs4 import BeautifulSoup # 自写模块 from CityId import CityIdList import Tools # host host = 'www.meituan.com' # 关键字 keyWord = '<PASSWORD>' # 省份名字 provinceName = '江西' # 城市名字(为空获取整个省) cityName = '永丰' # 每次获取个数 number = 32 # 获取的数据总数 count = 0 ...
others/python/meituan-demo/demo.py
import time import urllib.parse import json import re # 插件模块 import requests from bs4 import BeautifulSoup # 自写模块 from CityId import CityIdList import Tools # host host = 'www.meituan.com' # 关键字 keyWord = '<PASSWORD>' # 省份名字 provinceName = '江西' # 城市名字(为空获取整个省) cityName = '永丰' # 每次获取个数 number = 32 # 获取的数据总数 count = 0 ...
0.071017
0.057865
import numpy as np import numpy.linalg as la from scipy.special import erf, erfinv from ..util import numerical_types, sequence_types from .JumpingDistribution import JumpingDistribution class TruncatedGaussianJumpingDistribution(JumpingDistribution): """ Class representing a univariate jumping distribution wh...
distpy/jumping/TruncatedGaussianJumpingDistribution.py
import numpy as np import numpy.linalg as la from scipy.special import erf, erfinv from ..util import numerical_types, sequence_types from .JumpingDistribution import JumpingDistribution class TruncatedGaussianJumpingDistribution(JumpingDistribution): """ Class representing a univariate jumping distribution wh...
0.911946
0.644253
import torch from torch.utils.data import DataLoader, Dataset, Sampler import phyre import numpy as np import matplotlib.pyplot as plt import os INF = 10 ** 20 def dump_img(observation, name): img = phyre.observations_to_uint8_rgb(observation) name = "rollout/" + str(name) + ".jpg" plt.imsave(name, im...
agents/report_web_viewer/dataloader_parallel.py
import torch from torch.utils.data import DataLoader, Dataset, Sampler import phyre import numpy as np import matplotlib.pyplot as plt import os INF = 10 ** 20 def dump_img(observation, name): img = phyre.observations_to_uint8_rgb(observation) name = "rollout/" + str(name) + ".jpg" plt.imsave(name, im...
0.554712
0.396857
from web3 import Web3 import solc import os class EthException(Exception): pass class BankException(Exception): pass class Bank: """ Our Ethereum bank Web3 implementation. """ def __init__(self, http_url, priv_key): self._provider = Web3.HTTPProvider(http_url) self._w3 = Web3(self._provider) self._account...
tokens/bank.py
from web3 import Web3 import solc import os class EthException(Exception): pass class BankException(Exception): pass class Bank: """ Our Ethereum bank Web3 implementation. """ def __init__(self, http_url, priv_key): self._provider = Web3.HTTPProvider(http_url) self._w3 = Web3(self._provider) self._account...
0.442396
0.136695
import errno import os import pytest import sys # Import our local xcross. test_dir = os.path.dirname(os.path.realpath(__file__)) xcross_dir = os.path.dirname(test_dir) sys.path.insert(0, xcross_dir) import xcross os.environ['CROSS_TARGET'] = 'alpha-unknown-linux-gnu' os.environ['CROSS_WITH_PACKAGE_MANAGERS'] = '' ...
test/test_xcross.py
import errno import os import pytest import sys # Import our local xcross. test_dir = os.path.dirname(os.path.realpath(__file__)) xcross_dir = os.path.dirname(test_dir) sys.path.insert(0, xcross_dir) import xcross os.environ['CROSS_TARGET'] = 'alpha-unknown-linux-gnu' os.environ['CROSS_WITH_PACKAGE_MANAGERS'] = '' ...
0.353205
0.246196
import torch import numpy as np import sys import random import copy from torch.autograd import Variable from common_utils import TestCase, run_tests from common_device_type import dtypes, instantiate_device_type_tests from util_test import create_common_tensor class TestSolve(TestCase): def generate_data(self, m...
test/test_npu/test_solve.py
import torch import numpy as np import sys import random import copy from torch.autograd import Variable from common_utils import TestCase, run_tests from common_device_type import dtypes, instantiate_device_type_tests from util_test import create_common_tensor class TestSolve(TestCase): def generate_data(self, m...
0.422505
0.557725
# Standard Library Imports from itertools import combinations # Application-specific Imports from advent_of_code.solvers import solver class Solver(solver.AdventOfCodeSolver): """Advent of Code 2015 Day 17: No Such Thing as Too Much Attributes: puzzle_input (list): A list of instructions for solving...
advent_of_code/solvers/day_17.py
# Standard Library Imports from itertools import combinations # Application-specific Imports from advent_of_code.solvers import solver class Solver(solver.AdventOfCodeSolver): """Advent of Code 2015 Day 17: No Such Thing as Too Much Attributes: puzzle_input (list): A list of instructions for solving...
0.837354
0.315485
import logging, time, json, re from .utils import camel_case logger = logging.getLogger(__name__) # https://support.google.com/tagmanager/answer/7182738?hl=en # Array.from(str).map( s => s.innerText) BUILT_IN_VARIABLES_LIST = ["Click Element", "Click Classes", "Click ID", "Click Target", "Click URL", "Click Text",...
gtm_gear/entity.py
import logging, time, json, re from .utils import camel_case logger = logging.getLogger(__name__) # https://support.google.com/tagmanager/answer/7182738?hl=en # Array.from(str).map( s => s.innerText) BUILT_IN_VARIABLES_LIST = ["Click Element", "Click Classes", "Click ID", "Click Target", "Click URL", "Click Text",...
0.231527
0.135032
import logging import os import shutil import subprocess from typing import AnyStr from typing import Dict, Any, List class FilterModule(object): """ FilterModule is an abstraction responsible for providing Golang Template and Sprig Function functionality through an Ansible Playbook Filter. This class wi...
internal/filters/invoke_go_tf.py
import logging import os import shutil import subprocess from typing import AnyStr from typing import Dict, Any, List class FilterModule(object): """ FilterModule is an abstraction responsible for providing Golang Template and Sprig Function functionality through an Ansible Playbook Filter. This class wi...
0.756178
0.269236
from django.conf import settings from collections import OrderedDict try: from django.core.cache import caches except ImportError: from django.core.cache import get_cache as caches def check(request): all_stats = [] for alias in settings.CACHES: server_stats = [] if is_memcached_profi...
src/heartbeat/checkers/memcached_status.py
from django.conf import settings from collections import OrderedDict try: from django.core.cache import caches except ImportError: from django.core.cache import get_cache as caches def check(request): all_stats = [] for alias in settings.CACHES: server_stats = [] if is_memcached_profi...
0.486575
0.138812
import collections import sys from chainer.backends import cuda from chainer import function_hook try: MemoryHook = cuda.cupy.cuda.memory_hook.MemoryHook memory_hook_available = True except Exception as e: _resolution_error = e MemoryHook = object memory_hook_available = False class CupyMemoryP...
chainer/function_hooks/cupy_memory_profile.py
import collections import sys from chainer.backends import cuda from chainer import function_hook try: MemoryHook = cuda.cupy.cuda.memory_hook.MemoryHook memory_hook_available = True except Exception as e: _resolution_error = e MemoryHook = object memory_hook_available = False class CupyMemoryP...
0.602529
0.32461
import datetime import unittest from builtins import RuntimeError from unittest import mock from unittest.mock import call import freezegun import mongomock from bson import ObjectId from pymongo import MongoClient from pymongo_odm.document import Document from pymongo_odm.helpers import Map from pymongo_odm.helpers....
test/test_document.py
import datetime import unittest from builtins import RuntimeError from unittest import mock from unittest.mock import call import freezegun import mongomock from bson import ObjectId from pymongo import MongoClient from pymongo_odm.document import Document from pymongo_odm.helpers import Map from pymongo_odm.helpers....
0.510252
0.237736
import FWCore.ParameterSet.Config as cms simCastorDigis = cms.EDAlias( mix = cms.VPSet( cms.PSet(type = cms.string('CastorDataFramesSorted')) ) ) simEcalUnsuppressedDigis = cms.EDAlias( mix = cms.VPSet( cms.PSet(type = cms.string('EBDigiCollection')), cms.PSet(type = cms.string('EEDigiCol...
SimGeneral/MixingModule/python/aliases_cfi.py
import FWCore.ParameterSet.Config as cms simCastorDigis = cms.EDAlias( mix = cms.VPSet( cms.PSet(type = cms.string('CastorDataFramesSorted')) ) ) simEcalUnsuppressedDigis = cms.EDAlias( mix = cms.VPSet( cms.PSet(type = cms.string('EBDigiCollection')), cms.PSet(type = cms.string('EEDigiCol...
0.415373
0.30081
print ('《回村》0.1版本','Author: <NAME>') print ('附注:基于 <NAME> 的 Demo 开发') print ('更多内容请关注微博或微信公众号:IoT前哨站') print ('') print ('欢迎来到风景优美的山谷。但是时间不早了,你要返回村庄。亲戚朋友还在等你回去聚餐。') print ('') directions = ['北面','南面','东面','西面'] # Data structure to store details of each location in the game class Location: # Constructor - set up ...
Text-Adventure/Gohome.py
print ('《回村》0.1版本','Author: <NAME>') print ('附注:基于 <NAME> 的 Demo 开发') print ('更多内容请关注微博或微信公众号:IoT前哨站') print ('') print ('欢迎来到风景优美的山谷。但是时间不早了,你要返回村庄。亲戚朋友还在等你回去聚餐。') print ('') directions = ['北面','南面','东面','西面'] # Data structure to store details of each location in the game class Location: # Constructor - set up ...
0.215681
0.18743
from collections import Counter from typing import List from ranked_vote.ballot import Ballot, Candidate class ApprovalEntry: def __init__(self, candidate, other_candidate, candidate_votes, other_candidate_votes): self.candidate = candidate self.other_candidate = other_candidate self.cand...
ranked_vote/analysis/honest_approval_set.py
from collections import Counter from typing import List from ranked_vote.ballot import Ballot, Candidate class ApprovalEntry: def __init__(self, candidate, other_candidate, candidate_votes, other_candidate_votes): self.candidate = candidate self.other_candidate = other_candidate self.cand...
0.75985
0.150778
import sys import os import stat import re import copy from pwd import getpwnam import shutil def main(): from docassemble.base.config import daconfig, S3_ENABLED, s3_config, AZURE_ENABLED, azure_config certs_location = daconfig.get('certs', None) cloud = None prefix = None if S3_ENABLED: i...
docassemble_webapp/docassemble/webapp/install_certs.py
import sys import os import stat import re import copy from pwd import getpwnam import shutil def main(): from docassemble.base.config import daconfig, S3_ENABLED, s3_config, AZURE_ENABLED, azure_config certs_location = daconfig.get('certs', None) cloud = None prefix = None if S3_ENABLED: i...
0.150996
0.057388
import os, sys, inspect, torch, csv, copy currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) from torch_geometric.nn import MessagePassing from torch_geometric.utils import degree from torch_geometric.nn import gl...
stereonet/models/mp_layers.py
import os, sys, inspect, torch, csv, copy currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0, parentdir) from torch_geometric.nn import MessagePassing from torch_geometric.utils import degree from torch_geometric.nn import gl...
0.722723
0.431884
from __future__ import absolute_import, unicode_literals import unittest from django.core.files.base import ContentFile from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from django.utils.six import b from tuiuiu.tests.utils import TuiuiuTes...
tuiuiu/tuiuiudocs/tests/test_search.py
from __future__ import absolute_import, unicode_literals import unittest from django.core.files.base import ContentFile from django.core.urlresolvers import reverse from django.test import TestCase from django.test.utils import override_settings from django.utils.six import b from tuiuiu.tests.utils import TuiuiuTes...
0.638835
0.158989
import requests import json import csv from collections import deque import time import datetime def getsince(csv_file): with open(csv_file,'r') as f: return deque(csv.reader(f),1)[0][0] def getprices(): #urlbfx='https://api.bitfinex.com/v2/candles/trade:1m:tLTCBTC/hist' ...
pricefetch.py
import requests import json import csv from collections import deque import time import datetime def getsince(csv_file): with open(csv_file,'r') as f: return deque(csv.reader(f),1)[0][0] def getprices(): #urlbfx='https://api.bitfinex.com/v2/candles/trade:1m:tLTCBTC/hist' ...
0.042752
0.071819
import collections from typing import Any, Dict, Optional, Iterable, Sequence import numpy as np from modin.core.dataframe.base.exchange.dataframe_protocol.dataframe import ( ProtocolDataframe, ) from modin.core.dataframe.pandas.dataframe.dataframe import PandasDataframe from modin.utils import _inherit_docstrings...
modin/core/dataframe/pandas/exchange/dataframe_protocol/dataframe.py
import collections from typing import Any, Dict, Optional, Iterable, Sequence import numpy as np from modin.core.dataframe.base.exchange.dataframe_protocol.dataframe import ( ProtocolDataframe, ) from modin.core.dataframe.pandas.dataframe.dataframe import PandasDataframe from modin.utils import _inherit_docstrings...
0.911807
0.493714
import importlib.util, os, shutil, subprocess, sys, tempfile, urllib.request assert sys.version_info >= (3, 4) # A horrible workaround for a partially existing distutils. _distutils_usercustomize = """ # miniirc_bootstrap: Make user-provided packages load first. # This can safely be removed if distutils has been pro...
miniirc_bootstrap.py
import importlib.util, os, shutil, subprocess, sys, tempfile, urllib.request assert sys.version_info >= (3, 4) # A horrible workaround for a partially existing distutils. _distutils_usercustomize = """ # miniirc_bootstrap: Make user-provided packages load first. # This can safely be removed if distutils has been pro...
0.296145
0.200734
import lightgbm as lgb from sklearn.model_selection import GridSearchCV from sklearn.model_selection import StratifiedKFold from matplotlib import pyplot as plt import numpy as np class LightGBMWrapper: """ Apply an light GBM model on a dataset with hyperparameters tuning """ params = {'boosting_type':...
Contests/2018-11-09 - 2018-11-10 - Huawei Hackathon/src/models/other/lightGBMWrapper.py
import lightgbm as lgb from sklearn.model_selection import GridSearchCV from sklearn.model_selection import StratifiedKFold from matplotlib import pyplot as plt import numpy as np class LightGBMWrapper: """ Apply an light GBM model on a dataset with hyperparameters tuning """ params = {'boosting_type':...
0.786131
0.455986
import subprocess import time instList = [ \ #(0x707f, 0x2003, 'LW', ['rs1','rd','immI']), #(0x707f, 0x3, 'LB', ['rs1','rd','immI']), #(0x707f, 0x1003, 'LH', ['rs1','rd','immI']), #(0x707f, 0x3003, 'LD', ['rs1','rd','immI']), #(0x7...
cores/RISC-V/RISC-V-Synth/ILAVerif/BaseI/handle.py
import subprocess import time instList = [ \ #(0x707f, 0x2003, 'LW', ['rs1','rd','immI']), #(0x707f, 0x3, 'LB', ['rs1','rd','immI']), #(0x707f, 0x1003, 'LH', ['rs1','rd','immI']), #(0x707f, 0x3003, 'LD', ['rs1','rd','immI']), #(0x7...
0.04844
0.282017
from pynmea.exceptions import NoDataGivenError class NMEAStream(object): """ NMEAStream object is used to """ def __init__(self, stream_obj=None): """ stream_obj should be a file like object. If the requirement is just to split data in memory, no stream_obj is required. Sim...
adcpy/pynmea/streamer.py
from pynmea.exceptions import NoDataGivenError class NMEAStream(object): """ NMEAStream object is used to """ def __init__(self, stream_obj=None): """ stream_obj should be a file like object. If the requirement is just to split data in memory, no stream_obj is required. Sim...
0.426322
0.404949
import os import sys reload(sys) sys.setdefaultencoding('UTF-8') import signal import time from datetime import datetime from datetime import timedelta import ConfigParser import glob import json import uuid import shutil import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning request...
ETL/bin/WorkInfoCollector_MODULE.py
import os import sys reload(sys) sys.setdefaultencoding('UTF-8') import signal import time from datetime import datetime from datetime import timedelta import ConfigParser import glob import json import uuid import shutil import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning request...
0.138404
0.062417
import pytest from brownie import Contract, Wei, reverts from fixedint import * import shared def test_Demand_Curve_Setting(loanToken, loanTokenSettings, LoanTokenSettingsLowerAdmin, accounts, LoanToken, LoanTokenLogicStandard): baseRate = 1e18 rateMultiplier = 20.25e18 targetLevel=80*10**18 kinkLevel=...
tests/loanToken/administration/test_administration.py
import pytest from brownie import Contract, Wei, reverts from fixedint import * import shared def test_Demand_Curve_Setting(loanToken, loanTokenSettings, LoanTokenSettingsLowerAdmin, accounts, LoanToken, LoanTokenLogicStandard): baseRate = 1e18 rateMultiplier = 20.25e18 targetLevel=80*10**18 kinkLevel=...
0.452536
0.409752
import sys,os import argparse import subprocess MRFLOW_HOME = os.environ['MRFLOW_HOME'] sys.path.append(MRFLOW_HOME) import dataset_parameters def generate_paths(dataset, arg): """ Generate paths for either Sintel or Kitti Requires the following environment variables to be set: - SINTEL_HOME - KIT...
mrflow_dataset.py
import sys,os import argparse import subprocess MRFLOW_HOME = os.environ['MRFLOW_HOME'] sys.path.append(MRFLOW_HOME) import dataset_parameters def generate_paths(dataset, arg): """ Generate paths for either Sintel or Kitti Requires the following environment variables to be set: - SINTEL_HOME - KIT...
0.340376
0.21595
from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from horizon import tabs from horizon.utils import memoized from horizon import workflows from openstack_dashboard import ap...
openstack_dashboard/dashboards/project/vpn/views.py
from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages from horizon import tabs from horizon.utils import memoized from horizon import workflows from openstack_dashboard import ap...
0.448668
0.098599
import inspect import os import subprocess # noqa: S404 import sys from dataclasses import dataclass from pathlib import Path from textwrap import dedent from types import ModuleType from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import TYPE_CHECKING ...
tests/functional/conftest.py
import inspect import os import subprocess # noqa: S404 import sys from dataclasses import dataclass from pathlib import Path from textwrap import dedent from types import ModuleType from typing import Any from typing import Callable from typing import Iterable from typing import List from typing import TYPE_CHECKING ...
0.639736
0.204144
_character_map = { # Symbol: (Hex Value, URI Form) '!': (0x21, '!'), '"': (0x22, '%22'), '%': (0x25, '%25'), '&': (0x26, '%26'), '\'': (0x27, '\''), '(': (0x28, '('), ')': (0x29, ')'), '*': (0x2a, '*'), '+': (0x2b, '+'), ',': (0x2c, ','), '-': (0x2d, '-'), '.': (0x2e, '.'), '/': (0x2f, '%2F'), '0': ...
epc/encoding/string.py
_character_map = { # Symbol: (Hex Value, URI Form) '!': (0x21, '!'), '"': (0x22, '%22'), '%': (0x25, '%25'), '&': (0x26, '%26'), '\'': (0x27, '\''), '(': (0x28, '('), ')': (0x29, ')'), '*': (0x2a, '*'), '+': (0x2b, '+'), ',': (0x2c, ','), '-': (0x2d, '-'), '.': (0x2e, '.'), '/': (0x2f, '%2F'), '0': ...
0.395368
0.175856
from Token import Token from SymbolTable import SymbolTable from TableEntry import TableEntry from SymbolTableTree import SymbolTableTree from ASA import * class Syntactic(): token = '' arrayToken = [] indexToken = '' no = '' symbolTableTree = '' tableEntry = '' actualTable = '...
tp2/src/Syntactic.py
from Token import Token from SymbolTable import SymbolTable from TableEntry import TableEntry from SymbolTableTree import SymbolTableTree from ASA import * class Syntactic(): token = '' arrayToken = [] indexToken = '' no = '' symbolTableTree = '' tableEntry = '' actualTable = '...
0.119588
0.076615
from __future__ import absolute_import from datetime import datetime from os import path, listdir from time import sleep from unittest import TestCase import re import pytest from werkzeug.datastructures import Headers from werkzeug.http import http_date from werkzeug.test import EnvironBuilder from werkzeug.wrapper...
tests/webapp_t.py
from __future__ import absolute_import from datetime import datetime from os import path, listdir from time import sleep from unittest import TestCase import re import pytest from werkzeug.datastructures import Headers from werkzeug.http import http_date from werkzeug.test import EnvironBuilder from werkzeug.wrapper...
0.496094
0.19309
from .CodeHelpers import generateExpressionCode from .ErrorCodes import getErrorExitCode def generateCAPIObjectCodeCommon(to_name, capi, arg_desc, may_raise, ref_count, source_ref, emit, context, none_null = False): arg_names = [] for arg_name, arg_expression in arg_desc: ...
nuitka/codegen/PythonAPICodes.py
from .CodeHelpers import generateExpressionCode from .ErrorCodes import getErrorExitCode def generateCAPIObjectCodeCommon(to_name, capi, arg_desc, may_raise, ref_count, source_ref, emit, context, none_null = False): arg_names = [] for arg_name, arg_expression in arg_desc: ...
0.317426
0.070081
import tkinter as tk from tkinter.ttk import Combobox from tkinter import font class FontSelector(tk.Toplevel): """A font selector popup""" def __init__(self, master): super().__init__(master) self.master = master self.font = master.font self.title('Font') self.transient...
{{cookiecutter.project_slug}}/text_editor/widgets/fontselect.py
import tkinter as tk from tkinter.ttk import Combobox from tkinter import font class FontSelector(tk.Toplevel): """A font selector popup""" def __init__(self, master): super().__init__(master) self.master = master self.font = master.font self.title('Font') self.transient...
0.528777
0.096365
import tensorflow as tf from dl_playground.networks.model import BatchModel, ContinualModel class LayerModel(tf.keras.Model, BatchModel): """A model contains one layer. A thin wrapper around the layer to comply with model interface. Parameters ---------- layer : tf.keras.layers.Layer & BatchLay...
networks/layers/model.py
import tensorflow as tf from dl_playground.networks.model import BatchModel, ContinualModel class LayerModel(tf.keras.Model, BatchModel): """A model contains one layer. A thin wrapper around the layer to comply with model interface. Parameters ---------- layer : tf.keras.layers.Layer & BatchLay...
0.962743
0.509581
import json import os.path import netaddr import argparse from shared.organization import get_organization_accounts __description__ = "Add and remove items from the config file" def configure(action, arguments): if not os.path.isfile(arguments.config_file): print("Config file does not exist, creating on...
commands/configure.py
import json import os.path import netaddr import argparse from shared.organization import get_organization_accounts __description__ = "Add and remove items from the config file" def configure(action, arguments): if not os.path.isfile(arguments.config_file): print("Config file does not exist, creating on...
0.146423
0.16492
from extra_views.formsets import InlineFormSetMixin from django.http import HttpResponseRedirect from django.forms.formsets import all_valid from vanilla import GenericModelView class BaseInlinesView(GenericModelView): """ A base view class that provides a way to multiple inline formsets in a request. Us...
extra_views/advanced.py
from extra_views.formsets import InlineFormSetMixin from django.http import HttpResponseRedirect from django.forms.formsets import all_valid from vanilla import GenericModelView class BaseInlinesView(GenericModelView): """ A base view class that provides a way to multiple inline formsets in a request. Us...
0.688049
0.217753
import numpy as np def accuracy_score(y_true, y_pred): """ Classification performance metric that computes the accuracy of y_true and y_pred. :param numpy.array y_true: array-like of shape (n_samples,) Ground truth correct labels. :param numpy.array y_pred: array-like of shape (n_samples,) Estimat...
src/si/util/metrics.py
import numpy as np def accuracy_score(y_true, y_pred): """ Classification performance metric that computes the accuracy of y_true and y_pred. :param numpy.array y_true: array-like of shape (n_samples,) Ground truth correct labels. :param numpy.array y_pred: array-like of shape (n_samples,) Estimat...
0.910207
0.921181
import numpy as np import torch import torch.nn as nn class TNGraph(nn.Module): def __init__(self, graph, contract_order=None): super(TNGraph, self).__init__() self.graph = graph self.contract_order = contract_order self.cores = [] for item in range(len(graph)): ...
tensorNetwork/torch.py
import numpy as np import torch import torch.nn as nn class TNGraph(nn.Module): def __init__(self, graph, contract_order=None): super(TNGraph, self).__init__() self.graph = graph self.contract_order = contract_order self.cores = [] for item in range(len(graph)): ...
0.650911
0.30026
from django.shortcuts import render,redirect,get_object_or_404 from django.http import HttpResponse,Http404 from .models import Image,Profile,Comments from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import HttpResponseRedirect from .forms import New...
gram/views.py
from django.shortcuts import render,redirect,get_object_or_404 from django.http import HttpResponse,Http404 from .models import Image,Profile,Comments from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.http import HttpResponseRedirect from .forms import New...
0.293708
0.059102
from compas.utilities import flatten from compas.geometry import allclose from compas.geometry import multiply_matrices from compas.geometry.transformations import decompose_matrix from compas.geometry.transformations import matrix_from_scale_factors from compas.geometry.transformations import matrix_from_frame from co...
src/compas/geometry/transformations/scale.py
from compas.utilities import flatten from compas.geometry import allclose from compas.geometry import multiply_matrices from compas.geometry.transformations import decompose_matrix from compas.geometry.transformations import matrix_from_scale_factors from compas.geometry.transformations import matrix_from_frame from co...
0.949728
0.749821
import tensorflow as tf from keras import backend as K from keras.models import Model from keras.layers import Conv2D, BatchNormalization, ReLU, DepthwiseConv2D, Activation, Input, Add ,Lambda,Concatenate,GlobalAvgPool1D from keras.layers import GlobalAveragePooling2D, Reshape, Dense, multiply, Softmax, Flatten, merge,...
Densenet.py
import tensorflow as tf from keras import backend as K from keras.models import Model from keras.layers import Conv2D, BatchNormalization, ReLU, DepthwiseConv2D, Activation, Input, Add ,Lambda,Concatenate,GlobalAvgPool1D from keras.layers import GlobalAveragePooling2D, Reshape, Dense, multiply, Softmax, Flatten, merge,...
0.908634
0.521532
import skil_client from .base import Resource class AzureStorage(Resource): """AzureStorage SKIL Azure storage resource. # Arguments: skil: `Skil` server instance name: Resource name container_name: Azure storage container name credential_uri: path to credential file ...
skil/resources/storage.py
import skil_client from .base import Resource class AzureStorage(Resource): """AzureStorage SKIL Azure storage resource. # Arguments: skil: `Skil` server instance name: Resource name container_name: Azure storage container name credential_uri: path to credential file ...
0.753875
0.06357
import os import random import sys from pyglet.gl import * import pyglet from pyglet.window import key pyglet.resource.path.insert(0, os.path.dirname(__file__)) pyglet.resource.reindex() BALL_IMAGE = 'ball.png' BALL_SOUND = 'ping.wav' sound = pyglet.resource.media(BALL_SOUND, streaming=False) class Ball(pyglet.spri...
examples/pyglet/noisy/__init__.py
import os import random import sys from pyglet.gl import * import pyglet from pyglet.window import key pyglet.resource.path.insert(0, os.path.dirname(__file__)) pyglet.resource.reindex() BALL_IMAGE = 'ball.png' BALL_SOUND = 'ping.wav' sound = pyglet.resource.media(BALL_SOUND, streaming=False) class Ball(pyglet.spri...
0.216094
0.207536
"""Pools managing shared Session objects.""" from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import super from future import standard_library standard_library.install_aliases() import datetime from six....
google/cloud/spanner_v1/pool.py
"""Pools managing shared Session objects.""" from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import super from future import standard_library standard_library.install_aliases() import datetime from six....
0.907732
0.366533
from __future__ import print_function import os from fabric.api import abort, env, run, settings, put from braid import postgres, cron, archive, utils from braid.twisted import service from braid.utils import confirm from braid import config from braid.tasks import addTasks __all__ = ['config'] class Trac(service...
services/trac/fabfile.py
from __future__ import print_function import os from fabric.api import abort, env, run, settings, put from braid import postgres, cron, archive, utils from braid.twisted import service from braid.utils import confirm from braid import config from braid.tasks import addTasks __all__ = ['config'] class Trac(service...
0.188063
0.068694
import os from typing import Union from tests.warehouse_profile import WarehouseProfile from wr_profiles import EnvvarProfile def test_create_environment_with_and_without_activation(): wp: Union[WarehouseProfile, EnvvarProfile] = WarehouseProfile(name='for_this_test') original_values = wp.to_dict() env...
tests/test_environment.py
import os from typing import Union from tests.warehouse_profile import WarehouseProfile from wr_profiles import EnvvarProfile def test_create_environment_with_and_without_activation(): wp: Union[WarehouseProfile, EnvvarProfile] = WarehouseProfile(name='for_this_test') original_values = wp.to_dict() env...
0.617513
0.359252
__all__ = ['letv_download', 'letvcloud_download', 'letvcloud_download_by_vu'] import json import random import xml.etree.ElementTree as ET import base64, hashlib, urllib, time, re from ..common import * #@DEPRECATED def get_timestamp(): tn = random.random() url = 'http://api.letv.com/time?tn={}'.format(tn) ...
libraries/you-get/extractors/letv.py
__all__ = ['letv_download', 'letvcloud_download', 'letvcloud_download_by_vu'] import json import random import xml.etree.ElementTree as ET import base64, hashlib, urllib, time, re from ..common import * #@DEPRECATED def get_timestamp(): tn = random.random() url = 'http://api.letv.com/time?tn={}'.format(tn) ...
0.175503
0.178938
import io,sys,time,random import requests #用于模拟网页请求,抓取 from openpyxl import load_workbook #用于写入excel(why not csv???) import lxml #html&xml解析库,方便处理数据 from bs4 import BeautifulSoup #也是方便处理html页面(美味汤) from json import loads #处理respons...
spider.py
import io,sys,time,random import requests #用于模拟网页请求,抓取 from openpyxl import load_workbook #用于写入excel(why not csv???) import lxml #html&xml解析库,方便处理数据 from bs4 import BeautifulSoup #也是方便处理html页面(美味汤) from json import loads #处理respons...
0.057965
0.134577
import os import json # Status script # Checking the status of the annotations, # both old and new. # Samia and Petter annotations with open(os.path.join("v1.1","data","dev.json"),"r",encoding="utf-8") as data: dev_sp = json.load(data) with open(os.path.join("v1.1","data","train.json"),"r",encoding="utf-8") as...
status_script.py
import os import json # Status script # Checking the status of the annotations, # both old and new. # Samia and Petter annotations with open(os.path.join("v1.1","data","dev.json"),"r",encoding="utf-8") as data: dev_sp = json.load(data) with open(os.path.join("v1.1","data","train.json"),"r",encoding="utf-8") as...
0.218419
0.288547
from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_selection import SelectKBest, chi2 from sklearn.base import BaseEstimator,TransformerMixin import logging import time import logging logger = logging.getLogger(__name__) class...
python/build/lib/seldon/pipeline/tfidf_transform.py
from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_selection import SelectKBest, chi2 from sklearn.base import BaseEstimator,TransformerMixin import logging import time import logging logger = logging.getLogger(__name__) class...
0.834272
0.345906
import asyncio import io import pytz from datetime import datetime import pexpect import aioschedule from .sql import handling_casino_sql from .sql.database import loop from .parse_config import get_database_config BACKUP_PATH = "bot_database_backup.sql" HOST, USER, PASSWORD, DATABASE_NAME, PORT = loop.run_until_co...
Bot/task_scheduler.py
import asyncio import io import pytz from datetime import datetime import pexpect import aioschedule from .sql import handling_casino_sql from .sql.database import loop from .parse_config import get_database_config BACKUP_PATH = "bot_database_backup.sql" HOST, USER, PASSWORD, DATABASE_NAME, PORT = loop.run_until_co...
0.20834
0.128717
import torch import torch.nn as nn import torch.nn.functional as F from ..builder import LOSSES from .utils import weight_reduce_loss def cross_entropy(pred, label, weight=None, class_weight=None, reduction='mean', avg_factor=N...
mmseg/models/losses/affinity_loss.py
import torch import torch.nn as nn import torch.nn.functional as F from ..builder import LOSSES from .utils import weight_reduce_loss def cross_entropy(pred, label, weight=None, class_weight=None, reduction='mean', avg_factor=N...
0.934349
0.609524
from .Helpers import get_builtin_type, indent, get_attribute_size, is_flags_enum, get_comments_from_attribute from .Helpers import get_comments_if_present, create_enum_name, InterfaceType from .Helpers import get_read_method_name, get_reverse_method_name, get_write_method_name from .JavaGeneratorBase import JavaGenerat...
generators/java/JavaEnumGenerator.py
from .Helpers import get_builtin_type, indent, get_attribute_size, is_flags_enum, get_comments_from_attribute from .Helpers import get_comments_if_present, create_enum_name, InterfaceType from .Helpers import get_read_method_name, get_reverse_method_name, get_write_method_name from .JavaGeneratorBase import JavaGenerat...
0.630457
0.118947
from collections import defaultdict from pathlib import Path import csv from bs4 import BeautifulSoup from django.conf import settings from django.core.files import File from django.core.management.base import BaseCommand from django.urls import reverse from wagtail.core.models import Page, Site, Locale, Collection, P...
iogt_content_migration/management/commands/load_v1_db.py
from collections import defaultdict from pathlib import Path import csv from bs4 import BeautifulSoup from django.conf import settings from django.core.files import File from django.core.management.base import BaseCommand from django.urls import reverse from wagtail.core.models import Page, Site, Locale, Collection, P...
0.371137
0.063802
from collections import Counter from eva_cttv_pipeline.clinvar_xml_io import clinvar_xml_io from eva_cttv_pipeline.trait_mapping.trait import Trait def parse_trait_names(filepath: str) -> list: """For a file containing ClinVar records in the XML format, return a list of Traits for the records in the file. Ea...
eva_cttv_pipeline/trait_mapping/trait_names_parsing.py
from collections import Counter from eva_cttv_pipeline.clinvar_xml_io import clinvar_xml_io from eva_cttv_pipeline.trait_mapping.trait import Trait def parse_trait_names(filepath: str) -> list: """For a file containing ClinVar records in the XML format, return a list of Traits for the records in the file. Ea...
0.86941
0.54462
import numpy as np import scipy.integrate as integrate def rb_nfw(m200,c,z): """ Function to compute a NFW profile. Velocity Dispersion equation taken from Hoeft M.; <NAME>. & Gottlober, S, 2004, ApJ 602,1 http://adsabs.harvard.edu/cgi-bin/bib_query?2004ApJ...602..162H Input :- m200 :- ...
halo/rb_nfw.py
import numpy as np import scipy.integrate as integrate def rb_nfw(m200,c,z): """ Function to compute a NFW profile. Velocity Dispersion equation taken from Hoeft M.; <NAME>. & Gottlober, S, 2004, ApJ 602,1 http://adsabs.harvard.edu/cgi-bin/bib_query?2004ApJ...602..162H Input :- m200 :- ...
0.416678
0.257213
from ...ucsmo import ManagedObject from ...ucscoremeta import MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class FirmwareUcscInfoConsts: CONN_PROTOCOL_IPV4 = "ipv4" CONN_PROTOCOL_IPV6 = "ipv6" CONN_PROTOCOL_UNKNOWN = "unknown" class FirmwareUcscInfo(ManagedObject): """This is FirmwareU...
ucsmsdk/mometa/firmware/FirmwareUcscInfo.py
from ...ucsmo import ManagedObject from ...ucscoremeta import MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class FirmwareUcscInfoConsts: CONN_PROTOCOL_IPV4 = "ipv4" CONN_PROTOCOL_IPV6 = "ipv6" CONN_PROTOCOL_UNKNOWN = "unknown" class FirmwareUcscInfo(ManagedObject): """This is FirmwareU...
0.418578
0.204898
from __future__ import print_function import numpy as np import numba.unittest_support as unittest from numba.compiler import compile_isolated, Flags from numba import utils, jit from .support import TestCase def complex_constant(n): tmp = n + 4 return tmp + 3j def long_constant(n): return n + 10000000...
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/tests/test_object_mode.py
from __future__ import print_function import numpy as np import numba.unittest_support as unittest from numba.compiler import compile_isolated, Flags from numba import utils, jit from .support import TestCase def complex_constant(n): tmp = n + 4 return tmp + 3j def long_constant(n): return n + 10000000...
0.612541
0.573499
import copy import logging import typing from collections import defaultdict from typing import Dict, Any, List, Type, Optional import pandas as pd from flask_babel import _ from sqlalchemy import func, distinct from anyway.app_and_db import db from anyway.backend_constants import BE_CONST, LabeledCode ...
anyway/widgets/widget_utils.py
import copy import logging import typing from collections import defaultdict from typing import Dict, Any, List, Type, Optional import pandas as pd from flask_babel import _ from sqlalchemy import func, distinct from anyway.app_and_db import db from anyway.backend_constants import BE_CONST, LabeledCode ...
0.496094
0.214815
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databa...
terra_sdk/protobuf/cosmos/params/v1beta1/params_pb2.py
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databa...
0.422862
0.116011
import os import pytest import fetch_data as fd def test_file_logging(): import logging from fetch_data import utils dest = "./tests/downloads/logging_download.log" utils.log_to_file(dest) logging.warning("[TESTING] This is a test log for downloading") with open(dest) as file: a...
tests/test_download.py
import os import pytest import fetch_data as fd def test_file_logging(): import logging from fetch_data import utils dest = "./tests/downloads/logging_download.log" utils.log_to_file(dest) logging.warning("[TESTING] This is a test log for downloading") with open(dest) as file: a...
0.356895
0.34726