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 unittest from itertools import product import mock import numpy as np import pytest from tensorkit import tensor as T from tensorkit import * from tensorkit.distributions import * from tensorkit.distributions.categorical import BaseCategorical from tensorkit.distributions.utils import copy_distribution from te...
tests/distributions/test_categorical.py
import unittest from itertools import product import mock import numpy as np import pytest from tensorkit import tensor as T from tensorkit import * from tensorkit.distributions import * from tensorkit.distributions.categorical import BaseCategorical from tensorkit.distributions.utils import copy_distribution from te...
0.714927
0.493897
import cntk as C import os import pandas as pd import numpy as np import time from pandas_datareader import data as pd_data from saxpy.sax import sax_via_window import logging try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve logging.basicConfig(level=10, format...
generic/cntk-lstm-forecast/service/time_series_forecast.py
import cntk as C import os import pandas as pd import numpy as np import time from pandas_datareader import data as pd_data from saxpy.sax import sax_via_window import logging try: from urllib.request import urlretrieve except ImportError: from urllib import urlretrieve logging.basicConfig(level=10, format...
0.45181
0.197561
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import cPickle import os import download from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf def one_hot_encoded(class_numbers, num_classes=None): ...
data/cifar10/cifar10.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import cPickle import os import download from six.moves import xrange # pylint: disable=redefined-builtin import tensorflow as tf def one_hot_encoded(class_numbers, num_classes=None): ...
0.721841
0.561816
from cPickle import dumps, loads __all__ = ['DIST_MODULA', 'DIST_CONSISTENT', 'DIST_CONSISTENT_KETAMA', 'Client'] DIST_MODULA = 0 DIST_CONSISTENT = 1 DIST_CONSISTENT_KETAMA = 2 (BEHAVIOR_NO_BLOCK, BEHAVIOR_TCP_NODELAY, BEHAVIOR_HASH, BEHAVIOR_KETAMA, BEHAVIOR_SOCKET_SEND_SIZE, BEHAVIOR_SOCKET_RECV_S...
tests/stub/cmemcached.py
from cPickle import dumps, loads __all__ = ['DIST_MODULA', 'DIST_CONSISTENT', 'DIST_CONSISTENT_KETAMA', 'Client'] DIST_MODULA = 0 DIST_CONSISTENT = 1 DIST_CONSISTENT_KETAMA = 2 (BEHAVIOR_NO_BLOCK, BEHAVIOR_TCP_NODELAY, BEHAVIOR_HASH, BEHAVIOR_KETAMA, BEHAVIOR_SOCKET_SEND_SIZE, BEHAVIOR_SOCKET_RECV_S...
0.456894
0.118742
import inspect import random from typing import Callable, Iterable, Optional, Sequence, TypeVar from . import process from .util import Closed, Crashed, Stopped def proc(fn: Optional[Callable] = None, *args, **kwargs): """A decorator to create a process""" def decorator(fn): def proc_(): f...
cpo/meta.py
import inspect import random from typing import Callable, Iterable, Optional, Sequence, TypeVar from . import process from .util import Closed, Crashed, Stopped def proc(fn: Optional[Callable] = None, *args, **kwargs): """A decorator to create a process""" def decorator(fn): def proc_(): f...
0.695441
0.22946
import tensorflow as tf from .gpt2 import TFGPT2MainLayer from .discriminator import Discriminator class gpt2wgan(tf.keras.Model): def __init__(self, config, noise_len: int = 784, noise_dim: int = 32, d_extra_steps: int = 5, **kwargs): super(gpt2wgan, self).__init__() self.generator = TFGPT2Mai...
model/gpt2wgan.py
import tensorflow as tf from .gpt2 import TFGPT2MainLayer from .discriminator import Discriminator class gpt2wgan(tf.keras.Model): def __init__(self, config, noise_len: int = 784, noise_dim: int = 32, d_extra_steps: int = 5, **kwargs): super(gpt2wgan, self).__init__() self.generator = TFGPT2Mai...
0.905939
0.434161
from ai_lit.input import input_util from ai_lit.input.gutenberg_dataset import gb_input from ai_lit.input.gutenberg_dataset import gb_titles_dataset from ai_lit.models import mean_mlp from ai_lit.university import ai_lit_university import tensorflow as tf tf.flags.DEFINE_bool("use_pretrained_embeddings", False, ...
ai_lit/university/gutenberg/gb_titles_avg_mlp.py
from ai_lit.input import input_util from ai_lit.input.gutenberg_dataset import gb_input from ai_lit.input.gutenberg_dataset import gb_titles_dataset from ai_lit.models import mean_mlp from ai_lit.university import ai_lit_university import tensorflow as tf tf.flags.DEFINE_bool("use_pretrained_embeddings", False, ...
0.915005
0.493348
import sys import argparse import flask import json import psycopg2 from config import password from config import database from config import user # Connect to the database try: connection = psycopg2.connect(database=database, user=user, password=password) except Exception as e: print(e) exit() app = flask...
olympics-api/olympics-api.py
import sys import argparse import flask import json import psycopg2 from config import password from config import database from config import user # Connect to the database try: connection = psycopg2.connect(database=database, user=user, password=password) except Exception as e: print(e) exit() app = flask...
0.254324
0.171165
from collections import OrderedDict import torch.nn as nn from mmdet.models.utils import brick as vn_layer # https://github.com/AlexeyAB/darknet/wiki/YOLOv4-model-zoo class Yolov4(nn.Module): # 用于递归导入权重 custom_layers = (vn_layer.Resblock_body, vn_layer.Resblock_body.custom_layers, vn_layer.Head, ...
tools/darknet/yolov4.py
from collections import OrderedDict import torch.nn as nn from mmdet.models.utils import brick as vn_layer # https://github.com/AlexeyAB/darknet/wiki/YOLOv4-model-zoo class Yolov4(nn.Module): # 用于递归导入权重 custom_layers = (vn_layer.Resblock_body, vn_layer.Resblock_body.custom_layers, vn_layer.Head, ...
0.880013
0.302636
from math import sqrt from solid import * from solid.utils import * import util from util import radial, pipe, ABIT, vadd from fixings import M3 from aptsources.distinfo import Mirror def body(height=21.0, radius=50.0, insert_height=3.0, t=2.0, arch_width=12.0): def body_cross_section(): return translate([...
hardware/body.py
from math import sqrt from solid import * from solid.utils import * import util from util import radial, pipe, ABIT, vadd from fixings import M3 from aptsources.distinfo import Mirror def body(height=21.0, radius=50.0, insert_height=3.0, t=2.0, arch_width=12.0): def body_cross_section(): return translate([...
0.641871
0.216964
import scipy.io import numpy as np from scipy.sparse.linalg.eigen.arpack import eigsh try: from bregman import bregman except ImportError: print("Failed to import Bregman subroutines") pass def bregman_func(A_in, En_in, method=5, mu=0.001, lbd=3., maxIter=100, tol=1E-4): # Open the A matrix file i...
cssolve/bregman_func.py
import scipy.io import numpy as np from scipy.sparse.linalg.eigen.arpack import eigsh try: from bregman import bregman except ImportError: print("Failed to import Bregman subroutines") pass def bregman_func(A_in, En_in, method=5, mu=0.001, lbd=3., maxIter=100, tol=1E-4): # Open the A matrix file i...
0.268366
0.540196
import torch.nn as nn import torch from torch.autograd import Variable import pickle import numpy as np from torch.utils.data import SubsetRandomSampler, TensorDataset import os from model import * import torch.optim as optim import datetime seed = 1 torch.manual_seed(seed) np.random.seed(seed) torch.cuda.manual_seed_...
train.py
import torch.nn as nn import torch from torch.autograd import Variable import pickle import numpy as np from torch.utils.data import SubsetRandomSampler, TensorDataset import os from model import * import torch.optim as optim import datetime seed = 1 torch.manual_seed(seed) np.random.seed(seed) torch.cuda.manual_seed_...
0.418578
0.459015
from tencentcloud.common.abstract_model import AbstractModel class CreateDBInstanceHourRequest(AbstractModel): """CreateDBInstanceHour请求参数结构体 """ def __init__(self): """ :param Memory: 实例内存大小,单位:GB :type Memory: int :param Volume: 实例硬盘大小,单位:GB :type Volume: int ...
tencentcloud/mongodb/v20180408/models.py
from tencentcloud.common.abstract_model import AbstractModel class CreateDBInstanceHourRequest(AbstractModel): """CreateDBInstanceHour请求参数结构体 """ def __init__(self): """ :param Memory: 实例内存大小,单位:GB :type Memory: int :param Volume: 实例硬盘大小,单位:GB :type Volume: int ...
0.462959
0.238678
import copy import os from functools import lru_cache from collections import OrderedDict import torch from portal.portal_io import cache_file from mmf.common import Sample from mmf.datasets import BaseDataset class TextCommonClsDataset(BaseDataset): def __init__(self, config, dataset_type, dataset_name, data_f...
mmf/datasets/builders/text/text_dataset.py
import copy import os from functools import lru_cache from collections import OrderedDict import torch from portal.portal_io import cache_file from mmf.common import Sample from mmf.datasets import BaseDataset class TextCommonClsDataset(BaseDataset): def __init__(self, config, dataset_type, dataset_name, data_f...
0.618089
0.194349
import logging from typing import List from fuzzywuzzy import fuzz from DatabaseDriver.SqlClasses import PatchData from Objects.PatchDiffs import PatchDiffs def patch_matches(downstream_patches: List[PatchData], upstream: PatchData) -> bool: """Check if 'upstream' has an equivalent in 'downstream_patches'. """ ...
DownstreamTracker/DownstreamMatcher.py
import logging from typing import List from fuzzywuzzy import fuzz from DatabaseDriver.SqlClasses import PatchData from Objects.PatchDiffs import PatchDiffs def patch_matches(downstream_patches: List[PatchData], upstream: PatchData) -> bool: """Check if 'upstream' has an equivalent in 'downstream_patches'. """ ...
0.744749
0.398085
import base64 import json import os from pprint import pprint from typing import Dict, List import requests from github3 import apps def get_default_app(): if not hasattr(get_default_app, "app"): pem_key = os.getenv("BASE64_PRIVATE_PEM_KEY", "") if not pem_key: raise RuntimeError("Mis...
github_token_app/github_app.py
import base64 import json import os from pprint import pprint from typing import Dict, List import requests from github3 import apps def get_default_app(): if not hasattr(get_default_app, "app"): pem_key = os.getenv("BASE64_PRIVATE_PEM_KEY", "") if not pem_key: raise RuntimeError("Mis...
0.49707
0.087486
import nqs import numpy as np import sampler import observables import time import matplotlib.pyplot as plt import distances import ising1d #Script to generate the data -- sigmax(t) for all our time-evolved wave functions nsteps = 400 data_rate = 5 nruns = 1000 talk_rate = 25 h = ising1d.Ising1d(10,1.0) ## Now that w...
Scripts/data_time_series.py
import nqs import numpy as np import sampler import observables import time import matplotlib.pyplot as plt import distances import ising1d #Script to generate the data -- sigmax(t) for all our time-evolved wave functions nsteps = 400 data_rate = 5 nruns = 1000 talk_rate = 25 h = ising1d.Ising1d(10,1.0) ## Now that w...
0.358129
0.483161
import logging import click import torch from sonosco.serialization import Deserializer from sonosco.models import TDSSeq2Seq from sonosco.common.constants import SONOSCO from sonosco.common.utils import setup_logging from sonosco.common.path_utils import parse_yaml from sonosco.training import Experiment, ModelTraine...
executables/train.py
import logging import click import torch from sonosco.serialization import Deserializer from sonosco.models import TDSSeq2Seq from sonosco.common.constants import SONOSCO from sonosco.common.utils import setup_logging from sonosco.common.path_utils import parse_yaml from sonosco.training import Experiment, ModelTraine...
0.659186
0.100657
import datetime from django.conf import settings from django.core.management.base import BaseCommand from django.utils import timezone import requests from data_refinery_common.models import Dataset, DatasetAnnotation def post_downloads_summary(days, channel): start_time = timezone.now() - datetime.timedelta(d...
api/data_refinery_api/management/commands/post_downloads_summary.py
import datetime from django.conf import settings from django.core.management.base import BaseCommand from django.utils import timezone import requests from data_refinery_common.models import Dataset, DatasetAnnotation def post_downloads_summary(days, channel): start_time = timezone.now() - datetime.timedelta(d...
0.485356
0.208904
import subprocess import re import codecs import time class WiFiScanner(): """iw-based Wi-Fi networks scanner""" def __init__(self, interface): self.interface = interface def scan(self, dump_only=False): '''Parsing iw scan results''' def handle_network(line, result, networks): ...
main.py
import subprocess import re import codecs import time class WiFiScanner(): """iw-based Wi-Fi networks scanner""" def __init__(self, interface): self.interface = interface def scan(self, dump_only=False): '''Parsing iw scan results''' def handle_network(line, result, networks): ...
0.329931
0.148325
import numpy as np import matplotlib.image as mpimg # read image import matplotlib.pyplot as plt # plot image import tkinter as tk # GUI design from PIL import Image # used for save image from numpy.fft import fft2, ifft2, fftshift, ifftshift # fourier transform # Set information of GUI window = tk.Tk() w...
hw2.py
import numpy as np import matplotlib.image as mpimg # read image import matplotlib.pyplot as plt # plot image import tkinter as tk # GUI design from PIL import Image # used for save image from numpy.fft import fft2, ifft2, fftshift, ifftshift # fourier transform # Set information of GUI window = tk.Tk() w...
0.559531
0.507934
class Stack: def __init__(self): self.__items = [] def is_empty(self): return self.__items == [] def push(self, item): self.__items.append(item) def pop(self): try: return self.__items.pop() except IndexError: return "ERROR: The ...
Stacks/Postfix.py
class Stack: def __init__(self): self.__items = [] def is_empty(self): return self.__items == [] def push(self, item): self.__items.append(item) def pop(self): try: return self.__items.pop() except IndexError: return "ERROR: The ...
0.359139
0.15785
from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient class TeamBuilderConfigProductTypeApi(object): """ NOTE: This class is auto generated by...
TweakApi/apis/team_builder_config_product_type_api.py
from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..configuration import Configuration from ..api_client import ApiClient class TeamBuilderConfigProductTypeApi(object): """ NOTE: This class is auto generated by...
0.604399
0.055978
import re import wlsdeploy.aliases.model_constants as model_constants import wlsdeploy.util.model as model_sections from oracle.weblogic.deploy.aliases import AliasException from wlsdeploy.aliases.location_context import LocationContext from wlsdeploy.logging.platform_logger import PlatformLogger _class_name = 'varia...
core/src/main/python/wlsdeploy/tool/util/variable_injector_functions.py
import re import wlsdeploy.aliases.model_constants as model_constants import wlsdeploy.util.model as model_sections from oracle.weblogic.deploy.aliases import AliasException from wlsdeploy.aliases.location_context import LocationContext from wlsdeploy.logging.platform_logger import PlatformLogger _class_name = 'varia...
0.629205
0.106877
__author__ = 'emre' import unittest from hmm import * import sklearn.hmm import random def generate_observations(num_classes): size = random.randint(5, 30) observations = np.empty(size).astype(int) for t in xrange(size): observations[t] = random.randint(0, num_classes - 1) return observatio...
hmm-test.py
__author__ = 'emre' import unittest from hmm import * import sklearn.hmm import random def generate_observations(num_classes): size = random.randint(5, 30) observations = np.empty(size).astype(int) for t in xrange(size): observations[t] = random.randint(0, num_classes - 1) return observatio...
0.700997
0.480905
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name=...
test_django_denis/testdenis/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name=...
0.599954
0.173533
import numpy as np import pandas as pd # ------------------------------------------------------------------------------ # pandas dataframe utils # ------------------------------------------------------------------------------ def df_info(df): return f"{df.shape}; index={list(df.index.names)}; cols={list(df.colum...
callflow/utils/df.py
import numpy as np import pandas as pd # ------------------------------------------------------------------------------ # pandas dataframe utils # ------------------------------------------------------------------------------ def df_info(df): return f"{df.shape}; index={list(df.index.names)}; cols={list(df.colum...
0.701815
0.676633
import re __all__ = ['Attribute', 'Table', 'Operation', 'insert_alias'] class Attribute: def __init__(self, name, formula, is_pk): self.name = name self.formula = formula self.is_pk = is_pk def __str__(self): return self.name class Table: def __init__(self, name, alias,...
cellql/objects.py
import re __all__ = ['Attribute', 'Table', 'Operation', 'insert_alias'] class Attribute: def __init__(self, name, formula, is_pk): self.name = name self.formula = formula self.is_pk = is_pk def __str__(self): return self.name class Table: def __init__(self, name, alias,...
0.521959
0.113727
import json import os import random import sys from typing import Any, Iterable, Mapping, Optional, Tuple, Union import click from gensim.models import Word2Vec from sqlalchemy.orm import Session from tqdm import tqdm, trange from .models import Collection, Embedding, get_session from ..constants import config __all...
src/embeddingdb/sql/io.py
import json import os import random import sys from typing import Any, Iterable, Mapping, Optional, Tuple, Union import click from gensim.models import Word2Vec from sqlalchemy.orm import Session from tqdm import tqdm, trange from .models import Collection, Embedding, get_session from ..constants import config __all...
0.592784
0.128991
__author__ = 'vilelag' import sys import argparse import numpy as np def create_parsers(): #parser for the main program parser = argparse.ArgumentParser(description='Print all the n classes with most elements, only takes into account' 'words in the vocabulary...
scripts/print_top_classes.py
__author__ = 'vilelag' import sys import argparse import numpy as np def create_parsers(): #parser for the main program parser = argparse.ArgumentParser(description='Print all the n classes with most elements, only takes into account' 'words in the vocabulary...
0.27914
0.186539
from __future__ import annotations from homeassistant.components.select import ( DOMAIN as PLATFORM_SELECT, SelectEntity ) from .merossclient import const as mc # mEROSS cONST from .meross_entity import _MerossEntity, platform_setup_entry, platform_unload_entry async def async_setup_entry(hass: object, con...
custom_components/meross_lan/select.py
from __future__ import annotations from homeassistant.components.select import ( DOMAIN as PLATFORM_SELECT, SelectEntity ) from .merossclient import const as mc # mEROSS cONST from .meross_entity import _MerossEntity, platform_setup_entry, platform_unload_entry async def async_setup_entry(hass: object, con...
0.452899
0.110327
from .exceptions import NotRetriableError class ErrorWhitelist(object): """ Stores an error whitelist and provides a simple interface for whitelist update and mutation. Arguments: errors (set|list|tuple[Exception]): optional list of error exceptions classes to whitelist. Attr...
riprova/errors.py
from .exceptions import NotRetriableError class ErrorWhitelist(object): """ Stores an error whitelist and provides a simple interface for whitelist update and mutation. Arguments: errors (set|list|tuple[Exception]): optional list of error exceptions classes to whitelist. Attr...
0.796372
0.291182
import os import yaml from common.constants import ( PART_NAME, PLUGIN_TMP_DIR, PLUGIN_NAME, ) class HOTSOSDumper(yaml.Dumper): def increase_indent(self, flow=False, indentless=False): return super().increase_indent(flow, False) def represent_dict_preserve_order(self, data): retu...
common/plugin_yaml.py
import os import yaml from common.constants import ( PART_NAME, PLUGIN_TMP_DIR, PLUGIN_NAME, ) class HOTSOSDumper(yaml.Dumper): def increase_indent(self, flow=False, indentless=False): return super().increase_indent(flow, False) def represent_dict_preserve_order(self, data): retu...
0.408159
0.163746
import datetime import logging import re from os.path import basename, dirname, exists from requests import get from util import get_checksums, read_file def get_repo_content(artifactory_spec, repo_key): url = f'{artifactory_spec["url"]}/api/storage/{repo_key}?list&deep=1&listFolders=1' response = get(url, ...
src/artifactory.py
import datetime import logging import re from os.path import basename, dirname, exists from requests import get from util import get_checksums, read_file def get_repo_content(artifactory_spec, repo_key): url = f'{artifactory_spec["url"]}/api/storage/{repo_key}?list&deep=1&listFolders=1' response = get(url, ...
0.209551
0.078325
# pylint: skip-file import argparse import csv import uuid import json import sys from timesketch.lib.experimental.utils import event_stream from timesketch.lib.experimental.utils import parse_xml_event class KnowledgeBase(object): def __init__(self): self.ip2host = {} def add(self, ip, hostname):...
timesketch/lib/experimental/win_logins.py
# pylint: skip-file import argparse import csv import uuid import json import sys from timesketch.lib.experimental.utils import event_stream from timesketch.lib.experimental.utils import parse_xml_event class KnowledgeBase(object): def __init__(self): self.ip2host = {} def add(self, ip, hostname):...
0.328745
0.087019
import roslib; roslib.load_manifest('articulation_structure') import rospy import sys from visualization_msgs.msg import Marker, MarkerArray from geometry_msgs.msg import Vector3, Point, Pose, PoseArray from std_msgs.msg import ColorRGBA from sensor_msgs.msg import ChannelFloat32 from articulation_msgs.msg import * fr...
articulation_structure/nodes/articulation_collector.py
import roslib; roslib.load_manifest('articulation_structure') import rospy import sys from visualization_msgs.msg import Marker, MarkerArray from geometry_msgs.msg import Vector3, Point, Pose, PoseArray from std_msgs.msg import ColorRGBA from sensor_msgs.msg import ChannelFloat32 from articulation_msgs.msg import * fr...
0.282889
0.117572
import json import pytest from model_mommy import mommy from datetime import datetime from rest_framework import status from django_mock_queries.query import MockModel from usaspending_api.awards.models_matviews import SummaryTransactionView from usaspending_api.common.helpers.unit_test_helper import add_to_mock_obje...
usaspending_api/search/tests/unit/test_spending_over_time_details.py
import json import pytest from model_mommy import mommy from datetime import datetime from rest_framework import status from django_mock_queries.query import MockModel from usaspending_api.awards.models_matviews import SummaryTransactionView from usaspending_api.common.helpers.unit_test_helper import add_to_mock_obje...
0.569134
0.400691
import time import numpy as np def _t(x): return np.transpose(x) def _m(A, B): return np.matmul(A, B) class Sigmoid: def __init__(self): self.last_o = 1 def __call__(self, x): self.last_o = (1.0 / (1.0 + np.exp(-x))) return self.last_o def grad(self): return sel...
tensorflow/Backpropagation.py
import time import numpy as np def _t(x): return np.transpose(x) def _m(A, B): return np.matmul(A, B) class Sigmoid: def __init__(self): self.last_o = 1 def __call__(self, x): self.last_o = (1.0 / (1.0 + np.exp(-x))) return self.last_o def grad(self): return sel...
0.746231
0.421016
import time import matplotlib.pyplot as plt import numpy as np from communication import Transmitter from osparc_control import CommandManifest from osparc_control import CommandParameter from osparc_control import CommandType from osparc_control import PairedTransmitter class TSolver: def __init__( sel...
examples/3_tsolver/Tsolver.py
import time import matplotlib.pyplot as plt import numpy as np from communication import Transmitter from osparc_control import CommandManifest from osparc_control import CommandParameter from osparc_control import CommandType from osparc_control import PairedTransmitter class TSolver: def __init__( sel...
0.53777
0.409811
import random import time def print_sleep(start_message): print(start_message) time.sleep(2) def visit_character(pouch): print_sleep("Please enter the character that might help you exit" " the Haunted House:\n") character = input("Witch\n" "Pirate\n" ...
haunted_house.py
import random import time def print_sleep(start_message): print(start_message) time.sleep(2) def visit_character(pouch): print_sleep("Please enter the character that might help you exit" " the Haunted House:\n") character = input("Witch\n" "Pirate\n" ...
0.112186
0.121191
import json import argparse from lib import buildtools __description__ = "Display the contents of a file on the target machine" __author__ = "@_batsec_" EXEC_ID = 0x4000 OPCODE_LS = 0x2000 ERROR = False error_list = "" # let argparse error and exit nice def error(message): global ERROR, error_list ERROR...
lib/commands/cat.py
import json import argparse from lib import buildtools __description__ = "Display the contents of a file on the target machine" __author__ = "@_batsec_" EXEC_ID = 0x4000 OPCODE_LS = 0x2000 ERROR = False error_list = "" # let argparse error and exit nice def error(message): global ERROR, error_list ERROR...
0.298798
0.104569
from setuptools import setup, Extension import numpy import os, platform, sys, re try: from Cython.Build import cythonize except ImportError: print('Cython is required') quit(1) # path to libs and headers package_dir = os.path.join('src', 'svmrank') svm_rank_sourcedir = os.path.join('src', 'c') include_dirs = [...
setup.py
from setuptools import setup, Extension import numpy import os, platform, sys, re try: from Cython.Build import cythonize except ImportError: print('Cython is required') quit(1) # path to libs and headers package_dir = os.path.join('src', 'svmrank') svm_rank_sourcedir = os.path.join('src', 'c') include_dirs = [...
0.18159
0.060059
import datetime import tempfile import argparse from pathlib import Path import numpy as np import pandas as pd import scipy.constants from cdflib import cdfread, epochs import pymms from pymms.sdc import mrmms_sdc_api as api from pymms.sdc import selections as selections_api class Model_Data_Downloader: """ ...
pymms/gls/mp_dl_unh/data.py
import datetime import tempfile import argparse from pathlib import Path import numpy as np import pandas as pd import scipy.constants from cdflib import cdfread, epochs import pymms from pymms.sdc import mrmms_sdc_api as api from pymms.sdc import selections as selections_api class Model_Data_Downloader: """ ...
0.710025
0.347731
from unittest import TestCase from unittest.mock import Mock import numpy as np import pandas as pd import pytest from rdt.transformers import NullTransformer class TestNullTransformer(TestCase): def test___init__(self): """Test default instance""" # Run transformer = NullTransformer(No...
tests/transformers/test_null.py
from unittest import TestCase from unittest.mock import Mock import numpy as np import pandas as pd import pytest from rdt.transformers import NullTransformer class TestNullTransformer(TestCase): def test___init__(self): """Test default instance""" # Run transformer = NullTransformer(No...
0.890187
0.577555
from madflow.config import DTYPE import madflow.phasespace as ps import numpy as np import tensorflow as tf def massless_volume(n, e): """Volume of massless phase space 1 / 2 / (4*pi)^(2n-3) * E^(2n-4) / G(n)G(n-1) """ gn = np.math.factorial(n - 1) gnm1 = np.math.factorial(n - 2) energy = pow(...
python_package/madflow/tests/test_ps.py
from madflow.config import DTYPE import madflow.phasespace as ps import numpy as np import tensorflow as tf def massless_volume(n, e): """Volume of massless phase space 1 / 2 / (4*pi)^(2n-3) * E^(2n-4) / G(n)G(n-1) """ gn = np.math.factorial(n - 1) gnm1 = np.math.factorial(n - 2) energy = pow(...
0.752286
0.703893
class Solution: # @param S, a string # @param L, a list of string # @return a list of integer def findSubstring(self, S, L): if not S: return [] if not L: return [] wordcount = len(L) wordlen = len(L[0]) wordappear = {} for word in L: ...
src/Substring with Concatenation of All Words.py
class Solution: # @param S, a string # @param L, a list of string # @return a list of integer def findSubstring(self, S, L): if not S: return [] if not L: return [] wordcount = len(L) wordlen = len(L[0]) wordappear = {} for word in L: ...
0.380644
0.323701
import re rules = { 21: "71 69", 100: " 92 69 | 13 54", 116: " 34 13 | 41 92", 101: " 92 93 | 13 96", 122: " 13 22 | 92 19", 124: " 70 13 | 76 92", 29: "9 92 | 133 13", 2: "13 75 | 92 73", 117: " 132 92 | 109 13", 0: "8 11", 43: "92 13 | 13 13", 56: "41 13 | 34 92", ...
2020/19/main.py
import re rules = { 21: "71 69", 100: " 92 69 | 13 54", 116: " 34 13 | 41 92", 101: " 92 93 | 13 96", 122: " 13 22 | 92 19", 124: " 70 13 | 76 92", 29: "9 92 | 133 13", 2: "13 75 | 92 73", 117: " 132 92 | 109 13", 0: "8 11", 43: "92 13 | 13 13", 56: "41 13 | 34 92", ...
0.411584
0.407628
from config import config import sendgrid from sendgrid.helpers.mail import * import smtplib from email.mime.text import MIMEText ACCT_VERIFIED_SUBJECT = "Your iCTF Team Account has been verified!" ACCT_VERIFIED_MSG = """ Hello! The academic status of the iCTF account for your team (%s) has been verified! Thank you!...
teaminterface/lib/mailer.py
from config import config import sendgrid from sendgrid.helpers.mail import * import smtplib from email.mime.text import MIMEText ACCT_VERIFIED_SUBJECT = "Your iCTF Team Account has been verified!" ACCT_VERIFIED_MSG = """ Hello! The academic status of the iCTF account for your team (%s) has been verified! Thank you!...
0.128977
0.075756
import os import subprocess import tempfile from functools import partial from unittest.mock import patch import pytest from pkgcheck import __title__ as project from pkgcheck.checks.profiles import ProfileWarning from pkgcheck.reporters import JsonStream from pkgcheck.scripts import run from snakeoil.formatters impor...
tests/scripts/test_pkgcheck_replay.py
import os import subprocess import tempfile from functools import partial from unittest.mock import patch import pytest from pkgcheck import __title__ as project from pkgcheck.checks.profiles import ProfileWarning from pkgcheck.reporters import JsonStream from pkgcheck.scripts import run from snakeoil.formatters impor...
0.388038
0.305667
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Genre', fields=[ ('id', models.AutoField(a...
Backend/movie_reviews_back/api/migrations/0001_initial.py
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Genre', fields=[ ('id', models.AutoField(a...
0.424889
0.089018
from nltk import word_tokenize import nltk.data from readability import Readability import pprint import string import numpy import math numpy.seterr(divide='ignore', invalid='ignore') sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') def clean_words(words): new_words = [] for word in words...
feature/simple.py
from nltk import word_tokenize import nltk.data from readability import Readability import pprint import string import numpy import math numpy.seterr(divide='ignore', invalid='ignore') sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') def clean_words(words): new_words = [] for word in words...
0.353875
0.30728
import numpy as np import matplotlib.pylab as plt import json def getJsonData(data_file): with open(data_file, "r") as jsonFile: data= json.load(jsonFile) return data def saveDataToJson(fileName, data): with open(fileName, "w") as jsonFile: json.dump(data, jsonFile, indent=3) def compute...
geoflow1D/UtilsModule.py
import numpy as np import matplotlib.pylab as plt import json def getJsonData(data_file): with open(data_file, "r") as jsonFile: data= json.load(jsonFile) return data def saveDataToJson(fileName, data): with open(fileName, "w") as jsonFile: json.dump(data, jsonFile, indent=3) def compute...
0.321567
0.340129
from Graph import Graph from ContextFreeGrammar import ChomskyNormalForm as CNF from pyformlang.cfg import * def test_Asimov(): gr = CNF.from_file("cfg_input.txt") g = Graph() g.from_file("input4.txt") reachable = frozenset(gr.Asimov(g)) reachable_actual = frozenset(gr.Hellings(g)) assert reach...
tests/test_Task05.py
from Graph import Graph from ContextFreeGrammar import ChomskyNormalForm as CNF from pyformlang.cfg import * def test_Asimov(): gr = CNF.from_file("cfg_input.txt") g = Graph() g.from_file("input4.txt") reachable = frozenset(gr.Asimov(g)) reachable_actual = frozenset(gr.Hellings(g)) assert reach...
0.480235
0.380327
import copy from PyQt5 import QtCore from PyQt5.QtWidgets import QDialog, QSizePolicy, QLabel, QPushButton, QGridLayout, QSpinBox class EditMaxHPDialog(QDialog): def __init__(self, CharacterWindow): super().__init__(parent=CharacterWindow) # Store Parameters self.CharacterWindow = Charac...
Interface/Dialogs/EditMaxHPDialog.py
import copy from PyQt5 import QtCore from PyQt5.QtWidgets import QDialog, QSizePolicy, QLabel, QPushButton, QGridLayout, QSpinBox class EditMaxHPDialog(QDialog): def __init__(self, CharacterWindow): super().__init__(parent=CharacterWindow) # Store Parameters self.CharacterWindow = Charac...
0.468304
0.122313
import pathlib import numpy as np import pandas as pd import pyproj def vbar(vmodel, event_depth, station_elevation): """ Calculates the average velocity between source and receiver for a given velocity model. Only need the difference in the vertical axis as sines of angles will cancel. Par...
figures/figure6/functions/main.py
import pathlib import numpy as np import pandas as pd import pyproj def vbar(vmodel, event_depth, station_elevation): """ Calculates the average velocity between source and receiver for a given velocity model. Only need the difference in the vertical axis as sines of angles will cancel. Par...
0.915938
0.754327
import math import time import context import o80 import o80_pam import pam_mujoco mujoco_id = "balls" # only accepted number of balls ! # nb_balls = 3 # nb_balls = 10 nb_balls = 20 ## Boost error ! shared memory size issue ? # nb_balls = 50 # nb_balls = 100 # creating ball items balls = pam_mujoco.MujocoItems("extr...
balls/balls.py
import math import time import context import o80 import o80_pam import pam_mujoco mujoco_id = "balls" # only accepted number of balls ! # nb_balls = 3 # nb_balls = 10 nb_balls = 20 ## Boost error ! shared memory size issue ? # nb_balls = 50 # nb_balls = 100 # creating ball items balls = pam_mujoco.MujocoItems("extr...
0.416085
0.219494
# pylint: disable=invalid-name # Method names comply with OSID specification. # pylint: disable=no-init # Abstract classes do not define __init__. # pylint: disable=too-few-public-methods # Some interfaces are specified as 'markers' and include no methods. # pylint: disable=too-many-public-methods # Num...
dlkit/abstract_osid/calendaring/sessions.py
# pylint: disable=invalid-name # Method names comply with OSID specification. # pylint: disable=no-init # Abstract classes do not define __init__. # pylint: disable=too-few-public-methods # Some interfaces are specified as 'markers' and include no methods. # pylint: disable=too-many-public-methods # Num...
0.758689
0.234834
import logging from typing import Callable, Dict, List import pytest from eth_tester.exceptions import TransactionFailed from eth_typing import HexAddress from web3 import Web3 from web3.contract import Contract from raiden_contracts.contract_manager import ContractManager from raiden_contracts.tests.utils.constants ...
raiden_contracts/tests/fixtures/contracts.py
import logging from typing import Callable, Dict, List import pytest from eth_tester.exceptions import TransactionFailed from eth_typing import HexAddress from web3 import Web3 from web3.contract import Contract from raiden_contracts.contract_manager import ContractManager from raiden_contracts.tests.utils.constants ...
0.827306
0.188941
from googletrans import Translator from openpyxl import Workbook from openpyxl import load_workbook from helper.db_helper import DBHelper from json import JSONDecodeError from random import randint import time def extractYandeTags(): wb = Workbook() sheet = wb.get_active_sheet() sheet.append(('数量', '标签'))...
analysis.py
from googletrans import Translator from openpyxl import Workbook from openpyxl import load_workbook from helper.db_helper import DBHelper from json import JSONDecodeError from random import randint import time def extractYandeTags(): wb = Workbook() sheet = wb.get_active_sheet() sheet.append(('数量', '标签'))...
0.36659
0.139631
ARTEMIS_EMOTIONS = ['amusement', 'awe', 'contentment', 'excitement', 'anger', 'disgust', 'fear', 'sadness', 'something else'] EMOTION_TO_IDX = {e: i for i, e in enumerate(ARTEMIS_EMOTIONS)} IDX_TO_EMOTION = {EMOTION_TO_IDX[e]: e for e in EMOTION_TO_IDX} POS_NEG_ELSE = {'amusement': 0, 'awe': 0...
artemis/emotions.py
ARTEMIS_EMOTIONS = ['amusement', 'awe', 'contentment', 'excitement', 'anger', 'disgust', 'fear', 'sadness', 'something else'] EMOTION_TO_IDX = {e: i for i, e in enumerate(ARTEMIS_EMOTIONS)} IDX_TO_EMOTION = {EMOTION_TO_IDX[e]: e for e in EMOTION_TO_IDX} POS_NEG_ELSE = {'amusement': 0, 'awe': 0...
0.52683
0.303184
import pandas as pd import numpy as np START_PULL_UPS_UPPER_ANGLE_THRESHOLD = 40 END_PULL_UPS_UPPER_ANGLE_THRESHOLD = 130 TIME_FRAME_LIST = 20 reps_position = [] count_reps = 0 in_reps = 0 precedent_pos = 0 df_reps = pd.DataFrame(columns=['x_Nose','y_Nose','x_Neck','y_Neck','x_RShoulder','y_RShoulder','x_RElbow', 'y...
pull_ups_reps_counter.py
import pandas as pd import numpy as np START_PULL_UPS_UPPER_ANGLE_THRESHOLD = 40 END_PULL_UPS_UPPER_ANGLE_THRESHOLD = 130 TIME_FRAME_LIST = 20 reps_position = [] count_reps = 0 in_reps = 0 precedent_pos = 0 df_reps = pd.DataFrame(columns=['x_Nose','y_Nose','x_Neck','y_Neck','x_RShoulder','y_RShoulder','x_RElbow', 'y...
0.14731
0.121139
import logging import json import base64 from django.core.paginator import Paginator # Create your views here. from rest_framework import viewsets, status from rest_framework.decorators import action, detail_route from rest_framework.generics import get_object_or_404 from rest_framework.response import Response from d...
core/posts/views.py
import logging import json import base64 from django.core.paginator import Paginator # Create your views here. from rest_framework import viewsets, status from rest_framework.decorators import action, detail_route from rest_framework.generics import get_object_or_404 from rest_framework.response import Response from d...
0.228845
0.092074
import h5py import torch import numpy as np import pytorch_lightning as pl from torch.utils.data import TensorDataset, DataLoader def mask_data(data, bandwidth, rng): nan_mask = np.full(data.shape, np.nan) for i, sample in enumerate(data): for j, timestep in enumerate(sample): neuron_ixs =...
sbtt-demo/data.py
import h5py import torch import numpy as np import pytorch_lightning as pl from torch.utils.data import TensorDataset, DataLoader def mask_data(data, bandwidth, rng): nan_mask = np.full(data.shape, np.nan) for i, sample in enumerate(data): for j, timestep in enumerate(sample): neuron_ixs =...
0.84672
0.62758
from .utils import read_src_and_trg_files, read_tokenized_src_file, get_node_edge import random class Retriever(): def __init__(self, opt, word2idx, tag='train'): self.opt = opt self.ref_docs = read_src_and_trg_files(opt.ref_doc_path, opt.ref_kp_path, max_src_len=opt.max_src_len) if opt.de...
retrievers/retriever.py
from .utils import read_src_and_trg_files, read_tokenized_src_file, get_node_edge import random class Retriever(): def __init__(self, opt, word2idx, tag='train'): self.opt = opt self.ref_docs = read_src_and_trg_files(opt.ref_doc_path, opt.ref_kp_path, max_src_len=opt.max_src_len) if opt.de...
0.267504
0.153771
import copy import torch from mmcv.runner import obj_from_dict from mmgen.models import GANLoss, L1Loss, build_model from mmgen.models.architectures.pix2pix import (PatchDiscriminator, UnetGenerator) def test_pix2pix(): # model settings model_cfg = dict( ...
tests/test_models/test_pix2pix.py
import copy import torch from mmcv.runner import obj_from_dict from mmgen.models import GANLoss, L1Loss, build_model from mmgen.models.architectures.pix2pix import (PatchDiscriminator, UnetGenerator) def test_pix2pix(): # model settings model_cfg = dict( ...
0.831793
0.367923
import json import os import logging # Get the current logger object logger = logging.getLogger(__name__) class AppConfig(): """ This class holdes the application configuration parameters :param gpsd_ip_address: The GPSD server IP address/hostname (default: '127.0.0.1') :param gp...
config/config.py
import json import os import logging # Get the current logger object logger = logging.getLogger(__name__) class AppConfig(): """ This class holdes the application configuration parameters :param gpsd_ip_address: The GPSD server IP address/hostname (default: '127.0.0.1') :param gp...
0.664214
0.174147
from typing import Any """ Class to encode and decode the input string """ class HuffmanCoding: def recur(self, node, vi, val=''): """ Recur to add nodes with huffman codes """ new_v = val + str(node.hufcode) if(node.left): self.recur(node.left, vi, new_v) if (node....
HuffmanCoding.py
from typing import Any """ Class to encode and decode the input string """ class HuffmanCoding: def recur(self, node, vi, val=''): """ Recur to add nodes with huffman codes """ new_v = val + str(node.hufcode) if(node.left): self.recur(node.left, vi, new_v) if (node....
0.819785
0.477006
import os from sqlalchemy import create_engine from sqlalchemy.engine import Engine from sqlalchemy.orm import sessionmaker, scoped_session import sqlparse from robot.utils import ConnectionCache from robot.api import logger from .base import HybridCore from .base import keyword from .version import VERSION os.envir...
src/DatabaseLib/library.py
import os from sqlalchemy import create_engine from sqlalchemy.engine import Engine from sqlalchemy.orm import sessionmaker, scoped_session import sqlparse from robot.utils import ConnectionCache from robot.api import logger from .base import HybridCore from .base import keyword from .version import VERSION os.envir...
0.624408
0.097691
from rl_threat_hunting import result_evaluation from rl_threat_hunting.utils import safely_traverse_dict from rl_threat_hunting.constants import Classification from rl_threat_hunting.constants import HuntingStatus from rl_threat_hunting.constants import HuntingCategory from rl_threat_hunting.mwp_metadata_adapter import...
rl_threat_hunting/cloud/cloud_reputation.py
from rl_threat_hunting import result_evaluation from rl_threat_hunting.utils import safely_traverse_dict from rl_threat_hunting.constants import Classification from rl_threat_hunting.constants import HuntingStatus from rl_threat_hunting.constants import HuntingCategory from rl_threat_hunting.mwp_metadata_adapter import...
0.41941
0.185966
import importlib import pytest module = importlib.import_module("19_an_elephant_named_joseph") josephus = module.josephus round_game = module.round_game @pytest.mark.parametrize( "elves, winner", [ (1, 1), (2, 1), (3, 3), (4, 1), (5, 3), (6, 5), (7, 7)...
2016/19_an_elephant_named_joseph_test.py
import importlib import pytest module = importlib.import_module("19_an_elephant_named_joseph") josephus = module.josephus round_game = module.round_game @pytest.mark.parametrize( "elves, winner", [ (1, 1), (2, 1), (3, 3), (4, 1), (5, 3), (6, 5), (7, 7)...
0.358016
0.523725
from bs4 import BeautifulSoup import requests import requests.exceptions from urllib.parse import urlsplit from collections import deque import re import datetime import csv # user is prompted for a queue of urls to be crawled user_input_yes_no = "y" user_urls = deque([]) while user_input_yes_no == "y": user_input...
extract-email-from-url.py
from bs4 import BeautifulSoup import requests import requests.exceptions from urllib.parse import urlsplit from collections import deque import re import datetime import csv # user is prompted for a queue of urls to be crawled user_input_yes_no = "y" user_urls = deque([]) while user_input_yes_no == "y": user_input...
0.195825
0.084531
from math import prod from typing import List, Tuple import advent_of_code.utils.globals def hex_to_bin(hex: str) -> str: binary = "" for d in hex: binary += format(int(d, 16), "04b") return binary def compute_bits(binary_str: str) -> Tuple[int, str]: # Account for header version = int(...
src/advent_of_code/utils/bits.py
from math import prod from typing import List, Tuple import advent_of_code.utils.globals def hex_to_bin(hex: str) -> str: binary = "" for d in hex: binary += format(int(d, 16), "04b") return binary def compute_bits(binary_str: str) -> Tuple[int, str]: # Account for header version = int(...
0.664867
0.396185
from typing import Type import warnings import fitz import pytest import pdfcheck.core from pdfcheck.helper import inches_2_points @pytest.fixture(scope="function") def paper_size_coordinates() -> Type[pdfcheck.core.BoundingBox]: """ This fixture provides the paper size as bounding box (tuple of four values...
.github/actions/pdfcheck/pdfcheck/tests/margins.py
from typing import Type import warnings import fitz import pytest import pdfcheck.core from pdfcheck.helper import inches_2_points @pytest.fixture(scope="function") def paper_size_coordinates() -> Type[pdfcheck.core.BoundingBox]: """ This fixture provides the paper size as bounding box (tuple of four values...
0.89093
0.575916
import torch import torch.nn as nn from module.weight_init import * class DenseNet_conv(nn.Module): ''' doc ''' def __init__(self, in_c, L=5, k=12, bn=False): ''' dense block :param in_c: input channel number :param L: layer number in dense block :param k: outp...
module/densenet.py
import torch import torch.nn as nn from module.weight_init import * class DenseNet_conv(nn.Module): ''' doc ''' def __init__(self, in_c, L=5, k=12, bn=False): ''' dense block :param in_c: input channel number :param L: layer number in dense block :param k: outp...
0.894355
0.363082
import os import json import urllib3 # Get mailgun secret from Lambda environment variables mg_api = os.environ["MG_API"] # Get hCaptcha secret from Lambda environment variables h_captcha = os.environ["HC_API"] bcc_emails = os.environ["EMAILS"] # Use this (public) sitekey for hCaptcha hcKey = "8398bfb2-83c8-45fe-b3c8...
lambda.py
import os import json import urllib3 # Get mailgun secret from Lambda environment variables mg_api = os.environ["MG_API"] # Get hCaptcha secret from Lambda environment variables h_captcha = os.environ["HC_API"] bcc_emails = os.environ["EMAILS"] # Use this (public) sitekey for hCaptcha hcKey = "8398bfb2-83c8-45fe-b3c8...
0.362292
0.096323
import unittest from typing import cast, Generic, Optional, List, TypeVar from crosshair.condition_parser import * class Foo: """A thingy. Examples:: >>> 'blah' 'blah' inv:: self.x >= 0 inv: # a blank line with no indent is ok: self.y >= 0 notasection: ...
crosshair/condition_parser_test.py
import unittest from typing import cast, Generic, Optional, List, TypeVar from crosshair.condition_parser import * class Foo: """A thingy. Examples:: >>> 'blah' 'blah' inv:: self.x >= 0 inv: # a blank line with no indent is ok: self.y >= 0 notasection: ...
0.781497
0.549701
# ====================================================================================================================== # Imports # ====================================================================================================================== from python_practice.looping import * class TestLoopingChallengeO...
tests/test_looping.py
# ====================================================================================================================== # Imports # ====================================================================================================================== from python_practice.looping import * class TestLoopingChallengeO...
0.813905
0.391231
import importlib import pkgutil from . import formatters class AssetFormatter(): _by_name = {} _by_extension = {} def __init__(self, components=None, extensions=None): self.components = components if components else (None, ) self.extensions = extensions def __call__(self, fragment_f...
src/ttblit/asset/formatter.py
import importlib import pkgutil from . import formatters class AssetFormatter(): _by_name = {} _by_extension = {} def __init__(self, components=None, extensions=None): self.components = components if components else (None, ) self.extensions = extensions def __call__(self, fragment_f...
0.65368
0.137041
from celest.encounter.groundposition import GroundPosition from celest.satellite.coordinate import Coordinate from celest.satellite.time import Time from unittest import TestCase import numpy as np import unittest class TestCoordinate(TestCase): def setUp(self): """Test fixure for test method execution."...
tests/test_satellite/test_coordinate.py
from celest.encounter.groundposition import GroundPosition from celest.satellite.coordinate import Coordinate from celest.satellite.time import Time from unittest import TestCase import numpy as np import unittest class TestCoordinate(TestCase): def setUp(self): """Test fixure for test method execution."...
0.904321
0.760562
import unittest import numpy as np from ..potential_functions import (two_gaussian_potential, two_gaussian_potential_bc) coords = np.array([0.5, 0.5]) vnew = 0.5 f2 = 1.0 class TestTwoGaussianPotentialFunctions(unittest.TestCase): """Tests for the various potential functions"...
LimPy/tests/test_two_gaussian_potential_functions.py
import unittest import numpy as np from ..potential_functions import (two_gaussian_potential, two_gaussian_potential_bc) coords = np.array([0.5, 0.5]) vnew = 0.5 f2 = 1.0 class TestTwoGaussianPotentialFunctions(unittest.TestCase): """Tests for the various potential functions"...
0.820649
0.640706
from unittest.mock import MagicMock, PropertyMock import pytest import abstracts from aio.core import subprocess @abstracts.implementer(subprocess.ISubprocessHandler) class DummySubprocessHandlerInterface: @property def encoding(self): return subprocess.ISubprocessHandler.encoding.fget(self) ...
aio.core/tests/test_subprocess_handler.py
from unittest.mock import MagicMock, PropertyMock import pytest import abstracts from aio.core import subprocess @abstracts.implementer(subprocess.ISubprocessHandler) class DummySubprocessHandlerInterface: @property def encoding(self): return subprocess.ISubprocessHandler.encoding.fget(self) ...
0.705988
0.282349
import mock import neutron_fwaas.services.firewall.drivers.mcafee as mcafee import neutron_fwaas.services.firewall.drivers.mcafee.ngfw_fwaas as fwaas from neutron.tests import base FAKE_FIREWALL_ID = 'firewall_id' FAKE_POLICY_ID = 'policy_id' FAKE_TENANT_ID = 'tenant_id' FAKE_ROUTER_ID = 'router_id' FAKE_FW_NAME = ...
neutron_fwaas/tests/unit/services/firewall/drivers/mcafee/test_ngfw_fwaas.py
import mock import neutron_fwaas.services.firewall.drivers.mcafee as mcafee import neutron_fwaas.services.firewall.drivers.mcafee.ngfw_fwaas as fwaas from neutron.tests import base FAKE_FIREWALL_ID = 'firewall_id' FAKE_POLICY_ID = 'policy_id' FAKE_TENANT_ID = 'tenant_id' FAKE_ROUTER_ID = 'router_id' FAKE_FW_NAME = ...
0.40204
0.160924
import numpy as np # axis = 'x' / 'y' : 上下翻转/水平翻转 def flip(data, axis='x'): if isinstance(data, np.ndarray) == False: print("不支持非np.ndarray类型") return data if data.ndim != 3 and data.ndim != 4: print("不支持2,3,4之外的维度") return data if data.ndim == 3: ndata = np.expand...
GlowKeras/data_augmentation.py
import numpy as np # axis = 'x' / 'y' : 上下翻转/水平翻转 def flip(data, axis='x'): if isinstance(data, np.ndarray) == False: print("不支持非np.ndarray类型") return data if data.ndim != 3 and data.ndim != 4: print("不支持2,3,4之外的维度") return data if data.ndim == 3: ndata = np.expand...
0.211417
0.543772
# Copyright 2016 University of Chicago # Licensed under the APL 2.0 license import argparse import os import sys import psycopg2 import fsurfer import fsurfer.helpers import fsurfer.log VERSION = fsurfer.__version__ def remove_input_file(input_file): """ Remove input file :param input_file: path to i...
python/purge_inputs.py
# Copyright 2016 University of Chicago # Licensed under the APL 2.0 license import argparse import os import sys import psycopg2 import fsurfer import fsurfer.helpers import fsurfer.log VERSION = fsurfer.__version__ def remove_input_file(input_file): """ Remove input file :param input_file: path to i...
0.420957
0.118691
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pprint from typing import Any, Tuple, Text, Optional, Mapping from absl import app from absl import flags from absl import logging import tensorflow as tf from official.modeling.hyperparams import par...
tools/train_tf.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pprint from typing import Any, Tuple, Text, Optional, Mapping from absl import app from absl import flags from absl import logging import tensorflow as tf from official.modeling.hyperparams import par...
0.736021
0.154951
from abc import ABC from abc import abstractmethod from reader.unified_reader import InputReader from helper.enum_definitions import InputFormatEnum class InputParser(ABC): @staticmethod def factory(ipReader: InputReader, ipFormat: InputFormatEnum, ipStructure: str = None): inputParser ...
prodapt_solutions/parser/unified_parser.py
from abc import ABC from abc import abstractmethod from reader.unified_reader import InputReader from helper.enum_definitions import InputFormatEnum class InputParser(ABC): @staticmethod def factory(ipReader: InputReader, ipFormat: InputFormatEnum, ipStructure: str = None): inputParser ...
0.85022
0.343727
# pylint: disable=missing-docstring,no-self-use import contextlib import pathlib import unittest from typing import List # pylint: disable=unused-import import paramiko import temppathlib import spur.ssh import spurplus import spurplus.sftp import tests.common class TestConnectionFailure(unittest.TestCase): "...
tests/test_sftp_live.py
# pylint: disable=missing-docstring,no-self-use import contextlib import pathlib import unittest from typing import List # pylint: disable=unused-import import paramiko import temppathlib import spur.ssh import spurplus import spurplus.sftp import tests.common class TestConnectionFailure(unittest.TestCase): "...
0.50952
0.276318
import json import boto3 import common from botocore.exceptions import ClientError from s3 import * def lambda_handler(event, context): global aws_access_key_id, aws_secret_access_key, aws_session_token, CustAccID, Region common_policies = ["S3bucketNoPublicAAUFull", "S3bucketNoPublicAAURead", "S3bucketNoPubli...
remediation-functions/s3/s3_suborchestrator.py
import json import boto3 import common from botocore.exceptions import ClientError from s3 import * def lambda_handler(event, context): global aws_access_key_id, aws_secret_access_key, aws_session_token, CustAccID, Region common_policies = ["S3bucketNoPublicAAUFull", "S3bucketNoPublicAAURead", "S3bucketNoPubli...
0.324663
0.077938
from bitmovin import S3Input, S3Output, Encoding, StreamInput, AACCodecConfiguration, Stream, Bitmovin, CloudRegion, \ EncoderVersion, SelectionMode, H264CodecConfiguration, H264Profile, FMP4Muxing, EncodingOutput, \ StartEncodingRequest, MuxingStream, DashManifest, Period, VideoAdaptationSet, FMP4Representatio...
examples/encoding/create_per_title_encoding.py
from bitmovin import S3Input, S3Output, Encoding, StreamInput, AACCodecConfiguration, Stream, Bitmovin, CloudRegion, \ EncoderVersion, SelectionMode, H264CodecConfiguration, H264Profile, FMP4Muxing, EncodingOutput, \ StartEncodingRequest, MuxingStream, DashManifest, Period, VideoAdaptationSet, FMP4Representatio...
0.348756
0.075961
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('inventory', '0001_initial'), ] operations = [ migrations.AlterField( model_name='group', name='city', field=models.CharField(blank=True, max_length=16, ...
inventory/migrations/0002_alter_group_city_alter_group_country_and_more.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('inventory', '0001_initial'), ] operations = [ migrations.AlterField( model_name='group', name='city', field=models.CharField(blank=True, max_length=16, ...
0.665628
0.169372
import sys import os from hashlib import md5, sha1 from zlib import crc32 import os import time import shutil def get_filename_modifyTime(filename): time.ctime(os.stat(filename).st_mtime) time.ctime(os.stat(filename).st_ctime) time.localtime(os.stat(filename).st_mtime) ModifiedTime=time.localtime...
AdvancedRelease/AdvancedRelease.py
import sys import os from hashlib import md5, sha1 from zlib import crc32 import os import time import shutil def get_filename_modifyTime(filename): time.ctime(os.stat(filename).st_mtime) time.ctime(os.stat(filename).st_ctime) time.localtime(os.stat(filename).st_mtime) ModifiedTime=time.localtime...
0.146942
0.137619
from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2") buf.write(u"\63\u018b\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6") buf.write(u"\4\7...
sympy/parsing/autolev/_antlr/autolevlexer.py
from __future__ import print_function from antlr4 import * from io import StringIO import sys def serializedATN(): with StringIO() as buf: buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2") buf.write(u"\63\u018b\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6") buf.write(u"\4\7...
0.223038
0.285201
import datetime import numpy as np from ..base import Property from ..models.measurement import MeasurementModel from ..models.transition import TransitionModel from ..reader import GroundTruthReader from ..types.detection import TrueDetection, Clutter from ..types.groundtruth import GroundTruthPath, GroundTruthState...
stonesoup/simulator/simple.py
import datetime import numpy as np from ..base import Property from ..models.measurement import MeasurementModel from ..models.transition import TransitionModel from ..reader import GroundTruthReader from ..types.detection import TrueDetection, Clutter from ..types.groundtruth import GroundTruthPath, GroundTruthState...
0.902599
0.473962
"""Perform integration tests for `orion.algo.nomad`.""" import os import numpy import orion.core.cli import pytest from orion.algo.space import Integer, Real, Space from orion.client import create_experiment from orion.core.utils.tests import OrionState from orion.core.worker.primary_algo import PrimaryAlgo # pylint...
tests/integration_test.py
"""Perform integration tests for `orion.algo.nomad`.""" import os import numpy import orion.core.cli import pytest from orion.algo.space import Integer, Real, Space from orion.client import create_experiment from orion.core.utils.tests import OrionState from orion.core.worker.primary_algo import PrimaryAlgo # pylint...
0.838614
0.463626
import paramiko import logging import time import select import socket import traceback from steelscript.cmdline import sshprocess from steelscript.cmdline import exceptions class Shell(object): """ Class for running shell command remotely and statelessly. No persistent channel is maintained, so chang...
steelscript/cmdline/shell.py
import paramiko import logging import time import select import socket import traceback from steelscript.cmdline import sshprocess from steelscript.cmdline import exceptions class Shell(object): """ Class for running shell command remotely and statelessly. No persistent channel is maintained, so chang...
0.533884
0.212028
planar_graph_evals = dict() planar_graph_evals[100] = { 'y': 1.00000000000000, 'x': 0.03654477051892902919200923409811523110400, 'x*G_1_dx(x,y)': 0.037992196457707622946696582954948631589741128071633, 'G_1(x,y)': 0.037248430505369042824973498725034635645401138702917, 'G_1_dx(x,y)': 1.039606923732857132721102449652...
planar_graph_sampler/evaluations_planar_graph.py
planar_graph_evals = dict() planar_graph_evals[100] = { 'y': 1.00000000000000, 'x': 0.03654477051892902919200923409811523110400, 'x*G_1_dx(x,y)': 0.037992196457707622946696582954948631589741128071633, 'G_1(x,y)': 0.037248430505369042824973498725034635645401138702917, 'G_1_dx(x,y)': 1.039606923732857132721102449652...
0.17849
0.340814
from __future__ import unicode_literals import os import unittest from webtest import TestApp from pyramid.testing import DummyRequest from billy import main from billy.db.tables import DeclarativeBase from billy.models import setup_database from billy.models.model_factory import ModelFactory from billy.tests.fixture...
billy/tests/functional/helper.py
from __future__ import unicode_literals import os import unittest from webtest import TestApp from pyramid.testing import DummyRequest from billy import main from billy.db.tables import DeclarativeBase from billy.models import setup_database from billy.models.model_factory import ModelFactory from billy.tests.fixture...
0.522446
0.119024
from flask import Flask, abort, jsonify, make_response, request, Blueprint from app.api.version1.questions.models import Questions, questions quest = Blueprint('questions', __name__, url_prefix='/questions') @quest.route('/', methods=['GET']) def fetch_all_qustions(): if len(questions) == 0: return make_...
app/api/version1/questions/views.py
from flask import Flask, abort, jsonify, make_response, request, Blueprint from app.api.version1.questions.models import Questions, questions quest = Blueprint('questions', __name__, url_prefix='/questions') @quest.route('/', methods=['GET']) def fetch_all_qustions(): if len(questions) == 0: return make_...
0.350421
0.184676
from __future__ import unicode_literals from __future__ import print_function import re from mutagen import id3 # pylint: disable=R0903 class MockResponse: """Mock requests.Response class for tests""" def __init__(self, code, text): self.status_code = code self.text = text class FakeFile(di...
test/fakers.py
from __future__ import unicode_literals from __future__ import print_function import re from mutagen import id3 # pylint: disable=R0903 class MockResponse: """Mock requests.Response class for tests""" def __init__(self, code, text): self.status_code = code self.text = text class FakeFile(di...
0.466359
0.07024
from neptune.generated.swagger_client.models import ParameterTypeEnum as PTE from neptune.internal.cli import MLFramework from neptune.internal.common.values import Tag UNKNOWN_ML_FRAMEWORK = u"Invalid ml framework '{}'. Must be one of {}." _PARAM_TYPE_MISMATCH = ("Invalid value '{value}' for parameter '{name}'. " ...
neptune/internal/common/config/validation_rules.py
from neptune.generated.swagger_client.models import ParameterTypeEnum as PTE from neptune.internal.cli import MLFramework from neptune.internal.common.values import Tag UNKNOWN_ML_FRAMEWORK = u"Invalid ml framework '{}'. Must be one of {}." _PARAM_TYPE_MISMATCH = ("Invalid value '{value}' for parameter '{name}'. " ...
0.605682
0.122104