code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from enum import Enum from typing import List from typing import Any from tempfile import NamedTemporaryFile from openpyxl import Workbook from openpyxl.styles import NamedStyle from openpyxl.styles import PatternFill from validator.loader import file_nt from validator.engine.errors import TaskMessage error_style...
validator/writer.py
from enum import Enum from typing import List from typing import Any from tempfile import NamedTemporaryFile from openpyxl import Workbook from openpyxl.styles import NamedStyle from openpyxl.styles import PatternFill from validator.loader import file_nt from validator.engine.errors import TaskMessage error_style...
0.722625
0.137012
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the...
tests/test_inversedynamics.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the...
0.889643
0.620765
from __future__ import unicode_literals import re import json from .common import InfoExtractor from ..compat import ( compat_urllib_request, ) from ..utils import ( ExtractorError, ) class IviIE(InfoExtractor): IE_DESC = 'ivi.ru' IE_NAME = 'ivi' _VALID_URL = r'https?://(?:www\.)?ivi\.ru/(?:watc...
youtube_dl/extractor/ivi.py
from __future__ import unicode_literals import re import json from .common import InfoExtractor from ..compat import ( compat_urllib_request, ) from ..utils import ( ExtractorError, ) class IviIE(InfoExtractor): IE_DESC = 'ivi.ru' IE_NAME = 'ivi' _VALID_URL = r'https?://(?:www\.)?ivi\.ru/(?:watc...
0.481941
0.129293
from core.skills import skillsLoader from core.utils.cleanOrder import * def executeSkill(orderJson): # Traitement d'un ordre (complexe) order = orderJson["msg"] if(order == "") : return "Je ne vous ai pas entendu" orders = order.split(",") # On regarde si on peut séparer l'ordre en 2 (si il ...
core/core.py
from core.skills import skillsLoader from core.utils.cleanOrder import * def executeSkill(orderJson): # Traitement d'un ordre (complexe) order = orderJson["msg"] if(order == "") : return "Je ne vous ai pas entendu" orders = order.split(",") # On regarde si on peut séparer l'ordre en 2 (si il ...
0.39257
0.32029
"""Algorithms for topological sorting""" import queue from typing import List from .searching import dfs_recursive from .searching_strategy import DFSStrategy from ..directed_graph import DirectedGraph from ..graph import Vertex class DirectedCyclicGraphError(ValueError): pass def sort_topological_using_inputs...
algolib/graphs/algorithms/topological_sorting.py
"""Algorithms for topological sorting""" import queue from typing import List from .searching import dfs_recursive from .searching_strategy import DFSStrategy from ..directed_graph import DirectedGraph from ..graph import Vertex class DirectedCyclicGraphError(ValueError): pass def sort_topological_using_inputs...
0.927157
0.674767
from urllib.parse import urlparse from mitmproxy import http from lyrebird import log import os import json import logging import re _logger = log.get_logger() _logger.setLevel(logging.INFO) PROXY_PORT = int(os.environ.get('PROXY_PORT')) PROXY_FILTERS = json.loads(os.environ.get('PROXY_FILTERS')) def to_mock_server...
lyrebird/proxy/mitm_script.py
from urllib.parse import urlparse from mitmproxy import http from lyrebird import log import os import json import logging import re _logger = log.get_logger() _logger.setLevel(logging.INFO) PROXY_PORT = int(os.environ.get('PROXY_PORT')) PROXY_FILTERS = json.loads(os.environ.get('PROXY_FILTERS')) def to_mock_server...
0.36977
0.075176
def for_ops(state, operations, fn) -> None: for operation in operations: fn(state, operation) def get_process_calls(spec): return { # PHASE0 'process_block_header': lambda state, block: spec.process_block_header(state, block), 'process_randao': lambda st...
tests/core/pyspec/eth2spec/test/helpers/block_processing.py
def for_ops(state, operations, fn) -> None: for operation in operations: fn(state, operation) def get_process_calls(spec): return { # PHASE0 'process_block_header': lambda state, block: spec.process_block_header(state, block), 'process_randao': lambda st...
0.447702
0.353735
import os import random import pandas as pd import numpy as np import torch import torch.utils.data as data from PIL import Image import scipy.misc as ssc from psmnet.dataloader import preprocess IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', ] calib = [...
psmnet/dataloader/VKittiLoader.py
import os import random import pandas as pd import numpy as np import torch import torch.utils.data as data from PIL import Image import scipy.misc as ssc from psmnet.dataloader import preprocess IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', ] calib = [...
0.639173
0.331539
import logging from openstack import connection, config from . import AbstractDriver from ..node import Node, NodeState def create_connection_from_config(name=None): """ Creates a new open stack connection """ occ = config.OpenStackConfig() cloud = occ.get_one_cloud(name) return connection.from_conf...
powerfulseal/clouddrivers/open_stack_driver.py
import logging from openstack import connection, config from . import AbstractDriver from ..node import Node, NodeState def create_connection_from_config(name=None): """ Creates a new open stack connection """ occ = config.OpenStackConfig() cloud = occ.get_one_cloud(name) return connection.from_conf...
0.620162
0.112356
import os import numpy as np from tvtk.api import tvtk, write_data import sharpy.utils.algebra as algebra import sharpy.utils.cout_utils as cout from sharpy.utils.settings import str2bool from sharpy.utils.solver_interface import solver, BaseSolver import sharpy.utils.settings as settings from sharpy.utils.datastruct...
sharpy/postproc/stallcheck.py
import os import numpy as np from tvtk.api import tvtk, write_data import sharpy.utils.algebra as algebra import sharpy.utils.cout_utils as cout from sharpy.utils.settings import str2bool from sharpy.utils.solver_interface import solver, BaseSolver import sharpy.utils.settings as settings from sharpy.utils.datastruct...
0.556882
0.256861
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression, LassoCV, RidgeCV from sklearn.model_selection import cross_val_score, train_test_split from sklearn.preprocessing import StandardScaler, PolynomialFeatures from sklearn.metric...
eda_and_beyond/eda_tools.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.linear_model import LinearRegression, LassoCV, RidgeCV from sklearn.model_selection import cross_val_score, train_test_split from sklearn.preprocessing import StandardScaler, PolynomialFeatures from sklearn.metric...
0.594669
0.611875
import re import xraylib from skbeam.core.constants import XrfElement as Element from skbeam.core.fitting.xrf_model import K_LINE, L_LINE, M_LINE def get_element_atomic_number(element_str): r""" A wrapper to ``SymbolToAtomicNumber`` function from ``xraylib``. Returns atomic number for the sybmolic element...
pyxrf/core/xrf_utils.py
import re import xraylib from skbeam.core.constants import XrfElement as Element from skbeam.core.fitting.xrf_model import K_LINE, L_LINE, M_LINE def get_element_atomic_number(element_str): r""" A wrapper to ``SymbolToAtomicNumber`` function from ``xraylib``. Returns atomic number for the sybmolic element...
0.891138
0.637031
import json import os import random import socket import subprocess import sys from time import sleep from urllib.parse import urlparse import pytest import jsonschema_rs TEST_SUITE_PATH = "../../jsonschema/tests/suite" EXPONENTIAL_BASE = 2 JITTER = (0.0, 0.5) INITIAL_RETRY_DELAY = 0.05 MAX_WAITING_RETRIES = 10 de...
bindings/python/tests-py/test_suite.py
import json import os import random import socket import subprocess import sys from time import sleep from urllib.parse import urlparse import pytest import jsonschema_rs TEST_SUITE_PATH = "../../jsonschema/tests/suite" EXPONENTIAL_BASE = 2 JITTER = (0.0, 0.5) INITIAL_RETRY_DELAY = 0.05 MAX_WAITING_RETRIES = 10 de...
0.334916
0.16455
from aiohttp import web import asyncio import asyncio.tasks import datetime import functools import logging import itertools import typing import json from ..models import Update from ..utils import helper DEFAULT_WEB_PATH = '/webhook' DEFAULT_ROUTE_NAME = 'webhook_handler' BOT_DISPATCHER_KEY = 'BOT_DISPATCHER' RESP...
pyAitu/dispatcher/webhook.py
from aiohttp import web import asyncio import asyncio.tasks import datetime import functools import logging import itertools import typing import json from ..models import Update from ..utils import helper DEFAULT_WEB_PATH = '/webhook' DEFAULT_ROUTE_NAME = 'webhook_handler' BOT_DISPATCHER_KEY = 'BOT_DISPATCHER' RESP...
0.534612
0.093885
import asyncio from typing import List from readchar import * from api import pokeapi from config.config import TEXT from game.pokemon import Pokemon class Player: """Holds current information about the player""" team: List[Pokemon] = [] def __init__(self): """Fills the player's team with a rand...
game/player.py
import asyncio from typing import List from readchar import * from api import pokeapi from config.config import TEXT from game.pokemon import Pokemon class Player: """Holds current information about the player""" team: List[Pokemon] = [] def __init__(self): """Fills the player's team with a rand...
0.605216
0.318591
from tdw.controller import Controller from tdw.tdw_utils import TDWUtils from time import sleep from platform import system """ Create a fluid "container" with the NVIDIA Flex physics engine. Run several trials, dropping ball objects of increasing mass into the fluid. """ class FlexFluid(Controller): ...
Python/example_controllers/flex_fluid_object.py
from tdw.controller import Controller from tdw.tdw_utils import TDWUtils from time import sleep from platform import system """ Create a fluid "container" with the NVIDIA Flex physics engine. Run several trials, dropping ball objects of increasing mass into the fluid. """ class FlexFluid(Controller): ...
0.623033
0.353596
from unittest import TestCase from unittest.mock import MagicMock import numpy as np from pynwb import NWBFile from testfixtures import should_raise from rec_to_nwb.processing.exceptions.missing_data_exception import MissingDataException from rec_to_nwb.processing.nwb.components.mda.time.valid.fl_mda_valid_time_manag...
rec_to_nwb/test/processing/mda/time/valid/test_flMdaValidTimeManager.py
from unittest import TestCase from unittest.mock import MagicMock import numpy as np from pynwb import NWBFile from testfixtures import should_raise from rec_to_nwb.processing.exceptions.missing_data_exception import MissingDataException from rec_to_nwb.processing.nwb.components.mda.time.valid.fl_mda_valid_time_manag...
0.7237
0.496704
from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import os from gym.core import Env from gym.spaces import Box from gym.spaces import Discrete from gym.utils import play import numpy as np from PIL import Image from PIL import ImageDraw from PI...
v0.5.0/google/research_v3.32/gnmt-tpuv3-32/code/gnmt/model/t2t/tensor2tensor/rl/model_rl_experiment_player.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import copy import os from gym.core import Env from gym.spaces import Box from gym.spaces import Discrete from gym.utils import play import numpy as np from PIL import Image from PIL import ImageDraw from PI...
0.617513
0.248386
from rest_framework.permissions import BasePermission from django.conf import settings from seaserv import check_permission, is_repo_owner, ccnet_api from seahub.utils import is_pro_version SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class IsRepoWritable(BasePermission): """ Allows access only for user who ha...
seahub/api2/permissions.py
from rest_framework.permissions import BasePermission from django.conf import settings from seaserv import check_permission, is_repo_owner, ccnet_api from seahub.utils import is_pro_version SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] class IsRepoWritable(BasePermission): """ Allows access only for user who ha...
0.462959
0.072308
import hashlib import logging from stevedore import driver from pecan import conf from cauth.service import base from cauth.model import db as auth_map from cauth.utils import transaction from cauth.utils import exceptions def differentiate(login, domain, uid): suffix = hashlib.sha1((domain + '/' + str(uid)).e...
cauth/utils/userdetails.py
import hashlib import logging from stevedore import driver from pecan import conf from cauth.service import base from cauth.model import db as auth_map from cauth.utils import transaction from cauth.utils import exceptions def differentiate(login, domain, uid): suffix = hashlib.sha1((domain + '/' + str(uid)).e...
0.298798
0.049451
import jc.utils import jc.parsers.universal class info(): version = '1.0' description = 'crontab file parser with user support' author = '<NAME>' author_email = '<EMAIL>' # details = 'enter any other details here' # compatible options: linux, darwin, cygwin, win32, aix, freebsd compatible...
jc/parsers/crontab_u.py
import jc.utils import jc.parsers.universal class info(): version = '1.0' description = 'crontab file parser with user support' author = '<NAME>' author_email = '<EMAIL>' # details = 'enter any other details here' # compatible options: linux, darwin, cygwin, win32, aix, freebsd compatible...
0.49585
0.304145
import logging import os import shelve import struct from ...utils.codepage import load_obj, MemoryPage from ...irutils import verify_module from .. import wasm_to_ir from ..components import Table from ..util import PAGE_SIZE from ._base_instance import ModuleInstance, WasmMemory, WasmGlobal logger = logging.getLog...
ppci/wasm/execution/_native_instance.py
import logging import os import shelve import struct from ...utils.codepage import load_obj, MemoryPage from ...irutils import verify_module from .. import wasm_to_ir from ..components import Table from ..util import PAGE_SIZE from ._base_instance import ModuleInstance, WasmMemory, WasmGlobal logger = logging.getLog...
0.2414
0.160102
"""The Cartpole reinforcement learning environment.""" # Import all packages import collections from bsuite.experiments.cartpole import sweep import dm_env from dm_env import specs import numpy as np CartpoleState = collections.namedtuple( 'CartpoleState', ['x', 'x_dot', 'theta', 'theta_dot', 'time_elapsed']) ...
bsuite/experiments/cartpole/cartpole.py
"""The Cartpole reinforcement learning environment.""" # Import all packages import collections from bsuite.experiments.cartpole import sweep import dm_env from dm_env import specs import numpy as np CartpoleState = collections.namedtuple( 'CartpoleState', ['x', 'x_dot', 'theta', 'theta_dot', 'time_elapsed']) ...
0.924509
0.607809
from copy import deepcopy from inspect import isclass, signature import numpy as np import pandas as pd from fbprophet import Prophet from sklearn.base import BaseEstimator class SkProphet(Prophet): DS = 'ds' def __init__( self, sk_date_column=DS, sk_yhat_only=True, sk_extr...
muttlib/forecast.py
from copy import deepcopy from inspect import isclass, signature import numpy as np import pandas as pd from fbprophet import Prophet from sklearn.base import BaseEstimator class SkProphet(Prophet): DS = 'ds' def __init__( self, sk_date_column=DS, sk_yhat_only=True, sk_extr...
0.847274
0.396944
from datetime import timedelta from webargs import fields from . import BaseView, use_args, use_kwargs from ..models.event import Event as EventModel from ..schemas.event import Event as EventSchema, EventMatch from .utils import get_or_404 eventlist_args = { "fromdate": fields.Date(required=False), "todate":...
friday/views/event.py
from datetime import timedelta from webargs import fields from . import BaseView, use_args, use_kwargs from ..models.event import Event as EventModel from ..schemas.event import Event as EventSchema, EventMatch from .utils import get_or_404 eventlist_args = { "fromdate": fields.Date(required=False), "todate":...
0.610337
0.070688
import logging import random import pytest from ocs_ci.framework.pytest_customization.marks import aws_platform_required from ocs_ci.framework.testlib import ManageTest, tier4, bugzilla from ocs_ci.ocs.exceptions import CommandFailed from tests import sanity_helpers logger = logging.getLogger(__name__) @tier4 @pyt...
tests/manage/cluster/nodes/test_az_failure.py
import logging import random import pytest from ocs_ci.framework.pytest_customization.marks import aws_platform_required from ocs_ci.framework.testlib import ManageTest, tier4, bugzilla from ocs_ci.ocs.exceptions import CommandFailed from tests import sanity_helpers logger = logging.getLogger(__name__) @tier4 @pyt...
0.619932
0.290591
from __future__ import absolute_import from __future__ import print_function import os import numpy as np import matplotlib.pyplot as plt from clawpack.visclaw import geoplot, gaugetools import clawpack.clawutil.data as clawutil import clawpack.amrclaw.data as amrclaw import clawpack.geoclaw.data import clawpack.g...
examples/multi-layer/plane_wave/setplot.py
from __future__ import absolute_import from __future__ import print_function import os import numpy as np import matplotlib.pyplot as plt from clawpack.visclaw import geoplot, gaugetools import clawpack.clawutil.data as clawutil import clawpack.amrclaw.data as amrclaw import clawpack.geoclaw.data import clawpack.g...
0.765506
0.521654
from .taskonomy_network import TaskonomyEncoder, TaskonomyDecoder, TaskonomyNetwork, TASKONOMY_PRETRAINED_URLS, TASKS_TO_CHANNELS import multiprocessing.dummy as mp import torch default_device = 'cuda' if torch.cuda.is_available() else 'cpu' def representation_transform(img, feature_task='normal', device=default_devi...
visualpriors/transforms.py
from .taskonomy_network import TaskonomyEncoder, TaskonomyDecoder, TaskonomyNetwork, TASKONOMY_PRETRAINED_URLS, TASKS_TO_CHANNELS import multiprocessing.dummy as mp import torch default_device = 'cuda' if torch.cuda.is_available() else 'cpu' def representation_transform(img, feature_task='normal', device=default_devi...
0.810891
0.500732
"""Learning 2 Learn training.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from six.moves import xrange import tensorflow as tf from tqdm import tqdm from tensorflow.contrib.learn.python.learn import monitored_session as ms import meta imp...
train.py
"""Learning 2 Learn training.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from six.moves import xrange import tensorflow as tf from tqdm import tqdm from tensorflow.contrib.learn.python.learn import monitored_session as ms import meta imp...
0.817246
0.230514
import pandas as pd import os class DeploymentInfo(): """ A class to handle acoustic deployment metadadata . Object carrying deployment metadata that can be used for example to populate metadata fields in Annotation or Measurement objects. Attributes ---------- data : pandas DataFrame ...
ecosound/core/metadata.py
import pandas as pd import os class DeploymentInfo(): """ A class to handle acoustic deployment metadadata . Object carrying deployment metadata that can be used for example to populate metadata fields in Annotation or Measurement objects. Attributes ---------- data : pandas DataFrame ...
0.775095
0.477798
from sympy.core.symbol import Symbol from sympy.tensor.indexed import Idx, IndexedBase, Indexed from sympy.concrete import Product from sympy.core.compatibility import is_sequence from sympy.core.singleton import S from sympy.core.add import Add from sympy.core.function import Derivative from sympy.functions.special.te...
derivations/scripts/sympy_addons.py
from sympy.core.symbol import Symbol from sympy.tensor.indexed import Idx, IndexedBase, Indexed from sympy.concrete import Product from sympy.core.compatibility import is_sequence from sympy.core.singleton import S from sympy.core.add import Add from sympy.core.function import Derivative from sympy.functions.special.te...
0.752468
0.216881
import pandas as pd import h5py import numpy as np import os import matplotlib.pyplot as plt #load cdsdb new_file = h5py.File("../data/csdb_bt/csdb_bt.h5", "r") bt_csdb = new_file["bt"][:] new_file.close() #compute mean and var csdb dataset df_bt_csdb = pd.DataFrame(bt_csdb) mean_bt_csdb = df_bt_csdb.mean() ...
code/mean_var_bt.py
import pandas as pd import h5py import numpy as np import os import matplotlib.pyplot as plt #load cdsdb new_file = h5py.File("../data/csdb_bt/csdb_bt.h5", "r") bt_csdb = new_file["bt"][:] new_file.close() #compute mean and var csdb dataset df_bt_csdb = pd.DataFrame(bt_csdb) mean_bt_csdb = df_bt_csdb.mean() ...
0.178204
0.103749
from pyrosm.data_manager import get_osm_data from pyrosm.frames import prepare_geodataframe from pyrosm.utils import validate_custom_filter import geopandas as gpd import warnings def get_boundary_data(node_coordinates, way_records, relations, tags_as_columns, custom_filter, ...
pyrosm/boundary.py
from pyrosm.data_manager import get_osm_data from pyrosm.frames import prepare_geodataframe from pyrosm.utils import validate_custom_filter import geopandas as gpd import warnings def get_boundary_data(node_coordinates, way_records, relations, tags_as_columns, custom_filter, ...
0.734405
0.23688
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Address.extended_address' db.add_column(u'address_address', 'extended_address', self.gf('djang...
address/migrations/0004_auto__add_field_address_extended_address__chg_field_address_street_add.py
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Address.extended_address' db.add_column(u'address_address', 'extended_address', self.gf('djang...
0.443118
0.147986
# Modified by <NAME>' to test FTP class and IPv6 environment import ftplib import threading import asyncore import asynchat import socket import StringIO from unittest import TestCase from test import test_support from test.test_support import HOST # the dummy data returned by server over the data channel when # R...
Lib/test/test_ftplib.py
# Modified by <NAME>' to test FTP class and IPv6 environment import ftplib import threading import asyncore import asynchat import socket import StringIO from unittest import TestCase from test import test_support from test.test_support import HOST # the dummy data returned by server over the data channel when # R...
0.480479
0.143518
from PyQt5.QtWidgets import QLineEdit, QDialog, QFileDialog, QWidget, QTreeWidget, QToolButton, QRadioButton, QMessageBox, QTreeWidgetItem, QTabWidget, QLabel, QCheckBox, QPushButton, QSpinBox from os.path import basename from PyQt5.QtGui import QIcon from PyQt5.QtGui import QColor, QBrush from PyQt5.QtCore import Qt f...
data/user_input/plots/structural/plotStructuralFrequencyResponseInput.py
from PyQt5.QtWidgets import QLineEdit, QDialog, QFileDialog, QWidget, QTreeWidget, QToolButton, QRadioButton, QMessageBox, QTreeWidgetItem, QTabWidget, QLabel, QCheckBox, QPushButton, QSpinBox from os.path import basename from PyQt5.QtGui import QIcon from PyQt5.QtGui import QColor, QBrush from PyQt5.QtCore import Qt f...
0.560253
0.234024
__author__ = '<NAME>' __date__ = 'August 2012' __copyright__ = '(C) 2012, <NAME>' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '176c06ceefb5f555205e72b20c962740cc0ec183' import os from pprint import pformat import time from qgis.PyQt.QtCore import QCoreApplication, Qt from qgis....
python/plugins/processing/gui/AlgorithmDialog.py
__author__ = '<NAME>' __date__ = 'August 2012' __copyright__ = '(C) 2012, <NAME>' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '176c06ceefb5f555205e72b20c962740cc0ec183' import os from pprint import pformat import time from qgis.PyQt.QtCore import QCoreApplication, Qt from qgis....
0.350755
0.09451
import json import time from typing import Optional, Sequence import yaml from kubernetes import client from kubernetes.client.rest import ApiException from tempo.k8s.constants import TempoK8sLabel, TempoK8sModelSpecAnnotation from tempo.k8s.utils import create_k8s_client from tempo.seldon.endpoint import Endpoint fr...
tempo/seldon/k8s.py
import json import time from typing import Optional, Sequence import yaml from kubernetes import client from kubernetes.client.rest import ApiException from tempo.k8s.constants import TempoK8sLabel, TempoK8sModelSpecAnnotation from tempo.k8s.utils import create_k8s_client from tempo.seldon.endpoint import Endpoint fr...
0.68595
0.14445
import torch import torch.nn as nn import torch.nn.functional as F from layers.Transformer_EncDec import Decoder, DecoderLayer, Encoder, EncoderLayer, ConvLayer from layers.SelfAttention_Family import FullAttention, AttentionLayer from layers.Embed import DataEmbedding import numpy as np class Transformer(nn.Module):...
models/seq2seq/Transformer.py
import torch import torch.nn as nn import torch.nn.functional as F from layers.Transformer_EncDec import Decoder, DecoderLayer, Encoder, EncoderLayer, ConvLayer from layers.SelfAttention_Family import FullAttention, AttentionLayer from layers.Embed import DataEmbedding import numpy as np class Transformer(nn.Module):...
0.928854
0.310139
import os import pytest import subprocess as s from pyspaces import Container, Chroot, Inject, setns def execute(argv): """Execute programm with arguments. Args: *args (list): arguments """ os.execvp(argv[0], argv) def test_basic_container(capfd): """Check basic namespace. ``` ...
tests/test_create_container.py
import os import pytest import subprocess as s from pyspaces import Container, Chroot, Inject, setns def execute(argv): """Execute programm with arguments. Args: *args (list): arguments """ os.execvp(argv[0], argv) def test_basic_container(capfd): """Check basic namespace. ``` ...
0.417509
0.474449
import argparse import logging import multiprocessing import time from functools import partial, update_wrapper from defaults import EXTRACTION_MAX_READ_PAIRS, EXTRACTION_MAX_NM, EXTRACTION_MAX_INTERVAL_TRUNCATION, EXTRACTION_TRUNCATION_PAD import pysam compl_table = [chr(i) for i in xrange(256)] compl_table[ord('A')...
metasv/extract_pairs.py
import argparse import logging import multiprocessing import time from functools import partial, update_wrapper from defaults import EXTRACTION_MAX_READ_PAIRS, EXTRACTION_MAX_NM, EXTRACTION_MAX_INTERVAL_TRUNCATION, EXTRACTION_TRUNCATION_PAD import pysam compl_table = [chr(i) for i in xrange(256)] compl_table[ord('A')...
0.218503
0.154185
sMAP feed for BPA Total Wind, Hydro, and Thermal Generation. @author <NAME> ''' import urllib2 import logging from smap.driver import SmapDriver from smap.util import periodicSequentialCall from smap.contrib import dtutil class BPADriver(SmapDriver): ''' Scrape feed from BPA site and parse as a sMAP feed. BPA...
python/smap/drivers/washingtonbpa.py
sMAP feed for BPA Total Wind, Hydro, and Thermal Generation. @author <NAME> ''' import urllib2 import logging from smap.driver import SmapDriver from smap.util import periodicSequentialCall from smap.contrib import dtutil class BPADriver(SmapDriver): ''' Scrape feed from BPA site and parse as a sMAP feed. BPA...
0.437103
0.362518
from pathlib import Path import pytest from .. import base MB = 1 @base.bootstrapped @pytest.mark.asyncio async def test_action(event_loop): async with base.CleanModel() as model: ubuntu_app = await model.deploy( 'percona-cluster', application_name='mysql', series='x...
tests/integration/test_application.py
from pathlib import Path import pytest from .. import base MB = 1 @base.bootstrapped @pytest.mark.asyncio async def test_action(event_loop): async with base.CleanModel() as model: ubuntu_app = await model.deploy( 'percona-cluster', application_name='mysql', series='x...
0.406862
0.264216
from ..utils.game_history import game_event_history import torch import numpy as np from ..model.components import transform_input from ..tree.temperture import * def play_game(model, env, self_play=False, custom_end_function=None, custom_reward_function=None, custom_state_function=None, extra_loss_tracker=None, timeo...
musweeper/musweeper/muzero/model/selfplay.py
from ..utils.game_history import game_event_history import torch import numpy as np from ..model.components import transform_input from ..tree.temperture import * def play_game(model, env, self_play=False, custom_end_function=None, custom_reward_function=None, custom_state_function=None, extra_loss_tracker=None, timeo...
0.794943
0.353484
import PySimpleGUI as sg import plotly.graph_objects as go from NetLogoDOE.src.gui.custom_components import title, question_mark_button, explanation from NetLogoDOE.src.gui.custom_windows import show_help_window from NetLogoDOE.src.gui.help_dictionary import help_text from NetLogoDOE.src.util.data_processing.merge_sta...
NetLogoDOE/src/gui/plots/standard/BoxplotScreen.py
import PySimpleGUI as sg import plotly.graph_objects as go from NetLogoDOE.src.gui.custom_components import title, question_mark_button, explanation from NetLogoDOE.src.gui.custom_windows import show_help_window from NetLogoDOE.src.gui.help_dictionary import help_text from NetLogoDOE.src.util.data_processing.merge_sta...
0.508544
0.181771
import socket import threading import queue import time class loggerThread(threading.Thread): def __init__(self,loggerQueue,conn,addr): threading.Thread.__init__(self) self.loggerQueue = loggerQueue self.conn = conn self.addr = addr def run(self): logger(self.logg...
proje/proje.py
import socket import threading import queue import time class loggerThread(threading.Thread): def __init__(self,loggerQueue,conn,addr): threading.Thread.__init__(self) self.loggerQueue = loggerQueue self.conn = conn self.addr = addr def run(self): logger(self.logg...
0.037821
0.067547
from keras.layers import Flatten, Conv2D, Dense, Activation from keras.optimizers import Adam from keras import Sequential from rl.agents import DQNAgent, CEMAgent from rl.memory import SequentialMemory, EpisodeParameterMemory from rl.policy import EpsGreedyQPolicy from hexagon_agent import * from random import shuff...
dqn_centaur_ai_gym.py
from keras.layers import Flatten, Conv2D, Dense, Activation from keras.optimizers import Adam from keras import Sequential from rl.agents import DQNAgent, CEMAgent from rl.memory import SequentialMemory, EpisodeParameterMemory from rl.policy import EpsGreedyQPolicy from hexagon_agent import * from random import shuff...
0.756447
0.355719
import csv import json import logging import os import urllib3 import time from datetime import datetime, timedelta from typing import List # Globals TRANSFERWISE_BASE_URI = None FIREFLY_BASE_URI = None category_map = {} currency_accounts = {} logging.getLogger().setLevel(logging.INFO) http = urllib3.PoolManager() ...
transferwise/src/main.py
import csv import json import logging import os import urllib3 import time from datetime import datetime, timedelta from typing import List # Globals TRANSFERWISE_BASE_URI = None FIREFLY_BASE_URI = None category_map = {} currency_accounts = {} logging.getLogger().setLevel(logging.INFO) http = urllib3.PoolManager() ...
0.595375
0.145358
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn import numpy as np import json from json import encoder import random import string import time import os import sys from . import misc as utils from .eval_utils import getCO...
captioning/utils/eval_multi.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn import numpy as np import json from json import encoder import random import string import time import os import sys from . import misc as utils from .eval_utils import getCO...
0.424173
0.117673
from keras.models import Sequential from keras.layers.convolutional import Conv2D, Convolution2DTranspose, UpSampling2D from keras.layers.pooling import MaxPool2D from keras import metrics from keras.layers import Input from keras.layers.merge import concatenate from keras.models import Model from keras.applications im...
model.py
from keras.models import Sequential from keras.layers.convolutional import Conv2D, Convolution2DTranspose, UpSampling2D from keras.layers.pooling import MaxPool2D from keras import metrics from keras.layers import Input from keras.layers.merge import concatenate from keras.models import Model from keras.applications im...
0.895836
0.673156
import numpy from csb.statistics.pdf.parameterized import Parameter from binf import ArrayParameter from binf.pdf.priors import AbstractPrior from .sphere_prior_c import sphere_prior_gradient class SpherePrior(AbstractPrior): def __init__(self, name, sphere_radius, sphere_k, n_structures, bead...
ensemble_hic/sphere_prior.py
import numpy from csb.statistics.pdf.parameterized import Parameter from binf import ArrayParameter from binf.pdf.priors import AbstractPrior from .sphere_prior_c import sphere_prior_gradient class SpherePrior(AbstractPrior): def __init__(self, name, sphere_radius, sphere_k, n_structures, bead...
0.937996
0.476519
import logging from nni.assessor import Assessor, AssessResult logger = logging.getLogger('medianstop_Assessor') class MedianstopAssessor(Assessor): """MedianstopAssessor is The median stopping rule stops a pending trial X at step S if the trial’s best objective value by step S is strictly worse than the me...
src/sdk/pynni/nni/medianstop_assessor/medianstop_assessor.py
import logging from nni.assessor import Assessor, AssessResult logger = logging.getLogger('medianstop_Assessor') class MedianstopAssessor(Assessor): """MedianstopAssessor is The median stopping rule stops a pending trial X at step S if the trial’s best objective value by step S is strictly worse than the me...
0.724675
0.328664
import queue import copy, json from .newupgradebasetest import NewUpgradeBaseTest from remote.remote_util import RemoteMachineShellConnection, RemoteUtilHelper from couchbase_helper.documentgenerator import BlobGenerator from membase.api.rest_client import RestConnection, RestHelper from membase.api.exception import Re...
pytests/upgrade/xdcr_upgrade_collections.py
import queue import copy, json from .newupgradebasetest import NewUpgradeBaseTest from remote.remote_util import RemoteMachineShellConnection, RemoteUtilHelper from couchbase_helper.documentgenerator import BlobGenerator from membase.api.rest_client import RestConnection, RestHelper from membase.api.exception import Re...
0.433022
0.128717
import argparse import asyncio from eth_keys import keys import signal from quarkchain.p2p import ecies from quarkchain.p2p import kademlia from quarkchain.p2p.cancel_token.token import CancelToken from quarkchain.p2p.p2p_server import BaseServer from quarkchain.p2p.tools.paragon import ParagonContext, ParagonPeer, Pa...
quarkchain/p2p/poc/paragon_node.py
import argparse import asyncio from eth_keys import keys import signal from quarkchain.p2p import ecies from quarkchain.p2p import kademlia from quarkchain.p2p.cancel_token.token import CancelToken from quarkchain.p2p.p2p_server import BaseServer from quarkchain.p2p.tools.paragon import ParagonContext, ParagonPeer, Pa...
0.427277
0.114567
from SBaaS_base.postgresql_orm_base import * class data_stage01_resequencing_endpoints(Base): #TODO: rename to _group __tablename__ = 'data_stage01_resequencing_endpoints' id = Column(Integer, Sequence('data_stage01_resequencing_endpoints_id_seq'), primary_key=True) experiment_id = Column(String(50)) ...
SBaaS_resequencing/stage01_resequencing_endpoints_postgresql_models.py
from SBaaS_base.postgresql_orm_base import * class data_stage01_resequencing_endpoints(Base): #TODO: rename to _group __tablename__ = 'data_stage01_resequencing_endpoints' id = Column(Integer, Sequence('data_stage01_resequencing_endpoints_id_seq'), primary_key=True) experiment_id = Column(String(50)) ...
0.178956
0.129733
from discord import * from discord.ext.commands import * class HelpButtons(ui.View): def __init__(self): super().__init__(timeout=None) @ui.button(label="Home", emoji="<:home_button:918467896592719902>", style=ButtonStyle.red) async def home(self, button: ui.Button, interaction: Interaction): ...
cogs/help-command.py
from discord import * from discord.ext.commands import * class HelpButtons(ui.View): def __init__(self): super().__init__(timeout=None) @ui.button(label="Home", emoji="<:home_button:918467896592719902>", style=ButtonStyle.red) async def home(self, button: ui.Button, interaction: Interaction): ...
0.648132
0.211946
from tonclient.decorators import result_as from tonclient.module import TonModule from tonclient.types import ParamsOfRunExecutor, ResultOfRunExecutor, \ ParamsOfRunTvm, ResultOfRunTvm, ParamsOfRunGet, ResultOfRunGet class TonTvm(TonModule): """ Free TON tvm SDK API implementation """ @result_as(classnam...
tonclient/tvm.py
from tonclient.decorators import result_as from tonclient.module import TonModule from tonclient.types import ParamsOfRunExecutor, ResultOfRunExecutor, \ ParamsOfRunTvm, ResultOfRunTvm, ParamsOfRunGet, ResultOfRunGet class TonTvm(TonModule): """ Free TON tvm SDK API implementation """ @result_as(classnam...
0.865778
0.532304
from openstack import connection # create connection username = "xxxxxx" password = "<PASSWORD>" userDomainId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" # user account ID auth_url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" # endpoint url if __name__ == '__main__': conn = connection.Connection(auth_url=auth_url, ...
examples/bss/v1/period_order.py
from openstack import connection # create connection username = "xxxxxx" password = "<PASSWORD>" userDomainId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" # user account ID auth_url = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" # endpoint url if __name__ == '__main__': conn = connection.Connection(auth_url=auth_url, ...
0.460289
0.228404
import numpy as np import scipy.stats from sklearn.cluster import KMeans, MiniBatchKMeans from sklearn.preprocessing import StandardScaler from skimage.feature import local_binary_pattern from skimage.color import rgb2gray def calculate_change_values(images, masks, n_clusters, num_samples_for_kmeans=10000, use_mini...
utils/tcm_algorithms.py
import numpy as np import scipy.stats from sklearn.cluster import KMeans, MiniBatchKMeans from sklearn.preprocessing import StandardScaler from skimage.feature import local_binary_pattern from skimage.color import rgb2gray def calculate_change_values(images, masks, n_clusters, num_samples_for_kmeans=10000, use_mini...
0.858303
0.782372
import torch import torch.nn as nn import torch.nn.functional as F class RnnCommon(nn.Module): def __init__(self, input_size, hidden_size, layer_num, batch_first, drop_out = 0.0, biderction=True, ...
baseline/lstm/model/RNN_Common.py
import torch import torch.nn as nn import torch.nn.functional as F class RnnCommon(nn.Module): def __init__(self, input_size, hidden_size, layer_num, batch_first, drop_out = 0.0, biderction=True, ...
0.783285
0.298447
import atexit import datetime import functools import hashlib import logging import os import socket import threading import time import traceback from copy import deepcopy import elasticsearch import elasticsearch.helpers class Constants: HOST_KEY = 'host' PROCESS_KEY = 'process' THREAD_NAME_KEY = 'thre...
elasticsearch_util/helper.py
import atexit import datetime import functools import hashlib import logging import os import socket import threading import time import traceback from copy import deepcopy import elasticsearch import elasticsearch.helpers class Constants: HOST_KEY = 'host' PROCESS_KEY = 'process' THREAD_NAME_KEY = 'thre...
0.517083
0.21032
import mathutils import numpy as np import sys import os import json if len(sys.argv) < 5: print(f"""Not enough arguemnts!\n Use : {sys.argv[0]} [/path/manifest.json] => [BL=1-2,2-3] => [PBL=1-2,2-3] => [NM=1,2,3] => [CIs=A|1,2,3] => [CSFs=A|1,2,3] => [CSFv=label:1,1,0,0_label:0,0,1,1]...
analysis/plotter.py
import mathutils import numpy as np import sys import os import json if len(sys.argv) < 5: print(f"""Not enough arguemnts!\n Use : {sys.argv[0]} [/path/manifest.json] => [BL=1-2,2-3] => [PBL=1-2,2-3] => [NM=1,2,3] => [CIs=A|1,2,3] => [CSFs=A|1,2,3] => [CSFv=label:1,1,0,0_label:0,0,1,1]...
0.278159
0.291006
import random class UserAgent: pc_agents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50', 'Moz...
python/img/reptiles_imgs/util/user_agents.py
import random class UserAgent: pc_agents = [ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50', 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50', 'Moz...
0.393502
0.047758
import sys import pyCardDeck from pyCardDeck.cards import PokerCard class person: def __init__(self, name: str): self.h = [] self.n = name def __str__(self): return self.n class BlackTheJack: def __init__(self, persons: List[Person]): self.d = pyCardDeck.Deck() s...
task2.py
import sys import pyCardDeck from pyCardDeck.cards import PokerCard class person: def __init__(self, name: str): self.h = [] self.n = name def __str__(self): return self.n class BlackTheJack: def __init__(self, persons: List[Person]): self.d = pyCardDeck.Deck() s...
0.251096
0.219861
import pytest import re import secrets from botocore.exceptions import ClientError from aws_error_utils import ( get_aws_error_info, aws_error_matches, catch_aws_error, ALL_CODES, ALL_OPERATIONS, errors, make_aws_error, ) rand_str = lambda: secrets.token_hex(4) def _make_test_error( ...
test_aws_error_utils.py
import pytest import re import secrets from botocore.exceptions import ClientError from aws_error_utils import ( get_aws_error_info, aws_error_matches, catch_aws_error, ALL_CODES, ALL_OPERATIONS, errors, make_aws_error, ) rand_str = lambda: secrets.token_hex(4) def _make_test_error( ...
0.540924
0.319891
# pylint: disable=line-too-long # pylint: disable=too-many-lines import json from azure.cli.testsdk import ( ResourceGroupPreparer, ScenarioTest, StorageAccountPreparer ) from azure.cli.testsdk.scenario_tests import AllowLargeResponse class StreamAnalyticsClientTest(ScenarioTest): @ResourceGroupPre...
src/stream-analytics/azext_stream_analytics/tests/latest/test_stream_analytics_commands.py
# pylint: disable=line-too-long # pylint: disable=too-many-lines import json from azure.cli.testsdk import ( ResourceGroupPreparer, ScenarioTest, StorageAccountPreparer ) from azure.cli.testsdk.scenario_tests import AllowLargeResponse class StreamAnalyticsClientTest(ScenarioTest): @ResourceGroupPre...
0.52342
0.177597
#%% import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from sklearn.preprocessing import MinMaxScaler from skmultiflow.data import DataStream from skmultiflow.evaluation import EvaluatePrequential from skmultiflow.trees import RegressionHAT, RegressionHoeffdingTr...
dataset.py
#%% import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) from sklearn.preprocessing import MinMaxScaler from skmultiflow.data import DataStream from skmultiflow.evaluation import EvaluatePrequential from skmultiflow.trees import RegressionHAT, RegressionHoeffdingTr...
0.300027
0.36659
import math import unittest import arc.species.converter as converter import arc.species.vectors as vectors from arc.species.species import ARCSpecies class TestVectors(unittest.TestCase): """ Contains unit tests for the vectors module """ @classmethod def setUpClass(cls): """ A ...
arc/species/vectorsTest.py
import math import unittest import arc.species.converter as converter import arc.species.vectors as vectors from arc.species.species import ARCSpecies class TestVectors(unittest.TestCase): """ Contains unit tests for the vectors module """ @classmethod def setUpClass(cls): """ A ...
0.815416
0.748858
import os import numpy as np import pytest from webbpsf import roman, measure_fwhm from astropy.table import Table from numpy import allclose GRISM_FILTERS = roman.GRISM_FILTERS PRISM_FILTERS = roman.PRISM_FILTERS def detector_substr(detector): """ change detector string to match file format (e.g., "SCA0...
webbpsf/tests/test_roman.py
import os import numpy as np import pytest from webbpsf import roman, measure_fwhm from astropy.table import Table from numpy import allclose GRISM_FILTERS = roman.GRISM_FILTERS PRISM_FILTERS = roman.PRISM_FILTERS def detector_substr(detector): """ change detector string to match file format (e.g., "SCA0...
0.770033
0.359224
from selenium import webdriver from selenium.webdriver import ActionChains from bs4 import BeautifulSoup from time import sleep from selenium.webdriver.common.keys import Keys from file_io import * import textwrap print('Thank you for using Simple Quora Backup') print('This will backup your BOOKMARKS to a text file i...
backup_bookmarks.py
from selenium import webdriver from selenium.webdriver import ActionChains from bs4 import BeautifulSoup from time import sleep from selenium.webdriver.common.keys import Keys from file_io import * import textwrap print('Thank you for using Simple Quora Backup') print('This will backup your BOOKMARKS to a text file i...
0.162812
0.075414
from typing import Dict, List, Optional, Union, Tuple import csv import io import os import numpy as np import paddle from paddlehub.env import DATA_HOME from paddlehub.text.bert_tokenizer import BertTokenizer from paddlehub.text.tokenizer import CustomTokenizer from paddlehub.utils.log import logger from paddlehub.u...
paddlehub/datasets/base_nlp_dataset.py
from typing import Dict, List, Optional, Union, Tuple import csv import io import os import numpy as np import paddle from paddlehub.env import DATA_HOME from paddlehub.text.bert_tokenizer import BertTokenizer from paddlehub.text.tokenizer import CustomTokenizer from paddlehub.utils.log import logger from paddlehub.u...
0.895651
0.258782
"""This is an example to train a task with parallel sampling.""" import click from garage import wrap_experiment from garage.envs import GarageEnv from garage.experiment import LocalTFRunner from garage.experiment.deterministic import set_seed from garage.np.baselines import LinearFeatureBaseline from garage.tf.algos ...
examples/tf/trpo_cartpole_batch_sampler.py
"""This is an example to train a task with parallel sampling.""" import click from garage import wrap_experiment from garage.envs import GarageEnv from garage.experiment import LocalTFRunner from garage.experiment.deterministic import set_seed from garage.np.baselines import LinearFeatureBaseline from garage.tf.algos ...
0.909846
0.424651
import json import requests import json import os from dotenv import load_dotenv # Load env load_dotenv() bearer_token = os.getenv("BEARER_TOKEN") ##chatid = os.getenv("CHATID") def bearer_oauth(r): r.headers["Authorization"] = f"Bearer {bearer_token}" r.headers["User-Agent"] = "v2FilteredStreamPython" return r ...
doukichan.py
import json import requests import json import os from dotenv import load_dotenv # Load env load_dotenv() bearer_token = os.getenv("BEARER_TOKEN") ##chatid = os.getenv("CHATID") def bearer_oauth(r): r.headers["Authorization"] = f"Bearer {bearer_token}" r.headers["User-Agent"] = "v2FilteredStreamPython" return r ...
0.150715
0.078926
import requests import pymongo class DataBase: def __init__(self): self.client = None self.db = None self.col = None self.connect_init() def connect_init(self): # 下面这个是哪个数据库来着??? # self.client = pymongo.MongoClient("mongodb+srv://LanceLiang:<EMAIL>." # ...
database.py
import requests import pymongo class DataBase: def __init__(self): self.client = None self.db = None self.col = None self.connect_init() def connect_init(self): # 下面这个是哪个数据库来着??? # self.client = pymongo.MongoClient("mongodb+srv://LanceLiang:<EMAIL>." # ...
0.110435
0.108969
import re import pytest from errors import TemplateSyntaxError from template import Template def tryRender(text, ctx=None, expected=None): actual = Template(text).render(ctx or {}) if expected: assert actual == expected def assertSyntaxError(text, ctx=None, msg=None): with pytest.raises(Templa...
template_test.py
import re import pytest from errors import TemplateSyntaxError from template import Template def tryRender(text, ctx=None, expected=None): actual = Template(text).render(ctx or {}) if expected: assert actual == expected def assertSyntaxError(text, ctx=None, msg=None): with pytest.raises(Templa...
0.397237
0.358437
from __future__ import annotations from typing import Sequence, Tuple, Union from . import _vroom class LocationIndex(_vroom.Location): """Index in the custom duration matrix for where to find distances. Attributes: index: Location index referring to column in the duration ma...
src/vroom/location.py
from __future__ import annotations from typing import Sequence, Tuple, Union from . import _vroom class LocationIndex(_vroom.Location): """Index in the custom duration matrix for where to find distances. Attributes: index: Location index referring to column in the duration ma...
0.968186
0.662455
import os import warnings from RLTest import Env class FlowTestsBase(object): def __init__(self): self.env = Env() redis_con = self.env.getConnection() redis_con.execute_command("FLUSHALL") def _assert_equalish(self, a, b, e=0.05): delta = a * e diff = abs(a-b) ...
tests/flow/base.py
import os import warnings from RLTest import Env class FlowTestsBase(object): def __init__(self): self.env = Env() redis_con = self.env.getConnection() redis_con.execute_command("FLUSHALL") def _assert_equalish(self, a, b, e=0.05): delta = a * e diff = abs(a-b) ...
0.54698
0.336713
from __future__ import annotations from aioresponses import aioresponses from bold_smart_lock.auth import Auth from bold_smart_lock.const import API_URI, AUTHENTICATIONS_ENDPOINT, POST_HEADERS, VALIDATIONS_ENDPOINT import aiohttp import json import os def load_fixture(filename: str, raw: bool = False): """Load a...
tests/helpers.py
from __future__ import annotations from aioresponses import aioresponses from bold_smart_lock.auth import Auth from bold_smart_lock.const import API_URI, AUTHENTICATIONS_ENDPOINT, POST_HEADERS, VALIDATIONS_ENDPOINT import aiohttp import json import os def load_fixture(filename: str, raw: bool = False): """Load a...
0.61115
0.102709
import json, subprocess from ... pyaz_utils import get_cli_name, get_params def show(resource_group, profile_name, endpoint_name): params = get_params(locals()) command = "az afd endpoint show " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subp...
test/pyaz/afd/endpoint/__init__.py
import json, subprocess from ... pyaz_utils import get_cli_name, get_params def show(resource_group, profile_name, endpoint_name): params = get_params(locals()) command = "az afd endpoint show " + params print(command) output = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subp...
0.209712
0.062245
from attr import attrib, NOTHING from related import _init_fields, types from collections import OrderedDict from .converters import to_sequence_field_w_str, to_leaf_mapping_field, to_eval_str, identity from . import dispatchers # to load the dispatcher class UNSPECIFIED(object): pass def AnyField(default=NOTH...
kipoi_utils/external/related/fields.py
from attr import attrib, NOTHING from related import _init_fields, types from collections import OrderedDict from .converters import to_sequence_field_w_str, to_leaf_mapping_field, to_eval_str, identity from . import dispatchers # to load the dispatcher class UNSPECIFIED(object): pass def AnyField(default=NOTH...
0.777807
0.264563
from functools import lru_cache import logging import os from box import Box from tavern.util.dict_util import format_keys from tavern.util.general import load_global_config from tavern.util.strict_util import StrictLevel logger = logging.getLogger(__name__) def add_parser_options(parser_addoption, with_defaults=T...
tavern/testutils/pytesthook/util.py
from functools import lru_cache import logging import os from box import Box from tavern.util.dict_util import format_keys from tavern.util.general import load_global_config from tavern.util.strict_util import StrictLevel logger = logging.getLogger(__name__) def add_parser_options(parser_addoption, with_defaults=T...
0.585812
0.171651
import argparse from pathlib import Path import json import shutil import sys from termcolor import colored, cprint from pprint import pprint def command_interface(title=None): parser = argparse.ArgumentParser(description=title) parser.add_argument('--config', '-cf', default=None, help='training configs json ...
util/command_interface.py
import argparse from pathlib import Path import json import shutil import sys from termcolor import colored, cprint from pprint import pprint def command_interface(title=None): parser = argparse.ArgumentParser(description=title) parser.add_argument('--config', '-cf', default=None, help='training configs json ...
0.269422
0.055311
from cme.helpers import create_ps_command, get_ps_script, obfs_ps_script, gen_random_string, validate_ntlm, write_log from datetime import datetime import re class CMEModule: ''' Executes PowerSploit's Invoke-Mimikatz.ps1 script Module by @byt3bl33d3r ''' name = 'mimikatz' description...
cme/modules/mimikatz.py
from cme.helpers import create_ps_command, get_ps_script, obfs_ps_script, gen_random_string, validate_ntlm, write_log from datetime import datetime import re class CMEModule: ''' Executes PowerSploit's Invoke-Mimikatz.ps1 script Module by @byt3bl33d3r ''' name = 'mimikatz' description...
0.268078
0.163445
import matplotlib as mpl mpl.use('TkAgg') import time import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter as Tk import snake_classes # Hacky global variables (shame on you) root = None reset_button = None snake = None ax = None canvas = N...
meandering_snake/meandering_snake.py
import matplotlib as mpl mpl.use('TkAgg') import time import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter as Tk import snake_classes # Hacky global variables (shame on you) root = None reset_button = None snake = None ax = None canvas = N...
0.413359
0.168309
import copy import itertools import sys class RecordClass(object): __slots__ = () required_attributes = () optional_attributes = {} def __init__(self, *args, **kwargs): # First, check for the maximum number of arguments. required_attributes = type(self).required_attributes if ...
mutablerecords/records.py
import copy import itertools import sys class RecordClass(object): __slots__ = () required_attributes = () optional_attributes = {} def __init__(self, *args, **kwargs): # First, check for the maximum number of arguments. required_attributes = type(self).required_attributes if ...
0.604399
0.14448
import sys PY2 = sys.version_info[0] == 2 def _identity(x): # pragma: no cover return x __all__ = [ 'BytesIO', 'PY2', 'StringIO', 'ascii_lowercase', 'cmp', 'configparser', 'console_to_str', 'imap', 'input', 'integer_types', 'iteritems', 'iterkeys', 'itervalue...
mt940/_compat.py
import sys PY2 = sys.version_info[0] == 2 def _identity(x): # pragma: no cover return x __all__ = [ 'BytesIO', 'PY2', 'StringIO', 'ascii_lowercase', 'cmp', 'configparser', 'console_to_str', 'imap', 'input', 'integer_types', 'iteritems', 'iterkeys', 'itervalue...
0.233619
0.238683
from socket import inet_aton from struct import pack, unpack from types import IntType, StringType, TupleType from ncrypt.digest import DigestType, Digest from ncrypt.rsa import RSAKey, RSAError from nitro.bencode import encode from cspace.dht.params import DHT_ID_LENGTH, DHT_ID_MAX digestType = DigestType( 'S...
cspace/dht/util.py
from socket import inet_aton from struct import pack, unpack from types import IntType, StringType, TupleType from ncrypt.digest import DigestType, Digest from ncrypt.rsa import RSAKey, RSAError from nitro.bencode import encode from cspace.dht.params import DHT_ID_LENGTH, DHT_ID_MAX digestType = DigestType( 'S...
0.351089
0.379723
from random import randint def dice(): num = randint(1, 6) return num for i in range (5): result = dice(5) print(result) from random import randint def dice(): num = randint(1, 6) return num for i in range(5): dice1 = dice() dice2 = dice() sum = dice1 + dic...
class-notes/chapter_10/c10-1.py
from random import randint def dice(): num = randint(1, 6) return num for i in range (5): result = dice(5) print(result) from random import randint def dice(): num = randint(1, 6) return num for i in range(5): dice1 = dice() dice2 = dice() sum = dice1 + dic...
0.236957
0.211987
import json class RPCObject: """Just group of other classes""" __slots__ = () class RPCError(BaseException, RPCObject): """JSON-RPC 2.0 error object""" __slots__ = 'code', 'message', 'data' def __init__(self, code, message='error', data=None): self.code, self.message, self.data = code, m...
dcnnt/common/jsonrpc.py
import json class RPCObject: """Just group of other classes""" __slots__ = () class RPCError(BaseException, RPCObject): """JSON-RPC 2.0 error object""" __slots__ = 'code', 'message', 'data' def __init__(self, code, message='error', data=None): self.code, self.message, self.data = code, m...
0.558207
0.203173
from functools import reduce from operator import mul from typing import Any import networkx as nx import numpy as np import pandas as pd from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.metrics import mutual_info_score from sklearn.metrics.cluster import contingency_matrix from sklearn.utils.mul...
src/hw4/expectation_maximization.py
from functools import reduce from operator import mul from typing import Any import networkx as nx import numpy as np import pandas as pd from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.metrics import mutual_info_score from sklearn.metrics.cluster import contingency_matrix from sklearn.utils.mul...
0.906624
0.503601
import os, sys, argparse, errno, yaml, time, datetime import rospy, rospkg import numpy as np from road_following.msg import Inference from road_following.cfg import PID_ControlConfig from road_following.srv import save_action, save_actionResponse from rosky_msgs.msg import Twist2DStamped from dynamic_reconfigure.serv...
catkin_ws/src/deep_learning/road_following/src/road_inference_to_reaction.py
import os, sys, argparse, errno, yaml, time, datetime import rospy, rospkg import numpy as np from road_following.msg import Inference from road_following.cfg import PID_ControlConfig from road_following.srv import save_action, save_actionResponse from rosky_msgs.msg import Twist2DStamped from dynamic_reconfigure.serv...
0.36886
0.095476
import unittest class TestCantor(unittest.TestCase): def test_cantor_initiator(self): import torch from torch.autograd import Variable import neurofire.models.cantor.cantor as cantor # Build model initiator = cantor.CantorInitiator(3, base_width=30) # Build dummy i...
tests/neurofire/models/test_cantor.py
import unittest class TestCantor(unittest.TestCase): def test_cantor_initiator(self): import torch from torch.autograd import Variable import neurofire.models.cantor.cantor as cantor # Build model initiator = cantor.CantorInitiator(3, base_width=30) # Build dummy i...
0.667581
0.605099
import streamlit as st import math import numpy as np from flask import Flask, request, jsonify, render_template from model import Model app = Flask(__name__) @app.route('/') def home(): return render_template('login.html') @app.route('/realapp') def realapp(): """ Returns ------- Run App ...
app.py
import streamlit as st import math import numpy as np from flask import Flask, request, jsonify, render_template from model import Model app = Flask(__name__) @app.route('/') def home(): return render_template('login.html') @app.route('/realapp') def realapp(): """ Returns ------- Run App ...
0.385375
0.258097
import requests from typing import Callable, Union, Optional from .objects import SendableMessage def get_session_requests(): session = requests.Session() session.headers['Accept'] = 'application/json' session.headers['Content-Type'] = 'application/x-www-form-urlencoded' return session class VKChatB...
vkchatbot/__init__.py
import requests from typing import Callable, Union, Optional from .objects import SendableMessage def get_session_requests(): session = requests.Session() session.headers['Accept'] = 'application/json' session.headers['Content-Type'] = 'application/x-www-form-urlencoded' return session class VKChatB...
0.766075
0.057812
# Merge Sort function using loops def merge_sort(array): # Check if length of array is more than 1 if len(array) > 1: # Getting middle element index mid = len(array) // 2 left_half = array[:mid] right_half = array[mid:] # Merge sorting left half left = merge_sort(left_half) # Merge sorting rig...
Sorting Algorithms/Merge Sort Algorithm/Python/MergeSort.py
# Merge Sort function using loops def merge_sort(array): # Check if length of array is more than 1 if len(array) > 1: # Getting middle element index mid = len(array) // 2 left_half = array[:mid] right_half = array[mid:] # Merge sorting left half left = merge_sort(left_half) # Merge sorting rig...
0.605799
0.803097
from typing import Optional import numpy import torch import torch.autograd from torch import nn from ..base import EntityRelationEmbeddingModel from ...losses import Loss from ...nn.init import xavier_uniform_ from ...regularizers import Regularizer from ...triples import TriplesFactory from ...typing import DeviceH...
src/pykeen/models/unimodal/proj_e.py
from typing import Optional import numpy import torch import torch.autograd from torch import nn from ..base import EntityRelationEmbeddingModel from ...losses import Loss from ...nn.init import xavier_uniform_ from ...regularizers import Regularizer from ...triples import TriplesFactory from ...typing import DeviceH...
0.971913
0.840652
import logging from django.conf import settings from django.db import models # Instantiate logger. logger = logging.getLogger(__name__) class ApiKey(models.Model): """ Keys used for authenticating API requests. """ user = models.ForeignKey(settings.AUTH_USER_MODEL) key = models.CharField(max_leng...
yapi/models.py
import logging from django.conf import settings from django.db import models # Instantiate logger. logger = logging.getLogger(__name__) class ApiKey(models.Model): """ Keys used for authenticating API requests. """ user = models.ForeignKey(settings.AUTH_USER_MODEL) key = models.CharField(max_leng...
0.679285
0.097907
"""Window pane toolbar base class.""" from typing import Any, Callable, List, Optional import functools from prompt_toolkit.filters import Condition, has_focus from prompt_toolkit.layout import ( ConditionalContainer, FormattedTextControl, VSplit, Window, WindowAlign, ) import pw_console.style fr...
pw_console/py/pw_console/widgets/window_pane_toolbar.py
"""Window pane toolbar base class.""" from typing import Any, Callable, List, Optional import functools from prompt_toolkit.filters import Condition, has_focus from prompt_toolkit.layout import ( ConditionalContainer, FormattedTextControl, VSplit, Window, WindowAlign, ) import pw_console.style fr...
0.867162
0.068382
from opentrons import protocol_api import pandas as pd import decimal, math #Not yet implement labware compatibility and constrains metadata = {'apiLevel': '2.8'} def run(protocol: protocol_api.ProtocolContext): pipette_name = 'p300_single' #file path df = pd.read_csv(r'test/generated_test_files/random_p...
distribute.py
from opentrons import protocol_api import pandas as pd import decimal, math #Not yet implement labware compatibility and constrains metadata = {'apiLevel': '2.8'} def run(protocol: protocol_api.ProtocolContext): pipette_name = 'p300_single' #file path df = pd.read_csv(r'test/generated_test_files/random_p...
0.242564
0.275443
import numpy as np import eli5 from eli5.sklearn import PermutationImportance from eli5.permutation_importance import get_score_importances class PermutationImportance_(object): """ see https://eli5.readthedocs.io/en/latest/blackbox/permutation_importance.html and see https://www.kaggle.com/dansbecker/per...
eslearn/utils/permutation_importance.py
import numpy as np import eli5 from eli5.sklearn import PermutationImportance from eli5.permutation_importance import get_score_importances class PermutationImportance_(object): """ see https://eli5.readthedocs.io/en/latest/blackbox/permutation_importance.html and see https://www.kaggle.com/dansbecker/per...
0.839306
0.517815