code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import subprocess import os import zmq import time import pytest from loguru import logger @pytest.mark.skip() class TestClass: """Benchmars on the models in npc_engine/resources/models""" def setup_class(cls): logger.info("GPU VRAM Before starting inference engine:") os.system(...
tests/benchmarks/benchmark.py
import subprocess import os import zmq import time import pytest from loguru import logger @pytest.mark.skip() class TestClass: """Benchmars on the models in npc_engine/resources/models""" def setup_class(cls): logger.info("GPU VRAM Before starting inference engine:") os.system(...
0.218836
0.136464
from subprocess import call from argparse import ArgumentParser from re import sub class voice: def __init__(self): """ :param text : файл(путь/имя), начальная страница, финальная страница :type text : text :param reading : переключатель чтени...
voice.py
from subprocess import call from argparse import ArgumentParser from re import sub class voice: def __init__(self): """ :param text : файл(путь/имя), начальная страница, финальная страница :type text : text :param reading : переключатель чтени...
0.314156
0.164483
# http://www.apache.org/licenses/LICENSE-2.0.html # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language govern...
Model/lookalike-model/validations/validation_plan_1.py
# http://www.apache.org/licenses/LICENSE-2.0.html # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language govern...
0.661814
0.281795
from torch.utils.data import Dataset import h5py import torch import torchvision import numpy as np class HandSigns(Dataset): def __init__(self, train: bool, transform=None, target_transform=None): ''' Note: the parameter 'transform' overriden by Normalize transform under the train-mode (i...
projects/deep-learning/data/loaders/hand_signs.py
from torch.utils.data import Dataset import h5py import torch import torchvision import numpy as np class HandSigns(Dataset): def __init__(self, train: bool, transform=None, target_transform=None): ''' Note: the parameter 'transform' overriden by Normalize transform under the train-mode (i...
0.843863
0.471649
from abc import ABCMeta from abc import abstractmethod from .bbox3d_util import ( rbbox2d_to_near_bbox, iou_jit, distance_similarity ) # Region Similarity class RegionSimilarityCalculator(object): """Abstract base class for 2d region similarity calculator.""" __metaclass__ = ABCMeta def compa...
mvt/utils/similarity3d_util.py
from abc import ABCMeta from abc import abstractmethod from .bbox3d_util import ( rbbox2d_to_near_bbox, iou_jit, distance_similarity ) # Region Similarity class RegionSimilarityCalculator(object): """Abstract base class for 2d region similarity calculator.""" __metaclass__ = ABCMeta def compa...
0.955569
0.563678
import cgi import cgitb import time import os import sqlite3 import urlparse import subprocess import Cookie import math cgitb.enable() def htmlTop(): print("Content-type:text/html\n\n") print("<!DOCTYPE html>") print("<html lang='en'>") print("<head>") print("<meta charset='utf-8'/>") print("<title>prj</title>...
cgi-bin/index.py
import cgi import cgitb import time import os import sqlite3 import urlparse import subprocess import Cookie import math cgitb.enable() def htmlTop(): print("Content-type:text/html\n\n") print("<!DOCTYPE html>") print("<html lang='en'>") print("<head>") print("<meta charset='utf-8'/>") print("<title>prj</title>...
0.035195
0.039232
import numpy as np from torch.utils.data import Dataset from .dataset import PairDataset, InstanceDataset from neuron.config import registry from neuron import ops from collections import OrderedDict __all__ = ['Seq2Pair', 'Image2Pair', 'Seq2Instance', 'Subset', 'Slice', 'RandomConcat'] @registry.regist...
utils/neuron/data/datasets/structure.py
import numpy as np from torch.utils.data import Dataset from .dataset import PairDataset, InstanceDataset from neuron.config import registry from neuron import ops from collections import OrderedDict __all__ = ['Seq2Pair', 'Image2Pair', 'Seq2Instance', 'Subset', 'Slice', 'RandomConcat'] @registry.regist...
0.757301
0.426023
from __future__ import annotations import os import pickle import sys from typing import Dict, List, Optional, Tuple, Union import numpy as np import pandas as pd from bs4 import BeautifulSoup from scipy import sparse import util.tamer as tamer from util import utils from util.constants import * from util.groups imp...
util/datahandler.py
from __future__ import annotations import os import pickle import sys from typing import Dict, List, Optional, Tuple, Union import numpy as np import pandas as pd from bs4 import BeautifulSoup from scipy import sparse import util.tamer as tamer from util import utils from util.constants import * from util.groups imp...
0.632049
0.276249
import functools import sys import warnings import arviz as az # Makes this module as identical to arviz.plots as possible for attr in az.plots.__all__: obj = getattr(az.plots, attr) if not attr.startswith("__"): setattr(sys.modules[__name__], attr, obj) def map_args(func, alias: str): @functool...
pymc3/plots/__init__.py
import functools import sys import warnings import arviz as az # Makes this module as identical to arviz.plots as possible for attr in az.plots.__all__: obj = getattr(az.plots, attr) if not attr.startswith("__"): setattr(sys.modules[__name__], attr, obj) def map_args(func, alias: str): @functool...
0.594198
0.294069
from sfepy.base.base import * from sfepy.fem import * from sfepy.applications import pde_solve try: import matplotlib as mpl mpl.use('WXAgg') from matplotlib.pyplot import * except: pass def conditional_import(is_viewer): if is_viewer: from sfepy.postprocess import Viewer return locals...
sfepy/interactive/__init__.py
from sfepy.base.base import * from sfepy.fem import * from sfepy.applications import pde_solve try: import matplotlib as mpl mpl.use('WXAgg') from matplotlib.pyplot import * except: pass def conditional_import(is_viewer): if is_viewer: from sfepy.postprocess import Viewer return locals...
0.233008
0.088465
import sys import glob import copy import math import time from pathlib import Path import numpy as np from scipy.spatial.transform import Rotation import open3d as o3d import matplotlib.pyplot as plt import cv2 as cv from . image_depth import ImageDepth from cpp.pose_graph import optimize_pose_graph_with_matches, opt...
lib/process3d.py
import sys import glob import copy import math import time from pathlib import Path import numpy as np from scipy.spatial.transform import Rotation import open3d as o3d import matplotlib.pyplot as plt import cv2 as cv from . image_depth import ImageDepth from cpp.pose_graph import optimize_pose_graph_with_matches, opt...
0.338842
0.342709
import numpy as np import sklearn from sklearn.preprocessing import LabelEncoder import pickle from sensor_stick.srv import GetNormals from sensor_stick.features import compute_color_histograms from sensor_stick.features import compute_normal_histograms from visualization_msgs.msg import Marker from sensor_stick.ma...
pr2_robot/sensor_stick/scripts/object_recognition.py
import numpy as np import sklearn from sklearn.preprocessing import LabelEncoder import pickle from sensor_stick.srv import GetNormals from sensor_stick.features import compute_color_histograms from sensor_stick.features import compute_normal_histograms from visualization_msgs.msg import Marker from sensor_stick.ma...
0.264928
0.317903
from inspect import Signature, signature from typing import Callable, ClassVar from attrs import Factory, define, has from cattrs import Converter from flask import Flask from flask import Response as FrameworkResponse from flask import request from incant import Hook, Incanter try: from orjson import loads excep...
src/uapi/flask.py
from inspect import Signature, signature from typing import Callable, ClassVar from attrs import Factory, define, has from cattrs import Converter from flask import Flask from flask import Response as FrameworkResponse from flask import request from incant import Hook, Incanter try: from orjson import loads excep...
0.756178
0.07627
import functools try: # pragma: no cover import simplejson as json except ImportError:# pragma: no cover import json from twisted.web.resource import Resource from txyoga import errors, interface def forContentType(contentType): def decorator(encoder): encoder.contentType = contentType r...
txyoga/serializers.py
import functools try: # pragma: no cover import simplejson as json except ImportError:# pragma: no cover import json from twisted.web.resource import Resource from txyoga import errors, interface def forContentType(contentType): def decorator(encoder): encoder.contentType = contentType r...
0.604049
0.216508
# --------- Hardware Definition --------- # Define what Hardware you ar running on by # Comment out all except the platform you # are running on HW = "RPi-3B" # Raspberry Pi 3 Model B #HW = "OPi0-H2" # Orange Pi Zero with H2 Chipset # --- I2C Hardware # PCA9685 number_of_pca9685 = 1 # Numbe...
clees_io.py
# --------- Hardware Definition --------- # Define what Hardware you ar running on by # Comment out all except the platform you # are running on HW = "RPi-3B" # Raspberry Pi 3 Model B #HW = "OPi0-H2" # Orange Pi Zero with H2 Chipset # --- I2C Hardware # PCA9685 number_of_pca9685 = 1 # Numbe...
0.351089
0.282641
from django.contrib.auth.models import User from django.http import Http404 from story.serializers import UserSerializer from story.serializers import StorySerializer from story.serializers import UploadSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework...
story/views.py
from django.contrib.auth.models import User from django.http import Http404 from story.serializers import UserSerializer from story.serializers import StorySerializer from story.serializers import UploadSerializer from rest_framework.views import APIView from rest_framework.response import Response from rest_framework...
0.551815
0.07267
import jax.numpy as jnp from jax import jit def vf_stokes(r,g,eta,drho,Nkn=0.): """terminal velocity of Stokes flow (Reynolds number < 2, Davies number < 42) Args: r: particle size (cm) g: gravity (cm/s2) eta: dynamic viscosity (g/s/cm) drho: density difference between conde...
src/exojax/atm/vterm.py
import jax.numpy as jnp from jax import jit def vf_stokes(r,g,eta,drho,Nkn=0.): """terminal velocity of Stokes flow (Reynolds number < 2, Davies number < 42) Args: r: particle size (cm) g: gravity (cm/s2) eta: dynamic viscosity (g/s/cm) drho: density difference between conde...
0.911313
0.626153
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import * # noqa: F401,F403 pylint: disable=redefined-builtin,wildcard-import,unused-wildcard-import from future import standard_library standard_library....
flask_restful_hal/resource.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import * # noqa: F401,F403 pylint: disable=redefined-builtin,wildcard-import,unused-wildcard-import from future import standard_library standard_library....
0.707101
0.065515
from typing import Any, Optional from ass_parser.ass_color import AssColor from ass_parser.ass_sections.ass_base_tabular_section import ( AssBaseTabularSection, ) from ass_parser.ass_sections.const import STYLES_SECTION_NAME from ass_parser.ass_style import AssStyle from ass_parser.observable_sequence_mixin import...
ass_parser/ass_sections/ass_style_list.py
from typing import Any, Optional from ass_parser.ass_color import AssColor from ass_parser.ass_sections.ass_base_tabular_section import ( AssBaseTabularSection, ) from ass_parser.ass_sections.const import STYLES_SECTION_NAME from ass_parser.ass_style import AssStyle from ass_parser.observable_sequence_mixin import...
0.931641
0.243215
from __future__ import unicode_literals from onmt.utils.misc import split_corpus from onmt.translate.translator import build_translator from onmt.utils.parse import ArgumentParser import onmt.opts as opts from extractor import TFIDF from transformers import BertTokenizer import unicodedata import os import sys import t...
summarizer.py
from __future__ import unicode_literals from onmt.utils.misc import split_corpus from onmt.translate.translator import build_translator from onmt.utils.parse import ArgumentParser import onmt.opts as opts from extractor import TFIDF from transformers import BertTokenizer import unicodedata import os import sys import t...
0.300438
0.172939
import decimal from decimal import Decimal from InvoiceGenerator.conf import _ import qrcode __all__ = ['Address', 'Client', 'Provider', 'Creator', 'Item', 'Invoice'] class UnicodeProperty(object): _attrs = () def __setattr__(self, key, value): if key in self._attrs: value = value ...
InvoiceGenerator/api.py
import decimal from decimal import Decimal from InvoiceGenerator.conf import _ import qrcode __all__ = ['Address', 'Client', 'Provider', 'Creator', 'Item', 'Invoice'] class UnicodeProperty(object): _attrs = () def __setattr__(self, key, value): if key in self._attrs: value = value ...
0.807916
0.442697
""" This template creates a managed instance group. """ import copy REGIONAL_LOCAL_IGM_TYPES = { # https://cloud.google.com/compute/docs/reference/rest/v1/regionInstanceGroupManagers True: 'gcp-types/compute-v1:regionInstanceGroupManagers', # https://cloud.google.com/compute/docs/reference/rest/v1/instanc...
dm/templates/managed_instance_group/managed_instance_group.py
""" This template creates a managed instance group. """ import copy REGIONAL_LOCAL_IGM_TYPES = { # https://cloud.google.com/compute/docs/reference/rest/v1/regionInstanceGroupManagers True: 'gcp-types/compute-v1:regionInstanceGroupManagers', # https://cloud.google.com/compute/docs/reference/rest/v1/instanc...
0.870046
0.238672
import re import time import uuid import datetime from ModbusLib.common.utils import logger as logging from ModbusLib.common import exceptions, config_handler from multiprocessing import Queue from twisted.internet import reactor from twisted.internet import error as twisted_error from pymodbus.server.sync import Star...
ModbusLib/common/slave.py
import re import time import uuid import datetime from ModbusLib.common.utils import logger as logging from ModbusLib.common import exceptions, config_handler from multiprocessing import Queue from twisted.internet import reactor from twisted.internet import error as twisted_error from pymodbus.server.sync import Star...
0.305179
0.061452
from flask_wtf import FlaskForm from app.models import User from app import app from flask_login import current_user from wtforms import StringField, PasswordField, BooleanField, SubmitField, FloatField, SelectField from wtforms.validators import DataRequired, Email, EqualTo, ValidationError from flask_babel import laz...
app/auth/forms.py
from flask_wtf import FlaskForm from app.models import User from app import app from flask_login import current_user from wtforms import StringField, PasswordField, BooleanField, SubmitField, FloatField, SelectField from wtforms.validators import DataRequired, Email, EqualTo, ValidationError from flask_babel import laz...
0.362518
0.091992
import os import lxml.etree as ET from functools import reduce import logging import pkg_resources ns = ET.FunctionNamespace("http://nextnet.top/functions") ns.prefix = "nn" class FileResolver(ET.Resolver): def resolve(self, url, pubid, context): return self.resolve_filename(url, context) @ns def urlen...
src/rst_courses_converter/md.py
import os import lxml.etree as ET from functools import reduce import logging import pkg_resources ns = ET.FunctionNamespace("http://nextnet.top/functions") ns.prefix = "nn" class FileResolver(ET.Resolver): def resolve(self, url, pubid, context): return self.resolve_filename(url, context) @ns def urlen...
0.353875
0.267271
import json from requests import post class QiscusSDK(object): """ Simple Qiscus SDK wrapper, NOW POST TO QISME ENGINE """ @staticmethod def send_message(topic_id, message='', _type='text', base_url='', access_token='', payload=None): """ Send message to Qiscus SDK :para...
qiscus_sdk/qiscus_sdk.py
import json from requests import post class QiscusSDK(object): """ Simple Qiscus SDK wrapper, NOW POST TO QISME ENGINE """ @staticmethod def send_message(topic_id, message='', _type='text', base_url='', access_token='', payload=None): """ Send message to Qiscus SDK :para...
0.603815
0.174024
from django.test import TestCase from pipeline_test_use.components.collections.experience import ThePatchComponent from pipeline.component_framework.test import ( Call, CallAssertion, ComponentTestCase, ComponentTestMixin, ExecuteAssertion, Patcher, ) class TheComponentTest(TestCase, Componen...
runtime/bamboo-pipeline/test/pipeline_test_use/component_tests/test_patch_component.py
from django.test import TestCase from pipeline_test_use.components.collections.experience import ThePatchComponent from pipeline.component_framework.test import ( Call, CallAssertion, ComponentTestCase, ComponentTestMixin, ExecuteAssertion, Patcher, ) class TheComponentTest(TestCase, Componen...
0.59972
0.483831
from datetime import datetime from tornado.gen import coroutine from tornado.web import RequestHandler, HTTPError import bson import crypt __author__ = '<EMAIL>' __date__ = "2018/11/20 下午9:49:00" class AuthBaseHandler(RequestHandler): @property def db(self): return self.application.settings['db']...
py/wx.py
from datetime import datetime from tornado.gen import coroutine from tornado.web import RequestHandler, HTTPError import bson import crypt __author__ = '<EMAIL>' __date__ = "2018/11/20 下午9:49:00" class AuthBaseHandler(RequestHandler): @property def db(self): return self.application.settings['db']...
0.36693
0.053825
import dash # pip install dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Output, Input from dash_extensions import Lottie # pip install dash-extensions import dash_bootstrap_components as dbc # pip install dash-bootstrap-com...
d-final-analysis.py
import dash # pip install dash import dash_html_components as html import dash_core_components as dcc from dash.dependencies import Output, Input from dash_extensions import Lottie # pip install dash-extensions import dash_bootstrap_components as dbc # pip install dash-bootstrap-com...
0.608594
0.111555
import numpy as np import tensorflow as tf def match_indices(larger, smaller): """ Take two tensor sizes, and determine how to "shrink" the larger one to make it the same size as the smaller one. Basically, evenly reduce the resolution of the larger tensor so it can be compared to the smal...
model_helper_functions.py
import numpy as np import tensorflow as tf def match_indices(larger, smaller): """ Take two tensor sizes, and determine how to "shrink" the larger one to make it the same size as the smaller one. Basically, evenly reduce the resolution of the larger tensor so it can be compared to the smal...
0.784938
0.680772
from unittest import TestCase from bauh.gems.arch.mapper import ArchDataMapper class ArchDataMapperTest(TestCase): def test_check_update_no_suffix(self): self.assertTrue(ArchDataMapper.check_update('1.0.0-1', '1.0.0-2')) self.assertFalse(ArchDataMapper.check_update('1.0.0-2', '1.0.0-1')) ...
tests/gems/arch/arch_data_mapper_test.py
from unittest import TestCase from bauh.gems.arch.mapper import ArchDataMapper class ArchDataMapperTest(TestCase): def test_check_update_no_suffix(self): self.assertTrue(ArchDataMapper.check_update('1.0.0-1', '1.0.0-2')) self.assertFalse(ArchDataMapper.check_update('1.0.0-2', '1.0.0-1')) ...
0.667148
0.758265
import curses import logging import os import re from textwrap import dedent import npyscreen from initiative.constants import STAT_DISPLAY from initiative.models.encounter import Encounter, Member from initiative.ui.custom_mutt import _CustomMutt from initiative.ui.helpful_controller import HelpfulController from in...
initiative/ui/encounters/encounter_edit.py
import curses import logging import os import re from textwrap import dedent import npyscreen from initiative.constants import STAT_DISPLAY from initiative.models.encounter import Encounter, Member from initiative.ui.custom_mutt import _CustomMutt from initiative.ui.helpful_controller import HelpfulController from in...
0.319334
0.087994
import logging from typing import List, Optional, TYPE_CHECKING import pathlib import attr from aiogithubapi.github import AIOGitHubAPI from aiogithubapi.objects.repository import AIOGitHubAPIRepository from homeassistant.core import HomeAssistant from .enums import RacelandshopDisabledReason, RacelandshopStage from ...
custom_components/racelandshop/base.py
import logging from typing import List, Optional, TYPE_CHECKING import pathlib import attr from aiogithubapi.github import AIOGitHubAPI from aiogithubapi.objects.repository import AIOGitHubAPIRepository from homeassistant.core import HomeAssistant from .enums import RacelandshopDisabledReason, RacelandshopStage from ...
0.766731
0.099908
from nltk.tokenize import word_tokenize, sent_tokenize from nltk.stem import PorterStemmer, WordNetLemmatizer from nltk.corpus import wordnet from nltk import pos_tag, ne_chunk from nltk.tree import Tree import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer import re import time import sys analyzer =...
backend_resources/stats.py
from nltk.tokenize import word_tokenize, sent_tokenize from nltk.stem import PorterStemmer, WordNetLemmatizer from nltk.corpus import wordnet from nltk import pos_tag, ne_chunk from nltk.tree import Tree import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer import re import time import sys analyzer =...
0.184731
0.169028
import os import scrapy from scrapy.spiders import CrawlSpider from w3lib.html import remove_tags, remove_tags_with_content class BloombergSpider(CrawlSpider): name = 'bloomberg' handle_httpstatus_list = [200, 404] allowed_domains = ['bloomberg.com'] start_urls = ['https://www.bloomberg.com/markets']...
text/spiders/bloomberg.py
import os import scrapy from scrapy.spiders import CrawlSpider from w3lib.html import remove_tags, remove_tags_with_content class BloombergSpider(CrawlSpider): name = 'bloomberg' handle_httpstatus_list = [200, 404] allowed_domains = ['bloomberg.com'] start_urls = ['https://www.bloomberg.com/markets']...
0.332961
0.153486
from __future__ import annotations from typing import TYPE_CHECKING from fabric_cf.actor.core.kernel.rpc_request_type import RPCRequestType from fabric_cf.actor.core.util.rpc_exception import RPCException from fabric_cf.actor.core.apis.abc_actor_event import ABCActorEvent if TYPE_CHECKING: from fabric_cf.actor.co...
fabric_cf/actor/core/kernel/failed_rpc_event.py
from __future__ import annotations from typing import TYPE_CHECKING from fabric_cf.actor.core.kernel.rpc_request_type import RPCRequestType from fabric_cf.actor.core.util.rpc_exception import RPCException from fabric_cf.actor.core.apis.abc_actor_event import ABCActorEvent if TYPE_CHECKING: from fabric_cf.actor.co...
0.747339
0.142291
import gc import gzip import time import json import shutil import os,sys import tldextract import collections import pandas as pd from tqdm import tqdm import urllib.request from multiprocessing import Pool # !mkdir data # !wget https://commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2019-22/cc-index.paths.gz # !gzip...
dumping/common-crawl/get_language_index.py
import gc import gzip import time import json import shutil import os,sys import tldextract import collections import pandas as pd from tqdm import tqdm import urllib.request from multiprocessing import Pool # !mkdir data # !wget https://commoncrawl.s3.amazonaws.com/crawl-data/CC-MAIN-2019-22/cc-index.paths.gz # !gzip...
0.09678
0.155142
import pytest from cape.client import CapeClient from cape.client import CapeException from .fixtures import cc def test_saved_replies(cc): saved_replies = cc.get_saved_replies() assert 'totalItems' in saved_replies assert 'items' in saved_replies def test_saved_replies_ids(cc): saved_replies = cc.g...
tests/test_saved_replies.py
import pytest from cape.client import CapeClient from cape.client import CapeException from .fixtures import cc def test_saved_replies(cc): saved_replies = cc.get_saved_replies() assert 'totalItems' in saved_replies assert 'items' in saved_replies def test_saved_replies_ids(cc): saved_replies = cc.g...
0.55447
0.499817
import unittest import torch from numpy.testing import assert_array_almost_equal from torchvision.datasets import MNIST, CIFAR10 from torchvision.transforms import Normalize from mighty.utils.common import set_seed from mighty.utils.data import DataLoader from mighty.utils.data.normalize import NormalizeInverse, \ ...
mighty/tests/test_utils_data.py
import unittest import torch from numpy.testing import assert_array_almost_equal from torchvision.datasets import MNIST, CIFAR10 from torchvision.transforms import Normalize from mighty.utils.common import set_seed from mighty.utils.data import DataLoader from mighty.utils.data.normalize import NormalizeInverse, \ ...
0.790934
0.847211
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._enums import * __all__ = [ 'AliasProvisionedConcurrencyConfiguration', 'AliasRoutingConfiguration', 'AliasVersionWeight', 'Cod...
sdk/python/pulumi_aws_native/lambda_/outputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._enums import * __all__ = [ 'AliasProvisionedConcurrencyConfiguration', 'AliasRoutingConfiguration', 'AliasVersionWeight', 'Cod...
0.872971
0.089773
import restea.formats as formats class BaseResourceWrapper(object): ''' BaseResourceWrapper is added to have common interface between frameworks. ''' request_wrapper_class = None def __init__(self, resource_class): ''' :param resource_class: :class:`restea.resource.Resource` -- re...
restea/adapters/base.py
import restea.formats as formats class BaseResourceWrapper(object): ''' BaseResourceWrapper is added to have common interface between frameworks. ''' request_wrapper_class = None def __init__(self, resource_class): ''' :param resource_class: :class:`restea.resource.Resource` -- re...
0.860472
0.220531
import pytest from pytest import lazy_fixture @pytest.fixture def other_cohort(user_factory, cohort_factory): user = user_factory() cohort = cohort_factory(contributor__owners=[user]) return cohort @pytest.fixture def cohorts(cohort, other_cohort): return [cohort, other_cohort] @pytest.mark.django...
isic/core/tests/test_api_cohort.py
import pytest from pytest import lazy_fixture @pytest.fixture def other_cohort(user_factory, cohort_factory): user = user_factory() cohort = cohort_factory(contributor__owners=[user]) return cohort @pytest.fixture def cohorts(cohort, other_cohort): return [cohort, other_cohort] @pytest.mark.django...
0.409575
0.361954
from math import pi import ephem import unittest from nexstar import NexStar, RA_DEV, DEC_DEV PORT = '/dev/ttyACM0' class TestNexStar(unittest.TestCase): @classmethod def setUpClass(cls): cls.nex = NexStar(PORT, False) @classmethod def tearDownClass(cls): cls.nex.close() def set...
pynexstar/test_nexstar.py
from math import pi import ephem import unittest from nexstar import NexStar, RA_DEV, DEC_DEV PORT = '/dev/ttyACM0' class TestNexStar(unittest.TestCase): @classmethod def setUpClass(cls): cls.nex = NexStar(PORT, False) @classmethod def tearDownClass(cls): cls.nex.close() def set...
0.506591
0.500244
import torch from torch import nn from torch.nn import init from torch.nn import functional as F from transformers import BertModel from config import Baseline_LSTMConfig from config import Baseline_BertConfig from config import Baseline_CNNConfig from tools import load_bert_vocab_embedding_vec class Baseline_Model_B...
baseline_model.py
import torch from torch import nn from torch.nn import init from torch.nn import functional as F from transformers import BertModel from config import Baseline_LSTMConfig from config import Baseline_BertConfig from config import Baseline_CNNConfig from tools import load_bert_vocab_embedding_vec class Baseline_Model_B...
0.943582
0.18866
import boto3 import sys import argparse import subprocess import shutil import os from datetime import datetime import operator def dump(host, database, username, password, out): if username and password: auth_str= "--username %s --password %s" % (username, password) else: auth_str="" if ...
aws-scripts/s3-mongodump.py
import boto3 import sys import argparse import subprocess import shutil import os from datetime import datetime import operator def dump(host, database, username, password, out): if username and password: auth_str= "--username %s --password %s" % (username, password) else: auth_str="" if ...
0.228415
0.066297
import math import turtle class Graph: def __init__(self): self.__edges = [] # An edge is a relationship between two nodes. it is defined as: [node_a, node_b, weight] with weight defaulting to 1 self.__nodes = [] # A node is defined to be any 1 object. self.__isWeighted = True se...
EnderGraph.py
import math import turtle class Graph: def __init__(self): self.__edges = [] # An edge is a relationship between two nodes. it is defined as: [node_a, node_b, weight] with weight defaulting to 1 self.__nodes = [] # A node is defined to be any 1 object. self.__isWeighted = True se...
0.396302
0.501282
import hmac import json import random import urllib import requests from hashlib import sha1 from datetime import datetime from collections import OrderedDict from django.conf import settings as djsettings ENDPOINTS = { 'settings': 'account_settings.json', 'session': 'session.json', 'signup': 'users.json...
happ/integrations/quickblox.py
import hmac import json import random import urllib import requests from hashlib import sha1 from datetime import datetime from collections import OrderedDict from django.conf import settings as djsettings ENDPOINTS = { 'settings': 'account_settings.json', 'session': 'session.json', 'signup': 'users.json...
0.232571
0.071041
import mysql.connector import datetime import decimal import sys import json from flask import jsonify import numpy class GenericEncoder(json.JSONEncoder): def default(self,obj): if isinstance(obj, numpy.generic): return numpy.asscaler(obj) elif isinstance(obj, datetime.datetime): ...
telegram-python-bot/mysql_api.py
import mysql.connector import datetime import decimal import sys import json from flask import jsonify import numpy class GenericEncoder(json.JSONEncoder): def default(self,obj): if isinstance(obj, numpy.generic): return numpy.asscaler(obj) elif isinstance(obj, datetime.datetime): ...
0.182608
0.067485
import csv import logging import numpy as np import math import torch import torch.nn.functional as F import torch.optim as optim from torch import nn from torch import distributions from torch.utils.data.sampler import WeightedRandomSampler from meta_learn import metrics from .utils import avg_shortest_path_length, to...
meta_learn/active_learner.py
import csv import logging import numpy as np import math import torch import torch.nn.functional as F import torch.optim as optim from torch import nn from torch import distributions from torch.utils.data.sampler import WeightedRandomSampler from meta_learn import metrics from .utils import avg_shortest_path_length, to...
0.892357
0.383006
from django.conf import settings from django.contrib import admin, messages from jcasts.podcasts import feed_parser, models @admin.register(models.Category) class CategoryAdmin(admin.ModelAdmin): ordering = ("name",) list_display = ( "name", "parent", ) search_fields = ("name",) cla...
jcasts/podcasts/admin.py
from django.conf import settings from django.contrib import admin, messages from jcasts.podcasts import feed_parser, models @admin.register(models.Category) class CategoryAdmin(admin.ModelAdmin): ordering = ("name",) list_display = ( "name", "parent", ) search_fields = ("name",) cla...
0.487307
0.198122
import unittest import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from skactiveml.classifier import SklearnClassifier, ParzenWindowClassifier from skactiveml.pool import EpistemicUncertaintySampling from skactiveml.pool._epistemic_uncertainty_sampli...
skactiveml/pool/tests/test_epistemic_uncertainty_sampling.py
import unittest import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from skactiveml.classifier import SklearnClassifier, ParzenWindowClassifier from skactiveml.pool import EpistemicUncertaintySampling from skactiveml.pool._epistemic_uncertainty_sampli...
0.649579
0.615117
# 4920646f6e5c2774206361726520696620697420776f726b73206f6e20796f7572206d61636869 # 6e652120576520617265206e6f74207368697070696e6720796f7572206d616368696e6521 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import time, unittest from lib import chessboard, core, engine, movegenerator, p...
tests/test_performance.py
# 4920646f6e5c2774206361726520696620697420776f726b73206f6e20796f7572206d61636869 # 6e652120576520617265206e6f74207368697070696e6720796f7572206d616368696e6521 # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import time, unittest from lib import chessboard, core, engine, movegenerator, p...
0.634204
0.320569
import androidhelper as android import cv import time import numpy as np # 赤色のマスク def red_detect(img): # HSV色空間に変換 hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV) # 赤色のHSVの値域1 hsv_min = np.array([0, 127, 0]) hsv_max = np.array([30, 255, 255]) mask1 = cv.inRange(hsv, hsv_min, hsv_max) # 赤色のHSVの値域2...
JSTfair/android_for_test/android_openCV.py
import androidhelper as android import cv import time import numpy as np # 赤色のマスク def red_detect(img): # HSV色空間に変換 hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV) # 赤色のHSVの値域1 hsv_min = np.array([0, 127, 0]) hsv_max = np.array([30, 255, 255]) mask1 = cv.inRange(hsv, hsv_min, hsv_max) # 赤色のHSVの値域2...
0.314998
0.220259
import re from nomenclator.vendor.Qt import QtWidgets, QtCore class DescriptionSelector(QtWidgets.QWidget): """Widget used to select a description.""" #: :term:`Qt Signal` emitted when description value has been updated. updated = QtCore.Signal() #: Item label to indicate that a custom description...
source/nomenclator/widget/description_selector.py
import re from nomenclator.vendor.Qt import QtWidgets, QtCore class DescriptionSelector(QtWidgets.QWidget): """Widget used to select a description.""" #: :term:`Qt Signal` emitted when description value has been updated. updated = QtCore.Signal() #: Item label to indicate that a custom description...
0.767429
0.12276
import unittest from unittest.mock import patch import os import family import hub_map_tools import roster import person data_file_path = os.path.abspath("./family_tests/") hub_file_name = data_file_path + "/hub_map.csv" common_hub_map = hub_map_tools.ReadHubMapFromFile(hub_file_name) with patch('builtins.input', sid...
TEST/family_test.py
import unittest from unittest.mock import patch import os import family import hub_map_tools import roster import person data_file_path = os.path.abspath("./family_tests/") hub_file_name = data_file_path + "/hub_map.csv" common_hub_map = hub_map_tools.ReadHubMapFromFile(hub_file_name) with patch('builtins.input', sid...
0.430267
0.440529
import random import json import typing from flask import Flask, request, Response app = Flask(__name__) def get_device_info() -> Response: with open("resources/test/device_detail.txt", "r") as f: return Response(f.read(), mimetype="text/plain") def refresh_screen() -> Response: with open("resourc...
tests/server.py
import random import json import typing from flask import Flask, request, Response app = Flask(__name__) def get_device_info() -> Response: with open("resources/test/device_detail.txt", "r") as f: return Response(f.read(), mimetype="text/plain") def refresh_screen() -> Response: with open("resourc...
0.308607
0.148541
from logging import FATAL, ERROR, WARNING, INFO, DEBUG import os # Internal use LOG_LEVELS = { "fatal": FATAL, "error": ERROR, "warning": WARNING, "info": INFO, "debug": DEBUG } LOG_FORMAT = "[%(asctime)s]\n%(message)s" CPP_LOG_LEVEL = { FATAL: 3, ERROR: 3, WARNING: 2, INFO: 1, ...
maxatac/utilities/constants.py
from logging import FATAL, ERROR, WARNING, INFO, DEBUG import os # Internal use LOG_LEVELS = { "fatal": FATAL, "error": ERROR, "warning": WARNING, "info": INFO, "debug": DEBUG } LOG_FORMAT = "[%(asctime)s]\n%(message)s" CPP_LOG_LEVEL = { FATAL: 3, ERROR: 3, WARNING: 2, INFO: 1, ...
0.405331
0.221803
import itertools from typing import Dict, Tuple import jax from algorithmic_efficiency import spec import algorithmic_efficiency.random_utils as prng class BaseCifarWorkload(spec.Workload): def __init__(self): self._eval_iters = {} self._param_shapes = None self._param_types = None def has_reache...
algorithmic_efficiency/workloads/cifar/workload.py
import itertools from typing import Dict, Tuple import jax from algorithmic_efficiency import spec import algorithmic_efficiency.random_utils as prng class BaseCifarWorkload(spec.Workload): def __init__(self): self._eval_iters = {} self._param_shapes = None self._param_types = None def has_reache...
0.864425
0.377885
class Node: def __init__(self, val): self.cont = val self.next = None self.prev = None class doublyLinkedList: def __init__(self): self.head = None self.tail = None self.length = 0 def append(self, val): node = Node(val) if self.length == 0...
temp/doublyLinkedList.py
class Node: def __init__(self, val): self.cont = val self.next = None self.prev = None class doublyLinkedList: def __init__(self): self.head = None self.tail = None self.length = 0 def append(self, val): node = Node(val) if self.length == 0...
0.560012
0.252684
"""Defines an ellipse.""" import numpy as np from scipy.special import ellipe from . import Circle, Shape2D class Ellipse(Shape2D): """An ellipse with principal axes a and b. Args: a (float): Principal axis a of the ellipse (radius in the :math:`x` direction). b (flo...
coxeter/shapes/ellipse.py
"""Defines an ellipse.""" import numpy as np from scipy.special import ellipe from . import Circle, Shape2D class Ellipse(Shape2D): """An ellipse with principal axes a and b. Args: a (float): Principal axis a of the ellipse (radius in the :math:`x` direction). b (flo...
0.973393
0.818229
import io import os import appenv def test_init(workdir, monkeypatch): monkeypatch.setattr("sys.stdin", io.StringIO("ducker\n\n\n")) assert not os.path.exists(os.path.join(workdir, "ducker")) env = appenv.AppEnv(os.path.join(workdir, 'ducker')) env.init() assert os.readlink(os.path.join(workdi...
tests/test_init.py
import io import os import appenv def test_init(workdir, monkeypatch): monkeypatch.setattr("sys.stdin", io.StringIO("ducker\n\n\n")) assert not os.path.exists(os.path.join(workdir, "ducker")) env = appenv.AppEnv(os.path.join(workdir, 'ducker')) env.init() assert os.readlink(os.path.join(workdi...
0.325521
0.186502
import sys import matplotlib.pyplot as plt import numpy as np import time import fempy.fem.preprocessor as pre import fempy.fem.postprocessor as post from fempy.fem.core.elements import Quad4 from fempy.fem.core.entities import DOFtype, Load from fempy.fem.core.assemblers import ProblemStructural, ElementMaterialOnl...
examples/variable_young_modulus/cantilever_variable_E.py
import sys import matplotlib.pyplot as plt import numpy as np import time import fempy.fem.preprocessor as pre import fempy.fem.postprocessor as post from fempy.fem.core.elements import Quad4 from fempy.fem.core.entities import DOFtype, Load from fempy.fem.core.assemblers import ProblemStructural, ElementMaterialOnl...
0.372734
0.374619
def Start(parser, saveFile, controller): # Read CFG parser.read(saveFile) # Retrieve value of funds left over from previous game lastFunds = parser["GENERAL"]["last_funds"] # Retrieve starting funds funds = controller.RequestStart(lastFunds) # Accept valid starting funds if funds != "x...
source/v1u4/DroidModelv1u4.py
def Start(parser, saveFile, controller): # Read CFG parser.read(saveFile) # Retrieve value of funds left over from previous game lastFunds = parser["GENERAL"]["last_funds"] # Retrieve starting funds funds = controller.RequestStart(lastFunds) # Accept valid starting funds if funds != "x...
0.623721
0.367355
from collections import defaultdict from _datetime import datetime, timedelta import pytz from django.db.models import Sum from rest_framework import serializers from rest_framework.response import Response from apps.search_head_api.models import CaptureNode, Site from apps.search_head_api.views import SearchHeadAPIVi...
core/apps/stats_api/views.py
from collections import defaultdict from _datetime import datetime, timedelta import pytz from django.db.models import Sum from rest_framework import serializers from rest_framework.response import Response from apps.search_head_api.models import CaptureNode, Site from apps.search_head_api.views import SearchHeadAPIVi...
0.673084
0.145844
from metis.Task import Task from metis.File import File class CombinerTask(Task): def __init__(self, **kwargs): # Handle whatever kwargs we want here """ We feed in input files and per the splitting parameters, this task takes care of grouping them into output files """ ...
metis/CombinerTask.py
from metis.Task import Task from metis.File import File class CombinerTask(Task): def __init__(self, **kwargs): # Handle whatever kwargs we want here """ We feed in input files and per the splitting parameters, this task takes care of grouping them into output files """ ...
0.517571
0.300438
import argparse from Bio.Seq import Seq import re,sys import pipes import pprint import tempfile def read_pas(pas_file): f = open(pas_file, 'r') pas_dict = dict() f.readline() #sikp header for line in f.readlines(): line = line.rstrip('\n') pas_id,pas_type,chromosome,pos,strand,symbo...
src/legacy/extract_coverage_from_scanGenome.py
import argparse from Bio.Seq import Seq import re,sys import pipes import pprint import tempfile def read_pas(pas_file): f = open(pas_file, 'r') pas_dict = dict() f.readline() #sikp header for line in f.readlines(): line = line.rstrip('\n') pas_id,pas_type,chromosome,pos,strand,symbo...
0.116161
0.173813
import logging import threading import time from threading import Lock from etcd3 import Etcd3Exception from etcd3.events import PutEvent, DeleteEvent # type: ignore from client import V3Client # type: ignore class MonSvcClient(object): def __init__(self, end_points=None, ca_cert=None, cert_k...
PyServiceUtil/monitor.py
import logging import threading import time from threading import Lock from etcd3 import Etcd3Exception from etcd3.events import PutEvent, DeleteEvent # type: ignore from client import V3Client # type: ignore class MonSvcClient(object): def __init__(self, end_points=None, ca_cert=None, cert_k...
0.293708
0.040389
from kivy.app import App from kivy.lang import Builder KV_CODE = ''' <Separator@Widget>: size: 1, 1 canvas: Color: rgb: 1, 0, 1 Rectangle: pos: self.pos size: self.size BoxLayout: orientation: 'vertical' Label: text: "volume : {:.02f}".format...
examples/debug_Bgm.py
from kivy.app import App from kivy.lang import Builder KV_CODE = ''' <Separator@Widget>: size: 1, 1 canvas: Color: rgb: 1, 0, 1 Rectangle: pos: self.pos size: self.size BoxLayout: orientation: 'vertical' Label: text: "volume : {:.02f}".format...
0.603231
0.272762
from datetime import date from django.contrib.auth.models import User from django.test import TestCase from rest_framework.test import APIClient from donatori.models import ( Donatore, Donazione, Sesso, Sezione, StatoDonatore, ) class MockedTestCase(TestCase): def setUp(self): self.cl...
donatori/tests/mocked_data.py
from datetime import date from django.contrib.auth.models import User from django.test import TestCase from rest_framework.test import APIClient from donatori.models import ( Donatore, Donazione, Sesso, Sezione, StatoDonatore, ) class MockedTestCase(TestCase): def setUp(self): self.cl...
0.366476
0.361334
from django.shortcuts import reverse from model_bakery import baker from glitchtip.test_utils.test_case import APIPermissionTestCase class EnvironmentAPIPermissionTests(APIPermissionTestCase): def setUp(self): self.create_user_org() self.set_client_credentials(self.auth_token.token) self.e...
environments/tests/test_api_permissions.py
from django.shortcuts import reverse from model_bakery import baker from glitchtip.test_utils.test_case import APIPermissionTestCase class EnvironmentAPIPermissionTests(APIPermissionTestCase): def setUp(self): self.create_user_org() self.set_client_credentials(self.auth_token.token) self.e...
0.49585
0.285002
from typing import Optional, List from fastapi import FastAPI, HTTPException from fastapi.logger import logger from fastapi.param_functions import Query import json import logging # 2.22.0 es la version que deberia funcionar import requests import boto3 import os import uuid import datetime import pymysql from decima...
app/main.py
from typing import Optional, List from fastapi import FastAPI, HTTPException from fastapi.logger import logger from fastapi.param_functions import Query import json import logging # 2.22.0 es la version que deberia funcionar import requests import boto3 import os import uuid import datetime import pymysql from decima...
0.592431
0.09739
from . import UP_ENDPOINT, session import json class AccountIDMissingError(Exception): pass class Webhooks(self): """ Webhooks ~~~~~~~~~~~~~~~~~~~~~ Webhooks provide a mechanism for a configured URL to receive events when transaction activity occurs on Up. You can think of webhooks as being like ...
upbank_api_wrapper/webhooks.py
from . import UP_ENDPOINT, session import json class AccountIDMissingError(Exception): pass class Webhooks(self): """ Webhooks ~~~~~~~~~~~~~~~~~~~~~ Webhooks provide a mechanism for a configured URL to receive events when transaction activity occurs on Up. You can think of webhooks as being like ...
0.702122
0.093306
from gurobipy import * from models.milpconstraints import addAESrndconstraints def buildmodel(config): """ Constructs the model for the Gurobi Solver """ model = Model("aeslike") # Parameters state_dim = config["statedimension"] num_rounds = config["rounds"] branch_number = config["b...
analysis/models/aeslike.py
from gurobipy import * from models.milpconstraints import addAESrndconstraints def buildmodel(config): """ Constructs the model for the Gurobi Solver """ model = Model("aeslike") # Parameters state_dim = config["statedimension"] num_rounds = config["rounds"] branch_number = config["b...
0.669205
0.353484
import tempfile import pytest from intake_esgf import core def test_load(preset, mocker): search_data = { "response": { "numFound": 2, "docs": [ {"id": "id1", "name": "test1",}, {"id": "id2", "name": "test2",}, ], }} get = m...
intake_esgf/tests/test_catalog.py
import tempfile import pytest from intake_esgf import core def test_load(preset, mocker): search_data = { "response": { "numFound": 2, "docs": [ {"id": "id1", "name": "test1",}, {"id": "id2", "name": "test2",}, ], }} get = m...
0.556159
0.656507
from tapioca import (TapiocaAdapter, generate_wrapper_from_adapter) from requests_oauthlib import OAuth2 from .resource_mapping import RESOURCE_MAPPING from tapioca.adapters import XMLAdapterMixin from tapioca.oauth2_token_requester import Oauth2TokenRequester # todo: cookiecutter class GsheetsClientAdapter(XMLA...
tapioca_gsheets/tapioca_gsheets.py
from tapioca import (TapiocaAdapter, generate_wrapper_from_adapter) from requests_oauthlib import OAuth2 from .resource_mapping import RESOURCE_MAPPING from tapioca.adapters import XMLAdapterMixin from tapioca.oauth2_token_requester import Oauth2TokenRequester # todo: cookiecutter class GsheetsClientAdapter(XMLA...
0.326271
0.079424
from __future__ import absolute_import, print_function from __future__ import unicode_literals from collections import defaultdict from datetime import datetime import six from django.core.management.base import BaseCommand from casexml.apps.case.xform import get_case_updates from corehq.apps.commtrack.processing im...
corehq/apps/cleanup/management/commands/undo_uuid_clash.py
from __future__ import absolute_import, print_function from __future__ import unicode_literals from collections import defaultdict from datetime import datetime import six from django.core.management.base import BaseCommand from casexml.apps.case.xform import get_case_updates from corehq.apps.commtrack.processing im...
0.491944
0.060474
import numpy as np from flare_pp._C_flare import SparseGP, NormalizedDotProduct, B2, Structure from flare_pp.sparse_gp import SGP_Wrapper from flare_pp.sparse_gp_calculator import SGP_Calculator from flare.ase.atoms import FLARE_Atoms from ase import Atoms from ase.calculators.lj import LennardJones from ase.build impo...
tests/get_sgp.py
import numpy as np from flare_pp._C_flare import SparseGP, NormalizedDotProduct, B2, Structure from flare_pp.sparse_gp import SGP_Wrapper from flare_pp.sparse_gp_calculator import SGP_Calculator from flare.ase.atoms import FLARE_Atoms from ase import Atoms from ase.calculators.lj import LennardJones from ase.build impo...
0.763131
0.533519
import torch import torch.nn as nn import torch.nn.functional as F import os from model.modules import ConvBNLReLU, UpsampleNearestCBLR class Encoder(nn.Module): def __init__(self, nc, fmaps, latent_variable_size): super().__init__() self.nc = nc self.fmaps = fmaps self.latent_va...
src/model/vae.py
import torch import torch.nn as nn import torch.nn.functional as F import os from model.modules import ConvBNLReLU, UpsampleNearestCBLR class Encoder(nn.Module): def __init__(self, nc, fmaps, latent_variable_size): super().__init__() self.nc = nc self.fmaps = fmaps self.latent_va...
0.92597
0.424412
from bdb import BdbQuit import inspect import pdb import sys import threading from .util import getargnodes from .watch_element import WatchElement from .watch_print import WatchPrint class Watch: def __init__(self): self.watch_list = [] self.tracefunc_stack = [] self.enable = False ...
src/watchpoints/watch.py
from bdb import BdbQuit import inspect import pdb import sys import threading from .util import getargnodes from .watch_element import WatchElement from .watch_print import WatchPrint class Watch: def __init__(self): self.watch_list = [] self.tracefunc_stack = [] self.enable = False ...
0.26693
0.063657
import hashlib import hmac import unittest def TLSv1_0_PRF(outlen, secret, label, seed): ls = len(secret) ls1 = ls2 = (ls + 1) // 2 def xor(xx, yy): o = [] for i in range(len(xx)): o.append(xx[i] ^ yy[i]) return bytes(o) md5 = TLSv1_2_PRF(outlen, secret[:ls...
tls/prf.py
import hashlib import hmac import unittest def TLSv1_0_PRF(outlen, secret, label, seed): ls = len(secret) ls1 = ls2 = (ls + 1) // 2 def xor(xx, yy): o = [] for i in range(len(xx)): o.append(xx[i] ^ yy[i]) return bytes(o) md5 = TLSv1_2_PRF(outlen, secret[:ls...
0.427038
0.31384
import unittest import numpy as np import pandas as pd from nimbusml import Pipeline, FileDataStream, BinaryDataStream from nimbusml.datasets import get_dataset from nimbusml.feature_extraction.categorical import OneHotVectorizer from nimbusml.linear_model import FastLinearRegressor, OnlineGradientDescentRegressor fr...
src/python/nimbusml/tests/idv/test_idv.py
import unittest import numpy as np import pandas as pd from nimbusml import Pipeline, FileDataStream, BinaryDataStream from nimbusml.datasets import get_dataset from nimbusml.feature_extraction.categorical import OneHotVectorizer from nimbusml.linear_model import FastLinearRegressor, OnlineGradientDescentRegressor fr...
0.813164
0.666049
import matplotlib.animation as animation import numpy as np from gekko import GEKKO import matplotlib.pyplot as plt ''' NBUG ''' ''' MOD CONFIG ''' ''' MODEL CONFIG ''' _M1 = 10 # the cart _M2 = 1 # mass 2 _T_END = 6.2 def main(): sys = GEKKO() # declare an empty model sys.time = np.linspace(0,8,100) t_end ...
src/ipend_main.py
import matplotlib.animation as animation import numpy as np from gekko import GEKKO import matplotlib.pyplot as plt ''' NBUG ''' ''' MOD CONFIG ''' ''' MODEL CONFIG ''' _M1 = 10 # the cart _M2 = 1 # mass 2 _T_END = 6.2 def main(): sys = GEKKO() # declare an empty model sys.time = np.linspace(0,8,100) t_end ...
0.367951
0.460289
#pylint: disable=R0904,F0401 import unittest from client_test_lib import Bootstrap from client_test_lib import raise_exception class XmppConfigTest(unittest.TestCase): @classmethod def bootstrap(cls, xmpp): bootstrap = Bootstrap() bootstrap.ztps.set_config_response(xmpp=xmpp) boots...
test/client/test_xmpp_bootstrap.py
#pylint: disable=R0904,F0401 import unittest from client_test_lib import Bootstrap from client_test_lib import raise_exception class XmppConfigTest(unittest.TestCase): @classmethod def bootstrap(cls, xmpp): bootstrap = Bootstrap() bootstrap.ztps.set_config_response(xmpp=xmpp) boots...
0.354992
0.250262
import struct class FileId: """ A file identifier class, storing an unsigned short representing a file number. We can use a file identifier to retrieve the full path of a file from the database catalog. File identifiers implement pack and unpack methods to support their storage on disk. >>> id1...
HW3/dbsys-hw3/update/dbsys-hw3/Catalog/Identifiers.py
import struct class FileId: """ A file identifier class, storing an unsigned short representing a file number. We can use a file identifier to retrieve the full path of a file from the database catalog. File identifiers implement pack and unpack methods to support their storage on disk. >>> id1...
0.711531
0.186391
import time import pickle from utils import * from PIL import Image, ImageDraw from keras.layers import Input, Concatenate, Dense from keras.layers.recurrent import GRU from keras.models import Model, load_model from keras.applications import vgg16 from keras.optimizers import Adam from keras.layers.core import regul...
sf_gru.py
import time import pickle from utils import * from PIL import Image, ImageDraw from keras.layers import Input, Concatenate, Dense from keras.layers.recurrent import GRU from keras.models import Model, load_model from keras.applications import vgg16 from keras.optimizers import Adam from keras.layers.core import regul...
0.842572
0.489198
import time import os def programaparasalvar(): # coding: utf-8 """ Este projeto está sendo desenvolvido inteiramente Por <NAME>, e eu disponibilizei este projeto Para o público, para que o conhecimento s...
Arquivos/GuardarSenha.py
import time import os def programaparasalvar(): # coding: utf-8 """ Este projeto está sendo desenvolvido inteiramente Por <NAME>, e eu disponibilizei este projeto Para o público, para que o conhecimento s...
0.059224
0.303783
import logging import re from makeCourse.markdownRenderer import MarkdownRenderer from pathlib import Path, PurePath from . import slugify from .filter import burnInExtras logger = logging.getLogger(__name__) def load_item(course, data, parent=None): try: item_type = data['type'] except KeyError: ...
makeCourse/item.py
import logging import re from makeCourse.markdownRenderer import MarkdownRenderer from pathlib import Path, PurePath from . import slugify from .filter import burnInExtras logger = logging.getLogger(__name__) def load_item(course, data, parent=None): try: item_type = data['type'] except KeyError: ...
0.555676
0.133387
import math def binary_to_decimal(number: int) -> int: """Return decimal version of the specified binary number.""" result = 0 for index, digit in enumerate(reversed(str(number))): if index == 0: result += int(digit) else: result += 2 ** index * int(digit) retu...
Numbers/Binary to Decimal and Back Converter/binary_to_decimal_and_back_converter.py
import math def binary_to_decimal(number: int) -> int: """Return decimal version of the specified binary number.""" result = 0 for index, digit in enumerate(reversed(str(number))): if index == 0: result += int(digit) else: result += 2 ** index * int(digit) retu...
0.818483
0.454533
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class decimate(ScriptedConfigModuleMixin, Modul...
modules/filters/decimate.py
import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk import gen_utils from module_base import ModuleBase from module_mixins import ScriptedConfigModuleMixin import module_utils import vtk class decimate(ScriptedConfigModuleMixin, Modul...
0.490724
0.083479
from unicorn import * from enum import Enum from termcolor import colored, cprint from .utils import dict_add class MemoryType(Enum): STACK_MEMORY = 0 HEAP_MEMORY = 1 TEXT_MEMORY = 2 USER_MEMORY = 3 UNMAPPED_MEMORY = 4 UNDEFINED_MEMORY = 5 UNINITIALIZED_STACK_MEMORY = 6 UNINITIALIZ...
emulsia/memory_viewer.py
from unicorn import * from enum import Enum from termcolor import colored, cprint from .utils import dict_add class MemoryType(Enum): STACK_MEMORY = 0 HEAP_MEMORY = 1 TEXT_MEMORY = 2 USER_MEMORY = 3 UNMAPPED_MEMORY = 4 UNDEFINED_MEMORY = 5 UNINITIALIZED_STACK_MEMORY = 6 UNINITIALIZ...
0.470493
0.248278
from sys import version_info as _swig_python_version_info if _swig_python_version_info >= (2, 7, 0): def swig_import_helper(): import importlib pkg = __name__.rpartition('.')[0] mname = '.'.join((pkg, '_param_RubyCache')).lstrip('.') try: return importlib.import_module(m...
build/X86_MESI_Two_Level/python/m5/internal/param_RubyCache.py
from sys import version_info as _swig_python_version_info if _swig_python_version_info >= (2, 7, 0): def swig_import_helper(): import importlib pkg = __name__.rpartition('.')[0] mname = '.'.join((pkg, '_param_RubyCache')).lstrip('.') try: return importlib.import_module(m...
0.262842
0.061848
from rdflib import Graph, Literal, BNode, Namespace, RDF, URIRef from rdflib.collection import Collection from rdflib.extras.infixowl import Restriction from namespaces import * command_definitions = { "Command": { "tags": [ TAG.Command ], "subclasses": { "Cooling_Command": { ...
command.py
from rdflib import Graph, Literal, BNode, Namespace, RDF, URIRef from rdflib.collection import Collection from rdflib.extras.infixowl import Restriction from namespaces import * command_definitions = { "Command": { "tags": [ TAG.Command ], "subclasses": { "Cooling_Command": { ...
0.353875
0.317426
"""Tests for the @export decorator.""" import importlib import sys import textwrap import types from importlib.machinery import ModuleSpec from importlib.util import module_from_spec import pytest from pydecor.decorators import export @pytest.fixture() def reset_modules(): """Ensure sys.modules is reset at the...
tests/decorators/test_export.py
"""Tests for the @export decorator.""" import importlib import sys import textwrap import types from importlib.machinery import ModuleSpec from importlib.util import module_from_spec import pytest from pydecor.decorators import export @pytest.fixture() def reset_modules(): """Ensure sys.modules is reset at the...
0.480722
0.294262
from cerridwen import defs from .utils import jd2iso from .planets import Moon, Sun, Mercury, Venus, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto def generate_event_table(jd_start, jd_end, planets=None, aspects=None, compute_aspects=True, compute_ingresses=True, compute_retrogrades=True): ...
cerridwen/event_generator.py
from cerridwen import defs from .utils import jd2iso from .planets import Moon, Sun, Mercury, Venus, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto def generate_event_table(jd_start, jd_end, planets=None, aspects=None, compute_aspects=True, compute_ingresses=True, compute_retrogrades=True): ...
0.260013
0.371336
import pandas as pd import torch import torch.nn as nn import torch.utils.data from torch_model_base import TorchModelBase from utils import progress_bar from torch_autoencoder import TorchAutoencoder from torch.autograd import Variable __author__ = "Simranjit" __version__ = "CS224u, Stanford, Spring 2020" class MMDV...
torch_autoencoder_mmd_info.py
import pandas as pd import torch import torch.nn as nn import torch.utils.data from torch_model_base import TorchModelBase from utils import progress_bar from torch_autoencoder import TorchAutoencoder from torch.autograd import Variable __author__ = "Simranjit" __version__ = "CS224u, Stanford, Spring 2020" class MMDV...
0.82741
0.514461
import numpy as np from sawyer.mujoco.tasks.base import ComposableTask class InsertTask(ComposableTask): """ Task to insert a key object into an upward facing lock. The task assumes the key is already grasped and the gripper is close to the lock hole. Reward function is based on the following h...
sawyer/mujoco/tasks/toy_tasks.py
import numpy as np from sawyer.mujoco.tasks.base import ComposableTask class InsertTask(ComposableTask): """ Task to insert a key object into an upward facing lock. The task assumes the key is already grasped and the gripper is close to the lock hole. Reward function is based on the following h...
0.874023
0.322139
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_in...
google/ads/google_ads/v2/proto/services/keyword_view_service_pb2.py
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_in...
0.179818
0.087408
from barry.datasets.dataset import Dataset from barry.datasets.dataset_power_spectrum_abc import PowerSpectrum from barry.datasets.dataset_correlation_function_abc import CorrelationFunction from tests.utils import get_concrete class TestDataset: classes = get_concrete(Dataset) concrete = [] @classmethod...
tests/test_datasets.py
from barry.datasets.dataset import Dataset from barry.datasets.dataset_power_spectrum_abc import PowerSpectrum from barry.datasets.dataset_correlation_function_abc import CorrelationFunction from tests.utils import get_concrete class TestDataset: classes = get_concrete(Dataset) concrete = [] @classmethod...
0.765243
0.666673
import os import torch from tqdm import tqdm from abc import abstractmethod from PIL import Image if torch.__version__ >= '1.6.0': from torch.cuda.amp import autocast else: from ..torch_amp_dummy import autocast from .base import BaseVisualizer, BaseVideoVisualizer, get_collate_fn from ..datasets import DATASE...
utils/runners/seg_visualizer.py
import os import torch from tqdm import tqdm from abc import abstractmethod from PIL import Image if torch.__version__ >= '1.6.0': from torch.cuda.amp import autocast else: from ..torch_amp_dummy import autocast from .base import BaseVisualizer, BaseVideoVisualizer, get_collate_fn from ..datasets import DATASE...
0.743168
0.212457
from rest_framework import serializers from .models import Category, Book class CategorySerializer(serializers.HyperlinkedModelSerializer): """ Serializes a Category Model """ name = serializers.CharField(required=False) class Meta: model = Category fields = ( 'id', 'name', 'active' ) def crea...
techk/apps/base/serializers.py
from rest_framework import serializers from .models import Category, Book class CategorySerializer(serializers.HyperlinkedModelSerializer): """ Serializes a Category Model """ name = serializers.CharField(required=False) class Meta: model = Category fields = ( 'id', 'name', 'active' ) def crea...
0.553747
0.324637