code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from atom.views import CreateMessageMixin, DeleteMessageMixin, UpdateMessageMixin from braces.views import ( FormValidMessageMixin, PrefetchRelatedMixin, SelectRelatedMixin, UserFormKwargsMixin, ) from cached_property import cached_property from dal import autocomplete from django.urls import reverse_l...
feder/cases/views.py
from atom.views import CreateMessageMixin, DeleteMessageMixin, UpdateMessageMixin from braces.views import ( FormValidMessageMixin, PrefetchRelatedMixin, SelectRelatedMixin, UserFormKwargsMixin, ) from cached_property import cached_property from dal import autocomplete from django.urls import reverse_l...
0.667039
0.083367
import rospy import cv2 import numpy as np from cv_bridge import CvBridge, CvBridgeError from sensor_msgs.msg import Image class LineFollower(object): def __init__(self): self.bridge_object = CvBridge() self.image_sub = rospy.Subscriber("/robot1/duckbot/camera2/image_raw",Image,self.camera_ca...
Projects/Duckietown/ws-template/catkin_ws/src/line_follower/scripts/line_follow_test.py
import rospy import cv2 import numpy as np from cv_bridge import CvBridge, CvBridgeError from sensor_msgs.msg import Image class LineFollower(object): def __init__(self): self.bridge_object = CvBridge() self.image_sub = rospy.Subscriber("/robot1/duckbot/camera2/image_raw",Image,self.camera_ca...
0.543348
0.317664
import json import sys import os import random import string import docker import traceback from pathlib import Path import logging logger = logging.getLogger('DockerService') logger.setLevel(logging.DEBUG) from os.path import expanduser # Small hack so we can use a dockerfile string instead of having to write it #...
fair-cells/backend/container/docker_service.py
import json import sys import os import random import string import docker import traceback from pathlib import Path import logging logger = logging.getLogger('DockerService') logger.setLevel(logging.DEBUG) from os.path import expanduser # Small hack so we can use a dockerfile string instead of having to write it #...
0.200714
0.08043
from git import Repo import re from pathlib import Path from unicodedata import name REPO_ROOT = Path(__file__).parent.parent COZETTE_SFD = REPO_ROOT / "Cozette" / "Cozette.sfd" repo = Repo(REPO_ROOT) last_ver = sorted(repo.tags, key=lambda tag: tag.commit.committed_date)[-1] last_cozette_sfd: str = ( last_ver ...
cozette_builder/changeloggen.py
from git import Repo import re from pathlib import Path from unicodedata import name REPO_ROOT = Path(__file__).parent.parent COZETTE_SFD = REPO_ROOT / "Cozette" / "Cozette.sfd" repo = Repo(REPO_ROOT) last_ver = sorted(repo.tags, key=lambda tag: tag.commit.committed_date)[-1] last_cozette_sfd: str = ( last_ver ...
0.31563
0.131982
from collections import OrderedDict from google.appengine.ext import ndb import datetime import json import logging import unittest import webapp2 import webtest from api_handlers import api_routes from gae_models import DatastoreModel from unit_test_helper import ConsistencyTestCase, login_headers from model import ...
unit_testing/test_graphql_project_cohort.py
from collections import OrderedDict from google.appengine.ext import ndb import datetime import json import logging import unittest import webapp2 import webtest from api_handlers import api_routes from gae_models import DatastoreModel from unit_test_helper import ConsistencyTestCase, login_headers from model import ...
0.551332
0.132852
from .models_base import * from sqlalchemy.orm import relationship # ORM classes class data_stage02_isotopomer_analysis(Base): __tablename__ = 'data_stage02_isotopomer_analysis' id = Column(Integer, Sequence('data_stage02_isotopomer_analysis_id_seq'), primary_key=True) analysis_id = Column(String(500)) ...
sbaas/models/models_stage02_isotopomer.py
from .models_base import * from sqlalchemy.orm import relationship # ORM classes class data_stage02_isotopomer_analysis(Base): __tablename__ = 'data_stage02_isotopomer_analysis' id = Column(Integer, Sequence('data_stage02_isotopomer_analysis_id_seq'), primary_key=True) analysis_id = Column(String(500)) ...
0.728555
0.16248
import json import sys import os from datetime import datetime, timedelta from collections import defaultdict from windowseventmonitor import monitor_thread class Event_Monitor: """ Class is an application that monitors Windows Event Logs. Parameter config_file (string): File containing n...
windowseventmonitor/event_monitor.py
import json import sys import os from datetime import datetime, timedelta from collections import defaultdict from windowseventmonitor import monitor_thread class Event_Monitor: """ Class is an application that monitors Windows Event Logs. Parameter config_file (string): File containing n...
0.241579
0.145237
# NOTE: This is the imports for the file, # NOTE: there is a bunch of modules being imported, # NOTE: that are made for this file. # NOTE: The manifest module is used to make make the manifests import modules.manifest as manifest_module # NOTE: The splash module is a way to get the icon for the season import modules....
source/python-application/generation.py
# NOTE: This is the imports for the file, # NOTE: there is a bunch of modules being imported, # NOTE: that are made for this file. # NOTE: The manifest module is used to make make the manifests import modules.manifest as manifest_module # NOTE: The splash module is a way to get the icon for the season import modules....
0.647575
0.238644
import asyncio import concurrent.futures import enum import threading import time from typing import Any, Collection, Iterator, Optional, Set, Union from kopf.utilities import aiotasks Flag = Union[aiotasks.Future, asyncio.Event, concurrent.futures.Future, threading.Event] async def wait_flag( flag: Optiona...
kopf/structs/primitives.py
import asyncio import concurrent.futures import enum import threading import time from typing import Any, Collection, Iterator, Optional, Set, Union from kopf.utilities import aiotasks Flag = Union[aiotasks.Future, asyncio.Event, concurrent.futures.Future, threading.Event] async def wait_flag( flag: Optiona...
0.829492
0.280666
load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "action_config", "feature", "flag_group", "flag_set", "tool", "tool_path", "with_feature_set", ) load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") def _impl(ctx): if (ctx.attr.cpu == "armeabi-v7a")...
src/test/shell/bazel/testdata/bazel_toolchain_test_data/tools/arm_compiler/cc_toolchain_config.bzl
load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "action_config", "feature", "flag_group", "flag_set", "tool", "tool_path", "with_feature_set", ) load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") def _impl(ctx): if (ctx.attr.cpu == "armeabi-v7a")...
0.180757
0.099121
from io import BytesIO from time import sleep from telegram import Bot, Update, TelegramError from telegram.error import BadRequest from telegram.ext import CommandHandler, MessageHandler, Filters, run_async import tg_bot.modules.sql.users_sql as sql from tg_bot import dispatcher, OWNER_ID, LOGGER, DEV_USERS from tg...
tg_bot/modules/users.py
from io import BytesIO from time import sleep from telegram import Bot, Update, TelegramError from telegram.error import BadRequest from telegram.ext import CommandHandler, MessageHandler, Filters, run_async import tg_bot.modules.sql.users_sql as sql from tg_bot import dispatcher, OWNER_ID, LOGGER, DEV_USERS from tg...
0.361841
0.092565
import boto3 import pytest from moto import mock_dynamodb2 from cloudlift.config import EnvironmentConfiguration class TestEnvironmentConfiguration(object): def setup_existing_params(self): client = boto3.resource('dynamodb') client.create_table( TableName='environment_configurations'...
test/config/environment_configuration_test.py
import boto3 import pytest from moto import mock_dynamodb2 from cloudlift.config import EnvironmentConfiguration class TestEnvironmentConfiguration(object): def setup_existing_params(self): client = boto3.resource('dynamodb') client.create_table( TableName='environment_configurations'...
0.453262
0.263019
from StringIO import StringIO import json import os from django.core.urlresolvers import reverse from django.test import TestCase from corehq.apps.domain.shortcuts import create_domain from corehq.apps.reports.models import FormExportSchema from corehq.apps.users.models import CommCareUser from couchexport.models impor...
corehq/apps/reports/tests/test_form_export.py
from StringIO import StringIO import json import os from django.core.urlresolvers import reverse from django.test import TestCase from corehq.apps.domain.shortcuts import create_domain from corehq.apps.reports.models import FormExportSchema from corehq.apps.users.models import CommCareUser from couchexport.models impor...
0.365004
0.089574
import asyncio import requests import struct import ujson import websockets from obespoir.share.encodeutil import AesEncoder class RpcProtocol(object): """消息协议,包含消息处理""" def __init__(self): self.handfrt = "iii" # (int, int, int) -> (message_length, command_id, version) self.head_len = stru...
echecs_espoir/test/test_frame.py
import asyncio import requests import struct import ujson import websockets from obespoir.share.encodeutil import AesEncoder class RpcProtocol(object): """消息协议,包含消息处理""" def __init__(self): self.handfrt = "iii" # (int, int, int) -> (message_length, command_id, version) self.head_len = stru...
0.218669
0.131814
# Copyright (c) 2020-2022 tecnovert # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. import hashlib from enum import IntEnum from .contrib.test_framework.messages import ( CTxOutPart, ) from .contrib.test_framework.script imp...
basicswap/interface_part.py
# Copyright (c) 2020-2022 tecnovert # Distributed under the MIT software license, see the accompanying # file LICENSE or http://www.opensource.org/licenses/mit-license.php. import hashlib from enum import IntEnum from .contrib.test_framework.messages import ( CTxOutPart, ) from .contrib.test_framework.script imp...
0.550849
0.196094
from __future__ import division, print_function __all__ = [ "Term", "TermSum", "TermProduct", "TermDiff", "RealTerm", "ComplexTerm", "SHOTerm", "Matern32Term", ] import numpy as np from itertools import chain import theano import theano.tensor as tt from theano.ifelse import ifelse class Term(object):...
theano_ops/celerite/terms.py
from __future__ import division, print_function __all__ = [ "Term", "TermSum", "TermProduct", "TermDiff", "RealTerm", "ComplexTerm", "SHOTerm", "Matern32Term", ] import numpy as np from itertools import chain import theano import theano.tensor as tt from theano.ifelse import ifelse class Term(object):...
0.644225
0.238595
import unittest from shexer.shaper import Shaper from test.const import BASE_FILES, default_namespaces from test.t_utils import file_vs_str_tunned_comparison import os.path as pth from shexer.consts import TURTLE _BASE_DIR = BASE_FILES + "namespaces_to_ignore" + pth.sep class TestNamespacesToIgnore(unittest.TestCase)...
test/test_namespaces_to_ignore.py
import unittest from shexer.shaper import Shaper from test.const import BASE_FILES, default_namespaces from test.t_utils import file_vs_str_tunned_comparison import os.path as pth from shexer.consts import TURTLE _BASE_DIR = BASE_FILES + "namespaces_to_ignore" + pth.sep class TestNamespacesToIgnore(unittest.TestCase)...
0.366476
0.275285
import requests, json from urllib.parse import quote from fuzzywuzzy import process, fuzz from beers.models import Beer, ExternalAPI from django.core.management.base import BaseCommand class Command(BaseCommand): # Matches beers from beername to untappd ID. def handle(self, *args, **options): untappd...
api/beers/management/commands/match_untpd_brute.py
import requests, json from urllib.parse import quote from fuzzywuzzy import process, fuzz from beers.models import Beer, ExternalAPI from django.core.management.base import BaseCommand class Command(BaseCommand): # Matches beers from beername to untappd ID. def handle(self, *args, **options): untappd...
0.354545
0.126569
import socket import time import pygame start = 1 def main(): global start address = ('192.168.3.18', 5555) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) pygame.init() pygame.joystick.init() W, H = 320, 240 screen = pygame.display.set_mode((W, H)) clock = pygame.time.Clock() ...
joystick.py
import socket import time import pygame start = 1 def main(): global start address = ('192.168.3.18', 5555) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) pygame.init() pygame.joystick.init() W, H = 320, 240 screen = pygame.display.set_mode((W, H)) clock = pygame.time.Clock() ...
0.053354
0.11187
import tensorflow as tf from garage.tf.models.categorical_mlp_model import CategoricalMLPModel from garage.tf.models.cnn_model import CNNModel from garage.tf.models.model import Model class CategoricalCNNModel(Model): """Categorical CNN Model. A model represented by a Categorical distribution ...
src/garage/tf/models/categorical_cnn_model.py
import tensorflow as tf from garage.tf.models.categorical_mlp_model import CategoricalMLPModel from garage.tf.models.cnn_model import CNNModel from garage.tf.models.model import Model class CategoricalCNNModel(Model): """Categorical CNN Model. A model represented by a Categorical distribution ...
0.93559
0.814127
import random import time def A(x, y, z, d): return (~x & y) | (~d & z) def B(x, y, z, d): return (x & ~y) | (d & ~z) def C(x, y, z, d): return (x | (~y)) ^ (d | (~z)) def D(x, y, z, d): return ((~x) | y) ^ ((~d) | z) def E(x, y, z, d): return x ^ y ^ z ^ d def shift(k, bits): b...
final/170401053/final.py
import random import time def A(x, y, z, d): return (~x & y) | (~d & z) def B(x, y, z, d): return (x & ~y) | (d & ~z) def C(x, y, z, d): return (x | (~y)) ^ (d | (~z)) def D(x, y, z, d): return ((~x) | y) ^ ((~d) | z) def E(x, y, z, d): return x ^ y ^ z ^ d def shift(k, bits): b...
0.271541
0.338268
import dpkt __author__ = "<NAME>" class DPKTHelper(object): """ A Façade for DPKT module. """ def __init__(self): self.ssl_port = 443 self.handshake_byte = 22 self.reader = None def read_packet(self, packet): """ Reads a packet. :param packet: Pack...
Source/Facade/DpktHelper.py
import dpkt __author__ = "<NAME>" class DPKTHelper(object): """ A Façade for DPKT module. """ def __init__(self): self.ssl_port = 443 self.handshake_byte = 22 self.reader = None def read_packet(self, packet): """ Reads a packet. :param packet: Pack...
0.503906
0.184951
from email.mime.multipart import MIMEMultipart import smtplib from email.mime.text import MIMEText from django.db.backends.dummy.base import ignore import traceback class Email(object): def __init__(self,smtp_server,mail_user,login_passwd): self.mail_user = mail_user try: self.s = smt...
dark_emailSys/mailman.py
from email.mime.multipart import MIMEMultipart import smtplib from email.mime.text import MIMEText from django.db.backends.dummy.base import ignore import traceback class Email(object): def __init__(self,smtp_server,mail_user,login_passwd): self.mail_user = mail_user try: self.s = smt...
0.239616
0.052741
import datetime import numbers from contextlib import closing from typing import Any, Iterable, Mapping, Optional, Sequence, Union from airflow.operators.sql import BaseSQLOperator from airflow.providers.google.suite.hooks.sheets import GSheetsHook class SQLToGoogleSheetsOperator(BaseSQLOperator): """ Copy...
airflow/providers/google/suite/transfers/sql_to_sheets.py
import datetime import numbers from contextlib import closing from typing import Any, Iterable, Mapping, Optional, Sequence, Union from airflow.operators.sql import BaseSQLOperator from airflow.providers.google.suite.hooks.sheets import GSheetsHook class SQLToGoogleSheetsOperator(BaseSQLOperator): """ Copy...
0.885372
0.462776
from subprocess import check_output import random import numpy as np import os import re import importlib from itertools import chain, combinations if importlib.util.find_spec('spot'): import spot else: spot=None class OmegaAutomaton: """Transforms the LTL formula to an omega-automaton (OA) and stores t...
csrl/oa.py
from subprocess import check_output import random import numpy as np import os import re import importlib from itertools import chain, combinations if importlib.util.find_spec('spot'): import spot else: spot=None class OmegaAutomaton: """Transforms the LTL formula to an omega-automaton (OA) and stores t...
0.702428
0.607547
from observ import reactive from PySide6 import QtWidgets import collagraph as cg def test_widget_size(): renderer = cg.PySideRenderer(autoshow=False) widget = renderer.create_element("widget") renderer.set_attribute(widget, "size", (600, 400)) assert widget.size().width() == 600 assert widget.s...
tests/pyside/test_widget.py
from observ import reactive from PySide6 import QtWidgets import collagraph as cg def test_widget_size(): renderer = cg.PySideRenderer(autoshow=False) widget = renderer.create_element("widget") renderer.set_attribute(widget, "size", (600, 400)) assert widget.size().width() == 600 assert widget.s...
0.669205
0.37202
import logging from copy import deepcopy import numpy as np import pandas as pd import pymc as pm from arviz.plots import plot_posterior from formulae import design_matrices from .backend import PyMCModel from .defaults import get_default_prior, get_builtin_family from .families import Family, univariate, multivar...
bambi/models.py
import logging from copy import deepcopy import numpy as np import pandas as pd import pymc as pm from arviz.plots import plot_posterior from formulae import design_matrices from .backend import PyMCModel from .defaults import get_default_prior, get_builtin_family from .families import Family, univariate, multivar...
0.874077
0.449574
import json import numpy as np import os import pytest from numpy_encoder import NumpyEncoder, ndarray_hook test_vector = np.array([1.0, 2.0, 3.0]) test_mat = np.eye(3) here = os.path.dirname(os.path.realpath(__file__)) def write_encoded(obj, tdir): fp = tdir.mkdir("sub").join("obj.json") fp.write(obj) ...
gamechangerml/src/utilities/numpy_encoder/tests/test_encoder.py
import json import numpy as np import os import pytest from numpy_encoder import NumpyEncoder, ndarray_hook test_vector = np.array([1.0, 2.0, 3.0]) test_mat = np.eye(3) here = os.path.dirname(os.path.realpath(__file__)) def write_encoded(obj, tdir): fp = tdir.mkdir("sub").join("obj.json") fp.write(obj) ...
0.433502
0.347676
import io import steganosaurus.constants as constants from bitarray import bitarray from PIL import Image class PictureModifier: ''' This class can modify each pixel of picture to hide data. ''' def __init__(self, ste_lvl=constants.DEFAULT_STEGANOGRAPHY_LEVEL): ''' Constructor: ...
steganosaurus/picture_modifier.py
import io import steganosaurus.constants as constants from bitarray import bitarray from PIL import Image class PictureModifier: ''' This class can modify each pixel of picture to hide data. ''' def __init__(self, ste_lvl=constants.DEFAULT_STEGANOGRAPHY_LEVEL): ''' Constructor: ...
0.589244
0.44897
import pytest from teos.watcher import InvalidTransactionFormat from test.teos.conftest import generate_blocks from test.teos.unit.conftest import get_random_value_hex, fork hex_tx = ( "0100000001c997a5e56e104102fa209c6a852dd90660a20b2d9c352423edce25857fcd3704000000004847304402" "204e45e16932b8af514961a1d3a1a...
test/teos/unit/test_block_processor.py
import pytest from teos.watcher import InvalidTransactionFormat from test.teos.conftest import generate_blocks from test.teos.unit.conftest import get_random_value_hex, fork hex_tx = ( "0100000001c997a5e56e104102fa209c6a852dd90660a20b2d9c352423edce25857fcd3704000000004847304402" "204e45e16932b8af514961a1d3a1a...
0.680985
0.409634
import json swagger_file = open("api_v3.json") json_data = swagger_file.read() swagger_file.close() data = json.loads(json_data) api_version = data["info"]["version"] paths = data["paths"] definitions = data["components"]["schemas"] header = """@file:Suppress("unused", "SpellCheckingInspection", "KDocUnresolvedRefe...
tools/kbpy/scripts/swagger_paths_kt_2.py
import json swagger_file = open("api_v3.json") json_data = swagger_file.read() swagger_file.close() data = json.loads(json_data) api_version = data["info"]["version"] paths = data["paths"] definitions = data["components"]["schemas"] header = """@file:Suppress("unused", "SpellCheckingInspection", "KDocUnresolvedRefe...
0.349422
0.161519
#Usage: python parsecmsearch.py <directory of cmsearchoutputs> <outfile.txt> import sys import os import numpy as np def parseCMsearch(cmsearchoutput): #Parse output from cmsearch and return dictionary of hits and scores hitdict = {} #{sequencehit : [rank, evalue, score]} scorelines = [] querydict =...
parsecmsearch.py
#Usage: python parsecmsearch.py <directory of cmsearchoutputs> <outfile.txt> import sys import os import numpy as np def parseCMsearch(cmsearchoutput): #Parse output from cmsearch and return dictionary of hits and scores hitdict = {} #{sequencehit : [rank, evalue, score]} scorelines = [] querydict =...
0.351979
0.369855
import time import pickle import sys import time def get_all_files(dir): filelist = [] for root, dirs, files in os.walk(dir): for file in files: if "reject_trials" not in file and "noneeg" not in file: filelist.append(os.path.join(root, file)) return filelist prelim...
data_extraction/src/create_databases.py
import time import pickle import sys import time def get_all_files(dir): filelist = [] for root, dirs, files in os.walk(dir): for file in files: if "reject_trials" not in file and "noneeg" not in file: filelist.append(os.path.join(root, file)) return filelist prelim...
0.053527
0.126893
from abc import ABC, abstractmethod from typing import Callable, List class IStochasticFunction(ABC): """ Abstract class representing a stochastic function """ def __init__(self): super().__init__() """ Draw a sample from the stochastic function. :param x: point at which the...
utils/stats/StochasticFunction.py
from abc import ABC, abstractmethod from typing import Callable, List class IStochasticFunction(ABC): """ Abstract class representing a stochastic function """ def __init__(self): super().__init__() """ Draw a sample from the stochastic function. :param x: point at which the...
0.957675
0.729544
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import os from lib.layers import * class SSD(nn.Module): """Single Shot Multibox Architecture See: https://arxiv.org/pdf/1512.02325.pdf for more details. Args: phase: (string) Can be "eval" or ...
lib/modeling/ssds/ssd.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import os from lib.layers import * class SSD(nn.Module): """Single Shot Multibox Architecture See: https://arxiv.org/pdf/1512.02325.pdf for more details. Args: phase: (string) Can be "eval" or ...
0.899492
0.51013
import pytest from bach.operations.concat import DataFrameConcatOperation, SeriesConcatOperation from bach.expression import Expression from tests.unit.bach.util import get_fake_df @pytest.mark.db_independent def test_concat_empty_objects() -> None: with pytest.raises(ValueError, match=r'no objects to concat'): ...
bach/tests/unit/bach/test_concat.py
import pytest from bach.operations.concat import DataFrameConcatOperation, SeriesConcatOperation from bach.expression import Expression from tests.unit.bach.util import get_fake_df @pytest.mark.db_independent def test_concat_empty_objects() -> None: with pytest.raises(ValueError, match=r'no objects to concat'): ...
0.649023
0.675831
from functools import update_wrapper from django.conf.urls import url from django.contrib.admin.sites import AdminSite from peer.entity import views from peer.entity.models import Entity from peer.entity.feeds import EntitiesFeed, ChangesFeed class PublicAdminSite(AdminSite): def has_permission(self, request):...
peer/entity/adminsite.py
from functools import update_wrapper from django.conf.urls import url from django.contrib.admin.sites import AdminSite from peer.entity import views from peer.entity.models import Entity from peer.entity.feeds import EntitiesFeed, ChangesFeed class PublicAdminSite(AdminSite): def has_permission(self, request):...
0.444806
0.058051
import copy import threading from collections import OrderedDict from contextlib import contextmanager from magma.subscriberdb.sid import SIDUtils from .onready import OnDataReady from .base import BaseStore from .base import DuplicateSubscriberError class CachedStore(BaseStore): """ A thread-safe cached p...
lte/gateway/python/magma/subscriberdb/store/cached_store.py
import copy import threading from collections import OrderedDict from contextlib import contextmanager from magma.subscriberdb.sid import SIDUtils from .onready import OnDataReady from .base import BaseStore from .base import DuplicateSubscriberError class CachedStore(BaseStore): """ A thread-safe cached p...
0.687
0.094552
import argparse import csv import time import numpy as np import tensorflow.keras.optimizers as tko import tensorflow.keras.activations as tka import tensorflow.keras.losses as tkl from tensorflow.keras.layers import Input, Dense from tensorflow.keras.models import Model def build_model(): inputs = Input(shape=(1,...
parametric-curve-in-space-fitting/pmc3t_fit.py
import argparse import csv import time import numpy as np import tensorflow.keras.optimizers as tko import tensorflow.keras.activations as tka import tensorflow.keras.losses as tkl from tensorflow.keras.layers import Input, Dense from tensorflow.keras.models import Model def build_model(): inputs = Input(shape=(1,...
0.717111
0.218419
import os, signal, platform from twisted.internet import reactor from buildbot.scripts.logwatcher import LogWatcher, BuildmasterTimeoutError, \ ReconfigError class Reconfigurator: def run(self, config): # Returns "Microsoft" for Vista and "Windows" for other versions if platform.system() in...
third_party/buildbot_8_4p1/buildbot/scripts/reconfig.py
import os, signal, platform from twisted.internet import reactor from buildbot.scripts.logwatcher import LogWatcher, BuildmasterTimeoutError, \ ReconfigError class Reconfigurator: def run(self, config): # Returns "Microsoft" for Vista and "Windows" for other versions if platform.system() in...
0.4206
0.082846
from unittest.mock import patch from rest_framework import status from django.urls import reverse from rest_framework.test import APITestCase from .test_base import BaseTestCase from .test_data import test_user_data, reset_data, login_data, password_reset_data, unmatched_password, wrong_reset_email class TestPassword...
authors/apps/authentication/tests/test_password_reset.py
from unittest.mock import patch from rest_framework import status from django.urls import reverse from rest_framework.test import APITestCase from .test_base import BaseTestCase from .test_data import test_user_data, reset_data, login_data, password_reset_data, unmatched_password, wrong_reset_email class TestPassword...
0.553747
0.247999
from __future__ import absolute_import import struct try: from collections.abc import Sequence except ImportError: from collections import Sequence import uproot4.model import uproot4.deserialization import uproot4.models.TObject import uproot4.models.TBasket _tobjarray_format1 = struct.Struct(">ii") cl...
uproot4/models/TObjArray.py
from __future__ import absolute_import import struct try: from collections.abc import Sequence except ImportError: from collections import Sequence import uproot4.model import uproot4.deserialization import uproot4.models.TObject import uproot4.models.TBasket _tobjarray_format1 = struct.Struct(">ii") cl...
0.646795
0.123418
import logging from vitrage.common.constants import EntityCategory from vitrage.evaluator.template_fields import TemplateFields from vitrage.evaluator.template_validation.status_messages import status_msgs from vitrage.tests import base DEFINITIONS_INDEX_MOCK = { '123': {}, '456': {}, '789': {}, 'a1...
vitrage-4.3.1/vitrage/tests/unit/evaluator/template_validation/content/base.py
import logging from vitrage.common.constants import EntityCategory from vitrage.evaluator.template_fields import TemplateFields from vitrage.evaluator.template_validation.status_messages import status_msgs from vitrage.tests import base DEFINITIONS_INDEX_MOCK = { '123': {}, '456': {}, '789': {}, 'a1...
0.668231
0.346735
from __future__ import unicode_literals from pynodebb.http_client import HttpClient from pynodebb.settings import settings from pynodebb.api.users import User from pynodebb.api.topics import Topic from pynodebb.api.groups import Group from pynodebb.api.posts import Post from pynodebb.api.categories import Category ...
pynodebb/client.py
from __future__ import unicode_literals from pynodebb.http_client import HttpClient from pynodebb.settings import settings from pynodebb.api.users import User from pynodebb.api.topics import Topic from pynodebb.api.groups import Group from pynodebb.api.posts import Post from pynodebb.api.categories import Category ...
0.839997
0.184492
import sentry_sdk from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from graphene_file_upload.django import FileUploadGraphQLView from graphql_jwt.exceptions import PermissionDenied as JwtPermissionDenied from palvelutarjotin.consts import ( ALREADY_JOINED_EVENT_ERROR, API_USAGE_ERROR, ...
palvelutarjotin/views.py
import sentry_sdk from django.core.exceptions import ObjectDoesNotExist, PermissionDenied from graphene_file_upload.django import FileUploadGraphQLView from graphql_jwt.exceptions import PermissionDenied as JwtPermissionDenied from palvelutarjotin.consts import ( ALREADY_JOINED_EVENT_ERROR, API_USAGE_ERROR, ...
0.435421
0.066751
from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GL import _types, _glgets from OpenGL.raw.GL.VERSION.GL_1_3 import * from OpenGL.raw.GL.VERSION.GL_1_3 import _EXTENSION_NAME def glInitGl13VERSION(): '''Return boolean indicating whether this extensi...
deep-rl/lib/python2.7/site-packages/OpenGL/GL/VERSION/GL_1_3.py
from OpenGL import platform, constant, arrays from OpenGL import extensions, wrapper import ctypes from OpenGL.raw.GL import _types, _glgets from OpenGL.raw.GL.VERSION.GL_1_3 import * from OpenGL.raw.GL.VERSION.GL_1_3 import _EXTENSION_NAME def glInitGl13VERSION(): '''Return boolean indicating whether this extensi...
0.568176
0.158663
import torch from pykeops.torch import LazyTensor from pykeops.torch.cluster import grid_cluster def soft_distance(x, y, atomtype, smoothness=0.01): """ :param smoothness: float, the smoothing constant for the distance calculation. :param x: torch.Tensor, the coordinates for the atoms. :param y: torc...
modules/surface.py
import torch from pykeops.torch import LazyTensor from pykeops.torch.cluster import grid_cluster def soft_distance(x, y, atomtype, smoothness=0.01): """ :param smoothness: float, the smoothing constant for the distance calculation. :param x: torch.Tensor, the coordinates for the atoms. :param y: torc...
0.858496
0.922097
from argparse import Action from argparse import ArgumentParser from argparse import RawDescriptionHelpFormatter import json import logging import sys import etelemetry from neurodocker import __version__ from neurodocker import utils from neurodocker.generators import Dockerfile from neurodocker.generators import Si...
neurodocker/neurodocker.py
from argparse import Action from argparse import ArgumentParser from argparse import RawDescriptionHelpFormatter import json import logging import sys import etelemetry from neurodocker import __version__ from neurodocker import utils from neurodocker.generators import Dockerfile from neurodocker.generators import Si...
0.568895
0.155142
import torch from math import pow class QuaternionOperations(object): def __init__(self): print("Quaternion Operations called.") def quaternion_addition(self, q1, q2): """ Function for addition of two quaternions. :param q1: first quaternion :param q2: second quaternio...
code/quaternions/operations.py
import torch from math import pow class QuaternionOperations(object): def __init__(self): print("Quaternion Operations called.") def quaternion_addition(self, q1, q2): """ Function for addition of two quaternions. :param q1: first quaternion :param q2: second quaternio...
0.924396
0.67992
import logging import pathlib from ruamel import yaml _LOG = logging.getLogger(__name__) class RepoOwners: """ Abstracts the owners of a repository with per-path granularity. """ def __init__(self, git_cli, ref='master'): self._git_cli = git_cli self._ref = ref self._owners_...
utils/repo_owners.py
import logging import pathlib from ruamel import yaml _LOG = logging.getLogger(__name__) class RepoOwners: """ Abstracts the owners of a repository with per-path granularity. """ def __init__(self, git_cli, ref='master'): self._git_cli = git_cli self._ref = ref self._owners_...
0.819171
0.265172
import platform import sys import unittest from unittest import mock import pkg_resources from mopidy.internal import deps from mopidy.internal.gi import Gst, gi class DepsTest(unittest.TestCase): def test_format_dependency_list(self): adapters = [ lambda: dict(name="Python", version="FooPyt...
tests/internal/test_deps.py
import platform import sys import unittest from unittest import mock import pkg_resources from mopidy.internal import deps from mopidy.internal.gi import Gst, gi class DepsTest(unittest.TestCase): def test_format_dependency_list(self): adapters = [ lambda: dict(name="Python", version="FooPyt...
0.401453
0.554772
from typing import Optional class TemplateDescriptorPart: DEFAULTS = { 'html': { 'name': 'text', 'content-type': 'text/html', }, 'plain': { 'name': 'text', 'content-type': 'text/plain' }, '': { 'name': '', ...
dsw_mailer/model.py
from typing import Optional class TemplateDescriptorPart: DEFAULTS = { 'html': { 'name': 'text', 'content-type': 'text/html', }, 'plain': { 'name': 'text', 'content-type': 'text/plain' }, '': { 'name': '', ...
0.81283
0.152158
import argparse import re from datetime import timedelta from operator import itemgetter from mtools.mplotqueries.plottypes.base_type import BasePlotType try: import matplotlib.pyplot as plt from matplotlib import __version__ as mpl_version from matplotlib.dates import date2num from matplotlib.patche...
mtools/mplotqueries/plottypes/scatter_type.py
import argparse import re from datetime import timedelta from operator import itemgetter from mtools.mplotqueries.plottypes.base_type import BasePlotType try: import matplotlib.pyplot as plt from matplotlib import __version__ as mpl_version from matplotlib.dates import date2num from matplotlib.patche...
0.651466
0.306527
import json from jsonpath_ng.ext import parse from parameterized import parameterized from underbudget.tests.base import BaseTestCase class AccountsTestCase(BaseTestCase): """ Integration tests for account APIs """ @parameterized.expand([("not-an-id",), (999,)]) def test_account_category_requires_valid_...
backend/underbudget/tests/test_accounts.py
import json from jsonpath_ng.ext import parse from parameterized import parameterized from underbudget.tests.base import BaseTestCase class AccountsTestCase(BaseTestCase): """ Integration tests for account APIs """ @parameterized.expand([("not-an-id",), (999,)]) def test_account_category_requires_valid_...
0.490724
0.195729
class TestNCharVar(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) self.rawData = [] self.dataByKey = {} for i in range(1, 11): unicodeCol = u"Unicode \u3042 %d" % i fixedCharCol = (u"Fixed Unicode %d" % i).ljust(40) if i % 2: ...
cx_Oracle-doc/test/NCharVar.py
class TestNCharVar(BaseTestCase): def setUp(self): BaseTestCase.setUp(self) self.rawData = [] self.dataByKey = {} for i in range(1, 11): unicodeCol = u"Unicode \u3042 %d" % i fixedCharCol = (u"Fixed Unicode %d" % i).ljust(40) if i % 2: ...
0.521471
0.362772
from flask import render_template, Blueprint, request, make_response, url_for, redirect, flash from wtforms import ValidationError from flask_login import current_user from app.userstory.forms import UserstoryForm, UserstoryUpdateForm from app import db from app.models import Comment, Team, Userstory, Proj...
app/userstory/routes.py
from flask import render_template, Blueprint, request, make_response, url_for, redirect, flash from wtforms import ValidationError from flask_login import current_user from app.userstory.forms import UserstoryForm, UserstoryUpdateForm from app import db from app.models import Comment, Team, Userstory, Proj...
0.282988
0.046292
import numpy as np def spatial_kernel(X, Y, x, y, sigma_center, sigma_surround, inverse=1): """Creates a spatial kernel for the LGN cells' receptive field. The kernel is defined as the difference of Gaussians. Reference: Eq 2.45, Theoretical Neuroscience Dayan & Abbot (2011). Args: X (ndar...
v1_simple_cell/kernel.py
import numpy as np def spatial_kernel(X, Y, x, y, sigma_center, sigma_surround, inverse=1): """Creates a spatial kernel for the LGN cells' receptive field. The kernel is defined as the difference of Gaussians. Reference: Eq 2.45, Theoretical Neuroscience Dayan & Abbot (2011). Args: X (ndar...
0.941432
0.894144
import datetime import logging import feedparser import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, CONF_RADIUS, CONF_SCAN_INTE...
custom_components/p2000/sensor.py
import datetime import logging import feedparser import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_ATTRIBUTION, ATTR_LATITUDE, ATTR_LONGITUDE, CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, CONF_RADIUS, CONF_SCAN_INTE...
0.539226
0.118462
from typing import List, Optional from krita import Node as KritaNode from PyQt5.QtCore import QSize from PyQt5.QtGui import QImage, QColor, QPainter from .tile import MdpTile from .kra import setQImageToKritaNode def QColorFromArgbStr(c: str) -> QColor: a, r, g, b = int(c[0:2], 16), int(c[2:4], 16), int(c[4:6...
mdp_import/mdp/utils.py
from typing import List, Optional from krita import Node as KritaNode from PyQt5.QtCore import QSize from PyQt5.QtGui import QImage, QColor, QPainter from .tile import MdpTile from .kra import setQImageToKritaNode def QColorFromArgbStr(c: str) -> QColor: a, r, g, b = int(c[0:2], 16), int(c[2:4], 16), int(c[4:6...
0.795817
0.569972
from pathlib import Path USER_REPOS_PAGE1 = '''\ [ { "archive_url": "https://api.github.com/repos/jwodder/advent350/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/jwodder/advent350/assignees{/user}", "blobs_url": "https://api.github.com/repos/jwodder/advent350/git/b...
test/test_cli_request.py
from pathlib import Path USER_REPOS_PAGE1 = '''\ [ { "archive_url": "https://api.github.com/repos/jwodder/advent350/{archive_format}{/ref}", "assignees_url": "https://api.github.com/repos/jwodder/advent350/assignees{/user}", "blobs_url": "https://api.github.com/repos/jwodder/advent350/git/b...
0.517815
0.354266
import logging from pyhap.const import CATEGORY_ALARM_SYSTEM from homeassistant.components.alarm_control_panel import DOMAIN from homeassistant.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, SUPPORT_ALARM_ARM_NIGHT, SUPPORT_ALARM_ARM_VACATION, SUPPORT...
homeassistant/components/homekit/type_security_systems.py
import logging from pyhap.const import CATEGORY_ALARM_SYSTEM from homeassistant.components.alarm_control_panel import DOMAIN from homeassistant.components.alarm_control_panel.const import ( SUPPORT_ALARM_ARM_AWAY, SUPPORT_ALARM_ARM_HOME, SUPPORT_ALARM_ARM_NIGHT, SUPPORT_ALARM_ARM_VACATION, SUPPORT...
0.511961
0.082697
"""Test audit RBAC.""" import copy from os.path import abspath from os.path import dirname from os.path import join from collections import defaultdict from appengine import base from ggrc import app # noqa # pylint: disable=unused-import from ggrc.models import all_models from integration.ggrc import TestCase fro...
test/integration/ggrc_basic_permissions/test_audit_rbac.py
"""Test audit RBAC.""" import copy from os.path import abspath from os.path import dirname from os.path import join from collections import defaultdict from appengine import base from ggrc import app # noqa # pylint: disable=unused-import from ggrc.models import all_models from integration.ggrc import TestCase fro...
0.665084
0.22289
import logging from abc import ABC, abstractmethod from .coupler import NoCoupler, IdentityCoupler, coupler_map from .coupler import AdditiveCoupler, SubtractiveCoupler, MultiplicativeCoupler logger = logging.getLogger(__name__) # ============================================================================= # =====...
optimizer_utils/datastructures/parameter.py
import logging from abc import ABC, abstractmethod from .coupler import NoCoupler, IdentityCoupler, coupler_map from .coupler import AdditiveCoupler, SubtractiveCoupler, MultiplicativeCoupler logger = logging.getLogger(__name__) # ============================================================================= # =====...
0.901127
0.214383
import pickle from batchgenerators.utilities.file_and_folder_operations import subfiles import os import numpy as np def create_splits(output_dir, image_dir): npy_files = subfiles(image_dir, suffix=".npy", join=False) trainset_size = len(npy_files)*50//100 valset_size = len(npy_files)*25//100 testse...
datasets/prepare_dataset/create_splits.py
import pickle from batchgenerators.utilities.file_and_folder_operations import subfiles import os import numpy as np def create_splits(output_dir, image_dir): npy_files = subfiles(image_dir, suffix=".npy", join=False) trainset_size = len(npy_files)*50//100 valset_size = len(npy_files)*25//100 testse...
0.257952
0.226505
import numpy as np def polyfitND(x, y, deg, eps, rcond=None, full=False, w=None, cov=False): """ Return the polynomial fitting (and its derivative) for a set of points x, y where y=p(x). This is a wrapper of np.polyfit for more than one dimensions. :params x: Points where polynomial is being computed. e.g....
unittest/python/crocoddyl/locomotion/spline_utils.py
import numpy as np def polyfitND(x, y, deg, eps, rcond=None, full=False, w=None, cov=False): """ Return the polynomial fitting (and its derivative) for a set of points x, y where y=p(x). This is a wrapper of np.polyfit for more than one dimensions. :params x: Points where polynomial is being computed. e.g....
0.860516
0.866246
import os, time, random from io import BytesIO from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = g...
python3/tests/SMBConnectionTests/test_deletepattern.py
import os, time, random from io import BytesIO from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from smb import smb_structs from .util import getConnectionInfo conn = None def setup_func_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False info = g...
0.285671
0.381969
"""Session related attribute container definitions.""" import collections import time import uuid import plaso from plaso.containers import interface from plaso.containers import manager class Session(interface.AttributeContainer): """Session attribute container. Attributes: aborted (bool): True if the ses...
plaso/containers/sessions.py
"""Session related attribute container definitions.""" import collections import time import uuid import plaso from plaso.containers import interface from plaso.containers import manager class Session(interface.AttributeContainer): """Session attribute container. Attributes: aborted (bool): True if the ses...
0.83762
0.187709
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import dgad.grpc.classification_pb2 as classification__pb2 class ClassifierStub(object): """Missing associated documentation comment in .proto file.""" ...
dgad/grpc/classification_pb2_grpc.py
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import dgad.grpc.classification_pb2 as classification__pb2 class ClassifierStub(object): """Missing associated documentation comment in .proto file.""" ...
0.790085
0.078642
import numpy as np import aurora as au import aurora.autodiff as ad import timeit import argparse def measure_accuracy(activation, data, use_gpu=False): X_val, y_val = data executor = ad.Executor([activation], use_gpu=use_gpu) prob_val, = executor.run(feed_shapes={X: X_val}) if use_gpu: prob_v...
examples/mnist.py
import numpy as np import aurora as au import aurora.autodiff as ad import timeit import argparse def measure_accuracy(activation, data, use_gpu=False): X_val, y_val = data executor = ad.Executor([activation], use_gpu=use_gpu) prob_val, = executor.run(feed_shapes={X: X_val}) if use_gpu: prob_v...
0.635675
0.515193
from classes.Programm import * from PyQt5 import QtCore, QtGui, QtWidgets class MainForm(object): @property def programm(self): return self.__programm def __init__(self): self.__programm = Programm() self.__programm.file = None def setupUi(self, Form): ...
python/classes/MainForm.py
from classes.Programm import * from PyQt5 import QtCore, QtGui, QtWidgets class MainForm(object): @property def programm(self): return self.__programm def __init__(self): self.__programm = Programm() self.__programm.file = None def setupUi(self, Form): ...
0.41052
0.053924
import os import glob import subprocess import gc import exkaldi from exkaldi import args def main(): # ------------- Parse arguments from command line ---------------------- # 1. Add a discription of this program args.describe("This program is used to make dictionaries and language model") # 2....
examples/TIMIT/02_make_dict_and_LM.py
import os import glob import subprocess import gc import exkaldi from exkaldi import args def main(): # ------------- Parse arguments from command line ---------------------- # 1. Add a discription of this program args.describe("This program is used to make dictionaries and language model") # 2....
0.387574
0.167049
from modules.setup.app import app, session from modules.setup.database import Category, Item, User from functools import wraps from flask import flash, redirect, url_for, request, session as login_session import random import string import os def category_exists(f): """ Decorator to see if category exists. ...
modules/helpers.py
from modules.setup.app import app, session from modules.setup.database import Category, Item, User from functools import wraps from flask import flash, redirect, url_for, request, session as login_session import random import string import os def category_exists(f): """ Decorator to see if category exists. ...
0.436862
0.115936
import random import itertools from collections import defaultdict import pytest from plenum.common.util import randomString from sovtoken.exceptions import UTXOError, UTXONotFound from sovtoken.types import Output from sovtoken.utxo_cache import UTXOCache from storage.test.conftest import parametrised_storage # T...
sovtoken/sovtoken/test/test_utxo_cache.py
import random import itertools from collections import defaultdict import pytest from plenum.common.util import randomString from sovtoken.exceptions import UTXOError, UTXONotFound from sovtoken.types import Output from sovtoken.utxo_cache import UTXOCache from storage.test.conftest import parametrised_storage # T...
0.555435
0.322713
import abc import six @six.add_metaclass(abc.ABCMeta) class BaseAuthPlugin(object): @abc.abstractmethod def get_token(self, transport, **kwargs): """Obtain a token. How the token is obtained is up to the authenticator. If it is still valid it may be re-used, retrieved from cache or ...
python/venv/lib/python2.7/site-packages/openstack/auth/base.py
import abc import six @six.add_metaclass(abc.ABCMeta) class BaseAuthPlugin(object): @abc.abstractmethod def get_token(self, transport, **kwargs): """Obtain a token. How the token is obtained is up to the authenticator. If it is still valid it may be re-used, retrieved from cache or ...
0.868534
0.292456
from direct.task.Task import Task from pandac.PandaModules import VBase4, PandaNode from toontown.margins.MarginVisible import MarginVisible from toontown.nametag import NametagGlobals from toontown.nametag.Nametag2d import Nametag2d from toontown.nametag.Nametag3d import Nametag3d class NametagGroup: CHAT_TIMEO...
toontown/nametag/NametagGroup.py
from direct.task.Task import Task from pandac.PandaModules import VBase4, PandaNode from toontown.margins.MarginVisible import MarginVisible from toontown.nametag import NametagGlobals from toontown.nametag.Nametag2d import Nametag2d from toontown.nametag.Nametag3d import Nametag3d class NametagGroup: CHAT_TIMEO...
0.603815
0.081556
import json import os from datetime import datetime from os.path import expanduser create_folder = lambda pth: pth if os.path.exists(pth) else pth if os.makedirs(pth) is None else False current_timestamp = lambda: datetime.now().strftime("%y%m%d_%H%M") EXAMPLE_QUERY = { "query": {"ID": 0, "Date": None, "Run_Date"...
nn_logger/data_logger.py
import json import os from datetime import datetime from os.path import expanduser create_folder = lambda pth: pth if os.path.exists(pth) else pth if os.makedirs(pth) is None else False current_timestamp = lambda: datetime.now().strftime("%y%m%d_%H%M") EXAMPLE_QUERY = { "query": {"ID": 0, "Date": None, "Run_Date"...
0.347537
0.2771
shortcuts = { #https://support.google.com/docs/answer/181110 "Google Sheets" : { "Select column" : "Ctrl + Space", "Select row" : "Shift + Space", "Select all" : "⌘ + a or ⌘ + Shift + Space", "Undo" : "⌘ + z", "Redo" : "⌘ + y or ⌘ + Shift + z or Fn + F4", "Find" ...
cheatsheet/apps/googleSheets.py
shortcuts = { #https://support.google.com/docs/answer/181110 "Google Sheets" : { "Select column" : "Ctrl + Space", "Select row" : "Shift + Space", "Select all" : "⌘ + a or ⌘ + Shift + Space", "Undo" : "⌘ + z", "Redo" : "⌘ + y or ⌘ + Shift + z or Fn + F4", "Find" ...
0.583322
0.406744
import pytest from homeassistant.components import frontend from homeassistant.components.lovelace import const, dashboard from homeassistant.setup import async_setup_component from tests.async_mock import patch from tests.common import assert_setup_component, async_capture_events async def test_lovelace_from_stora...
tests/components/lovelace/test_dashboard.py
import pytest from homeassistant.components import frontend from homeassistant.components.lovelace import const, dashboard from homeassistant.setup import async_setup_component from tests.async_mock import patch from tests.common import assert_setup_component, async_capture_events async def test_lovelace_from_stora...
0.641422
0.467636
import torch as th from torch.utils.data import Dataset import pandas as pd import os import numpy as np import random import ffmpeg import time import re import pickle class Youcook_DataLoader(Dataset): """Youcook Video-Text loader.""" def __init__( self, data, video_root...
youcook_loader.py
import torch as th from torch.utils.data import Dataset import pandas as pd import os import numpy as np import random import ffmpeg import time import re import pickle class Youcook_DataLoader(Dataset): """Youcook Video-Text loader.""" def __init__( self, data, video_root...
0.636014
0.261225
import torch import faiss import numpy as np import multiprocessing as mp from torch.autograd import Variable from metrics import precision_at_k, mean_average_precision, average_precision from metrics import dcg_at_k, ndcg_at_k from utils import AverageMeter, to_numpy def L2norm(x): return x / np.linalg.norm(x, a...
validate.py
import torch import faiss import numpy as np import multiprocessing as mp from torch.autograd import Variable from metrics import precision_at_k, mean_average_precision, average_precision from metrics import dcg_at_k, ndcg_at_k from utils import AverageMeter, to_numpy def L2norm(x): return x / np.linalg.norm(x, a...
0.682997
0.453201
import os import time from flask import Flask, render_template, make_response, flash, redirect, request, url_for, send_from_directory from werkzeug.utils import secure_filename from pathlib import Path import ai upP = "./templates/usr_data/" pkl_file = "./pkl_file" ALLOWED_EXTENSIONS = {"jpg"} def allowed_file(filen...
server/src/app.py
import os import time from flask import Flask, render_template, make_response, flash, redirect, request, url_for, send_from_directory from werkzeug.utils import secure_filename from pathlib import Path import ai upP = "./templates/usr_data/" pkl_file = "./pkl_file" ALLOWED_EXTENSIONS = {"jpg"} def allowed_file(filen...
0.294418
0.044204
import pytest import time from distutils.version import LooseVersion from f5.bigip.tm.analytics.protocol_inspection import Generate_Report from f5.bigip.tm.analytics.protocol_inspection import Report_Results @pytest.fixture(scope='function') def generate_report(mgmt_root): task = mgmt_root.tm.analytics.protocol...
f5/bigip/tm/analytics/test/functional/test_protocol_inspection.py
import pytest import time from distutils.version import LooseVersion from f5.bigip.tm.analytics.protocol_inspection import Generate_Report from f5.bigip.tm.analytics.protocol_inspection import Report_Results @pytest.fixture(scope='function') def generate_report(mgmt_root): task = mgmt_root.tm.analytics.protocol...
0.397588
0.241489
import pytest from ezdxf.tools import pattern def test_load_iso_pattern(): p = pattern.load() assert p['ANSI31'][0] == [45.0, (0.0, 0.0), (-2.2450640303, 2.2450640303), []] def test_load_scaled_iso_pattern(): p = pattern.load(factor=2) assert p['ANSI31'][0] == [45.0, (...
tests/test_05_tools/test_512_pattern.py
import pytest from ezdxf.tools import pattern def test_load_iso_pattern(): p = pattern.load() assert p['ANSI31'][0] == [45.0, (0.0, 0.0), (-2.2450640303, 2.2450640303), []] def test_load_scaled_iso_pattern(): p = pattern.load(factor=2) assert p['ANSI31'][0] == [45.0, (...
0.582729
0.501831
""" Base class for resources based on DB models. """ from __future__ import absolute_import, unicode_literals # stdlib imports from logging import getLogger from typing import Text # 3rd party imports import jsonschema from serafin import Fieldspec, serialize # local imports from .resource import RestResource from ....
src/restible/model.py
""" Base class for resources based on DB models. """ from __future__ import absolute_import, unicode_literals # stdlib imports from logging import getLogger from typing import Text # 3rd party imports import jsonschema from serafin import Fieldspec, serialize # local imports from .resource import RestResource from ....
0.872334
0.290975
from contextlib import contextmanager import difflib import filecmp import io import json import os import re import sys from unittest.mock import Mock @contextmanager def capture(): with capture_std_streams(streams=['stdout']) as captured_streams: yield captured_streams['stdout'] def capture_std_streams...
mc/utils/testing/__init__.py
from contextlib import contextmanager import difflib import filecmp import io import json import os import re import sys from unittest.mock import Mock @contextmanager def capture(): with capture_std_streams(streams=['stdout']) as captured_streams: yield captured_streams['stdout'] def capture_std_streams...
0.293202
0.176512
import time import logging import multiprocessing import pickle as pkl import os from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from sklearn.model_selection import StratifiedKFold from alphaml.engine.components.models.classification import _classifiers from alphaml.engin...
alphaml/engine/evaluator/hyperopt_evaluator.py
import time import logging import multiprocessing import pickle as pkl import os from sklearn.metrics import roc_auc_score from sklearn.model_selection import train_test_split from sklearn.model_selection import StratifiedKFold from alphaml.engine.components.models.classification import _classifiers from alphaml.engin...
0.581065
0.185947
from django.http import Http404 from django.views.generic.base import TemplateView, RedirectView from django.views.generic.edit import FormView, FormMixin from django.contrib.messages.views import SuccessMessageMixin from django.utils import timezone from django.contrib.flatpages.models import FlatPage import logging ...
blog_django/views.py
from django.http import Http404 from django.views.generic.base import TemplateView, RedirectView from django.views.generic.edit import FormView, FormMixin from django.contrib.messages.views import SuccessMessageMixin from django.utils import timezone from django.contrib.flatpages.models import FlatPage import logging ...
0.32896
0.038683
import cjm import os.path as osp import logging, os, configparser, sys logger = logging.getLogger('cjm') class ConfigCollection(object): """ Reads a config file with all the different configuration options """ def __init__(self, config_file): """ Constructor method """ s...
cjm/config.py
import cjm import os.path as osp import logging, os, configparser, sys logger = logging.getLogger('cjm') class ConfigCollection(object): """ Reads a config file with all the different configuration options """ def __init__(self, config_file): """ Constructor method """ s...
0.298287
0.09899
import time import logging import concurrent.futures from spaceone.core.service import * from spaceone.inventory.manager.collector_manager import CollectorManager _LOGGER = logging.getLogger(__name__) FILTER_FORMAT = [ { 'key': 'project_id', 'name': 'Project ID', 'type': 'str', 'r...
src/spaceone/inventory/service/collector_service.py
import time import logging import concurrent.futures from spaceone.core.service import * from spaceone.inventory.manager.collector_manager import CollectorManager _LOGGER = logging.getLogger(__name__) FILTER_FORMAT = [ { 'key': 'project_id', 'name': 'Project ID', 'type': 'str', 'r...
0.472683
0.084493
import pandas as pd import os from clarifai.rest import ClarifaiApp from clarifai.rest import Image as ClImage import time import logging import warnings from logging.handlers import RotatingFileHandler logger_file_handler = RotatingFileHandler(u'working_data/logs/clarifai_custom_model.log') logger_file_handler.set...
train_models/helpers/custommodels/clarifai_trainer.py
import pandas as pd import os from clarifai.rest import ClarifaiApp from clarifai.rest import Image as ClImage import time import logging import warnings from logging.handlers import RotatingFileHandler logger_file_handler = RotatingFileHandler(u'working_data/logs/clarifai_custom_model.log') logger_file_handler.set...
0.229881
0.115461
import text_colors def starting_server(): print(text_colors.CGREENBG + text_colors.CBOLD + "[STARTING]"+ text_colors.CEND + text_colors.CGREEN +" server is starting." + text_colors.CEND) def listening(SERVER, PORT): print(text_colors.CBLUEBG2 + text_colors.CBOLD + "[LISTENING]" + text_colors.CEND + text_col...
messages.py
import text_colors def starting_server(): print(text_colors.CGREENBG + text_colors.CBOLD + "[STARTING]"+ text_colors.CEND + text_colors.CGREEN +" server is starting." + text_colors.CEND) def listening(SERVER, PORT): print(text_colors.CBLUEBG2 + text_colors.CBOLD + "[LISTENING]" + text_colors.CEND + text_col...
0.153296
0.040961
import mock from rally import exceptions from rally.plugins.common import types from tests.unit import test class PathOrUrlTestCase(test.TestCase): @mock.patch("os.path.isfile") @mock.patch("requests.head") def test_preprocess_file(self, mock_requests_head, mock_isfile): mock_isfile.return_valu...
tests/unit/plugins/common/test_types.py
import mock from rally import exceptions from rally.plugins.common import types from tests.unit import test class PathOrUrlTestCase(test.TestCase): @mock.patch("os.path.isfile") @mock.patch("requests.head") def test_preprocess_file(self, mock_requests_head, mock_isfile): mock_isfile.return_valu...
0.624294
0.257899
import os, sys, time import numpy as np import dolfin as df from GalerkinSolverComplex import * from PML import * #======================================================================================= class HelmholtzSolver(GalerkinSolverComplex): #--------------------------------------------------------------...
HelmholtzSolver.py
import os, sys, time import numpy as np import dolfin as df from GalerkinSolverComplex import * from PML import * #======================================================================================= class HelmholtzSolver(GalerkinSolverComplex): #--------------------------------------------------------------...
0.412057
0.218232
from __future__ import absolute_import # NOTE(kgriffs): Work around a Cython bug from typing import Union from falcon import errors from falcon.media.base import BaseHandler, BinaryBaseHandlerWS class MessagePackHandler(BaseHandler): """Handler built using the :py:mod:`msgpack` module. This handler uses `...
falcon/media/msgpack.py
from __future__ import absolute_import # NOTE(kgriffs): Work around a Cython bug from typing import Union from falcon import errors from falcon.media.base import BaseHandler, BinaryBaseHandlerWS class MessagePackHandler(BaseHandler): """Handler built using the :py:mod:`msgpack` module. This handler uses `...
0.907457
0.168515
import re from quodlibet import config from quodlibet import util from quodlibet.parse import XMLFromMarkupPattern as XMLFromPattern from quodlibet.parse import pattern_from_markup class PaneConfig(object): """Row pattern format: 'categorize_pattern:display_pattern' * display_pattern is optional (fallback...
stdlib2-src/dist-packages/quodlibet/browsers/paned/util.py
import re from quodlibet import config from quodlibet import util from quodlibet.parse import XMLFromMarkupPattern as XMLFromPattern from quodlibet.parse import pattern_from_markup class PaneConfig(object): """Row pattern format: 'categorize_pattern:display_pattern' * display_pattern is optional (fallback...
0.321886
0.143368
from keystoneauth1 import exceptions from asclient.common import exceptions as execs from asclient.common import manager from asclient.common import utils from asclient.common.i18n import _ from asclient.v1 import resource class GroupManager(manager.Manager): """Auto Scaling Group Manager""" resource_class ...
asclient/v1/group_mgr.py
from keystoneauth1 import exceptions from asclient.common import exceptions as execs from asclient.common import manager from asclient.common import utils from asclient.common.i18n import _ from asclient.v1 import resource class GroupManager(manager.Manager): """Auto Scaling Group Manager""" resource_class ...
0.701202
0.130979
import io import os import random from typing import List, Optional, Text, Tuple import numpy as np import pytorch_lightning as pl import torch from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader, Dataset, random_split from varclr.data.preprocessor import Preprocessor from varclr.data....
varclr/data/dataset.py
import io import os import random from typing import List, Optional, Text, Tuple import numpy as np import pytorch_lightning as pl import torch from torch.nn.utils.rnn import pad_sequence from torch.utils.data import DataLoader, Dataset, random_split from varclr.data.preprocessor import Preprocessor from varclr.data....
0.716814
0.373076
import os import tensorflow as tf import operator from pathlib import Path from transformers import AutoTokenizer, TFAutoModelForSequenceClassification, AutoConfig from .config import model_params, model_location from .get_weights import Download from .label_mapping import LabelMapping from . import __version__ cl...
dialog_tag/DialogTag.py
import os import tensorflow as tf import operator from pathlib import Path from transformers import AutoTokenizer, TFAutoModelForSequenceClassification, AutoConfig from .config import model_params, model_location from .get_weights import Download from .label_mapping import LabelMapping from . import __version__ cl...
0.36693
0.11129
import logging import os from pathlib import Path import pytest from jinja2 import UndefinedError from astrality.compiler import ( compile_template, compile_template_to_string, jinja_environment, ) from astrality.context import Context @pytest.fixture def test_templates_folder(): return Path(__file...
astrality/tests/test_compiler.py
import logging import os from pathlib import Path import pytest from jinja2 import UndefinedError from astrality.compiler import ( compile_template, compile_template_to_string, jinja_environment, ) from astrality.context import Context @pytest.fixture def test_templates_folder(): return Path(__file...
0.386532
0.516169
import os import sys import random import logging import argparse import gensim logger = logging.getLogger(__name__) def word2vec2tensor(word2vec_model_path,tensor_filename, binary=False): ''' Convert Word2Vec mode to 2D tensor TSV file and metadata file Args: param1 (str): word2vec model file pa...
lib/python2.7/site-packages/gensim/scripts/word2vec2tensor.py
import os import sys import random import logging import argparse import gensim logger = logging.getLogger(__name__) def word2vec2tensor(word2vec_model_path,tensor_filename, binary=False): ''' Convert Word2Vec mode to 2D tensor TSV file and metadata file Args: param1 (str): word2vec model file pa...
0.265976
0.146057