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
question_conf = { 'Name' : 'Exercise 11', 'Questions' : { 'Question 1': {'Total Points': 40}, } } import argparse import datetime import sys def parse_args(): parser = argparse.ArgumentParser() for i in range(1, len(question_conf['Questions'])+1, 1): pa...
HPCI/exercises/ex11/grade.py
question_conf = { 'Name' : 'Exercise 11', 'Questions' : { 'Question 1': {'Total Points': 40}, } } import argparse import datetime import sys def parse_args(): parser = argparse.ArgumentParser() for i in range(1, len(question_conf['Questions'])+1, 1): pa...
0.285571
0.241121
import numpy as np import pandas as pd import argparse import logging from datetime import date, timedelta import matplotlib.pyplot as plt from dx import * def visualize(port, n_stock, n=500): # Monte Carlo simulation of portfolio compositions rets = [] vols = [] for w in range(n): weights...
examples/portfolio.py
import numpy as np import pandas as pd import argparse import logging from datetime import date, timedelta import matplotlib.pyplot as plt from dx import * def visualize(port, n_stock, n=500): # Monte Carlo simulation of portfolio compositions rets = [] vols = [] for w in range(n): weights...
0.450601
0.28738
import os import sys import json from uuid import uuid4 import boto3 import botocore.exceptions import requests from requests_http_signature import HTTPSignatureAuth import unittest from unittest import mock import datetime import typing from copy import deepcopy import importlib pkg_root = os.path.abspath(os.path.jo...
tests/test_notify_v2.py
import os import sys import json from uuid import uuid4 import boto3 import botocore.exceptions import requests from requests_http_signature import HTTPSignatureAuth import unittest from unittest import mock import datetime import typing from copy import deepcopy import importlib pkg_root = os.path.abspath(os.path.jo...
0.38445
0.108236
import os from glob import glob from configparser import ConfigParser from collections.abc import Sequence def save_dir(save_prefix): return str(os.path.split(save_prefix)[0]) def is_seq(x): return isinstance(x, Sequence) and not isinstance(x, str) def glob_most_recent(path): paths = glob(path) if le...
train/files.py
import os from glob import glob from configparser import ConfigParser from collections.abc import Sequence def save_dir(save_prefix): return str(os.path.split(save_prefix)[0]) def is_seq(x): return isinstance(x, Sequence) and not isinstance(x, str) def glob_most_recent(path): paths = glob(path) if le...
0.363647
0.140867
from .todos import models from .todos import views from freezegun import freeze_time import pytest pytestmark = pytest.mark.django_db def test_list(arf): todo1 = create_todo('todo1') todo2 = create_todo('todo2') todo3 = create_todo('todo3') request = arf.get('') response = views.todo_list(reque...
tests/test_view_filtering.py
from .todos import models from .todos import views from freezegun import freeze_time import pytest pytestmark = pytest.mark.django_db def test_list(arf): todo1 = create_todo('todo1') todo2 = create_todo('todo2') todo3 = create_todo('todo3') request = arf.get('') response = views.todo_list(reque...
0.364325
0.545165
from typing import TYPE_CHECKING, Any from dis_snek.const import MISSING, Absent from dis_snek.models.route import Route from dis_snek.utils.serializer import dict_filter_missing if TYPE_CHECKING: from dis_snek.models.snowflake import Snowflake_Type class ReactionRequests: request: Any async def create...
dis_snek/http_requests/reactions.py
from typing import TYPE_CHECKING, Any from dis_snek.const import MISSING, Absent from dis_snek.models.route import Route from dis_snek.utils.serializer import dict_filter_missing if TYPE_CHECKING: from dis_snek.models.snowflake import Snowflake_Type class ReactionRequests: request: Any async def create...
0.883958
0.140749
from __future__ import absolute_import import sys from datetime import datetime from xml.etree.ElementTree import Element, SubElement, tostring from xml.sax.saxutils import escape from .helpers import datetime_to_api_timezone from .constants import (AUTOTASK_API_QUERY_ID_LIMIT, AUTOTASK_API_QUER...
atws/query.py
from __future__ import absolute_import import sys from datetime import datetime from xml.etree.ElementTree import Element, SubElement, tostring from xml.sax.saxutils import escape from .helpers import datetime_to_api_timezone from .constants import (AUTOTASK_API_QUERY_ID_LIMIT, AUTOTASK_API_QUER...
0.397588
0.113309
from errors.errors import ExecutorError class Executor: """ Basic class for Executor classes """ def __init__(self, input_data, ssc=None): """ Create Executor and set initial data for executor :param input_data: Data of RDD or Dstream class """ self._data = in...
input/executors.py
from errors.errors import ExecutorError class Executor: """ Basic class for Executor classes """ def __init__(self, input_data, ssc=None): """ Create Executor and set initial data for executor :param input_data: Data of RDD or Dstream class """ self._data = in...
0.853088
0.624265
#---------------------------------------------------------------------- # Beginning Of PIECTRL wxPython Code #---------------------------------------------------------------------- import wx from math import pi, sin, cos #---------------------------------------------------------------------- # Class PieCtrlLegend #...
app/external/agw/piectrl.py
#---------------------------------------------------------------------- # Beginning Of PIECTRL wxPython Code #---------------------------------------------------------------------- import wx from math import pi, sin, cos #---------------------------------------------------------------------- # Class PieCtrlLegend #...
0.776453
0.358241
import time from tornado.escape import json_encode, json_decode from tornado.testing import gen_test from toshieth.app import urls from toshi.test.base import AsyncHandlerTest from toshi.test.database import requires_database from toshi.request import sign_request from toshi.ethereum.utils import data_decoder from to...
toshieth/test/test_pn_registration.py
import time from tornado.escape import json_encode, json_decode from tornado.testing import gen_test from toshieth.app import urls from toshi.test.base import AsyncHandlerTest from toshi.test.database import requires_database from toshi.request import sign_request from toshi.ethereum.utils import data_decoder from to...
0.508788
0.26656
import services, sims4.resources from server_commands.argument_helpers import OptionalSimInfoParam, get_optional_target, TunableInstanceParam from sims4.resources import Types from spells.spellbook import SpellbookHelper @sims4.commands.Command('spells.generate_spell_book', command_type=(sims4.commands.CommandType.Liv...
Scripts/simulation/spells/spell_commands.py
import services, sims4.resources from server_commands.argument_helpers import OptionalSimInfoParam, get_optional_target, TunableInstanceParam from sims4.resources import Types from spells.spellbook import SpellbookHelper @sims4.commands.Command('spells.generate_spell_book', command_type=(sims4.commands.CommandType.Liv...
0.523908
0.144752
import unittest from datetime import datetime from datetime import timedelta from unittest import TestCase from configparser import ConfigParser from td.client import TDClient from td.stream import TDStreamerClient class TDSession(TestCase): """Will perform a unit test for the TD session.""" def setUp(self)...
tests/unit/test_stream.py
import unittest from datetime import datetime from datetime import timedelta from unittest import TestCase from configparser import ConfigParser from td.client import TDClient from td.stream import TDStreamerClient class TDSession(TestCase): """Will perform a unit test for the TD session.""" def setUp(self)...
0.708313
0.389024
# -*- coding: utf-8 -*- import os import sys import time import tempfile import shutil from pycompss.util.process.manager import new_process from pycompss.util.exceptions import PyCOMPSsException from pycompss.util.serialization.serializer import deserialize_from_file from pycompss.api.task import task if sys.versi...
compss/programming_model/bindings/python/src/pycompss/tests/worker/common_piper_tester.py
# -*- coding: utf-8 -*- import os import sys import time import tempfile import shutil from pycompss.util.process.manager import new_process from pycompss.util.exceptions import PyCOMPSsException from pycompss.util.serialization.serializer import deserialize_from_file from pycompss.api.task import task if sys.versi...
0.195825
0.14814
import os import service_configuration_lib import yaml try: from yaml.cyaml import CSafeDumper as Dumper except ImportError: # pragma: no cover (no libyaml-dev / pypy) Dumper = yaml.SafeDumper from paasta_tools.tron.client import TronClient from paasta_tools.utils import DEFAULT_SOA_DIR from paasta_tools.uti...
paasta_tools/tron_tools.py
import os import service_configuration_lib import yaml try: from yaml.cyaml import CSafeDumper as Dumper except ImportError: # pragma: no cover (no libyaml-dev / pypy) Dumper = yaml.SafeDumper from paasta_tools.tron.client import TronClient from paasta_tools.utils import DEFAULT_SOA_DIR from paasta_tools.uti...
0.58166
0.103341
from .. import ChargingNetwork from .. current import Current from ...models.evse import get_evse_by_type def caltech_acn(basic_evse=False, voltage=208, transformer_cap=150, network_type=ChargingNetwork): """ Predefined ChargingNetwork for the Caltech ACN. Args: basic_evse (bool): If True use BASIC E...
acnportal/acnsim/network/sites/caltech_acn.py
from .. import ChargingNetwork from .. current import Current from ...models.evse import get_evse_by_type def caltech_acn(basic_evse=False, voltage=208, transformer_cap=150, network_type=ChargingNetwork): """ Predefined ChargingNetwork for the Caltech ACN. Args: basic_evse (bool): If True use BASIC E...
0.813646
0.247351
from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from PooledEffect import PooledEffect from EffectController import EffectController import random class ShockwaveHit(PooledEffect, EffectController): __module__ = __name__ def __init__(self): PooledEffect.__init__(self) ...
pirates/effects/ShockwaveHit.py
from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from PooledEffect import PooledEffect from EffectController import EffectController import random class ShockwaveHit(PooledEffect, EffectController): __module__ = __name__ def __init__(self): PooledEffect.__init__(self) ...
0.603231
0.136148
from argparse import ArgumentParser, Namespace import attr from pathlib import Path import sys import typing from kgtk.kgtkformat import KgtkFormat from kgtk.io.kgtkreader import KgtkReader, KgtkReaderOptions from kgtk.io.kgtkwriter import KgtkWriter from kgtk.utils.argparsehelpers import optional_bool from kgtk.value...
kgtk/iff/kgtkifexists.py
from argparse import ArgumentParser, Namespace import attr from pathlib import Path import sys import typing from kgtk.kgtkformat import KgtkFormat from kgtk.io.kgtkreader import KgtkReader, KgtkReaderOptions from kgtk.io.kgtkwriter import KgtkWriter from kgtk.utils.argparsehelpers import optional_bool from kgtk.value...
0.336331
0.148726
import sys import time sys.path.append('/home/root/ArduCAM_USB_Camera_Shield/RaspberryPi/Python/Streaming_demo') from ImageConvert import * import arducam_config_parser import ArducamSDK import globals from datetime import datetime import logging import faulthandler import cProfile, pstats faulthandler.enable() profi...
ardu_camera.py
import sys import time sys.path.append('/home/root/ArduCAM_USB_Camera_Shield/RaspberryPi/Python/Streaming_demo') from ImageConvert import * import arducam_config_parser import ArducamSDK import globals from datetime import datetime import logging import faulthandler import cProfile, pstats faulthandler.enable() profi...
0.149904
0.162081
import argparse import os import subprocess import sys import zipfile import requests SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) DUMP_SYMS = os.path.join(os.path.dirname(SCRIPT_DIR), "miscDeps", "tools", "dump_syms.exe") NVDA_SOURCE = os.path.join(os.path.dirname(SCRIPT_DIR), "source") NVDA_LIB ...
appveyor/mozillaSyms.py
import argparse import os import subprocess import sys import zipfile import requests SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) DUMP_SYMS = os.path.join(os.path.dirname(SCRIPT_DIR), "miscDeps", "tools", "dump_syms.exe") NVDA_SOURCE = os.path.join(os.path.dirname(SCRIPT_DIR), "source") NVDA_LIB ...
0.100591
0.051678
import cv2 import os from cut_twist_process import cut_part from cut_twist_process import twist_part def preprecess_cut_twist_one_img(img_path, img_name, template_list, save_path, norm_parm): """ 函数用于处理单张原始图片,切分处身份证正反面并旋转,然后写入到指定目录。 :param img_path: 图片所在路径 :param img_name: 图片名 :param template_list...
cut_twist_process/cut_twist_join.py
import cv2 import os from cut_twist_process import cut_part from cut_twist_process import twist_part def preprecess_cut_twist_one_img(img_path, img_name, template_list, save_path, norm_parm): """ 函数用于处理单张原始图片,切分处身份证正反面并旋转,然后写入到指定目录。 :param img_path: 图片所在路径 :param img_name: 图片名 :param template_list...
0.100713
0.189953
import os import uuid from concurrent.futures import ThreadPoolExecutor from functools import wraps from json import JSONDecodeError from time import time import requests from flask import current_app, request from werkzeug.exceptions import InternalServerError, HTTPException from meerkat_consul import logger def ...
meerkat_consul/decorators.py
import os import uuid from concurrent.futures import ThreadPoolExecutor from functools import wraps from json import JSONDecodeError from time import time import requests from flask import current_app, request from werkzeug.exceptions import InternalServerError, HTTPException from meerkat_consul import logger def ...
0.461745
0.123762
import os import pytest import yaml import shutil from util import update_dict from user_sync.config import ConfigFileLoader, ConfigLoader, DictConfig from user_sync import app from user_sync.error import AssertionException def load_ldap_config_options(args): from user_sync.connector.directory import DirectoryCon...
tests/test_config.py
import os import pytest import yaml import shutil from util import update_dict from user_sync.config import ConfigFileLoader, ConfigLoader, DictConfig from user_sync import app from user_sync.error import AssertionException def load_ldap_config_options(args): from user_sync.connector.directory import DirectoryCon...
0.284079
0.115013
from __future__ import division import mmtbx.model import libtbx.load_env import iotbx.pdb import time from libtbx.utils import null_out pdb_str_1 = """ CRYST1 79.110 79.110 37.465 90.00 90.00 90.00 P 43 21 2 ATOM 1 N GLY A 67 11.351 9.426 29.699 1.00 16.57 A N ATOM 2 CA GLY A...
mmtbx/regression/model/tst_model_2.py
from __future__ import division import mmtbx.model import libtbx.load_env import iotbx.pdb import time from libtbx.utils import null_out pdb_str_1 = """ CRYST1 79.110 79.110 37.465 90.00 90.00 90.00 P 43 21 2 ATOM 1 N GLY A 67 11.351 9.426 29.699 1.00 16.57 A N ATOM 2 CA GLY A...
0.285372
0.098903
import pprint import re # noqa: F401 import six class BaasClientVendorDataVO(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name ...
integration/python/integration_api/models/baas_client_vendor_data_vo.py
import pprint import re # noqa: F401 import six class BaasClientVendorDataVO(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name ...
0.556641
0.080105
import errno import os from importlib import import_module from django.apps import apps from django.conf import settings from django.core.management.base import ( CommandError, no_translations, ) from django.db import DEFAULT_DB_ALIAS, connections from django.db.migrations.executor import MigrationExecutor f...
vb_baseapp/management/commands/create_custom_user_model.py
import errno import os from importlib import import_module from django.apps import apps from django.conf import settings from django.core.management.base import ( CommandError, no_translations, ) from django.db import DEFAULT_DB_ALIAS, connections from django.db.migrations.executor import MigrationExecutor f...
0.31321
0.055209
from networking_brocade._i18n import _ from oslo_log import log as logging from oslo_utils import importutils CONNECTION_FACTORY = ("networking_brocade.mlx.ml2.connector_factory." "ConnectorFactory") INVALID_INPUT = "Invalid input" RANGE_ERROR = "outside of allowed max" ERROR = "Error" DUPLICATE_...
networking_brocade/mlx/ml2/fi_ni/fi_ni_driver.py
from networking_brocade._i18n import _ from oslo_log import log as logging from oslo_utils import importutils CONNECTION_FACTORY = ("networking_brocade.mlx.ml2.connector_factory." "ConnectorFactory") INVALID_INPUT = "Invalid input" RANGE_ERROR = "outside of allowed max" ERROR = "Error" DUPLICATE_...
0.643553
0.119691
import struct import numpy as np import os import subprocess class LAXParser: """ Parses a `.lax` file and generates point index intervals. :param path: The path of the input `.lax` file. """ def __init__(self, path): stream = open(path, 'rb') self.parsed_bytes = [] # TODO...
laxpy/file.py
import struct import numpy as np import os import subprocess class LAXParser: """ Parses a `.lax` file and generates point index intervals. :param path: The path of the input `.lax` file. """ def __init__(self, path): stream = open(path, 'rb') self.parsed_bytes = [] # TODO...
0.451568
0.452052
from datetime import datetime, timedelta from functools import partial from typing import Optional import sqlalchemy as sa from airflow import DAG from airflow.operators.python_operator import PythonOperator from dataflow import config from dataflow.dags import _PipelineDAG from dataflow.dags.base import PipelineMeta...
dataflow/dags/dun_and_bradstreet_pipelines.py
from datetime import datetime, timedelta from functools import partial from typing import Optional import sqlalchemy as sa from airflow import DAG from airflow.operators.python_operator import PythonOperator from dataflow import config from dataflow.dags import _PipelineDAG from dataflow.dags.base import PipelineMeta...
0.66356
0.171755
Copyright 2011-2014 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distri...
swiftly/client/localmemcache.py
Copyright 2011-2014 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distri...
0.821903
0.150372
import hetu as ht from hetu import init import numpy as np def layer_norm( input_tensor, feature_size, eps=1e-8 ): scale = init.ones(name='layer_norm_scale', shape=(feature_size, )) bias = init.zeros(name='layer_norm_biad', shape=(feature_size, )) return ht.layer_normalization_op(input_tensor,...
examples/nlp/hetu_transformer.py
import hetu as ht from hetu import init import numpy as np def layer_norm( input_tensor, feature_size, eps=1e-8 ): scale = init.ones(name='layer_norm_scale', shape=(feature_size, )) bias = init.zeros(name='layer_norm_biad', shape=(feature_size, )) return ht.layer_normalization_op(input_tensor,...
0.653901
0.467028
import boto3 import os import requests from settings import DEFAULT_REGION, KEYNAME session = boto3.session.Session(region_name=DEFAULT_REGION, profile_name=KEYNAME) def get_public_ip(instance_ids): ec2_client = session.client("ec2") reservations = ec2_client.describe_instances(InstanceIds=instance_ids).get(...
utils.py
import boto3 import os import requests from settings import DEFAULT_REGION, KEYNAME session = boto3.session.Session(region_name=DEFAULT_REGION, profile_name=KEYNAME) def get_public_ip(instance_ids): ec2_client = session.client("ec2") reservations = ec2_client.describe_instances(InstanceIds=instance_ids).get(...
0.306838
0.093058
import unittest from django.core.urlresolvers import reverse from django import test from .. import models from .. import views from .. import factories from tuticfruti_blog.core import data_fixtures class TestViewCommonMixin: view = None context_data_vars = None template_name = None def test_http_...
tuticfruti_blog/posts/tests/test_views.py
import unittest from django.core.urlresolvers import reverse from django import test from .. import models from .. import views from .. import factories from tuticfruti_blog.core import data_fixtures class TestViewCommonMixin: view = None context_data_vars = None template_name = None def test_http_...
0.495606
0.246783
from django.urls import reverse from django.contrib import admin from django.utils.html import format_html from openstates.data.admin.person import MembershipInline from .. import models from .base import ModelAdmin, ReadOnlyTabularInline class PostInline(admin.TabularInline): """a read-only inline for posts he...
openstates/data/admin/organization.py
from django.urls import reverse from django.contrib import admin from django.utils.html import format_html from openstates.data.admin.person import MembershipInline from .. import models from .base import ModelAdmin, ReadOnlyTabularInline class PostInline(admin.TabularInline): """a read-only inline for posts he...
0.5
0.135432
# ................................................................................................................. def KikiWireWall( c , p): if world.isUnoccupiedPos(KikiPos (p.x,p.y,p.z)): world.addObjectAtPos (KikiWall() , KikiPos (p.x,p.y,p.z)) world.addObjectAtPos (KikiWire (KikiFace.X, c ), KikiPos (p.x+...
py/levels/conductor.py
# ................................................................................................................. def KikiWireWall( c , p): if world.isUnoccupiedPos(KikiPos (p.x,p.y,p.z)): world.addObjectAtPos (KikiWall() , KikiPos (p.x,p.y,p.z)) world.addObjectAtPos (KikiWire (KikiFace.X, c ), KikiPos (p.x+...
0.14072
0.310289
from sympy.matrices.expressions.blockmatrix import ( block_collapse, bc_matmul, bc_block_plus_ident, BlockDiagMatrix, BlockMatrix, bc_dist, bc_matadd, bc_transpose, bc_inverse, blockcut, reblock_2x2, deblock) from sympy.matrices.expressions import (MatrixSymbol, Identity, Inverse, trace, Transpose, ...
sympy/matrices/expressions/tests/test_blockmatrix.py
from sympy.matrices.expressions.blockmatrix import ( block_collapse, bc_matmul, bc_block_plus_ident, BlockDiagMatrix, BlockMatrix, bc_dist, bc_matadd, bc_transpose, bc_inverse, blockcut, reblock_2x2, deblock) from sympy.matrices.expressions import (MatrixSymbol, Identity, Inverse, trace, Transpose, ...
0.84916
0.807916
import json from pydent.models import Sample from util.plans import ExternalPlan, PlanStep, Transformation, get_obj_by_attr from util.plasmid_assembly_legs import GibsonLeg, SangerSeqLeg, PCRLeg from util.plasmid_assembly_legs import YeastTransformationLeg, YeastGenotypingLeg class CloningPlan(ExternalPlan): """...
menagerie/util/cloning_plans.py
import json from pydent.models import Sample from util.plans import ExternalPlan, PlanStep, Transformation, get_obj_by_attr from util.plasmid_assembly_legs import GibsonLeg, SangerSeqLeg, PCRLeg from util.plasmid_assembly_legs import YeastTransformationLeg, YeastGenotypingLeg class CloningPlan(ExternalPlan): """...
0.685529
0.285192
import numpy as np class Norm_3D(object): def __init__(self, mean, cov): self.Ndim = len(mean) self.set_mean(mean) self.set_cov(cov) def set_mean(self, mean): self.mean = mean def set_cov(self, cov): self.cov = cov self.sigx2 = self.cov[0,0] self...
stat_funcs.py
import numpy as np class Norm_3D(object): def __init__(self, mean, cov): self.Ndim = len(mean) self.set_mean(mean) self.set_cov(cov) def set_mean(self, mean): self.mean = mean def set_cov(self, cov): self.cov = cov self.sigx2 = self.cov[0,0] self...
0.474144
0.353791
from __future__ import absolute_import from __future__ import division import collections import copy import logging import operator import pprint import six from guild import util log = logging.getLogger("guild") class ResourceFormatError(ValueError): pass class ResourceDefValueError(ValueError): pass ...
guild/resourcedef.py
from __future__ import absolute_import from __future__ import division import collections import copy import logging import operator import pprint import six from guild import util log = logging.getLogger("guild") class ResourceFormatError(ValueError): pass class ResourceDefValueError(ValueError): pass ...
0.548915
0.101991
import json import os import sys from contextlib import closing import boto3 import botocore import click from .base import BackendError, BaseBackend, validate_backend_empty class S3Backend(BaseBackend): tag = "s3" auth_tag = "aws" def __init__(self, authenticators, definitions, deployment=None): ...
tfworker/backends/s3.py
import json import os import sys from contextlib import closing import boto3 import botocore import click from .base import BackendError, BaseBackend, validate_backend_empty class S3Backend(BaseBackend): tag = "s3" auth_tag = "aws" def __init__(self, authenticators, definitions, deployment=None): ...
0.391173
0.095097
import torch import os.path as osp import cv2 import numpy as np import albumentations as A from typing import List, Optional from torch.utils.data.dataset import Dataset from retinal.utils import load_list class FGADRDataset(Dataset): """ Wrapper for FGADR datset """ def __init__(self, data_root: st...
retinal/data/fgadr_dataset.py
import torch import os.path as osp import cv2 import numpy as np import albumentations as A from typing import List, Optional from torch.utils.data.dataset import Dataset from retinal.utils import load_list class FGADRDataset(Dataset): """ Wrapper for FGADR datset """ def __init__(self, data_root: st...
0.830285
0.322153
from __future__ import unicode_literals from utils import CanadianScraper, CanadianPerson as Person import re COUNCIL_PAGE = 'http://www.lambtononline.ca/home/government/accessingcountycouncil/countycouncillors/Pages/default.aspx' class LambtonPersonScraper(CanadianScraper): def scrape(self): councillo...
ca_on_lambton/people.py
from __future__ import unicode_literals from utils import CanadianScraper, CanadianPerson as Person import re COUNCIL_PAGE = 'http://www.lambtononline.ca/home/government/accessingcountycouncil/countycouncillors/Pages/default.aspx' class LambtonPersonScraper(CanadianScraper): def scrape(self): councillo...
0.325199
0.112259
from app import db from datetime import datetime, date, time from sqlalchemy import func class Offer(db.Model): __tablename__ = "offer" id = db.Column(db.Integer(), primary_key=True) user_id = db.Column(db.Integer(), db.ForeignKey( "app_user.id"), nullable=False) event_id = db.Column(db.Int...
api/app/registration/models.py
from app import db from datetime import datetime, date, time from sqlalchemy import func class Offer(db.Model): __tablename__ = "offer" id = db.Column(db.Integer(), primary_key=True) user_id = db.Column(db.Integer(), db.ForeignKey( "app_user.id"), nullable=False) event_id = db.Column(db.Int...
0.612078
0.075927
from PyQt5 import QtCore, QtWidgets from configurator import Ui_configurator import generator as gen class ShipHolderApplication(QtWidgets.QMainWindow): def __init__(self, parent=None): super(ShipHolderApplication, self).__init__(parent) self.createWidgets() self.connectActions() s...
main.py
from PyQt5 import QtCore, QtWidgets from configurator import Ui_configurator import generator as gen class ShipHolderApplication(QtWidgets.QMainWindow): def __init__(self, parent=None): super(ShipHolderApplication, self).__init__(parent) self.createWidgets() self.connectActions() s...
0.18363
0.066478
import pdb from YTest.TestBase import TestBase from ObjXp import * import logging import json class ObexCallbackSrcTest(TestBase): def setUpCommon(self): EnableObjStats() SetTraceLevel(8) self._ioSvc = BasicIoService() self._cCb = CreateObject(objxp.DefaultConnectionCallback) ...
test/ObexCallbackSrcTest.py
import pdb from YTest.TestBase import TestBase from ObjXp import * import logging import json class ObexCallbackSrcTest(TestBase): def setUpCommon(self): EnableObjStats() SetTraceLevel(8) self._ioSvc = BasicIoService() self._cCb = CreateObject(objxp.DefaultConnectionCallback) ...
0.344554
0.155719
import logging import tempfile import numpy as np from joblib import Parallel, delayed, dump, load from dosna.backends import get_backend from dosna.engines import Engine from dosna.engines.base import EngineConnection, EngineDataChunk from dosna.engines.cpu import CpuDataset from six.moves import range log = loggin...
dosna/engines/jl.py
import logging import tempfile import numpy as np from joblib import Parallel, delayed, dump, load from dosna.backends import get_backend from dosna.engines import Engine from dosna.engines.base import EngineConnection, EngineDataChunk from dosna.engines.cpu import CpuDataset from six.moves import range log = loggin...
0.546496
0.170612
import inspect import logging import os import sys import re # FILE_LOG_LEVEL and CONSOLE_LOG_LEVEL # valid levels are: DEBUG, INFO, WARNING or ERROR # specifies the log level to file and console respectively # log to file logging.INFO and above file_log_level = logging.DEBUG # log to console logging.WARNING and above...
pkg-mirrors/AddPkgLogging.py
import inspect import logging import os import sys import re # FILE_LOG_LEVEL and CONSOLE_LOG_LEVEL # valid levels are: DEBUG, INFO, WARNING or ERROR # specifies the log level to file and console respectively # log to file logging.INFO and above file_log_level = logging.DEBUG # log to console logging.WARNING and above...
0.099039
0.050424
from __future__ import annotations from datetime import datetime from typing import Set, List, Union import pandas as pd from card_live_dashboard.model.RGIParser import RGIParser class CardLiveData: INSTANCE = None def __init__(self, main_df: pd.DataFrame, rgi_parser: RGIParser, rgi_kmer_df: pd.DataFrame,...
card_live_dashboard/model/CardLiveData.py
from __future__ import annotations from datetime import datetime from typing import Set, List, Union import pandas as pd from card_live_dashboard.model.RGIParser import RGIParser class CardLiveData: INSTANCE = None def __init__(self, main_df: pd.DataFrame, rgi_parser: RGIParser, rgi_kmer_df: pd.DataFrame,...
0.916278
0.44354
from haigha.writer import Writer from haigha.classes import ProtocolClass from haigha.frames import MethodFrame class ExchangeClass(ProtocolClass): ''' Implements the AMQP Exchange class ''' def __init__(self, *args, **kwargs): super(ExchangeClass, self).__init__(*args, **kwargs) self.dispatch_map = {...
haigha/classes/exchange_class.py
from haigha.writer import Writer from haigha.classes import ProtocolClass from haigha.frames import MethodFrame class ExchangeClass(ProtocolClass): ''' Implements the AMQP Exchange class ''' def __init__(self, *args, **kwargs): super(ExchangeClass, self).__init__(*args, **kwargs) self.dispatch_map = {...
0.395018
0.087955
from gevent import monkey monkey.patch_all() import os import sys import socket import subprocess import json import time import datetime import platform import select import gevent import ConfigParser import yaml from nodemgr.common.event_manager import EventManager from ConfigParser import NoOptionError from supe...
src/nodemgr/database_nodemgr/database_event_manager.py
from gevent import monkey monkey.patch_all() import os import sys import socket import subprocess import json import time import datetime import platform import select import gevent import ConfigParser import yaml from nodemgr.common.event_manager import EventManager from ConfigParser import NoOptionError from supe...
0.253676
0.064271
import gym import numpy as np import matplotlib.pyplot as plt from collections import defaultdict def generate_session(policy, t_max=10 ** 4): """ Play game until end or for t_max ticks. :param policy: an array of shape [n_states,n_actions] with action probabilities :returns: list of states, list of a...
Reinforcement learning/cross_entropy.py
import gym import numpy as np import matplotlib.pyplot as plt from collections import defaultdict def generate_session(policy, t_max=10 ** 4): """ Play game until end or for t_max ticks. :param policy: an array of shape [n_states,n_actions] with action probabilities :returns: list of states, list of a...
0.768429
0.707784
from contextlib import contextmanager import logging from flask import Flask from flask import render_template from flask import request from flask import json from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String, Float from sqlalchemy.ext.declarative import declarative_base from sqlalc...
paolo.py
from contextlib import contextmanager import logging from flask import Flask from flask import render_template from flask import request from flask import json from sqlalchemy import create_engine from sqlalchemy import Column, Integer, String, Float from sqlalchemy.ext.declarative import declarative_base from sqlalc...
0.2676
0.067793
import demistomock as demisto from CommonServerPython import * import urllib3 import traceback from typing import Dict, List # Disable insecure warnings urllib3.disable_warnings() ''' CONSTANTS ''' DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' BITCOIN = 'bitcoin' INTEGRATION_NAME = 'Cryptocurrency' SCORE = { 4: 'Critical'...
Packs/Cryptocurrency/Integrations/Cryptocurrency/Cryptocurrency.py
import demistomock as demisto from CommonServerPython import * import urllib3 import traceback from typing import Dict, List # Disable insecure warnings urllib3.disable_warnings() ''' CONSTANTS ''' DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' BITCOIN = 'bitcoin' INTEGRATION_NAME = 'Cryptocurrency' SCORE = { 4: 'Critical'...
0.635562
0.135232
from dataclasses import dataclass from functools import partial from typing import Any from typing import Callable from typing import NamedTuple from typing import Optional import jax import jax.lax as lax import jax.numpy as jnp from jaxopt.tree_util import tree_add_scalar_mul, tree_l2_norm from jaxopt.tree_util im...
jaxopt/_src/armijo_sgd.py
from dataclasses import dataclass from functools import partial from typing import Any from typing import Callable from typing import NamedTuple from typing import Optional import jax import jax.lax as lax import jax.numpy as jnp from jaxopt.tree_util import tree_add_scalar_mul, tree_l2_norm from jaxopt.tree_util im...
0.950296
0.488527
from pygame import Color, Surface, Vector3, surfarray, SRCALPHA, BLEND_RGBA_MULT from pygame.transform import scale as image_scale class Gradient: def __init__(self, vertical=False): self.vertical = vertical self.surface = None def apply_surface_blend(self, surface, special_flags=BLEND_RGBA_M...
gamelayer/graphics/gradient.py
from pygame import Color, Surface, Vector3, surfarray, SRCALPHA, BLEND_RGBA_MULT from pygame.transform import scale as image_scale class Gradient: def __init__(self, vertical=False): self.vertical = vertical self.surface = None def apply_surface_blend(self, surface, special_flags=BLEND_RGBA_M...
0.870996
0.528533
import json import os import pathlib from argparse import ArgumentParser from datetime import datetime import matplotlib.pyplot as plt import pytorch_lightning as pl import torch import wandb from fastmri.data.mri_data import fetch_dir from fastmri.data.transforms import MiniCoilTransform from fastmri.pl_modules impor...
fastmri_examples/adaptive_varnet/train_adaptive_varnet_demo.py
import json import os import pathlib from argparse import ArgumentParser from datetime import datetime import matplotlib.pyplot as plt import pytorch_lightning as pl import torch import wandb from fastmri.data.mri_data import fetch_dir from fastmri.data.transforms import MiniCoilTransform from fastmri.pl_modules impor...
0.428233
0.243125
from django.http import HttpResponse from django.shortcuts import render from .User import User, UserData from . import models from . import scraper import json def home(request): return render(request, "signup.html") def login(request): first_name = request.GET.get("FirstName") last_name = request.GET....
Randomizer/Randomizer/views.py
from django.http import HttpResponse from django.shortcuts import render from .User import User, UserData from . import models from . import scraper import json def home(request): return render(request, "signup.html") def login(request): first_name = request.GET.get("FirstName") last_name = request.GET....
0.334698
0.100172
import tensorflow as tf import tensorflow_probability as tfp # @tf.function # @tf.function(experimental_compile=True) def sample_chain(*args, **kwargs): """Since this is bulk of the computation, using @tf.function here to compile a static graph for tfp.mcmc.sample_chain significantly improves performance,...
src/hmc_utils.py
import tensorflow as tf import tensorflow_probability as tfp # @tf.function # @tf.function(experimental_compile=True) def sample_chain(*args, **kwargs): """Since this is bulk of the computation, using @tf.function here to compile a static graph for tfp.mcmc.sample_chain significantly improves performance,...
0.863722
0.451266
from ...ucsmo import ManagedObject from ...ucscoremeta import MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class AdaptorRssProfileConsts: RECEIVE_SIDE_SCALING_DISABLED = "disabled" RECEIVE_SIDE_SCALING_ENABLED = "enabled" class AdaptorRssProfile(ManagedObject): """This is AdaptorRssProfile...
ucsmsdk/mometa/adaptor/AdaptorRssProfile.py
from ...ucsmo import ManagedObject from ...ucscoremeta import MoPropertyMeta, MoMeta from ...ucsmeta import VersionMeta class AdaptorRssProfileConsts: RECEIVE_SIDE_SCALING_DISABLED = "disabled" RECEIVE_SIDE_SCALING_ENABLED = "enabled" class AdaptorRssProfile(ManagedObject): """This is AdaptorRssProfile...
0.504883
0.198122
import json from flask_login import login_required from service.broadcrawler_service import \ get_broadcrawl_results_summary, get_broadcrawl_results_summary_count_mongo_dao, pin_service from ui import app, Singleton from flask import Response, request from utils.json_encoder import JSONEncoder __author__ = 'tomas'...
ui/controller/broad_crawl_results_summary_handler.py
import json from flask_login import login_required from service.broadcrawler_service import \ get_broadcrawl_results_summary, get_broadcrawl_results_summary_count_mongo_dao, pin_service from ui import app, Singleton from flask import Response, request from utils.json_encoder import JSONEncoder __author__ = 'tomas'...
0.439507
0.105303
import paddle.fluid as fluid import paddle.fluid.dygraph.nn as nn import paddle.fluid.layers as L from utils import ConvModule, model_size from models.resnet import ResNet, BasicBlock, make_res_layer from models.triple_loss import TripletLoss class DeCoder(fluid.dygraph.Layer): def __init__(self, ...
models/scan.py
import paddle.fluid as fluid import paddle.fluid.dygraph.nn as nn import paddle.fluid.layers as L from utils import ConvModule, model_size from models.resnet import ResNet, BasicBlock, make_res_layer from models.triple_loss import TripletLoss class DeCoder(fluid.dygraph.Layer): def __init__(self, ...
0.879587
0.29923
import pygame as pg import numpy as np import os from pygame.color import THECOLORS def calculateIncludedAngle(vector1, vector2): includedAngle = abs(np.angle(complex(vector1[0], vector1[1]) / complex(vector2[0], vector2[1]))) return includedAngle def findQuadrant(vector): quadrant = 0 if vector[0] ...
src/visualization/visualization.py
import pygame as pg import numpy as np import os from pygame.color import THECOLORS def calculateIncludedAngle(vector1, vector2): includedAngle = abs(np.angle(complex(vector1[0], vector1[1]) / complex(vector2[0], vector2[1]))) return includedAngle def findQuadrant(vector): quadrant = 0 if vector[0] ...
0.630571
0.226356
from db import mydb, mycursor import json import sys import requests import numpy as np import pandas as pd def find_similar(title): sql_1 = '''SELECT id,plot FROM movie_data_2 WHERE title = "%s"''' % title mycursor.execute(sql_1) results_1 = mycursor.fetchone() string = [ "Plot is unknown", ...
python/find.py
from db import mydb, mycursor import json import sys import requests import numpy as np import pandas as pd def find_similar(title): sql_1 = '''SELECT id,plot FROM movie_data_2 WHERE title = "%s"''' % title mycursor.execute(sql_1) results_1 = mycursor.fetchone() string = [ "Plot is unknown", ...
0.17749
0.135861
import logging import os import subprocess from xml.etree import ElementTree log = logging.getLogger(__name__) class Tool(object): """ Base class for tools """ name = '' options = {} def __init__(self, problems, options=None, base_path=None): self.problems = problems self.bas...
lintreview/tools/__init__.py
import logging import os import subprocess from xml.etree import ElementTree log = logging.getLogger(__name__) class Tool(object): """ Base class for tools """ name = '' options = {} def __init__(self, problems, options=None, base_path=None): self.problems = problems self.bas...
0.577972
0.112162
import abc import pytest import py_vsys as pv from test.func_test import conftest as cft class TestNFTCtrt: """ TestNFTCtrt is the collection of functional tests of NFT contract. """ @pytest.fixture async def new_ctrt(self, acnt0: pv.Account) -> pv.NFTCtrt: """ new_ctrt is the f...
test/func_test/test_ctrt/test_nft_ctrt.py
import abc import pytest import py_vsys as pv from test.func_test import conftest as cft class TestNFTCtrt: """ TestNFTCtrt is the collection of functional tests of NFT contract. """ @pytest.fixture async def new_ctrt(self, acnt0: pv.Account) -> pv.NFTCtrt: """ new_ctrt is the f...
0.733738
0.4856
import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class Plan(pulumi.CustomResource): arn: pulumi.Output[str] """ The ARN of the backup plan. """ name: pulumi.Output[str] """ The display name of a backup plan. """ rules: p...
sdk/python/pulumi_aws/backup/plan.py
import warnings import pulumi import pulumi.runtime from typing import Union from .. import utilities, tables class Plan(pulumi.CustomResource): arn: pulumi.Output[str] """ The ARN of the backup plan. """ name: pulumi.Output[str] """ The display name of a backup plan. """ rules: p...
0.873889
0.465205
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed u...
code/Model/Train.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed u...
0.839537
0.117294
from os import chmod,remove from time import time from subprocess import Popen,PIPE def get_tables(family="ipv4"): ''' List iptables tables :param family: iptables ip family version. type: str ''' if family == "ipv4": cmd = 'iptables-save' elif family == "ipv6": cmd = 'ip6tables...
_modules/iptables_extra.py
from os import chmod,remove from time import time from subprocess import Popen,PIPE def get_tables(family="ipv4"): ''' List iptables tables :param family: iptables ip family version. type: str ''' if family == "ipv4": cmd = 'iptables-save' elif family == "ipv6": cmd = 'ip6tables...
0.309128
0.148201
import pathlib import typing as t import attr from phd_qmclib.qmc_exec import data as qmc_data, dmc as dmc_exec from phd_qmclib.util.attr import ( bool_validator, opt_str_validator, str_validator ) from .proc import Proc, ProcResult from .. import dmc IO_HANDLER_TYPES = ('HDF5_FILE',) IO_FILE_HANDLER_TYPES = ('H...
src/phd_qmclib/mrbp_qmc/dmc_exec/io.py
import pathlib import typing as t import attr from phd_qmclib.qmc_exec import data as qmc_data, dmc as dmc_exec from phd_qmclib.util.attr import ( bool_validator, opt_str_validator, str_validator ) from .proc import Proc, ProcResult from .. import dmc IO_HANDLER_TYPES = ('HDF5_FILE',) IO_FILE_HANDLER_TYPES = ('H...
0.682997
0.168207
from .grammar import QueryGrammar from ...utils import basestring class PostgresQueryGrammar(QueryGrammar): _operators = [ "=", "<", ">", "<=", ">=", "<>", "!=", "like", "not like", "between", "ilike", "&", "...
orator/query/grammars/postgres_grammar.py
from .grammar import QueryGrammar from ...utils import basestring class PostgresQueryGrammar(QueryGrammar): _operators = [ "=", "<", ">", "<=", ">=", "<>", "!=", "like", "not like", "between", "ilike", "&", "...
0.804214
0.414632
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [("hosts", "0001_initial")] operations = [ migrations.CreateModel( name="Challenge", fi...
apps/challenges/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [("hosts", "0001_initial")] operations = [ migrations.CreateModel( name="Challenge", fi...
0.651466
0.210401
import json import os import sqlite3 import tempfile import pandas import pytest from great_expectations.core import ExpectationSuiteValidationResult, \ ExpectationValidationResult, ExpectationConfiguration from great_expectations.data_context import BaseDataContext from great_expectations.data_context.types.base ...
integration/common/tests/great_expectations/test_great_expectations_validation_action.py
import json import os import sqlite3 import tempfile import pandas import pytest from great_expectations.core import ExpectationSuiteValidationResult, \ ExpectationValidationResult, ExpectationConfiguration from great_expectations.data_context import BaseDataContext from great_expectations.data_context.types.base ...
0.542136
0.461684
import sys from io import BytesIO from docker import APIClient """USAGE python3 hw6.py homework:6 Prerequestiments sudo apt install python3-pip && sudo pip3 install docker MAIN DOCUMENTAION https://docker-py.readthedocs.io/en/5.0.3/api.html """ # input paramether - tag_name with sysargv tag_name = str(sys.arg...
Python/hw6.py
import sys from io import BytesIO from docker import APIClient """USAGE python3 hw6.py homework:6 Prerequestiments sudo apt install python3-pip && sudo pip3 install docker MAIN DOCUMENTAION https://docker-py.readthedocs.io/en/5.0.3/api.html """ # input paramether - tag_name with sysargv tag_name = str(sys.arg...
0.285173
0.125815
from google.colab import drive drive.mount('/gdrive') import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications import Mobile...
car_damage_detection.py
from google.colab import drive drive.mount('/gdrive') import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from tensorflow.keras.preprocessing.image import ImageDataGenerator from tensorflow.keras.applications import Mobile...
0.714628
0.355607
from telegraph import Telegraph from telethon import events from telethon.errors.rpcerrorlist import YouBlockedUserError from userbot.cmdhelp import CmdHelp from userbot.utils import admin_cmd telegraph = Telegraph() mee = telegraph.create_account(short_name="yohohehe") @borg.on(admin_cmd(pattern="recognized ?(.*)"...
userbot/plugins/bots.py
from telegraph import Telegraph from telethon import events from telethon.errors.rpcerrorlist import YouBlockedUserError from userbot.cmdhelp import CmdHelp from userbot.utils import admin_cmd telegraph = Telegraph() mee = telegraph.create_account(short_name="yohohehe") @borg.on(admin_cmd(pattern="recognized ?(.*)"...
0.343232
0.17614
from pathlib import Path import numpy as np import torch from utils.utils import load_pickle, logger class ModelCheckpoint(object): """Save the model after every epoch. # Arguments checkpoint_dir: string, path to save the model file. monitor: quantity to monitor. verbose: ve...
mltc/callback/model_checkpoint.py
from pathlib import Path import numpy as np import torch from utils.utils import load_pickle, logger class ModelCheckpoint(object): """Save the model after every epoch. # Arguments checkpoint_dir: string, path to save the model file. monitor: quantity to monitor. verbose: ve...
0.829871
0.246519
import unittest, os, shutil from planet import config, splice, logger from xml.dom import minidom workdir = 'tests/work/apply' configfile = 'tests/data/apply/config-%s.ini' testfeed = 'tests/data/apply/feed.xml' class ApplyTest(unittest.TestCase): def setUp(self): testfile = open(testfeed) self.f...
tests/test_apply.py
import unittest, os, shutil from planet import config, splice, logger from xml.dom import minidom workdir = 'tests/work/apply' configfile = 'tests/data/apply/config-%s.ini' testfeed = 'tests/data/apply/feed.xml' class ApplyTest(unittest.TestCase): def setUp(self): testfile = open(testfeed) self.f...
0.293202
0.290635
import json def mktemp(prefix = "", suffix=""): import random, string, tempfile rand = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(8)]) temp_path = "%s/%s%s%s" % (tempfile.gettempdir(), prefix, rand, suffix) return temp_path class Genesis(object): """ Utility to cre...
genesis.py
import json def mktemp(prefix = "", suffix=""): import random, string, tempfile rand = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(8)]) temp_path = "%s/%s%s%s" % (tempfile.gettempdir(), prefix, rand, suffix) return temp_path class Genesis(object): """ Utility to cre...
0.343122
0.308906
from email.message import Message import re from typing import ( TYPE_CHECKING, List, Optional, SupportsInt, Text, Union ) from sifter.grammar.test import Test from sifter.grammar.string import expand_variables, compare as string_compare from sifter.grammar.state import EvaluationState from si...
sifter/tests/header.py
from email.message import Message import re from typing import ( TYPE_CHECKING, List, Optional, SupportsInt, Text, Union ) from sifter.grammar.test import Test from sifter.grammar.string import expand_variables, compare as string_compare from sifter.grammar.state import EvaluationState from si...
0.724968
0.188473
import torch import numpy as np def normalize(vecs, order=None): norms = np.linalg.norm(vecs, axis=1, ord=order) norms_matrix = norms[:, np.newaxis] normalized_vecs = np.divide(vecs, norms_matrix, out=np.zeros_like(vecs), where=norms_matrix !...
optimizer/compressor_nn.py
import torch import numpy as np def normalize(vecs, order=None): norms = np.linalg.norm(vecs, axis=1, ord=order) norms_matrix = norms[:, np.newaxis] normalized_vecs = np.divide(vecs, norms_matrix, out=np.zeros_like(vecs), where=norms_matrix !...
0.785473
0.510863
from __future__ import unicode_literals from dfdatetime import posix_time as dfdatetime_posix_time from plaso.lib import errors from plaso.lib import py2to3 from plaso.lib import timelib from plaso.output import interface from plaso.output import manager class TLNBaseOutputModule(interface.LinearOutputModule): ""...
plaso/output/tln.py
from __future__ import unicode_literals from dfdatetime import posix_time as dfdatetime_posix_time from plaso.lib import errors from plaso.lib import py2to3 from plaso.lib import timelib from plaso.output import interface from plaso.output import manager class TLNBaseOutputModule(interface.LinearOutputModule): ""...
0.842442
0.396477
import os import lemon.libs.errors import lemon.libs.file_extensions import os.path import config.config import lemon.libs.colors import random import string import threading import lemon.libs.extensions import sys from jinja2 import Template extensions = lemon.libs.extensions.extensions(config.config.EXTENSIONS_CONF...
lemon/libs/lemon.py
import os import lemon.libs.errors import lemon.libs.file_extensions import os.path import config.config import lemon.libs.colors import random import string import threading import lemon.libs.extensions import sys from jinja2 import Template extensions = lemon.libs.extensions.extensions(config.config.EXTENSIONS_CONF...
0.10528
0.062445
import sys import numpy as np import pandas as pd import csv import math import operator import os import time from feat_eng import * from modeling import * # Adding relative path to python path #abs_path = os.path.abspath(__file__) #file_dir = os.path.dirname(abs_path) #sys.path.append(file_dir) sys.path.append("/h...
create_pred_set.py
import sys import numpy as np import pandas as pd import csv import math import operator import os import time from feat_eng import * from modeling import * # Adding relative path to python path #abs_path = os.path.abspath(__file__) #file_dir = os.path.dirname(abs_path) #sys.path.append(file_dir) sys.path.append("/h...
0.341473
0.27217
import tensorflow as tf gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: tf.config.experimental.set_memory_growth(gpus[0], True) print(gpus) except RuntimeError as e: # 프로그램 시작시에 메모리 증가가 설정되어야만 합니다 print(e) import numpy as np from source.layers import visi...
run.py
import tensorflow as tf gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: try: tf.config.experimental.set_memory_growth(gpus[0], True) print(gpus) except RuntimeError as e: # 프로그램 시작시에 메모리 증가가 설정되어야만 합니다 print(e) import numpy as np from source.layers import visi...
0.468304
0.39065
import time import unittest from unittest import mock from opentelemetry import metrics from opentelemetry.sdk.metrics import Counter, MeterProvider from azure_monitor.sdk.auto_collection.live_metrics.exporter import ( LiveMetricsExporter, ) from azure_monitor.sdk.auto_collection.live_metrics.manager import ( ...
azure_monitor/tests/auto_collection/live_metrics/test_manager.py
import time import unittest from unittest import mock from opentelemetry import metrics from opentelemetry.sdk.metrics import Counter, MeterProvider from azure_monitor.sdk.auto_collection.live_metrics.exporter import ( LiveMetricsExporter, ) from azure_monitor.sdk.auto_collection.live_metrics.manager import ( ...
0.777807
0.285714
"""Train and eval functions used in main.py.""" import json import math import sys from typing import Iterable import torch from termcolor import colored import util.misc as utils from datasets.thumos14_eval import Thumos14Evaluator def load_json(file): with open(file) as json_file: data = json.load(jso...
engine.py
"""Train and eval functions used in main.py.""" import json import math import sys from typing import Iterable import torch from termcolor import colored import util.misc as utils from datasets.thumos14_eval import Thumos14Evaluator def load_json(file): with open(file) as json_file: data = json.load(jso...
0.776792
0.342737
import errno import socket from struct import pack, unpack, error from enum import Enum from hexdump import hexdump from ubjson.decoder import DecoderException import ubjson from . import enums from .minimal_states import MinimalGameState # pylint: disable=too-few-public-methods class EventType(Enum): """ Replay...
meleepy/slippi.py
import errno import socket from struct import pack, unpack, error from enum import Enum from hexdump import hexdump from ubjson.decoder import DecoderException import ubjson from . import enums from .minimal_states import MinimalGameState # pylint: disable=too-few-public-methods class EventType(Enum): """ Replay...
0.508056
0.18208
import collections import yaml tree = lambda: collections.defaultdict(tree) # register a recursive defaultdict with pyyaml yaml.add_representer(collections.defaultdict, yaml.representer.Representer.represent_dict) class FormatError(Exception): """An exception thrown when the YAML document i...
datman/checklist.py
import collections import yaml tree = lambda: collections.defaultdict(tree) # register a recursive defaultdict with pyyaml yaml.add_representer(collections.defaultdict, yaml.representer.Representer.represent_dict) class FormatError(Exception): """An exception thrown when the YAML document i...
0.609757
0.353177
from __future__ import annotations from inspect import isclass from typing import Any, Dict, List, Optional, Type, Union, get_type_hints from sanic.exceptions import SanicException from .types import Definition, Schema class Reference(Schema): def __init__(self, value): super().__init__(**{"$ref": valu...
sanic_ext/extensions/openapi/definitions.py
from __future__ import annotations from inspect import isclass from typing import Any, Dict, List, Optional, Type, Union, get_type_hints from sanic.exceptions import SanicException from .types import Definition, Schema class Reference(Schema): def __init__(self, value): super().__init__(**{"$ref": valu...
0.884838
0.220321
import datetime import re import urllib import urlparse import log_utils # @UnusedImport import kodi import dom_parser2 from salts_lib import scraper_utils from salts_lib.constants import FORCE_NO_MATCH from salts_lib.constants import SHORT_MONS from salts_lib.constants import VIDEO_TYPES from salts_lib.utils2 import ...
plugin.video.saltsrd.lite/scrapers/scenehdtv_scraper.py
import datetime import re import urllib import urlparse import log_utils # @UnusedImport import kodi import dom_parser2 from salts_lib import scraper_utils from salts_lib.constants import FORCE_NO_MATCH from salts_lib.constants import SHORT_MONS from salts_lib.constants import VIDEO_TYPES from salts_lib.utils2 import ...
0.229881
0.103885
from __future__ import unicode_literals from django.db import models class response(models.Model): request_id = models.CharField(max_length=16,blank=False) name = models.CharField(max_length=100) roll_number = models.IntegerField(blank=False) mobile_number = models.IntegerField(blank=False) email ...
form_app/models.py
from __future__ import unicode_literals from django.db import models class response(models.Model): request_id = models.CharField(max_length=16,blank=False) name = models.CharField(max_length=100) roll_number = models.IntegerField(blank=False) mobile_number = models.IntegerField(blank=False) email ...
0.495361
0.141252
from .aws import Action as BaseAction from .aws import BaseARN service_name = "Amazon WorkSpaces" prefix = "workspaces" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str ...
awacs/workspaces.py
from .aws import Action as BaseAction from .aws import BaseARN service_name = "Amazon WorkSpaces" prefix = "workspaces" class Action(BaseAction): def __init__(self, action: str = None) -> None: super().__init__(prefix, action) class ARN(BaseARN): def __init__(self, resource: str = "", region: str ...
0.537041
0.041833
import ast import optparse from collections import defaultdict, deque from graph import Graph class BFS(object): _UNDISCOVERED = 0 _DISCOVERED = 1 _PROCESSED = 2 def __init__(self): self._parent = defaultdict(int) self._level = {} def do_bfs(self, g, s): state = defaultdic...
graphs/bfs.py
import ast import optparse from collections import defaultdict, deque from graph import Graph class BFS(object): _UNDISCOVERED = 0 _DISCOVERED = 1 _PROCESSED = 2 def __init__(self): self._parent = defaultdict(int) self._level = {} def do_bfs(self, g, s): state = defaultdic...
0.406626
0.1937
import argparse import os import torch import torch.nn as nn from neutrino.framework.functions import LossFunction from neutrino.framework.torch_framework import TorchFramework from neutrino.framework.torch_nn import NativeOptimizerFactory, NativeSchedulerFactory from deeplite.profiler import Device from deeplite.torc...
src/hello_neutrino_unet.py
import argparse import os import torch import torch.nn as nn from neutrino.framework.functions import LossFunction from neutrino.framework.torch_framework import TorchFramework from neutrino.framework.torch_nn import NativeOptimizerFactory, NativeSchedulerFactory from deeplite.profiler import Device from deeplite.torc...
0.828939
0.165559
from k8crawler import settings, const import scrapy import pymysql import re from k8crawler import items # レース開催一覧ページのベースURL NET_KEIBA_URL_BASE = "https://race.netkeiba.com/top/" RACE_LIST_URL_BASE = NET_KEIBA_URL_BASE + "race_list_sub.html?" HORSE_URL_BASE = "https://db.netkeiba.com/horse/" class NetkeibaRaceHisto...
k8crawler/spiders/netkeiba_race_history.py
from k8crawler import settings, const import scrapy import pymysql import re from k8crawler import items # レース開催一覧ページのベースURL NET_KEIBA_URL_BASE = "https://race.netkeiba.com/top/" RACE_LIST_URL_BASE = NET_KEIBA_URL_BASE + "race_list_sub.html?" HORSE_URL_BASE = "https://db.netkeiba.com/horse/" class NetkeibaRaceHisto...
0.310904
0.15131
from datetime import date, datetime from django.db import models from django.conf import settings from django.utils import timezone from gettext import gettext as _ DEFAULT_DATE_FORMAT = getattr(settings, 'DJANGO_PARAMS_DATE_FORMAT', '%d.%m.%Y') DEFAULT_DATETIME_FORMAT = getattr(settings, 'DJANGO_PARAMS_DATETIME_FORMA...
django_params/models.py
from datetime import date, datetime from django.db import models from django.conf import settings from django.utils import timezone from gettext import gettext as _ DEFAULT_DATE_FORMAT = getattr(settings, 'DJANGO_PARAMS_DATE_FORMAT', '%d.%m.%Y') DEFAULT_DATETIME_FORMAT = getattr(settings, 'DJANGO_PARAMS_DATETIME_FORMA...
0.502197
0.089853
from copy import copy, deepcopy from random import shuffle, choice from numpy import infty from sushigo.cards import Card, MakiCard, SashimiCard, WasabiCard, DumplingCard, PuddingCard, NigiriCard, TempuraCard from sushigo.cards import sum_scores class Deck: def __init__(self, *cards): for card in cards:...
sushigo/deck.py
from copy import copy, deepcopy from random import shuffle, choice from numpy import infty from sushigo.cards import Card, MakiCard, SashimiCard, WasabiCard, DumplingCard, PuddingCard, NigiriCard, TempuraCard from sushigo.cards import sum_scores class Deck: def __init__(self, *cards): for card in cards:...
0.729809
0.092442
from __future__ import absolute_import, print_function import os import sys from pex import pex_warnings from pex.common import die from pex.executor import Executor from pex.interpreter import PythonInterpreter from pex.interpreter_constraints import matched_interpreters from pex.orderedset import OrderedSet from p...
pex/pex_bootstrapper.py
from __future__ import absolute_import, print_function import os import sys from pex import pex_warnings from pex.common import die from pex.executor import Executor from pex.interpreter import PythonInterpreter from pex.interpreter_constraints import matched_interpreters from pex.orderedset import OrderedSet from p...
0.412767
0.099689
from .rfc3986 import URI_reference, absolute_URI from .rfc5322 import mailbox from .rfc5234 import DIGIT, SP, ALPHA from .rfc5646 import Language_Tag as language_tag from .rfc7230 import ( list_rule, BWS, OWS, RWS, field_name, quoted_string, partial_URI, comment, token, ) SPEC_URL =...
redbot/syntax/rfc7231.py
from .rfc3986 import URI_reference, absolute_URI from .rfc5322 import mailbox from .rfc5234 import DIGIT, SP, ALPHA from .rfc5646 import Language_Tag as language_tag from .rfc7230 import ( list_rule, BWS, OWS, RWS, field_name, quoted_string, partial_URI, comment, token, ) SPEC_URL =...
0.515132
0.249939
from rest_framework import status, mixins from rest_framework.decorators import permission_classes from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet, GenericViewSet from src.apps.shop.models.order import OrderC...
src/apps/shop/viewsets.py
from rest_framework import status, mixins from rest_framework.decorators import permission_classes from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet, GenericViewSet from src.apps.shop.models.order import OrderC...
0.78436
0.31237
class XmlWriterTraceListener(TextWriterTraceListener): """ Directs tracing or debugging output as XML-encoded data to a System.IO.TextWriter or to a System.IO.Stream,such as a System.IO.FileStream. XmlWriterTraceListener(stream: Stream) XmlWriterTraceListener(stream: Stream,name: str) XmlWriterTraceLis...
release/stubs.min/System/Diagnostics/__init___parts/XmlWriterTraceListener.py
class XmlWriterTraceListener(TextWriterTraceListener): """ Directs tracing or debugging output as XML-encoded data to a System.IO.TextWriter or to a System.IO.Stream,such as a System.IO.FileStream. XmlWriterTraceListener(stream: Stream) XmlWriterTraceListener(stream: Stream,name: str) XmlWriterTraceLis...
0.621081
0.131118