code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import asyncio
from asyncio.futures import Future
from collections import defaultdict
from typing import Dict, Any, List, Optional, Set, Tuple
import ray
import ray.cloudpickle as pickle
from ray.actor import ActorHandle
from ray.serve.config import BackendConfig
from ray.serve.exceptions import RayServeException
from... | python/ray/serve/backend_state.py | import asyncio
from asyncio.futures import Future
from collections import defaultdict
from typing import Dict, Any, List, Optional, Set, Tuple
import ray
import ray.cloudpickle as pickle
from ray.actor import ActorHandle
from ray.serve.config import BackendConfig
from ray.serve.exceptions import RayServeException
from... | 0.86332 | 0.105027 |
from . import cntk_py
from .device import use_default_device
from .utils import sanitize_var_map, sanitize_function, typemap, value_to_seq
__doc__= '''\
A trainer encapsulates the overall training process and employs one or more
:doc:`learners <cntk.learner>` to tune the parameters of a specified model
using gradient... | bindings/python/cntk/trainer.py |
from . import cntk_py
from .device import use_default_device
from .utils import sanitize_var_map, sanitize_function, typemap, value_to_seq
__doc__= '''\
A trainer encapsulates the overall training process and employs one or more
:doc:`learners <cntk.learner>` to tune the parameters of a specified model
using gradient... | 0.873943 | 0.709722 |
import logging
from contextlib import closing
from typing import Iterable
import chembl_downloader
from pyobo.struct import Obo, Reference, Term
__all__ = [
"ChEMBLCompoundGetter",
]
logger = logging.getLogger(__name__)
PREFIX = "chembl.compound"
QUERY = """\
SELECT
MOLECULE_DICTIONARY.chembl_id,
MOLE... | src/pyobo/sources/chembl.py | import logging
from contextlib import closing
from typing import Iterable
import chembl_downloader
from pyobo.struct import Obo, Reference, Term
__all__ = [
"ChEMBLCompoundGetter",
]
logger = logging.getLogger(__name__)
PREFIX = "chembl.compound"
QUERY = """\
SELECT
MOLECULE_DICTIONARY.chembl_id,
MOLE... | 0.371707 | 0.10793 |
import json
import requests
import base64
import re
import csv
from django.views import View
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q, Max
from django.db import transaction
from django.utils ... | api/exporter/views.py | import json
import requests
import base64
import re
import csv
from django.views import View
from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q, Max
from django.db import transaction
from django.utils ... | 0.290679 | 0.06724 |
from typing import Any, Dict, List, Optional, Sequence, Set, Union
import numpy
from . import _vroom
from .amount import Amount
from .location import Location, LocationCoordinates, LocationIndex
from .time_window import TimeWindow
class JobBaseclass:
"""Baseclass for all Job classes containing common attribute... | src/vroom/job.py | from typing import Any, Dict, List, Optional, Sequence, Set, Union
import numpy
from . import _vroom
from .amount import Amount
from .location import Location, LocationCoordinates, LocationIndex
from .time_window import TimeWindow
class JobBaseclass:
"""Baseclass for all Job classes containing common attribute... | 0.956786 | 0.284092 |
import json
from datetime import datetime
import os
import csv
from anomaly_detector import detect_anomaly
import pandas as pd
import numpy as np
import util
import warnings
warnings.filterwarnings("ignore")
DOCKBEAT_DIR="/tmp/dockbeat"
DATASET_DIR="/tmp/anomaly_dataset/"
data_files = ["cpu_dataset.csv", "network_rx_... | depracated/anomaly_detection_files/parse_dockbeat.py | import json
from datetime import datetime
import os
import csv
from anomaly_detector import detect_anomaly
import pandas as pd
import numpy as np
import util
import warnings
warnings.filterwarnings("ignore")
DOCKBEAT_DIR="/tmp/dockbeat"
DATASET_DIR="/tmp/anomaly_dataset/"
data_files = ["cpu_dataset.csv", "network_rx_... | 0.147248 | 0.135518 |
import sys
import numpy as np
import scipy as sp
import scipy.stats as stats
from numpy import (
arange,
array,
asanyarray,
asarray,
diag,
exp,
isscalar,
log,
ndarray,
ones,
vstack,
zeros,
)
from numpy.linalg import norm
from scipy.special import gammaln, polygamma, psi
... | src/direchlet_mle.py |
import sys
import numpy as np
import scipy as sp
import scipy.stats as stats
from numpy import (
arange,
array,
asanyarray,
asarray,
diag,
exp,
isscalar,
log,
ndarray,
ones,
vstack,
zeros,
)
from numpy.linalg import norm
from scipy.special import gammaln, polygamma, psi
... | 0.766556 | 0.62601 |
"""Tests for the CLI argument helper interface."""
from __future__ import unicode_literals
import locale
import sys
import unittest
from plaso.lib import errors
from tests.cli import test_lib as cli_test_lib
from tests.cli.helpers import test_lib
class HelperManagerTest(unittest.TestCase):
"""Tests the parsers ... | tests/cli/helpers/interface.py | """Tests for the CLI argument helper interface."""
from __future__ import unicode_literals
import locale
import sys
import unittest
from plaso.lib import errors
from tests.cli import test_lib as cli_test_lib
from tests.cli.helpers import test_lib
class HelperManagerTest(unittest.TestCase):
"""Tests the parsers ... | 0.647687 | 0.587115 |
import numpy as np
import rayoptics.seq.medium as mdm
import rayoptics.elem.profiles as profiles
import rayoptics.elem.surface as surface
from rayoptics.optical.model_enums import DecenterType as dec
def apply_fct_to_sm(opt_model, fct, start=None, stop=None, step=None):
"""Iterate in reverse over seq_model.ifcs. ... | src/rayoptics/zemax/zmx2ro.py | import numpy as np
import rayoptics.seq.medium as mdm
import rayoptics.elem.profiles as profiles
import rayoptics.elem.surface as surface
from rayoptics.optical.model_enums import DecenterType as dec
def apply_fct_to_sm(opt_model, fct, start=None, stop=None, step=None):
"""Iterate in reverse over seq_model.ifcs. ... | 0.648466 | 0.236676 |
from __future__ import print_function
import collections
import json
import operator
import os
import packaging.markers
import packaging.requirements
import packaging.specifiers
import packaging.utils
import packaging.version
import pytest
from resolvelib import AbstractProvider, ResolutionImpossible, Resolver
Can... | tests/functional/python/test_resolvers_python.py | from __future__ import print_function
import collections
import json
import operator
import os
import packaging.markers
import packaging.requirements
import packaging.specifiers
import packaging.utils
import packaging.version
import pytest
from resolvelib import AbstractProvider, ResolutionImpossible, Resolver
Can... | 0.618089 | 0.16132 |
from __future__ import absolute_import, unicode_literals
from django import forms
from django.utils.safestring import mark_safe
from django.utils.timezone import now
from pagedown.widgets import PagedownWidget
from junction.base.constants import (
ConferenceSettingConstants,
ProposalReviewerComment,
Propo... | junction/proposals/forms.py | from __future__ import absolute_import, unicode_literals
from django import forms
from django.utils.safestring import mark_safe
from django.utils.timezone import now
from pagedown.widgets import PagedownWidget
from junction.base.constants import (
ConferenceSettingConstants,
ProposalReviewerComment,
Propo... | 0.527073 | 0.16848 |
import uuid
from abc import abstractmethod
from typing import Dict, List, Optional, Union
import great_expectations.exceptions as ge_exceptions
from great_expectations import DataContext
from great_expectations.core.batch import Batch, BatchRequest
from great_expectations.rule_based_profiler.domain_builder.domain impo... | great_expectations/rule_based_profiler/parameter_builder/multi_batch_parameter_builder.py | import uuid
from abc import abstractmethod
from typing import Dict, List, Optional, Union
import great_expectations.exceptions as ge_exceptions
from great_expectations import DataContext
from great_expectations.core.batch import Batch, BatchRequest
from great_expectations.rule_based_profiler.domain_builder.domain impo... | 0.896954 | 0.435001 |
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
""" Statistics history task
Fetch information from the statistics table, compute delta and
stores the delta value (statistics.value - statistics.previous_value) in the statistics_history table
"""
import json
from foglamp.common.storage_client.payl... | python/foglamp/tasks/statistics/statistics_history.py |
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
""" Statistics history task
Fetch information from the statistics table, compute delta and
stores the delta value (statistics.value - statistics.previous_value) in the statistics_history table
"""
import json
from foglamp.common.storage_client.payl... | 0.699665 | 0.248329 |
from django.conf.urls.defaults import patterns, url
urlpatterns = patterns(
"ccui.manage.views",
url("^$", "home", name="manage"),
# products
url("^products/$", "products", name="manage_products"),
url("^product/add/$", "add_product", name="manage_product_add"),
url("^product/(?P<product_id>\... | data/train/python/07b893d93d6982dfc259ef34bd08317f51d22c87urls.py | from django.conf.urls.defaults import patterns, url
urlpatterns = patterns(
"ccui.manage.views",
url("^$", "home", name="manage"),
# products
url("^products/$", "products", name="manage_products"),
url("^product/add/$", "add_product", name="manage_product_add"),
url("^product/(?P<product_id>\... | 0.221351 | 0.338706 |
import re
from pathlib import Path
from typing import NamedTuple, Optional, List, Iterable
import subprocess, os, sys, shutil
from contextlib import contextmanager
import json
class CompilationError(Exception): ...
class FlintCompilationError(CompilationError): ...
class MoveRuntimeError(RuntimeError):
def __in... | Tests/MoveTests/BehaviourTests/run_behaviour_tests.py | import re
from pathlib import Path
from typing import NamedTuple, Optional, List, Iterable
import subprocess, os, sys, shutil
from contextlib import contextmanager
import json
class CompilationError(Exception): ...
class FlintCompilationError(CompilationError): ...
class MoveRuntimeError(RuntimeError):
def __in... | 0.629433 | 0.194349 |
from __future__ import print_function
from datetime import datetime
import json
import logging
import p9admin.user
MAPPING_NAME = "idp1_mapping"
class SAML(object):
# client should be p9admin.OpenStackClient
def __init__(self, client, backup_directory="/tmp"):
self.client = client
self.backup_... | p9admin/saml.py | from __future__ import print_function
from datetime import datetime
import json
import logging
import p9admin.user
MAPPING_NAME = "idp1_mapping"
class SAML(object):
# client should be p9admin.OpenStackClient
def __init__(self, client, backup_directory="/tmp"):
self.client = client
self.backup_... | 0.384912 | 0.081447 |
import subprocess
import shlex
# The only relavent source I've found is here:
# http://m1ked.com/post/12304626776/pos-tagger-for-twitter-successfully-implemented-in
# which is a very simple implementation, my implementation is a bit more
# useful (but not much).
# NOTE this command is directly lifted from runTagger.s... | src/tools/CMUTweetTagger.py | import subprocess
import shlex
# The only relavent source I've found is here:
# http://m1ked.com/post/12304626776/pos-tagger-for-twitter-successfully-implemented-in
# which is a very simple implementation, my implementation is a bit more
# useful (but not much).
# NOTE this command is directly lifted from runTagger.s... | 0.578686 | 0.21305 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import traceback
libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'pylib'))
sys.path.append(libdir)
try:
# pylint: disable=wrong-... | check_apache_drill_cluster_nodes_offline.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import sys
import traceback
libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'pylib'))
sys.path.append(libdir)
try:
# pylint: disable=wrong-... | 0.314051 | 0.05375 |
from faker import Faker
from pydapper.commands import BaseSqlParamHandler
from pydapper.commands import Commands
from pydapper.commands import CommandsAsync
class MockCursor:
def __init__(self):
self.faker = Faker()
self.rowcount = 0
@property
def description(self):
return ("id",... | tests/mocks.py | from faker import Faker
from pydapper.commands import BaseSqlParamHandler
from pydapper.commands import Commands
from pydapper.commands import CommandsAsync
class MockCursor:
def __init__(self):
self.faker = Faker()
self.rowcount = 0
@property
def description(self):
return ("id",... | 0.683525 | 0.176956 |
import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import re
import time
import os
import sys
import json
import concurrent.futures
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from i... | services/twitter/Chatter.py | import tweepy
from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import re
import time
import os
import sys
import json
import concurrent.futures
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from i... | 0.285472 | 0.103522 |
from src.utils import *
def image_key(sk, PK):
H = point_hash(PK)
I = point_mul(sk, H)
return I
def key_generation(n):
"""
The key generation algorithm
:param n: Number of users
:return: Public keys, Secret key, Signer secret index
"""
index = random.randint(0, n - 1)
PK_s... | src/lsag/lsag.py | from src.utils import *
def image_key(sk, PK):
H = point_hash(PK)
I = point_mul(sk, H)
return I
def key_generation(n):
"""
The key generation algorithm
:param n: Number of users
:return: Public keys, Secret key, Signer secret index
"""
index = random.randint(0, n - 1)
PK_s... | 0.841826 | 0.52902 |
from django.test import TestCase
from django.test.client import RequestFactory
from opps.contrib.mobile import template
from opps.contrib.mobile.middleware import (
MobileDetectionMiddleware, MobileRedirectMiddleware
)
class TestMobileTemplatesDir(TestCase):
def setUp(self):
self.detection_middlewar... | tests/contrib/test_mobile.py | from django.test import TestCase
from django.test.client import RequestFactory
from opps.contrib.mobile import template
from opps.contrib.mobile.middleware import (
MobileDetectionMiddleware, MobileRedirectMiddleware
)
class TestMobileTemplatesDir(TestCase):
def setUp(self):
self.detection_middlewar... | 0.632957 | 0.102036 |
from importlib import import_module
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import EmailMessage
from django.core.urlresolvers import get_mod_func
from django.forms import ModelForm
from django.forms.fields import FileField
from django.template.load... | glitter/blocks/form/views.py | from importlib import import_module
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import EmailMessage
from django.core.urlresolvers import get_mod_func
from django.forms import ModelForm
from django.forms.fields import FileField
from django.template.load... | 0.290377 | 0.092237 |
__author__ = 'api.jscudder (<NAME>)'
import StringIO
USER_AGENT = '%s GData-Python/2.0.10'
class Error(Exception):
pass
class UnparsableUrlObject(Error):
pass
class ContentLengthRequired(Error):
pass
class HttpResponse(object):
def __init__(self, body=None, status=None, reason=None, headers=None):... | lib/atom/http_interface.py | __author__ = 'api.jscudder (<NAME>)'
import StringIO
USER_AGENT = '%s GData-Python/2.0.10'
class Error(Exception):
pass
class UnparsableUrlObject(Error):
pass
class ContentLengthRequired(Error):
pass
class HttpResponse(object):
def __init__(self, body=None, status=None, reason=None, headers=None):... | 0.815747 | 0.114418 |
import collections
from functools import partial
from typing import Callable, Dict, Optional, TypeVar
import numpy as np
__all__ = ["DictToArrayBijection"]
T = TypeVar("T")
PointType = Dict[str, np.ndarray]
# `point_map_info` is a tuple of tuples containing `(name, shape, dtype)` for
# each of the raveled variabl... | pymc/blocking.py | import collections
from functools import partial
from typing import Callable, Dict, Optional, TypeVar
import numpy as np
__all__ = ["DictToArrayBijection"]
T = TypeVar("T")
PointType = Dict[str, np.ndarray]
# `point_map_info` is a tuple of tuples containing `(name, shape, dtype)` for
# each of the raveled variabl... | 0.912373 | 0.529324 |
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_import_helper():
import importlib
pkg = __name__.rpartition('.')[0]
mname = '.'.join((pkg, '_param_X86System')).lstrip('.')
try:
return importlib.import_module(m... | build/X86_MESI_Two_Level/python/m5/internal/param_X86System.py |
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
def swig_import_helper():
import importlib
pkg = __name__.rpartition('.')[0]
mname = '.'.join((pkg, '_param_X86System')).lstrip('.')
try:
return importlib.import_module(m... | 0.281702 | 0.075278 |
import glob
import importlib
import inspect
import logging
import os
import sys
from typing import List
import src.view.cli_view
def main(argv):
""" Script's main function """
cli_view_path = os.path.join('src', 'view', 'cli', '*.py')
cli_view_objects = load_views(cli_view_path)
# Build lookup class... | cli.py | import glob
import importlib
import inspect
import logging
import os
import sys
from typing import List
import src.view.cli_view
def main(argv):
""" Script's main function """
cli_view_path = os.path.join('src', 'view', 'cli', '*.py')
cli_view_objects = load_views(cli_view_path)
# Build lookup class... | 0.330687 | 0.094469 |
from gym_torcs import TorcsEnv
import numpy as np
import argparse
import time
from keras.models import model_from_json, Model
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam
import tensorflow as tf
import json
from models import TR... | wgail_info_1/wgail_info.py | from gym_torcs import TorcsEnv
import numpy as np
import argparse
import time
from keras.models import model_from_json, Model
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.optimizers import Adam
import tensorflow as tf
import json
from models import TR... | 0.694821 | 0.158044 |
import torch
from torch import nn
from collections import OrderedDict
def to_cuda(tensors): # pragma: no cover (No CUDA on travis)
""" Transfer tensor, dict or list of tensors to GPU.
Args:
tensors (:class:`torch.Tensor`, list or dict): May be a single, a
list or a dictionary of tensors.... | asteroid/utils/torch_utils.py | import torch
from torch import nn
from collections import OrderedDict
def to_cuda(tensors): # pragma: no cover (No CUDA on travis)
""" Transfer tensor, dict or list of tensors to GPU.
Args:
tensors (:class:`torch.Tensor`, list or dict): May be a single, a
list or a dictionary of tensors.... | 0.939304 | 0.825836 |
from msrest.serialization import Model
from azure.core import HttpResponseError
class Action(Model):
"""The action that will be executed.
:param action_type: The type of the action. Possible values include:
'EmailContacts', 'AutoRenew'
:type action_type: str or ~azure.keyvault.v2016_10_01.models.Ac... | sdk/keyvault/azure-keyvault-secrets/azure/keyvault/secrets/_shared/_generated/v2016_10_01/models/_models_py3.py |
from msrest.serialization import Model
from azure.core import HttpResponseError
class Action(Model):
"""The action that will be executed.
:param action_type: The type of the action. Possible values include:
'EmailContacts', 'AutoRenew'
:type action_type: str or ~azure.keyvault.v2016_10_01.models.Ac... | 0.888233 | 0.264843 |
import re
import binascii
import itertools
from django.utils.encoding import force_str
from django.utils.module_loading import import_string
from django_python3_ldap.conf import settings
def import_func(func):
if callable(func):
return func
elif isinstance(func, str):
return import_string(fu... | django_python3_ldap/utils.py | import re
import binascii
import itertools
from django.utils.encoding import force_str
from django.utils.module_loading import import_string
from django_python3_ldap.conf import settings
def import_func(func):
if callable(func):
return func
elif isinstance(func, str):
return import_string(fu... | 0.475118 | 0.294032 |
import pytest
from colors import yellow, red
from util import UserError, Logger, merge_into, merge, post_process
def test_new_usererror():
msg = f"hello!"
e: UserError = UserError(msg)
assert e.message == msg
@pytest.mark.parametrize("header", ["test header", None])
@pytest.mark.parametrize("indent_amo... | tests/test_util.py | import pytest
from colors import yellow, red
from util import UserError, Logger, merge_into, merge, post_process
def test_new_usererror():
msg = f"hello!"
e: UserError = UserError(msg)
assert e.message == msg
@pytest.mark.parametrize("header", ["test header", None])
@pytest.mark.parametrize("indent_amo... | 0.505371 | 0.461259 |
import threading
import time
from meerk40t.tools.zinglplotter import ZinglPlotter
from ...core.drivers import Driver
from ...core.plotplanner import grouped
from ...kernel import (
STATE_ACTIVE,
STATE_BUSY,
STATE_END,
STATE_IDLE,
STATE_INITIALIZE,
STATE_PAUSE,
STATE_SUSPEND,
STATE_TERM... | meerk40t/device/lhystudios/lhystudiosdevice.py | import threading
import time
from meerk40t.tools.zinglplotter import ZinglPlotter
from ...core.drivers import Driver
from ...core.plotplanner import grouped
from ...kernel import (
STATE_ACTIVE,
STATE_BUSY,
STATE_END,
STATE_IDLE,
STATE_INITIALIZE,
STATE_PAUSE,
STATE_SUSPEND,
STATE_TERM... | 0.423696 | 0.111386 |
import struct, time
from PyWANN import WiSARD
from array import array
startTime = time.time()
trainImagesFilename = "train-images.idx3-ubyte"
trainLabelsFilename = "train-labels.idx1-ubyte"
testImagesFilename = "t10k-images.idx3-ubyte"
testLabelsFilename = "t10k-labels.idx1-ubyte"
# a threshold to binarize the pixel... | RNSP - Trabalho I/main.py | import struct, time
from PyWANN import WiSARD
from array import array
startTime = time.time()
trainImagesFilename = "train-images.idx3-ubyte"
trainLabelsFilename = "train-labels.idx1-ubyte"
testImagesFilename = "t10k-images.idx3-ubyte"
testLabelsFilename = "t10k-labels.idx1-ubyte"
# a threshold to binarize the pixel... | 0.227727 | 0.352257 |
from collections import namedtuple
import re
from six import string_types
from conans.errors import ConanException, InvalidNameException
from conans.model.version import Version
class ConanName(object):
_max_chars = 51
_min_chars = 2
_validation_pattern = re.compile("^[a-zA-Z0-9_][a-zA-Z0-9_\+\.-]{%s,%s}$... | conans/model/ref.py | from collections import namedtuple
import re
from six import string_types
from conans.errors import ConanException, InvalidNameException
from conans.model.version import Version
class ConanName(object):
_max_chars = 51
_min_chars = 2
_validation_pattern = re.compile("^[a-zA-Z0-9_][a-zA-Z0-9_\+\.-]{%s,%s}$... | 0.728941 | 0.175927 |
from typing import Dict, Optional, Tuple, Union
import torch
import torch.nn as nn
from roca.modeling.depth_head.depth_modules import (
DepthFeatures,
DepthOutput,
Sobel,
)
from roca.modeling.logging_metrics import depth_metrics
from roca.modeling.loss_functions import (
cosine_distance,
inverse_h... | network/roca/modeling/depth_head/depth_head.py | from typing import Dict, Optional, Tuple, Union
import torch
import torch.nn as nn
from roca.modeling.depth_head.depth_modules import (
DepthFeatures,
DepthOutput,
Sobel,
)
from roca.modeling.logging_metrics import depth_metrics
from roca.modeling.loss_functions import (
cosine_distance,
inverse_h... | 0.936894 | 0.409044 |
from google.appengine.ext import ndb
from rogerthat.bizz.payment.providers.payconiq.consts import PAYMENT_PROVIDER_ID
from rogerthat.bizz.payment.utils import get_provider_namespace
class PayconiqTransaction(ndb.Model):
STATUS_PENDING = u'pending'
STATUS_SUCCEEDED = u'succeeded'
STATUS_FAILED = u'failed... | src/rogerthat/bizz/payment/providers/payconiq/models.py |
from google.appengine.ext import ndb
from rogerthat.bizz.payment.providers.payconiq.consts import PAYMENT_PROVIDER_ID
from rogerthat.bizz.payment.utils import get_provider_namespace
class PayconiqTransaction(ndb.Model):
STATUS_PENDING = u'pending'
STATUS_SUCCEEDED = u'succeeded'
STATUS_FAILED = u'failed... | 0.51879 | 0.058912 |
import datetime
from decimal import Decimal
from typing import Dict, List
import factory
from babel.dates import format_date
from dateutil.utils import today
from django.conf import settings
from django_ilmoitin.dummy_context import dummy_context
from applications.tests.factories import BerthApplicationFactory
from b... | payments/notifications/dummy_context.py | import datetime
from decimal import Decimal
from typing import Dict, List
import factory
from babel.dates import format_date
from dateutil.utils import today
from django.conf import settings
from django_ilmoitin.dummy_context import dummy_context
from applications.tests.factories import BerthApplicationFactory
from b... | 0.61057 | 0.126515 |
import numpy as np
from write_fault_shp import fault2shp
infile = 'outputs/rupture_mesh_1818_YoungsEtAl1997SInter_Mw6p75_118p882_-8p102_13p62km.txt'
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
def mesh2shp(infile):
"""
"""
output_shp... | mesh_fault_shp.py | import numpy as np
from write_fault_shp import fault2shp
infile = 'outputs/rupture_mesh_1818_YoungsEtAl1997SInter_Mw6p75_118p882_-8p102_13p62km.txt'
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
def mesh2shp(infile):
"""
"""
output_shp... | 0.148479 | 0.205197 |
import logging
import os
from playhouse.signals import Model as SignalsModel
from slimurl import URL
from peewee import Proxy, SqliteDatabase, MySQLDatabase, PostgresqlDatabase
from playhouse.migrate import SqliteMigrator, MySQLMigrator, PostgresqlMigrator
DB = Proxy()
class BaseModel(SignalsModel):
class Meta:
... | pypi_server/db/__init__.py | import logging
import os
from playhouse.signals import Model as SignalsModel
from slimurl import URL
from peewee import Proxy, SqliteDatabase, MySQLDatabase, PostgresqlDatabase
from playhouse.migrate import SqliteMigrator, MySQLMigrator, PostgresqlMigrator
DB = Proxy()
class BaseModel(SignalsModel):
class Meta:
... | 0.397938 | 0.05211 |
import sys
from ..pakbase import Package
class ModflowGmg(Package):
"""
MODFLOW GMG Package Class.
Parameters
----------
model : model object
The model object (of type :class:`flopy.modflow.mf.Modflow`) to which
this package will be added.
mxiter : int
maximum number o... | flopy/modflow/mfgmg.py | import sys
from ..pakbase import Package
class ModflowGmg(Package):
"""
MODFLOW GMG Package Class.
Parameters
----------
model : model object
The model object (of type :class:`flopy.modflow.mf.Modflow`) to which
this package will be added.
mxiter : int
maximum number o... | 0.716318 | 0.732089 |
MAX_RELAY_SIZE = 2048 # 2 ** 11
MAX_PROXY_CONNECTIONS = 131072 # 2 ** 17
REUSE_CONNECTION_IDS = False
import os
import sys
import array
import socket
import struct
import shutil
import traceback
from math import log2
from subprocess import Popen
from select import poll, POLLIN, POLLPRI
(
LOG_LEVEL_DEBUG,
... | wayland_proxy.py | MAX_RELAY_SIZE = 2048 # 2 ** 11
MAX_PROXY_CONNECTIONS = 131072 # 2 ** 17
REUSE_CONNECTION_IDS = False
import os
import sys
import array
import socket
import struct
import shutil
import traceback
from math import log2
from subprocess import Popen
from select import poll, POLLIN, POLLPRI
(
LOG_LEVEL_DEBUG,
... | 0.083059 | 0.05151 |
from __future__ import absolute_import, division
import logging
from collections import defaultdict, deque
import blinker
import gevent
from gevent.event import AsyncResult
from gevent.pool import Group
from gevent.queue import Queue, Empty
from . import protocol as nsq
from .backofftimer import BackoffTimer
from ... | gnsq/producer.py | from __future__ import absolute_import, division
import logging
from collections import defaultdict, deque
import blinker
import gevent
from gevent.event import AsyncResult
from gevent.pool import Group
from gevent.queue import Queue, Empty
from . import protocol as nsq
from .backofftimer import BackoffTimer
from ... | 0.826991 | 0.165998 |
from pandac.PandaModules import *
class EffectController():
particleDummy = None
def __init__(self):
self.track = None
self.startEffect = None
self.endEffect = None
self.f = None
self.p0 = None
return
def createTrack(self):
pass
@report(types=[... | pirates/effects/EffectController.py | from pandac.PandaModules import *
class EffectController():
particleDummy = None
def __init__(self):
self.track = None
self.startEffect = None
self.endEffect = None
self.f = None
self.p0 = None
return
def createTrack(self):
pass
@report(types=[... | 0.511717 | 0.081776 |
import time
import requests
import parsel
import re
import os
from ThreadPool import ThreadPool
class Downloader(object):
base_url="https://www.ishuyin.com/"
def __init__(self, id):
self.search_url="https://www.ishuyin.com/show-{id}.html".format(id=id)
self.mp3_url_list=[]
self.cha... | audioBook/downloader.py | import time
import requests
import parsel
import re
import os
from ThreadPool import ThreadPool
class Downloader(object):
base_url="https://www.ishuyin.com/"
def __init__(self, id):
self.search_url="https://www.ishuyin.com/show-{id}.html".format(id=id)
self.mp3_url_list=[]
self.cha... | 0.040484 | 0.074198 |
from __future__ import print_function
import unittest
import numpy as np
import math
from op_test import OpTest
import paddle.fluid.core as core
def quantize_max_abs(x, max_range):
scale = np.max(np.abs(x).flatten())
y = np.round(x / scale * max_range)
return y, scale
def dequantize_max_abs(x, scale, ... | python/paddle/fluid/tests/unittests/test_fake_dequantize_op.py |
from __future__ import print_function
import unittest
import numpy as np
import math
from op_test import OpTest
import paddle.fluid.core as core
def quantize_max_abs(x, max_range):
scale = np.max(np.abs(x).flatten())
y = np.round(x / scale * max_range)
return y, scale
def dequantize_max_abs(x, scale, ... | 0.731442 | 0.529263 |
import streamlit as st
import cv2
from streamlit.server.server import Server
from PIL import Image
import session_state as SessionState
import numpy as np
import pandas as pd
import pydeck as pdk
import time
import requests
import base64
import json
st.set_page_config(page_title="Kludge Inc.", page_icon="🔱")
'''
# Ae... | frontend/visualisation.py | import streamlit as st
import cv2
from streamlit.server.server import Server
from PIL import Image
import session_state as SessionState
import numpy as np
import pandas as pd
import pydeck as pdk
import time
import requests
import base64
import json
st.set_page_config(page_title="Kludge Inc.", page_icon="🔱")
'''
# Ae... | 0.326593 | 0.128689 |
# Copyright (c) 2017 <NAME>. All rights reserved.
# Restrictions are listed in the LICENSE file distributed with this package.
import sys, os, argparse
from habis.formats import WaveformSet, loadkeymat
def nonzero(string):
val = int(string)
if not val: raise argparse.ArgumentTypeError('must be nonzero')
return ... | shell/wset-txshift.py |
# Copyright (c) 2017 <NAME>. All rights reserved.
# Restrictions are listed in the LICENSE file distributed with this package.
import sys, os, argparse
from habis.formats import WaveformSet, loadkeymat
def nonzero(string):
val = int(string)
if not val: raise argparse.ArgumentTypeError('must be nonzero')
return ... | 0.419648 | 0.281079 |
from img2dataset import download
import os
import shutil
import cv2
import pytest
import glob
import time
import pandas as pd
import tarfile
def test_basic():
print("it works !")
current_folder = os.path.dirname(__file__)
test_folder = current_folder + "/" + "test_folder"
if not os.path.exists(test_folder):
o... | tests/test_basic.py | from img2dataset import download
import os
import shutil
import cv2
import pytest
import glob
import time
import pandas as pd
import tarfile
def test_basic():
print("it works !")
current_folder = os.path.dirname(__file__)
test_folder = current_folder + "/" + "test_folder"
if not os.path.exists(test_folder):
o... | 0.236869 | 0.269946 |
r""" Handy utility methods to make using the API simpler """
import typing
import requests
from ...constants import *
from json import dumps
class Route(object):
def __init__(self, method: str, route: str, *, payload=None, headers=None, params=None, **others):
if headers is None:
heade... | PyPtero/Sync/API/base.py | r""" Handy utility methods to make using the API simpler """
import typing
import requests
from ...constants import *
from json import dumps
class Route(object):
def __init__(self, method: str, route: str, *, payload=None, headers=None, params=None, **others):
if headers is None:
heade... | 0.697815 | 0.234757 |
import click
import jinja2
import mdv
from ..db import Recipe
from . import cli
RECIPE_TEMPLATE = u"""
# {{ RECIPE['title'] }}
---
* Complexity **{{ RECIPE['complexity'] }}**.
* Ready in **{{ RECIPE.preparation_time }}** minutes.
* Serves **{{ RECIPE['portions'] }}**.
{% if RECIPE['tags'] %}
* Tagged as ... | feedem/commands/cmd_recipe.py | import click
import jinja2
import mdv
from ..db import Recipe
from . import cli
RECIPE_TEMPLATE = u"""
# {{ RECIPE['title'] }}
---
* Complexity **{{ RECIPE['complexity'] }}**.
* Ready in **{{ RECIPE.preparation_time }}** minutes.
* Serves **{{ RECIPE['portions'] }}**.
{% if RECIPE['tags'] %}
* Tagged as ... | 0.454956 | 0.175185 |
import time
from dotenv import load_dotenv, find_dotenv
import os
import numpy as np
from pathlib import Path
import tensorflow as tf
from keras import Input, Model
from keras.callbacks import TensorBoard
from keras.layers import Dense, Dropout, Lambda, BatchNormalization
from keras.optimizers import RMSprop, Adam
f... | src/models/train_siamese.py | import time
from dotenv import load_dotenv, find_dotenv
import os
import numpy as np
from pathlib import Path
import tensorflow as tf
from keras import Input, Model
from keras.callbacks import TensorBoard
from keras.layers import Dense, Dropout, Lambda, BatchNormalization
from keras.optimizers import RMSprop, Adam
f... | 0.712232 | 0.519278 |
import sys
from cyvcf2 import VCF
from collections import defaultdict
from argparse import ArgumentParser
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def main():
args = get_args()
len_dict = defaultdict(list)
vcf = VCF(args.vcf)
if len(vcf.samples) > 1:
sys.stderr.w... | scripts/SV-length-plot.py | import sys
from cyvcf2 import VCF
from collections import defaultdict
from argparse import ArgumentParser
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
def main():
args = get_args()
len_dict = defaultdict(list)
vcf = VCF(args.vcf)
if len(vcf.samples) > 1:
sys.stderr.w... | 0.400867 | 0.275891 |
import argparse
import json
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
from metrics import (
BaseMetric,
AnswerMetric,
SupportingFactsMetric
)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Script to ev... | evaluation_scripts/evaluate_original_dataset.py | import argparse
import json
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
from metrics import (
BaseMetric,
AnswerMetric,
SupportingFactsMetric
)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Script to ev... | 0.33928 | 0.140454 |
from __future__ import print_function
import pymongo
from pymongo import MongoClient
import os
import sys
import errno
from Multithreading import submit_and_monitor_thread
import codecs
import csv
import unicodedata
import re
CURRENT_WORKING_DIRECTORY = os.getcwd()
def cleanup():
#This should contain the logic to cl... | Preprocessing/CreateReviewText.py | from __future__ import print_function
import pymongo
from pymongo import MongoClient
import os
import sys
import errno
from Multithreading import submit_and_monitor_thread
import codecs
import csv
import unicodedata
import re
CURRENT_WORKING_DIRECTORY = os.getcwd()
def cleanup():
#This should contain the logic to cl... | 0.14143 | 0.082254 |
import asyncio
import os
import configparser
from datetime import datetime, timedelta
import discord
from discord.ext import tasks
import cv2
config = configparser.ConfigParser()
config.read('config.ini', 'UTF-8')
token = os.environ.get('DISCORD_TOKEN') or config.get('discord', 'bot_token')
idea_channel_id = config.... | bot_main.py | import asyncio
import os
import configparser
from datetime import datetime, timedelta
import discord
from discord.ext import tasks
import cv2
config = configparser.ConfigParser()
config.read('config.ini', 'UTF-8')
token = os.environ.get('DISCORD_TOKEN') or config.get('discord', 'bot_token')
idea_channel_id = config.... | 0.289975 | 0.050191 |
import json
from mock.mock import MagicMock, call, patch
from stacks.utils.RMFTestCase import *
class TestHiveClient(RMFTestCase):
COMMON_SERVICES_PACKAGE_DIR = "HIVE/0.12.0.2.0/package"
STACK_VERSION = "2.0.6"
def test_configure_default(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts... | ambari-server/src/test/python/stacks/2.0.6/HIVE/test_hive_client.py | import json
from mock.mock import MagicMock, call, patch
from stacks.utils.RMFTestCase import *
class TestHiveClient(RMFTestCase):
COMMON_SERVICES_PACKAGE_DIR = "HIVE/0.12.0.2.0/package"
STACK_VERSION = "2.0.6"
def test_configure_default(self):
self.executeScript(self.COMMON_SERVICES_PACKAGE_DIR + "/scripts... | 0.18363 | 0.083479 |
import glob
import os
import os.path
import tempfile
import numpy as np
from annif import logger
from annif.suggestion import VectorSuggestionResult
def atomic_save(obj, dirname, filename, method=None):
"""Save the given object (which must have a .save() method, unless the
method parameter is given) into the... | annif/util.py |
import glob
import os
import os.path
import tempfile
import numpy as np
from annif import logger
from annif.suggestion import VectorSuggestionResult
def atomic_save(obj, dirname, filename, method=None):
"""Save the given object (which must have a .save() method, unless the
method parameter is given) into the... | 0.619356 | 0.251602 |
import time
from unittest import mock
from urllib.parse import urlparse
from azure.core.credentials import AccessToken
from azure.identity import AzureAuthorityHosts, CredentialUnavailableError
from azure.identity._constants import EnvironmentVariables
from azure.identity._internal.user_agent import USER_AGENT
from az... | sdk/identity/azure-identity/tests/test_vscode_credential_async.py | import time
from unittest import mock
from urllib.parse import urlparse
from azure.core.credentials import AccessToken
from azure.identity import AzureAuthorityHosts, CredentialUnavailableError
from azure.identity._constants import EnvironmentVariables
from azure.identity._internal.user_agent import USER_AGENT
from az... | 0.697918 | 0.217951 |
from oslo_log import log as logging
from trove.guestagent.strategies.replication import mysql_base
LOG = logging.getLogger(__name__)
class MysqlGTIDReplication(mysql_base.MysqlReplicationBase):
"""MySql Replication coordinated by GTIDs."""
def connect_to_master(self, service, master_info):
if 'datas... | trove/guestagent/strategies/replication/mysql_gtid.py | from oslo_log import log as logging
from trove.guestagent.strategies.replication import mysql_base
LOG = logging.getLogger(__name__)
class MysqlGTIDReplication(mysql_base.MysqlReplicationBase):
"""MySql Replication coordinated by GTIDs."""
def connect_to_master(self, service, master_info):
if 'datas... | 0.382372 | 0.079389 |
class Qualifications:
def __init__(self, requirements = []):
self.requirements = requirements
def add(self, req):
self.requirements.append(req)
def get_as_params(self):
params = {}
assert(len(self.requirements) <= 10)
for n, req in enumerate(self.requirements):
... | vendor/boto/boto/mturk/qualification.py |
class Qualifications:
def __init__(self, requirements = []):
self.requirements = requirements
def add(self, req):
self.requirements.append(req)
def get_as_params(self):
params = {}
assert(len(self.requirements) <= 10)
for n, req in enumerate(self.requirements):
... | 0.722625 | 0.291472 |
from django.test import override_settings
from jackal.exceptions import NotFound
from jackal.helpers.data_helper import isiter
from jackal.settings import jackal_settings
from jackal.shortcuts import get_object_or_404, get_object_or_None, model_update, operating, status_checker, \
status_readable, get_object_or
fr... | tests/test_shortcuts.py | from django.test import override_settings
from jackal.exceptions import NotFound
from jackal.helpers.data_helper import isiter
from jackal.settings import jackal_settings
from jackal.shortcuts import get_object_or_404, get_object_or_None, model_update, operating, status_checker, \
status_readable, get_object_or
fr... | 0.514644 | 0.507934 |
import random
import math
import statistics
import time
from operator import itemgetter
from tetris import TetrisApp
from sys import stdout
def createIndividual(size):
result = []
for i in range(0, size):
result.append(random.uniform(-10, 10))
return result
def individualFromDistribution(average, ... | tetris/genetic.py | import random
import math
import statistics
import time
from operator import itemgetter
from tetris import TetrisApp
from sys import stdout
def createIndividual(size):
result = []
for i in range(0, size):
result.append(random.uniform(-10, 10))
return result
def individualFromDistribution(average, ... | 0.143638 | 0.220489 |
import abc
import os
from typing import Any, Dict
from perfkitbenchmarker import resource
MESSAGING_SERVICE_DATA_DIR = 'messaging_service'
MESSAGING_SERVICE_CLIENT_PY = 'messaging_service_client.py'
def GetMessagingServiceClass(cloud, delivery):
"""Gets the underlying Messaging Service class."""
return resource.... | perfkitbenchmarker/messaging_service.py | import abc
import os
from typing import Any, Dict
from perfkitbenchmarker import resource
MESSAGING_SERVICE_DATA_DIR = 'messaging_service'
MESSAGING_SERVICE_CLIENT_PY = 'messaging_service_client.py'
def GetMessagingServiceClass(cloud, delivery):
"""Gets the underlying Messaging Service class."""
return resource.... | 0.651355 | 0.097993 |
import collections
import os
import typing
import warnings
import mmf.utils.download as download
from mmf.datasets.base_dataset_builder import BaseDatasetBuilder
from mmf.datasets.concat_dataset import MMFConcatDataset
from mmf.utils.configuration import get_global_config, get_mmf_env, get_zoo_config
from mmf.utils.ge... | mmf/datasets/mmf_dataset_builder.py | import collections
import os
import typing
import warnings
import mmf.utils.download as download
from mmf.datasets.base_dataset_builder import BaseDatasetBuilder
from mmf.datasets.concat_dataset import MMFConcatDataset
from mmf.utils.configuration import get_global_config, get_mmf_env, get_zoo_config
from mmf.utils.ge... | 0.587352 | 0.25105 |
import sys
assert sys.version_info >= (3,9), "This script requires at least Python 3.9"
world = {
"uuid": "9BD60891-83E8-4CCF-9ED1-A98D881D79CF",
"name": "Rare Art Museum Heist",
"creator": "Twine",
"creatorVersion": "2.3.14",
"schemaName": "Harlowe 3 to JSON",
"schemaVersion": "0.0.6",
"create... | main.py | import sys
assert sys.version_info >= (3,9), "This script requires at least Python 3.9"
world = {
"uuid": "9BD60891-83E8-4CCF-9ED1-A98D881D79CF",
"name": "Rare Art Museum Heist",
"creator": "Twine",
"creatorVersion": "2.3.14",
"schemaName": "Harlowe 3 to JSON",
"schemaVersion": "0.0.6",
"create... | 0.244634 | 0.418222 |
from mvnc import mvncapi as mvnc
import numpy, cv2
import sys, os
import cPickle as pickle
import utilities, argparse
def setup(args):
utilities.setup(args)
model = None
with open(args.testModel, 'rb') as mod:
model = pickle.load(mod)
return model
def run(model, testData, threshold):
if ... | Code/Dlib/faceRecognition.py |
from mvnc import mvncapi as mvnc
import numpy, cv2
import sys, os
import cPickle as pickle
import utilities, argparse
def setup(args):
utilities.setup(args)
model = None
with open(args.testModel, 'rb') as mod:
model = pickle.load(mod)
return model
def run(model, testData, threshold):
if ... | 0.247169 | 0.160365 |
from argparse import ArgumentParser, Namespace
from functools import wraps
import io
import os
import sys
import shutil
from tempfile import TemporaryDirectory, NamedTemporaryFile
import time
from typing import Callable, List, Tuple
import multiprocessing as mp
import zipfile
from flask import json, jsonify, redirect... | web/app/views.py |
from argparse import ArgumentParser, Namespace
from functools import wraps
import io
import os
import sys
import shutil
from tempfile import TemporaryDirectory, NamedTemporaryFile
import time
from typing import Callable, List, Tuple
import multiprocessing as mp
import zipfile
from flask import json, jsonify, redirect... | 0.680348 | 0.18188 |
# https://github.com/IronLanguages/main/issues/733
import _ssl as real_ssl
import os
import socket
import unittest
from iptest import IronPythonTestCase, is_cli, is_netcoreapp, retryOnFailure, run_test, skipUnlessIronPython
SSL_URL = "www.microsoft.com"
SSL_ISSUER = "CN=Microsoft IT TLS CA 4, OU=Microsoft IT, ... | Tests/modules/network_related/test__ssl.py | # https://github.com/IronLanguages/main/issues/733
import _ssl as real_ssl
import os
import socket
import unittest
from iptest import IronPythonTestCase, is_cli, is_netcoreapp, retryOnFailure, run_test, skipUnlessIronPython
SSL_URL = "www.microsoft.com"
SSL_ISSUER = "CN=Microsoft IT TLS CA 4, OU=Microsoft IT, ... | 0.280912 | 0.25198 |
"""Evaluation NAML."""
import os
import time
from mindspore import context
from mindspore.common import set_seed
from mindspore.train.serialization import load_checkpoint
from src.naml import NAML, NAMLWithLossCell
from src.dataset import MINDPreprocess
from src.utils import NAMLMetric, get_metric
from model_utils.con... | official/recommend/naml/eval.py | """Evaluation NAML."""
import os
import time
from mindspore import context
from mindspore.common import set_seed
from mindspore.train.serialization import load_checkpoint
from src.naml import NAML, NAMLWithLossCell
from src.dataset import MINDPreprocess
from src.utils import NAMLMetric, get_metric
from model_utils.con... | 0.436142 | 0.130645 |
import numpy as np
import pytest
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor
from mindspore.common.parameter import ParameterTuple
from mindspore.ops import operations as P
from mindspore.ops import composite as C
class MSLRNOpNet(nn.Cell):
def __init__(self):
... | tests/st/ops/gpu/test_local_response_norm_op.py |
import numpy as np
import pytest
import mindspore.context as context
import mindspore.nn as nn
from mindspore import Tensor
from mindspore.common.parameter import ParameterTuple
from mindspore.ops import operations as P
from mindspore.ops import composite as C
class MSLRNOpNet(nn.Cell):
def __init__(self):
... | 0.654564 | 0.376136 |
from utils import *
from torch.utils.data import DataLoader
class BASEModel(torch.nn.Module):
def __init__(self, input1_module, input2_module, embedding1_module, embedding2_module, rec_module):
super(BASEModel, self).__init__()
self.input_user_loading = input1_module
self.input_item_loadi... | models.py | from utils import *
from torch.utils.data import DataLoader
class BASEModel(torch.nn.Module):
def __init__(self, input1_module, input2_module, embedding1_module, embedding2_module, rec_module):
super(BASEModel, self).__init__()
self.input_user_loading = input1_module
self.input_item_loadi... | 0.916232 | 0.253509 |
import unittest
import torch
import torchdiffeq
from problems import construct_problem
eps = 1e-12
torch.set_default_dtype(torch.float64)
TEST_DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def max_abs(tensor):
return torch.max(torch.abs(tensor))
class TestGradient(unittest.TestCase)... | tests/gradient_tests.py | import unittest
import torch
import torchdiffeq
from problems import construct_problem
eps = 1e-12
torch.set_default_dtype(torch.float64)
TEST_DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
def max_abs(tensor):
return torch.max(torch.abs(tensor))
class TestGradient(unittest.TestCase)... | 0.880643 | 0.79534 |
import socket
import traceback
from urlparse import urlparse
import gevent
from swiftclient.exceptions import ClientException
from wal_e import log_help
from wal_e.blobstore.swift import calling_format
from wal_e.pipeline import get_download_pipeline
from wal_e.piper import PIPE
from wal_e.retries import retry, retr... | wal_e/blobstore/swift/utils.py | import socket
import traceback
from urlparse import urlparse
import gevent
from swiftclient.exceptions import ClientException
from wal_e import log_help
from wal_e.blobstore.swift import calling_format
from wal_e.pipeline import get_download_pipeline
from wal_e.piper import PIPE
from wal_e.retries import retry, retr... | 0.442155 | 0.223441 |
from api.api import api
from flask_restplus import Resource, fields
from flask import request, jsonify, make_response, Response
from werkzeug.utils import secure_filename
from api.implementation import upload_file, download_file, delete_file, send_email
import sys
# namespace sets the endpoints with a prefix of... | api/endpoints/marketing.py | from api.api import api
from flask_restplus import Resource, fields
from flask import request, jsonify, make_response, Response
from werkzeug.utils import secure_filename
from api.implementation import upload_file, download_file, delete_file, send_email
import sys
# namespace sets the endpoints with a prefix of... | 0.373304 | 0.156137 |
import datetime
import ddt
import freezegun
from ggrc import db
from ggrc.models import all_models
from ggrc_workflows.models import Workflow
from integration.ggrc import TestCase
from integration.ggrc.models import factories as glob_factories
from integration.ggrc_workflows.models import factories
from integration.gg... | test/integration/ggrc_workflows/models/test_workflow.py | import datetime
import ddt
import freezegun
from ggrc import db
from ggrc.models import all_models
from ggrc_workflows.models import Workflow
from integration.ggrc import TestCase
from integration.ggrc.models import factories as glob_factories
from integration.ggrc_workflows.models import factories
from integration.gg... | 0.400632 | 0.162347 |
import os
from distutils.core import setup
from distutils.command.install import INSTALL_SCHEMES
app_name = 'templatesadmin'
version = __import__(app_name).__version__
# Tell distutils to put the data_files in platform-specific installation
# locations. See here for an explanation:
# http://groups.google.com/group/co... | setup.py | import os
from distutils.core import setup
from distutils.command.install import INSTALL_SCHEMES
app_name = 'templatesadmin'
version = __import__(app_name).__version__
# Tell distutils to put the data_files in platform-specific installation
# locations. See here for an explanation:
# http://groups.google.com/group/co... | 0.327131 | 0.079854 |
import sys
import argparse
import isodate
from gpxpy import GPX
import functools
import xml.etree.ElementTree as ET
ET._namespace_map['http://www.google.com/kml/ext/2.2'] = 'gx'
# TODO: this should go into tokml!
# Taken from http://effbot.org/zone/element-builder.htm
class _K(object):
def __call__(self, tag, *c... | gpxpy/tools/tokml.py | import sys
import argparse
import isodate
from gpxpy import GPX
import functools
import xml.etree.ElementTree as ET
ET._namespace_map['http://www.google.com/kml/ext/2.2'] = 'gx'
# TODO: this should go into tokml!
# Taken from http://effbot.org/zone/element-builder.htm
class _K(object):
def __call__(self, tag, *c... | 0.056172 | 0.075109 |
from typing import (
Any,
Dict,
)
from .utility import (
initialize_list_field,
initialize_object_field,
)
from jsonpointer import resolve_pointer, set_pointer
from . import wot_common
def initialize_object_from_json_pointer(sdf_model: Dict, json_pointer: str):
current_element = sdf_model
for ... | sdf_wot_converter/converters/wot_to_sdf.py | from typing import (
Any,
Dict,
)
from .utility import (
initialize_list_field,
initialize_object_field,
)
from jsonpointer import resolve_pointer, set_pointer
from . import wot_common
def initialize_object_from_json_pointer(sdf_model: Dict, json_pointer: str):
current_element = sdf_model
for ... | 0.402862 | 0.116236 |
import os
import cv2
import math
import pandas as pd
from PIL import Image
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torchvision.transforms as standard_transforms
from misc.utils import *
from test_config import cfg
import matplotlib
matplotlib.use('Ag... | test.py | import os
import cv2
import math
import pandas as pd
from PIL import Image
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torchvision.transforms as standard_transforms
from misc.utils import *
from test_config import cfg
import matplotlib
matplotlib.use('Ag... | 0.33764 | 0.24173 |
import logging
import os
from argparse import ArgumentParser
import discord
from discord.ext import commands
import Util
from Util import Configuration, GearbotLogging, GlobalHandlers
def prefix_callable(bot, message):
return GlobalHandlers.prefix_callable(bot, message)
bot = commands.AutoShardedBot(command_pr... | GearBot/Bot.py | import logging
import os
from argparse import ArgumentParser
import discord
from discord.ext import commands
import Util
from Util import Configuration, GearbotLogging, GlobalHandlers
def prefix_callable(bot, message):
return GlobalHandlers.prefix_callable(bot, message)
bot = commands.AutoShardedBot(command_pr... | 0.369884 | 0.068975 |
class Section(dict):
""" Helper class that includes some frequently used routines """
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
if not self.get('line'):
self['line'] = 1
def has_code(self):
""" Check if there is some code """
return boo... | pyccoon/languages/utils.py | class Section(dict):
""" Helper class that includes some frequently used routines """
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
if not self.get('line'):
self['line'] = 1
def has_code(self):
""" Check if there is some code """
return boo... | 0.842798 | 0.427456 |
import sys
import hid
import argparse
from time import sleep
class ATENUsbSwitch(object):
def __init__(self, vendor_id=1367, product_id=9223):
self.vendor_id = vendor_id
self.product_id = product_id
self.device = None
def __del__(self):
self._close()
def _open(self):
... | atenusbsw.py |
import sys
import hid
import argparse
from time import sleep
class ATENUsbSwitch(object):
def __init__(self, vendor_id=1367, product_id=9223):
self.vendor_id = vendor_id
self.product_id = product_id
self.device = None
def __del__(self):
self._close()
def _open(self):
... | 0.197483 | 0.087994 |
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy import abs, cos, exp, arange, pi, sin, sqrt, sum, zeros, tanh
from numpy.testing import assert_almost_equal
from .go_benchmark import Benchmark
class Damavandi(Benchmark):
"""
Damavandi objective function.
Th... | benchmarks/benchmarks/go_benchmark_functions/go_funcs_D.py | from __future__ import division, print_function, absolute_import
import numpy as np
from numpy import abs, cos, exp, arange, pi, sin, sqrt, sum, zeros, tanh
from numpy.testing import assert_almost_equal
from .go_benchmark import Benchmark
class Damavandi(Benchmark):
"""
Damavandi objective function.
Th... | 0.81648 | 0.620622 |
# 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.
import os
import time
import joblib
import tqdm
import glob
import imageio
import copy
import numpy as np
from typing import ClassVar, Dict, Li... | pointnav_vo/rl/common/base_trainer.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.
import os
import time
import joblib
import tqdm
import glob
import imageio
import copy
import numpy as np
from typing import ClassVar, Dict, Li... | 0.759225 | 0.193776 |
from typing import List, TYPE_CHECKING
from discordmenu.embed.view_state import ViewState
from tsutils.menu.components.config import UserConfig
from tsutils.query_settings.enums import AltEvoSort
from tsutils.query_settings.query_settings import QuerySettings
from padinfo.view.common import get_monster_from_ims
from ... | padinfo/view/components/view_state_base_id.py | from typing import List, TYPE_CHECKING
from discordmenu.embed.view_state import ViewState
from tsutils.menu.components.config import UserConfig
from tsutils.query_settings.enums import AltEvoSort
from tsutils.query_settings.query_settings import QuerySettings
from padinfo.view.common import get_monster_from_ims
from ... | 0.726329 | 0.142769 |
import asyncio
from functools import partial
import binascii
import logging
import voluptuous as vol
from homeassistant.helpers import config_validation as cv, entity_platform, service
from datetime import datetime
from homeassistant.components.climate import (
PLATFORM_SCHEMA,
ClimateEntity
)
from homeassis... | hysen2pfc/climate.py | import asyncio
from functools import partial
import binascii
import logging
import voluptuous as vol
from homeassistant.helpers import config_validation as cv, entity_platform, service
from datetime import datetime
from homeassistant.components.climate import (
PLATFORM_SCHEMA,
ClimateEntity
)
from homeassis... | 0.204819 | 0.083106 |
import collections
import datetime
import inspect
import logging
import os
import unittest
import six
from six.moves import configparser
if six.PY2:
ConfigParser = configparser.RawConfigParser
else:
ConfigParser = configparser.ConfigParser
from strategyease_sdk import JoinQuantExecutor
@unittest.skip("int... | tests/strategyease_sdk/joinquant/test_executor.py |
import collections
import datetime
import inspect
import logging
import os
import unittest
import six
from six.moves import configparser
if six.PY2:
ConfigParser = configparser.RawConfigParser
else:
ConfigParser = configparser.ConfigParser
from strategyease_sdk import JoinQuantExecutor
@unittest.skip("int... | 0.328422 | 0.205874 |
import collections
import re
import numpy as np
from collections import Iterable
from numbers import Number
from pandas.compat import (PY2, string_types, text_type,
string_and_binary_types, re_type)
from pandas._libs import lib
is_bool = lib.is_bool
is_integer = lib.is_integer
is_float = ... | pandas/core/dtypes/inference.py |
import collections
import re
import numpy as np
from collections import Iterable
from numbers import Number
from pandas.compat import (PY2, string_types, text_type,
string_and_binary_types, re_type)
from pandas._libs import lib
is_bool = lib.is_bool
is_integer = lib.is_integer
is_float = ... | 0.875041 | 0.4474 |
import uuid
import json
from esrally import track, config, exceptions
from esrally.utils import io, console
color_scheme_rgba = [
"rgba(0,191,179,1)",
"rgba(0,169,224,1)",
"rgba(240,78,152,1)",
"rgba(255,205,0,1)",
"rgba(0,118,168,1)",
"rgba(147,201,14,1)",
"rgba(100,100,100,1)",
]
def i... | esrally/chart_generator.py | import uuid
import json
from esrally import track, config, exceptions
from esrally.utils import io, console
color_scheme_rgba = [
"rgba(0,191,179,1)",
"rgba(0,169,224,1)",
"rgba(240,78,152,1)",
"rgba(255,205,0,1)",
"rgba(0,118,168,1)",
"rgba(147,201,14,1)",
"rgba(100,100,100,1)",
]
def i... | 0.452536 | 0.291724 |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
"""# Notebook Presentation"""
pd.options.display.float_format = '{:,.2f}'.format
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
"""# Read the Data... | Day-077/main.py | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
"""# Notebook Presentation"""
pd.options.display.float_format = '{:,.2f}'.format
from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()
"""# Read the Data... | 0.832203 | 0.715225 |
import json, sys, csv, math
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
class GraphConfig:
def __init__(self, config:dict):
self.FileName = config['output_file_name']
self.Dpi = config['dpi']
self.Width = config['graph_width']
self.Height = config['graph_h... | Tripartite/Tripartite.py | import json, sys, csv, math
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
class GraphConfig:
def __init__(self, config:dict):
self.FileName = config['output_file_name']
self.Dpi = config['dpi']
self.Width = config['graph_width']
self.Height = config['graph_h... | 0.347316 | 0.313512 |
import os
import argparse
import random
import string
from glob import glob
from natsort import natsorted
import numpy as np
from skimage.io import imread, imsave
from skimage.color import grey2rgb
import pandas as pd
def random_string(length=16):
letters = string.ascii_lowercase
return ... | util/merge_data_for_classifier.py | import os
import argparse
import random
import string
from glob import glob
from natsort import natsorted
import numpy as np
from skimage.io import imread, imsave
from skimage.color import grey2rgb
import pandas as pd
def random_string(length=16):
letters = string.ascii_lowercase
return ... | 0.20201 | 0.124798 |
import rosbag
import subprocess, yaml
import numpy as np
import pdb
import sys
from scipy import interpolate
# static parameters
CUBE_TOPIC_STRING = '/tagslam/odom/body_cube'
BOARD_TOPIC_STRING = '/tagslam/odom/body_surface'
if len(sys.argv) < 3:
print("usage: python[2] apriltag_csv.py [ROSBAG] [CSV_OUT]")
s... | tools/apriltag/apriltag_csv.py | import rosbag
import subprocess, yaml
import numpy as np
import pdb
import sys
from scipy import interpolate
# static parameters
CUBE_TOPIC_STRING = '/tagslam/odom/body_cube'
BOARD_TOPIC_STRING = '/tagslam/odom/body_surface'
if len(sys.argv) < 3:
print("usage: python[2] apriltag_csv.py [ROSBAG] [CSV_OUT]")
s... | 0.23014 | 0.159807 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetVirtualMachineImageTemplateResult',
'AwaitableGetVirtualMachineImageTemplateResult',
'get_virtual_machine_image_template'... | sdk/python/pulumi_azure_native/virtualmachineimages/latest/get_virtual_machine_image_template.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetVirtualMachineImageTemplateResult',
'AwaitableGetVirtualMachineImageTemplateResult',
'get_virtual_machine_image_template'... | 0.84941 | 0.083479 |
from typing import Any, Optional, Sequence, Tuple, Union
import torch
import torch.nn as nn
import numpy as np
import math
from monai.networks.blocks import Convolution, ResidualUnit, Upsample
from monai.networks.blocks import ADN
from monai.networks.layers.factories import Act, Norm
from monai.utils.misc import gen... | monai/networks/nets/pmvae.py |
from typing import Any, Optional, Sequence, Tuple, Union
import torch
import torch.nn as nn
import numpy as np
import math
from monai.networks.blocks import Convolution, ResidualUnit, Upsample
from monai.networks.blocks import ADN
from monai.networks.layers.factories import Act, Norm
from monai.utils.misc import gen... | 0.960398 | 0.292823 |
from json import load, JSONDecodeError
from cmd import Cmd
from itertools import zip_longest
from webbrowser import open as webbrowser_open
from urllib.parse import quote
from typing import Set
from util import __version__, ROOT_DIR
from download_category import download_and_write, write_one
def read_one(title: str, ... | search_category.py | from json import load, JSONDecodeError
from cmd import Cmd
from itertools import zip_longest
from webbrowser import open as webbrowser_open
from urllib.parse import quote
from typing import Set
from util import __version__, ROOT_DIR
from download_category import download_and_write, write_one
def read_one(title: str, ... | 0.31258 | 0.118309 |
import json
import mock
import pytest
from pywps.app import WPSRequest
from requests.models import Request, Response
from weaver.formats import CONTENT_TYPE_APP_NETCDF
from weaver.processes.wps3_process import Wps3Process
from weaver.visibility import VISIBILITY_PUBLIC
def test_wps3_process_step_io_data_or_href():
... | tests/processes/test_wps3_process.py | import json
import mock
import pytest
from pywps.app import WPSRequest
from requests.models import Request, Response
from weaver.formats import CONTENT_TYPE_APP_NETCDF
from weaver.processes.wps3_process import Wps3Process
from weaver.visibility import VISIBILITY_PUBLIC
def test_wps3_process_step_io_data_or_href():
... | 0.452536 | 0.342324 |
from math import floor
from app.models.base import db, Base
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from sqlalchemy import Column, Integer, String, Boolean, Float
from flask_login imp... | app/models/user.py | from math import floor
from app.models.base import db, Base
from flask import current_app
from werkzeug.security import generate_password_hash, check_password_hash
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from sqlalchemy import Column, Integer, String, Boolean, Float
from flask_login imp... | 0.48438 | 0.079317 |
import numpy as np
import argparse
from project.midi_handler import midi2score, score2midi
from project.utils import padding, load_model, save_model, add_beat
from project.test import style_transfer
from project.model import lstm_wavenet
from project.train import train
def main():
# Arguments
parser = argpars... | MusicStyleTransfer.py | import numpy as np
import argparse
from project.midi_handler import midi2score, score2midi
from project.utils import padding, load_model, save_model, add_beat
from project.test import style_transfer
from project.model import lstm_wavenet
from project.train import train
def main():
# Arguments
parser = argpars... | 0.501953 | 0.144843 |