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 __future__ import print_function import argparse import collections import copy import io import json import logging import os import sys DEFAULT_LOG_LEVEL = logging.DEBUG LOG_LEVELS = collections.defaultdict( lambda: DEFAULT_LOG_LEVEL, { "critical": logging.CRITICAL, "error": logging.ERR...
modules/policy_documents/policy_document_handler.py
from __future__ import print_function import argparse import collections import copy import io import json import logging import os import sys DEFAULT_LOG_LEVEL = logging.DEBUG LOG_LEVELS = collections.defaultdict( lambda: DEFAULT_LOG_LEVEL, { "critical": logging.CRITICAL, "error": logging.ERR...
0.371707
0.077378
"""Compute the RNA features.""" from __future__ import print_function import argparse import sys from eden.converter.fasta import fasta_to_sequence from eden.converter.rna.rnaplfold import rnaplfold_to_eden from eden.graph import Vectorizer from eden.util import vectorize as eden_vectorize import pandas as pd from...
rnacommender/rnafeatures.py
"""Compute the RNA features.""" from __future__ import print_function import argparse import sys from eden.converter.fasta import fasta_to_sequence from eden.converter.rna.rnaplfold import rnaplfold_to_eden from eden.graph import Vectorizer from eden.util import vectorize as eden_vectorize import pandas as pd from...
0.803714
0.444565
from files.launcher import Launcher Launcher.set('ulauncher') import os from files.service import FilesService from files.icon import IconRegistry from ulauncher.api.client.Extension import Extension from ulauncher.api.client.EventListener import EventListener from ulauncher.api.shared.event import KeywordQueryEvent, P...
main.py
from files.launcher import Launcher Launcher.set('ulauncher') import os from files.service import FilesService from files.icon import IconRegistry from ulauncher.api.client.Extension import Extension from ulauncher.api.client.EventListener import EventListener from ulauncher.api.shared.event import KeywordQueryEvent, P...
0.267217
0.039379
import unittest import sys import rosunit from mock import patch from parameterized import parameterized, param from fiware_ros_bridge.logging import getLogger class TestGetLogger(unittest.TestCase): @parameterized.expand([ param(logm='debugf', rosm='logdebug'), param(logm='infof', rosm='logi...
tests/test_logging.py
import unittest import sys import rosunit from mock import patch from parameterized import parameterized, param from fiware_ros_bridge.logging import getLogger class TestGetLogger(unittest.TestCase): @parameterized.expand([ param(logm='debugf', rosm='logdebug'), param(logm='infof', rosm='logi...
0.310172
0.170819
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from collections import Counter import sys import pickle # Parameters params = { 'N_sub': 300, 'B_tags': 5, 'reg_C': 10.0 } # Set random seed for reproducible output np.random.seed(137) # Load pickled data...
analyze.py
import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import LogisticRegression from collections import Counter import sys import pickle # Parameters params = { 'N_sub': 300, 'B_tags': 5, 'reg_C': 10.0 } # Set random seed for reproducible output np.random.seed(137) # Load pickled data...
0.599954
0.541166
from ast import literal_eval as make_tuple from tqdm import tqdm from utils.steiner_tree_te import * import networkx as nx import itertools import copy def relabel_nodes_str_to_tuple(G): node_list = list(G.nodes) relable_node_list = [] for node in node_list: relable_node_list.append(make_tuple(node...
utils/networkx_operations.py
from ast import literal_eval as make_tuple from tqdm import tqdm from utils.steiner_tree_te import * import networkx as nx import itertools import copy def relabel_nodes_str_to_tuple(G): node_list = list(G.nodes) relable_node_list = [] for node in node_list: relable_node_list.append(make_tuple(node...
0.487307
0.467271
import itertools import numpy as np import pandas as pd import tensorflow as tf MODEL_DIR = "model_checkpoints" def pandas_input_fn( df, y_col=None, batch_size=128, num_epochs=1, shuffle=False, seed=None ): """Pandas input function for TensorFlow high-level API Estimator. This function returns tf.data....
reco_utils/common/tf_utils.py
import itertools import numpy as np import pandas as pd import tensorflow as tf MODEL_DIR = "model_checkpoints" def pandas_input_fn( df, y_col=None, batch_size=128, num_epochs=1, shuffle=False, seed=None ): """Pandas input function for TensorFlow high-level API Estimator. This function returns tf.data....
0.894709
0.470372
# Copyright (c) 2011 <NAME> # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license.php import sys import codecs from optparse import OptionParser from screenplain.parsers import fountain output_formats = ( 'fdx', 'html', 'pdf' ) usage = """Usage: %prog [options] [input-file [output-...
screenplain/main.py
# Copyright (c) 2011 <NAME> # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license.php import sys import codecs from optparse import OptionParser from screenplain.parsers import fountain output_formats = ( 'fdx', 'html', 'pdf' ) usage = """Usage: %prog [options] [input-file [output-...
0.591487
0.250683
import unittest from pypika import ( Array, Bracket, Dialects, PostgreSQLQuery, Query, Tables, Tuple, ) class TupleTests(unittest.TestCase): table_abc, table_efg = Tables('abc', 'efg') def test_tuple_equality_tuple_on_both(self): q = Query.from_(self.table_abc) \ ...
pypika/tests/test_tuples.py
import unittest from pypika import ( Array, Bracket, Dialects, PostgreSQLQuery, Query, Tables, Tuple, ) class TupleTests(unittest.TestCase): table_abc, table_efg = Tables('abc', 'efg') def test_tuple_equality_tuple_on_both(self): q = Query.from_(self.table_abc) \ ...
0.658966
0.471041
from collections import defaultdict class graph: def __init__(self): self.nodes=set() self.edges=defaultdict(list) def add_node(self,value): self.nodes.add(value) def add_edge(self,from_node, to_node ): self.edges[from_node].append(to_node) def dijkstra(initial,graph): ...
project_euler/problem_83/sol1.py
from collections import defaultdict class graph: def __init__(self): self.nodes=set() self.edges=defaultdict(list) def add_node(self,value): self.nodes.add(value) def add_edge(self,from_node, to_node ): self.edges[from_node].append(to_node) def dijkstra(initial,graph): ...
0.275812
0.383843
import datetime class Currency: RUB = 'RUB' USD = 'USD' EUR = 'EUR' class Operation: class Type: PAY_IN = 'PayIn' PAY_OUT = 'PayOut' BUY = 'Buy' BUY_CARD = 'BuyCard' # direct buy from the debit card SELL = 'Sell' DIVIDEND = 'Dividend' SERVICE_...
investments/models.py
import datetime class Currency: RUB = 'RUB' USD = 'USD' EUR = 'EUR' class Operation: class Type: PAY_IN = 'PayIn' PAY_OUT = 'PayOut' BUY = 'Buy' BUY_CARD = 'BuyCard' # direct buy from the debit card SELL = 'Sell' DIVIDEND = 'Dividend' SERVICE_...
0.522689
0.151435
import re from functools import wraps from twisted.web.resource import Resource, NoResource class _FakeResource(Resource): _result = '' isLeaf = True def __init__(self, result): Resource.__init__(self) self._result = result def render(self, request): return self._result def...
src/txrestserver/txrestapi/resource.py
import re from functools import wraps from twisted.web.resource import Resource, NoResource class _FakeResource(Resource): _result = '' isLeaf = True def __init__(self, result): Resource.__init__(self) self._result = result def render(self, request): return self._result def...
0.583797
0.065485
import pulumi import pulumi.runtime class Connection(pulumi.CustomResource): """ Provides a Connection of Direct Connect. """ def __init__(__self__, __name__, __opts__=None, bandwidth=None, location=None, name=None, tags=None): """Create a Connection resource with the given unique name, props,...
sdk/python/pulumi_aws/directconnect/connection.py
import pulumi import pulumi.runtime class Connection(pulumi.CustomResource): """ Provides a Connection of Direct Connect. """ def __init__(__self__, __name__, __opts__=None, bandwidth=None, location=None, name=None, tags=None): """Create a Connection resource with the given unique name, props,...
0.754463
0.052668
from minibench import Benchmark from faker import Faker from flask import Flask from flask_restplus import fields, Api, Resource from flask_restplus.swagger import Swagger fake = Faker() api = Api() person = api.model('Person', { 'name': fields.String, 'age': fields.Integer }) family = api.model('Family', ...
benchmarks/swagger.bench.py
from minibench import Benchmark from faker import Faker from flask import Flask from flask_restplus import fields, Api, Resource from flask_restplus.swagger import Swagger fake = Faker() api = Api() person = api.model('Person', { 'name': fields.String, 'age': fields.Integer }) family = api.model('Family', ...
0.627723
0.059949
import numpy as np import skimage import skimage.transform as trans """ Some lines borrowed from: https://www.kaggle.com/sashakorekov/end-to-end-resnet50-with-tta-lb-0-93 """ def rotate_clk_img_and_msk(img, msk): angle = np.random.choice((4, 6, 8, 10, 12, 14, 16, 18, 20)) img_o = trans.rotate(img, angle, res...
Cloud-Net-A-semantic-segmentation-CNN-for-cloud-detection/Cloud-Net/augmentation.py
import numpy as np import skimage import skimage.transform as trans """ Some lines borrowed from: https://www.kaggle.com/sashakorekov/end-to-end-resnet50-with-tta-lb-0-93 """ def rotate_clk_img_and_msk(img, msk): angle = np.random.choice((4, 6, 8, 10, 12, 14, 16, 18, 20)) img_o = trans.rotate(img, angle, res...
0.599251
0.453443
__author__ = '<NAME> <<EMAIL>>, <NAME>' import functools import sys import threading import traceback from gevent import event as gevent_event from pyon.core import bootstrap, MSG_HEADER_ACTOR from pyon.core.bootstrap import CFG from pyon.core.exception import BadRequest, IonException, StreamException from pyon.datas...
src/pyon/ion/event.py
__author__ = '<NAME> <<EMAIL>>, <NAME>' import functools import sys import threading import traceback from gevent import event as gevent_event from pyon.core import bootstrap, MSG_HEADER_ACTOR from pyon.core.bootstrap import CFG from pyon.core.exception import BadRequest, IonException, StreamException from pyon.datas...
0.450118
0.12363
from pyids.algorithms.optimizers.rs_optimizer import RSOptimizer from ...data_structures.ids_ruleset import IDSRuleSet import math import numpy as np import logging class SLSOptimizer: def __init__(self, objective_function, objective_func_params, optimizer_args=dict(), random_seed=None): self.delta = 0.3...
pyids/algorithms/optimizers/sls_optimizer.py
from pyids.algorithms.optimizers.rs_optimizer import RSOptimizer from ...data_structures.ids_ruleset import IDSRuleSet import math import numpy as np import logging class SLSOptimizer: def __init__(self, objective_function, objective_func_params, optimizer_args=dict(), random_seed=None): self.delta = 0.3...
0.732687
0.295509
import scrapy import re import json from locations.items import GeojsonPointItem class McDonaldsEGSpider(scrapy.Spider): name = "mcdonalds_eg" item_attributes = {"brand": "McDonald's"} allowed_domains = ["www.mcdonalds.eg"] start_urls = ("http://www.mcdonalds.eg/ar/stores/page/228",) def normali...
locations/spiders/mcdonalds_eg.py
import scrapy import re import json from locations.items import GeojsonPointItem class McDonaldsEGSpider(scrapy.Spider): name = "mcdonalds_eg" item_attributes = {"brand": "McDonald's"} allowed_domains = ["www.mcdonalds.eg"] start_urls = ("http://www.mcdonalds.eg/ar/stores/page/228",) def normali...
0.336767
0.165694
import re from argparse import ArgumentParser from itertools import groupby from os import environ from sys import stderr, stdout from typing import Any, Dict, List, Match, Optional, Set, Tuple from pithy.ansi import BG, BOLD, FILL, RST, RST_BOLD, RST_TXT, TXT, gray26, rgb6, sanitize_for_console, sgr from pithy.diff ...
pithytools/bin/same_same.py
import re from argparse import ArgumentParser from itertools import groupby from os import environ from sys import stderr, stdout from typing import Any, Dict, List, Match, Optional, Set, Tuple from pithy.ansi import BG, BOLD, FILL, RST, RST_BOLD, RST_TXT, TXT, gray26, rgb6, sanitize_for_console, sgr from pithy.diff ...
0.61555
0.217379
from rebus.agent import Agent import threading import time import tornado.ioloop import tornado.web import tornado.template import rebus.agents.inject from rebus.descriptor import Descriptor @Agent.register class HTTPListener(Agent): _name_ = "httplistener" _desc_ = "Push any descriptor that gets POSTed to th...
rebus/agents/http_listener.py
from rebus.agent import Agent import threading import time import tornado.ioloop import tornado.web import tornado.template import rebus.agents.inject from rebus.descriptor import Descriptor @Agent.register class HTTPListener(Agent): _name_ = "httplistener" _desc_ = "Push any descriptor that gets POSTed to th...
0.534127
0.086903
# Legion - <NAME>, ConsenSys Diligence import argparse from legions.context import LegionContext from legions.statusbar import LegionStatusBar from nubia import PluginInterface, CompletionDataSource from nubia.internal.blackcmd import CommandBlacklist class LegionPlugin(PluginInterface): """ The PluginInte...
legions/plugin.py
# Legion - <NAME>, ConsenSys Diligence import argparse from legions.context import LegionContext from legions.statusbar import LegionStatusBar from nubia import PluginInterface, CompletionDataSource from nubia.internal.blackcmd import CommandBlacklist class LegionPlugin(PluginInterface): """ The PluginInte...
0.582254
0.229352
class chromaticity: """Store chromaticity coordinates in *x* and *y*.""" def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return repr((self.x, self.y)) class point: """Point is a 2D point, with members *x* and *y*.""" def __init__(self, x, y): self...
OpenEXR-1.2.0/build/lib.win-amd64-2.7/Imath.py
class chromaticity: """Store chromaticity coordinates in *x* and *y*.""" def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return repr((self.x, self.y)) class point: """Point is a 2D point, with members *x* and *y*.""" def __init__(self, x, y): self...
0.94837
0.431225
import os import subprocess from gen_tools import run_ftool import numpy as np def ev2dpi(infile, outfile, tstart, tstop, e0, e1, detmask): ftool = "batbinevt" arg_list = [infile, outfile, 'DPI', '0', 'uniform', str(e0)+'-'+str(e1)] arg_list += ['tstart='+str(tstart), 'tstop='+str(tstop), 'detmask='+detma...
HeasoftTools/bat_tool_funcs.py
import os import subprocess from gen_tools import run_ftool import numpy as np def ev2dpi(infile, outfile, tstart, tstop, e0, e1, detmask): ftool = "batbinevt" arg_list = [infile, outfile, 'DPI', '0', 'uniform', str(e0)+'-'+str(e1)] arg_list += ['tstart='+str(tstart), 'tstop='+str(tstop), 'detmask='+detma...
0.089244
0.161254
import math from compas.geometry._core import allclose __all__ = [ 'quaternion_norm', 'quaternion_unitize', 'quaternion_is_unit', 'quaternion_multiply', 'quaternion_canonize', 'quaternion_conjugate', ] ATOL = 1e-6 # absolute tolerance def quaternion_norm(q): """Calculates the length (...
src/compas/geometry/_core/quaternions.py
import math from compas.geometry._core import allclose __all__ = [ 'quaternion_norm', 'quaternion_unitize', 'quaternion_is_unit', 'quaternion_multiply', 'quaternion_canonize', 'quaternion_conjugate', ] ATOL = 1e-6 # absolute tolerance def quaternion_norm(q): """Calculates the length (...
0.952508
0.789356
"""Tests for cisconx acl rendering module.""" from absl.testing import absltest from unittest import mock from capirca.lib import cisconx from capirca.lib import nacaddr from capirca.lib import naming from capirca.lib import policy GOOD_HEADER = """ header { comment:: "this is a test extended acl" target:: cisco...
tests/lib/cisconx_test.py
"""Tests for cisconx acl rendering module.""" from absl.testing import absltest from unittest import mock from capirca.lib import cisconx from capirca.lib import nacaddr from capirca.lib import naming from capirca.lib import policy GOOD_HEADER = """ header { comment:: "this is a test extended acl" target:: cisco...
0.759582
0.376365
import torch.nn as nn from torch.nn import Conv2d, BatchNorm2d, Dropout2d import torch.nn.functional as nnf from ..layers import ActivationFactory as AF def _conv3x3(in_channels, out_channels, stride=1, groups=1, dilation=1, bias=False): """3x3 convolution with padding""" return nn.Conv2d( in_channel...
hyperion/torch/layer_blocks/resnet_blocks.py
import torch.nn as nn from torch.nn import Conv2d, BatchNorm2d, Dropout2d import torch.nn.functional as nnf from ..layers import ActivationFactory as AF def _conv3x3(in_channels, out_channels, stride=1, groups=1, dilation=1, bias=False): """3x3 convolution with padding""" return nn.Conv2d( in_channel...
0.953046
0.497986
import unittest import numpy as np import torch # Import torch first! from crf.py_permutohedral import PyPermutohedral try: import permuto_cpp except ImportError as e: raise (e, 'Did you import `torch` first?') from pytorch_permuto.filters import PermutoFunction from torch.autograd import gradcheck class ...
pytorch_permuto/pytorch_permuto/unit_tests/test_permuto_op.py
import unittest import numpy as np import torch # Import torch first! from crf.py_permutohedral import PyPermutohedral try: import permuto_cpp except ImportError as e: raise (e, 'Did you import `torch` first?') from pytorch_permuto.filters import PermutoFunction from torch.autograd import gradcheck class ...
0.763924
0.694374
"""Simplest FFN model, as described in https://arxiv.org/abs/1611.00421.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from .. import model from . import convstack_3d from .. import optimizer from tensorflow.python.util import ...
ffn/training/models/horovod_convstack_3d.py
"""Simplest FFN model, as described in https://arxiv.org/abs/1611.00421.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from .. import model from . import convstack_3d from .. import optimizer from tensorflow.python.util import ...
0.806205
0.433742
import os from os import path import logging import kubernetes from flask import Blueprint, jsonify, request from kubernetes.client.rest import ApiException from operator_service.config import Config from operator_service.data_store import create_sql_job, get_sql_status, get_sql_jobs, stop_sql_job, remove_sql_job fro...
operator_service/routes.py
import os from os import path import logging import kubernetes from flask import Blueprint, jsonify, request from kubernetes.client.rest import ApiException from operator_service.config import Config from operator_service.data_store import create_sql_job, get_sql_status, get_sql_jobs, stop_sql_job, remove_sql_job fro...
0.495361
0.165492
import json import time from asyncio import TimeoutError from datetime import timedelta from json.decoder import JSONDecodeError from random import choice from typing import Union import discord from discord.ext import commands, tasks from discord.ext.commands import Cog, command from lib import (FutureTime, ...
minato_namikaze/cogs/events/giveaway.py
import json import time from asyncio import TimeoutError from datetime import timedelta from json.decoder import JSONDecodeError from random import choice from typing import Union import discord from discord.ext import commands, tasks from discord.ext.commands import Cog, command from lib import (FutureTime, ...
0.65202
0.157947
from __future__ import division import numpy as np import scipy as sp from scipy import ndimage from scipy.sparse.csgraph import connected_components from sklearn.feature_extraction.image import ( img_to_graph, grid_to_graph, extract_patches_2d, reconstruct_from_patches_2d, PatchExtractor, extract_patches) fr...
env/lib/python3.5/site-packages/sklearn/feature_extraction/tests/test_image.py
from __future__ import division import numpy as np import scipy as sp from scipy import ndimage from scipy.sparse.csgraph import connected_components from sklearn.feature_extraction.image import ( img_to_graph, grid_to_graph, extract_patches_2d, reconstruct_from_patches_2d, PatchExtractor, extract_patches) fr...
0.828141
0.650453
import struct import socket from datetime import datetime from fdfs_client.fdfs_protol import * from fdfs_client.connection import * from fdfs_client.exceptions import ( FDFSError, ConnectionError, ResponseError, InvaildResponse, DataError ) from fdfs_client.utils import * def par...
fdfs_client/tracker_client.py
import struct import socket from datetime import datetime from fdfs_client.fdfs_protol import * from fdfs_client.connection import * from fdfs_client.exceptions import ( FDFSError, ConnectionError, ResponseError, InvaildResponse, DataError ) from fdfs_client.utils import * def par...
0.257578
0.057945
import os import tempfile from contextlib import contextmanager from typing import Generator, Optional from unittest.mock import patch, Mock, call import pytest # type: ignore from click.testing import CliRunner, Result import purgeraw.main from purgeraw.index_extraction import indexer class TestMain: @contex...
tests/test_main.py
import os import tempfile from contextlib import contextmanager from typing import Generator, Optional from unittest.mock import patch, Mock, call import pytest # type: ignore from click.testing import CliRunner, Result import purgeraw.main from purgeraw.index_extraction import indexer class TestMain: @contex...
0.63624
0.269977
import cv2 import numpy as np import re # Importing our dependencies import util as ut import svm_train as st import time # create and train SVM model each time coz bug in opencv 3.1.0 svm.load() https://github.com/Itseez/opencv/issues/4969 model = st.trainSVM(9, 20, 'TrainData2') move_text = {'1': 'GRAB...
hand_pose.py
import cv2 import numpy as np import re # Importing our dependencies import util as ut import svm_train as st import time # create and train SVM model each time coz bug in opencv 3.1.0 svm.load() https://github.com/Itseez/opencv/issues/4969 model = st.trainSVM(9, 20, 'TrainData2') move_text = {'1': 'GRAB...
0.241221
0.133613
from zigpy.profiles import zha from zigpy.quirks import CustomDevice from zigpy.zcl.clusters.general import ( Basic, Groups, Identify, LevelControl, OnOff, Ota, PowerConfiguration, ) from zigpy.zcl.clusters.lighting import Color from zigpy.zcl.clusters.lightlink import LightLink from zhaqui...
zhaquirks/lds/cctswitch.py
from zigpy.profiles import zha from zigpy.quirks import CustomDevice from zigpy.zcl.clusters.general import ( Basic, Groups, Identify, LevelControl, OnOff, Ota, PowerConfiguration, ) from zigpy.zcl.clusters.lighting import Color from zigpy.zcl.clusters.lightlink import LightLink from zhaqui...
0.575946
0.135861
from zope.interface import ( Attribute, Interface, ) # public API class IHandler(Interface): """A Callback Handler for Zookeeper completion and watch callbacks This object must implement several methods responsible for determining how completion / watch callbacks are handled as well as the m...
kazoo/interfaces.py
from zope.interface import ( Attribute, Interface, ) # public API class IHandler(Interface): """A Callback Handler for Zookeeper completion and watch callbacks This object must implement several methods responsible for determining how completion / watch callbacks are handled as well as the m...
0.903341
0.530176
from selenium import webdriver from selenium.webdriver.common.proxy import Proxy, ProxyType from selenium.webdriver.firefox.options import Options from webdriver_manager.chrome import ChromeDriverManager from webdriver_manager.firefox import GeckoDriverManager from config import Config from utils.helpers import get_ra...
{{cookiecutter.project_name}}/utils/Driver.py
from selenium import webdriver from selenium.webdriver.common.proxy import Proxy, ProxyType from selenium.webdriver.firefox.options import Options from webdriver_manager.chrome import ChromeDriverManager from webdriver_manager.firefox import GeckoDriverManager from config import Config from utils.helpers import get_ra...
0.456652
0.044183
import tensorflow as tf import tensorflow.contrib.slim as slim import config as cfg class Lenet: def __init__(self): self.raw_input_image = tf.placeholder(tf.float32, [None, 784]) self.input_images = tf.reshape(self.raw_input_image, [-1, 28, 28, 1]) self.raw_input_label = tf.placeholder("f...
lenet.py
import tensorflow as tf import tensorflow.contrib.slim as slim import config as cfg class Lenet: def __init__(self): self.raw_input_image = tf.placeholder(tf.float32, [None, 784]) self.input_images = tf.reshape(self.raw_input_image, [-1, 28, 28, 1]) self.raw_input_label = tf.placeholder("f...
0.783077
0.330174
#------------------------------ import numpy as np #------------------------------ def hist_values(nda) : """Depending on nda.dtype fills/returns 1-D 2^8(16)-bin histogram-array of 8(16)-bit values of input n-d array """ #print '%s for array dtype=%s'%(FR().f_code.co_name, str(nda.dtype)) if nda.dtype...
psana/psana/pyalgos/generic/Entropy.py
#------------------------------ import numpy as np #------------------------------ def hist_values(nda) : """Depending on nda.dtype fills/returns 1-D 2^8(16)-bin histogram-array of 8(16)-bit values of input n-d array """ #print '%s for array dtype=%s'%(FR().f_code.co_name, str(nda.dtype)) if nda.dtype...
0.448426
0.463809
def style_transfer(content_image, style_image, content_layer_ids, style_layer_ids, weight_content=1.5, weight_style=10.0, weight_denoise=0.3, num_iterations=120, step_size=10.0): # operations to the graph so it can grow very large...
Style.py
def style_transfer(content_image, style_image, content_layer_ids, style_layer_ids, weight_content=1.5, weight_style=10.0, weight_denoise=0.3, num_iterations=120, step_size=10.0): # operations to the graph so it can grow very large...
0.858837
0.681432
import traceback import base import dbutils import extensions from textutils import json_encode, json_decode from operation.basictypes import (OperationResult, OperationError, OperationFailure, OperationFailureMustLogin) from operation.typechecker import (Optional, Request, Restri...
src/operation/__init__.py
import traceback import base import dbutils import extensions from textutils import json_encode, json_decode from operation.basictypes import (OperationResult, OperationError, OperationFailure, OperationFailureMustLogin) from operation.typechecker import (Optional, Request, Restri...
0.756537
0.229438
import os from pyfakefs.fake_filesystem_unittest import TestCase import backend class TestDatasets(TestCase): def setUp(self): self.setUpPyfakefs() self.fs.create_dir(backend.DATASETS_PATH) self.fs.create_file(os.path.join(backend.DATASETS_PATH, 'dataset1', 'img1.nii.gz')) self...
tests/test_backend.py
import os from pyfakefs.fake_filesystem_unittest import TestCase import backend class TestDatasets(TestCase): def setUp(self): self.setUpPyfakefs() self.fs.create_dir(backend.DATASETS_PATH) self.fs.create_file(os.path.join(backend.DATASETS_PATH, 'dataset1', 'img1.nii.gz')) self...
0.464902
0.379005
import argparse import time import util import azureutils import sys config_set_name = "apache-test-application" def parse_args (): # Ugly but expedient conversion of ansible-playbook to a parameterized python script parser = argparse.ArgumentParser() parser.add_argument("--NODE_IP", type=str, required=Tr...
azure/scripts/deploy-application.py
import argparse import time import util import azureutils import sys config_set_name = "apache-test-application" def parse_args (): # Ugly but expedient conversion of ansible-playbook to a parameterized python script parser = argparse.ArgumentParser() parser.add_argument("--NODE_IP", type=str, required=Tr...
0.22051
0.176778
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import onnx import onnx.onnx_cpp2py_export.shape_inference as C from onnx import ModelProto from typing import Text, Union def infer_shapes(model: Union[ModelProto, byt...
onnx/shape_inference.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import onnx import onnx.onnx_cpp2py_export.shape_inference as C from onnx import ModelProto from typing import Text, Union def infer_shapes(model: Union[ModelProto, byt...
0.908476
0.419113
import datetime import json import re from rdr_service import config from rdr_service.dao.bigquery_sync_dao import BigQuerySyncDao, BigQueryGenerator from rdr_service.model.bq_base import BQRecord from rdr_service.model.bq_participant_summary import BQParticipantSummarySchema, BQParticipantSummary from rdr_service.mod...
rdr_service/dao/bq_participant_summary_dao.py
import datetime import json import re from rdr_service import config from rdr_service.dao.bigquery_sync_dao import BigQuerySyncDao, BigQueryGenerator from rdr_service.model.bq_base import BQRecord from rdr_service.model.bq_participant_summary import BQParticipantSummarySchema, BQParticipantSummary from rdr_service.mod...
0.602062
0.22642
import planckStyle as s from getdist import types import six g = s.getSinglePlotter() pars = ['omegabh2', 'omegach2', 'theta', 'tau', 'logA', 'ns', 'omegamh2', 'H0', 'omegam', 'age', 'sigma8', 'S8', 'zrei', 'thetastar', 'rdrag'] lines = [] heading = '' formatter = types.NoLineTableFormatter() class col(obj...
batch3/outputs/lcdm_default_table.py
import planckStyle as s from getdist import types import six g = s.getSinglePlotter() pars = ['omegabh2', 'omegach2', 'theta', 'tau', 'logA', 'ns', 'omegamh2', 'H0', 'omegam', 'age', 'sigma8', 'S8', 'zrei', 'thetastar', 'rdrag'] lines = [] heading = '' formatter = types.NoLineTableFormatter() class col(obj...
0.267983
0.222098
import argparse import os import re import json from pathlib import Path def parse_args(): """ Parse command line arguments :returns: object -- Object containing command line options """ parser = argparse.ArgumentParser(description="Link each minimized structure with the corresponding QM co...
benchmarks/geometry/link_structures.py
import argparse import os import re import json from pathlib import Path def parse_args(): """ Parse command line arguments :returns: object -- Object containing command line options """ parser = argparse.ArgumentParser(description="Link each minimized structure with the corresponding QM co...
0.515376
0.163947
from __future__ import annotations import dataclasses import inspect import pathlib import types from typing import Any, Optional, Type, Union from . import module from . import package from . import traits @dataclasses.dataclass class Inspector(object): """Inspector factory which returns the appropraite Inspect...
amos/observe/examine.py
from __future__ import annotations import dataclasses import inspect import pathlib import types from typing import Any, Optional, Type, Union from . import module from . import package from . import traits @dataclasses.dataclass class Inspector(object): """Inspector factory which returns the appropraite Inspect...
0.944625
0.262357
import smtplib import pymongo import time from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import json with open('/home/idong-gi/VINEDING/email_information') as data_file: email_data = json.load(data_file) MAIL_ACCOUNT = email_data["id"] MAIL_PASSWORD = email_data["pw"] TITLE = ...
ProcessInformation/python/email_transfer/email_transfer/EmailTransfer.py
import smtplib import pymongo import time from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import json with open('/home/idong-gi/VINEDING/email_information') as data_file: email_data = json.load(data_file) MAIL_ACCOUNT = email_data["id"] MAIL_PASSWORD = email_data["pw"] TITLE = ...
0.099815
0.132683
from __future__ import print_function import argparse # [START dlp_list_jobs] def list_dlp_jobs(project, filter_string=None, job_type=None): """Uses the Data Loss Prevention API to lists DLP jobs that match the specified filter in the request. Args: project: The project id to use as a parent ...
dlp/jobs.py
from __future__ import print_function import argparse # [START dlp_list_jobs] def list_dlp_jobs(project, filter_string=None, job_type=None): """Uses the Data Loss Prevention API to lists DLP jobs that match the specified filter in the request. Args: project: The project id to use as a parent ...
0.87444
0.405625
import logging import typing from enum import Enum from ..exceptions import KeyboardException from vk.constants import JSON_LIBRARY logger = logging.getLogger(__name__) # Keyboards: https://vk.com/dev/bots_docs_3 class ButtonColor(Enum): PRIMARY = "primary" # blue SECONDARY = "secondary" # white NEG...
vk/keyboards/keyboard.py
import logging import typing from enum import Enum from ..exceptions import KeyboardException from vk.constants import JSON_LIBRARY logger = logging.getLogger(__name__) # Keyboards: https://vk.com/dev/bots_docs_3 class ButtonColor(Enum): PRIMARY = "primary" # blue SECONDARY = "secondary" # white NEG...
0.714728
0.207696
from poi.infer.base import BaseModel import tensorrt as trt import pycuda.driver as cuda import numpy as np # a helper to host device storage class HostDeviceMem(object): def __init__(self, host_mem, device_mem, shape): self.host = host_mem self.device = device_mem self.shape = shape ...
poi/infer/trt.py
from poi.infer.base import BaseModel import tensorrt as trt import pycuda.driver as cuda import numpy as np # a helper to host device storage class HostDeviceMem(object): def __init__(self, host_mem, device_mem, shape): self.host = host_mem self.device = device_mem self.shape = shape ...
0.783947
0.11187
import sys import time import logging import schedule from nemapi import NetEase from charter import Charter from utils.cover import CoverToolkits logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler(sys.stdout) stream_handler.setLevel(level=logging.DEBUG) logger...
charts/nembee.py
import sys import time import logging import schedule from nemapi import NetEase from charter import Charter from utils.cover import CoverToolkits logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) stream_handler = logging.StreamHandler(sys.stdout) stream_handler.setLevel(level=logging.DEBUG) logger...
0.193376
0.086864
import numpy as np import sys from .telescope_functions import * from .usefuls import * from . import conv from . import cosmology as cm from . import smoothing as sm import scipy from glob import glob from time import time, sleep import pickle from joblib import Parallel, delayed from tqdm import tqdm def noise_map(n...
src/tools21cm/noise_model.py
import numpy as np import sys from .telescope_functions import * from .usefuls import * from . import conv from . import cosmology as cm from . import smoothing as sm import scipy from glob import glob from time import time, sleep import pickle from joblib import Parallel, delayed from tqdm import tqdm def noise_map(n...
0.560974
0.352007
import os import sys import re COPYRIGHT = re.compile(r'Copyright') INTEL_COPYRIGHT = re.compile(r'Copyright (\(c\) )?(201(8|9)-)?20(20|19|18) Intel Corporation') FORBIDDEN_FUNCTIONS = re.compile(r'setjmp\(|longjmp\(|getwd\(|strlen\(|wcslen\(|gets\(|strcpy\(|wcscpy\(|strcat\(|wcscat\(|sprintf\(|vsprintf\(|asctime\('...
lib_search.py
import os import sys import re COPYRIGHT = re.compile(r'Copyright') INTEL_COPYRIGHT = re.compile(r'Copyright (\(c\) )?(201(8|9)-)?20(20|19|18) Intel Corporation') FORBIDDEN_FUNCTIONS = re.compile(r'setjmp\(|longjmp\(|getwd\(|strlen\(|wcslen\(|gets\(|strcpy\(|wcscpy\(|strcat\(|wcscat\(|sprintf\(|vsprintf\(|asctime\('...
0.140912
0.095392
import unittest from silasdk.processingTypes import ProcessingTypes from silasdk.transactions import Transaction from silasdk.users import User from tests.poll_until_status import poll from tests.test_config import (sardine_handle, eth_private_key_6, app, business_uuid, eth_private_key, user_handle) class Test011...
tests/test011_redeem_sila.py
import unittest from silasdk.processingTypes import ProcessingTypes from silasdk.transactions import Transaction from silasdk.users import User from tests.poll_until_status import poll from tests.test_config import (sardine_handle, eth_private_key_6, app, business_uuid, eth_private_key, user_handle) class Test011...
0.549882
0.42322
import string import math from codestat_token import Token from codestat_tokenizer import Tokenizer from token_builders import ( InvalidTokenBuilder, WhitespaceTokenBuilder, NewlineTokenBuilder, EscapedStringTokenBuilder, PrefixedStringTokenBuilder, IntegerTokenBuilder, IntegerExponentTokenBuilder, Rea...
csharp_examiner.py
import string import math from codestat_token import Token from codestat_tokenizer import Tokenizer from token_builders import ( InvalidTokenBuilder, WhitespaceTokenBuilder, NewlineTokenBuilder, EscapedStringTokenBuilder, PrefixedStringTokenBuilder, IntegerTokenBuilder, IntegerExponentTokenBuilder, Rea...
0.31216
0.068475
from collections import namedtuple from enum import Enum from math import sqrt from typing import NamedTuple, Optional from pathos.helpers import mp from tqdm import tqdm from skdecide import ( DiscreteDistribution, EnvironmentOutcome, GoalMDPDomain, Space, TransitionOutcome, Value, ) from sk...
tests/solvers/cpp/parallelism/test_parallel_probabilistic_algorithms.py
from collections import namedtuple from enum import Enum from math import sqrt from typing import NamedTuple, Optional from pathos.helpers import mp from tqdm import tqdm from skdecide import ( DiscreteDistribution, EnvironmentOutcome, GoalMDPDomain, Space, TransitionOutcome, Value, ) from sk...
0.914853
0.363703
import discord from discord.ext import commands from mysqldb import the_database from typing import List, Union, Optional from extra import utils class UserBabiesTable(commands.Cog): """ Class for the UserBabies table and its commands and methods. """ def __init__(self, client: commands.Bot) -> None: ...
extra/slothclasses/userbabies.py
import discord from discord.ext import commands from mysqldb import the_database from typing import List, Union, Optional from extra import utils class UserBabiesTable(commands.Cog): """ Class for the UserBabies table and its commands and methods. """ def __init__(self, client: commands.Bot) -> None: ...
0.703346
0.150434
import asyncio import json import asyncpg import enum import time from bs4 import BeautifulSoup from bs4.element import Tag, ResultSet import aiofiles from aiohttp import ClientSession, TCPConnector, ClientTimeout, ServerDisconnectedError, ClientConnectorError from asyncpg import Pool # 全局数据库信息 = > config.json CONFIG...
AreaInfo.py
import asyncio import json import asyncpg import enum import time from bs4 import BeautifulSoup from bs4.element import Tag, ResultSet import aiofiles from aiohttp import ClientSession, TCPConnector, ClientTimeout, ServerDisconnectedError, ClientConnectorError from asyncpg import Pool # 全局数据库信息 = > config.json CONFIG...
0.128895
0.108095
import time import struct import socket import threading import numpy as np from .BCIDecoder import generate_simulation_data from . import logger simulationMode = True maxLength = 3600 # Seconds class SimulationDataGenerator(object): ''' Generate simulation data ''' def __init__(self): ...
BCIClient/neuroScanToolbox.py
import time import struct import socket import threading import numpy as np from .BCIDecoder import generate_simulation_data from . import logger simulationMode = True maxLength = 3600 # Seconds class SimulationDataGenerator(object): ''' Generate simulation data ''' def __init__(self): ...
0.607197
0.22114
import pdb, os, glob, sys, torch, numpy as np, json import torch.utils.data as data import torchvision.transforms as transforms from PIL import Image, ImageDraw, ImageFont class SpaceNet(data.Dataset): name = 'VOC' classes = ['building'] def __init__(self, anno_file, transform = None): self.transfo...
data/spacenet.py
import pdb, os, glob, sys, torch, numpy as np, json import torch.utils.data as data import torchvision.transforms as transforms from PIL import Image, ImageDraw, ImageFont class SpaceNet(data.Dataset): name = 'VOC' classes = ['building'] def __init__(self, anno_file, transform = None): self.transfo...
0.547706
0.439326
import os import sys from abc import ABC, abstractmethod from importlib import import_module from typing import Any import torch from albumentations import Compose from omegaconf.dictconfig import DictConfig from torch.nn import Module from torch.optim.lr_scheduler import _LRScheduler from torch.optim.optimizer import...
riad/runner/base_runner.py
import os import sys from abc import ABC, abstractmethod from importlib import import_module from typing import Any import torch from albumentations import Compose from omegaconf.dictconfig import DictConfig from torch.nn import Module from torch.optim.lr_scheduler import _LRScheduler from torch.optim.optimizer import...
0.763131
0.1831
"""Account service tests.""" from unittest import TestCase from six import PY3 from . import ICloudPyServiceMock from .const import AUTHENTICATED_USER, VALID_PASSWORD class AccountServiceTest(TestCase): """ "Account service tests""" service = None def setUp(self): self.service = ICloudPyService...
tests/test_account.py
"""Account service tests.""" from unittest import TestCase from six import PY3 from . import ICloudPyServiceMock from .const import AUTHENTICATED_USER, VALID_PASSWORD class AccountServiceTest(TestCase): """ "Account service tests""" service = None def setUp(self): self.service = ICloudPyService...
0.755817
0.490602
from django.core.validators import FileExtensionValidator from django.db import models from src.base.services import get_path_upload_avatar, validate_size_img class AuthUser(models.Model): """ Модель пользователя """ email = models.EmailField(max_length=150, unique=True) join_date = models.DateTimeF...
src/oauth/models.py
from django.core.validators import FileExtensionValidator from django.db import models from src.base.services import get_path_upload_avatar, validate_size_img class AuthUser(models.Model): """ Модель пользователя """ email = models.EmailField(max_length=150, unique=True) join_date = models.DateTimeF...
0.550607
0.077657
import json from django.conf import settings from django.db import models from django.template.defaultfilters import slugify from fernet_fields import EncryptedCharField from fernet_fields import EncryptedTextField from polymorphic.models import PolymorphicModel import yaml class DateNameAwareModel(models.Model):...
djcloudbridge/models.py
import json from django.conf import settings from django.db import models from django.template.defaultfilters import slugify from fernet_fields import EncryptedCharField from fernet_fields import EncryptedTextField from polymorphic.models import PolymorphicModel import yaml class DateNameAwareModel(models.Model):...
0.532182
0.108236
import copy import types import pickle import numpy from learning import Model from learning.rlearn import RLTable class MultiOutputs(Model): """Ensemble enabling given model to return a higher dimensional output tensor. Can be used to return an output vector from a model returing an output value. Or ...
learning/architecture/multioutputs.py
import copy import types import pickle import numpy from learning import Model from learning.rlearn import RLTable class MultiOutputs(Model): """Ensemble enabling given model to return a higher dimensional output tensor. Can be used to return an output vector from a model returing an output value. Or ...
0.798854
0.694607
from argparse import ArgumentParser import codecs import json import logging import os import pickle import sys import tempfile from typing import Union import numpy as np from rusenttokenize import ru_sent_tokenize try: from deep_ner.elmo_ner import ELMo_NER, elmo_ner_logger from deep_ner.utils import factru...
demo/demo_elmo_factrueval2016.py
from argparse import ArgumentParser import codecs import json import logging import os import pickle import sys import tempfile from typing import Union import numpy as np from rusenttokenize import ru_sent_tokenize try: from deep_ner.elmo_ner import ELMo_NER, elmo_ner_logger from deep_ner.utils import factru...
0.415847
0.186095
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.core.validators import RegexValidator from django.db import models from django.utils.translation import gettext_lazy as _ # Create your models here. class PhoneOTP(models.Model): phone_regex = RegexValidator( reg...
api/models.py
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.core.validators import RegexValidator from django.db import models from django.utils.translation import gettext_lazy as _ # Create your models here. class PhoneOTP(models.Model): phone_regex = RegexValidator( reg...
0.481698
0.087837
import os import shutil from PIL import Image # ============================ CONFIG ================================ user = os.environ['USERPROFILE'] dest_folder = r"Downloads\_tmp_" # Destination folder in Downloads delete_portraits = False # delete portraits or not? min_size = 500 # dim...
Spotlight/run.py
import os import shutil from PIL import Image # ============================ CONFIG ================================ user = os.environ['USERPROFILE'] dest_folder = r"Downloads\_tmp_" # Destination folder in Downloads delete_portraits = False # delete portraits or not? min_size = 500 # dim...
0.293404
0.058939
# Author: fvj # License: BSD 3 clause import datetime import argparse import atexit import os import numpy as np from pyrad.io import get_trtfile_list, read_trt_data, write_trt_cell_data print(__doc__) def main(): """ """ # parse the arguments parser = argparse.ArgumentParser( description=...
src/pyrad_proc/pyrad/EGG-INFO/scripts/main_extract_trt.py
# Author: fvj # License: BSD 3 clause import datetime import argparse import atexit import os import numpy as np from pyrad.io import get_trtfile_list, read_trt_data, write_trt_cell_data print(__doc__) def main(): """ """ # parse the arguments parser = argparse.ArgumentParser( description=...
0.405096
0.228329
import os import sys from importlib.abc import MetaPathFinder, Loader from importlib.machinery import ModuleSpec from .lib_import import VersionImporter __all__ = [ 'init_finder', 'init_loader', 'loader', 'import_name_to_name_version', 'PyLibImportFinder', 'PyLibImportLoader', ] LOADER = None FINDER = ...
pylibimport/finder_loader.py
import os import sys from importlib.abc import MetaPathFinder, Loader from importlib.machinery import ModuleSpec from .lib_import import VersionImporter __all__ = [ 'init_finder', 'init_loader', 'loader', 'import_name_to_name_version', 'PyLibImportFinder', 'PyLibImportLoader', ] LOADER = None FINDER = ...
0.480722
0.075007
import setuptools long_description = """# Pandas Bokeh **Pandas Bokeh** provides a [Bokeh](https://bokeh.pydata.org/en/latest/) plotting backend for [Pandas](https://pandas.pydata.org/) and [GeoPandas](http://geopandas.org/), similar to the already existing [Visualization](https://pandas.pydata.org/pandas-docs/stable...
setup.py
df.plot_bokeh()
0.346541
0.963437
from __future__ import (absolute_import, division, print_function, unicode_literals) import os import os import logging import pandas as pd from hansel import Crumb from invoke import task from boyle.files.search import recursive_glob from neur...
examples/pipelines.py
from __future__ import (absolute_import, division, print_function, unicode_literals) import os import os import logging import pandas as pd from hansel import Crumb from invoke import task from boyle.files.search import recursive_glob from neur...
0.604983
0.144571
import unittest import avltree_eaf3d as bst import eaf3D import numpy as np from operator import attrgetter from stack import Stack class AVLTreeTestsFromStarter(unittest.TestCase): def setUp(self): # Set initial points for sentinels (to simulate infinity) big_pos_value = 10E10 big_neg_va...
Analysis/eaf3D/test_avl_eaf3d.py
import unittest import avltree_eaf3d as bst import eaf3D import numpy as np from operator import attrgetter from stack import Stack class AVLTreeTestsFromStarter(unittest.TestCase): def setUp(self): # Set initial points for sentinels (to simulate infinity) big_pos_value = 10E10 big_neg_va...
0.603698
0.548492
import requests, json, textwrap, time, os, glob, random, hashlib from random import randint from PIL import Image, ImageDraw, ImageFont, ImageStat, ImageFilter, ImageEnhance import nltk from resizeimage import resizeimage from tinydb import TinyDB, Query from time import sleep from selenium import webdriver from seleni...
postImageWin.py
import requests, json, textwrap, time, os, glob, random, hashlib from random import randint from PIL import Image, ImageDraw, ImageFont, ImageStat, ImageFilter, ImageEnhance import nltk from resizeimage import resizeimage from tinydb import TinyDB, Query from time import sleep from selenium import webdriver from seleni...
0.282691
0.120594
import torch import torchvision from torch import nn import logging import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import time import os import copy import logging import sys sys.path.append('../') from Model.fcdn import FCDenseNet as UNet from Data.get_super_synth_loader import ...
Train/Train_fcdn.py
import torch import torchvision from torch import nn import logging import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import time import os import copy import logging import sys sys.path.append('../') from Model.fcdn import FCDenseNet as UNet from Data.get_super_synth_loader import ...
0.583203
0.183411
from __future__ import print_function import argparse import torch import torch.nn.functional as F from torchvision import datasets, transforms from models import vgg, resnet, densenet import numpy as np import os import sys from tqdm import tqdm from utils import * import glob if __name__ == '__main__': parser = a...
cifar10/eval_acc_all.py
from __future__ import print_function import argparse import torch import torch.nn.functional as F from torchvision import datasets, transforms from models import vgg, resnet, densenet import numpy as np import os import sys from tqdm import tqdm from utils import * import glob if __name__ == '__main__': parser = a...
0.397354
0.136868
import os import sys from copy import deepcopy from glob import glob MODNAME = '_builtin' def _copy(obj, **kws): """copy an object""" return deepcopy(obj) def _parent(name, _larch=None, **kw): "print out parent group name of an object" print(_larch.symtable._lookup(name, create=False)) def _ls(dire...
plugins/std/shellutils.py
import os import sys from copy import deepcopy from glob import glob MODNAME = '_builtin' def _copy(obj, **kws): """copy an object""" return deepcopy(obj) def _parent(name, _larch=None, **kw): "print out parent group name of an object" print(_larch.symtable._lookup(name, create=False)) def _ls(dire...
0.160102
0.063628
import datetime import ddt from ggrc.models import all_models from ggrc.utils import errors from integration.ggrc import api_helper from integration.ggrc.models import factories from integration.ggrc import TestCase class TestProgram(TestCase): """Program test cases.""" def setUp(self): self.api = api_help...
test/integration/ggrc/models/test_program.py
import datetime import ddt from ggrc.models import all_models from ggrc.utils import errors from integration.ggrc import api_helper from integration.ggrc.models import factories from integration.ggrc import TestCase class TestProgram(TestCase): """Program test cases.""" def setUp(self): self.api = api_help...
0.659734
0.347177
from django.contrib.auth.models import User from django.test import TestCase from django.utils import timezone from dfirtrack_main.models import Entry, System, Systemstatus class EntryModelTestCase(TestCase): """ entry model tests """ @classmethod def setUpTestData(cls): # create user tes...
Incident-Response/Tools/dfirtrack/dfirtrack_main/tests/entry/test_entry_models.py
from django.contrib.auth.models import User from django.test import TestCase from django.utils import timezone from dfirtrack_main.models import Entry, System, Systemstatus class EntryModelTestCase(TestCase): """ entry model tests """ @classmethod def setUpTestData(cls): # create user tes...
0.577495
0.195959
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables from . import outputs from ._inputs import * __all__ = ['RunBook'] class RunBook(pulumi.CustomResource): def __init__(__self__, resource_name: str, ...
sdk/python/pulumi_azure/automation/run_book.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union from .. import _utilities, _tables from . import outputs from ._inputs import * __all__ = ['RunBook'] class RunBook(pulumi.CustomResource): def __init__(__self__, resource_name: str, ...
0.817319
0.22051
import pytest import sys sys.path.append('../') from server.parsing.utils import create_chat_df, create_students_df import os # TODO: need to load the file as FileStorage type and then start testing @pytest.fixture def folders(): CHAT_FILES_FOLDER = "./files_to_test/chat_files" STUDENT_EXCEL_FILES_FOLDER = "....
server/tests/test_parsing_utils.py
import pytest import sys sys.path.append('../') from server.parsing.utils import create_chat_df, create_students_df import os # TODO: need to load the file as FileStorage type and then start testing @pytest.fixture def folders(): CHAT_FILES_FOLDER = "./files_to_test/chat_files" STUDENT_EXCEL_FILES_FOLDER = "....
0.209551
0.316871
import os import argparse import logging from utils.sentence_scorer import SentenceScorer from utils.tokenizer import Tokenizer logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO, datefmt='%H:%M:%S') logger = logging.getLogger(__name__) class Preprocessor: def __init__(s...
preprocess.py
import os import argparse import logging from utils.sentence_scorer import SentenceScorer from utils.tokenizer import Tokenizer logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.INFO, datefmt='%H:%M:%S') logger = logging.getLogger(__name__) class Preprocessor: def __init__(s...
0.465387
0.26106
import os import sys import sqlalchemy import datetime _S2DB_ROOT = os.path.normpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..")) sys.path.append(_S2DB_ROOT) from common.config import config from common.log import get_logger logger = get_logger(__name__) engine = sqlalchemy.create_engine(config["...
s2db/db/engine.py
import os import sys import sqlalchemy import datetime _S2DB_ROOT = os.path.normpath(os.path.join(os.path.abspath(os.path.dirname(__file__)), "..")) sys.path.append(_S2DB_ROOT) from common.config import config from common.log import get_logger logger = get_logger(__name__) engine = sqlalchemy.create_engine(config["...
0.185283
0.126273
import os import click from train_and_eval import ( train_and_eval_arct, train_and_eval_arc, train_and_eval_piqa, train_and_eval_csqa, ) @click.group() def cli(): pass @click.command() @click.option("--do_train", is_flag=True, help="Train the model.") @click.option("--do_test", is_flag=True, he...
GPT-2/main.py
import os import click from train_and_eval import ( train_and_eval_arct, train_and_eval_arc, train_and_eval_piqa, train_and_eval_csqa, ) @click.group() def cli(): pass @click.command() @click.option("--do_train", is_flag=True, help="Train the model.") @click.option("--do_test", is_flag=True, he...
0.50293
0.214846
# Copyright Toolkit Authors """Test metadata loader script with Pytest.""" import pytest def test_metadata_model(): """Run the metadata loader test.""" path = 'test/records/json_model_test/json_test.json.json' from pydtk.models import MetaDataModel assert MetaDataModel.is_loadable(path) # loa...
test/test_models.py
# Copyright Toolkit Authors """Test metadata loader script with Pytest.""" import pytest def test_metadata_model(): """Run the metadata loader test.""" path = 'test/records/json_model_test/json_test.json.json' from pydtk.models import MetaDataModel assert MetaDataModel.is_loadable(path) # loa...
0.781956
0.40539
import asyncio import logging import pigpio from surrortg.inputs import Switch from surrortg.inputs.input_filters import SpamFilter from games.arcade_pinball.config import ( BUTTON_PRESS_TIME, MAX_HOLD_TIME, MAX_INPUTS_PER_INPUT, PER_SECONDS, ) class ArcadeMultiButton(Switch): def __init__( ...
games/arcade_pinball/arcade_button.py
import asyncio import logging import pigpio from surrortg.inputs import Switch from surrortg.inputs.input_filters import SpamFilter from games.arcade_pinball.config import ( BUTTON_PRESS_TIME, MAX_HOLD_TIME, MAX_INPUTS_PER_INPUT, PER_SECONDS, ) class ArcadeMultiButton(Switch): def __init__( ...
0.382603
0.108378
from __future__ import print_function, unicode_literals, division, absolute_import import os, json, collections, concurrent.futures, traceback, sys, time, gc from multiprocessing import cpu_count import dateutil.parser from .. import logger from ..compat import basestring, THREAD_TIMEOUT_MAX from ..exceptions import D...
src/python/dxpy/utils/__init__.py
from __future__ import print_function, unicode_literals, division, absolute_import import os, json, collections, concurrent.futures, traceback, sys, time, gc from multiprocessing import cpu_count import dateutil.parser from .. import logger from ..compat import basestring, THREAD_TIMEOUT_MAX from ..exceptions import D...
0.440951
0.163612
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHE...
test/test_communicate.py
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHE...
0.402627
0.06078
# Standard library imports try: from unittest.mock import Mock except ImportError: from mock import Mock # Python 2 # Third party imports import pytest # Local imports from spyder.plugins.profiler.widgets import profilergui # --- Helper methods # ------------------------------------------------------------...
spyder/plugins/profiler/tests/test_profiler.py
# Standard library imports try: from unittest.mock import Mock except ImportError: from mock import Mock # Python 2 # Third party imports import pytest # Local imports from spyder.plugins.profiler.widgets import profilergui # --- Helper methods # ------------------------------------------------------------...
0.792906
0.664186
import configparser as ConfigParser from optparse import OptionParser def str_to_bool(s): if s == 'True': return True elif s == 'False': return False else: raise ValueError def read_conf(cfg_path, options): cfg_file=options.cfg Config = ConfigParser.ConfigParser()...
sincnet/utils.py
import configparser as ConfigParser from optparse import OptionParser def str_to_bool(s): if s == 'True': return True elif s == 'False': return False else: raise ValueError def read_conf(cfg_path, options): cfg_file=options.cfg Config = ConfigParser.ConfigParser()...
0.291687
0.072276
import gym import gym_reacher import time import os import numpy as np import pandas as pd import optuna import yaml from pathlib import Path from stable_baselines import A2C, ACKTR, DDPG, PPO1, PPO2, SAC, TRPO, TD3 from stable_baselines import results_plotter from stable_baselines.results_plotter import load_result...
scripts/13_hyperparameter_tuning.py
import gym import gym_reacher import time import os import numpy as np import pandas as pd import optuna import yaml from pathlib import Path from stable_baselines import A2C, ACKTR, DDPG, PPO1, PPO2, SAC, TRPO, TD3 from stable_baselines import results_plotter from stable_baselines.results_plotter import load_result...
0.688154
0.369059
from scheduler.exceptions import KubeHTTPException from scheduler.resources import Resource from scheduler.utils import dict_merge class Service(Resource): short_name = 'svc' def get(self, namespace, name=None, **kwargs): """ Fetch a single Service or a list """ url = '/namesp...
rootfs/scheduler/resources/service.py
from scheduler.exceptions import KubeHTTPException from scheduler.resources import Resource from scheduler.utils import dict_merge class Service(Resource): short_name = 'svc' def get(self, namespace, name=None, **kwargs): """ Fetch a single Service or a list """ url = '/namesp...
0.505615
0.0771
import asyncio import aiohttp BASE_URL = "http://0.0.0.0:8080" async def login(session, credentials: dict) -> dict: """Retrieve token with credentials""" resp = await session.post(f"{BASE_URL}/auth", json=credentials) assert resp.status == 200, f"Authentication Failed, {resp.reason}" token_payload ...
examples/refresh_token/cli.py
import asyncio import aiohttp BASE_URL = "http://0.0.0.0:8080" async def login(session, credentials: dict) -> dict: """Retrieve token with credentials""" resp = await session.post(f"{BASE_URL}/auth", json=credentials) assert resp.status == 200, f"Authentication Failed, {resp.reason}" token_payload ...
0.627267
0.28143
import numpy as np import pandas as pd import itertools as it import matplotlib.pyplot as plt from sklearn.metrics import mean_absolute_error from source.engine import funciones as f from source.engine.InputsNoRevolvente import InputsNoRevolvente from source.engine.OutputsNoRevolvente import OutputsNoRevolvente #CAMBI...
ExtraccionNoRev.py
import numpy as np import pandas as pd import itertools as it import matplotlib.pyplot as plt from sklearn.metrics import mean_absolute_error from source.engine import funciones as f from source.engine.InputsNoRevolvente import InputsNoRevolvente from source.engine.OutputsNoRevolvente import OutputsNoRevolvente #CAMBI...
0.100746
0.121061
import jinja2 as jinja2 import pytest as pytest from localstack.utils.common import short_uid from localstack.utils.generic.wait_utils import wait_until from tests.integration.cloudformation.test_cloudformation_changesets import load_template_raw def test_resolve_ssm( ssm_client, cfn_client, is_change_se...
tests/integration/cloudformation/test_cloudformation_dynamic_parameters.py
import jinja2 as jinja2 import pytest as pytest from localstack.utils.common import short_uid from localstack.utils.generic.wait_utils import wait_until from tests.integration.cloudformation.test_cloudformation_changesets import load_template_raw def test_resolve_ssm( ssm_client, cfn_client, is_change_se...
0.213623
0.395309
# @package OpTestHMC # This class can contain common functions which are useful for # FSP_PHYP (HMC) platforms import os import sys import time import pexpect import shlex import OpTestLogger from common.OpTestError import OpTestError from common.OpTestSSH import OpTestSSH from common.OpTestUtil import OpTestUtil ...
common/OpTestHMC.py
# @package OpTestHMC # This class can contain common functions which are useful for # FSP_PHYP (HMC) platforms import os import sys import time import pexpect import shlex import OpTestLogger from common.OpTestError import OpTestError from common.OpTestSSH import OpTestSSH from common.OpTestUtil import OpTestUtil ...
0.318697
0.223419
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # M...
vega/datasets/pytorch/transforms/BboxTransform.py
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # M...
0.903241
0.348008
import pytest from .. import api # test setup to avoid cluttering pytest parameterize mni2009_urls = [ "https://doi.org/10.1016/j.neuroimage.2010.07.033", "https://doi.org/10.1016/S1053-8119(09)70884-5", "http://nist.mni.mcgill.ca/?p=904", "https://doi.org/10.1007/3-540-48714-X_16", ] mni2009_fbib =...
templateflow/tests/test_api.py
import pytest from .. import api # test setup to avoid cluttering pytest parameterize mni2009_urls = [ "https://doi.org/10.1016/j.neuroimage.2010.07.033", "https://doi.org/10.1016/S1053-8119(09)70884-5", "http://nist.mni.mcgill.ca/?p=904", "https://doi.org/10.1007/3-540-48714-X_16", ] mni2009_fbib =...
0.486819
0.591753