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 torch import torch.nn as nn import math from eod.utils.model import accuracy as A # noqa F401 from eod.utils.model.initializer import initialize_from_cfg from eod.utils.general.registry_factory import MODULE_ZOO_REGISTRY from eod.tasks.det.plugins.yolox.models.backbone.cspdarknet import DWConv from eod.tasks.d...
eod/tasks/det/plugins/yolox/models/head/yolox_head.py
import torch import torch.nn as nn import math from eod.utils.model import accuracy as A # noqa F401 from eod.utils.model.initializer import initialize_from_cfg from eod.utils.general.registry_factory import MODULE_ZOO_REGISTRY from eod.tasks.det.plugins.yolox.models.backbone.cspdarknet import DWConv from eod.tasks.d...
0.921056
0.233794
import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/") n_epochs = 400 batch_size = 50 learning_rate = 0.01 n_inputs = 28 * 28 n_hidden1 = 300 n_hidden2 = 200 n_outputs = 10 X = tf.placeholder(tf.float32, shape=(None, n_...
06_dnn_plain_tf_api/train.py
import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("/tmp/data/") n_epochs = 400 batch_size = 50 learning_rate = 0.01 n_inputs = 28 * 28 n_hidden1 = 300 n_hidden2 = 200 n_outputs = 10 X = tf.placeholder(tf.float32, shape=(None, n_...
0.666062
0.49762
import sys import os #sys.setdefaultencoding("utf-8") from sqlalchemy import Table from yaml import load try: from yaml import CSafeLoader as SafeLoader except ImportError: from yaml import SafeLoader print("Using Python SafeLoader") def importyaml(connection,metadata,sourcePath,language='en'): print("Importi...
tableloader/tableFunctions/npccorporations.py
import sys import os #sys.setdefaultencoding("utf-8") from sqlalchemy import Table from yaml import load try: from yaml import CSafeLoader as SafeLoader except ImportError: from yaml import SafeLoader print("Using Python SafeLoader") def importyaml(connection,metadata,sourcePath,language='en'): print("Importi...
0.095867
0.065128
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pytest import pandas import ray.dataframe as pd from ray.dataframe.utils import ( to_pandas, from_pandas ) @pytest.fixture def ray_df_equals_pandas(ray_df, pandas_df): return to_pandas(ray_...
python/ray/dataframe/test/test_concat.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import pytest import pandas import ray.dataframe as pd from ray.dataframe.utils import ( to_pandas, from_pandas ) @pytest.fixture def ray_df_equals_pandas(ray_df, pandas_df): return to_pandas(ray_...
0.816077
0.619673
from torchvision import datasets, transforms import numpy as np from numpy.random import RandomState def download_MNIST(use_training_set=False): """ Use Torchvision datasets and transform to a float WxHxD tensor. In the case of MNIST, we have a 28x28x1 tensor Args: use_training_set: If true,...
BitsBack/datasets.py
from torchvision import datasets, transforms import numpy as np from numpy.random import RandomState def download_MNIST(use_training_set=False): """ Use Torchvision datasets and transform to a float WxHxD tensor. In the case of MNIST, we have a 28x28x1 tensor Args: use_training_set: If true,...
0.937975
0.735262
import random from user import User from credentials import Credentials # Functions to add credentials def create_new_credential(site_name,account_name, account_password): """Function to create a new account and its credentials""" new_credential = Credentials(site_name,account_name, account_password) re...
run.py
import random from user import User from credentials import Credentials # Functions to add credentials def create_new_credential(site_name,account_name, account_password): """Function to create a new account and its credentials""" new_credential = Credentials(site_name,account_name, account_password) re...
0.280715
0.097907
import unittest class Solution: @staticmethod def checkValidString(s: str) -> bool: """ Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: Any l...
python/valid_parenthesis_string.py
import unittest class Solution: @staticmethod def checkValidString(s: str) -> bool: """ Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: Any l...
0.812459
0.778186
import glob import logging import os import sys import pyauto_functional # must be imported before pyauto import pyauto class ExtensionsPage(object): """Access options in extensions page (chrome://extensions-frame).""" _URL = 'chrome://extensions-frame' def __init__(self, driver): self._driver = driver ...
chrome/test/functional/extensions.py
import glob import logging import os import sys import pyauto_functional # must be imported before pyauto import pyauto class ExtensionsPage(object): """Access options in extensions page (chrome://extensions-frame).""" _URL = 'chrome://extensions-frame' def __init__(self, driver): self._driver = driver ...
0.685318
0.102215
from gauged.drivers import parse_dsn, SQLiteDriver from .test_case import TestCase class TestDSN(TestCase): '''Test the driver functions''' def test_stripping_dialect_from_schema(self): driver = parse_dsn('sqlite+foobar://')[0] self.assertIs(driver, SQLiteDriver) def test_unknown_driver...
test/test_dsn.py
from gauged.drivers import parse_dsn, SQLiteDriver from .test_case import TestCase class TestDSN(TestCase): '''Test the driver functions''' def test_stripping_dialect_from_schema(self): driver = parse_dsn('sqlite+foobar://')[0] self.assertIs(driver, SQLiteDriver) def test_unknown_driver...
0.536313
0.476032
# 执行用时:40 ms, 在所有 Python3 提交中击败了91.95%的用户 # 内存消耗:13.7 MB, 在所有 Python3 提交中击败了46.93%的用户 class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if head==None: return if head.next==None: return head if k<0: print(" k is negative number.")...
leetCode_Q61_rotateRight.py
# 执行用时:40 ms, 在所有 Python3 提交中击败了91.95%的用户 # 内存消耗:13.7 MB, 在所有 Python3 提交中击败了46.93%的用户 class Solution: def rotateRight(self, head: ListNode, k: int) -> ListNode: if head==None: return if head.next==None: return head if k<0: print(" k is negative number.")...
0.228587
0.29537
from django.test import TestCase, Client from rest_framework.test import force_authenticate, APIRequestFactory from django.urls import reverse import json from users.models import User from users.views import UsersList class TestProfile(TestCase): """ class to test the user models """ def setUp(self): ...
formoms/users/tests.py
from django.test import TestCase, Client from rest_framework.test import force_authenticate, APIRequestFactory from django.urls import reverse import json from users.models import User from users.views import UsersList class TestProfile(TestCase): """ class to test the user models """ def setUp(self): ...
0.669529
0.208945
import sys import uuid from xrt_binding import * # found in PYTHONPATH from ert_binding import * # found in PYTHONPATH sys.path.append('../') # utils_binding.py from utils_binding import * XHELLO_HELLO_CONTROL_ADDR_AP_CTRL = 0x00 XHELLO_HELLO_CONTROL_ADDR_GIE = 0x04 XHELLO_HELLO_CONTROL_ADDR_IER = 0x08 XHELLO_HELLO_CO...
tests/python/22_verify/22_verify.py
import sys import uuid from xrt_binding import * # found in PYTHONPATH from ert_binding import * # found in PYTHONPATH sys.path.append('../') # utils_binding.py from utils_binding import * XHELLO_HELLO_CONTROL_ADDR_AP_CTRL = 0x00 XHELLO_HELLO_CONTROL_ADDR_GIE = 0x04 XHELLO_HELLO_CONTROL_ADDR_IER = 0x08 XHELLO_HELLO_CO...
0.199542
0.090695
# pylint: disable=broad-except,invalid-name import os import sys import json import argparse from install import download_file from install import register_file from install import clai_installed from install import register_the_user from install import append_setup_to_file from install import install_orchestration f...
develop.py
# pylint: disable=broad-except,invalid-name import os import sys import json import argparse from install import download_file from install import register_file from install import clai_installed from install import register_the_user from install import append_setup_to_file from install import install_orchestration f...
0.232571
0.101991
import builtins import datetime from files_sdk.api import Api from files_sdk.list_obj import ListObj from files_sdk.exceptions import InvalidParameterError, MissingParameterError, NotImplementedError class InboxRecipient: default_attributes = { 'company': None, # string - The recipient's company. ...
files_sdk/models/inbox_recipient.py
import builtins import datetime from files_sdk.api import Api from files_sdk.list_obj import ListObj from files_sdk.exceptions import InvalidParameterError, MissingParameterError, NotImplementedError class InboxRecipient: default_attributes = { 'company': None, # string - The recipient's company. ...
0.609059
0.171755
import allure import pytest pytestmark = [pytest.mark.client_connectivity, pytest.mark.nat, pytest.mark.enterprise, pytest.mark.ttls, pytest.mark.ucentral, pytest.mark.sanity] #pytest.mark.usefixtures("setup_test_run"), setup_params_enterprise = { "mode": "NAT", "ssid_modes": { "wpa_ente...
tests/e2e/basic/validation_of_operating_modes/nat_mode/client_connectivity/test_enterprise_ttls.py
import allure import pytest pytestmark = [pytest.mark.client_connectivity, pytest.mark.nat, pytest.mark.enterprise, pytest.mark.ttls, pytest.mark.ucentral, pytest.mark.sanity] #pytest.mark.usefixtures("setup_test_run"), setup_params_enterprise = { "mode": "NAT", "ssid_modes": { "wpa_ente...
0.19729
0.46794
import pandas as pd from sklearn.model_selection import train_test_split import numpy as np from collections import Counter import tensorflow as tf import os import pickle import re from tensorflow.python.ops import math_ops from urllib.request import urlretrieve from os.path import isfile, isdir from tq...
movie_recommender.py
import pandas as pd from sklearn.model_selection import train_test_split import numpy as np from collections import Counter import tensorflow as tf import os import pickle import re from tensorflow.python.ops import math_ops from urllib.request import urlretrieve from os.path import isfile, isdir from tq...
0.367724
0.211335
import rospy from mavros_msgs.msg import PositionTarget from geometry_msgs.msg import PoseStamped, Point from arion.offboard import OffboardControl from arion.subscriber.point_subscriber import PointSubscriber from arion.subscriber.position_subscriber import CurrentPositionSubscriber class PositionControlRawNode(Off...
src/arion/node/position_control_raw_node.py
import rospy from mavros_msgs.msg import PositionTarget from geometry_msgs.msg import PoseStamped, Point from arion.offboard import OffboardControl from arion.subscriber.point_subscriber import PointSubscriber from arion.subscriber.position_subscriber import CurrentPositionSubscriber class PositionControlRawNode(Off...
0.463687
0.081301
import necrobot.exception from necrobot.botbase import server from necrobot.database import userdb from necrobot.util import console from necrobot.user.necrouser import NecroUser from necrobot.user.userprefs import UserPrefs # Libraries of checked out users user_library_by_uid = {} user_library_by_did = {} user_libra...
necrobot/user/userlib.py
import necrobot.exception from necrobot.botbase import server from necrobot.database import userdb from necrobot.util import console from necrobot.user.necrouser import NecroUser from necrobot.user.userprefs import UserPrefs # Libraries of checked out users user_library_by_uid = {} user_library_by_did = {} user_libra...
0.473657
0.074736
import numpy as np from scipy.optimize import fmin_slsqp import statsmodels.base.l1_solvers_common as l1_solvers_common def fit_l1_slsqp( f, score, start_params, args, kwargs, disp=False, maxiter=1000, callback=None, retall=False, full_output=False, hess=None): """ Solve the l1 regularized pro...
statsmodels/base/l1_slsqp.py
import numpy as np from scipy.optimize import fmin_slsqp import statsmodels.base.l1_solvers_common as l1_solvers_common def fit_l1_slsqp( f, score, start_params, args, kwargs, disp=False, maxiter=1000, callback=None, retall=False, full_output=False, hess=None): """ Solve the l1 regularized pro...
0.785884
0.523055
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import app from absl import flags from absl import logging from PIL import ImageColor import atlasmaker_io import convert import montage import parallelize # DEFAULT settings _DEFAULT_COL...
facets_atlasmaker/atlasmaker.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from absl import app from absl import flags from absl import logging from PIL import ImageColor import atlasmaker_io import convert import montage import parallelize # DEFAULT settings _DEFAULT_COL...
0.783699
0.129403
from spack import * class PySetuptools(PythonPackage): """A Python utility that aids in the process of downloading, building, upgrading, installing, and uninstalling Python packages.""" homepage = "https://github.com/pypa/setuptools" url = "https://pypi.io/packages/source/s/setuptools/setupt...
var/spack/repos/builtin/packages/py-setuptools/package.py
from spack import * class PySetuptools(PythonPackage): """A Python utility that aids in the process of downloading, building, upgrading, installing, and uninstalling Python packages.""" homepage = "https://github.com/pypa/setuptools" url = "https://pypi.io/packages/source/s/setuptools/setupt...
0.649801
0.23433
from flask import Flask from flask_restful import Api, Resource, reqparse, abort, fields, marshal_with from flask_sqlalchemy import SQLAlchemy if __name__ == "__main__": app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' db = SQLAlchemy(app) else: from flask_start imp...
quiz_api/quiz_api.py
from flask import Flask from flask_restful import Api, Resource, reqparse, abort, fields, marshal_with from flask_sqlalchemy import SQLAlchemy if __name__ == "__main__": app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' db = SQLAlchemy(app) else: from flask_start imp...
0.318379
0.083329
from unittest import TestCase from api.models import APIKey, Device, Manufacturer from tests.setup_tests import db, seed_db import datetime class APIKeyTestCase(TestCase): '''APIKey Test Case''' @classmethod def setUpClass(cls): seed_db() def test_validate(self): '''Test validation o...
tests/test_models.py
from unittest import TestCase from api.models import APIKey, Device, Manufacturer from tests.setup_tests import db, seed_db import datetime class APIKeyTestCase(TestCase): '''APIKey Test Case''' @classmethod def setUpClass(cls): seed_db() def test_validate(self): '''Test validation o...
0.752286
0.5919
from . import unittest, mock from architect import install, uninstall from architect.orms.bases import BaseFeature class BaseDecoratorTestCase(object): def setUp(self): with mock.patch('pkgutil.iter_modules') as modules: modules.return_value = [(None, 'foo', True)] self.foo_featur...
tests/test_decorators.py
from . import unittest, mock from architect import install, uninstall from architect.orms.bases import BaseFeature class BaseDecoratorTestCase(object): def setUp(self): with mock.patch('pkgutil.iter_modules') as modules: modules.return_value = [(None, 'foo', True)] self.foo_featur...
0.665737
0.217213
# The goal of this lesson is to develop your ability to look at some code and indentify its time complexity, using Big O notation. # Comparison computacional complexity import matplotlib.pyplot as plt from scipy.special import gamma import math import numpy as np n = np.linspace(1,101,100) O1 = gamma(n) O2 = 2**n O3 ...
src/efficiency/big_o_efficiency.py
# The goal of this lesson is to develop your ability to look at some code and indentify its time complexity, using Big O notation. # Comparison computacional complexity import matplotlib.pyplot as plt from scipy.special import gamma import math import numpy as np n = np.linspace(1,101,100) O1 = gamma(n) O2 = 2**n O3 ...
0.742328
0.769968
from .archive import archive from .archive_extension import archive_extension from bes.fs import file_util import os, os.path as path, stat, zipfile class archive_zip(archive): 'A Zip archive class.' def __init__(self, filename): super(archive_zip, self).__init__(filename) @classmethod #@abstractmethod...
lib/bes/archive2/caca_archive_zip.py
from .archive import archive from .archive_extension import archive_extension from bes.fs import file_util import os, os.path as path, stat, zipfile class archive_zip(archive): 'A Zip archive class.' def __init__(self, filename): super(archive_zip, self).__init__(filename) @classmethod #@abstractmethod...
0.464173
0.11479
import numpy as np import tensorflow as tf import tensorflow_probability as tfp from scipy.stats import multivariate_normal from abc import ABC, abstractmethod class Copula(ABC): @abstractmethod def __init__(self, dim): super(Copula, self).__init__() self.dim = dim @abstractmethod de...
copulas.py
import numpy as np import tensorflow as tf import tensorflow_probability as tfp from scipy.stats import multivariate_normal from abc import ABC, abstractmethod class Copula(ABC): @abstractmethod def __init__(self, dim): super(Copula, self).__init__() self.dim = dim @abstractmethod de...
0.798972
0.349311
from __future__ import print_function, absolute_import import os.path as osp class MSMT(object): def __init__(self, root, combine_all=True): self.images_dir = osp.join(root) self.combine_all = combine_all self.train_path = 'train' self.test_path = 'test' self.train_list_f...
trainCode/Source/reid/datasets/msmt_copy.py
from __future__ import print_function, absolute_import import os.path as osp class MSMT(object): def __init__(self, root, combine_all=True): self.images_dir = osp.join(root) self.combine_all = combine_all self.train_path = 'train' self.test_path = 'test' self.train_list_f...
0.409929
0.107157
import re from google.appengine.ext import ndb from model.flake.flake_issue import FlakeIssue _OS_REGEX_PATTERN_MAPPING = [(re.compile('os:mac', re.I), 'os:Mac'), (re.compile('os:linux', re.I), 'os:linux'), (re.compile('os:ubuntu', re.I), 'os:linux'), ...
appengine/findit/model/test_inventory.py
import re from google.appengine.ext import ndb from model.flake.flake_issue import FlakeIssue _OS_REGEX_PATTERN_MAPPING = [(re.compile('os:mac', re.I), 'os:Mac'), (re.compile('os:linux', re.I), 'os:linux'), (re.compile('os:ubuntu', re.I), 'os:linux'), ...
0.773302
0.319626
from __future__ import absolute_import from __future__ import unicode_literals import pytest from detect_secrets.core.potential_secret import PotentialSecret from detect_secrets.plugins.keyword import KeywordDetector from testing.mocks import mock_file_object QUOTES_REQUIRED_FILE_EXTENSIONS = ( '.cls', '.ja...
tests/plugins/keyword_test.py
from __future__ import absolute_import from __future__ import unicode_literals import pytest from detect_secrets.core.potential_secret import PotentialSecret from detect_secrets.plugins.keyword import KeywordDetector from testing.mocks import mock_file_object QUOTES_REQUIRED_FILE_EXTENSIONS = ( '.cls', '.ja...
0.338077
0.154983
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databas...
build/lib.macosx-10.9-x86_64-3.9/mediapipe/calculators/video/video_pre_stream_calculator_pb2.py
"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_databas...
0.362179
0.08141
import copy import json import os import urllib.parse import boto3 import hashlib from io import StringIO # -------------------------------------------------- # Initializes global variables # -------------------------------------------------- def init(): global s3, s3_client, stpfn_client, lambda_client, event_cl...
daas-core/lmd-ingest-invoker.py
import copy import json import os import urllib.parse import boto3 import hashlib from io import StringIO # -------------------------------------------------- # Initializes global variables # -------------------------------------------------- def init(): global s3, s3_client, stpfn_client, lambda_client, event_cl...
0.227298
0.053974
import copy import unittest import warnings import mock import numpy as np import pytest import chainer from chainer import backend from chainer.backends import cuda from chainer import optimizer from chainer import optimizers from chainer import serializer from chainer import testing from chainer.testing import attr...
tests/chainer_tests/test_optimizer.py
import copy import unittest import warnings import mock import numpy as np import pytest import chainer from chainer import backend from chainer.backends import cuda from chainer import optimizer from chainer import optimizers from chainer import serializer from chainer import testing from chainer.testing import attr...
0.537284
0.345574
from ..data import get_data from dataclasses import dataclass import numpy as np __all__ = [ "get_square_grid_neighbours", "CameraCoordinates", "SSTCameraMapping", ] def get_square_grid_neighbours(row, column, diagonal): """ Obtain the neighbours for a position on a square grid Parameters ...
sstcam_simulation/camera/mapping.py
from ..data import get_data from dataclasses import dataclass import numpy as np __all__ = [ "get_square_grid_neighbours", "CameraCoordinates", "SSTCameraMapping", ] def get_square_grid_neighbours(row, column, diagonal): """ Obtain the neighbours for a position on a square grid Parameters ...
0.941708
0.70108
from datetime import timedelta, date import datetime from pymongo import MongoClient import time class BasicSolver: def __init__(self): self.client = MongoClient('mongodb://localhost:27017/') self.db_GTFS = self.client.cota_gtfs self.db_time_stamps_set = set() self.db_time_stamps = ...
BasicSolver.py
from datetime import timedelta, date import datetime from pymongo import MongoClient import time class BasicSolver: def __init__(self): self.client = MongoClient('mongodb://localhost:27017/') self.db_GTFS = self.client.cota_gtfs self.db_time_stamps_set = set() self.db_time_stamps = ...
0.41182
0.156298
import argparse import datetime import warnings from urllib.error import HTTPError import pandas as pd import matplotlib import matplotlib.dates as mdates import matplotlib.pyplot as plt import src.utils as cutil parser = argparse.ArgumentParser() parser.add_argument( "--nd", dest="d", action="store_fals...
code/plotting/figED1.py
import argparse import datetime import warnings from urllib.error import HTTPError import pandas as pd import matplotlib import matplotlib.dates as mdates import matplotlib.pyplot as plt import src.utils as cutil parser = argparse.ArgumentParser() parser.add_argument( "--nd", dest="d", action="store_fals...
0.367838
0.280998
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.debug.lib import grpc_debug_test_server from tensorflow.python.debug.lib import session_debug_testlib...
vendor/github.com/tensorflow/tensorflow/tensorflow/python/debug/lib/grpc_large_data_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.python.debug.lib import grpc_debug_test_server from tensorflow.python.debug.lib import session_debug_testlib...
0.610802
0.186151
from __future__ import unicode_literals import uuid import mock from timesketch.lib import emojis from timesketch.lib import testlib from timesketch.lib.analyzers import chain from timesketch.lib.analyzers.chain_plugins import interface from timesketch.lib.analyzers.chain_plugins import manager class FakeEvent(ob...
timesketch/lib/analyzers/chain_test.py
from __future__ import unicode_literals import uuid import mock from timesketch.lib import emojis from timesketch.lib import testlib from timesketch.lib.analyzers import chain from timesketch.lib.analyzers.chain_plugins import interface from timesketch.lib.analyzers.chain_plugins import manager class FakeEvent(ob...
0.782413
0.200401
import random import os import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data from dataset.data_loader_emd import GetLoader from torchvision import datasets from torchvision import transforms from models.model_emd_1 import CNNModel import numpy as np from test_emd import test source...
train/main_emd.py
import random import os import torch.backends.cudnn as cudnn import torch.optim as optim import torch.utils.data from dataset.data_loader_emd import GetLoader from torchvision import datasets from torchvision import transforms from models.model_emd_1 import CNNModel import numpy as np from test_emd import test source...
0.556159
0.224757
# Hello! I,<NAME>, am the creator of this data-set and just wanted to provide a sample analysis for anyone interested in looking at CS. I look at mainly the pistol round here but many of the techniques can be applied to all types of rounds. There are many ways to analyze this dataset so I hope you can go off and answe...
cs go.py
# Hello! I,<NAME>, am the creator of this data-set and just wanted to provide a sample analysis for anyone interested in looking at CS. I look at mainly the pistol round here but many of the techniques can be applied to all types of rounds. There are many ways to analyze this dataset so I hope you can go off and answe...
0.428233
0.582016
from nengo.exceptions import SpaParseError from nengo.utils.numpy import is_number class Symbol: """A set of semantic pointer symbols and associated math. This is an abstract semantic pointer (not associated with a particular vocabulary or dimension). It is just meant for keeping track of the desire...
nengo/spa/action_objects.py
from nengo.exceptions import SpaParseError from nengo.utils.numpy import is_number class Symbol: """A set of semantic pointer symbols and associated math. This is an abstract semantic pointer (not associated with a particular vocabulary or dimension). It is just meant for keeping track of the desire...
0.920611
0.457318
import requests from lxml import html import json import datetime as dt import global_settings as gs import os if not gs.local: import boto3 from dynamodb_json import json_util as dyjson def daterange(start_date, end_date): """ Works the same as python's 'range' but...
src/get_articles_url.py
import requests from lxml import html import json import datetime as dt import global_settings as gs import os if not gs.local: import boto3 from dynamodb_json import json_util as dyjson def daterange(start_date, end_date): """ Works the same as python's 'range' but...
0.528533
0.181989
from st2tests.base import BaseSensorTestCase import laas import responses import json class LaaSSensorTest(BaseSensorTestCase): sensor_cls = laas.LaaS_Sensor def setUp(self): super(LaaSSensorTest, self).setUp() self.sensor = self.get_sensor_instance(config={ "dashboard": { ...
laas/tests/test_sensor_laas_api.py
from st2tests.base import BaseSensorTestCase import laas import responses import json class LaaSSensorTest(BaseSensorTestCase): sensor_cls = laas.LaaS_Sensor def setUp(self): super(LaaSSensorTest, self).setUp() self.sensor = self.get_sensor_instance(config={ "dashboard": { ...
0.413596
0.278985
__author__ = 'plandes' from typing import List, Dict, Tuple from dataclasses import dataclass, field import sys import logging import re from pathlib import Path from io import TextIOWrapper import bibtexparser from bibtexparser.bibdatabase import BibDatabase from bibtexparser.bwriter import BibTexWriter from bibtexpa...
src/python/zensols/bibstract/extractor.py
__author__ = 'plandes' from typing import List, Dict, Tuple from dataclasses import dataclass, field import sys import logging import re from pathlib import Path from io import TextIOWrapper import bibtexparser from bibtexparser.bibdatabase import BibDatabase from bibtexparser.bwriter import BibTexWriter from bibtexpa...
0.782704
0.215867
from __future__ import print_function from django.test import TestCase from django.test import Client from django.contrib.auth.models import User import mock import os import pytest import json # os.environ["NUM_BUDGET_YEARS"] = '2' from ...taxbrain.models import TaxSaveInputs from ...taxbrain.models import convert_to...
webapp/apps/dynamic/tests/test_ogusa.py
from __future__ import print_function from django.test import TestCase from django.test import Client from django.contrib.auth.models import User import mock import os import pytest import json # os.environ["NUM_BUDGET_YEARS"] = '2' from ...taxbrain.models import TaxSaveInputs from ...taxbrain.models import convert_to...
0.408277
0.206834
from __future__ import absolute_import, print_function import glob import os import subprocess import sys from codecs import open from setuptools import setup if sys.version_info < (2, 7): print("Python 2.7 or higher is required") sys.exit(1) description = "Create and validate BagIt packages" with open("R...
setup.py
from __future__ import absolute_import, print_function import glob import os import subprocess import sys from codecs import open from setuptools import setup if sys.version_info < (2, 7): print("Python 2.7 or higher is required") sys.exit(1) description = "Create and validate BagIt packages" with open("R...
0.337859
0.124293
from typing import cast from aries_cloudagent.core.profile import ProfileSession from aries_cloudagent.indy.holder import IndyHolderError from aries_cloudagent.indy.models.requested_creds import ( IndyRequestedCredsRequestedAttrSchema, IndyRequestedCredsRequestedPredSchema, ) from aries_cloudagent.ledger.error...
acapy_plugin_toolbox/holder/v0_1/messages/pres_request_approve.py
from typing import cast from aries_cloudagent.core.profile import ProfileSession from aries_cloudagent.indy.holder import IndyHolderError from aries_cloudagent.indy.models.requested_creds import ( IndyRequestedCredsRequestedAttrSchema, IndyRequestedCredsRequestedPredSchema, ) from aries_cloudagent.ledger.error...
0.832134
0.126111
from django import forms from django.conf import settings from django.db import connection import sqlite3 from biostar.recipes import const, models, util # Share the logger with models. logger = models.logger def float_field(data): numrange = data.get("range", [1.0, 100000.0]) min_value, max_value = numrang...
biostar/recipes/factory.py
from django import forms from django.conf import settings from django.db import connection import sqlite3 from biostar.recipes import const, models, util # Share the logger with models. logger = models.logger def float_field(data): numrange = data.get("range", [1.0, 100000.0]) min_value, max_value = numrang...
0.467089
0.19544
import logging from spacel.model.aws import VALID_REGIONS, INSTANCE_TYPES logger = logging.getLogger('spacel.model.orbit') NAT_CONFIGURATIONS = { 'disabled', # No NAT, don't even try 'enabled', # Single NAT gateway for every AZ (default) 'per-az' # NAT gateway per AZ (suggested for production) } cla...
src/spacel/model/orbit.py
import logging from spacel.model.aws import VALID_REGIONS, INSTANCE_TYPES logger = logging.getLogger('spacel.model.orbit') NAT_CONFIGURATIONS = { 'disabled', # No NAT, don't even try 'enabled', # Single NAT gateway for every AZ (default) 'per-az' # NAT gateway per AZ (suggested for production) } cla...
0.735452
0.126623
import argparse import cv2 import numpy as np import os import random import sys from glob import glob from scipy.spatial import cKDTree from skimage import color def get_cell_tree(cell_images): L_vector = [np.mean(im[:,:,0]) for im in cell_images] a_vector = [np.mean(im[:,:,1]) for im in cell_images] b_vector...
photomosaic.py
import argparse import cv2 import numpy as np import os import random import sys from glob import glob from scipy.spatial import cKDTree from skimage import color def get_cell_tree(cell_images): L_vector = [np.mean(im[:,:,0]) for im in cell_images] a_vector = [np.mean(im[:,:,1]) for im in cell_images] b_vector...
0.286668
0.354782
import time import torch import random import logging import numpy as np from model import VOGUE from args import get_parser from torchtext.data import BucketIterator from data.dataset import AnswerVerbalizationDataset from constants import * from utils import (SingleTaskLoss, MultiTaskLoss, Scorer...
test.py
import time import torch import random import logging import numpy as np from model import VOGUE from args import get_parser from torchtext.data import BucketIterator from data.dataset import AnswerVerbalizationDataset from constants import * from utils import (SingleTaskLoss, MultiTaskLoss, Scorer...
0.657209
0.188847
from __future__ import print_function import json import json5 import re import sys import copy # All site names appear to follow the pattern <type>_X<abs coord>Y<abs coord>. # Generally speaking, only the tile relatively coordinates are required to # assemble arch defs, so we re-origin the coordinates to be relative ...
fuzzers/074-dump_all/cleanup_site_pins.py
from __future__ import print_function import json import json5 import re import sys import copy # All site names appear to follow the pattern <type>_X<abs coord>Y<abs coord>. # Generally speaking, only the tile relatively coordinates are required to # assemble arch defs, so we re-origin the coordinates to be relative ...
0.50293
0.628635
import numpy as np from pyPDP.algorithms.pdp import PDP from pyPDP.blackbox_functions.synthetic_functions import Square, StyblinskiTang from pyPDP.sampler.bayesian_optimization import BayesianOptimizationSampler from pyPDP.utils.advanced_plots import plot_2D_ICE_Curve_with_confidence from tests import PlottableTest ...
tests/algorithms/test_pdp.py
import numpy as np from pyPDP.algorithms.pdp import PDP from pyPDP.blackbox_functions.synthetic_functions import Square, StyblinskiTang from pyPDP.sampler.bayesian_optimization import BayesianOptimizationSampler from pyPDP.utils.advanced_plots import plot_2D_ICE_Curve_with_confidence from tests import PlottableTest ...
0.758689
0.648007
from __future__ import absolute_import, division, print_function import os.path import Microsoft.Win32 as Win32 RegistryHive = Win32.RegistryHive RegistryView = Win32.RegistryView RegistryKey = Win32.RegistryKey RegistryValueKind = Win32.RegistryValueKind import System from System.Reflection import Assembly, Assemb...
installer/reg.py
from __future__ import absolute_import, division, print_function import os.path import Microsoft.Win32 as Win32 RegistryHive = Win32.RegistryHive RegistryView = Win32.RegistryView RegistryKey = Win32.RegistryKey RegistryValueKind = Win32.RegistryValueKind import System from System.Reflection import Assembly, Assemb...
0.560012
0.054224
import numpy as np from anchor_free import anchor_free_helper def test_get_loc_label(): inputs = np.array([0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0]) output = anchor_free_helper.get_loc_label(inputs) answer = np.array([[0, 0], [0, 0], [0, 0], ...
tests/anchor_free/test_anchor_free_helper.py
import numpy as np from anchor_free import anchor_free_helper def test_get_loc_label(): inputs = np.array([0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0]) output = anchor_free_helper.get_loc_label(inputs) answer = np.array([[0, 0], [0, 0], [0, 0], ...
0.594198
0.666931
# Created: Sat Dec 2 16:02:17 2000 # <EMAIL>, http://www.cbs.dtu.dk/thomas """BLAST code for graphical Xbbtools tool.""" from __future__ import print_function import os import tempfile import threading try: import tkMessageBox as messagebox # Python 2 except ImportError: from tkinter import messagebox #...
Scripts/xbbtools/xbb_blastbg.py
# Created: Sat Dec 2 16:02:17 2000 # <EMAIL>, http://www.cbs.dtu.dk/thomas """BLAST code for graphical Xbbtools tool.""" from __future__ import print_function import os import tempfile import threading try: import tkMessageBox as messagebox # Python 2 except ImportError: from tkinter import messagebox #...
0.699254
0.122078
"""this file is only for PaddleCloud""" import os import logging import paddle.fluid.contrib.utils.hdfs_utils as hdfs_utils logging.basicConfig( format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger("cloud") logger.setLevel(logging.INFO) def run(): cmd = "python -u train.py " ...
PaddleRec/ctr/cloud.py
"""this file is only for PaddleCloud""" import os import logging import paddle.fluid.contrib.utils.hdfs_utils as hdfs_utils logging.basicConfig( format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger("cloud") logger.setLevel(logging.INFO) def run(): cmd = "python -u train.py " ...
0.127002
0.074838
import logging import requests from . import AuthenticatedBaseException _LOGGER = logging.getLogger(__name__) PROVIDERS = {} def register_provider(classname): """Decorator used to register providers.""" PROVIDERS[classname.name] = classname return classname class GeoProvider: """GeoProvider class....
custom_components/authenticated/providers.py
import logging import requests from . import AuthenticatedBaseException _LOGGER = logging.getLogger(__name__) PROVIDERS = {} def register_provider(classname): """Decorator used to register providers.""" PROVIDERS[classname.name] = classname return classname class GeoProvider: """GeoProvider class....
0.837454
0.14851
import logging import time try: import unittest2 as unittest except ImportError: import unittest from M2Crypto import EVP, Rand, util from M2Crypto.AuthCookie import AuthCookie, AuthCookieJar, mix, unmix, unmix3 from M2Crypto.six.moves.http_cookies import SimpleCookie # pylint: disable=no-name-in-module,impor...
tests/test_authcookie.py
import logging import time try: import unittest2 as unittest except ImportError: import unittest from M2Crypto import EVP, Rand, util from M2Crypto.AuthCookie import AuthCookie, AuthCookieJar, mix, unmix, unmix3 from M2Crypto.six.moves.http_cookies import SimpleCookie # pylint: disable=no-name-in-module,impor...
0.421433
0.314573
from __future__ import print_function import argparse import sys from disco_aws_automation import DiscoElasticsearch from disco_aws_automation import DiscoESArchive from disco_aws_automation.disco_aws_util import run_gracefully, is_truthy from disco_aws_automation.disco_logging import configure_logging # R0912 Allow...
bin/disco_elasticsearch.py
from __future__ import print_function import argparse import sys from disco_aws_automation import DiscoElasticsearch from disco_aws_automation import DiscoESArchive from disco_aws_automation.disco_aws_util import run_gracefully, is_truthy from disco_aws_automation.disco_logging import configure_logging # R0912 Allow...
0.413477
0.131954
import pygame from pygame.locals import Rect from random import randint # game constants WIDTH = 1024 HEIGHT = 576 SCREEN_RECT = Rect(0, 0, WIDTH, HEIGHT) class BgLayer: def __init__(self, center_point, variability=100, speed=5, color=(0, 0, 0), bar_width=10): pygame.sprite.Sprite.__init...
parallax_city.py
import pygame from pygame.locals import Rect from random import randint # game constants WIDTH = 1024 HEIGHT = 576 SCREEN_RECT = Rect(0, 0, WIDTH, HEIGHT) class BgLayer: def __init__(self, center_point, variability=100, speed=5, color=(0, 0, 0), bar_width=10): pygame.sprite.Sprite.__init...
0.612426
0.18881
from nintendo.nex import common, streams import logging logger = logging.getLogger(__name__) class ClearCondition: NORMAL = 0 COLLECT_COINS = 4116396131 KILL_SKIPSQUEAKS = 4042480826 class CourseDifficulty: EASY = 0 STANDARD = 1 EXPERT = 2 SUPER_EXPERT = 3 class CourseOption: PLAY_STATS = 1 RATINGS = 2...
nintendo/nex/datastore_smm2.py
from nintendo.nex import common, streams import logging logger = logging.getLogger(__name__) class ClearCondition: NORMAL = 0 COLLECT_COINS = 4116396131 KILL_SKIPSQUEAKS = 4042480826 class CourseDifficulty: EASY = 0 STANDARD = 1 EXPERT = 2 SUPER_EXPERT = 3 class CourseOption: PLAY_STATS = 1 RATINGS = 2...
0.2304
0.151843
from pandas import DataFrame from .roc import roc from pandas_ta.utils import get_drift, get_offset, verify_series def kst(close, roc1=None, roc2=None, roc3=None, roc4=None, sma1=None, sma2=None, sma3=None, sma4=None, signal=None, drift=None, offset=None, **kwargs): """Indicator: 'Know Sure Thing' (KST)""" ...
pandas_ta/momentum/kst.py
from pandas import DataFrame from .roc import roc from pandas_ta.utils import get_drift, get_offset, verify_series def kst(close, roc1=None, roc2=None, roc3=None, roc4=None, sma1=None, sma2=None, sma3=None, sma4=None, signal=None, drift=None, offset=None, **kwargs): """Indicator: 'Know Sure Thing' (KST)""" ...
0.6705
0.341034
import logging import time import allure from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver import ActionChains from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriv...
builds/tests/source/ui/pages/base_page.py
import logging import time import allure from selenium.webdriver.remote.webelement import WebElement from selenium.webdriver import ActionChains from selenium.webdriver.remote.webdriver import WebDriver from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriv...
0.4856
0.131396
from typing import Dict, Generator, List, Tuple, Union from .jsonld import IndexerSchemaOrgProperties, IndexerJsonLdTags, IndexerSchemaOrgTypes from datalad.metadata.indexers.base import MetadataIndexer STUDYMINIMETA_FORMAT_NAME = 'metalad_studyminimeta' class StudyMiniMetaIds: PERSON_LIST = "#personList" ...
datalad_metalad/indexers/studyminimeta.py
from typing import Dict, Generator, List, Tuple, Union from .jsonld import IndexerSchemaOrgProperties, IndexerJsonLdTags, IndexerSchemaOrgTypes from datalad.metadata.indexers.base import MetadataIndexer STUDYMINIMETA_FORMAT_NAME = 'metalad_studyminimeta' class StudyMiniMetaIds: PERSON_LIST = "#personList" ...
0.831759
0.354685
import logging from snuggle import errors from .api_subset import APISubset logger = logging.getLogger("snuggle.mediawiki.api.pages") class Pages(APISubset): def _get_edit_token(self, page_name, access_token=None): doc = self.api.post( { 'action': "query", 'prop': "info|revisions", 'titles': pag...
snuggle/mediawiki/api/pages.py
import logging from snuggle import errors from .api_subset import APISubset logger = logging.getLogger("snuggle.mediawiki.api.pages") class Pages(APISubset): def _get_edit_token(self, page_name, access_token=None): doc = self.api.post( { 'action': "query", 'prop': "info|revisions", 'titles': pag...
0.19163
0.079424
from __future__ import absolute_import import lintreview.git as git import os from .test_github import config from nose.tools import eq_ from nose.tools import raises from unittest import skipIf settings = { 'WORKSPACE': './tests' } cant_write_to_test = not(os.access(os.path.abspath('./tests'), os.W_OK)) def te...
tests/test_git.py
from __future__ import absolute_import import lintreview.git as git import os from .test_github import config from nose.tools import eq_ from nose.tools import raises from unittest import skipIf settings = { 'WORKSPACE': './tests' } cant_write_to_test = not(os.access(os.path.abspath('./tests'), os.W_OK)) def te...
0.51562
0.227126
from federatedml.framework.homo.blocks.base import HomoTransferBase from federatedml.secureprotol.diffie_hellman import DiffieHellman from federatedml.util import consts class DHTransVar(HomoTransferBase): def __init__(self, server=(consts.ARBITER,), clients=(consts.GUEST, consts.HOST), prefix=None): supe...
python/federatedml/framework/homo/blocks/diffie_hellman.py
from federatedml.framework.homo.blocks.base import HomoTransferBase from federatedml.secureprotol.diffie_hellman import DiffieHellman from federatedml.util import consts class DHTransVar(HomoTransferBase): def __init__(self, server=(consts.ARBITER,), clients=(consts.GUEST, consts.HOST), prefix=None): supe...
0.611846
0.09782
import os,glob import sys,getopt class commandline: def __init__(self): opts,args = getopt.getopt(sys.argv[1:],'d:b:s:qh') opts = dict(opts) # default do not submit jod to HPC self.qsub = False self.level = 1 if '-h' in opts: self.printHe...
preproc/4_copy_mri_back.py
import os,glob import sys,getopt class commandline: def __init__(self): opts,args = getopt.getopt(sys.argv[1:],'d:b:s:qh') opts = dict(opts) # default do not submit jod to HPC self.qsub = False self.level = 1 if '-h' in opts: self.printHe...
0.05301
0.043752
from django.db.models import Prefetch, Q from rest_framework import exceptions, mixins, viewsets from rest_framework.decorators import action from rest_framework.response import Response from resolwe.flow.filters import DataFilter from resolwe.flow.models import Collection, Data, DescriptorSchema, Entity, Process fro...
resolwe/flow/views/data.py
from django.db.models import Prefetch, Q from rest_framework import exceptions, mixins, viewsets from rest_framework.decorators import action from rest_framework.response import Response from resolwe.flow.filters import DataFilter from resolwe.flow.models import Collection, Data, DescriptorSchema, Entity, Process fro...
0.743447
0.145722
import sys import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.utils import COMMASPACE, formatdate from email import encoders from PyQt5 import uic from PyQt5.QtWidgets import QApplication, QWidget WRONG_FILE = 1 PASS = 0 FILE_ERROR = -1 ACCESS_ERROR = -2 clas...
ComputerNetworks/lab6/main.py
import sys import smtplib from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.utils import COMMASPACE, formatdate from email import encoders from PyQt5 import uic from PyQt5.QtWidgets import QApplication, QWidget WRONG_FILE = 1 PASS = 0 FILE_ERROR = -1 ACCESS_ERROR = -2 clas...
0.16388
0.064036
import sys import json from firepro import * def usage(): print('parsewrestler.py wrestler.json') sys.exit(1) def main(): if len(sys.argv) != 2: usage() with open(sys.argv[1]) as json_file: wrestler_struct = json.load(json_file) print("===RENAME===") print("RENAME_last_name:...
parsewrestler.py
import sys import json from firepro import * def usage(): print('parsewrestler.py wrestler.json') sys.exit(1) def main(): if len(sys.argv) != 2: usage() with open(sys.argv[1]) as json_file: wrestler_struct = json.load(json_file) print("===RENAME===") print("RENAME_last_name:...
0.21684
0.080683
import os import pickle import matplotlib.pyplot as plt import numpy as np from keras.preprocessing.image import ImageDataGenerator, load_img from api_face.keras_vggface.vggface import VGGFace ''' vgg_conv = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) v...
api_face/pretrained-imagenet-models-classification.py
import os import pickle import matplotlib.pyplot as plt import numpy as np from keras.preprocessing.image import ImageDataGenerator, load_img from api_face.keras_vggface.vggface import VGGFace ''' vgg_conv = VGG16(weights='imagenet', include_top=False, input_shape=(224, 224, 3)) v...
0.52975
0.321673
# # Kubeflow pipeline # This is a fairly simple pipeline, containing sequential steps: # # 1. Update data - implemented by lightbend/kubeflow-datapublisher:0.0.1 image # 2. Run model training. Ideally we would run TFJob, but due to the current limitations for pipelines, we will directly use an image implementing trai...
pipelines/RecommenderPipeline.py
# # Kubeflow pipeline # This is a fairly simple pipeline, containing sequential steps: # # 1. Update data - implemented by lightbend/kubeflow-datapublisher:0.0.1 image # 2. Run model training. Ideally we would run TFJob, but due to the current limitations for pipelines, we will directly use an image implementing trai...
0.684475
0.377024
from django.test import TestCase from django.urls import reverse from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from common.models import InvenTreeSetting import json from datetime import datetime, timedelta from InvenTree.status_codes import StockStatus class StockVie...
InvenTree/stock/test_views.py
from django.test import TestCase from django.urls import reverse from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from common.models import InvenTreeSetting import json from datetime import datetime, timedelta from InvenTree.status_codes import StockStatus class StockVie...
0.518059
0.194942
import typing as t import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import StratifiedKFold from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis class MFELandma...
pymfe/landmarking.py
import typing as t import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import StratifiedKFold from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn.discriminant_analysis import LinearDiscriminantAnalysis class MFELandma...
0.920571
0.627267
import datetime import unittest import ddt import freezegun from ggrc.models import all_models from integration.ggrc import TestCase from integration.ggrc.api_helper import Api from integration.ggrc.access_control import acl_helper from integration.ggrc.models import factories from integration.ggrc_workflows import ...
test/integration/ggrc_workflows/test_workflow_api_calls.py
import datetime import unittest import ddt import freezegun from ggrc.models import all_models from integration.ggrc import TestCase from integration.ggrc.api_helper import Api from integration.ggrc.access_control import acl_helper from integration.ggrc.models import factories from integration.ggrc_workflows import ...
0.644001
0.254822
import unittest import numpy import tempfile from pyscf import lib, gto def make_ab(n): numpy.random.seed(1) a = numpy.random.random((n,n)) + numpy.eye(n) * 2 b = numpy.random.random(n) adiag = a.diagonal() x0 = b / adiag arest = a - numpy.diag(adiag) return a, b, adiag, arest, x0 class ...
pyscf/lib/test/test_diis.py
import unittest import numpy import tempfile from pyscf import lib, gto def make_ab(n): numpy.random.seed(1) a = numpy.random.random((n,n)) + numpy.eye(n) * 2 b = numpy.random.random(n) adiag = a.diagonal() x0 = b / adiag arest = a - numpy.diag(adiag) return a, b, adiag, arest, x0 class ...
0.467089
0.609146
import argparse import math import psycopg2 import sys import re parser = argparse.ArgumentParser() parser.add_argument("--dbname", action="store", required=True, help="Database to which the script will connect.") parser.add_argument("--port", action="store", type=int, default=5432, help="Port of the postmaster.") par...
analysis/dynamic/new/prepareDataset.py
import argparse import math import psycopg2 import sys import re parser = argparse.ArgumentParser() parser.add_argument("--dbname", action="store", required=True, help="Database to which the script will connect.") parser.add_argument("--port", action="store", type=int, default=5432, help="Port of the postmaster.") par...
0.34798
0.257978
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from side_scroller.game import Game import pygame from side_scroller.settings import GameSettings def display_player_death_animation(current_game: Game): obstacles_in_player_path_y = [(obstacle.image, obstacle.rect) for obsta...
side_scroller/death_animation.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from side_scroller.game import Game import pygame from side_scroller.settings import GameSettings def display_player_death_animation(current_game: Game): obstacles_in_player_path_y = [(obstacle.image, obstacle.rect) for obsta...
0.794505
0.106877
import os import unittest import nlgeval from nlgeval import NLGEval class TestNlgEval(unittest.TestCase): @classmethod def setUpClass(cls): cls.n = NLGEval() def test_compute_individual_metrics(self): scores = self.n.compute_individual_metrics(ref=["this is a test", ...
utils/nlg_eval/nlgeval/tests/test_nlgeval.py
import os import unittest import nlgeval from nlgeval import NLGEval class TestNlgEval(unittest.TestCase): @classmethod def setUpClass(cls): cls.n = NLGEval() def test_compute_individual_metrics(self): scores = self.n.compute_individual_metrics(ref=["this is a test", ...
0.681303
0.768928
import numpy as np import datetime import multiprocessing as mp from prep.cheb import Process_Point_Cheb from prep.smoothing import Smoothing def Preprocess_derivatives(field, steps = None, output_file_name = None, smooth = True, mp_poolsize = 4, max_order = 2, polynomial_window = 9, poly_order = None): ''' ...
estar/prep/derivatives_scaling.py
import numpy as np import datetime import multiprocessing as mp from prep.cheb import Process_Point_Cheb from prep.smoothing import Smoothing def Preprocess_derivatives(field, steps = None, output_file_name = None, smooth = True, mp_poolsize = 4, max_order = 2, polynomial_window = 9, poly_order = None): ''' ...
0.517083
0.531149
import sys, os from basic.constant import ROOT_PATH from basic.common import makedirsforfile,checkToSkip,printStatus from basic.annotationtable import readConcepts,readAnnotationsFrom from liblinear193.python.liblinearutil import train as liblinear_train from fastlinear import liblinear_to_fastlinear, fastlinear_save...
model_based/svms/fastlinear/trainLinearConcepts.py
import sys, os from basic.constant import ROOT_PATH from basic.common import makedirsforfile,checkToSkip,printStatus from basic.annotationtable import readConcepts,readAnnotationsFrom from liblinear193.python.liblinearutil import train as liblinear_train from fastlinear import liblinear_to_fastlinear, fastlinear_save...
0.214774
0.348534
{ ' Assessment Series Details': ' Assessment Series Details', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '# of International Staff'...
languages/en-gb.py
{ ' Assessment Series Details': ' Assessment Series Details', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '# of International Staff'...
0.612194
0.566738
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.p...
python/istio_api/broker/dev/service_plan_pb2.py
import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database from google.p...
0.194062
0.103115
from mock import patch from django.test import override_settings from django.utils.timezone import now as timezone_now from zerver.lib.test_classes import ZulipTestCase from zerver.lib.exceptions import JsonableError from zerver.lib.test_helpers import use_s3_backend from zerver.models import RealmAuditLog from zerv...
zerver/tests/test_realm_export.py
from mock import patch from django.test import override_settings from django.utils.timezone import now as timezone_now from zerver.lib.test_classes import ZulipTestCase from zerver.lib.exceptions import JsonableError from zerver.lib.test_helpers import use_s3_backend from zerver.models import RealmAuditLog from zerv...
0.448185
0.263238
import os import re import sys if sys.version_info >= (3,): import urllib.parse as urlparse else: import urlparse import zlib from http_parser.util import (b, bytes_to_str, IOrderedDict, StringIO, unquote, MAXSIZE) METHOD_RE = re.compile("[A-Z0-9$-_.]{3,20}") VERSION_RE = re.compile("HTTP/(\d+).(\...
http_parser/pyparser.py
import os import re import sys if sys.version_info >= (3,): import urllib.parse as urlparse else: import urlparse import zlib from http_parser.util import (b, bytes_to_str, IOrderedDict, StringIO, unquote, MAXSIZE) METHOD_RE = re.compile("[A-Z0-9$-_.]{3,20}") VERSION_RE = re.compile("HTTP/(\d+).(\...
0.335351
0.141875
import Alignment.MillePedeAlignmentAlgorithm.mpslib.Mpslibclass as mpslib import re import os import argparse lib = mpslib.jobdatabase() ## Parse arguments ## ----------------------------------------------------------------------------- parser = argparse.ArgumentParser( description='Produce Config for Pede-job f...
Alignment/MillePedeAlignmentAlgorithm/scripts/mps_merge.py
import Alignment.MillePedeAlignmentAlgorithm.mpslib.Mpslibclass as mpslib import re import os import argparse lib = mpslib.jobdatabase() ## Parse arguments ## ----------------------------------------------------------------------------- parser = argparse.ArgumentParser( description='Produce Config for Pede-job f...
0.258232
0.107297
from spack import * import os class Xsdktrilinos(CMakePackage): """xSDKTrilinos contains the portions of Trilinos that depend on PETSc because they would cause a circular dependency if built as part of Trilinos. """ homepage = "https://trilinos.org/" url = "https://github.com/trilinos/xS...
var/spack/repos/builtin/packages/xsdktrilinos/package.py
from spack import * import os class Xsdktrilinos(CMakePackage): """xSDKTrilinos contains the portions of Trilinos that depend on PETSc because they would cause a circular dependency if built as part of Trilinos. """ homepage = "https://trilinos.org/" url = "https://github.com/trilinos/xS...
0.572603
0.149935
import random from nvflare.apis.client import Client from nvflare.apis.fl_context import FLContext from nvflare.apis.impl.controller import ClientTask, Controller, Task from nvflare.apis.shareable import Shareable from nvflare.apis.signal import Signal from nvflare.app_common.abstract.learnable_persistor import Learn...
nvflare/app_common/workflows/cyclic_ctl.py
import random from nvflare.apis.client import Client from nvflare.apis.fl_context import FLContext from nvflare.apis.impl.controller import ClientTask, Controller, Task from nvflare.apis.shareable import Shareable from nvflare.apis.signal import Signal from nvflare.app_common.abstract.learnable_persistor import Learn...
0.7324
0.152916
import base64 import json import codecs from .. import identifiers, msg_type, property_enumeration, command_with_properties from ..properties import hmproperty import logging log = logging.getLogger('hmkit.autoapi') class IgnitionState(command_with_properties.CommandWithProperties): """ Handle Ignition Sta...
hmkit/autoapi/commands/ignition_state.py
import base64 import json import codecs from .. import identifiers, msg_type, property_enumeration, command_with_properties from ..properties import hmproperty import logging log = logging.getLogger('hmkit.autoapi') class IgnitionState(command_with_properties.CommandWithProperties): """ Handle Ignition Sta...
0.348756
0.091382
# standard library imports import argparse import textwrap import sys # NOQA importing sys so I can mock sys.argv in tests from pandashells.lib import module_checker_lib, arg_lib module_checker_lib.check_for_modules(['pandas']) from pandashells.lib import io_lib import pandas as pd import numpy as np # want dif...
pandashells/bin/p_rand.py
# standard library imports import argparse import textwrap import sys # NOQA importing sys so I can mock sys.argv in tests from pandashells.lib import module_checker_lib, arg_lib module_checker_lib.check_for_modules(['pandas']) from pandashells.lib import io_lib import pandas as pd import numpy as np # want dif...
0.586049
0.441733
EYE_LOOK_IN_LEFT = "eyeLookInLeft" EYE_LOOK_OUT_LEFT = "eyeLookOutLeft" EYE_LOOK_DOWN_LEFT = "eyeLookDownLeft" EYE_LOOK_UP_LEFT = "eyeLookUpLeft" EYE_BLINK_LEFT = "eyeBlinkLeft" EYE_SQUINT_LEFT = "eyeSquintLeft" EYE_WIDE_LEFT = "eyeWideLeft" EYE_LOOK_IN_RIGHT = "eyeLookInRight" EYE_LOOK_OUT_RIGHT = "eyeLookOutRight" EY...
tha2/mocap/ifacialmocap_constants.py
EYE_LOOK_IN_LEFT = "eyeLookInLeft" EYE_LOOK_OUT_LEFT = "eyeLookOutLeft" EYE_LOOK_DOWN_LEFT = "eyeLookDownLeft" EYE_LOOK_UP_LEFT = "eyeLookUpLeft" EYE_BLINK_LEFT = "eyeBlinkLeft" EYE_SQUINT_LEFT = "eyeSquintLeft" EYE_WIDE_LEFT = "eyeWideLeft" EYE_LOOK_IN_RIGHT = "eyeLookInRight" EYE_LOOK_OUT_RIGHT = "eyeLookOutRight" EY...
0.323487
0.120284
import typing from pathlib import Path import dask.distributed class DummyFuture(dask.distributed.Future): """ A class that mimics a distributed Future, the outcome of performing submit on a distributed client. """ def __init__(self, result: typing.Any) -> None: self._result = result # t...
autoPyTorch/utils/single_thread_client.py
import typing from pathlib import Path import dask.distributed class DummyFuture(dask.distributed.Future): """ A class that mimics a distributed Future, the outcome of performing submit on a distributed client. """ def __init__(self, result: typing.Any) -> None: self._result = result # t...
0.73914
0.52007
import cv2 import re import numpy as np import pytesseract import tesserocr from myPackage import tools as tl from matplotlib import pyplot as plt from os.path import basename, getsize from PIL import Image from sklearn.cluster import KMeans def validateImage(nameImage, training= False): if getsize(nameImage) != ...
myPackage/crotalProcessing.py
import cv2 import re import numpy as np import pytesseract import tesserocr from myPackage import tools as tl from matplotlib import pyplot as plt from os.path import basename, getsize from PIL import Image from sklearn.cluster import KMeans def validateImage(nameImage, training= False): if getsize(nameImage) != ...
0.47658
0.313499
import socket import hashlib import sys # RBN client class Client: server: str = "telnet.reversebeacon.net" port: int = 7000 def connect(self, call: str): # Open socket and connect self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__sock.connect((self.server, s...
dxmon/gethash.py
import socket import hashlib import sys # RBN client class Client: server: str = "telnet.reversebeacon.net" port: int = 7000 def connect(self, call: str): # Open socket and connect self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__sock.connect((self.server, s...
0.338296
0.252047
import itertools import torch import torch.nn as nn from jactorch.functional import broadcast from ._utils import exclude_mask, mask_value __all__ = ['Expander', 'Reducer', 'Permutation'] class Expander(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim def forward(se...
jactorch/nn/neural_logic/modules/dimension.py
import itertools import torch import torch.nn as nn from jactorch.functional import broadcast from ._utils import exclude_mask, mask_value __all__ = ['Expander', 'Reducer', 'Permutation'] class Expander(nn.Module): def __init__(self, dim): super().__init__() self.dim = dim def forward(se...
0.900683
0.40116
import rospy import ros_numpy import numpy as np import copy import json import os import sys import torch import yaml import time from std_msgs.msg import Header import sensor_msgs.point_cloud2 as pc2 from nav_msgs.msg import Odometry from sensor_msgs.msg import PointCloud2, PointField from jsk_recognition_msgs.msg i...
tools/multi_sweep_inference.py
import rospy import ros_numpy import numpy as np import copy import json import os import sys import torch import yaml import time from std_msgs.msg import Header import sensor_msgs.point_cloud2 as pc2 from nav_msgs.msg import Odometry from sensor_msgs.msg import PointCloud2, PointField from jsk_recognition_msgs.msg i...
0.512449
0.313499
from typing import Union, Dict, Optional, List from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import] # Disable insecure warnings requests.packages.urllib3.disable_warnings() INTEGRATION_CONTEXT_BRAND = "DeHashed" BASE_URL = "https://api.dehashed.com/" RESULTS_FROM = 1 RESULTS_TO = 50 class Clie...
Packs/DeHashed/Integrations/DeHashed/DeHashed.py
from typing import Union, Dict, Optional, List from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import] # Disable insecure warnings requests.packages.urllib3.disable_warnings() INTEGRATION_CONTEXT_BRAND = "DeHashed" BASE_URL = "https://api.dehashed.com/" RESULTS_FROM = 1 RESULTS_TO = 50 class Clie...
0.908879
0.283786
from .format_types import Font, Alignment, Color import warnings from .defines import TagType # TODO: text style supported as 4th field on Font obj. How does text_style work? # * is /TS:style/ tag only shorthand for /F:::style/? # * is it toggle bitfield or overwrite? # * what happens if calling /END:TS/ after /F/ or ...
src/format.py
from .format_types import Font, Alignment, Color import warnings from .defines import TagType # TODO: text style supported as 4th field on Font obj. How does text_style work? # * is /TS:style/ tag only shorthand for /F:::style/? # * is it toggle bitfield or overwrite? # * what happens if calling /END:TS/ after /F/ or ...
0.266166
0.211173