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 tenable.errors import *
from ..checker import check, single
import uuid, io, pytest
@pytest.mark.vcr()
def test_configure_id_typeerror(api):
with pytest.raises(TypeError):
api.policies.configure('nope', dict())
@pytest.mark.vcr()
def test_configure_policy_typeerror(api):
with pytest.raises(TypeEr... | tests/io/test_policies.py | from tenable.errors import *
from ..checker import check, single
import uuid, io, pytest
@pytest.mark.vcr()
def test_configure_id_typeerror(api):
with pytest.raises(TypeError):
api.policies.configure('nope', dict())
@pytest.mark.vcr()
def test_configure_policy_typeerror(api):
with pytest.raises(TypeEr... | 0.435061 | 0.44903 |
"""Provides the web interface for adding and editing sheriff rotations."""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import json
from dashboard import edit_config_handler
from dashboard.models import sheriff
from dashboard import sheriff_pb2
from goo... | dashboard/dashboard/edit_sheriffs.py |
"""Provides the web interface for adding and editing sheriff rotations."""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import json
from dashboard import edit_config_handler
from dashboard.models import sheriff
from dashboard import sheriff_pb2
from goo... | 0.840062 | 0.111628 |
def test_import():
from heart_rate import ECG
first_set = ECG(filename='test_data1.csv')
assert first_set.time[0] == 0
assert first_set.time[-1] == 27.775
assert first_set.voltage[0] == -0.145
assert first_set.voltage[-1] == 0.72
second_set = ECG(filename='test_data27.csv')
assert seco... | code/test_heart_rate.py | def test_import():
from heart_rate import ECG
first_set = ECG(filename='test_data1.csv')
assert first_set.time[0] == 0
assert first_set.time[-1] == 27.775
assert first_set.voltage[0] == -0.145
assert first_set.voltage[-1] == 0.72
second_set = ECG(filename='test_data27.csv')
assert seco... | 0.441191 | 0.595022 |
import io
import sys
from textwrap import dedent
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
def import_htpasswd_file(filename, verbosity=1, overwrite=False):
with io.open(filename) as file:
for line in file:
if not ':' in line:
... | ietf/utils/management/commands/import_htpasswd.py | import io
import sys
from textwrap import dedent
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
def import_htpasswd_file(filename, verbosity=1, overwrite=False):
with io.open(filename) as file:
for line in file:
if not ':' in line:
... | 0.208018 | 0.060391 |
import FWCore.ParameterSet.Config as cms
trackingMaterialAnalyser = cms.EDAnalyzer("TrackingMaterialAnalyser",
MaterialAccounting = cms.InputTag("trackingMaterialProducer"),
SplitMode = cms.string("NearestLayer"),
SkipBeforeFirstDetector = cms.bool(False),
SkipAfterLastDetector = c... | SimTracker/TrackerMaterialAnalysis/python/trackingMaterialAnalyser_ForPhaseI_cfi.py | import FWCore.ParameterSet.Config as cms
trackingMaterialAnalyser = cms.EDAnalyzer("TrackingMaterialAnalyser",
MaterialAccounting = cms.InputTag("trackingMaterialProducer"),
SplitMode = cms.string("NearestLayer"),
SkipBeforeFirstDetector = cms.bool(False),
SkipAfterLastDetector = c... | 0.556279 | 0.174621 |
"""OCR."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import struct
from tensor2tensor.data_generators import image_utils
from tensor2tensor.data_generators import problem
from tensor2tensor.utils import registry
import tensorflow.compat.v1 ... | tensor2tensor/data_generators/ocr.py |
"""OCR."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import struct
from tensor2tensor.data_generators import image_utils
from tensor2tensor.data_generators import problem
from tensor2tensor.utils import registry
import tensorflow.compat.v1 ... | 0.801354 | 0.234593 |
from Gridworld import Gridworld
from MonteCarlo import MonteCarlo
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import csv
env = Gridworld(shape=[5,5], initialState=25)
print("------------------------------epsilon=0.01-------------------------------------")
MC_1 = MonteCarlo(grid_world = env,... | MonteCarlo_and_SARSA/run_MonteCarlo.py | from Gridworld import Gridworld
from MonteCarlo import MonteCarlo
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import csv
env = Gridworld(shape=[5,5], initialState=25)
print("------------------------------epsilon=0.01-------------------------------------")
MC_1 = MonteCarlo(grid_world = env,... | 0.390825 | 0.518424 |
from typing import AsyncGenerator, Tuple
import anyio
from p2pclient.libp2p_stubs.crypto.pb import crypto_pb2 as crypto_pb
from p2pclient.libp2p_stubs.peer.id import ID
from .control import DaemonConnector
from .datastructures import PeerInfo
from .exceptions import ControlFailure
from .pb import p2pd_pb2 as p2pd_pb
... | p2pclient/dht.py | from typing import AsyncGenerator, Tuple
import anyio
from p2pclient.libp2p_stubs.crypto.pb import crypto_pb2 as crypto_pb
from p2pclient.libp2p_stubs.peer.id import ID
from .control import DaemonConnector
from .datastructures import PeerInfo
from .exceptions import ControlFailure
from .pb import p2pd_pb2 as p2pd_pb
... | 0.52902 | 0.122655 |
SIMPLE = '''{% for item in seq %}{{ item }}{% endfor %}'''
ELSE = '''{% for item in seq %}XXX{% else %}...{% endfor %}'''
EMPTYBLOCKS = '''<{% for item in seq %}{% else %}{% endfor %}>'''
CONTEXTVARS = '''{% for item in seq %}\
{{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{
loop.revindex0 }}|{{ loop.first... | tests/test_forloop.py | SIMPLE = '''{% for item in seq %}{{ item }}{% endfor %}'''
ELSE = '''{% for item in seq %}XXX{% else %}...{% endfor %}'''
EMPTYBLOCKS = '''<{% for item in seq %}{% else %}{% endfor %}>'''
CONTEXTVARS = '''{% for item in seq %}\
{{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{
loop.revindex0 }}|{{ loop.first... | 0.386648 | 0.528229 |
import pandas as pd
import numpy as np
import tensorflow as tf
import os
import matplotlib.pyplot as plt
import seaborn as sns
import PIL
from typing import List
# EfficientNet
from tensorflow.keras.applications import EfficientNetB7, ResNet50
from tensorflow.keras.applications.efficientnet import preprocess_input
#... | big_model.py | import pandas as pd
import numpy as np
import tensorflow as tf
import os
import matplotlib.pyplot as plt
import seaborn as sns
import PIL
from typing import List
# EfficientNet
from tensorflow.keras.applications import EfficientNetB7, ResNet50
from tensorflow.keras.applications.efficientnet import preprocess_input
#... | 0.672117 | 0.378402 |
import sys
import os
import json
import math
def init_static(jsonfile, output_dir = ""):
with open(jsonfile, "r") as f:
plan = json.loads(f.read())
output = {}
tracks = []
static = []
for item in plan:
bbox = item['bbox']
x_offset = -(bbox[2]-bbox[0])/2 - bbox[0] #计算y轴位移
... | tools/generate/static_fixtures.py | import sys
import os
import json
import math
def init_static(jsonfile, output_dir = ""):
with open(jsonfile, "r") as f:
plan = json.loads(f.read())
output = {}
tracks = []
static = []
for item in plan:
bbox = item['bbox']
x_offset = -(bbox[2]-bbox[0])/2 - bbox[0] #计算y轴位移
... | 0.117547 | 0.197715 |
from __future__ import unicode_literals
from django import forms
from django.forms.models import model_to_dict
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest, JsonResponse
from django.views.generic import TemplateView
from django.core import serializers
from django.utils import ti... | server/turb/views.py | from __future__ import unicode_literals
from django import forms
from django.forms.models import model_to_dict
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest, JsonResponse
from django.views.generic import TemplateView
from django.core import serializers
from django.utils import ti... | 0.457137 | 0.328126 |
import copy
import datetime
import importlib
import verboselogs, logging
logger = verboselogs.VerboseLogger(__name__)
import random
import sys
from contextlib import contextmanager
import numpy as np
import pandas as pd
from sklearn.model_selection import ParameterGrid
from sqlalchemy.orm import sessionmaker
from ... | src/triage/component/catwalk/model_trainers.py | import copy
import datetime
import importlib
import verboselogs, logging
logger = verboselogs.VerboseLogger(__name__)
import random
import sys
from contextlib import contextmanager
import numpy as np
import pandas as pd
from sklearn.model_selection import ParameterGrid
from sqlalchemy.orm import sessionmaker
from ... | 0.638835 | 0.230065 |
# Lint as python3
"""Common configurable image manipulation methods for use in preprocessors."""
from typing import Callable, List, Optional, Sequence
import gin
from six.moves import zip
import tensorflow.compat.v1 as tf
def RandomCropImages(images, input_shape,
target_shape):
"""Crop a par... | preprocessors/image_transformations.py |
# Lint as python3
"""Common configurable image manipulation methods for use in preprocessors."""
from typing import Callable, List, Optional, Sequence
import gin
from six.moves import zip
import tensorflow.compat.v1 as tf
def RandomCropImages(images, input_shape,
target_shape):
"""Crop a par... | 0.964288 | 0.677275 |
"""Experimental Resolver for getting the latest artifact."""
from typing import Dict, List, Optional, Text
from tfx import types
from tfx.dsl.components.common import resolver
from tfx.orchestration import data_types
from tfx.orchestration import metadata
from tfx.types import artifact_utils
from tfx.utils import doc... | tfx/dsl/experimental/latest_artifacts_resolver.py | """Experimental Resolver for getting the latest artifact."""
from typing import Dict, List, Optional, Text
from tfx import types
from tfx.dsl.components.common import resolver
from tfx.orchestration import data_types
from tfx.orchestration import metadata
from tfx.types import artifact_utils
from tfx.utils import doc... | 0.836555 | 0.53607 |
import logging
from django.db.models import Q
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.contrib.contenttypes.fields import GenericForeignKeyField
from ... | scielomanager/api/resources_v1.py | import logging
from django.db.models import Q
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from tastypie.resources import ModelResource
from tastypie import fields
from tastypie.contrib.contenttypes.fields import GenericForeignKeyField
from ... | 0.593727 | 0.107907 |
import torch
import torch.nn as nn
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor, Compose, Resize, InterpolationMode
from mighty.loss import TripletLossSampler
from mighty.trainer import TrainerEmbedding, TrainerGrad
from mighty.utils.common import set_seed
from mighty.utils.data i... | nn/mnist.py | import torch
import torch.nn as nn
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensor, Compose, Resize, InterpolationMode
from mighty.loss import TripletLossSampler
from mighty.trainer import TrainerEmbedding, TrainerGrad
from mighty.utils.common import set_seed
from mighty.utils.data i... | 0.857515 | 0.435361 |
import numpy as np
import cirq
def test_inconclusive():
class No:
pass
assert not cirq.has_unitary(object())
assert not cirq.has_unitary('boo')
assert not cirq.has_unitary(No())
def test_via_unitary():
class No1:
def _unitary_(self):
return NotImplemented
c... | cirq/protocols/has_unitary_protocol_test.py |
import numpy as np
import cirq
def test_inconclusive():
class No:
pass
assert not cirq.has_unitary(object())
assert not cirq.has_unitary('boo')
assert not cirq.has_unitary(No())
def test_via_unitary():
class No1:
def _unitary_(self):
return NotImplemented
c... | 0.796609 | 0.709768 |
import warnings
import time
import sys
import os
import requests
from dateutil import parser
import datetime, time
from ....core.BaseAgent3 import BaseAgent
import json
class snowAgent(BaseAgent):
warnings.filterwarnings('ignore')
@BaseAgent.timed
def process(self):
self.baseLogger.info('Inside pr... | PlatformAgents/com/cognizant/devops/platformagents/agents/itsm/snow/snowAgent3.py | import warnings
import time
import sys
import os
import requests
from dateutil import parser
import datetime, time
from ....core.BaseAgent3 import BaseAgent
import json
class snowAgent(BaseAgent):
warnings.filterwarnings('ignore')
@BaseAgent.timed
def process(self):
self.baseLogger.info('Inside pr... | 0.082913 | 0.046249 |
import torch
from rlkit.torch.vpg.vpg import VPGTrainer
from rlkit.torch.optimizers import OptimizerWrapper
class PPOTrainer(VPGTrainer):
"""Proximal Policy Optimization (PPO).
Args:
policy (garage.torch.policies.Policy): Policy.
value_function (garage.torch.value_functions.ValueFunction): T... | rlkit/torch/vpg/ppo.py | import torch
from rlkit.torch.vpg.vpg import VPGTrainer
from rlkit.torch.optimizers import OptimizerWrapper
class PPOTrainer(VPGTrainer):
"""Proximal Policy Optimization (PPO).
Args:
policy (garage.torch.policies.Policy): Policy.
value_function (garage.torch.value_functions.ValueFunction): T... | 0.915606 | 0.446977 |
import re
from datetime import datetime
from typing import Optional, Tuple
from email_validator import EmailNotValidError, validate_email
from authx.backend.base import Base
class UsersCRUDMixin(Base):
"""User CRUD MIXIN"""
async def get(self, id: int) -> Optional[dict]:
"""
Get a user by i... | authx/backend/api/crud.py | import re
from datetime import datetime
from typing import Optional, Tuple
from email_validator import EmailNotValidError, validate_email
from authx.backend.base import Base
class UsersCRUDMixin(Base):
"""User CRUD MIXIN"""
async def get(self, id: int) -> Optional[dict]:
"""
Get a user by i... | 0.669745 | 0.124532 |
from __future__ import (absolute_import, print_function, unicode_literals,
with_statement)
import random
import zlib
from wolframclient.serializers.wxfencoder.streaming import (
ExactSizeReader, ZipCompressedReader, ZipCompressedWriter)
from wolframclient.utils import six
from wolframclie... | wolframclient/tests/serializers/wxf_compress.py |
from __future__ import (absolute_import, print_function, unicode_literals,
with_statement)
import random
import zlib
from wolframclient.serializers.wxfencoder.streaming import (
ExactSizeReader, ZipCompressedReader, ZipCompressedWriter)
from wolframclient.utils import six
from wolframclie... | 0.579162 | 0.32826 |
from pix2pix import pix2pix
import argparse
from utils import *
"""parsing and configuration"""
def parse_args():
desc = "Tensorflow implementation of jh_GAN"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--phase', type=str, default='train', help='train or test ?')
parser.add_... | main.py | from pix2pix import pix2pix
import argparse
from utils import *
"""parsing and configuration"""
def parse_args():
desc = "Tensorflow implementation of jh_GAN"
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('--phase', type=str, default='train', help='train or test ?')
parser.add_... | 0.553988 | 0.167185 |
import unittest
from binascii import unhexlify, hexlify
from pyelliptic import Cipher, OpenSSL
class TestCipher(unittest.TestCase):
@unittest.skipIf('aes-256-ctr' not in OpenSSL.cipher_algo,
'aes-256-ctr is not supported by the SSL library')
def test_aes256ctr(self):
ciphername ... | tests/test_cipher.py | import unittest
from binascii import unhexlify, hexlify
from pyelliptic import Cipher, OpenSSL
class TestCipher(unittest.TestCase):
@unittest.skipIf('aes-256-ctr' not in OpenSSL.cipher_algo,
'aes-256-ctr is not supported by the SSL library')
def test_aes256ctr(self):
ciphername ... | 0.499023 | 0.442396 |
import os
import sys
import fnmatch
import subprocess
## prepare to run PyTest as a command
from distutils.core import Command
from setuptools import setup, find_packages
from version import get_git_version
VERSION, SOURCE_LABEL = get_git_version()
PROJECT = 'streamcorpus_filter'
AUTHOR = 'Diffeo, Inc.'
AUTHOR_EMAI... | py/setup.py |
import os
import sys
import fnmatch
import subprocess
## prepare to run PyTest as a command
from distutils.core import Command
from setuptools import setup, find_packages
from version import get_git_version
VERSION, SOURCE_LABEL = get_git_version()
PROJECT = 'streamcorpus_filter'
AUTHOR = 'Diffeo, Inc.'
AUTHOR_EMAI... | 0.296858 | 0.124186 |
from spack import *
class Jsoncpp(CMakePackage):
"""JsonCpp is a C++ library that allows manipulating JSON values,
including serialization and deserialization to and from strings.
It can also preserve existing comment in unserialization/serialization
steps, making it a convenient format to store user... | var/spack/repos/builtin/packages/jsoncpp/package.py |
from spack import *
class Jsoncpp(CMakePackage):
"""JsonCpp is a C++ library that allows manipulating JSON values,
including serialization and deserialization to and from strings.
It can also preserve existing comment in unserialization/serialization
steps, making it a convenient format to store user... | 0.775265 | 0.314774 |
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from colour.plotting import CONSTANTS_COLOUR_STYLE, override_style, render
from colour.utilities import as_float_array
from colour_hdri.exposure import adjust_exposure
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2015-2021 - Colo... | colour_hdri/plotting/radiance.py | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from colour.plotting import CONSTANTS_COLOUR_STYLE, override_style, render
from colour.utilities import as_float_array
from colour_hdri.exposure import adjust_exposure
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2015-2021 - Colo... | 0.859855 | 0.361982 |
import tracta_ml.pool_maintenance as pm
import numpy as np
import collections
def converge(parents, best_parent):
mean_fitness = np.mean([i.fitness['fit_mod'] for i in parents])
best_fitness = best_parent.fitness['fit_mod']
return abs(best_fitness - mean_fitness)/mean_fitness
def model_tuner(... | tracta_ml/evolve.py | import tracta_ml.pool_maintenance as pm
import numpy as np
import collections
def converge(parents, best_parent):
mean_fitness = np.mean([i.fitness['fit_mod'] for i in parents])
best_fitness = best_parent.fitness['fit_mod']
return abs(best_fitness - mean_fitness)/mean_fitness
def model_tuner(... | 0.268654 | 0.283986 |
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from common import permissions
from .models import System, Station, Commodity, StationCommodity
from .serializers import CommoditySerializer, StationSerializer, \
SystemSerializer, MinimizedSystemSerializer, StationComm... | elitedata/views.py | from rest_framework.decorators import detail_route
from rest_framework.response import Response
from common import permissions
from .models import System, Station, Commodity, StationCommodity
from .serializers import CommoditySerializer, StationSerializer, \
SystemSerializer, MinimizedSystemSerializer, StationComm... | 0.733643 | 0.097777 |
import unittest
from bson import SON
from mongoengine import *
from mongoengine.pymongo_support import list_collection_names
from tests.utils import MongoDBTestCase
class TestDelta(MongoDBTestCase):
def setUp(self):
super(TestDelta, self).setUp()
class Person(Document):
name = String... | tests/document/test_delta.py | import unittest
from bson import SON
from mongoengine import *
from mongoengine.pymongo_support import list_collection_names
from tests.utils import MongoDBTestCase
class TestDelta(MongoDBTestCase):
def setUp(self):
super(TestDelta, self).setUp()
class Person(Document):
name = String... | 0.584864 | 0.429549 |
import socket
from test import resolvesLocalhostFQDN
from unittest.mock import patch
import pytest
from urllib3 import connection_from_url
from urllib3.exceptions import ClosedPoolError, LocationValueError
from urllib3.poolmanager import PoolKey, PoolManager, key_fn_by_scheme
from urllib3.util import retry, timeout
... | test/test_poolmanager.py | import socket
from test import resolvesLocalhostFQDN
from unittest.mock import patch
import pytest
from urllib3 import connection_from_url
from urllib3.exceptions import ClosedPoolError, LocationValueError
from urllib3.poolmanager import PoolKey, PoolManager, key_fn_by_scheme
from urllib3.util import retry, timeout
... | 0.63307 | 0.486941 |
# Analyze difference between two PALADIN alignemnts
import argparse
import shlex
import core.main
from core.datastore import DataStore
def plugin_connect(definition):
definition.name = "difference"
definition.description = "Analyze relative differences between two PALADIN taxonomy reports"
definition.ver... | plugins/difference.py | # Analyze difference between two PALADIN alignemnts
import argparse
import shlex
import core.main
from core.datastore import DataStore
def plugin_connect(definition):
definition.name = "difference"
definition.description = "Analyze relative differences between two PALADIN taxonomy reports"
definition.ver... | 0.518059 | 0.321141 |
class ListViewGroupCollection(object, IList, ICollection, IEnumerable):
""" Represents the collection of groups within a System.Windows.Forms.ListView control. """
def Add(self, *__args):
"""
Add(self: ListViewGroupCollection,key: str,headerText: str) -> ListViewGroup
Adds a new Syst... | release/stubs.min/System/Windows/Forms/__init___parts/ListViewGroupCollection.py | class ListViewGroupCollection(object, IList, ICollection, IEnumerable):
""" Represents the collection of groups within a System.Windows.Forms.ListView control. """
def Add(self, *__args):
"""
Add(self: ListViewGroupCollection,key: str,headerText: str) -> ListViewGroup
Adds a new Syst... | 0.776284 | 0.313492 |
from pyspedas.mms.mms_load_data import mms_load_data
from pyspedas.mms.print_vars import print_vars
@print_vars
def mms_load_aspoc(trange=['2015-10-16', '2015-10-17'], probe='1', data_rate='srvy',
level='l2', datatype='', varformat=None, varnames=[], get_support_data=False, suffix='', time_clip=False, no_update=F... | pyspedas/mms/aspoc/aspoc.py | from pyspedas.mms.mms_load_data import mms_load_data
from pyspedas.mms.print_vars import print_vars
@print_vars
def mms_load_aspoc(trange=['2015-10-16', '2015-10-17'], probe='1', data_rate='srvy',
level='l2', datatype='', varformat=None, varnames=[], get_support_data=False, suffix='', time_clip=False, no_update=F... | 0.634996 | 0.361841 |
from datetime import datetime, timedelta
from typing import Optional
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from .models import UserModel
from .sche... | fairy_note/auth.py | from datetime import datetime, timedelta
from typing import Optional
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from .models import UserModel
from .sche... | 0.723114 | 0.080864 |
"""API handler for rendering descriptors of GRR data structures."""
from grr.lib import rdfvalue
from grr.lib.rdfvalues import structs as rdf_structs
from grr_response_proto.api import reflection_pb2
from grr.server.grr_response_server import aff4
from grr.server.grr_response_server.gui import api_call_handler_base
... | grr/server/grr_response_server/gui/api_plugins/reflection.py | """API handler for rendering descriptors of GRR data structures."""
from grr.lib import rdfvalue
from grr.lib.rdfvalues import structs as rdf_structs
from grr_response_proto.api import reflection_pb2
from grr.server.grr_response_server import aff4
from grr.server.grr_response_server.gui import api_call_handler_base
... | 0.855021 | 0.156201 |
import numpy as np
import tensorflow as tf
import os
import cv2
from scipy.misc import imresize
from PIL import Image, ImageOps
import random
import sys
from sklearn.utils import shuffle
def crop_to_square(image, upsampling):
"""
Crop image to square
"""
if image.shape[0] == image.shape[1]:
ret... | utils.py | import numpy as np
import tensorflow as tf
import os
import cv2
from scipy.misc import imresize
from PIL import Image, ImageOps
import random
import sys
from sklearn.utils import shuffle
def crop_to_square(image, upsampling):
"""
Crop image to square
"""
if image.shape[0] == image.shape[1]:
ret... | 0.38943 | 0.409162 |
from __future__ import unicode_literals
from functools import reduce
from django.conf import settings
from django.conf.urls import include, url
from django.views.i18n import JavaScriptCatalog
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
from ckeditor_... | modoboa/urls.py | from __future__ import unicode_literals
from functools import reduce
from django.conf import settings
from django.conf.urls import include, url
from django.views.i18n import JavaScriptCatalog
from django.contrib.auth import views as auth_views
from django.contrib.auth.decorators import login_required
from ckeditor_... | 0.395951 | 0.06951 |
from darknet_config_generator.common import *
""" Learning Rate Decay Policies """
class ScheduledLRDecay:
"""
Learning rate decay policy
"""
def __init__(self, lr_decay_schedule={400000:0.1, 450000:0.1}):
self.__HEADER__= '# LR Policy'
self.policy = LearningRateDecayPolicy.SCHEDULED
... | darknet_config_generator/yolo_optimizers.py | from darknet_config_generator.common import *
""" Learning Rate Decay Policies """
class ScheduledLRDecay:
"""
Learning rate decay policy
"""
def __init__(self, lr_decay_schedule={400000:0.1, 450000:0.1}):
self.__HEADER__= '# LR Policy'
self.policy = LearningRateDecayPolicy.SCHEDULED
... | 0.84338 | 0.227662 |
# pylama: ignore=W0611
from exceptions import ImproperlyConfigured
import os
import dash_core_components as dcc
import dash_html_components as html
import plotly.plotly as py
import plotly.graph_objs as go
from flask import Flask
from dash import Dash
from dash.dependencies import Input, Output, State
from dotenv impo... | ccc_gui/app.py |
# pylama: ignore=W0611
from exceptions import ImproperlyConfigured
import os
import dash_core_components as dcc
import dash_html_components as html
import plotly.plotly as py
import plotly.graph_objs as go
from flask import Flask
from dash import Dash
from dash.dependencies import Input, Output, State
from dotenv impo... | 0.477311 | 0.120568 |
from abstract.instruccion import *
from tools.tabla_tipos import *
from tools.tabla_simbolos import *
from error.errores import *
from instruccion.P_Key import *
from tools.console_text import *
from storage import jsonMode as funciones
class altertb_drop(instruccion):
def __init__(self,alterdrop, ID, line, column... | parser/team23/instruccion/altertb_drop.py | from abstract.instruccion import *
from tools.tabla_tipos import *
from tools.tabla_simbolos import *
from error.errores import *
from instruccion.P_Key import *
from tools.console_text import *
from storage import jsonMode as funciones
class altertb_drop(instruccion):
def __init__(self,alterdrop, ID, line, column... | 0.24599 | 0.110447 |
import config
from utils import Utils
class Wenker:
@staticmethod
def create_transcribe_media(app, client):
req, resp = app.op['get_tasks'](limit=20000)
tasks = client.request((req, resp)).data
for t in tasks:
media = {
'source_id': '',
'path... | general/tasks_importer/wenker.py | import config
from utils import Utils
class Wenker:
@staticmethod
def create_transcribe_media(app, client):
req, resp = app.op['get_tasks'](limit=20000)
tasks = client.request((req, resp)).data
for t in tasks:
media = {
'source_id': '',
'path... | 0.128484 | 0.148973 |
import os
from telethon import events
from telethon.tl import functions
from uniborg.util import admin_cmd
@borg.on(admin_cmd("pbio (.*)")) # pylint:disable=E0602
async def _(event):
if event.fwd_from:
return
bio = event.pattern_match.group(1)
try:
await borg(functions.account.UpdateProf... | stdplugins/account_profile.py |
import os
from telethon import events
from telethon.tl import functions
from uniborg.util import admin_cmd
@borg.on(admin_cmd("pbio (.*)")) # pylint:disable=E0602
async def _(event):
if event.fwd_from:
return
bio = event.pattern_match.group(1)
try:
await borg(functions.account.UpdateProf... | 0.207375 | 0.076064 |
import logging
import random
import uuid
import time
import zmq
from include.functions_pb2 import *
from include.serializer import *
from include import server_utils as sutils
from include.shared import *
from . import utils
sys_random = random.SystemRandom()
def call_function(func_call_socket, pusher_cache, execu... | functions/scheduler/call.py |
import logging
import random
import uuid
import time
import zmq
from include.functions_pb2 import *
from include.serializer import *
from include import server_utils as sutils
from include.shared import *
from . import utils
sys_random = random.SystemRandom()
def call_function(func_call_socket, pusher_cache, execu... | 0.384219 | 0.173778 |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
import argparse
import os
from abc import ABC, abstractmethod
from datetime import datetime
from typing imp... | parlai/crowdsourcing/utils/analysis.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
import argparse
import os
from abc import ABC, abstractmethod
from datetime import datetime
from typing imp... | 0.76973 | 0.173533 |
from os import listdir, remove
from os.path import isdir, isfile
from pkg_resources import resource_filename, Requirement
from shutil import rmtree
from tempfile import TemporaryFile, TemporaryDirectory
from unittest import TestCase
import json
import search_google.api
class resultsTest(TestCase):
def setUp(self)... | search_google/tests/test_api_results.py |
from os import listdir, remove
from os.path import isdir, isfile
from pkg_resources import resource_filename, Requirement
from shutil import rmtree
from tempfile import TemporaryFile, TemporaryDirectory
from unittest import TestCase
import json
import search_google.api
class resultsTest(TestCase):
def setUp(self)... | 0.27914 | 0.249556 |
import sys
from io import BytesIO
import telegram
import youtube_dl
from flask import Flask, request, send_file
from fsm import TocMachine
import urllib.request
from urllib.request import urlopen
API_TOKEN = '356618024:AAElDMxCEDCCodg27fr-ewUtoNFmmruPi3s'
WEBHOOK_URL = 'https://07567b0d.ngrok.io/hook'
app = Fla... | app.py | import sys
from io import BytesIO
import telegram
import youtube_dl
from flask import Flask, request, send_file
from fsm import TocMachine
import urllib.request
from urllib.request import urlopen
API_TOKEN = '356618024:AAElDMxCEDCCodg27fr-ewUtoNFmmruPi3s'
WEBHOOK_URL = 'https://07567b0d.ngrok.io/hook'
app = Fla... | 0.18866 | 0.21158 |
import os
import torch
import cv2
import util.io
from glob import glob
from torchvision.transforms import Compose
from dpt.load_models import load_model
from dpt.transforms import Resize, PrepareForNet
def run(input_path,
model_path,
model_type="dpt_hybrid",
optimize=True,
save_p... | run_monodepth_cityscapes.py | import os
import torch
import cv2
import util.io
from glob import glob
from torchvision.transforms import Compose
from dpt.load_models import load_model
from dpt.transforms import Resize, PrepareForNet
def run(input_path,
model_path,
model_type="dpt_hybrid",
optimize=True,
save_p... | 0.717111 | 0.334263 |
import numpy as np
import gp.base as base
import gp.numeric as numeric
from gp.numeric import correlation_between_distinct_sets_from_covariance
from gp.moment_matching.numpy.moment_matching_minimum import (
calculate_cumulative_min_moments,
get_next_cumulative_min_moments,
)
class SequentialMomentMatchingEI(... | PyStationB/libraries/GlobalPenalisation/gp/moment_matching/numpy/api.py | import numpy as np
import gp.base as base
import gp.numeric as numeric
from gp.numeric import correlation_between_distinct_sets_from_covariance
from gp.moment_matching.numpy.moment_matching_minimum import (
calculate_cumulative_min_moments,
get_next_cumulative_min_moments,
)
class SequentialMomentMatchingEI(... | 0.87153 | 0.45538 |
import itertools
import datetime
from collections import defaultdict
import sqlalchemy as sa
from werkzeug import exceptions
from ggrc import db
from ggrc.models import relationship, inflector
from ggrc.rbac import permissions
from ggrc.services import signals
from ggrc.utils.log_event import log_event
# TODO: C... | src/ggrc/models/mixins/clonable.py | import itertools
import datetime
from collections import defaultdict
import sqlalchemy as sa
from werkzeug import exceptions
from ggrc import db
from ggrc.models import relationship, inflector
from ggrc.rbac import permissions
from ggrc.services import signals
from ggrc.utils.log_event import log_event
# TODO: C... | 0.428712 | 0.10904 |
from test_gc01 import test_gc_base
from wiredtiger import stat
from wtdataset import SimpleDataSet
# test_gc04.py
# Test that checkpoint must not clean the pages that are not obsolete.
class test_gc04(test_gc_base):
conn_config = 'cache_size=50MB,statistics=(all)'
def get_stat(self, stat):
stat_curso... | src/third_party/wiredtiger/test/suite/test_gc04.py |
from test_gc01 import test_gc_base
from wiredtiger import stat
from wtdataset import SimpleDataSet
# test_gc04.py
# Test that checkpoint must not clean the pages that are not obsolete.
class test_gc04(test_gc_base):
conn_config = 'cache_size=50MB,statistics=(all)'
def get_stat(self, stat):
stat_curso... | 0.671471 | 0.372648 |
from pipeline.c3dgenrator import *
from tensorflow.keras.layers import Input
from nets.extract_1 import *
from tensorflow.python.keras.engine.training import Model
from tensorflow.python.keras.layers.wrappers import TimeDistributed
from nets.RoiPoolingConv import *
from pipeline.SPN import *
from helper import losses
i... | Scipts/train_c3d.py | from pipeline.c3dgenrator import *
from tensorflow.keras.layers import Input
from nets.extract_1 import *
from tensorflow.python.keras.engine.training import Model
from tensorflow.python.keras.layers.wrappers import TimeDistributed
from nets.RoiPoolingConv import *
from pipeline.SPN import *
from helper import losses
i... | 0.81648 | 0.337777 |
"""Unit tests for check_grid_match function."""
import unittest
import numpy as np
from iris.tests import IrisTest
from improver.metadata.utilities import create_coordinate_hash
from improver.spotdata.build_spotdata_cube import build_spotdata_cube
from improver.spotdata.spot_extraction import check_grid_match
from ... | improver_tests/spotdata/spotdata/test_check_grid_match.py | """Unit tests for check_grid_match function."""
import unittest
import numpy as np
from iris.tests import IrisTest
from improver.metadata.utilities import create_coordinate_hash
from improver.spotdata.build_spotdata_cube import build_spotdata_cube
from improver.spotdata.spot_extraction import check_grid_match
from ... | 0.814717 | 0.621541 |
from root.config.main import sIze, np
from screws.freeze.main import FrozenOnly
class _3dCSCG_Mesh_DO_FIND(FrozenOnly):
def __init__(self, DO):
self._DO_ = DO
self._mesh_ = DO._mesh_
self._freeze_self_()
def region_name_of_element(self, i):
"""Find the regions of ith element.... | objects/CSCG/_3d/mesh/do/find.py | from root.config.main import sIze, np
from screws.freeze.main import FrozenOnly
class _3dCSCG_Mesh_DO_FIND(FrozenOnly):
def __init__(self, DO):
self._DO_ = DO
self._mesh_ = DO._mesh_
self._freeze_self_()
def region_name_of_element(self, i):
"""Find the regions of ith element.... | 0.676727 | 0.341596 |
"""Monitor learning rate during training."""
from composer.core import Callback, State
from composer.loggers import Logger
__all__ = ["LRMonitor"]
class LRMonitor(Callback):
"""Logs the learning rate.
This callback iterates over all optimizers and their parameter groups to log learning rate under the
`... | composer/callbacks/lr_monitor.py |
"""Monitor learning rate during training."""
from composer.core import Callback, State
from composer.loggers import Logger
__all__ = ["LRMonitor"]
class LRMonitor(Callback):
"""Logs the learning rate.
This callback iterates over all optimizers and their parameter groups to log learning rate under the
`... | 0.921825 | 0.36424 |
import argparse
from argparse import RawTextHelpFormatter
import subprocess
from subprocess import PIPE
import os, sys, time
import logging
import re
from . import filterGraph
def checkStatus(args):
if sys.version_info.major != 3:
logging.error('Please use Python3.x to run this pipeline.')
exit()
... | whdenovo/partition.py | import argparse
from argparse import RawTextHelpFormatter
import subprocess
from subprocess import PIPE
import os, sys, time
import logging
import re
from . import filterGraph
def checkStatus(args):
if sys.version_info.major != 3:
logging.error('Please use Python3.x to run this pipeline.')
exit()
... | 0.150185 | 0.058051 |
from collections import defaultdict
from itertools import product
N = 5
def evolve(grid):
new_grid = [l[:] for l in grid]
for x in range(N):
for y in range(N):
num_neighbors = 0
for nx, ny in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
if not (0 <= nx < N... | Day20-25/24.py | from collections import defaultdict
from itertools import product
N = 5
def evolve(grid):
new_grid = [l[:] for l in grid]
for x in range(N):
for y in range(N):
num_neighbors = 0
for nx, ny in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]:
if not (0 <= nx < N... | 0.560012 | 0.57069 |
import pytest
def test_client_setname(judge_command):
judge_command(
"CLIENT SETNAME foobar", {"command_value": "CLIENT SETNAME", "value": "foobar"}
)
def test_client_unblock(judge_command):
judge_command(
"CLIENT UNBLOCK 33 TIMEOUT",
{
"command_clientid_errorx": "CLI... | tests/command_parse/test_server.py | import pytest
def test_client_setname(judge_command):
judge_command(
"CLIENT SETNAME foobar", {"command_value": "CLIENT SETNAME", "value": "foobar"}
)
def test_client_unblock(judge_command):
judge_command(
"CLIENT UNBLOCK 33 TIMEOUT",
{
"command_clientid_errorx": "CLI... | 0.348978 | 0.205914 |
import textwrap
from nbsafety.data_model.code_cell import cells
from nbsafety.line_magics import _USAGE
from nbsafety.run_mode import FlowOrder, ExecutionMode, ExecutionSchedule
from nbsafety.singletons import kernel, nbs
from nbsafety.tracing.nbsafety_tracer import SafetyTracer
from test.utils import make_safety_fix... | test/test_line_magics.py | import textwrap
from nbsafety.data_model.code_cell import cells
from nbsafety.line_magics import _USAGE
from nbsafety.run_mode import FlowOrder, ExecutionMode, ExecutionSchedule
from nbsafety.singletons import kernel, nbs
from nbsafety.tracing.nbsafety_tracer import SafetyTracer
from test.utils import make_safety_fix... | 0.460289 | 0.405213 |
from requests_pkcs12 import Pkcs12Adapter
from pyravendb.commands.raven_commands import GetTopologyCommand, GetStatisticsCommand
from pyravendb.connection.requests_helpers import *
from pyravendb.custom_exceptions import exceptions
from OpenSSL import crypto
from pyravendb.data.document_conventions import DocumentConv... | pyravendb/connection/requests_executor.py | from requests_pkcs12 import Pkcs12Adapter
from pyravendb.commands.raven_commands import GetTopologyCommand, GetStatisticsCommand
from pyravendb.connection.requests_helpers import *
from pyravendb.custom_exceptions import exceptions
from OpenSSL import crypto
from pyravendb.data.document_conventions import DocumentConv... | 0.538498 | 0.080105 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import paddle
from .comfunc import rerange_index
class MSMLoss(paddle.nn.Layer):
"""
MSMLoss Loss, based on triplet loss. USE P * K samples.
the batch size is fixed. Batch_size = P * K; but the K... | paddlex/ppcls/loss/msmloss.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import paddle
from .comfunc import rerange_index
class MSMLoss(paddle.nn.Layer):
"""
MSMLoss Loss, based on triplet loss. USE P * K samples.
the batch size is fixed. Batch_size = P * K; but the K... | 0.836688 | 0.237233 |
import pybamm
import unittest
import numpy as np
class TestQuickPlot(unittest.TestCase):
def test_simple_ode_model(self):
model = pybamm.lithium_ion.BaseModel(name="Simple ODE Model")
whole_cell = ["negative electrode", "separator", "positive electrode"]
# Create variables: domain is expl... | tests/unit/test_quick_plot.py | import pybamm
import unittest
import numpy as np
class TestQuickPlot(unittest.TestCase):
def test_simple_ode_model(self):
model = pybamm.lithium_ion.BaseModel(name="Simple ODE Model")
whole_cell = ["negative electrode", "separator", "positive electrode"]
# Create variables: domain is expl... | 0.789315 | 0.764056 |
from math import ceil, log
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, bias_init_with_prob
from mmcv.ops import CornerPool, batched_nms
from mmdet.core import multi_apply
from ..builder import HEADS, build_loss
from ..utils import gaussian_radius, gen_gaussian_t... | mmdet/models/dense_heads/corner_head.py | from math import ceil, log
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, bias_init_with_prob
from mmcv.ops import CornerPool, batched_nms
from mmdet.core import multi_apply
from ..builder import HEADS, build_loss
from ..utils import gaussian_radius, gen_gaussian_t... | 0.962285 | 0.350005 |
import numpy as np
from alive_progress import alive_bar
from copy import copy
class neuroevolution:
def __init__(self, inshape, outshape, PopulationSize, model):
self.inshape, self.outshape, self.PopulationSize = inshape, outshape, PopulationSize
self.model = np.zeros((PopulationSize, len(model)), dtype... | testing/testsrc/neuroevolution.py | import numpy as np
from alive_progress import alive_bar
from copy import copy
class neuroevolution:
def __init__(self, inshape, outshape, PopulationSize, model):
self.inshape, self.outshape, self.PopulationSize = inshape, outshape, PopulationSize
self.model = np.zeros((PopulationSize, len(model)), dtype... | 0.491456 | 0.208682 |
import youtube_dl
import asyncio
import discord
import aiohttp
import re
youtube_dl.utils.bug_reports_message = lambda: ''
ydl = youtube_dl.YoutubeDL({"format": "bestaudio/best", "restrictfilenames": True, "noplaylist": True, "nocheckcertificate": True, "ignoreerrors": True, "logtostderr": False, "quiet": True, "no_wa... | DiscordUtils/Music.py | import youtube_dl
import asyncio
import discord
import aiohttp
import re
youtube_dl.utils.bug_reports_message = lambda: ''
ydl = youtube_dl.YoutubeDL({"format": "bestaudio/best", "restrictfilenames": True, "noplaylist": True, "nocheckcertificate": True, "ignoreerrors": True, "logtostderr": False, "quiet": True, "no_wa... | 0.389547 | 0.198899 |
__docformat__ = """epytext"""
__authors__ = """<NAME>"""
__copyright__ = """Copyright (C) 2011-2015 <NAME>"""
import math
import logging
import wx
from .spControl import spControl
from .channelctrl import ChannelCtrl, WavePreferences
# ---------------------------------------------------------------------------
... | sppas/sppas/src/ui/wxgui/ui/wavectrl.py |
__docformat__ = """epytext"""
__authors__ = """<NAME>"""
__copyright__ = """Copyright (C) 2011-2015 <NAME>"""
import math
import logging
import wx
from .spControl import spControl
from .channelctrl import ChannelCtrl, WavePreferences
# ---------------------------------------------------------------------------
... | 0.52342 | 0.196209 |
import inspect
import sys
import traceback
from collections import namedtuple
from queue import Queue
from threading import Lock, Thread
import stopit
from pypeln import utils as pypeln_utils
from . import utils
class Stage(pypeln_utils.BaseStage):
def __init__(self, f, on_start, on_done, dependencies, timeout... | pypeln/sync/stage.py | import inspect
import sys
import traceback
from collections import namedtuple
from queue import Queue
from threading import Lock, Thread
import stopit
from pypeln import utils as pypeln_utils
from . import utils
class Stage(pypeln_utils.BaseStage):
def __init__(self, f, on_start, on_done, dependencies, timeout... | 0.247351 | 0.084078 |
from time import sleep
class Text:
def animated_text(self,text):
for i in text:
print(i,end="",flush=True)
sleep(0.050)
print()
def logintext(self):
text = """
Welcome to EasytoMan , abbr. of Easy to Manipulate, this tool helps in creating & hiding securit... | texts.py |
from time import sleep
class Text:
def animated_text(self,text):
for i in text:
print(i,end="",flush=True)
sleep(0.050)
print()
def logintext(self):
text = """
Welcome to EasytoMan , abbr. of Easy to Manipulate, this tool helps in creating & hiding securit... | 0.258794 | 0.292557 |
from cStringIO import StringIO
import json
import unittest
from zipfile import ZipFile
from compiled_file_system import CompiledFileSystem
from content_provider import ContentProvider
from file_system import FileNotFoundError
from object_store_creator import ObjectStoreCreator
from path_canonicalizer import PathCanon... | chrome/common/extensions/docs/server2/content_provider_test.py |
from cStringIO import StringIO
import json
import unittest
from zipfile import ZipFile
from compiled_file_system import CompiledFileSystem
from content_provider import ContentProvider
from file_system import FileNotFoundError
from object_store_creator import ObjectStoreCreator
from path_canonicalizer import PathCanon... | 0.308503 | 0.231202 |
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import annotations
import logging # isort:skip
log = logging.getLogger(__name__)
#------------------------------------------------... | bokeh/server/connection.py | #-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import annotations
import logging # isort:skip
log = logging.getLogger(__name__)
#------------------------------------------------... | 0.644449 | 0.0809 |
from typing import Optional, List, Dict
from torch_geometric.typing import Adj, OptTensor
import torch
from torch import Tensor
from torch.nn import ModuleList, Sequential, Linear, ReLU
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.inits import reset
from torch_geometric.utils import degre... | comparison_methods/PNA/pna.py | from typing import Optional, List, Dict
from torch_geometric.typing import Adj, OptTensor
import torch
from torch import Tensor
from torch.nn import ModuleList, Sequential, Linear, ReLU
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.nn.inits import reset
from torch_geometric.utils import degre... | 0.964035 | 0.671329 |
from view.modes import NormalMode, EditMode
import curses
import logging
log = logging.getLogger("wfcli")
class LateralCursor:
def __init__(self):
self._index = float("-Inf")
self.allowed_offset = 0
def align_cursor(self, current_node):
if self._index != self.in_line(current_node):
... | view/view.py | from view.modes import NormalMode, EditMode
import curses
import logging
log = logging.getLogger("wfcli")
class LateralCursor:
def __init__(self):
self._index = float("-Inf")
self.allowed_offset = 0
def align_cursor(self, current_node):
if self._index != self.in_line(current_node):
... | 0.646349 | 0.157105 |
import numpy as np
import pytest
import aesara
import aesara.sandbox.rng_mrg
from aesara import gpuarray
from aesara import tensor as aet
from aesara.gpuarray.basic_ops import GpuFromHost, HostFromGpu
from aesara.gpuarray.elemwise import GpuElemwise
from aesara.scan.basic import scan
from aesara.scan.checkpoints impor... | tests/gpuarray/test_scan.py | import numpy as np
import pytest
import aesara
import aesara.sandbox.rng_mrg
from aesara import gpuarray
from aesara import tensor as aet
from aesara.gpuarray.basic_ops import GpuFromHost, HostFromGpu
from aesara.gpuarray.elemwise import GpuElemwise
from aesara.scan.basic import scan
from aesara.scan.checkpoints impor... | 0.703651 | 0.542742 |
from tests.util import yasha_cli
from pathlib import Path
import pytest
def test_string(with_tmp_path):
Path('template.j2').write_text("{{ var is string }}, {{ var }}")
yasha_cli('--var=foo template.j2')
assert Path('template').read_text() == 'True, foo'
yasha_cli("--var='foo' template.j2")
... | tests/test_template_variables.py | from tests.util import yasha_cli
from pathlib import Path
import pytest
def test_string(with_tmp_path):
Path('template.j2').write_text("{{ var is string }}, {{ var }}")
yasha_cli('--var=foo template.j2')
assert Path('template').read_text() == 'True, foo'
yasha_cli("--var='foo' template.j2")
... | 0.482673 | 0.36659 |
import pathlib
from lingpy import tokens2class, prosodic_string
from lingpy.align.sca import get_consensus
from lingpy import basictypes as bt
def lingrex_path(*comps):
return str(pathlib.Path(__file__).parent.joinpath(*comps))
def add_structure(
wordlist, model="cv", segments="tokens", structure="structur... | src/lingrex/util.py | import pathlib
from lingpy import tokens2class, prosodic_string
from lingpy.align.sca import get_consensus
from lingpy import basictypes as bt
def lingrex_path(*comps):
return str(pathlib.Path(__file__).parent.joinpath(*comps))
def add_structure(
wordlist, model="cv", segments="tokens", structure="structur... | 0.293303 | 0.394376 |
"""Linear Gaussian State Space Model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability.python.distributions.linear_gaussian_s... | tensorflow_probability/python/distributions/linear_gaussian_ssm_test.py | """Linear Gaussian State Space Model."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from tensorflow_probability.python.distributions.linear_gaussian_s... | 0.926058 | 0.571348 |
import math
from typing import Tuple
import numpy as np
from examples.PolicyGradient.TestRigs.Interface.RewardFunction1D import RewardFunction1D
"""
This Reward Function has two local maxima and one global maxima. This is modelled as 2.5 cycles
of a sinusoidal curve with the 2nd (central) peek weighed as give it a l... | examples/PolicyGradient/TestRigs/RewardFunctions/LocalMaximaRewardFunction1D.py | import math
from typing import Tuple
import numpy as np
from examples.PolicyGradient.TestRigs.Interface.RewardFunction1D import RewardFunction1D
"""
This Reward Function has two local maxima and one global maxima. This is modelled as 2.5 cycles
of a sinusoidal curve with the 2nd (central) peek weighed as give it a l... | 0.920191 | 0.791942 |
from numpy import all, abs
from overloads import hstack
from FDmisc import FuncDesignerException
def d(arg, v, **kw):#, *args, **kw):
N = len(v)
# if len(args) == 1:
# derivativeSide = args[0]
# assert derivativeSide in ('left', 'right', 'both')
# else:
# derivativeSide = 'both'
sten... | lib/python2.7/site-packages/FuncDesigner/stencils.py | from numpy import all, abs
from overloads import hstack
from FDmisc import FuncDesignerException
def d(arg, v, **kw):#, *args, **kw):
N = len(v)
# if len(args) == 1:
# derivativeSide = args[0]
# assert derivativeSide in ('left', 'right', 'both')
# else:
# derivativeSide = 'both'
sten... | 0.186206 | 0.332744 |
__version__ = "3.7.4.post11"
from typing import Tuple
from . import hdrs as hdrs
from .client import (
BaseConnector as BaseConnector,
ClientConnectionError as ClientConnectionError,
ClientConnectorCertificateError as ClientConnectorCertificateError,
ClientConnectorError as ClientConnectorError,
C... | aiohttp/__init__.py | __version__ = "3.7.4.post11"
from typing import Tuple
from . import hdrs as hdrs
from .client import (
BaseConnector as BaseConnector,
ClientConnectionError as ClientConnectionError,
ClientConnectorCertificateError as ClientConnectorCertificateError,
ClientConnectorError as ClientConnectorError,
C... | 0.507324 | 0.052887 |
import argparse, gzip, sys
sys.path.insert(0,'.')
from collections import defaultdict
import numpy as np
from Bio.SeqIO.FastaIO import SimpleFastaParser
from Bio.Seq import Seq
from Bio import AlignIO, SeqIO
from get_distance_to_focal_set import sequence_to_int_array
from augur.utils import read_metadata
from datetime ... | scripts/diagnostic.py | import argparse, gzip, sys
sys.path.insert(0,'.')
from collections import defaultdict
import numpy as np
from Bio.SeqIO.FastaIO import SimpleFastaParser
from Bio.Seq import Seq
from Bio import AlignIO, SeqIO
from get_distance_to_focal_set import sequence_to_int_array
from augur.utils import read_metadata
from datetime ... | 0.318167 | 0.346749 |
import os
import json
import uuid
from collections import deque
from typing import Dict, Union, Tuple, Optional, Callable
from base58 import b58decode, b58encode
from plenum.client.client import Client as PlenumClient
from plenum.common.error import fault
from plenum.common.txn_util import get_type
from stp_core.comm... | indy_client/client/client.py | import os
import json
import uuid
from collections import deque
from typing import Dict, Union, Tuple, Optional, Callable
from base58 import b58decode, b58encode
from plenum.client.client import Client as PlenumClient
from plenum.common.error import fault
from plenum.common.txn_util import get_type
from stp_core.comm... | 0.562417 | 0.098686 |
import re
import os
import sublime
import sublime_plugin
DEBUG = False
def debug_message(message):
if not DEBUG:
pass
print('DEBUG phpunitkit: %s' % str(message))
class PluginSettings():
def __init__(self, name):
self.name = name
self.loaded = False
self.transient_data =... | plugin.py | import re
import os
import sublime
import sublime_plugin
DEBUG = False
def debug_message(message):
if not DEBUG:
pass
print('DEBUG phpunitkit: %s' % str(message))
class PluginSettings():
def __init__(self, name):
self.name = name
self.loaded = False
self.transient_data =... | 0.401923 | 0.074097 |
import string
import random
from datetime import datetime
from hashlib import blake2b as blake
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
ENCODE_KEY = string.digits + string.ascii_letters
NEGATIVE_SYMBOL = "Z"
def create_random_string(n: int) -> str:
return ''.join(random.choices(string.asci... | util.py | import string
import random
from datetime import datetime
from hashlib import blake2b as blake
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
ENCODE_KEY = string.digits + string.ascii_letters
NEGATIVE_SYMBOL = "Z"
def create_random_string(n: int) -> str:
return ''.join(random.choices(string.asci... | 0.53607 | 0.206154 |
import io
import os
import time
import gym
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
from datetime import datetime
from threading import Thread
from rl_visualization.app import start_app
from math ... | rl_visualization/visualization_env.py | import io
import os
import time
import gym
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
from datetime import datetime
from threading import Thread
from rl_visualization.app import start_app
from math ... | 0.596903 | 0.304701 |
import json
import requests
import warnings
import html
import re
warnings.filterwarnings('always', '.*', PendingDeprecationWarning)
class HTTPException(Exception):
def __init__(self, response):
"""
Custom exception class to report possible API errors
The body is contructed by extracting ... | modules/vectra.py | import json
import requests
import warnings
import html
import re
warnings.filterwarnings('always', '.*', PendingDeprecationWarning)
class HTTPException(Exception):
def __init__(self, response):
"""
Custom exception class to report possible API errors
The body is contructed by extracting ... | 0.594551 | 0.14627 |
"""API module to serve cluster host service calls."""
import datetime
import endpoints
from protorpc import message_types
from protorpc import messages
from protorpc import remote
from tradefed_cluster.util import ndb_shim as ndb
from tradefed_cluster import api_common
from tradefed_cluster import api_messages
from... | tradefed_cluster/cluster_host_api.py | """API module to serve cluster host service calls."""
import datetime
import endpoints
from protorpc import message_types
from protorpc import messages
from protorpc import remote
from tradefed_cluster.util import ndb_shim as ndb
from tradefed_cluster import api_common
from tradefed_cluster import api_messages
from... | 0.613005 | 0.152505 |
from nicos.core import Attach, HasTimeout, Moveable, Override, PositionError, \
Readable, oneof, status
class SR7Shutter(HasTimeout, Moveable):
"""Class for the PUMA secondary shutter."""
attached_devices = {
'sr7cl': Attach('status of SR7 shutter closed/open', Readable),
'sr7p1': Attach(... | nicos_mlz/puma/devices/sr7.py | from nicos.core import Attach, HasTimeout, Moveable, Override, PositionError, \
Readable, oneof, status
class SR7Shutter(HasTimeout, Moveable):
"""Class for the PUMA secondary shutter."""
attached_devices = {
'sr7cl': Attach('status of SR7 shutter closed/open', Readable),
'sr7p1': Attach(... | 0.573798 | 0.266724 |
import json
import warnings
import kulado
import kulado.runtime
from .. import utilities, tables
class OutputMssql(kulado.CustomResource):
database: kulado.Output[str]
name: kulado.Output[str]
"""
The name of the Stream Output. Changing this forces a new resource to be created.
"""
password: k... | sdk/python/kulado_azure/streamanalytics/output_mssql.py |
import json
import warnings
import kulado
import kulado.runtime
from .. import utilities, tables
class OutputMssql(kulado.CustomResource):
database: kulado.Output[str]
name: kulado.Output[str]
"""
The name of the Stream Output. Changing this forces a new resource to be created.
"""
password: k... | 0.580828 | 0.224586 |
import matplotlib as plb
plb.use('Agg')
# python3 compareClock.py --standard /data/acs/pea/example/EX03/standard/igs20624.clk --test /data/acs/pea/example/EX03/standard/aus20624.clk
from matplotlib import rcParams
import matplotlib.pyplot as plt
import numpy as np
import os
from pathlib import Path
import math
from nu... | scripts/backup_old/pppPlot.py | import matplotlib as plb
plb.use('Agg')
# python3 compareClock.py --standard /data/acs/pea/example/EX03/standard/igs20624.clk --test /data/acs/pea/example/EX03/standard/aus20624.clk
from matplotlib import rcParams
import matplotlib.pyplot as plt
import numpy as np
import os
from pathlib import Path
import math
from nu... | 0.304559 | 0.434041 |
from barbican.common import utils
from barbican.plugin.interface import certificate_manager as cert
LOG = utils.getLogger(__name__)
MSEC_UNTIL_CHECK_STATUS = 5000
class SimpleCertificatePlugin(cert.CertificatePluginBase):
"""Simple/default certificate plugin."""
def get_default_ca_name(self):
retu... | barbican/plugin/simple_certificate_manager.py | from barbican.common import utils
from barbican.plugin.interface import certificate_manager as cert
LOG = utils.getLogger(__name__)
MSEC_UNTIL_CHECK_STATUS = 5000
class SimpleCertificatePlugin(cert.CertificatePluginBase):
"""Simple/default certificate plugin."""
def get_default_ca_name(self):
retu... | 0.824037 | 0.347454 |
from __future__ import print_function
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode
from pyspark.sql.functions import split, desc, col
from pyspark.sql.types import StructType
if __name__ == "__main__":
"""if len(sys.argv) != 3:
print("Usage: structured_network... | adminmgr/media/code/A3/task2/BD_275_950_1346.py | from __future__ import print_function
import sys
from pyspark.sql import SparkSession
from pyspark.sql.functions import explode
from pyspark.sql.functions import split, desc, col
from pyspark.sql.types import StructType
if __name__ == "__main__":
"""if len(sys.argv) != 3:
print("Usage: structured_network... | 0.326701 | 0.164114 |
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.MultiCurrencyMoneyOpenApi import MultiCurrencyMoneyOpenApi
from alipay.aop.api.domain.MultiCurrencyMoneyOpenApi import MultiCurrencyMoneyOpenApi
class WriteOffLeftRightDetailOpenApiDTO(object):
def __init__(self):
... | alipay/aop/api/domain/WriteOffLeftRightDetailOpenApiDTO.py | import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.MultiCurrencyMoneyOpenApi import MultiCurrencyMoneyOpenApi
from alipay.aop.api.domain.MultiCurrencyMoneyOpenApi import MultiCurrencyMoneyOpenApi
class WriteOffLeftRightDetailOpenApiDTO(object):
def __init__(self):
... | 0.678647 | 0.193967 |
from Firefly import logging
from Firefly.components.zwave.device_types.switch import ZwaveSwitch
from Firefly.const import ACTION_OFF, ACTION_ON, SWITCH
from Firefly.services.alexa.alexa_const import ALEXA_SMARTPLUG
TITLE = 'Aeotec Smart Switch 5'
BATTERY = 'battery'
ALARM = 'alarm'
POWER_METER = 'power_meter'
VOLTAG... | Firefly/components/zwave/aeotec/dsc06106_smart_energy_switch.py | from Firefly import logging
from Firefly.components.zwave.device_types.switch import ZwaveSwitch
from Firefly.const import ACTION_OFF, ACTION_ON, SWITCH
from Firefly.services.alexa.alexa_const import ALEXA_SMARTPLUG
TITLE = 'Aeotec Smart Switch 5'
BATTERY = 'battery'
ALARM = 'alarm'
POWER_METER = 'power_meter'
VOLTAG... | 0.449876 | 0.169097 |
import asyncio
import binascii
from collections import OrderedDict
import copy
import logging
import RFXtrx as rfxtrxmod
import async_timeout
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.binary_sensor import DEVICE_CLASSES_SCHEMA
from homeassistant.const import (
... | homeassistant/components/rfxtrx/__init__.py | import asyncio
import binascii
from collections import OrderedDict
import copy
import logging
import RFXtrx as rfxtrxmod
import async_timeout
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components.binary_sensor import DEVICE_CLASSES_SCHEMA
from homeassistant.const import (
... | 0.437103 | 0.12416 |
from .. import tf
from ..Arch import Discriminator
from ..Framework.GAN import loss_bce_gan
from ..Framework.SuperResolution import SuperResolution
from ..Util import Vgg, prelu
def _normalize(x):
return x / 127.5 - 1
def _denormalize(x):
return (x + 1) * 127.5
def _clip(image):
return tf.cast(tf.clip_by_va... | VSR/Backend/TF/Models/SrGan.py | from .. import tf
from ..Arch import Discriminator
from ..Framework.GAN import loss_bce_gan
from ..Framework.SuperResolution import SuperResolution
from ..Util import Vgg, prelu
def _normalize(x):
return x / 127.5 - 1
def _denormalize(x):
return (x + 1) * 127.5
def _clip(image):
return tf.cast(tf.clip_by_va... | 0.897367 | 0.233357 |
import tensorflow as tf
import numpy as np
import os
import random
def _single_process(image, label, specs, cropped_size):
"""Map function to process single instance of dataset object.
Args:
image: numpy array image object, (28, 28), 0 ~ 255 uint8;
label: numpy array label, (,);
spec... | input_data/mnist/mnist_input.py | import tensorflow as tf
import numpy as np
import os
import random
def _single_process(image, label, specs, cropped_size):
"""Map function to process single instance of dataset object.
Args:
image: numpy array image object, (28, 28), 0 ~ 255 uint8;
label: numpy array label, (,);
spec... | 0.835517 | 0.507324 |
import unittest
from controller.array_action import errors
from controller.array_action.svc_cli_result_reader import SVCListResultsReader
host_1 = "\n".join(("id 1", "name host_1", "WWPN wwpn1", "protocol fc", "WWPN wwpn2"))
host_2 = "\n".join(("id 2", "name host_2", "", " ", "iscsi", "status not active"))
host_3... | controller/tests/array_action/svc/svc_cli_result_reader_test.py | import unittest
from controller.array_action import errors
from controller.array_action.svc_cli_result_reader import SVCListResultsReader
host_1 = "\n".join(("id 1", "name host_1", "WWPN wwpn1", "protocol fc", "WWPN wwpn2"))
host_2 = "\n".join(("id 2", "name host_2", "", " ", "iscsi", "status not active"))
host_3... | 0.477067 | 0.377828 |
import unittest
from protein_inference.problem_network import ProblemNetwork
import networkx as nx
class ProblemNetworkTest(unittest.TestCase):
def test_get_proteins_several(self):
g = nx.Graph()
g.add_nodes_from([1,2,3], protein = 1)
pn = ProblemNetwork(g)
self.assertEq... | tests/unit/problem_network_test.py | import unittest
from protein_inference.problem_network import ProblemNetwork
import networkx as nx
class ProblemNetworkTest(unittest.TestCase):
def test_get_proteins_several(self):
g = nx.Graph()
g.add_nodes_from([1,2,3], protein = 1)
pn = ProblemNetwork(g)
self.assertEq... | 0.443118 | 0.647687 |
import torch
from UnarySim.stream.gen import RNG, SourceGen, BSGen
class FSUHardtanh(torch.nn.Identity):
"""
This module is used for inference in unary domain.
"""
def __init__(self):
super(FSUHardtanh, self).__init__()
class ScaleHardtanh(torch.nn.Hardtanh):
"""
Inputs within range ... | kernel/tanh.py | import torch
from UnarySim.stream.gen import RNG, SourceGen, BSGen
class FSUHardtanh(torch.nn.Identity):
"""
This module is used for inference in unary domain.
"""
def __init__(self):
super(FSUHardtanh, self).__init__()
class ScaleHardtanh(torch.nn.Hardtanh):
"""
Inputs within range ... | 0.892815 | 0.415551 |
from collections import namedtuple
import struct
import sys
from natsort import natsorted, ns
import re
import os
import pandas as pd
from . import firmware_gen as lf
import json
import aditofpython as tof
import tof_calib.device as device
import logging
import logging.config
import numpy as np
def setup_logging():
... | tools/calibration-96tof1/cal_eeprom/cal_eeprom.py | from collections import namedtuple
import struct
import sys
from natsort import natsorted, ns
import re
import os
import pandas as pd
from . import firmware_gen as lf
import json
import aditofpython as tof
import tof_calib.device as device
import logging
import logging.config
import numpy as np
def setup_logging():
... | 0.289673 | 0.188903 |