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 json
from ducktape.tests.test import Test
from kafkatest.services.kafka import KafkaService
from kafkatest.services.trogdor.produce_bench_workload import ProduceBenchWorkloadService, ProduceBenchWorkloadSpec
from kafkatest.services.trogdor.task_spec import TaskSpec
from kafkatest.services.trogdor.trogdor import... | tests/kafkatest/tests/core/produce_bench_test.py |
import json
from ducktape.tests.test import Test
from kafkatest.services.kafka import KafkaService
from kafkatest.services.trogdor.produce_bench_workload import ProduceBenchWorkloadService, ProduceBenchWorkloadSpec
from kafkatest.services.trogdor.task_spec import TaskSpec
from kafkatest.services.trogdor.trogdor import... | 0.470737 | 0.204958 |
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | connect-four/ttt_pb2.py | """Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_insertion_point(imports)
_sym_db = _symbol_databas... | 0.243552 | 0.077727 |
import json
import os
import re
from ...helpers import article
from .._helpers import SphereScheme, cartesian_to_spherical, untangle2
# Sphere integration schemes from a series of publications, in chronological order
# <https://en.wikipedia.org/wiki/Lebedev_quadrature>
# <https://people.sc.fsu.edu/~jburkardt/datasets... | quadpy/sphere/_lebedev/__init__.py | import json
import os
import re
from ...helpers import article
from .._helpers import SphereScheme, cartesian_to_spherical, untangle2
# Sphere integration schemes from a series of publications, in chronological order
# <https://en.wikipedia.org/wiki/Lebedev_quadrature>
# <https://people.sc.fsu.edu/~jburkardt/datasets... | 0.640299 | 0.525795 |
import unittest
import invoiced
import responses
import json
from requests.exceptions import HTTPError, ConnectTimeout, ReadTimeout
class TestClient(unittest.TestCase):
def test_new_client(self):
client = invoiced.Client('api_key')
self.assertEqual('api_key', client.api_key)
self.assertE... | invoiced/test/test_client.py | import unittest
import invoiced
import responses
import json
from requests.exceptions import HTTPError, ConnectTimeout, ReadTimeout
class TestClient(unittest.TestCase):
def test_new_client(self):
client = invoiced.Client('api_key')
self.assertEqual('api_key', client.api_key)
self.assertE... | 0.512205 | 0.284588 |
import time
import urllib.request
import urllib.error
from socket import timeout
import json
import gzip
import logging
import shutil
import io
from config import PROXY, ERROR_DELAY, DEBUG, DELAY, ERROR_403_DELAY
logger = logging.getLogger(__name__)
def log(*args):
s = " ".join([str(i) for i in args])
logge... | http_api.py | import time
import urllib.request
import urllib.error
from socket import timeout
import json
import gzip
import logging
import shutil
import io
from config import PROXY, ERROR_DELAY, DEBUG, DELAY, ERROR_403_DELAY
logger = logging.getLogger(__name__)
def log(*args):
s = " ".join([str(i) for i in args])
logge... | 0.188436 | 0.066539 |
import pandas as pd
import os
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
import tensorflow as tf
import numpy as np
from bert4keras.backend import keras
from bert4keras.models import build_transformer_model
from keras.layers import Lambda, Dense
from keras import backend as K
from helper.seed import... | semi_final/noahsark/nezha/joint_train_val.py | import pandas as pd
import os
from iterstrat.ml_stratifiers import MultilabelStratifiedKFold
import tensorflow as tf
import numpy as np
from bert4keras.backend import keras
from bert4keras.models import build_transformer_model
from keras.layers import Lambda, Dense
from keras import backend as K
from helper.seed import... | 0.592431 | 0.196383 |
import subprocess
import re
import os
import sys
from collections import defaultdict
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from help_parser import HelpParser
unit_e_path = os.environ.get("UNIT_E_PATH")
if not unit_e_path:
sys.exit("UNIT_E_PATH is not set. Exiting.")
unite_cl... | helpers/rpc_docs/rpc_docs.py |
import subprocess
import re
import os
import sys
from collections import defaultdict
from pathlib import Path
from jinja2 import Environment, FileSystemLoader
from help_parser import HelpParser
unit_e_path = os.environ.get("UNIT_E_PATH")
if not unit_e_path:
sys.exit("UNIT_E_PATH is not set. Exiting.")
unite_cl... | 0.242026 | 0.064535 |
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
class ParticleFilter():
def __init__(self, data, particle=1000):
self.data = data.values
self.timelength = len(self.data)
self.n_particle = particle
self.sigma_2 = 2**(-2)
self.alpha_2 = 10**(-1)
... | Filter/particle_filter.py | import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
class ParticleFilter():
def __init__(self, data, particle=1000):
self.data = data.values
self.timelength = len(self.data)
self.n_particle = particle
self.sigma_2 = 2**(-2)
self.alpha_2 = 10**(-1)
... | 0.486575 | 0.479991 |
from db.mongo_setup import global_init
from fastapi import APIRouter, HTTPException
from services.scheduler_services import Scheduler, post_webhooks
from services.settings_services import SiteSettings, SiteTheme
from utils.snackbar import SnackResponse
router = APIRouter()
global_init()
scheduler = Scheduler()
schedu... | mealie/routes/setting_routes.py | from db.mongo_setup import global_init
from fastapi import APIRouter, HTTPException
from services.scheduler_services import Scheduler, post_webhooks
from services.settings_services import SiteSettings, SiteTheme
from utils.snackbar import SnackResponse
router = APIRouter()
global_init()
scheduler = Scheduler()
schedu... | 0.575111 | 0.053576 |
import argparse
import sys
import os
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, utils
from tqdm import tqdm
from vqvae import VQVAE
from scheduler import CycleScheduler
import distributed as dist
def train(epoch, ... | train_vqvae.py | import argparse
import sys
import os
import torch
from torch import nn, optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, utils
from tqdm import tqdm
from vqvae import VQVAE
from scheduler import CycleScheduler
import distributed as dist
def train(epoch, ... | 0.526586 | 0.203767 |
import functools
from vcr.matchers import query, body
from vcr.util import read_body
from cornell.cornell_helpers import expand_in_query, ODATA_EXPEND_FILTER, xml_in_headers, \
strip_soap_namespaces_from_body
def requests_match_conditions(*conditions):
def decorator(func):
@functools.wraps(func)
... | cornell/custom_matchers.py | import functools
from vcr.matchers import query, body
from vcr.util import read_body
from cornell.cornell_helpers import expand_in_query, ODATA_EXPEND_FILTER, xml_in_headers, \
strip_soap_namespaces_from_body
def requests_match_conditions(*conditions):
def decorator(func):
@functools.wraps(func)
... | 0.624294 | 0.192388 |
import time
from typing import Dict
from peewee import *
from playhouse.postgres_ext import ArrayField, BinaryJSONField
import config
from model import BaseModel, MyTimestampField, db
from model._post import POST_STATE, POST_TYPES
from model.user import User
from slim import json_ex_dumps
from slim.utils import StateO... | backend/model/notif.py | import time
from typing import Dict
from peewee import *
from playhouse.postgres_ext import ArrayField, BinaryJSONField
import config
from model import BaseModel, MyTimestampField, db
from model._post import POST_STATE, POST_TYPES
from model.user import User
from slim import json_ex_dumps
from slim.utils import StateO... | 0.196518 | 0.092647 |
import os
import re
import pyauto_functional # Must be imported before pyauto
import pyauto
import pyauto_utils
class AboutPluginsUITest(pyauto.PyUITest):
"""Testcase for chrome://plugins UI."""
def testAboutPluginDetailInfo(self):
"""Verify chrome://plugins page shows plugin details."""
self.Navigate... | chrome/test/functional/about_plugins_ui.py |
import os
import re
import pyauto_functional # Must be imported before pyauto
import pyauto
import pyauto_utils
class AboutPluginsUITest(pyauto.PyUITest):
"""Testcase for chrome://plugins UI."""
def testAboutPluginDetailInfo(self):
"""Verify chrome://plugins page shows plugin details."""
self.Navigate... | 0.677154 | 0.223049 |
"""The fseventsd event formatter."""
from __future__ import unicode_literals
from plaso.formatters import interface
from plaso.formatters import manager
from plaso.lib import errors
class FSEventsdEventFormatter(interface.ConditionalEventFormatter):
"""The fseventsd event formatter."""
DATA_TYPE = 'macos:fseve... | plaso/formatters/fseventsd.py | """The fseventsd event formatter."""
from __future__ import unicode_literals
from plaso.formatters import interface
from plaso.formatters import manager
from plaso.lib import errors
class FSEventsdEventFormatter(interface.ConditionalEventFormatter):
"""The fseventsd event formatter."""
DATA_TYPE = 'macos:fseve... | 0.789802 | 0.291939 |
import csv # to process CSV file
import cv2 # to read images and flip them
import numpy as np # to generate numpy arrays
import random # to generate random numbers in order to filter out some training data
def readCSV(filename):
""" Process CSV file
filename - Name of the CSV file which stores training da... | model.py | import csv # to process CSV file
import cv2 # to read images and flip them
import numpy as np # to generate numpy arrays
import random # to generate random numbers in order to filter out some training data
def readCSV(filename):
""" Process CSV file
filename - Name of the CSV file which stores training da... | 0.718594 | 0.626767 |
import node
import string
import random
import container
import control
# List of needed control nodes:
# s:load - input set of strings
# o:time - increments time between generations - (ClockObserver)
# s:samplertank - Chooses a tank to work over that hasn't been chosen in the current generation - (SimpleSampler... | StringCatChem/stringcat_nodes.py | import node
import string
import random
import container
import control
# List of needed control nodes:
# s:load - input set of strings
# o:time - increments time between generations - (ClockObserver)
# s:samplertank - Chooses a tank to work over that hasn't been chosen in the current generation - (SimpleSampler... | 0.398406 | 0.472927 |
import itertools
import numpy as np
from numpy.linalg import inv
from numpy.testing import (assert_array_almost_equal, assert_almost_equal,
assert_array_equal, assert_equal)
from scipy.spatial.transform import Rotation
from tadataka.camera import CameraParameters
from tadataka.matrix impo... | tests/test_matrix.py | import itertools
import numpy as np
from numpy.linalg import inv
from numpy.testing import (assert_array_almost_equal, assert_almost_equal,
assert_array_equal, assert_equal)
from scipy.spatial.transform import Rotation
from tadataka.camera import CameraParameters
from tadataka.matrix impo... | 0.78016 | 0.782995 |
from __future__ import absolute_import, print_function
import tensorflow as tf
from tensorflow.contrib.layers.python.layers import regularizers
from niftynet.network.vnet import VNetBlock
from tests.niftynet_testcase import NiftyNetTestCase
class VNetBlockTest(NiftyNetTestCase):
def get_2d_data(self):
i... | tests/vnetblock_test.py | from __future__ import absolute_import, print_function
import tensorflow as tf
from tensorflow.contrib.layers.python.layers import regularizers
from niftynet.network.vnet import VNetBlock
from tests.niftynet_testcase import NiftyNetTestCase
class VNetBlockTest(NiftyNetTestCase):
def get_2d_data(self):
i... | 0.688992 | 0.330255 |
import json
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import PermissionDenied
from .models import Contributor
from civictechprojects.models import ProjectLink, ProjectFile, FileCategory
from common.models.tags import Tag
class DemocracyLabUserCreationForm(UserCreationForm):
... | python-app/democracylab/forms.py | import json
from django.contrib.auth.forms import UserCreationForm
from django.core.exceptions import PermissionDenied
from .models import Contributor
from civictechprojects.models import ProjectLink, ProjectFile, FileCategory
from common.models.tags import Tag
class DemocracyLabUserCreationForm(UserCreationForm):
... | 0.261142 | 0.055438 |
from __future__ import absolute_import, unicode_literals
import io
import os
import stat
from hypothesis import HealthCheck, assume, example, given, settings
from hypothesis_fspaths import fspaths
from six.moves.urllib import parse as urllib_parse
import vistir
from .strategies import legal_path_chars, relative_pat... | tests/test_path.py | from __future__ import absolute_import, unicode_literals
import io
import os
import stat
from hypothesis import HealthCheck, assume, example, given, settings
from hypothesis_fspaths import fspaths
from six.moves.urllib import parse as urllib_parse
import vistir
from .strategies import legal_path_chars, relative_pat... | 0.404037 | 0.22835 |
import sys
import json
import itertools
from distance_util import DistanceUtil
def split_list_by_specific_value(iterable, splitters):
return [list(g) for k, g in itertools.groupby(iterable, lambda x: x in splitters) if not k]
if __name__ == '__main__':
for line in sys.stdin:
if not line.startswith('{... | preprocess/6.generate_para_match_score_feature.py | import sys
import json
import itertools
from distance_util import DistanceUtil
def split_list_by_specific_value(iterable, splitters):
return [list(g) for k, g in itertools.groupby(iterable, lambda x: x in splitters) if not k]
if __name__ == '__main__':
for line in sys.stdin:
if not line.startswith('{... | 0.260389 | 0.147893 |
from profilehooks import profile, timecall
import argparse
from model.shsamodel import SHSAModel
from model.substitutionlist import SubstitutionList
from engine.orr import ORR
from engine.dfs import DepthFirstSearch
from engine.shpgsa import SHPGSA
@timecall(immediate=False)
def orr(model, root):
engine = ORR(m... | shsa/benchmark/benchmark.py |
from profilehooks import profile, timecall
import argparse
from model.shsamodel import SHSAModel
from model.substitutionlist import SubstitutionList
from engine.orr import ORR
from engine.dfs import DepthFirstSearch
from engine.shpgsa import SHPGSA
@timecall(immediate=False)
def orr(model, root):
engine = ORR(m... | 0.515376 | 0.161155 |
import numpy as np
import cv2
import pdb
import math
from geometry import *
class MapPoint():
def __init__(self, pos, descriptor):
pos = np.array(pos).reshape(-1,1)
if len(pos) == 3:
pos = homogenize_vectors(pos)
self.pos = pos # Should be a homogeneous 4x1 column vector
self.descriptor = descriptor
def... | src/odometry_classes.py | import numpy as np
import cv2
import pdb
import math
from geometry import *
class MapPoint():
def __init__(self, pos, descriptor):
pos = np.array(pos).reshape(-1,1)
if len(pos) == 3:
pos = homogenize_vectors(pos)
self.pos = pos # Should be a homogeneous 4x1 column vector
self.descriptor = descriptor
def... | 0.509032 | 0.420362 |
import argparse
import os
import numpy as np
import yaml
import cv2
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", default=0, help="input video file or camera device")
parser.add_argument("-grid", "--grid", default="20x20", help="size of the grid (rows x cols)")
pa... | calibrate_camera.py | import argparse
import os
import numpy as np
import yaml
import cv2
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", default=0, help="input video file or camera device")
parser.add_argument("-grid", "--grid", default="20x20", help="size of the grid (rows x cols)")
pa... | 0.359814 | 0.199016 |
import argparse
import tempfile
import importlib
from importlib.machinery import SourceFileLoader
import os
import sys
import json
from furniture.animation import Animation
try:
from fontTools.misc.cliTools import makeOutputFileName
except:
print("fontTools not installed")
pass
def str2bool(v):
if v.l... | furniture/renderer.py | import argparse
import tempfile
import importlib
from importlib.machinery import SourceFileLoader
import os
import sys
import json
from furniture.animation import Animation
try:
from fontTools.misc.cliTools import makeOutputFileName
except:
print("fontTools not installed")
pass
def str2bool(v):
if v.l... | 0.159119 | 0.086516 |
from __future__ import unicode_literals
from unittest import TestCase
from wtforms.form import BaseForm, Form
from wtforms.meta import DefaultMeta
from wtforms.fields import StringField, IntegerField
from wtforms.validators import ValidationError
from tests.common import DummyPostData
class BaseFormTest(TestCase):
... | tests/form.py | from __future__ import unicode_literals
from unittest import TestCase
from wtforms.form import BaseForm, Form
from wtforms.meta import DefaultMeta
from wtforms.fields import StringField, IntegerField
from wtforms.validators import ValidationError
from tests.common import DummyPostData
class BaseFormTest(TestCase):
... | 0.734024 | 0.448306 |
import os,copy,argparse
from collections import OrderedDict
from pypospack.pyposmat.data import PyposmatDataFile
from pypospack.pyposmat.data import PyposmatConfigurationFile
from pypospack.pyposmat.data import PyposmatDataAnalyzer
def get_qoi_targets(o_config):
print(type(o_config))
assert type(o_config) is P... | examples/Si__sw/reference_potentials/make_rugplots.py | import os,copy,argparse
from collections import OrderedDict
from pypospack.pyposmat.data import PyposmatDataFile
from pypospack.pyposmat.data import PyposmatConfigurationFile
from pypospack.pyposmat.data import PyposmatDataAnalyzer
def get_qoi_targets(o_config):
print(type(o_config))
assert type(o_config) is P... | 0.190159 | 0.398641 |
# Copyright (c) 2013, <NAME>
# All rights reserved.
# Description of generated groups
import sugar.groups_generator
"""Universal group for files that is not chosen other groups"""
class AnyGroup:
def __init__(self, group_name):
self.result = sugar.groups_generator.Result(
r'{}'.format(group_name)
... | Toolkits/CMake/hunter/packages/sugar/python/sugar/groups.py |
# Copyright (c) 2013, <NAME>
# All rights reserved.
# Description of generated groups
import sugar.groups_generator
"""Universal group for files that is not chosen other groups"""
class AnyGroup:
def __init__(self, group_name):
self.result = sugar.groups_generator.Result(
r'{}'.format(group_name)
... | 0.813313 | 0.080719 |
import typing # noqa: F401
from kubernetes import client # noqa: F401
from kuber import kube_api as _kube_api # noqa: F401
from kuber import definitions as _kuber_definitions # noqa: F401
from kuber import _types # noqa: F401
from kuber.v1_21.meta_v1 import Condition # noqa: F401
from kuber.v1_21.meta_v1 import... | kuber/v1_21/policy_v1.py | import typing # noqa: F401
from kubernetes import client # noqa: F401
from kuber import kube_api as _kube_api # noqa: F401
from kuber import definitions as _kuber_definitions # noqa: F401
from kuber import _types # noqa: F401
from kuber.v1_21.meta_v1 import Condition # noqa: F401
from kuber.v1_21.meta_v1 import... | 0.724286 | 0.141815 |
from .contact_utils import *
__all__ = ["compute_vanderwaals"]
SOFT_VDW_CUTOFF = 0
def update_soft_cutoff(traj_frag_molid, index_to_atom, sele1, sele2, epsilon):
global SOFT_VDW_CUTOFF
ids1 = get_selection_indices(traj_frag_molid, 0, "%s" % sele1)
ids2 = get_selection_indices(traj_frag_molid, 0, "%s" %... | contact_calc/vanderwaals.py |
from .contact_utils import *
__all__ = ["compute_vanderwaals"]
SOFT_VDW_CUTOFF = 0
def update_soft_cutoff(traj_frag_molid, index_to_atom, sele1, sele2, epsilon):
global SOFT_VDW_CUTOFF
ids1 = get_selection_indices(traj_frag_molid, 0, "%s" % sele1)
ids2 = get_selection_indices(traj_frag_molid, 0, "%s" %... | 0.797714 | 0.263462 |
import streamlit as st
from ..constants import *
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def set_data(df):
st.title('Data')
menu_items = ["The Dataset", "The Users"]
menu_variables= st.radio("",menu_items)
df_small = df.head(500)
# Check if user davimenxpro is in t... | src/app/pages/data.py | import streamlit as st
from ..constants import *
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
def set_data(df):
st.title('Data')
menu_items = ["The Dataset", "The Users"]
menu_variables= st.radio("",menu_items)
df_small = df.head(500)
# Check if user davimenxpro is in t... | 0.458591 | 0.502441 |
import os
import sqlalchemy
import sqlalchemy.dialects.postgresql
import unittest
from pedsnetdcc.id_mapping_transform import IDMappingTransform
from pedsnetdcc.utils import make_conn_str, stock_metadata
class IDMappingTransformTest(unittest.TestCase):
def setUp(self):
self.metadata = stock_metadata('2.... | pedsnetdcc/tests/id_mapping_transform_test.py | import os
import sqlalchemy
import sqlalchemy.dialects.postgresql
import unittest
from pedsnetdcc.id_mapping_transform import IDMappingTransform
from pedsnetdcc.utils import make_conn_str, stock_metadata
class IDMappingTransformTest(unittest.TestCase):
def setUp(self):
self.metadata = stock_metadata('2.... | 0.196017 | 0.439747 |
""" ds status Check for OpenShift V3 """
# pylint: disable=invalid-name
# pylint: disable=wrong-import-position
# pylint: disable=broad-except
# pylint: disable=line-too-long
import argparse
import time
import sys
import logging
sys.path.insert(0, '/container_setup')
from zabbix_data_sync import *
logging.basicCon... | scripts/monitoring/cron-send-daemonset-status.py | """ ds status Check for OpenShift V3 """
# pylint: disable=invalid-name
# pylint: disable=wrong-import-position
# pylint: disable=broad-except
# pylint: disable=line-too-long
import argparse
import time
import sys
import logging
sys.path.insert(0, '/container_setup')
from zabbix_data_sync import *
logging.basicCon... | 0.331769 | 0.110471 |
"""RomaFileOps class."""
import os
import fcntl
import logging
import moxing
from vega.core import FileOps
class RomaFileOps(object):
"""This is the class which use the function of roma."""
@classmethod
def copy_folder(cls, src, dst):
"""Copy a local dir to s3 bucket.
:param str src: pat... | built-in/TensorFlow/Official/cv/image_classification/ResnetVariant_for_TensorFlow/automl/roma/file_ops.py | """RomaFileOps class."""
import os
import fcntl
import logging
import moxing
from vega.core import FileOps
class RomaFileOps(object):
"""This is the class which use the function of roma."""
@classmethod
def copy_folder(cls, src, dst):
"""Copy a local dir to s3 bucket.
:param str src: pat... | 0.650356 | 0.332365 |
import os.path
from datetime import datetime, timedelta
from app import storage
from data import model
from data.database import LogEntry, LogEntry2, LogEntry3
from data.logs_model.elastic_logs import INDEX_NAME_PREFIX, INDEX_DATE_FORMAT
from data.logs_model.datatypes import AggregatedLogCount, LogEntriesPage, Log
f... | workers/test/test_logrotateworker.py | import os.path
from datetime import datetime, timedelta
from app import storage
from data import model
from data.database import LogEntry, LogEntry2, LogEntry3
from data.logs_model.elastic_logs import INDEX_NAME_PREFIX, INDEX_DATE_FORMAT
from data.logs_model.datatypes import AggregatedLogCount, LogEntriesPage, Log
f... | 0.610802 | 0.314156 |
import dbus
import dbus.mainloop.glib
import HFPEvent as Event
class HFP:
push_event = None
call_path = None
incoming_path = None
bus = None
modem = None
def __init__(self, push_event):
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
manager = dbus.Interface(bus.get_object... | HFP.py |
import dbus
import dbus.mainloop.glib
import HFPEvent as Event
class HFP:
push_event = None
call_path = None
incoming_path = None
bus = None
modem = None
def __init__(self, push_event):
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
manager = dbus.Interface(bus.get_object... | 0.07597 | 0.091139 |
import collections
import re
import peru.glob as glob
import shared
class GlobTest(shared.PeruTest):
def test_split_on_stars_interpreting_backslashes(self):
cases = [
('', ['']),
('*', ['', '']),
('abc', ['abc']),
('abc\\', ['abc\\']),
('abc\\n'... | tests/test_glob.py | import collections
import re
import peru.glob as glob
import shared
class GlobTest(shared.PeruTest):
def test_split_on_stars_interpreting_backslashes(self):
cases = [
('', ['']),
('*', ['', '']),
('abc', ['abc']),
('abc\\', ['abc\\']),
('abc\\n'... | 0.282295 | 0.198064 |
import os
from django.core.files import File
from django.core.management.base import BaseCommand
from waldur_mastermind.marketplace.models import (
Attribute,
AttributeOption,
Category,
CategoryColumn,
CategoryComponent,
Section,
)
def merge_two_dicts(x, y):
z = x.copy() # start with x'... | src/waldur_mastermind/marketplace/management/commands/load_categories.py | import os
from django.core.files import File
from django.core.management.base import BaseCommand
from waldur_mastermind.marketplace.models import (
Attribute,
AttributeOption,
Category,
CategoryColumn,
CategoryComponent,
Section,
)
def merge_two_dicts(x, y):
z = x.copy() # start with x'... | 0.492676 | 0.215382 |
import falcon
import base64
import logging
import os
import json
from ..helpers.configurator import Configurator
from ..helpers.hmac_validator import HMACValidator
from ..helpers.request_store import RequestStore
logging.basicConfig(level=logging.INFO)
class AuthMiddleware(object):
def __init__(self):
c... | swobup/middleware/hmacAuth_middleware.py | import falcon
import base64
import logging
import os
import json
from ..helpers.configurator import Configurator
from ..helpers.hmac_validator import HMACValidator
from ..helpers.request_store import RequestStore
logging.basicConfig(level=logging.INFO)
class AuthMiddleware(object):
def __init__(self):
c... | 0.277375 | 0.048971 |
from spotipy.oauth2 import SpotifyClientCredentials
from spotipy import Spotify
import json
from sys import argv
def spotify_authentication(client_id, client_secret, playlist_id):
"""
This part verifies the credentials for the spotify-api usage
Args:
client_id:
client_secret:
playlist_id: Playlist i... | SpotDown/spotipy_api/client.py | from spotipy.oauth2 import SpotifyClientCredentials
from spotipy import Spotify
import json
from sys import argv
def spotify_authentication(client_id, client_secret, playlist_id):
"""
This part verifies the credentials for the spotify-api usage
Args:
client_id:
client_secret:
playlist_id: Playlist i... | 0.181299 | 0.073364 |
def egyptian(c,d):
i=1
j=2
L=[]
K=[]
print(r"$$\begin{array}{rrr}")
a=c
b=d
rest1=a
zeile=0
while i<=a:
L.append([i,i*b,zeile])
rest1-=i
i=10*i
zeile+=1
while j-1<=rest1:
L.append([j,j*b,zeile])
j=2*j
rest=rest1
zeile+=1
rest=a
L.sort(key=lambda x: int(x[0]))
... | advanced-examples-eng/egyptian1.py | def egyptian(c,d):
i=1
j=2
L=[]
K=[]
print(r"$$\begin{array}{rrr}")
a=c
b=d
rest1=a
zeile=0
while i<=a:
L.append([i,i*b,zeile])
rest1-=i
i=10*i
zeile+=1
while j-1<=rest1:
L.append([j,j*b,zeile])
j=2*j
rest=rest1
zeile+=1
rest=a
L.sort(key=lambda x: int(x[0]))
... | 0.201971 | 0.268102 |
import copy
from oslo_utils import excutils
import webob
from designer_family import errors
from designer_family import exception
# TODO(cdent): That we are doing this suggests that there's stuff to be
# extracted from the handler to a shared module.
from designer_family.handlers import allocation
from designer_famil... | designer_family/handlers/reshaper.py | import copy
from oslo_utils import excutils
import webob
from designer_family import errors
from designer_family import exception
# TODO(cdent): That we are doing this suggests that there's stuff to be
# extracted from the handler to a shared module.
from designer_family.handlers import allocation
from designer_famil... | 0.205057 | 0.075142 |
import numpy as np
from neural_compressor.utils.utility import LazyImport
from .transform import transform_registry, BaseTransform
tf = LazyImport('tensorflow')
cv2 = LazyImport('cv2')
@transform_registry(transform_type="QuantizedInput", \
process="preprocess", framework="tensorflow")
class Quanti... | neural_compressor/experimental/data/transforms/imagenet_transform.py |
import numpy as np
from neural_compressor.utils.utility import LazyImport
from .transform import transform_registry, BaseTransform
tf = LazyImport('tensorflow')
cv2 = LazyImport('cv2')
@transform_registry(transform_type="QuantizedInput", \
process="preprocess", framework="tensorflow")
class Quanti... | 0.926387 | 0.426083 |
from nexus import settings,job,run_project
from nexus import generate_physical_system
from nexus import generate_pwscf
from nexus import generate_pw2qmcpack
from nexus import generate_qmcpack,vmc
from structure import *
settings(
pseudo_dir = '../../pseudopotentials',
status_only = 0,
generate_only =... | nexus/examples/qmcpack/rsqmc_misc/excited/band.py |
from nexus import settings,job,run_project
from nexus import generate_physical_system
from nexus import generate_pwscf
from nexus import generate_pw2qmcpack
from nexus import generate_qmcpack,vmc
from structure import *
settings(
pseudo_dir = '../../pseudopotentials',
status_only = 0,
generate_only =... | 0.356895 | 0.194406 |
import sys, os
headers= [[3e-4, 9.36e-5, 3.0593e-6, 133443824], \
[4e-4, 2.099e-4, 4.5810e-6, 102734148], \
[5e-4, 3.96e-4, 6.2916e-6, 84332489], \
[6e-4, 6.635e-4, 8.1428e-6, 72160925], \
[7e-4, 0.0010, 1.0228e-5, 63397696], \
[8e-4, 0.0015, 1.2418e-5, 56898453]]
#... | Data/Compact/Surface_1EC_D5/compressor.py |
import sys, os
headers= [[3e-4, 9.36e-5, 3.0593e-6, 133443824], \
[4e-4, 2.099e-4, 4.5810e-6, 102734148], \
[5e-4, 3.96e-4, 6.2916e-6, 84332489], \
[6e-4, 6.635e-4, 8.1428e-6, 72160925], \
[7e-4, 0.0010, 1.0228e-5, 63397696], \
[8e-4, 0.0015, 1.2418e-5, 56898453]]
#... | 0.099405 | 0.419886 |
from __future__ import division, print_function
import sys
from math import log, ceil
from optparse import OptionParser
import subprocess
# crack the command line
parser = OptionParser(
usage="%prog lower-revision upper-revision test_script [arg1 ...]",
description="Binary search for a bug i... | bin/svn-bisect.py | from __future__ import division, print_function
import sys
from math import log, ceil
from optparse import OptionParser
import subprocess
# crack the command line
parser = OptionParser(
usage="%prog lower-revision upper-revision test_script [arg1 ...]",
description="Binary search for a bug i... | 0.365117 | 0.136349 |
import pytest
from sept.parser import PathTemplateParser
from sept.balancer import ParenthesisBalancer
from sept.errors import (
ParsingError,
OperatorNotFoundError,
OpeningBalancingParenthesisError,
ClosingBalancingParenthesisError,
MultipleBalancingError,
)
state_data = {
"name": "AhUgHeS",
... | tests/test_basic.py | import pytest
from sept.parser import PathTemplateParser
from sept.balancer import ParenthesisBalancer
from sept.errors import (
ParsingError,
OperatorNotFoundError,
OpeningBalancingParenthesisError,
ClosingBalancingParenthesisError,
MultipleBalancingError,
)
state_data = {
"name": "AhUgHeS",
... | 0.477311 | 0.44734 |
import twint
import psaw
import datetime as dt
import csv
from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request
import time
import credentials
import pandas as pd
def tweet_scr(key, since, until, out):
"""
this function is dedicated to scrap Twitter data using Twint
:param ke... | nlp_project/data_fetching.py | import twint
import psaw
import datetime as dt
import csv
from bs4 import BeautifulSoup
from bs4.element import Comment
import urllib.request
import time
import credentials
import pandas as pd
def tweet_scr(key, since, until, out):
"""
this function is dedicated to scrap Twitter data using Twint
:param ke... | 0.247805 | 0.220489 |
import io
import os
import sys
from datetime import datetime
import matplotlib.pyplot as plt
from PIL import Image
from github import Github, GithubException
import constants
import notify_chat
import utils
ballerina_bot_token = os.environ[constants.ENV_BALLERINA_BOT_TOKEN]
README_FILE = "README.md"
github = Githu... | dependabot/update_lag_status.py | import io
import os
import sys
from datetime import datetime
import matplotlib.pyplot as plt
from PIL import Image
from github import Github, GithubException
import constants
import notify_chat
import utils
ballerina_bot_token = os.environ[constants.ENV_BALLERINA_BOT_TOKEN]
README_FILE = "README.md"
github = Githu... | 0.190724 | 0.097347 |
from asyncio import sleep
from telethon.tl.types import ChatBannedRights
from telethon.tl.functions.channels import EditBannedRequest
from userbot.events import register
from userbot import CMD_HELP
# Ported Apis Ganteng ( Hexxa - Userbot )
@register(outgoing=True, pattern="^.xban(?: |$)(.*)")
async def allban(event)... | userbot/modules/super_all.py | from asyncio import sleep
from telethon.tl.types import ChatBannedRights
from telethon.tl.functions.channels import EditBannedRequest
from userbot.events import register
from userbot import CMD_HELP
# Ported Apis Ganteng ( Hexxa - Userbot )
@register(outgoing=True, pattern="^.xban(?: |$)(.*)")
async def allban(event)... | 0.348978 | 0.102484 |
import unittest
from conans.client.conf import default_settings_yml
from conans.client.generators.pkg_config import PkgConfigGenerator
from conans.model.build_info import CppInfo
from conans.model.conan_file import ConanFile
from conans.model.env_info import EnvValues
from conans.model.ref import ConanFileReference
fr... | conans/test/unittests/client/generators/pkg_config_test.py | import unittest
from conans.client.conf import default_settings_yml
from conans.client.generators.pkg_config import PkgConfigGenerator
from conans.model.build_info import CppInfo
from conans.model.conan_file import ConanFile
from conans.model.env_info import EnvValues
from conans.model.ref import ConanFileReference
fr... | 0.28877 | 0.118156 |
import sys
import webbrowser
import click
import homeassistant_cli.autocompletion as autocompletion
from homeassistant_cli.cli import pass_context
from homeassistant_cli.config import Configuration
import homeassistant_cli.remote as api
OSM_URL = "https://www.openstreetmap.org/"
GOOGLE_URL = "https://www.google.com/... | homeassistant_cli/plugins/map.py | import sys
import webbrowser
import click
import homeassistant_cli.autocompletion as autocompletion
from homeassistant_cli.cli import pass_context
from homeassistant_cli.config import Configuration
import homeassistant_cli.remote as api
OSM_URL = "https://www.openstreetmap.org/"
GOOGLE_URL = "https://www.google.com/... | 0.36727 | 0.177882 |
from __future__ import division
from python_qt_binding.QtCore import QPointF, QRectF, Qt
from python_qt_binding.QtGui import QGraphicsView, QTransform
class InteractiveGraphicsView(QGraphicsView):
def __init__(self, parent=None):
super(InteractiveGraphicsView, self).__init__(parent)
self.setObje... | rqt_decision_graph/src/rqt_decision_graph/interactive_graphics_view.py | from __future__ import division
from python_qt_binding.QtCore import QPointF, QRectF, Qt
from python_qt_binding.QtGui import QGraphicsView, QTransform
class InteractiveGraphicsView(QGraphicsView):
def __init__(self, parent=None):
super(InteractiveGraphicsView, self).__init__(parent)
self.setObje... | 0.753013 | 0.365372 |
import itertools
import re
from typing import (
Iterable,
TYPE_CHECKING,
Optional,
Callable,
Dict,
List,
)
if TYPE_CHECKING:
from ... import DocumentArray, Document
from ...types import T
ATTRIBUTES_SEPARATOR = ','
PATHS_SEPARATOR = ','
SLICE_BASE = r'[-\d:]+'
WRAPPED_SLICE_BASE = r'\... | docarray/array/mixins/traverse.py | import itertools
import re
from typing import (
Iterable,
TYPE_CHECKING,
Optional,
Callable,
Dict,
List,
)
if TYPE_CHECKING:
from ... import DocumentArray, Document
from ...types import T
ATTRIBUTES_SEPARATOR = ','
PATHS_SEPARATOR = ','
SLICE_BASE = r'[-\d:]+'
WRAPPED_SLICE_BASE = r'\... | 0.68679 | 0.151153 |
import argparse
from models import auth
from models import options
from subprocess import call
def parser():
pars = argparse.ArgumentParser(description='Script hacking ODOO')
pars.add_argument('host',help='URL o HOST de ODOO')
arguments = pars.parse_args()
return arguments
def main(arguments):
call... | main.py | import argparse
from models import auth
from models import options
from subprocess import call
def parser():
pars = argparse.ArgumentParser(description='Script hacking ODOO')
pars.add_argument('host',help='URL o HOST de ODOO')
arguments = pars.parse_args()
return arguments
def main(arguments):
call... | 0.309128 | 0.117395 |
import argparse
import os
import sys
import json
import numpy as np
PROG = os.path.basename(sys.argv[0])
def main():
parser = argparse.ArgumentParser(
description='Fix a raman.json file created before 99e7a42a5 (June 14)',
)
parser.add_argument('INPUT', nargs='*')
parser.add_argument(
... | rsp2/scripts/fix-raman-tensors.py |
import argparse
import os
import sys
import json
import numpy as np
PROG = os.path.basename(sys.argv[0])
def main():
parser = argparse.ArgumentParser(
description='Fix a raman.json file created before 99e7a42a5 (June 14)',
)
parser.add_argument('INPUT', nargs='*')
parser.add_argument(
... | 0.306008 | 0.258086 |
import pytest
import numpy as np
from numpy.testing import assert_allclose
import astropy.units as u
from gammapy.datasets import Datasets, SpectrumDatasetOnOff
from gammapy.estimators.flux import FluxEstimator
from gammapy.modeling.models import PowerLawSpectralModel, SkyModel
from gammapy.utils.testing import require... | gammapy/estimators/tests/test_flux.py | import pytest
import numpy as np
from numpy.testing import assert_allclose
import astropy.units as u
from gammapy.datasets import Datasets, SpectrumDatasetOnOff
from gammapy.estimators.flux import FluxEstimator
from gammapy.modeling.models import PowerLawSpectralModel, SkyModel
from gammapy.utils.testing import require... | 0.675658 | 0.575349 |
import io
import re
import setuptools
from setuptools import setup
PACKAGE_NAME = 'petastorm'
with open('README.rst') as f:
long_description = f.read()
with io.open('petastorm/__init__.py', 'rt', encoding='utf8') as f:
version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)
if version is No... | setup.py |
import io
import re
import setuptools
from setuptools import setup
PACKAGE_NAME = 'petastorm'
with open('README.rst') as f:
long_description = f.read()
with io.open('petastorm/__init__.py', 'rt', encoding='utf8') as f:
version = re.search(r'__version__ = \'(.*?)\'', f.read()).group(1)
if version is No... | 0.374448 | 0.216425 |
import requests
import pandas as pd
import os
data = []
url = "http://ehall.szu.edu.cn/jwapp/sys/kccx/modules/kccx/kcxxcx.do"
headers = {
'Accept':'*/*',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'zh-CN,zh;q=0.9',
'Connection':'keep-alive',
'Cookie':'route=dca48fec126b3d7c5e6354cda3035b78; EMAP_LA... | code/getCourseBaseData.py | import requests
import pandas as pd
import os
data = []
url = "http://ehall.szu.edu.cn/jwapp/sys/kccx/modules/kccx/kcxxcx.do"
headers = {
'Accept':'*/*',
'Accept-Encoding':'gzip, deflate',
'Accept-Language':'zh-CN,zh;q=0.9',
'Connection':'keep-alive',
'Cookie':'route=dca48fec126b3d7c5e6354cda3035b78; EMAP_LA... | 0.051059 | 0.0809 |
import os
import joblib
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
#MODELS_FILE_PATH = './../mod... | src/models/predict_model.py | import os
import joblib
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
#MODELS_FILE_PATH = './../mod... | 0.541166 | 0.239761 |
import os
from ..plugin import Plugin
from ..loader import Loader
from ..control import Control
from ..exception import FrictionlessException
from .. import errors
# Plugin
class StreamPlugin(Plugin):
"""Plugin for Local Data
API | Usage
-------- | --------
Public | `from frictionless.plugin... | frictionless/plugins/stream.py | import os
from ..plugin import Plugin
from ..loader import Loader
from ..control import Control
from ..exception import FrictionlessException
from .. import errors
# Plugin
class StreamPlugin(Plugin):
"""Plugin for Local Data
API | Usage
-------- | --------
Public | `from frictionless.plugin... | 0.759315 | 0.126677 |
"""Parser for utmpx files."""
from dfdatetime import posix_time as dfdatetime_posix_time
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import errors
from plaso.lib import definitions
from plaso.lib import specification
from plaso.parsers import dtfabric_parser
from plaso.... | plaso/parsers/utmpx.py | """Parser for utmpx files."""
from dfdatetime import posix_time as dfdatetime_posix_time
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import errors
from plaso.lib import definitions
from plaso.lib import specification
from plaso.parsers import dtfabric_parser
from plaso.... | 0.729327 | 0.276839 |
import sys
from PySide2.QtWidgets import *
from PySide2 import QtGui
from PySide2.QtCore import Qt
from widgets.tab_table import TabTable
from widgets.pandas_model import PandasModel
class BulkAnalysis(QWidget):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
sel... | layouts/bulk_analysis.py | import sys
from PySide2.QtWidgets import *
from PySide2 import QtGui
from PySide2.QtCore import Qt
from widgets.tab_table import TabTable
from widgets.pandas_model import PandasModel
class BulkAnalysis(QWidget):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
sel... | 0.435661 | 0.147187 |
import os
import numpy as np
from qutip.interpolate import Cubic_Spline
_cython_path = os.path.dirname(os.path.abspath(__file__)).replace("\\", "/")
_include_string = "'"+_cython_path+"/complex_math.pxi'"
__all__ = ['Codegen']
class Codegen():
"""
Class for generating cython code files at runtime.
"""
... | qutip/cy/codegen.py | import os
import numpy as np
from qutip.interpolate import Cubic_Spline
_cython_path = os.path.dirname(os.path.abspath(__file__)).replace("\\", "/")
_include_string = "'"+_cython_path+"/complex_math.pxi'"
__all__ = ['Codegen']
class Codegen():
"""
Class for generating cython code files at runtime.
"""
... | 0.342681 | 0.178705 |
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, HTML, Field
from django import forms
from django.forms.widgets import ClearableFileInput
from django.utils.translation import ugettext as _
from mecc.apps.utils.widgets import Custom... | mecc/apps/years/forms.py | from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, HTML, Field
from django import forms
from django.forms.widgets import ClearableFileInput
from django.utils.translation import ugettext as _
from mecc.apps.utils.widgets import Custom... | 0.519278 | 0.105625 |
__author__ = '<NAME> (gfxman)'
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.translator import *
from datetime import datetime
class TestTraversalStrategies(object):
def test_translations(self):
g = traversal... | gremlin-python/src/main/python/tests/process/test_translator.py | __author__ = '<NAME> (gfxman)'
from gremlin_python.structure.graph import Graph
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.translator import *
from datetime import datetime
class TestTraversalStrategies(object):
def test_translations(self):
g = traversal... | 0.269518 | 0.292059 |
import numpy as np
from .. import base
from river.utils.skmultiflow_utils import check_random_state
class LED(base.SyntheticDataset):
""" LED stream generator.
This data source originates from the CART book [^1]. An implementation
in C was donated to the UCI [^2] machine learning repository by <NAME>.
... | river/datasets/synth/led.py | import numpy as np
from .. import base
from river.utils.skmultiflow_utils import check_random_state
class LED(base.SyntheticDataset):
""" LED stream generator.
This data source originates from the CART book [^1]. An implementation
in C was donated to the UCI [^2] machine learning repository by <NAME>.
... | 0.872741 | 0.697094 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .torx.adc import _adc
from .torx.dac import _quantize_dac
quantize_input = _quantize_dac.apply
quantize_weight = _quantize_dac.apply
adc = _adc.apply
class QConv2d(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size,
... | model/quantize3.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .torx.adc import _adc
from .torx.dac import _quantize_dac
quantize_input = _quantize_dac.apply
quantize_weight = _quantize_dac.apply
adc = _adc.apply
class QConv2d(nn.Conv2d):
def __init__(self, in_channels, out_channels, kernel_size,
... | 0.805441 | 0.33185 |
import argparse
import numpy as np
from metpy.units import units
from ncmagics import fetchtime, japanmap_nh, meteotool_nh
def parse_args() -> dict:
"""parse_args.
set file path.
Args:
Returns:
dict:
"""
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help=... | ptl_vrt_nh.py | import argparse
import numpy as np
from metpy.units import units
from ncmagics import fetchtime, japanmap_nh, meteotool_nh
def parse_args() -> dict:
"""parse_args.
set file path.
Args:
Returns:
dict:
"""
parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file", help=... | 0.72086 | 0.409221 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import codecs
import doctest
import fnmatch
import glob
import errno
import json
import os
import platform
import pprint
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import... | guild/_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import codecs
import doctest
import fnmatch
import glob
import errno
import json
import os
import platform
import pprint
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import... | 0.36693 | 0.069038 |
# autogenerated on 2020-05-06 22:13
# Split and Merge
import cv2
import numpy as np
from utils import *
def check_variance(img, var_threshold):
var = np.var(img.ravel())
return var > var_threshold
class AbstractQuadTree:
def __init__(self, data):
self.value = data
self.tl = None
... | lab_14.py |
# autogenerated on 2020-05-06 22:13
# Split and Merge
import cv2
import numpy as np
from utils import *
def check_variance(img, var_threshold):
var = np.var(img.ravel())
return var > var_threshold
class AbstractQuadTree:
def __init__(self, data):
self.value = data
self.tl = None
... | 0.500732 | 0.355243 |
import tensorflow as tf
def euclidean_sq_distance(x, y, all_pairs=False):
"""
Computes Euclidean squared distance.
:param x: Tensor of size B1 x d
:param y: Tensor of size (B1 x) B2 x d if rhs_dep_lhs = False (True)
:param all_pairs: boolean indicating whether to compute pairwise distances from ... | hyperbolic-rs/rudders/math/euclid.py |
import tensorflow as tf
def euclidean_sq_distance(x, y, all_pairs=False):
"""
Computes Euclidean squared distance.
:param x: Tensor of size B1 x d
:param y: Tensor of size (B1 x) B2 x d if rhs_dep_lhs = False (True)
:param all_pairs: boolean indicating whether to compute pairwise distances from ... | 0.951908 | 0.885086 |
from tradersbot import TradersBot
import sys
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
class AlgoBot(TradersBot):
#Initialize variables: positions, expectations, future customer orders, etc
POSITION_LIMIT = 5000
CASE_LENGTH = 450
CURRENCY = 'USD'
ORDER_DELAY = ... | Algo S&T/algo_bot.py | from tradersbot import TradersBot
import sys
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
class AlgoBot(TradersBot):
#Initialize variables: positions, expectations, future customer orders, etc
POSITION_LIMIT = 5000
CASE_LENGTH = 450
CURRENCY = 'USD'
ORDER_DELAY = ... | 0.185762 | 0.1425 |
import json
from typing import Dict
from formula_getter_setter import integer_types, decimal_types
import AlteryxPythonSDK as Sdk
import xml.etree.ElementTree as Et
import pika
class AyxPlugin:
def __init__(self, n_tool_id: int, alteryx_engine: object, output_anchor_mgr: object):
# Default properties
... | StreamerCode/rabbitmq_out.py | import json
from typing import Dict
from formula_getter_setter import integer_types, decimal_types
import AlteryxPythonSDK as Sdk
import xml.etree.ElementTree as Et
import pika
class AyxPlugin:
def __init__(self, n_tool_id: int, alteryx_engine: object, output_anchor_mgr: object):
# Default properties
... | 0.701713 | 0.100746 |
from dataclasses import dataclass
from enum import Enum
from typing import List, Dict
from dome9 import Dome9Resource, Client, BaseDataclassRequest
class OrganizationalUnitConsts(Enum):
ORGANIZATIONAL_UNIT = 'OrganizationalUnit'
FLAT_ORGANIZATIONAL_UNIT = 'GetFlatOrganizationalUnits'
CLOUD_ACCOUNTS = 'cloudaccou... | resources/organizational_unit.py | from dataclasses import dataclass
from enum import Enum
from typing import List, Dict
from dome9 import Dome9Resource, Client, BaseDataclassRequest
class OrganizationalUnitConsts(Enum):
ORGANIZATIONAL_UNIT = 'OrganizationalUnit'
FLAT_ORGANIZATIONAL_UNIT = 'GetFlatOrganizationalUnits'
CLOUD_ACCOUNTS = 'cloudaccou... | 0.82748 | 0.228867 |
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
import os
from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.losses import *
from keras import backend as K
from keras.utils import plot_model
import pandas as pd
from all_utils import get_... | Landmark_Detection/train.py | import numpy as np
from keras.preprocessing.image import ImageDataGenerator
import os
from keras.models import *
from keras.layers import *
from keras.optimizers import *
from keras.losses import *
from keras import backend as K
from keras.utils import plot_model
import pandas as pd
from all_utils import get_... | 0.535827 | 0.119254 |
import pandas as pd
import numpy as np
from math import log, exp
from random import uniform
class UtilityModel:
def __init__(self,name,churn_rate,behavior_model):
'''
This class calculates the churn probability for a customer based on their event counts. Its called a "Utility
Model" to me... | data-generation/py/utility.py | import pandas as pd
import numpy as np
from math import log, exp
from random import uniform
class UtilityModel:
def __init__(self,name,churn_rate,behavior_model):
'''
This class calculates the churn probability for a customer based on their event counts. Its called a "Utility
Model" to me... | 0.887314 | 0.855972 |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
parse_resolution,
try_get,
unified_timestamp,
url_or_none,
urljoin,
)
class PeerTubeIE(InfoExtractor):
_INSTANCES_RE = r'''(?:
... | youtube_dl/extractor/peertube.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
int_or_none,
parse_resolution,
try_get,
unified_timestamp,
url_or_none,
urljoin,
)
class PeerTubeIE(InfoExtractor):
_INSTANCES_RE = r'''(?:
... | 0.499756 | 0.112942 |
import argparse
import os
import sys
import json
import h5py
import shutil
import numpy as np
from datetime import datetime
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--gpu_num", type=int, default=0)
# models
... | option.py | import argparse
import os
import sys
import json
import h5py
import shutil
import numpy as np
from datetime import datetime
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--seed", type=int, default=0)
parser.add_argument("--gpu_num", type=int, default=0)
# models
... | 0.217088 | 0.046834 |
import torch
from torch import nn
import math
import numpy as np
from utils.misc import NestedTensor
"""
1D position encoding and 2D postion encoding
The code is modified based on DETR of Facebook:
https://github.com/facebookresearch/detr/blob/master/models/position_encoding.py
"""
class PositionEmbeddding1D(nn.Modu... | utils/position_encoding.py | import torch
from torch import nn
import math
import numpy as np
from utils.misc import NestedTensor
"""
1D position encoding and 2D postion encoding
The code is modified based on DETR of Facebook:
https://github.com/facebookresearch/detr/blob/master/models/position_encoding.py
"""
class PositionEmbeddding1D(nn.Modu... | 0.940667 | 0.659445 |
import logging
import json
from pathlib import Path
from metaflow import Run
from eurito_indicators import get_yaml_config, PROJECT_DIR
from eurito_indicators.utils.metaflow_runner import update_model_config, execute_flow
from industrial_taxonomy.flows.classifier.classifier_utils import create_org_data
logger = log... | ds/eurito_indicators/pipeline/sdg/run_classifier_train.py | import logging
import json
from pathlib import Path
from metaflow import Run
from eurito_indicators import get_yaml_config, PROJECT_DIR
from eurito_indicators.utils.metaflow_runner import update_model_config, execute_flow
from industrial_taxonomy.flows.classifier.classifier_utils import create_org_data
logger = log... | 0.2676 | 0.103612 |
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import urlparse
import urllib
import json
import logging
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
sh = logging.StreamHandler()
sh.setLevel(lo... | theappnetas/appliance.py | import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import urlparse
import urllib
import json
import logging
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
sh = logging.StreamHandler()
sh.setLevel(lo... | 0.278159 | 0.062132 |
from __settings__ import *
from opensimplex import OpenSimplex
from random import randint
from filters.int_median_cutter import int_median_cutter
def refactor(map_array: list, min_height: int, max_height: int):
"""
Function blending map composed from rectangular chunks into seamless one, without visible... | filters/refactor.py | from __settings__ import *
from opensimplex import OpenSimplex
from random import randint
from filters.int_median_cutter import int_median_cutter
def refactor(map_array: list, min_height: int, max_height: int):
"""
Function blending map composed from rectangular chunks into seamless one, without visible... | 0.754825 | 0.26354 |
from twisted.internet import base
from twisted.internet import defer
from twisted.internet.task import Clock
from twisted.test.iosim import connectedServerAndClient
from twisted.trial import unittest
import txredisapi as redis
from tests.mixins import REDIS_HOST, REDIS_PORT
from tests.test_sentinel import FakeRedisPr... | tests/test_connection.py | from twisted.internet import base
from twisted.internet import defer
from twisted.internet.task import Clock
from twisted.test.iosim import connectedServerAndClient
from twisted.trial import unittest
import txredisapi as redis
from tests.mixins import REDIS_HOST, REDIS_PORT
from tests.test_sentinel import FakeRedisPr... | 0.490968 | 0.102215 |
import os
import json
from uuid import uuid4
from socket import gethostname
from typing import List, Optional
import pydantic
from .models import PingHost
ENV_FILE = os.getenv("ENV_FILE", ".env")
class BaseSettings(pydantic.BaseSettings):
class Config:
env_file = ENV_FILE
class GeneralSettings(BaseSe... | ping2mqtt/settings.py | import os
import json
from uuid import uuid4
from socket import gethostname
from typing import List, Optional
import pydantic
from .models import PingHost
ENV_FILE = os.getenv("ENV_FILE", ".env")
class BaseSettings(pydantic.BaseSettings):
class Config:
env_file = ENV_FILE
class GeneralSettings(BaseSe... | 0.427636 | 0.069795 |
import responses
from matrix_client import client
class TestTagsApi:
cli = client.MatrixClient("http://example.com")
user_id = "@user:matrix.org"
room_id = "#foo:matrix.org"
@responses.activate
def test_get_user_tags(self):
tags_url = "http://example.com" \
"/_matrix/client/r0/... | test/api_test.py | import responses
from matrix_client import client
class TestTagsApi:
cli = client.MatrixClient("http://example.com")
user_id = "@user:matrix.org"
room_id = "#foo:matrix.org"
@responses.activate
def test_get_user_tags(self):
tags_url = "http://example.com" \
"/_matrix/client/r0/... | 0.508056 | 0.324075 |
import scrapy
import json
import re
from locations.items import GeojsonPointItem
class LoblawsSpider(scrapy.Spider):
name = "loblaws"
allowed_domains = ["www.loblaws.ca"]
start_urls = (
'https://www.loblaws.ca/store-locator/locations/all?showNonShoppable=true&_=1513445413276',
)
def sto... | locations/spiders/loblaws.py | import scrapy
import json
import re
from locations.items import GeojsonPointItem
class LoblawsSpider(scrapy.Spider):
name = "loblaws"
allowed_domains = ["www.loblaws.ca"]
start_urls = (
'https://www.loblaws.ca/store-locator/locations/all?showNonShoppable=true&_=1513445413276',
)
def sto... | 0.283583 | 0.261248 |
import re
import pytest
from aws_schema_registry import ValidationError
from aws_schema_registry.jsonschema import JsonSchema
def test_readwrite():
s = JsonSchema("""{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"name": {
... | tests/test_jsonschema.py | import re
import pytest
from aws_schema_registry import ValidationError
from aws_schema_registry.jsonschema import JsonSchema
def test_readwrite():
s = JsonSchema("""{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"name": {
... | 0.42322 | 0.369429 |
from discord import Embed
from discord.ext.commands import Context
from discord.ext import commands
from core.cls import Bot
from difflib import get_close_matches as gcm
class ErrorHandler(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_e... | modules/errors.py | from discord import Embed
from discord.ext.commands import Context
from discord.ext import commands
from core.cls import Bot
from difflib import get_close_matches as gcm
class ErrorHandler(commands.Cog):
def __init__(self, bot: Bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_e... | 0.583441 | 0.23053 |
from __future__ import division
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import os
import model_def
import basic_utils
import utils
def main():
# Get the hparams
hparams = model_def.get_hparams()
# Set up some things according to hparams
utils.setup(hparam... | commons/mnist/inf/train.py | from __future__ import division
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import os
import model_def
import basic_utils
import utils
def main():
# Get the hparams
hparams = model_def.get_hparams()
# Set up some things according to hparams
utils.setup(hparam... | 0.73914 | 0.470554 |
import errno
import sys
sys.path.append("../../common")
from env_indigo import *
indigo = Indigo()
indigo.setOption("molfile-saving-skip-date", "1")
if not os.path.exists(joinPathPy("out", __file__)):
try:
os.makedirs(joinPathPy("out", __file__))
except OSError as e:
if e.errno != errno.EEXIS... | api/tests/integration/tests/basic/query_instrumentation.py | import errno
import sys
sys.path.append("../../common")
from env_indigo import *
indigo = Indigo()
indigo.setOption("molfile-saving-skip-date", "1")
if not os.path.exists(joinPathPy("out", __file__)):
try:
os.makedirs(joinPathPy("out", __file__))
except OSError as e:
if e.errno != errno.EEXIS... | 0.137532 | 0.274097 |
import sequence
import ps
sequence.font = ps.Courier(8)
ps.put_header()
p = sequence.Uml_sequence_page("WRITE_ERROR -- drive error writing data block")
encp = p.add_class_role(sequence.Uml_class_role("Encp"))
lm = p.add_class_role(sequence.Uml_class_role("LibMan"))
mover = p.add_class_role(sequence.Uml_class... | doc/other/read_error_detail.py | import sequence
import ps
sequence.font = ps.Courier(8)
ps.put_header()
p = sequence.Uml_sequence_page("WRITE_ERROR -- drive error writing data block")
encp = p.add_class_role(sequence.Uml_class_role("Encp"))
lm = p.add_class_role(sequence.Uml_class_role("LibMan"))
mover = p.add_class_role(sequence.Uml_class... | 0.181408 | 0.132571 |
from __future__ import division, print_function, absolute_import
# Unit Test
import unittest
import time
from numpy import arange, allclose, ones, NaN, isnan
import numpy as np
# functionality to be tested
from scipy.interpolate.interpolate_wrapper import atleast_1d_and_contiguous, \
linear, logarithmic, bloc... | scipy/interpolate/tests/test_interpolate_wrapper.py | from __future__ import division, print_function, absolute_import
# Unit Test
import unittest
import time
from numpy import arange, allclose, ones, NaN, isnan
import numpy as np
# functionality to be tested
from scipy.interpolate.interpolate_wrapper import atleast_1d_and_contiguous, \
linear, logarithmic, bloc... | 0.355775 | 0.611498 |
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
from landlab.components import FlowDirectorSteepest, NetworkSedimentTransporter
from landlab.data_record import DataRecord
from landlab.grid.network import NetworkModelGrid
def test_no_flow_no_transport(example_nmg, example_pa... | tests/components/network_sediment_transporter/test_transport.py | import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
from landlab.components import FlowDirectorSteepest, NetworkSedimentTransporter
from landlab.data_record import DataRecord
from landlab.grid.network import NetworkModelGrid
def test_no_flow_no_transport(example_nmg, example_pa... | 0.653016 | 0.580828 |
import pickle
import torch
from VerifyOutputSpeed import verify_speed
from trajectories import data_loader
from models import TrajectoryGenerator
from utils import displacement_error, final_displacement_error, relative_to_abs, get_dataset_name
from constants import *
def evaluate_helper(error, traj, seq_start_end):
... | evaluate_model.py | import pickle
import torch
from VerifyOutputSpeed import verify_speed
from trajectories import data_loader
from models import TrajectoryGenerator
from utils import displacement_error, final_displacement_error, relative_to_abs, get_dataset_name
from constants import *
def evaluate_helper(error, traj, seq_start_end):
... | 0.522202 | 0.331228 |
import json
from unittest.mock import patch
from moto import mock_sqs
from phoenix_letter.common.enums import ReasonStopEnum
from phoenix_letter.main import main
from tests.bootstrap import BaseTestCase
@mock_sqs
@patch("phoenix_letter.common.credentials.getpass")
class MoveMessagesTestCase(BaseTestCase):
def s... | tests/test_move_messages.py | import json
from unittest.mock import patch
from moto import mock_sqs
from phoenix_letter.common.enums import ReasonStopEnum
from phoenix_letter.main import main
from tests.bootstrap import BaseTestCase
@mock_sqs
@patch("phoenix_letter.common.credentials.getpass")
class MoveMessagesTestCase(BaseTestCase):
def s... | 0.557364 | 0.294215 |
import argparse
import signal
import subprocess
import os
import getpass
import calendar
import sqlite3 as db
import time
import re
# Our command-line interface
argp = argparse.ArgumentParser(
description="Run some Test262-style tests with some JS implementation: by default, with JSRef.")
argp.add_argument("file... | runtests.py | import argparse
import signal
import subprocess
import os
import getpass
import calendar
import sqlite3 as db
import time
import re
# Our command-line interface
argp = argparse.ArgumentParser(
description="Run some Test262-style tests with some JS implementation: by default, with JSRef.")
argp.add_argument("file... | 0.402275 | 0.143698 |
"""Tests for convert_to_constants.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from tensorflow.python import keras
from tensorflow.python.client import session as session_lib
from tensorflow.python.eager import def_fu... | tensorflow/python/framework/convert_to_constants_test.py | """Tests for convert_to_constants.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from tensorflow.python import keras
from tensorflow.python.client import session as session_lib
from tensorflow.python.eager import def_fu... | 0.883355 | 0.441553 |
import decimal
from test_framework.test_particl import GhostTestFramework
from test_framework.util import (
assert_equal,
assert_greater_than
)
class ControlAnonTest(GhostTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args ... | test/functional/feature_control_anon.py | import decimal
from test_framework.test_particl import GhostTestFramework
from test_framework.util import (
assert_equal,
assert_greater_than
)
class ControlAnonTest(GhostTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 2
self.extra_args ... | 0.32306 | 0.313991 |
import time
import logging
import telnetlib
class RPS(object):
def __init__(self, model, ip, port, outlet, username, password,
logger=None, dbg_lvl=0, desc=""):
"""
Construction of the RPS object
:param model: RPS Model Rariron/ServerTech/Avocent/AvocentRoot
:type ... | spytest/spytest/rps.py | import time
import logging
import telnetlib
class RPS(object):
def __init__(self, model, ip, port, outlet, username, password,
logger=None, dbg_lvl=0, desc=""):
"""
Construction of the RPS object
:param model: RPS Model Rariron/ServerTech/Avocent/AvocentRoot
:type ... | 0.431105 | 0.080502 |