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 django.core.exceptions import ObjectDoesNotExist from rest_framework import viewsets from rest_framework.response import Response from .serializers import UserSerializer, PostSerializer, \ PostImageSerializer, CommentSerializer, LikeSerializer from .models import User, Post, Like, Commen...
server/sns/views.py
from django.core.exceptions import ObjectDoesNotExist from rest_framework import viewsets from rest_framework.response import Response from .serializers import UserSerializer, PostSerializer, \ PostImageSerializer, CommentSerializer, LikeSerializer from .models import User, Post, Like, Commen...
0.548432
0.084909
import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.SignerBean import SignerBean class SignFieldBean(object): def __init__(self): self._sign_field_type = None self._signer = None self._struct_key = None @property def sign_field_type(self):...
alipay/aop/api/domain/SignFieldBean.py
import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.SignerBean import SignerBean class SignFieldBean(object): def __init__(self): self._sign_field_type = None self._signer = None self._struct_key = None @property def sign_field_type(self):...
0.552057
0.114467
from __future__ import division import numpy as np from sklearn import datasets from sklearn import metrics from sklearn.model_selection import StratifiedKFold, train_test_split from neupy import algorithms from neupy.exceptions import NotTrained from base import BaseTestCase class PNNTestCase(BaseTestCase): d...
tests/algorithms/rbfn/test_pnn.py
from __future__ import division import numpy as np from sklearn import datasets from sklearn import metrics from sklearn.model_selection import StratifiedKFold, train_test_split from neupy import algorithms from neupy.exceptions import NotTrained from base import BaseTestCase class PNNTestCase(BaseTestCase): d...
0.877411
0.61806
import csv import zipfile import requests import StringIO, datetime, re from lxml import etree from util import fred_countries_currencies, oecd_countries_currencies FRED_RATES = "https://fred.stlouisfed.org/categories/94/downloaddata/INTLFXD_csv_2.zip" OECD_RATES = "http://stats.oecd.org/restsdmx/sdmx.ashx/GetData/MEI...
exchangerates/get_rates.py
import csv import zipfile import requests import StringIO, datetime, re from lxml import etree from util import fred_countries_currencies, oecd_countries_currencies FRED_RATES = "https://fred.stlouisfed.org/categories/94/downloaddata/INTLFXD_csv_2.zip" OECD_RATES = "http://stats.oecd.org/restsdmx/sdmx.ashx/GetData/MEI...
0.370909
0.197948
# "申报时间", "证券代码", "证券名称", "操作", "委托状态", "委托数量", "成交数量", "撤消数量", , "委托价格", "成交均价", "合同编号", "委托子业务", "约定号", "对方账户", "参考汇率", "结算币种", "交易币种", "证券中文名", "出错信息 from QUANTAXIS.QAUtil.QAParameter import ORDER_DIRECTION, TRADE_STATUS, ORDER_STATUS cn_en_compare = {'明细': 'id', '证券代码': 'code', '...
QUANTAXIS/QAMarket/common.py
# "申报时间", "证券代码", "证券名称", "操作", "委托状态", "委托数量", "成交数量", "撤消数量", , "委托价格", "成交均价", "合同编号", "委托子业务", "约定号", "对方账户", "参考汇率", "结算币种", "交易币种", "证券中文名", "出错信息 from QUANTAXIS.QAUtil.QAParameter import ORDER_DIRECTION, TRADE_STATUS, ORDER_STATUS cn_en_compare = {'明细': 'id', '证券代码': 'code', '...
0.226612
0.245847
import argparse import sys, os, subprocess from env_backup.src.kernel import kernel_exists, get_kernel_location, install_new_ipykernel, \ set_userbase, get_userbase, install_launch_script from env_backup.src.util import fmt_now, backup_local, valid_label, remove_local, \ _kernel_name_description, prompt_procee...
env_backup/command_line.py
import argparse import sys, os, subprocess from env_backup.src.kernel import kernel_exists, get_kernel_location, install_new_ipykernel, \ set_userbase, get_userbase, install_launch_script from env_backup.src.util import fmt_now, backup_local, valid_label, remove_local, \ _kernel_name_description, prompt_procee...
0.23855
0.085633
import ast import tempfile from datetime import datetime from http import HTTPStatus from os import remove from fastapi import APIRouter, Request, Query from fastapi.concurrency import run_in_threadpool from kfp import Client as kfclient import mlrun.api.crud import mlrun.api.schemas from mlrun.api.api.utils import l...
mlrun/api/api/endpoints/pipelines.py
import ast import tempfile from datetime import datetime from http import HTTPStatus from os import remove from fastapi import APIRouter, Request, Query from fastapi.concurrency import run_in_threadpool from kfp import Client as kfclient import mlrun.api.crud import mlrun.api.schemas from mlrun.api.api.utils import l...
0.327238
0.073763
from pysmt.shortcuts import Symbol, And, Equals, BVAdd, BVMul, Bool, Ite, BV, BVURem, BVExtract, ForAll, Exists, Portfolio, Solver from pysmt.typing import BVType from pysmt.logics import BV as logicBV from frail import IteExtend, BVAddExtend, BVSubExtend, BVMulExtend, BVEqualsExtend import time op_design_free_vars =...
run/gen_smt/example_smt.py
from pysmt.shortcuts import Symbol, And, Equals, BVAdd, BVMul, Bool, Ite, BV, BVURem, BVExtract, ForAll, Exists, Portfolio, Solver from pysmt.typing import BVType from pysmt.logics import BV as logicBV from frail import IteExtend, BVAddExtend, BVSubExtend, BVMulExtend, BVEqualsExtend import time op_design_free_vars =...
0.319758
0.245808
entryPoints = [ "autocomplete", "autocomplete/testing", "badge", "badge/testing", "bottom-sheet", "bottom-sheet/testing", "button", "button/testing", "button-toggle", "button-toggle/testing", "card", "checkbox", "checkbox/testing", "chips", "core", "core/t...
src/material/config.bzl
entryPoints = [ "autocomplete", "autocomplete/testing", "badge", "badge/testing", "bottom-sheet", "bottom-sheet/testing", "button", "button/testing", "button-toggle", "button-toggle/testing", "card", "checkbox", "checkbox/testing", "chips", "core", "core/t...
0.443841
0.419291
import os import requests import ujson as json from . import errors as err class Config(object): """Load Configuration.""" def __init__(self, const): """Initialize default configuration parameters. :const: Constant class with default values. """ self.config_file = const.CONFI...
src/libapp/app/app__PROJECT_/config.py
import os import requests import ujson as json from . import errors as err class Config(object): """Load Configuration.""" def __init__(self, const): """Initialize default configuration parameters. :const: Constant class with default values. """ self.config_file = const.CONFI...
0.590425
0.061255
import unittest2 from google.appengine.ext import ndb from google.appengine.ext import testbed from helpers.district_manipulator import DistrictManipulator from helpers.event_helper import EventHelper from models.district import District class TestEventGetShortName(unittest2.TestCase): def setUp(self): ...
old_py2/tests/test_event_get_short_name.py
import unittest2 from google.appengine.ext import ndb from google.appengine.ext import testbed from helpers.district_manipulator import DistrictManipulator from helpers.event_helper import EventHelper from models.district import District class TestEventGetShortName(unittest2.TestCase): def setUp(self): ...
0.496826
0.297763
import os import sys import subprocess def supports_color(): """Check if system supports ANSI colour.""" plat = sys.platform supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ) is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() return supported_p...
juicy-jaguars/setup.py
import os import sys import subprocess def supports_color(): """Check if system supports ANSI colour.""" plat = sys.platform supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ) is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() return supported_p...
0.455441
0.140454
"""Tests for the Disentangled Sequential Variational Autoencoder.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow_probability.examples import disentangled_vae tfe = tf.contrib.eager @tfe.run_...
tensorflow_probability/examples/disentangled_vae_test.py
"""Tests for the Disentangled Sequential Variational Autoencoder.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow_probability.examples import disentangled_vae tfe = tf.contrib.eager @tfe.run_...
0.928522
0.608449
import logging import sys import typing from typing import Union from dbnd._core.errors.friendly_error.executor_k8s import ( local_engine_not_accept_remote_jobs, ) from dbnd._core.parameter.parameter_builder import parameter from dbnd._core.task import config from dbnd._core.task_build.task_registry import build_...
modules/dbnd/src/dbnd/_core/settings/engine.py
import logging import sys import typing from typing import Union from dbnd._core.errors.friendly_error.executor_k8s import ( local_engine_not_accept_remote_jobs, ) from dbnd._core.parameter.parameter_builder import parameter from dbnd._core.task import config from dbnd._core.task_build.task_registry import build_...
0.529993
0.167832
import numpy as np import cirq import cirq.google as cg import cirq.google.common_serializers as cgc def test_foxtail_qubits(): expected_qubits = [] for i in range(0, 2): for j in range(0, 11): expected_qubits.append(cirq.GridQubit(i, j)) assert set(expected_qubits) == cirq.google.Fox...
cirq/google/devices/known_devices_test.py
import numpy as np import cirq import cirq.google as cg import cirq.google.common_serializers as cgc def test_foxtail_qubits(): expected_qubits = [] for i in range(0, 2): for j in range(0, 11): expected_qubits.append(cirq.GridQubit(i, j)) assert set(expected_qubits) == cirq.google.Fox...
0.509764
0.509825
import math import torch import torch.nn as nn import torch.nn.functional as F from utils.tools import get_mask_from_lengths class SpeakerEncoder(nn.Module): def __init__(self): super(SpeakerEncoder, self).__init__() self.frameencoder = NormalEncoder() self.dsencoder = DownsampleEncoder() ...
model/reference.py
import math import torch import torch.nn as nn import torch.nn.functional as F from utils.tools import get_mask_from_lengths class SpeakerEncoder(nn.Module): def __init__(self): super(SpeakerEncoder, self).__init__() self.frameencoder = NormalEncoder() self.dsencoder = DownsampleEncoder() ...
0.94248
0.437703
import hashlib import json import re from dateutil import parser from dojo.models import Finding class DawnScannerParser(object): def get_scan_types(self): return ["DawnScanner Scan"] def get_label_for_scan_types(self, scan_type): return scan_type # no custom label for now def get_de...
dojo/tools/dawnscanner/parser.py
import hashlib import json import re from dateutil import parser from dojo.models import Finding class DawnScannerParser(object): def get_scan_types(self): return ["DawnScanner Scan"] def get_label_for_scan_types(self, scan_type): return scan_type # no custom label for now def get_de...
0.232746
0.140013
import functools from json import loads as _loads from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipel...
test/azure/version-tolerant/Expected/AcceptanceTests/PagingVersionTolerant/pagingversiontolerant/operations/_operations.py
import functools from json import loads as _loads from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error, ) from azure.core.paging import ItemPaged from azure.core.pipel...
0.67971
0.067454
import tensorflow as tf import tensorflow_probability as tfp import tree import numpy as np from numbers import Number from .base_policy import ContinuousPolicy, BasePolicy class UniformPolicyMixin: @tf.function(experimental_relax_shapes=True) def actions(self, observations): first_observation = tre...
softlearning/policies/uniform_policy.py
import tensorflow as tf import tensorflow_probability as tfp import tree import numpy as np from numbers import Number from .base_policy import ContinuousPolicy, BasePolicy class UniformPolicyMixin: @tf.function(experimental_relax_shapes=True) def actions(self, observations): first_observation = tre...
0.883097
0.449513
# Copyright 2019 <NAME> (Nagoya University) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) # NETWORK & TRAINING PARAMETERS INITIALIZATION class network_parameter(object): def __init__(self, upsampling_flag=True, spk_code_flag=False, quantize=256, aux=39, resch=512, s...
src/utils/param_model.py
# Copyright 2019 <NAME> (Nagoya University) # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) # NETWORK & TRAINING PARAMETERS INITIALIZATION class network_parameter(object): def __init__(self, upsampling_flag=True, spk_code_flag=False, quantize=256, aux=39, resch=512, s...
0.718693
0.148695
import re import sys import time import yaml from kubernetes import client, config, watch def get_expected_labels_regexs(): with open("./expected-output.txt") as f: expected_labels = f.readlines() return [re.compile(label.strip()) for label in expected_labels] def deploy_yaml_file(core_api, a...
tests/e2e-tests.py
import re import sys import time import yaml from kubernetes import client, config, watch def get_expected_labels_regexs(): with open("./expected-output.txt") as f: expected_labels = f.readlines() return [re.compile(label.strip()) for label in expected_labels] def deploy_yaml_file(core_api, a...
0.289975
0.295243
import os import re import subprocess import sys import threading import time import c_misc import c_path from c_logging import logger def run_command(cmd, expected_retcode=0, large_output=False, log=True): if log: logger.debug('Running command: ' + str(cmd)) if large_output: try: ...
QCA4020_SDK/target/sectools/qdn/sectools/common/utils/c_process.py
import os import re import subprocess import sys import threading import time import c_misc import c_path from c_logging import logger def run_command(cmd, expected_retcode=0, large_output=False, log=True): if log: logger.debug('Running command: ' + str(cmd)) if large_output: try: ...
0.452294
0.096877
import numpy as np import matplotlib.pyplot as plt from matplotlib.sankey import Sankey fig = plt.figure(figsize=(8, 12)) ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Rankine Power Cycle: Example 8.6 from Moran and Shapiro\n" + "\x22Fundamentals of Enginee...
examples/api/sankey_demo_rankine.py
import numpy as np import matplotlib.pyplot as plt from matplotlib.sankey import Sankey fig = plt.figure(figsize=(8, 12)) ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[], title="Rankine Power Cycle: Example 8.6 from Moran and Shapiro\n" + "\x22Fundamentals of Enginee...
0.582372
0.619443
import requests import json import sys import random class ReddeApi: receive_url = "https://api.reddeonline.com/v1/receive" cashout_url = "https://api.reddeonline.com/v1/cashout" def __init__(self, api_key, app_id): self.apikey = api_key self.appid = app_id """Generate a number of...
reddeApi/redde.py
import requests import json import sys import random class ReddeApi: receive_url = "https://api.reddeonline.com/v1/receive" cashout_url = "https://api.reddeonline.com/v1/cashout" def __init__(self, api_key, app_id): self.apikey = api_key self.appid = app_id """Generate a number of...
0.150809
0.097048
from web.controllers.api import route_api from flask import request,jsonify,g from common.models.food.FoodCat import FoodCat from common.models.food.Food import Food from common.models.member.MemberCart import MemberCart from common.models.member.MemberComments import MemberComments from common.models.member.Member im...
web/controllers/api/Food.py
from web.controllers.api import route_api from flask import request,jsonify,g from common.models.food.FoodCat import FoodCat from common.models.food.Food import Food from common.models.member.MemberCart import MemberCart from common.models.member.MemberComments import MemberComments from common.models.member.Member im...
0.220846
0.113309
import asyncio import datetime import os import sys from typing import Any from pydantic.fields import Field from pydantic.main import BaseModel from blacksmith import ( AsyncClientFactory, AsyncHTTPAuthorizationMiddleware, AsyncStaticDiscovery, PathInfoField, QueryStringField, Request, Re...
examples/gandi_domain.py
import asyncio import datetime import os import sys from typing import Any from pydantic.fields import Field from pydantic.main import BaseModel from blacksmith import ( AsyncClientFactory, AsyncHTTPAuthorizationMiddleware, AsyncStaticDiscovery, PathInfoField, QueryStringField, Request, Re...
0.452052
0.128963
from django.conf import settings from django.db import models, transaction from django.db.models import Sum from django.utils import timezone from rest_framework.exceptions import ParseError, PermissionDenied from lego.apps.content.models import Content from lego.apps.polls.permissions import PollPermissionHandler fro...
lego/apps/polls/models.py
from django.conf import settings from django.db import models, transaction from django.db.models import Sum from django.utils import timezone from rest_framework.exceptions import ParseError, PermissionDenied from lego.apps.content.models import Content from lego.apps.polls.permissions import PollPermissionHandler fro...
0.701815
0.083591
import nltk nltk.download('punkt') import pickle from collections import Counter import configparser import pandas as pd import os import json config = configparser.ConfigParser() config.read('config.ini') class Vocabulary(object): """Simple vocabulary wrapper.""" def __init__(self): self.word2idx = {...
tutorials/03-advanced/image_captioning/build_vocab.py
import nltk nltk.download('punkt') import pickle from collections import Counter import configparser import pandas as pd import os import json config = configparser.ConfigParser() config.read('config.ini') class Vocabulary(object): """Simple vocabulary wrapper.""" def __init__(self): self.word2idx = {...
0.623606
0.110904
from typing import Optional import pytest from pants.build_graph.address import Address, AddressInput, InvalidSpecPath, InvalidTargetName def assert_address_input_parsed( spec: str, *, path_component: str, target_component: Optional[str], relative_to: Optional[str] = None ) -> None: ai = Ad...
src/python/pants/build_graph/address_test.py
from typing import Optional import pytest from pants.build_graph.address import Address, AddressInput, InvalidSpecPath, InvalidTargetName def assert_address_input_parsed( spec: str, *, path_component: str, target_component: Optional[str], relative_to: Optional[str] = None ) -> None: ai = Ad...
0.886562
0.594993
import signal import sys import consul from multiprocessing.managers import SyncManager import pickle sys.path.append('./gen-py') from GenericServerPi import GenericPiThriftService from GenericStruct.ttypes import ActionEnum from ThriftException.ttypes import ThriftServiceException from ThriftException.ttypes import...
PhonePi/src/PythonPhonePiServer.py
import signal import sys import consul from multiprocessing.managers import SyncManager import pickle sys.path.append('./gen-py') from GenericServerPi import GenericPiThriftService from GenericStruct.ttypes import ActionEnum from ThriftException.ttypes import ThriftServiceException from ThriftException.ttypes import...
0.200714
0.038939
import ckan.lib.helpers as h import ckan.logic as l import ckan.model as model import ckan.lib.create_test_data as create_test_data import ckan.tests.functional.base as base import ckan.plugins as plugins import ckan.tests.mock_plugin as mock import ckan.lib.dictization.model_dictize as model_dictize class MockResou...
ckan/tests/functional/test_preview_interface.py
import ckan.lib.helpers as h import ckan.logic as l import ckan.model as model import ckan.lib.create_test_data as create_test_data import ckan.tests.functional.base as base import ckan.plugins as plugins import ckan.tests.mock_plugin as mock import ckan.lib.dictization.model_dictize as model_dictize class MockResou...
0.622115
0.284741
from neutron_lib import exceptions as n_exc from oslo_log import log as logging from oslo_utils import excutils from vmware_nsx._i18n import _ from vmware_nsx.db import db as nsx_db from vmware_nsx.services.lbaas import base_mgr from vmware_nsx.services.lbaas import lb_const from vmware_nsx.services.lbaas.nsx_v3.impl...
vmware_nsx/services/lbaas/nsx_v3/implementation/healthmonitor_mgr.py
from neutron_lib import exceptions as n_exc from oslo_log import log as logging from oslo_utils import excutils from vmware_nsx._i18n import _ from vmware_nsx.db import db as nsx_db from vmware_nsx.services.lbaas import base_mgr from vmware_nsx.services.lbaas import lb_const from vmware_nsx.services.lbaas.nsx_v3.impl...
0.311113
0.063802
from cmd import cmd import difflib import gzip import zlib import aiohttp @cmd.new() async def tio(snd, ctx, piped, args): r''' whatis: 'executes the given code using tio.run api' man: usage: '{name} [lang] [code] {{input}}' props: - PIPED [code] description: > ...
cmds/tio.py
from cmd import cmd import difflib import gzip import zlib import aiohttp @cmd.new() async def tio(snd, ctx, piped, args): r''' whatis: 'executes the given code using tio.run api' man: usage: '{name} [lang] [code] {{input}}' props: - PIPED [code] description: > ...
0.383988
0.243575
from typing import AsyncGenerator from unittest.mock import patch import pytest from pywizlight import SCENES, PilotBuilder, wizlight from pywizlight.bulb import states_match from pywizlight.bulblibrary import BulbClass, BulbType, Features, KelvinRange from pywizlight.discovery import discover_lights from pywizlight....
pywizlight/tests/test_bulb.py
from typing import AsyncGenerator from unittest.mock import patch import pytest from pywizlight import SCENES, PilotBuilder, wizlight from pywizlight.bulb import states_match from pywizlight.bulblibrary import BulbClass, BulbType, Features, KelvinRange from pywizlight.discovery import discover_lights from pywizlight....
0.906691
0.639525
"""Shared resource arguments and flags.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.calliope.concepts import concepts from googlecloudsdk.command_lib.secrets import completers as s...
lib/googlecloudsdk/command_lib/secrets/args.py
"""Shared resource arguments and flags.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope import arg_parsers from googlecloudsdk.calliope.concepts import concepts from googlecloudsdk.command_lib.secrets import completers as s...
0.78535
0.072341
import pytest class TestReclosers13Bus: @pytest.fixture(autouse=True) def _request(self, solve_snap_13bus): self.dss = solve_snap_13bus self.dss.text(r"New 'Recloser.cb1' MonitoredObj=Line.650632 " r"MonitoredTerm=1 " r"NumFast=4 " ...
tests/py_dss_interface/test_reclosers.py
import pytest class TestReclosers13Bus: @pytest.fixture(autouse=True) def _request(self, solve_snap_13bus): self.dss = solve_snap_13bus self.dss.text(r"New 'Recloser.cb1' MonitoredObj=Line.650632 " r"MonitoredTerm=1 " r"NumFast=4 " ...
0.639511
0.49231
from AutoHotPy import AutoHotPy from InterceptionWrapper import * import time def exitAutoHotKey(autohotpy,event): autohotpy.stop() def recorded_macro(autohotpy, event): start = time.time() autohotpy.moveMouseToPosition(241,388) autohotpy.sleep(0.0) stroke = InterceptionMouseStroke() stroke.stat...
frontend/assets/backup/AutoHotPy-master/red.py
from AutoHotPy import AutoHotPy from InterceptionWrapper import * import time def exitAutoHotKey(autohotpy,event): autohotpy.stop() def recorded_macro(autohotpy, event): start = time.time() autohotpy.moveMouseToPosition(241,388) autohotpy.sleep(0.0) stroke = InterceptionMouseStroke() stroke.stat...
0.281406
0.125923
from mapa import Map import math import random def find_corner(mapa): for x in range(mapa.hor_tiles): for y in range(mapa.ver_tiles): if not mapa.is_blocked((x, y)): return (x, y) # para qualquer posicao retorna um lista de possoveis movimentos def get_possible_ways2(mapa, pos...
defs2.py
from mapa import Map import math import random def find_corner(mapa): for x in range(mapa.hor_tiles): for y in range(mapa.ver_tiles): if not mapa.is_blocked((x, y)): return (x, y) # para qualquer posicao retorna um lista de possoveis movimentos def get_possible_ways2(mapa, pos...
0.234319
0.485356
from __future__ import absolute_import from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'cloudbuild' class AddBitbucketServerConnectedRepositoryRequest(_messages.Message): r"""RPC request object accepted by the ...
lib/googlecloudsdk/third_party/apis/cloudbuild/v1/cloudbuild_v1_messages.py
from __future__ import absolute_import from apitools.base.protorpclite import messages as _messages from apitools.base.py import encoding from apitools.base.py import extra_types package = 'cloudbuild' class AddBitbucketServerConnectedRepositoryRequest(_messages.Message): r"""RPC request object accepted by the ...
0.841988
0.160332
import re import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.error, urllib.parse from core.parser import Parser from core.display import Display, ProgressBar class Gather(): def __init__(self, domain, display=None): self.domain = domain self.display = display s...
spf/core/gather.py
import re import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.error, urllib.parse from core.parser import Parser from core.display import Display, ProgressBar class Gather(): def __init__(self, domain, display=None): self.domain = domain self.display = display s...
0.381335
0.087175
import os, sys from lxml.etree import Element, ElementTree class XmlBase (object): nsmap = { 'ds': 'http://schema.programmfabrik.de/database-schema/0.1', 'es': 'http://schema.programmfabrik.de/easydb-database-schema/0.1', 'em': 'http://schema.programmfabrik.de/easydb-mask-schema/0.1', ...
tools/analyze-mask.py
import os, sys from lxml.etree import Element, ElementTree class XmlBase (object): nsmap = { 'ds': 'http://schema.programmfabrik.de/database-schema/0.1', 'es': 'http://schema.programmfabrik.de/easydb-database-schema/0.1', 'em': 'http://schema.programmfabrik.de/easydb-mask-schema/0.1', ...
0.308398
0.116462
# $Id$ # Copyright (c) 2004 <NAME> # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retai...
head/crypto/heimdal/lib/wind/gen-errorlist.py
# $Id$ # Copyright (c) 2004 <NAME> # (Royal Institute of Technology, Stockholm, Sweden). # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retai...
0.289874
0.044827
import discord from discord.ext import commands from discord.ext.commands import has_permissions, BucketType, cooldown from datetime import datetime, timedelta import asyncio import json import pymongo class Moderation(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(aliases=['m']) @comm...
cogs/moderation.py
import discord from discord.ext import commands from discord.ext.commands import has_permissions, BucketType, cooldown from datetime import datetime, timedelta import asyncio import json import pymongo class Moderation(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(aliases=['m']) @comm...
0.121191
0.059183
from collections.abc import Sequence import urwid import blinker import textwrap import pprint from typing import Optional from mitmproxy import exceptions from mitmproxy import optmanager from mitmproxy.tools.console import layoutwidget from mitmproxy.tools.console import signals from mitmproxy.tools.console import ...
mitmproxy/tools/console/options.py
from collections.abc import Sequence import urwid import blinker import textwrap import pprint from typing import Optional from mitmproxy import exceptions from mitmproxy import optmanager from mitmproxy.tools.console import layoutwidget from mitmproxy.tools.console import signals from mitmproxy.tools.console import ...
0.721547
0.138841
# Emulate Python 3 style unicode string literals. from __future__ import unicode_literals __author__ = '<EMAIL> (<NAME>)' import icu from . import abstract_translator # To allow the rest of the file to assume Python 3 strings, we will assign str # to unicode for Python 2. This will error in 3 and be ignored. try: ...
python/simple_translator.py
# Emulate Python 3 style unicode string literals. from __future__ import unicode_literals __author__ = '<EMAIL> (<NAME>)' import icu from . import abstract_translator # To allow the rest of the file to assume Python 3 strings, we will assign str # to unicode for Python 2. This will error in 3 and be ignored. try: ...
0.831417
0.384739
import re import os import json import glob import logging from time import sleep from ulauncher.api.shared.action.CopyToClipboardAction import CopyToClipboardAction from ulauncher.search.SortedList import SortedList from ulauncher.utils.SortedCollection import SortedCollection from ulauncher.api.client.Extension impor...
main.py
import re import os import json import glob import logging from time import sleep from ulauncher.api.shared.action.CopyToClipboardAction import CopyToClipboardAction from ulauncher.search.SortedList import SortedList from ulauncher.utils.SortedCollection import SortedCollection from ulauncher.api.client.Extension impor...
0.399109
0.069226
import io from datetime import datetime from enum import IntEnum, auto from pathlib import Path from typing import Union import pptx from PIL import Image from pptx.presentation import Presentation TEMPLATE = Path(__file__).parents[2] / "resources" / "./template.pptx" class SlideMaster(IntEnum): Title = 0 I...
src/sbs/powerpoint.py
import io from datetime import datetime from enum import IntEnum, auto from pathlib import Path from typing import Union import pptx from PIL import Image from pptx.presentation import Presentation TEMPLATE = Path(__file__).parents[2] / "resources" / "./template.pptx" class SlideMaster(IntEnum): Title = 0 I...
0.817647
0.287068
import socket import logging import click import kazoo import websocket as ws_client from treadmill import cli from treadmill import context from treadmill import admin from treadmill import restclient from treadmill import zknamespace as z _LOGGER = logging.getLogger(__name__) def check(func, message): """C...
treadmill/cli/admin/ok.py
import socket import logging import click import kazoo import websocket as ws_client from treadmill import cli from treadmill import context from treadmill import admin from treadmill import restclient from treadmill import zknamespace as z _LOGGER = logging.getLogger(__name__) def check(func, message): """C...
0.475605
0.070144
from mmcv import Config from .base import BaseArgConverter from ..registry import ARG_CONVERTERS @ARG_CONVERTERS.register_module() class MMDetectionArgsConverter(BaseArgConverter): # NB: compress_update_args_map is the same as train_update_args_map, # but without base_learning_rate and epochs # TODO(...
pytorch_toolkit/ote/ote/modules/arg_converters/mmdetection.py
from mmcv import Config from .base import BaseArgConverter from ..registry import ARG_CONVERTERS @ARG_CONVERTERS.register_module() class MMDetectionArgsConverter(BaseArgConverter): # NB: compress_update_args_map is the same as train_update_args_map, # but without base_learning_rate and epochs # TODO(...
0.272411
0.214331
from __future__ import print_function import numpy as np import six import os import inspect from paddle.fluid.layer_helper import LayerHelper __all__ = ['fused_elemwise_activation', ] def fused_elemwise_activation(x, y, functor_list, ...
python/paddle/fluid/contrib/layers/nn.py
from __future__ import print_function import numpy as np import six import os import inspect from paddle.fluid.layer_helper import LayerHelper __all__ = ['fused_elemwise_activation', ] def fused_elemwise_activation(x, y, functor_list, ...
0.877214
0.248888
import os from .base_video_dataset import BaseVideoDataset from lib.train.data import jpeg4py_loader import xml.etree.ElementTree as ET import json import torch from collections import OrderedDict from lib.train.admin import env_settings def get_target_to_image_ratio(seq): anno = torch.Tensor(seq['anno']) img...
lib/train/dataset/imagenetvid.py
import os from .base_video_dataset import BaseVideoDataset from lib.train.data import jpeg4py_loader import xml.etree.ElementTree as ET import json import torch from collections import OrderedDict from lib.train.admin import env_settings def get_target_to_image_ratio(seq): anno = torch.Tensor(seq['anno']) img...
0.622
0.302926
import random import uuid import unicodedata import ctypes import math import fdb import fdb.tuple from bindingtester import util from bindingtester import FDB_API_VERSION from bindingtester.known_testers import COMMON_TYPES class RandomGenerator(object): def __init__(self, max_int_bits=64, api_version=FDB_API...
bindings/bindingtester/tests/test_util.py
import random import uuid import unicodedata import ctypes import math import fdb import fdb.tuple from bindingtester import util from bindingtester import FDB_API_VERSION from bindingtester.known_testers import COMMON_TYPES class RandomGenerator(object): def __init__(self, max_int_bits=64, api_version=FDB_API...
0.41941
0.207014
from functools import partial import numpy as np from unittest import TestCase from datumaro.components.project import Dataset from datumaro.components.extractor import ( DatasetItem, AnnotationType, Label, Mask, Points, Polygon, PolyLine, Bbox, Caption, LabelCategories, Mas...
tests/test_datumaro_format.py
from functools import partial import numpy as np from unittest import TestCase from datumaro.components.project import Dataset from datumaro.components.extractor import ( DatasetItem, AnnotationType, Label, Mask, Points, Polygon, PolyLine, Bbox, Caption, LabelCategories, Mas...
0.669529
0.3341
from __future__ import unicode_literals import frappe, json from frappe import _ from frappe.model.document import Document from frappe.model.rename_doc import rename_doc class Medication(Document): def validate(self): self.enable_disable_item() def after_insert(self): create_item_from_medication(self) def o...
hms_tz/hms_tz/doctype/medication/medication.py
from __future__ import unicode_literals import frappe, json from frappe import _ from frappe.model.document import Document from frappe.model.rename_doc import rename_doc class Medication(Document): def validate(self): self.enable_disable_item() def after_insert(self): create_item_from_medication(self) def o...
0.329392
0.126893
import mysql.connector from django.shortcuts import render from plotly.offline import plot import plotly.graph_objects as go from .models import Ping, Report # Create your views here. def home(request): return render(request, 'home.html', {'section': 'home'}) def report(request): reports...
nosairis/nosairis/switches/views.py
import mysql.connector from django.shortcuts import render from plotly.offline import plot import plotly.graph_objects as go from .models import Ping, Report # Create your views here. def home(request): return render(request, 'home.html', {'section': 'home'}) def report(request): reports...
0.417746
0.118513
import SimulateTrade from utils import ensure_dir_exist, archive_dir_folders import pandas as pd import time import os import zipfile import datetime import sys DEST_DIR = ".\\FilteredCSVs" if __name__ == '__main__': src_dir = SimulateTrade.SOURCE_DIR archive_results = False if len(sys.argv) > 1: ...
NormalizeData/FilterCSVs.py
import SimulateTrade from utils import ensure_dir_exist, archive_dir_folders import pandas as pd import time import os import zipfile import datetime import sys DEST_DIR = ".\\FilteredCSVs" if __name__ == '__main__': src_dir = SimulateTrade.SOURCE_DIR archive_results = False if len(sys.argv) > 1: ...
0.149469
0.09645
from constants import CMD_CHAT, CMD_LIST_USERS, CMD_QUIT, SERVER_NAME, SERVER_PORT import sys import socket import threading import select as s from datetime import datetime import pickle from message import Message HOST = '' # Entradas para escuta do select entry_points = [sys.stdin] # Mapa de conexoes com o servid...
server.py
from constants import CMD_CHAT, CMD_LIST_USERS, CMD_QUIT, SERVER_NAME, SERVER_PORT import sys import socket import threading import select as s from datetime import datetime import pickle from message import Message HOST = '' # Entradas para escuta do select entry_points = [sys.stdin] # Mapa de conexoes com o servid...
0.220175
0.095814
import argparse import glob import multiprocessing import re from functools import partial from pathlib import Path import librosa import numpy from become_yukarin import SuperResolution from become_yukarin.config.sr_config import create_from_json as create_config from become_yukarin.dataset.dataset import AcousticFe...
scripts/super_resolution_test.py
import argparse import glob import multiprocessing import re from functools import partial from pathlib import Path import librosa import numpy from become_yukarin import SuperResolution from become_yukarin.config.sr_config import create_from_json as create_config from become_yukarin.dataset.dataset import AcousticFe...
0.331877
0.09645
import numpy as np import os from soundfile import SoundFile from scipy.interpolate import interp1d import partitura TWO_PI = 2 * np.pi SAMPLE_RATE = 44100 A4 = 440 DTYPE = float def midinote2freq(midi_pitch, a4=A4): return (a4 / 32) * (2 ** ((midi_pitch - 9) / 12)) def freq2midinote(freq, a4=A4): pitch ...
Tonnetz/synthesize_midi.py
import numpy as np import os from soundfile import SoundFile from scipy.interpolate import interp1d import partitura TWO_PI = 2 * np.pi SAMPLE_RATE = 44100 A4 = 440 DTYPE = float def midinote2freq(midi_pitch, a4=A4): return (a4 / 32) * (2 ** ((midi_pitch - 9) / 12)) def freq2midinote(freq, a4=A4): pitch ...
0.803714
0.474327
from __future__ import print_function, unicode_literals, absolute_import from collections import OrderedDict from atomic_reactor.plugin import PreBuildPluginsRunner, PluginFailedException from atomic_reactor.plugins.pre_add_labels_in_df import AddLabelsPlugin from atomic_reactor.plugins.pre_reactor_config import (Reac...
tests/plugins/test_add_labels.py
from __future__ import print_function, unicode_literals, absolute_import from collections import OrderedDict from atomic_reactor.plugin import PreBuildPluginsRunner, PluginFailedException from atomic_reactor.plugins.pre_add_labels_in_df import AddLabelsPlugin from atomic_reactor.plugins.pre_reactor_config import (Reac...
0.606265
0.136033
import time import numpy as np import numba from sklearn.utils.validation import check_is_fitted import scipy.sparse @numba.njit(parallel=True) def fast_knn_indices(X, n_neighbors): """A fast computation of knn indices. Parameters ---------- X: array of shape (n_samples, n_features) The inp...
umap/utils.py
import time import numpy as np import numba from sklearn.utils.validation import check_is_fitted import scipy.sparse @numba.njit(parallel=True) def fast_knn_indices(X, n_neighbors): """A fast computation of knn indices. Parameters ---------- X: array of shape (n_samples, n_features) The inp...
0.907622
0.799129
import math from typing import List, Tuple, Optional from rgtk.constraint_solver import ConstraintSolver, Evaluator, Move from rgtk.Interval import Interval from rgtk.BitSet import BitSet class IntervalsToBitSetsEvaluator(Evaluator): # Static Vars # Larger intervals will get a better score. SCOR...
rgtk/IntervalsToBitSetsEvaluator.py
import math from typing import List, Tuple, Optional from rgtk.constraint_solver import ConstraintSolver, Evaluator, Move from rgtk.Interval import Interval from rgtk.BitSet import BitSet class IntervalsToBitSetsEvaluator(Evaluator): # Static Vars # Larger intervals will get a better score. SCOR...
0.809088
0.355327
import re import uuid from ast import literal_eval from collections import defaultdict from typing import ( Any, Dict, Generator, Iterator, List, NamedTuple, Optional, Pattern, Set, Tuple, Union, ) from urllib.parse import urlencode, urlunsplit from sortedcontainers import SortedListWithKey from .exceptions impor...
quart/routing.py
import re import uuid from ast import literal_eval from collections import defaultdict from typing import ( Any, Dict, Generator, Iterator, List, NamedTuple, Optional, Pattern, Set, Tuple, Union, ) from urllib.parse import urlencode, urlunsplit from sortedcontainers import SortedListWithKey from .exceptions impor...
0.770637
0.155751
from django.contrib.auth import views as auth_views from django.urls import include, path, reverse_lazy from .views import ( AccountView, ActivationView, LoginView, become, create_password, oauth, ) app_name = 'users' public_urlpatterns = [ path( 'login/', LoginView.as_vi...
hypha/apply/users/urls.py
from django.contrib.auth import views as auth_views from django.urls import include, path, reverse_lazy from .views import ( AccountView, ActivationView, LoginView, become, create_password, oauth, ) app_name = 'users' public_urlpatterns = [ path( 'login/', LoginView.as_vi...
0.334372
0.094218
import asyncio import logging from typing import Any, Dict, List, Optional, Tuple, Type, Union from uuid import UUID import aiohttp from aiohttp import ClientTimeout, web from models_library.projects import ProjectID from models_library.projects_pipeline import ComputationTask from models_library.settings.services_com...
services/web/server/src/simcore_service_webserver/director_v2_core.py
import asyncio import logging from typing import Any, Dict, List, Optional, Tuple, Type, Union from uuid import UUID import aiohttp from aiohttp import ClientTimeout, web from models_library.projects import ProjectID from models_library.projects_pipeline import ComputationTask from models_library.settings.services_com...
0.721743
0.119305
import re import sys import textwrap import time import xml.etree.ElementTree as ET from urllib.parse import urlparse import requests from django.utils.translation import ugettext_lazy as _ from orchestra.contrib.orchestration import ServiceController from orchestra.contrib.resources import ServiceMonitor from . imp...
orchestra/contrib/saas/backends/owncloud.py
import re import sys import textwrap import time import xml.etree.ElementTree as ET from urllib.parse import urlparse import requests from django.utils.translation import ugettext_lazy as _ from orchestra.contrib.orchestration import ServiceController from orchestra.contrib.resources import ServiceMonitor from . imp...
0.162081
0.063657
from __future__ import annotations from coredis._utils import CaseAndEncodingInsensitiveEnum class PureToken(CaseAndEncodingInsensitiveEnum): """ Enum for using pure-tokens with the redis api. """ #: Used by: #: #: - ``ACL LOG`` RESET = b"RESET" #: Used by: #: #: - ``BGSAV...
coredis/tokens.py
from __future__ import annotations from coredis._utils import CaseAndEncodingInsensitiveEnum class PureToken(CaseAndEncodingInsensitiveEnum): """ Enum for using pure-tokens with the redis api. """ #: Used by: #: #: - ``ACL LOG`` RESET = b"RESET" #: Used by: #: #: - ``BGSAV...
0.629775
0.057467
import sys import os import vtk import numpy from siconos.io.mechanics_io import Hdf5 ## the best way to dump all data # $ h5dump toto.hdf5 > toto.txt import h5py import getopt def usage(): """ {0} <hdf5 file> """.format(sys.argv[0]) print '{0}: Usage'.format(sys.argv[0]) print """ {0} [--...
examples/Mechanics/ContactDetection/BulletIO/filter_output_frequency.py
import sys import os import vtk import numpy from siconos.io.mechanics_io import Hdf5 ## the best way to dump all data # $ h5dump toto.hdf5 > toto.txt import h5py import getopt def usage(): """ {0} <hdf5 file> """.format(sys.argv[0]) print '{0}: Usage'.format(sys.argv[0]) print """ {0} [--...
0.045131
0.167185
import numpy as np import vispy.app from vispy import gloo from vispy import visuals from vispy.visuals.transforms import (AffineTransform, STTransform, arg_to_array, TransformSystem, LogTransform, PolarTransform, ...
examples/basics/visuals/image_transforms.py
import numpy as np import vispy.app from vispy import gloo from vispy import visuals from vispy.visuals.transforms import (AffineTransform, STTransform, arg_to_array, TransformSystem, LogTransform, PolarTransform, ...
0.603348
0.605507
# pylint: disable=import-error, no-member, too-many-arguments, no-self-use import torch import torch.nn as nn import regular_nd_grid_interpolation as rgi def query_local_implicit_grid(model, latent_grid, query_pts, xmin, xmax): """Function for querying local implicit grid. The latent feature grid can be of...
src/local_implicit_grid.py
# pylint: disable=import-error, no-member, too-many-arguments, no-self-use import torch import torch.nn as nn import regular_nd_grid_interpolation as rgi def query_local_implicit_grid(model, latent_grid, query_pts, xmin, xmax): """Function for querying local implicit grid. The latent feature grid can be of...
0.941345
0.699627
from dataclasses import dataclass from typing import Optional from aioredis import Redis from fastapi import Depends, Request from httpx import AsyncClient from safir.dependencies.http_client import http_client_dependency from safir.dependencies.logger import logger_dependency from sqlalchemy.ext.asyncio import AsyncS...
src/gafaelfawr/dependencies/context.py
from dataclasses import dataclass from typing import Optional from aioredis import Redis from fastapi import Depends, Request from httpx import AsyncClient from safir.dependencies.http_client import http_client_dependency from safir.dependencies.logger import logger_dependency from sqlalchemy.ext.asyncio import AsyncS...
0.913497
0.159971
from __util import util class RequestPacket(util.struct): mapcls_context = util.mapclass(util.string, util.string) mapcls_status = util.mapclass(util.string, util.string) def __init__(self): self.iVersion = 0 self.cPacketType = 0 self.iMessageType = 0 self.iRequestId = 0...
tup-python/tars/__packet.py
from __util import util class RequestPacket(util.struct): mapcls_context = util.mapclass(util.string, util.string) mapcls_status = util.mapclass(util.string, util.string) def __init__(self): self.iVersion = 0 self.cPacketType = 0 self.iMessageType = 0 self.iRequestId = 0...
0.538983
0.1679
import os import re import subprocess from setuptools import find_packages, setup from setuptools.command.develop import develop from setuptools.command.install import install from setuptools.command.test import test __author__ = '<NAME>' __copyright__ = 'Copyright (c) 2018, Pawelzny' with open('README.rst', 'r') as...
setup.py
import os import re import subprocess from setuptools import find_packages, setup from setuptools.command.develop import develop from setuptools.command.install import install from setuptools.command.test import test __author__ = '<NAME>' __copyright__ = 'Copyright (c) 2018, Pawelzny' with open('README.rst', 'r') as...
0.506103
0.104843
import os import multiprocessing import re import datetime import tempfile import numpy as np from collections import Counter from tokenizers import BertWordPieceTokenizer omitted_strings = ["<media omitted>", "messages to this chat and calls are now secured with end-to-end encryption. tap for more info.", "you delete...
src/whatsapp_parser.py
import os import multiprocessing import re import datetime import tempfile import numpy as np from collections import Counter from tokenizers import BertWordPieceTokenizer omitted_strings = ["<media omitted>", "messages to this chat and calls are now secured with end-to-end encryption. tap for more info.", "you delete...
0.264738
0.10942
import time import smbus from Adafruit_I2C import Adafruit_I2C # =========================================================================== # INA219 Class # =========================================================================== class INA219: i2c = None # ======================================================...
Subfact_ina219.py
import time import smbus from Adafruit_I2C import Adafruit_I2C # =========================================================================== # INA219 Class # =========================================================================== class INA219: i2c = None # ======================================================...
0.273769
0.087408
from __future__ import absolute_import from time import strptime, mktime from datetime import datetime import fnmatch import os from astropy.units import Unit, nm, equivalencies from sqlalchemy import Column, Integer, Float, String, DateTime, Boolean,\ Table, ForeignKey from sqlalchemy.orm import relationship fr...
sunpy/database/tables.py
from __future__ import absolute_import from time import strptime, mktime from datetime import datetime import fnmatch import os from astropy.units import Unit, nm, equivalencies from sqlalchemy import Column, Integer, Float, String, DateTime, Boolean,\ Table, ForeignKey from sqlalchemy.orm import relationship fr...
0.657428
0.216094
import unittest from unittest.mock import MagicMock, call from qtt.instrument_drivers.virtualAwg.awgs.ZurichInstrumentsHDAWG8 import ZurichInstrumentsHDAWG8 from qtt.instrument_drivers.virtualAwg.awgs.common import AwgCommonError class TestZurichInstrumentsHDAWG8(unittest.TestCase): def setUp(self): clas...
qtt/tests/test_zi_hdawg8.py
import unittest from unittest.mock import MagicMock, call from qtt.instrument_drivers.virtualAwg.awgs.ZurichInstrumentsHDAWG8 import ZurichInstrumentsHDAWG8 from qtt.instrument_drivers.virtualAwg.awgs.common import AwgCommonError class TestZurichInstrumentsHDAWG8(unittest.TestCase): def setUp(self): clas...
0.690663
0.439687
import uuid import os from cloudify_rest_client.exceptions import CloudifyClientError from integration_tests import AgentlessTestCase from integration_tests.tests.utils import get_resource as resource from integration_tests.tests.utils import ( verify_deployment_env_created, wait_for_deployment_deletion_to_c...
tests/integration_tests/tests/agentless_tests/test_deployment_workflows.py
import uuid import os from cloudify_rest_client.exceptions import CloudifyClientError from integration_tests import AgentlessTestCase from integration_tests.tests.utils import get_resource as resource from integration_tests.tests.utils import ( verify_deployment_env_created, wait_for_deployment_deletion_to_c...
0.428592
0.296107
import unittest from fabric_cf.actor.core.common.constants import Constants from fabric_cf.actor.core.kernel.kernel_tick import KernelTick class TickTest(unittest.TestCase): from fabric_cf.actor.core.container.globals import Globals Globals.config_file = "./config/config.test.yaml" Constants.SUPERBLOCK_L...
fabric_cf/actor/test/core/kernel/tick_test.py
import unittest from fabric_cf.actor.core.common.constants import Constants from fabric_cf.actor.core.kernel.kernel_tick import KernelTick class TickTest(unittest.TestCase): from fabric_cf.actor.core.container.globals import Globals Globals.config_file = "./config/config.test.yaml" Constants.SUPERBLOCK_L...
0.52902
0.543166
"""Tests for combinator layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import absltest from trax.backend import numpy as np from trax.layers import base from trax.layers import combinators as cb from trax.layers import core fro...
trax/layers/combinators_test.py
"""Tests for combinator layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import absltest from trax.backend import numpy as np from trax.layers import base from trax.layers import combinators as cb from trax.layers import core fro...
0.866669
0.583619
from copy import deepcopy from datetime import datetime, date from json import load as json_in_str from os.path import isfile, exists, join as path_join from random import choice from string import digits, ascii_letters from typing import Any, Type, Union from unittest import TestCase from marshmallow import Schema fr...
ms_tools/flask/test_case/nosql.py
from copy import deepcopy from datetime import datetime, date from json import load as json_in_str from os.path import isfile, exists, join as path_join from random import choice from string import digits, ascii_letters from typing import Any, Type, Union from unittest import TestCase from marshmallow import Schema fr...
0.668231
0.130535
import re from django.utils.translation import gettext as _ import publications.six as six from publications.models import CustomLink, CustomFile, Publication, Type from publisher.models import Publisher # mapping of months MONTHS = { 'jan': 1, 'january': 1, 'feb': 2, 'february': 2, 'mar': 3, 'march': 3, 'apr': ...
publications/utils.py
import re from django.utils.translation import gettext as _ import publications.six as six from publications.models import CustomLink, CustomFile, Publication, Type from publisher.models import Publisher # mapping of months MONTHS = { 'jan': 1, 'january': 1, 'feb': 2, 'february': 2, 'mar': 3, 'march': 3, 'apr': ...
0.213705
0.108472
import contextlib import os import threading from textwrap import dedent import unittest import time from test import support from test.support import import_helper _interpreters = import_helper.import_module('_xxsubinterpreters') from test.support import interpreters def _captured_script(script): r, w = os.pipe...
Lib/test/test_interpreters.py
import contextlib import os import threading from textwrap import dedent import unittest import time from test import support from test.support import import_helper _interpreters = import_helper.import_module('_xxsubinterpreters') from test.support import interpreters def _captured_script(script): r, w = os.pipe...
0.425605
0.241093
from __future__ import annotations import zipfile import tarfile import typing as T from pathlib import Path import tempfile try: import zstandard except ImportError: zstandard = None # type: ignore Pathlike = T.Union[str, Path] def extract_zst(archive: Pathlike, out_path: Pathlike): """extract .zst fi...
src/gemini3d/archive.py
from __future__ import annotations import zipfile import tarfile import typing as T from pathlib import Path import tempfile try: import zstandard except ImportError: zstandard = None # type: ignore Pathlike = T.Union[str, Path] def extract_zst(archive: Pathlike, out_path: Pathlike): """extract .zst fi...
0.645008
0.235724
import os import json import requests import urllib.parse import concurrent.futures as thread import urllib3 import getopt import sys import re r = '\033[1;31m' g = '\033[1;32m' y = '\033[1;33m' b = '\033[1;34m' r_ = '\033[0;31m' g_ = '\033[0;32m' y_ = '\033[0;33m' b_ = '\033[0;34m' e = '\033[0m' global _output _ou...
takeover.py
import os import json import requests import urllib.parse import concurrent.futures as thread import urllib3 import getopt import sys import re r = '\033[1;31m' g = '\033[1;32m' y = '\033[1;33m' b = '\033[1;34m' r_ = '\033[0;31m' g_ = '\033[0;32m' y_ = '\033[0;33m' b_ = '\033[0;34m' e = '\033[0m' global _output _ou...
0.233969
0.102394
import os import unittest from copy import deepcopy from typing import Dict import pytorch_lightning as pl # type: ignore import torch from d2go.config import CfgNode, temp_defrost from d2go.runner import create_runner from d2go.runner.callbacks.quantization import ( QuantizationAwareTraining, ) from d2go.runne...
tests/runner/test_runner_lightning_task.py
import os import unittest from copy import deepcopy from typing import Dict import pytorch_lightning as pl # type: ignore import torch from d2go.config import CfgNode, temp_defrost from d2go.runner import create_runner from d2go.runner.callbacks.quantization import ( QuantizationAwareTraining, ) from d2go.runne...
0.698535
0.392395
from rest_framework import status from mayan.apps.documents.permissions import permission_document_type_view from mayan.apps.documents.tests.mixins import DocumentTestMixin from mayan.apps.rest_api.tests.base import BaseAPITestCase from ..models import Workflow from ..permissions import ( permission_workflow_crea...
mayan/apps/document_states/tests/test_api.py
from rest_framework import status from mayan.apps.documents.permissions import permission_document_type_view from mayan.apps.documents.tests.mixins import DocumentTestMixin from mayan.apps.rest_api.tests.base import BaseAPITestCase from ..models import Workflow from ..permissions import ( permission_workflow_crea...
0.580709
0.343094
import os from os.path import join, dirname import sys from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.exc import IntegrityError import environs import logging import json import lib.uti...
cid-minting/local_cid_minter.py
import os from os.path import join, dirname import sys from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.exc import IntegrityError import environs import logging import json import lib.uti...
0.277179
0.148232
from openpyxl import load_workbook import re filename = 'aalh_iit_jeep_001.xlsx' wb = load_workbook(filename) ws = wb['Metadata Template'] minimumcol = 31 maximumcol = 31 minimumrow = 7 maximumrow = 394 iterationrow = 7 targetcol = 31 for row in ws.iter_rows(min_row=minimumrow, min_col=minimumcol, ma...
aalh_iit_jeep_001/debug-convert-dates.py
from openpyxl import load_workbook import re filename = 'aalh_iit_jeep_001.xlsx' wb = load_workbook(filename) ws = wb['Metadata Template'] minimumcol = 31 maximumcol = 31 minimumrow = 7 maximumrow = 394 iterationrow = 7 targetcol = 31 for row in ws.iter_rows(min_row=minimumrow, min_col=minimumcol, ma...
0.10566
0.15772
import os import sys import mock import pathlib import pytest import six @pytest.mark.parametrize("nproc", [1]) def test_ccp4_scalerA(regression_test, ccp4, dials_data, run_in_tmpdir, nproc): if nproc is not None: from xia2.Handlers.Phil import PhilIndex PhilIndex.params.xia2.settings.multiproce...
Test/Modules/Scaler/test_CCP4ScalerA.py
import os import sys import mock import pathlib import pytest import six @pytest.mark.parametrize("nproc", [1]) def test_ccp4_scalerA(regression_test, ccp4, dials_data, run_in_tmpdir, nproc): if nproc is not None: from xia2.Handlers.Phil import PhilIndex PhilIndex.params.xia2.settings.multiproce...
0.195902
0.346486
import os from instaloader import Instaloader class Config: API_ID = int(os.environ.get("API_ID", "")) API_HASH = os.environ.get("API_HASH", "") BOT_TOKEN = os.environ.get("BOT_TOKEN", "") USER = os.environ.get("INSTAGRAM_USERNAME", "") OWNER = os.environ.get("OWNER_ID", "") INSTA_SESSIONFILE_I...
config.py
import os from instaloader import Instaloader class Config: API_ID = int(os.environ.get("API_ID", "")) API_HASH = os.environ.get("API_HASH", "") BOT_TOKEN = os.environ.get("BOT_TOKEN", "") USER = os.environ.get("INSTAGRAM_USERNAME", "") OWNER = os.environ.get("OWNER_ID", "") INSTA_SESSIONFILE_I...
0.357007
0.205555
import pytest import stk import os from os.path import join import logging import sys from collections import Counter, defaultdict from .fixtures import * logging.basicConfig( format='\n\n%(levelname)s:%(module)s:%(message)s', stream=sys.stdout ) logging.getLogger('stk').setLevel(logging.DEBUG) # Run tests...
tests/conftest.py
import pytest import stk import os from os.path import join import logging import sys from collections import Counter, defaultdict from .fixtures import * logging.basicConfig( format='\n\n%(levelname)s:%(module)s:%(message)s', stream=sys.stdout ) logging.getLogger('stk').setLevel(logging.DEBUG) # Run tests...
0.314998
0.127029
import unittest from datafinder.core.configuration.icons import icon from datafinder.core.error import ConfigurationError from datafinder.persistence.error import PersistenceError from datafinder_test.mocks import SimpleMock __version__ = "$Revision-Id:$" class IconTestCase(unittest.TestCase): """...
test/unittest/datafinder_test/core/configuration/icons/icon_test.py
import unittest from datafinder.core.configuration.icons import icon from datafinder.core.error import ConfigurationError from datafinder.persistence.error import PersistenceError from datafinder_test.mocks import SimpleMock __version__ = "$Revision-Id:$" class IconTestCase(unittest.TestCase): """...
0.586286
0.314037
"""Tests for Kubeflow V2 step builder.""" from typing import Any, Dict from kfp.pipeline_spec import pipeline_spec_pb2 as pipeline_pb2 import tensorflow as tf from tfx import components from tfx.dsl.components.common import importer from tfx.dsl.components.common import resolver from tfx.dsl.experimental import lates...
tfx/orchestration/kubeflow/v2/step_builder_test.py
"""Tests for Kubeflow V2 step builder.""" from typing import Any, Dict from kfp.pipeline_spec import pipeline_spec_pb2 as pipeline_pb2 import tensorflow as tf from tfx import components from tfx.dsl.components.common import importer from tfx.dsl.components.common import resolver from tfx.dsl.experimental import lates...
0.865948
0.458712
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: oci_database_database_actions short_description: Perform actions on a Database reso...
plugins/modules/oci_database_database_actions.py
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { "metadata_version": "1.1", "status": ["preview"], "supported_by": "community", } DOCUMENTATION = """ --- module: oci_database_database_actions short_description: Perform actions on a Database reso...
0.865039
0.332812
import pytest import sklearn.decomposition import sklearn.linear_model from numpy.testing import assert_array_equal from sklearn import datasets from sklearn.model_selection import GridSearchCV, StratifiedKFold from sklearn.pipeline import Pipeline from baikal import Model, Input from baikal.sklearn import SKLearnWrap...
tests/test_sklearn_wrapper.py
import pytest import sklearn.decomposition import sklearn.linear_model from numpy.testing import assert_array_equal from sklearn import datasets from sklearn.model_selection import GridSearchCV, StratifiedKFold from sklearn.pipeline import Pipeline from baikal import Model, Input from baikal.sklearn import SKLearnWrap...
0.869632
0.604632
import collections import tensorflow as tf def load_data(filename, sep=' ', sep1=',', isCharacter=False): label_list = [] features_list = [] with tf.gfile.GFile(filename, 'r') as f: for line in f.readlines(): fields = line.strip().split(sep) if len(fields) != 2: ...
feng-ml-tf/src/data_helper.py
import collections import tensorflow as tf def load_data(filename, sep=' ', sep1=',', isCharacter=False): label_list = [] features_list = [] with tf.gfile.GFile(filename, 'r') as f: for line in f.readlines(): fields = line.strip().split(sep) if len(fields) != 2: ...
0.354321
0.299293
from __future__ import absolute_import from __future__ import unicode_literals from builtins import zip from builtins import object from curation.tasks import update_instance, bulk_change_tracking_state, bulk_prepend_record_history, save_creation_to_citation from django import forms from django.http import QueryDict ...
isiscb/curation/actions.py
from __future__ import absolute_import from __future__ import unicode_literals from builtins import zip from builtins import object from curation.tasks import update_instance, bulk_change_tracking_state, bulk_prepend_record_history, save_creation_to_citation from django import forms from django.http import QueryDict ...
0.327561
0.139133
from django.db import connection, transaction from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.reverse import reverse from rest_framework.settings import api_settings from rest_framework_recursive.fields import RecursiveField from mayan.apps.documents....
mayan/apps/cabinets/serializers.py
from django.db import connection, transaction from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.reverse import reverse from rest_framework.settings import api_settings from rest_framework_recursive.fields import RecursiveField from mayan.apps.documents....
0.687
0.108001
import sys print("Running tests with Python: {}".format(sys.version)) import scalopus import time import os import unittest import threading try: from thread import get_ident as thread_ident except ImportError: from threading import get_ident as thread_ident # This is the same as test_tracing, except that i...
scalopus_python/test/test_tracing_exposer.py
import sys print("Running tests with Python: {}".format(sys.version)) import scalopus import time import os import unittest import threading try: from thread import get_ident as thread_ident except ImportError: from threading import get_ident as thread_ident # This is the same as test_tracing, except that i...
0.340595
0.217452