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 annotations from datetime import timedelta import logging from typing import Any, Generic, cast from hahomematic.const import HmEntityUsage from hahomematic.entity import ( CallbackEntity, CustomEntity, GenericEntity, GenericSystemVariable, ) from homeassistant.core import call...
custom_components/homematicip_local/generic_entity.py
from __future__ import annotations from datetime import timedelta import logging from typing import Any, Generic, cast from hahomematic.const import HmEntityUsage from hahomematic.entity import ( CallbackEntity, CustomEntity, GenericEntity, GenericSystemVariable, ) from homeassistant.core import call...
0.887802
0.09709
from PyQt5.QtCore import QObject, pyqtSignal from multiprocessing import cpu_count, Pool import time from drawDataProcessUtils import * class CalDrawData(QObject): sbar = pyqtSignal(str) pbar = pyqtSignal(int) tbw = pyqtSignal(str) run_end = pyqtSignal() logger = MyLog("CalDrawData", BASEDIR) ...
basic_analysis_module/calDrawData.py
from PyQt5.QtCore import QObject, pyqtSignal from multiprocessing import cpu_count, Pool import time from drawDataProcessUtils import * class CalDrawData(QObject): sbar = pyqtSignal(str) pbar = pyqtSignal(int) tbw = pyqtSignal(str) run_end = pyqtSignal() logger = MyLog("CalDrawData", BASEDIR) ...
0.453262
0.18717
import voluptuous as vol from esphome import pins from esphome.components import light from esphome.components.light import AddressableLight from esphome.components.power_supply import PowerSupplyComponent import esphome.config_validation as cv from esphome.const import CONF_CLOCK_PIN, CONF_COLOR_CORRECT, CONF_DATA_PI...
esphome/components/light/neopixelbus.py
import voluptuous as vol from esphome import pins from esphome.components import light from esphome.components.light import AddressableLight from esphome.components.power_supply import PowerSupplyComponent import esphome.config_validation as cv from esphome.const import CONF_CLOCK_PIN, CONF_COLOR_CORRECT, CONF_DATA_PI...
0.501709
0.125039
import urllib.request import urllib.parse import re import pathlib from html.parser import HTMLParser from html.entities import name2codepoint BASE_URL = "https://ga-covid19.ondemand.sas.com/" PATTERN = re.compile(r"JSON.parse\('(.*?)'\)") FILENAME = [ "timestamp", "county_history", "county_totals", "...
fetch.py
import urllib.request import urllib.parse import re import pathlib from html.parser import HTMLParser from html.entities import name2codepoint BASE_URL = "https://ga-covid19.ondemand.sas.com/" PATTERN = re.compile(r"JSON.parse\('(.*?)'\)") FILENAME = [ "timestamp", "county_history", "county_totals", "...
0.380644
0.176867
import logging from datetime import datetime, timezone from flask import current_app as app from flask import Blueprint, flash, render_template, request, redirect, url_for from flask_login import login_required from flask_paginate import Pagination from iso8601 import parse_date from structlog import wrap_logger from...
response_operations_ui/views/reporting_units.py
import logging from datetime import datetime, timezone from flask import current_app as app from flask import Blueprint, flash, render_template, request, redirect, url_for from flask_login import login_required from flask_paginate import Pagination from iso8601 import parse_date from structlog import wrap_logger from...
0.375936
0.302897
import argparse import logging import plistlib import psycopg2 DEFAULT_LIBRARY_FILE_LOCATION = '/Users/stephan/Music/iTunes/iTunes Music Library.xml' DEFAULT_DATABASE_NAME = 'music' DEFAULT_SCHEMA_NAME = 'public' DEFAULT_USER_NAME = 'postgres' DEFAULT_PASSWORD = '<PASSWORD>' DEFAULT_PORT = 5432 TEMPORARY_TABLE_NAME...
import-to-postgres.py
import argparse import logging import plistlib import psycopg2 DEFAULT_LIBRARY_FILE_LOCATION = '/Users/stephan/Music/iTunes/iTunes Music Library.xml' DEFAULT_DATABASE_NAME = 'music' DEFAULT_SCHEMA_NAME = 'public' DEFAULT_USER_NAME = 'postgres' DEFAULT_PASSWORD = '<PASSWORD>' DEFAULT_PORT = 5432 TEMPORARY_TABLE_NAME...
0.310694
0.068413
import os, sys from sqlalchemy import func from codes.upbit.recorder.upbit_price_collector import get_coin_price_class, db_session, Unit, local_fmt, get_price idx = os.getcwd().index("trade") PROJECT_HOME = os.getcwd()[:idx] + "trade" sys.path.append(PROJECT_HOME) from codes.upbit.upbit_api import Upbit from common...
codes/upbit/recorder/upbit_price_past_collector.py
import os, sys from sqlalchemy import func from codes.upbit.recorder.upbit_price_collector import get_coin_price_class, db_session, Unit, local_fmt, get_price idx = os.getcwd().index("trade") PROJECT_HOME = os.getcwd()[:idx] + "trade" sys.path.append(PROJECT_HOME) from codes.upbit.upbit_api import Upbit from common...
0.187318
0.139983
import tkinter as tk from tkinter import filedialog from tkinter.simpledialog import askinteger from PIL import Image, ImageTk import numpy as np import matplotlib.pyplot as plt import random import math from scipy import misc import os root = tk.Tk() root.title('AIP 60947061s') screen_width = root.winfo_screenwidth()...
Advanced Image Processing/HW6/HW6 60947061s.py
import tkinter as tk from tkinter import filedialog from tkinter.simpledialog import askinteger from PIL import Image, ImageTk import numpy as np import matplotlib.pyplot as plt import random import math from scipy import misc import os root = tk.Tk() root.title('AIP 60947061s') screen_width = root.winfo_screenwidth()...
0.147863
0.150528
import pytest from pytest import approx import numpy as np import quimb as qu import quimb.tensor as qtn from quimb.tensor.tensor_1d_tebd import OTOC_local class TestTEBD: def test_setup_and_sweep(self): n = 10 H_int = qu.ham_heis(n=2, cyclic=False) psi0 = qtn.MPS_neel_state(n, dtype=com...
tests/test_tensor/test_tensor_tebd.py
import pytest from pytest import approx import numpy as np import quimb as qu import quimb.tensor as qtn from quimb.tensor.tensor_1d_tebd import OTOC_local class TestTEBD: def test_setup_and_sweep(self): n = 10 H_int = qu.ham_heis(n=2, cyclic=False) psi0 = qtn.MPS_neel_state(n, dtype=com...
0.641198
0.671504
from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer import json class LobbyConsumer(WebsocketConsumer): def connect(self): self.room_name = 'lobby' self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.cha...
lobby/consumers.py
from asgiref.sync import async_to_sync from channels.generic.websocket import WebsocketConsumer import json class LobbyConsumer(WebsocketConsumer): def connect(self): self.room_name = 'lobby' self.room_group_name = 'chat_%s' % self.room_name # Join room group async_to_sync(self.cha...
0.3863
0.065965
from copy import deepcopy from random import sample, choice from BucketLib.bucket import Bucket from cb_tools.cb_cli import CbCli from constants.sdk_constants.java_client import SDKConstants from couchbase_helper.documentgenerator import doc_generator from couchbase_helper.durability_helper import BucketDurability fro...
pytests/epengine/bucket_level_durability.py
from copy import deepcopy from random import sample, choice from BucketLib.bucket import Bucket from cb_tools.cb_cli import CbCli from constants.sdk_constants.java_client import SDKConstants from couchbase_helper.documentgenerator import doc_generator from couchbase_helper.durability_helper import BucketDurability fro...
0.531209
0.091829
import json from django.test import TestCase from unittest.mock import Mock from silk.model_factory import RequestModelFactory, ResponseModelFactory DJANGO_META_CONTENT_TYPE = 'CONTENT_TYPE' HTTP_CONTENT_TYPE = 'Content-Type' CLEANSED = RequestModelFactory.CLEANSED_SUBSTITUTE class MaskCredentialsInFormsTest(Test...
project/tests/test_sensitive_data_in_request.py
import json from django.test import TestCase from unittest.mock import Mock from silk.model_factory import RequestModelFactory, ResponseModelFactory DJANGO_META_CONTENT_TYPE = 'CONTENT_TYPE' HTTP_CONTENT_TYPE = 'Content-Type' CLEANSED = RequestModelFactory.CLEANSED_SUBSTITUTE class MaskCredentialsInFormsTest(Test...
0.562177
0.304998
import gc import os import statistics import sys import textwrap import time from argparse import Namespace from operator import attrgetter import click MAX_DAG_RUNS_ALLOWED = 1 class ShortCircuitExecutorMixin: """ Mixin class to manage the scheduler state during the performance test run. """ def __...
scripts/perf/scheduler_dag_execution_timing.py
import gc import os import statistics import sys import textwrap import time from argparse import Namespace from operator import attrgetter import click MAX_DAG_RUNS_ALLOWED = 1 class ShortCircuitExecutorMixin: """ Mixin class to manage the scheduler state during the performance test run. """ def __...
0.563138
0.364042
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djstripe', '0024_auto_20170308_0757'), ] operations = [ migrations.AlterField( model_name='account', name='created', ...
djstripe/migrations/0025_auto_20170322_0428.py
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djstripe', '0024_auto_20170308_0757'), ] operations = [ migrations.AlterField( model_name='account', name='created', ...
0.729423
0.158207
__author__ = 'VMware, Inc.' __copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.' # pylint: disable=line-too-long import requests from com.vmware.cis_client import Session from vmware.vapi.bindings.stub import ApiClient from vmware.vapi.bindings.stub import StubFactoryBase from vmware.vapi.lib....
vmware/vapi/vsphere/client.py
__author__ = 'VMware, Inc.' __copyright__ = 'Copyright 2017 VMware, Inc. All rights reserved.' # pylint: disable=line-too-long import requests from com.vmware.cis_client import Session from vmware.vapi.bindings.stub import ApiClient from vmware.vapi.bindings.stub import StubFactoryBase from vmware.vapi.lib....
0.653238
0.057812
from commands.autoformat import AutoPep8 from handlers.autoformat_handler import AutoFormatHandler _code = '''import math, sys; def example1(): ####This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wr...
sublime-packages/Anaconda/test/test_autoformat.py
from commands.autoformat import AutoPep8 from handlers.autoformat_handler import AutoFormatHandler _code = '''import math, sys; def example1(): ####This is a long comment. This should be wrapped to fit within 72 characters. some_tuple=( 1,2, 3,'a' ); some_variable={'long':'Long code lines should be wr...
0.407451
0.262381
from collections import OrderedDict import warnings import numpy as np from jax import random import jax.numpy as jnp import numpyro from numpyro.distributions.distribution import COERCIONS from numpyro.primitives import ( _PYRO_STACK, CondIndepStackFrame, Messenger, apply_stack, plate, ) from nu...
numpyro/handlers.py
from collections import OrderedDict import warnings import numpy as np from jax import random import jax.numpy as jnp import numpyro from numpyro.distributions.distribution import COERCIONS from numpyro.primitives import ( _PYRO_STACK, CondIndepStackFrame, Messenger, apply_stack, plate, ) from nu...
0.832713
0.373476
import time import os from cooka.common import util, dataset_util from cooka.common.consts import BATCH_PREDICTION_COL from cooka.common.log import log_core as logger from cooka.common import client from cooka.common import consts from cooka.common.model import AnalyzeStep, JobStep, PredictStepType, Model, Feature, Mo...
cooka/core/batch_predict_job.py
import time import os from cooka.common import util, dataset_util from cooka.common.consts import BATCH_PREDICTION_COL from cooka.common.log import log_core as logger from cooka.common import client from cooka.common import consts from cooka.common.model import AnalyzeStep, JobStep, PredictStepType, Model, Feature, Mo...
0.282295
0.151404
import math import torch class Graft(torch.optim.Optimizer): """Grafted meta-optimizer for disentanglement of optimizers and implicit step size schedules. Takes black-box optimizers M and D, and grafts the norm of M's update with the normalized step direction of D's update, with in-place operations. ...
optimetry/graft.py
import math import torch class Graft(torch.optim.Optimizer): """Grafted meta-optimizer for disentanglement of optimizers and implicit step size schedules. Takes black-box optimizers M and D, and grafts the norm of M's update with the normalized step direction of D's update, with in-place operations. ...
0.864968
0.646851
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_io.core.python.ops import core_ops def decode_dicom_image( contents, color_dim=False, on_error='skip', scale='preserve', dtype=tf.uint16, name=No...
tensorflow_io/core/python/ops/dicom_ops.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from tensorflow_io.core.python.ops import core_ops def decode_dicom_image( contents, color_dim=False, on_error='skip', scale='preserve', dtype=tf.uint16, name=No...
0.924688
0.880232
import frappe from frappe import _ from chat.utils import get_full_name import ast @frappe.whitelist() def get(email): """Get all the rooms for a user Args: email (str): Email of user requests all rooms """ room_doctype = frappe.qb.DocType('Chat Room') all_rooms = ( frappe.qb.f...
chat/api/room.py
import frappe from frappe import _ from chat.utils import get_full_name import ast @frappe.whitelist() def get(email): """Get all the rooms for a user Args: email (str): Email of user requests all rooms """ room_doctype = frappe.qb.DocType('Chat Room') all_rooms = ( frappe.qb.f...
0.419053
0.159675
async def test_event_deletion(container): """Check event deletion.""" newsfeed_id = '123' event_dispatcher_service = container.event_dispatcher_service() event_processor_service = container.event_processor_service() event_1 = await _process_new_event( event_dispatcher_service, even...
tests/unit/domain/test_event_deletion.py
async def test_event_deletion(container): """Check event deletion.""" newsfeed_id = '123' event_dispatcher_service = container.event_dispatcher_service() event_processor_service = container.event_processor_service() event_1 = await _process_new_event( event_dispatcher_service, even...
0.651577
0.18756
import json import logging from affine import Affine import numpy as np from numpy.testing import assert_almost_equal import pytest import rasterio from rasterio.control import GroundControlPoint from rasterio.crs import CRS from rasterio.enums import Resampling from rasterio.env import GDALVersion from rasterio.err...
tests/test_warp.py
import json import logging from affine import Affine import numpy as np from numpy.testing import assert_almost_equal import pytest import rasterio from rasterio.control import GroundControlPoint from rasterio.crs import CRS from rasterio.enums import Resampling from rasterio.env import GDALVersion from rasterio.err...
0.698535
0.310289
import glob import os import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element import json START_BOUNDING_BOX_ID = 0 START_IMAGE_ID = 0 PRE_DEFINE_CATEGORIES = {"DaoXianYiWu": 0, "DiaoChe": 1, "ShiGongJiXie": 2, "TaDiao": 3, "YanHuo":4} # PRE_DEFINE_CATEGORIES = {"GanTa": 0} # PRE_DEFINE_CATEGORIE...
tools/dataset_analysis/xml2coco_new.py
import glob import os import xml.etree.ElementTree as ET from xml.etree.ElementTree import Element import json START_BOUNDING_BOX_ID = 0 START_IMAGE_ID = 0 PRE_DEFINE_CATEGORIES = {"DaoXianYiWu": 0, "DiaoChe": 1, "ShiGongJiXie": 2, "TaDiao": 3, "YanHuo":4} # PRE_DEFINE_CATEGORIES = {"GanTa": 0} # PRE_DEFINE_CATEGORIE...
0.145055
0.23092
__appname__ = "puls_price_converter" __version__ = "17.233.1000" #pid locking update, fix coding troubles #__version__ = "17.229.1140" #update pathes, working with pid-file, code readability #__version__ = "17.228.1800" #first edition import os import sys import glob import time import email import poplib import trac...
attcdown/puls_price_conv.py
__appname__ = "puls_price_converter" __version__ = "17.233.1000" #pid locking update, fix coding troubles #__version__ = "17.229.1140" #update pathes, working with pid-file, code readability #__version__ = "17.228.1800" #first edition import os import sys import glob import time import email import poplib import trac...
0.18866
0.062303
from __future__ import absolute_import, division, print_function, unicode_literals import logging from typing import List, Optional, Union, TYPE_CHECKING import numpy as np from art.estimators.classification.classifier import ClassifierGradients if TYPE_CHECKING: from GPy.models import GPClassification fro...
art/estimators/classification/GPy.py
from __future__ import absolute_import, division, print_function, unicode_literals import logging from typing import List, Optional, Union, TYPE_CHECKING import numpy as np from art.estimators.classification.classifier import ClassifierGradients if TYPE_CHECKING: from GPy.models import GPClassification fro...
0.948834
0.560433
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision import torchvision.transforms as transforms transform = transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ] ) trainset = torchvis...
NetDemo.py
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision import torchvision.transforms as transforms transform = transforms.Compose( [ transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ] ) trainset = torchvis...
0.943138
0.718823
import datetime import matplotlib.pyplot as plt from decimal import Decimal def gps_report(gpsdata, goodsats, inps): cwd = inps['cwd'] # Get current main working directory file_path = open(cwd+'\\output\\gps_report\\GPS_Report.txt', 'w') line = 'G ' line += ' Pos_X (km) ' line +=...
codes/pubplt.py
import datetime import matplotlib.pyplot as plt from decimal import Decimal def gps_report(gpsdata, goodsats, inps): cwd = inps['cwd'] # Get current main working directory file_path = open(cwd+'\\output\\gps_report\\GPS_Report.txt', 'w') line = 'G ' line += ' Pos_X (km) ' line +=...
0.296145
0.245254
from __future__ import unicode_literals # Normalize python2 and python3 vacaboulary # http://www.rfk.id.au/blog/entry/preparing-pyenchant-for-python-3/ try: is_python2 = str != unicode except NameError: # 'unicode' is undefined, must be Python 3 is_python2 = False unicode = str basestring = (str, b...
validict/__init__.py
from __future__ import unicode_literals # Normalize python2 and python3 vacaboulary # http://www.rfk.id.au/blog/entry/preparing-pyenchant-for-python-3/ try: is_python2 = str != unicode except NameError: # 'unicode' is undefined, must be Python 3 is_python2 = False unicode = str basestring = (str, b...
0.521227
0.23479
# pylint: disable=no-self-argument import re from typing import Dict, List, Optional from pydantic import BaseModel, validator from app.core.security.password import validate_password from app.helpers.expressions import VALID_EMAIL class GroupBase(BaseModel): """ Base Schema for Groups """ name: str de...
src/app/schema/auth.py
# pylint: disable=no-self-argument import re from typing import Dict, List, Optional from pydantic import BaseModel, validator from app.core.security.password import validate_password from app.helpers.expressions import VALID_EMAIL class GroupBase(BaseModel): """ Base Schema for Groups """ name: str de...
0.803868
0.242172
import numpy as np from ..core import Array def _read_bound_key(infofile, ncpu): with open(infofile) as f: content = f.readlines() starting_line = None for num, line in enumerate(content): if len(set(["DOMAIN", "ind_min", "ind_max"]) - set(line.split())) == 0: starting_line = ...
src/osyris/io/hilbert.py
import numpy as np from ..core import Array def _read_bound_key(infofile, ncpu): with open(infofile) as f: content = f.readlines() starting_line = None for num, line in enumerate(content): if len(set(["DOMAIN", "ind_min", "ind_max"]) - set(line.split())) == 0: starting_line = ...
0.433742
0.38549
import logging import time import argparse import requests logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) def post(emailAddress, password): session = requests.session() data = {'email_address': emailAddress, ...
2.py
import logging import time import argparse import requests logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__) def post(emailAddress, password): session = requests.session() data = {'email_address': emailAddress, ...
0.31384
0.086825
__all__ = ['Input'] import re from tebless.devs import Widget, echo from tebless.utils.keyboard import KEY_BACKSPACE, KEY_DELETE class Input(Widget): """Input widget with label. :param text: placeholder text :param label: Desc of input :param align: center, ljust, rjust text :param fill_c: blank...
tebless/widgets/input.py
__all__ = ['Input'] import re from tebless.devs import Widget, echo from tebless.utils.keyboard import KEY_BACKSPACE, KEY_DELETE class Input(Widget): """Input widget with label. :param text: placeholder text :param label: Desc of input :param align: center, ljust, rjust text :param fill_c: blank...
0.591723
0.316119
from direct.interval.IntervalGlobal import * from direct.gui.OnscreenText import OnscreenText from direct.actor import Actor from pandac.PandaModules import * from otp.otpbase import OTPGlobals from otp.avatar import Avatar from pirates.piratesbase import PiratesGlobals from pirates.movement.AnimationMixer import Anim...
pirates/creature/Creature.py
from direct.interval.IntervalGlobal import * from direct.gui.OnscreenText import OnscreenText from direct.actor import Actor from pandac.PandaModules import * from otp.otpbase import OTPGlobals from otp.avatar import Avatar from pirates.piratesbase import PiratesGlobals from pirates.movement.AnimationMixer import Anim...
0.566019
0.08438
import numpy as np import numpy from scipy.stats import multivariate_normal class MultiGaussianDistribution(object): def __init__(self, dimensions): self.dimensions = dimensions self.mean = np.zeros([dimensions]) self.cov = np.ones([dimensions, dimensions]) #self.cov = np.dot(self.c...
stammer/hmmtrain/__init__.py
import numpy as np import numpy from scipy.stats import multivariate_normal class MultiGaussianDistribution(object): def __init__(self, dimensions): self.dimensions = dimensions self.mean = np.zeros([dimensions]) self.cov = np.ones([dimensions, dimensions]) #self.cov = np.dot(self.c...
0.677474
0.376423
import os import wget import tarfile import logging import shutil import pytorch_lightning as pl from typing import Tuple, Optional from omegaconf import DictConfig from openspeech.data.dataset import SpeechToTextDataset from torch.utils.data import DataLoader from openspeech.datasets import register_data_module from...
openspeech/datasets/librispeech/lit_data_module.py
import os import wget import tarfile import logging import shutil import pytorch_lightning as pl from typing import Tuple, Optional from omegaconf import DictConfig from openspeech.data.dataset import SpeechToTextDataset from torch.utils.data import DataLoader from openspeech.datasets import register_data_module from...
0.698124
0.156395
def fix_multi_T1w_source_name(in_files): """ Make up a generic source name when there are multiple T1s >>> fix_multi_T1w_source_name([ ... '/path/to/sub-045_ses-test_T1w.nii.gz', ... '/path/to/sub-045_ses-retest_T1w.nii.gz']) '/path/to/sub-045_T1w.nii.gz' """ import os from...
fmriprep/utils/misc.py
def fix_multi_T1w_source_name(in_files): """ Make up a generic source name when there are multiple T1s >>> fix_multi_T1w_source_name([ ... '/path/to/sub-045_ses-test_T1w.nii.gz', ... '/path/to/sub-045_ses-retest_T1w.nii.gz']) '/path/to/sub-045_T1w.nii.gz' """ import os from...
0.478041
0.243502
import os ROBLOX_DIR = os.path.abspath(os.path.join(__file__, '..')) ROBLOX_GA_DIR = os.path.join(ROBLOX_DIR, "GameAnalyticsSDK") RBXMX_TMP_FILE = os.path.join(ROBLOX_DIR, "GameAnalyticsSDK.rbxmx.tmp") RBXMX_RELEASE_FILE = os.path.join(ROBLOX_DIR, "release", "GameAnalyticsSDK.rbxmx") GAMEANALYTICSSERVER_BODY = 'GameA...
generate_rbxmx_file.py
import os ROBLOX_DIR = os.path.abspath(os.path.join(__file__, '..')) ROBLOX_GA_DIR = os.path.join(ROBLOX_DIR, "GameAnalyticsSDK") RBXMX_TMP_FILE = os.path.join(ROBLOX_DIR, "GameAnalyticsSDK.rbxmx.tmp") RBXMX_RELEASE_FILE = os.path.join(ROBLOX_DIR, "release", "GameAnalyticsSDK.rbxmx") GAMEANALYTICSSERVER_BODY = 'GameA...
0.1291
0.065575
from unittest.mock import MagicMock import numpy as np # ----- Test Example #1 ------ # ex1: The distribution of samples of a test example. X_dsel_ex1 = np.array([[-1, 1], [-0.75, 0.5], [-1.5, 1.5], [1, 1], [0.75, 0.5], [1.5, 1.5], [1, -1], [-0.5, 0.5], [0.5, 0.5], ...
deslib/tests/examples_test.py
from unittest.mock import MagicMock import numpy as np # ----- Test Example #1 ------ # ex1: The distribution of samples of a test example. X_dsel_ex1 = np.array([[-1, 1], [-0.75, 0.5], [-1.5, 1.5], [1, 1], [0.75, 0.5], [1.5, 1.5], [1, -1], [-0.5, 0.5], [0.5, 0.5], ...
0.847432
0.832271
from typing import List, Tuple, Union, Deque, Iterable, Dict from collections import deque from tqdm import tqdm # type: ignore def get_data(fn: str) -> Deque[int]: with open(fn) as f: data = f.read() return deque([int(el) for el in data]) class Node: def __init__(self, value: int): sel...
puzzles/puzzle23.py
from typing import List, Tuple, Union, Deque, Iterable, Dict from collections import deque from tqdm import tqdm # type: ignore def get_data(fn: str) -> Deque[int]: with open(fn) as f: data = f.read() return deque([int(el) for el in data]) class Node: def __init__(self, value: int): sel...
0.806586
0.334481
from allensdk.api.queries.cell_types_api import CellTypesApi import os import sys ct = CellTypesApi() from data_helper import CURRENT_DATASETS, DATASET_TARGET_SWEEPS test = '-test' in sys.argv dataset_ids = CURRENT_DATASETS if test: dataset_ids = [479704527] sweep_numbers_for_data = DATASET_TARGET_SWEEPS for...
CellTypesDatabase/data/download.py
from allensdk.api.queries.cell_types_api import CellTypesApi import os import sys ct = CellTypesApi() from data_helper import CURRENT_DATASETS, DATASET_TARGET_SWEEPS test = '-test' in sys.argv dataset_ids = CURRENT_DATASETS if test: dataset_ids = [479704527] sweep_numbers_for_data = DATASET_TARGET_SWEEPS for...
0.324663
0.303796
from .models import Cadres, Teacher, Curriculum from django.contrib import admin @admin.register(Cadres) class CadresAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if change: user = request.user.username name = self.model.objects.get(pk=obj.pk).name ...
function/admin.py
from .models import Cadres, Teacher, Curriculum from django.contrib import admin @admin.register(Cadres) class CadresAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): if change: user = request.user.username name = self.model.objects.get(pk=obj.pk).name ...
0.165425
0.109325
statementArr = [ 'startSwitch("variableName")', 'endSwitch()', '''getComment("This is a comment")''', "puts('Something to print')", "getClassBeginning('sampleClass')", "getClassEnding()", 'setVar(valueToGet="1", valueToChange="x")', 'startCase("x")', 'endCase()', 'startDefault()', 'endDefault()', "equals(th...
libraries/statementArr.py
statementArr = [ 'startSwitch("variableName")', 'endSwitch()', '''getComment("This is a comment")''', "puts('Something to print')", "getClassBeginning('sampleClass')", "getClassEnding()", 'setVar(valueToGet="1", valueToChange="x")', 'startCase("x")', 'endCase()', 'startDefault()', 'endDefault()', "equals(th...
0.273186
0.32888
from ..conf_tests import app, cli from flask_batteries.commands import generate, destroy, new import os import traceback from flask_batteries.config import TAB from flask_batteries.helpers import verify_file from flask_batteries.installers import FlaskSQLAlchemyInstaller import subprocess def test_model_generator(app...
tests/generators/test_model_generator.py
from ..conf_tests import app, cli from flask_batteries.commands import generate, destroy, new import os import traceback from flask_batteries.config import TAB from flask_batteries.helpers import verify_file from flask_batteries.installers import FlaskSQLAlchemyInstaller import subprocess def test_model_generator(app...
0.321993
0.331471
import json import logging import inspect import io import os my_path = os.path.dirname(__file__) def check_hashseed(desired_seed = 0): if os.environ.get('PYTHONHASHSEED') != desired_seed: info(f"Ideally set PYTHONHASHSEED={desired_seed} for perfect reproducibility") return False return True ...
utils.py
import json import logging import inspect import io import os my_path = os.path.dirname(__file__) def check_hashseed(desired_seed = 0): if os.environ.get('PYTHONHASHSEED') != desired_seed: info(f"Ideally set PYTHONHASHSEED={desired_seed} for perfect reproducibility") return False return True ...
0.350644
0.141756
# It's based on oslo.i18n usage in OpenStack Keystone project and # recommendations from # https://docs.openstack.org/oslo.i18n/latest/user/usage.html """Utilities and helper functions.""" import eventlet import functools import inspect import json import mimetypes from oslo_concurrency import lockutils from oslo_co...
zun/common/utils.py
# It's based on oslo.i18n usage in OpenStack Keystone project and # recommendations from # https://docs.openstack.org/oslo.i18n/latest/user/usage.html """Utilities and helper functions.""" import eventlet import functools import inspect import json import mimetypes from oslo_concurrency import lockutils from oslo_co...
0.515376
0.209935
from re import S import re import time from requests.sessions import merge_setting import telepot from telepot import Bot from telepot.loop import MessageLoop from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup from common.MyMQTT import MyMQTT from common.RegManager import Reg...
teleBot/Telegram.py
from re import S import re import time from requests.sessions import merge_setting import telepot from telepot import Bot from telepot.loop import MessageLoop from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup from common.MyMQTT import MyMQTT from common.RegManager import Reg...
0.116487
0.062991
from src.FileActionHelper import FileActionHelper from src.Constants import Constants from src.StringActionHelper import StringActionHelper from src.FileUpdater import FileUpdater from src.ChangelogTableHelper import ChangelogTableHelper from bs4 import element import html2markdown def get_new_table_row(cell_list, ne...
src/ChangelogUpdater.py
from src.FileActionHelper import FileActionHelper from src.Constants import Constants from src.StringActionHelper import StringActionHelper from src.FileUpdater import FileUpdater from src.ChangelogTableHelper import ChangelogTableHelper from bs4 import element import html2markdown def get_new_table_row(cell_list, ne...
0.555435
0.13733
import requests import pafy from hurry.filesize import size from bs4 import BeautifulSoup def trade_spider(): print('Do you want to download a video or audio? (a/v)') download_content() def download_content(): type_of_file = input() if type_of_file == 'v' or type_of_file == 'a': type_string = ...
youtube/youtube_videos_7.py
import requests import pafy from hurry.filesize import size from bs4 import BeautifulSoup def trade_spider(): print('Do you want to download a video or audio? (a/v)') download_content() def download_content(): type_of_file = input() if type_of_file == 'v' or type_of_file == 'a': type_string = ...
0.19163
0.156105
from src.extract_old_site.modules import feature_descriptions as desc import pytest from unittest import mock import pathlib import os # Test Data # Sidebar index0_html_str = """ <html><body> <b>Descriptions</b><p> <a target="body" href="../split/report53.html">Burial 1 Description</a><br> <a target="body" href="../sp...
tests/extract_old_site/modules/test_feature_descriptions.py
from src.extract_old_site.modules import feature_descriptions as desc import pytest from unittest import mock import pathlib import os # Test Data # Sidebar index0_html_str = """ <html><body> <b>Descriptions</b><p> <a target="body" href="../split/report53.html">Burial 1 Description</a><br> <a target="body" href="../sp...
0.512937
0.129348
import json from hubcommander.bot_components.decorators import hubcommander_command, format_help_text, auth from hubcommander.bot_components.slack_comm import WORKING_COLOR from hubcommander.bot_components.parse_functions import ParseException def test_hubcommander_command_required(user_data, slack_client): fail...
tests/test_decorators.py
import json from hubcommander.bot_components.decorators import hubcommander_command, format_help_text, auth from hubcommander.bot_components.slack_comm import WORKING_COLOR from hubcommander.bot_components.parse_functions import ParseException def test_hubcommander_command_required(user_data, slack_client): fail...
0.667798
0.38885
# pylint: disable=line-too-long from azure.cli.core.application import APPLICATION from azure.cli.core.commands import cli_command from azure.cli.core.commands.arm import cli_generic_update_command from azure.cli.core.util import empty_on_404 from azure.cli.core.profiles import supported_api_version, PROFILE_TYPE fro...
src/command_modules/azure-cli-appservice/azure/cli/command_modules/appservice/commands.py
# pylint: disable=line-too-long from azure.cli.core.application import APPLICATION from azure.cli.core.commands import cli_command from azure.cli.core.commands.arm import cli_generic_update_command from azure.cli.core.util import empty_on_404 from azure.cli.core.profiles import supported_api_version, PROFILE_TYPE fro...
0.47926
0.049543
from core.GUI import * from engine.AttackTarget import AttackTarget from engine.SetFollow import SetFollow EnabledAutoAttack = False TargetNumber = 0 priority = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] monsters = [ "Rat", "CaveRat", "Orc", "OrcWarrior", "OrcSpearman", "Cyclops", "Rotworm", "Any...
modules/ShowMap.py
from core.GUI import * from engine.AttackTarget import AttackTarget from engine.SetFollow import SetFollow EnabledAutoAttack = False TargetNumber = 0 priority = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] monsters = [ "Rat", "CaveRat", "Orc", "OrcWarrior", "OrcSpearman", "Cyclops", "Rotworm", "Any...
0.404037
0.195019
from copy import deepcopy from flask_restful import Resource, request import jsonschema import caps import common from rest.rest_exceptions import BadRequest, InternalError from rest.rest_auth import auth from config import ConfigStore class CapsMba(Resource): """ Handles /caps/mba requests """ @s...
appqos/rest/rest_rdt.py
from copy import deepcopy from flask_restful import Resource, request import jsonschema import caps import common from rest.rest_exceptions import BadRequest, InternalError from rest.rest_auth import auth from config import ConfigStore class CapsMba(Resource): """ Handles /caps/mba requests """ @s...
0.439747
0.060919
# # Create figures for talk # # Generate figures for talk using stored variables from simulation experiments # In[ ]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import os import sys import glob import pickle import pandas as pd import numpy as np from pl...
archive/scripts/Pa_experiment_lvl_sim/nbconverted/4_create_figs_talk.py
# # Create figures for talk # # Generate figures for talk using stored variables from simulation experiments # In[ ]: get_ipython().run_line_magic('load_ext', 'autoreload') get_ipython().run_line_magic('autoreload', '2') import os import sys import glob import pickle import pandas as pd import numpy as np from pl...
0.432303
0.168994
from operator import attrgetter import random from bs4 import BeautifulSoup from django.utils.translation import ugettext as _ from natsort import natsorted from reportlab.lib import colors from reportlab.lib.units import cm from reportlab.platypus import PageBreak, Paragraph, Spacer, Table, TableStyle from openslid...
openslides/motion/pdf.py
from operator import attrgetter import random from bs4 import BeautifulSoup from django.utils.translation import ugettext as _ from natsort import natsorted from reportlab.lib import colors from reportlab.lib.units import cm from reportlab.platypus import PageBreak, Paragraph, Spacer, Table, TableStyle from openslid...
0.208421
0.154695
from __future__ import print_function import io import logging import logging.handlers import sys import threading import time try: import argparse except ImportError: sys.stderr.write(""" ntploggps: can't find the Python argparse module If your Python version is < 2.7, then manual installation is ne...
ntpclients/ntploggps.py
from __future__ import print_function import io import logging import logging.handlers import sys import threading import time try: import argparse except ImportError: sys.stderr.write(""" ntploggps: can't find the Python argparse module If your Python version is < 2.7, then manual installation is ne...
0.304765
0.081009
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import scipy as sp import pandas as pd from numpy.linalg import svd class CorrespondenceAnalysis(object): """Correspondence analysis (CA). Methods: fit: Fit corresponden...
correspondence_analysis.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import scipy as sp import pandas as pd from numpy.linalg import svd class CorrespondenceAnalysis(object): """Correspondence analysis (CA). Methods: fit: Fit corresponden...
0.911036
0.715262
from typing import TypeVar from pickle import HIGHEST_PROTOCOL from io import BytesIO, SEEK_SET from adam.curriculum.curriculum_utils import phase1_instances, PHASE1_CHOOSER_FACTORY from adam.language.language_utils import phase1_language_generator from adam.ontology.phase1_ontology import GAILA_PHASE_1_ONTOLOGY from ...
tests/pickle_test.py
from typing import TypeVar from pickle import HIGHEST_PROTOCOL from io import BytesIO, SEEK_SET from adam.curriculum.curriculum_utils import phase1_instances, PHASE1_CHOOSER_FACTORY from adam.language.language_utils import phase1_language_generator from adam.ontology.phase1_ontology import GAILA_PHASE_1_ONTOLOGY from ...
0.792424
0.183758
from flask import request from sqlalchemy.exc import IntegrityError from redash import models from redash.handlers.base import (BaseResource, get_object_or_404, paginate) from redash.permissions import require_access, view_only class QueryFavoriteResource(BaseResource): def post...
redash/handlers/favorites.py
from flask import request from sqlalchemy.exc import IntegrityError from redash import models from redash.handlers.base import (BaseResource, get_object_or_404, paginate) from redash.permissions import require_access, view_only class QueryFavoriteResource(BaseResource): def post...
0.413004
0.071461
#Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. #You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 #Unless required by applicable law or agreed to in writing, software #distributed under the Licen...
web.py
#Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. #You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 #Unless required by applicable law or agreed to in writing, software #distributed under the Licen...
0.375363
0.093927
from aiida.orm.data.int import Int from aiida.orm.data.list import List from aiida.orm.data.str import Str from aiida.orm.calculation.inline import make_inline from aiida.work import submit from aiida.work.persistence import ObjectLoader from aiida.work.workfunctions import workfunction from aiida.work.workchain import...
.ci/workchains.py
from aiida.orm.data.int import Int from aiida.orm.data.list import List from aiida.orm.data.str import Str from aiida.orm.calculation.inline import make_inline from aiida.work import submit from aiida.work.persistence import ObjectLoader from aiida.work.workfunctions import workfunction from aiida.work.workchain import...
0.697403
0.286576
from logging import getLogger from ClusterShell.NodeSet import NodeSet class TelemetryUtils(): # pylint: disable=too-many-nested-blocks """Defines a object used to verify telemetry information.""" ENGINE_CONTAINER_METRICS = [ "engine_pool_container_handles", "engine_pool_ops_cont_close", ...
src/tests/ftest/util/telemetry_utils.py
from logging import getLogger from ClusterShell.NodeSet import NodeSet class TelemetryUtils(): # pylint: disable=too-many-nested-blocks """Defines a object used to verify telemetry information.""" ENGINE_CONTAINER_METRICS = [ "engine_pool_container_handles", "engine_pool_ops_cont_close", ...
0.534855
0.146179
import random import grafanalib.core as G import pytest def dummy_grid_pos() -> G.GridPos: return G.GridPos(h=1, w=2, x=3, y=4) def dummy_data_link() -> G.DataLink: return G.DataLink( title='dummy title', linkUrl='https://www.dummy-link-url.com', isNewTab=True ) def dummy_eval...
grafanalib/tests/test_core.py
import random import grafanalib.core as G import pytest def dummy_grid_pos() -> G.GridPos: return G.GridPos(h=1, w=2, x=3, y=4) def dummy_data_link() -> G.DataLink: return G.DataLink( title='dummy title', linkUrl='https://www.dummy-link-url.com', isNewTab=True ) def dummy_eval...
0.592077
0.551755
import pathlib from subprocess import call, run from os import path from json import dumps import base64 from requests import get, post import noma.config as cfg def check_wallet(): """ This will either import an existing seed (or our own generated one), or use LND to create one. It will also create a...
noma/lnd.py
import pathlib from subprocess import call, run from os import path from json import dumps import base64 from requests import get, post import noma.config as cfg def check_wallet(): """ This will either import an existing seed (or our own generated one), or use LND to create one. It will also create a...
0.348202
0.10393
import numpy as np from . import het_compiled from ...utilities.interpolate import interpolate_coord_robust, interpolate_coord from ...utilities.multidim import batch_multiply_ith_dimension, multiply_ith_dimension from typing import Optional, Sequence, Any, List, Tuple, Union import copy class LawOfMotion: """Abst...
src/sequence_jacobian/blocks/support/law_of_motion.py
import numpy as np from . import het_compiled from ...utilities.interpolate import interpolate_coord_robust, interpolate_coord from ...utilities.multidim import batch_multiply_ith_dimension, multiply_ith_dimension from typing import Optional, Sequence, Any, List, Tuple, Union import copy class LawOfMotion: """Abst...
0.844794
0.442275
import copy import logging class EventCollectRecorder(): """EventCollectRecorder implements an recorder that logs events into a regular text file. On each arrival of an event (with a new time) a line is written into the log file. In each line all the states of the events are printed. Like this, a space sep...
event_collect_recorder.py
import copy import logging class EventCollectRecorder(): """EventCollectRecorder implements an recorder that logs events into a regular text file. On each arrival of an event (with a new time) a line is written into the log file. In each line all the states of the events are printed. Like this, a space sep...
0.625781
0.459622
from typing import Any, List, Optional, Union from azure.core.exceptions import HttpResponseError import msrest.serialization from ._azure_quota_extension_api_enums import * class CommonResourceProperties(msrest.serialization.Model): """Resource properties. Variables are only populated by the server, and ...
sdk/quota/azure-mgmt-quota/azure/mgmt/quota/models/_models_py3.py
from typing import Any, List, Optional, Union from azure.core.exceptions import HttpResponseError import msrest.serialization from ._azure_quota_extension_api_enums import * class CommonResourceProperties(msrest.serialization.Model): """Resource properties. Variables are only populated by the server, and ...
0.944855
0.16228
import logging from iotbx.reflection_file_reader import any_reflection_file from mmtbx.scaling import data_statistics from six.moves import StringIO logger = logging.getLogger("xia2.Modules.CctbxFrenchWilson") def do_french_wilson(mtz_file, hklout, anomalous=False): logger.debug("Reading reflections from %s", m...
Modules/CctbxFrenchWilson.py
import logging from iotbx.reflection_file_reader import any_reflection_file from mmtbx.scaling import data_statistics from six.moves import StringIO logger = logging.getLogger("xia2.Modules.CctbxFrenchWilson") def do_french_wilson(mtz_file, hklout, anomalous=False): logger.debug("Reading reflections from %s", m...
0.440229
0.349339
import sqlite3 import config class TokensModel: def __init__(self, uuid, ipaddr, username, password, sa_name, va_name, domain): self.uuid = uuid self.ipaddr = ipaddr self.username = username self.password = password self.sa_name = sa_name self.va_name = va_name ...
models/tokens.py
import sqlite3 import config class TokensModel: def __init__(self, uuid, ipaddr, username, password, sa_name, va_name, domain): self.uuid = uuid self.ipaddr = ipaddr self.username = username self.password = password self.sa_name = sa_name self.va_name = va_name ...
0.33928
0.09947
import os from pprint import pprint as pp import os import cv2 as cv import numpy as np import matplotlib.pyplot as plt from pyzbar import pyzbar as zbar from pprint import pprint as pp from barcode.rotation import get_rotation import time import csv def detect_from_image(image): image_norm = image found...
barcode/detection.py
import os from pprint import pprint as pp import os import cv2 as cv import numpy as np import matplotlib.pyplot as plt from pyzbar import pyzbar as zbar from pprint import pprint as pp from barcode.rotation import get_rotation import time import csv def detect_from_image(image): image_norm = image found...
0.124027
0.207054
import os import unittest import test_env from test_case import TestCaseWithFuzzer class CorpusTest(TestCaseWithFuzzer): def test_find_on_device(self): data = self.ns.data('corpus') resource = self.ns.resource('corpus') self.corpus.find_on_device() self.assertEqual(self.corpus....
scripts/fuzzing/test/corpus_test.py
import os import unittest import test_env from test_case import TestCaseWithFuzzer class CorpusTest(TestCaseWithFuzzer): def test_find_on_device(self): data = self.ns.data('corpus') resource = self.ns.resource('corpus') self.corpus.find_on_device() self.assertEqual(self.corpus....
0.476823
0.284862
import chumpy import smpl.smpl_webuser.lbs from smpl.smpl_webuser.posemapper import posemap import scipy.sparse as sp from chumpy.ch import MatVecMult def ischumpy(x): return hasattr(x, 'dterms') def verts_decorated(trans, pose, v_template, J, weights, kintree_table, bs_style, f, bs_type=None, posedirs=None,...
smpl/smpl_webuser/verts.py
import chumpy import smpl.smpl_webuser.lbs from smpl.smpl_webuser.posemapper import posemap import scipy.sparse as sp from chumpy.ch import MatVecMult def ischumpy(x): return hasattr(x, 'dterms') def verts_decorated(trans, pose, v_template, J, weights, kintree_table, bs_style, f, bs_type=None, posedirs=None,...
0.386763
0.363675
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division import math import torch import torch.nn as nn class _DynamicInputDenseBlock(nn.Module): def __init__(self, conv_modules, debug): super(_DynamicInputDenseB...
models/msdnet_layers.py
from __future__ import absolute_import from __future__ import unicode_literals from __future__ import print_function from __future__ import division import math import torch import torch.nn as nn class _DynamicInputDenseBlock(nn.Module): def __init__(self, conv_modules, debug): super(_DynamicInputDenseB...
0.901958
0.410343
from typing import Callable import cv2 import numpy as np # how much to crop the image to find the biggest blob # (this is to avoid picking a biggest blob that is not the worm) _CROP_PERCENT = 0.15 class ConstantThreshold: """ Threshold function that always returns the same threshold """ def __init...
wormpose/dataset/image_processing/image_utils.py
from typing import Callable import cv2 import numpy as np # how much to crop the image to find the biggest blob # (this is to avoid picking a biggest blob that is not the worm) _CROP_PERCENT = 0.15 class ConstantThreshold: """ Threshold function that always returns the same threshold """ def __init...
0.94323
0.730073
import asyncio import logging import sys from typing import Sequence import colorlog # type: ignore from .list_tasks import list_bare, list_tasks from .run_tasks import run_tasks from ..config import ToxConfig, load as load_config from ..config.cli import get_logging ROOT_LOGGER = logging.getLogger() LOGGER = logg...
src/toxn/evaluate/__init__.py
import asyncio import logging import sys from typing import Sequence import colorlog # type: ignore from .list_tasks import list_bare, list_tasks from .run_tasks import run_tasks from ..config import ToxConfig, load as load_config from ..config.cli import get_logging ROOT_LOGGER = logging.getLogger() LOGGER = logg...
0.488771
0.08152
import unittest import numpy import cupy from cupy import testing @testing.parameterize( # array only {'shape': (2, 3, 4), 'slices': numpy.array(-1), 'value': 1}, {'shape': (2, 3, 4), 'slices': numpy.array([1, 0]), 'value': 1}, {'shape': (2, 3, 4), 'slices': (slice(None), [1, 2]), 'value': 1}, {...
tests/cupy_tests/core_tests/test_ndarray_scatter.py
import unittest import numpy import cupy from cupy import testing @testing.parameterize( # array only {'shape': (2, 3, 4), 'slices': numpy.array(-1), 'value': 1}, {'shape': (2, 3, 4), 'slices': numpy.array([1, 0]), 'value': 1}, {'shape': (2, 3, 4), 'slices': (slice(None), [1, 2]), 'value': 1}, {...
0.612657
0.855369
import pytest import urllib from django.db import connection from model_mommy import mommy URLENCODE_FUNCTION_NAME = "urlencode" @pytest.fixture() def add_fun_awards(db): generated_unique_award_ids = [ "CONT_IDV_ABCDEFG_0123456", "CONT_IDV_abcdefg_9876543", "CONT_AWD_._.._..._....", ...
usaspending_api/database_scripts/tests/test_custom_sql_functions.py
import pytest import urllib from django.db import connection from model_mommy import mommy URLENCODE_FUNCTION_NAME = "urlencode" @pytest.fixture() def add_fun_awards(db): generated_unique_award_ids = [ "CONT_IDV_ABCDEFG_0123456", "CONT_IDV_abcdefg_9876543", "CONT_AWD_._.._..._....", ...
0.246896
0.22325
from unittest.mock import patch, MagicMock, PropertyMock, mock_open, call import pytest from mountains import main @patch('mountains.core.handle_args') @patch('mountains.core.get_http_data') @patch('mountains.core.get_file_data') @patch('mountains.core.create_key') @patch('mountains.core.create_header') @patch('moun...
tests/test_main.py
from unittest.mock import patch, MagicMock, PropertyMock, mock_open, call import pytest from mountains import main @patch('mountains.core.handle_args') @patch('mountains.core.get_http_data') @patch('mountains.core.get_file_data') @patch('mountains.core.create_key') @patch('mountains.core.create_header') @patch('moun...
0.722233
0.314893
import os import argparse import shelve import datetime import shutil import numpy as np import isce import isceobj from isceobj.Constants import SPEED_OF_LIGHT from isceobj.Util.Poly2D import Poly2D from mroipac.looks.Looks import Looks def createParser(): ''' Command line parser. ''' parser = argpa...
contrib/stack/stripmapStack/topo.py
import os import argparse import shelve import datetime import shutil import numpy as np import isce import isceobj from isceobj.Constants import SPEED_OF_LIGHT from isceobj.Util.Poly2D import Poly2D from mroipac.looks.Looks import Looks def createParser(): ''' Command line parser. ''' parser = argpa...
0.309754
0.135833
from dataclasses import dataclass import threading import pytest from typing import Any, Callable from flask.testing import FlaskClient from src.artemis.parameters import FullParameters from src.artemis.main import create_app, Status, Actions from src.artemis.devices.det_dim_constants import EIGER_TYPE_EIGER2_X_4M imp...
src/artemis/tests/test_main_system.py
from dataclasses import dataclass import threading import pytest from typing import Any, Callable from flask.testing import FlaskClient from src.artemis.parameters import FullParameters from src.artemis.main import create_app, Status, Actions from src.artemis.devices.det_dim_constants import EIGER_TYPE_EIGER2_X_4M imp...
0.633864
0.315565
import random import pathlib import sys """ This script is for making 8 kind of xyz data of 700 samples with specific combination of LC(Lattice constant) and Temperature 1. all(7) of LC with 300K [100x7] 2. all(7) of LC with 900K [100x7] 3. all(7) of LC with 1500K [100x7] 4. all(7) of LC with 600K(20),90...
tools/bad-sample/pkup_xyz.py
import random import pathlib import sys """ This script is for making 8 kind of xyz data of 700 samples with specific combination of LC(Lattice constant) and Temperature 1. all(7) of LC with 300K [100x7] 2. all(7) of LC with 900K [100x7] 3. all(7) of LC with 1500K [100x7] 4. all(7) of LC with 600K(20),90...
0.099006
0.375191
import gym import pathlib from gym.wrappers import FlattenObservation import safety_gym import simple_safety_gym import safe_rl from safe_rl.utils.run_utils import setup_logger_kwargs from safe_rl.utils.mpi_tools import mpi_fork from constraint.constraint_wrapper import ConstraintEnv from constraint.constraints.regist...
scripts/experiment.py
import gym import pathlib from gym.wrappers import FlattenObservation import safety_gym import simple_safety_gym import safe_rl from safe_rl.utils.run_utils import setup_logger_kwargs from safe_rl.utils.mpi_tools import mpi_fork from constraint.constraint_wrapper import ConstraintEnv from constraint.constraints.regist...
0.534855
0.300925
from nx import classes as pc import json from string import ascii_letters, digits from random import choice import copy import operator from functools import reduce def from_file_to_cy( classes_dict, session ) -> dict(): """ A (valid) json file is loaded and converted into a python dictionary. ""...
nx/__init__.py
from nx import classes as pc import json from string import ascii_letters, digits from random import choice import copy import operator from functools import reduce def from_file_to_cy( classes_dict, session ) -> dict(): """ A (valid) json file is loaded and converted into a python dictionary. ""...
0.214938
0.229784
""" This is a template module just for instruction. """ # no imports # functions def foo(i, j): # real signature unknown; restored from __doc__ """ foo(i,j) Return the sum of i and j. """ pass def new(): # real signature unknown; restored from __doc__ """ new() -> new Xx object """ p...
pyy1/.pycharm_helpers/python_stubs/-1550516950/xxlimited.py
""" This is a template module just for instruction. """ # no imports # functions def foo(i, j): # real signature unknown; restored from __doc__ """ foo(i,j) Return the sum of i and j. """ pass def new(): # real signature unknown; restored from __doc__ """ new() -> new Xx object """ p...
0.656328
0.162779
import artm import numpy as np import shutil import pytest import warnings from ..cooking_machine.models.topic_model import TopicModel from ..cooking_machine.dataset import Dataset, W_DIFF_BATCHES_1 from ..viewers import top_documents_viewer NUM_TOPICS = 5 NUM_DOCUMENT_PASSES = 1 NUM_ITERATIONS = 10 class TestTop...
topicnet/tests/test_top_documents_viewer.py
import artm import numpy as np import shutil import pytest import warnings from ..cooking_machine.models.topic_model import TopicModel from ..cooking_machine.dataset import Dataset, W_DIFF_BATCHES_1 from ..viewers import top_documents_viewer NUM_TOPICS = 5 NUM_DOCUMENT_PASSES = 1 NUM_ITERATIONS = 10 class TestTop...
0.619817
0.434581
from msrest.serialization import Model class CertificateBundle(Model): """A certificate bundle consists of a certificate (X509) plus its attributes. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The certificate id. :vartype id: str :ivar k...
azure-keyvault/azure/keyvault/generated/models/certificate_bundle.py
from msrest.serialization import Model class CertificateBundle(Model): """A certificate bundle consists of a certificate (X509) plus its attributes. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: The certificate id. :vartype id: str :ivar k...
0.891838
0.361841
import numpy as np import tensorflow as tf import argparse import time import os import pickle from utils import DataLoader from model import Model def main(): parser = argparse.ArgumentParser() parser.add_argument('--rnn_size', type=int, default=256, help='size of RNN hidden state') parse...
train.py
import numpy as np import tensorflow as tf import argparse import time import os import pickle from utils import DataLoader from model import Model def main(): parser = argparse.ArgumentParser() parser.add_argument('--rnn_size', type=int, default=256, help='size of RNN hidden state') parse...
0.593256
0.082512
import pandas as pd import numpy as np import sklearn import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.metrics import classification_report from sklearn.linear_model import LogisticRegression from sklearn.m...
telecomproject.py
import pandas as pd import numpy as np import sklearn import matplotlib.pyplot as plt import seaborn as sns from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler from sklearn.metrics import classification_report from sklearn.linear_model import LogisticRegression from sklearn.m...
0.348756
0.676533
from __init__ import sanitize from time import sleep from ldap import SCOPE_SUBORDINATE from swiftclient import service as swiftService from cinderclient.v2 import client as cinderClient from keystoneclient.exceptions import NotFound from keystoneclient.v3 import client as keystoneClient from keystoneclient.v3.roles im...
quota_checker.py
from __init__ import sanitize from time import sleep from ldap import SCOPE_SUBORDINATE from swiftclient import service as swiftService from cinderclient.v2 import client as cinderClient from keystoneclient.exceptions import NotFound from keystoneclient.v3 import client as keystoneClient from keystoneclient.v3.roles im...
0.574514
0.064036
import sys import requests import json import phantom.app as phantom from datetime import datetime from bs4 import BeautifulSoup from phantom.base_connector import BaseConnector from phantom.action_result import ActionResult from digitalguardianarc_consts import * from bs4 import UnicodeDammit class RetVal(tuple): ...
Apps/phdigitalguardianarc/digitalguardianarc_connector.py
import sys import requests import json import phantom.app as phantom from datetime import datetime from bs4 import BeautifulSoup from phantom.base_connector import BaseConnector from phantom.action_result import ActionResult from digitalguardianarc_consts import * from bs4 import UnicodeDammit class RetVal(tuple): ...
0.346984
0.089415
import glob import requests import json import os import datetime import re from invoke import task from monty.os import cd from monty import __version__ as ver __author__ = "<NAME>" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __date__ =...
tasks.py
import glob import requests import json import os import datetime import re from invoke import task from monty.os import cd from monty import __version__ as ver __author__ = "<NAME>" __copyright__ = "Copyright 2012, The Materials Project" __version__ = "0.1" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __date__ =...
0.241132
0.075995
from typing import Optional import sortedcontainers import logging import asyncio import random import collections from gear import Database from hailtop import aiotools from hailtop.utils import ( secret_alnum_string, retry_long_running, run_if_changed, time_msecs, WaitableSharedPool, AsyncWor...
batch/batch/driver/instance_collection/pool.py
from typing import Optional import sortedcontainers import logging import asyncio import random import collections from gear import Database from hailtop import aiotools from hailtop.utils import ( secret_alnum_string, retry_long_running, run_if_changed, time_msecs, WaitableSharedPool, AsyncWor...
0.779448
0.098512
from __future__ import division, print_function, unicode_literals import argparse import importlib import itertools import json import os import re import shutil import string import sys from collections import OrderedDict from bentoo.common.conf import load_conf from bentoo.common.utils import replace_template, saf...
bentoo/tools/generator.py
from __future__ import division, print_function, unicode_literals import argparse import importlib import itertools import json import os import re import shutil import string import sys from collections import OrderedDict from bentoo.common.conf import load_conf from bentoo.common.utils import replace_template, saf...
0.657209
0.600013
import json import jsonpickle from .errors import InvalidInstance from ..paystack_config import PaystackConfig class Base(): ''' Abstract Base Class ''' def __init__(self): if type(self) is Base: raise TypeError("Can not make instance of abstract base class") def to_json(self,...
python_paystack/objects/base.py
import json import jsonpickle from .errors import InvalidInstance from ..paystack_config import PaystackConfig class Base(): ''' Abstract Base Class ''' def __init__(self): if type(self) is Base: raise TypeError("Can not make instance of abstract base class") def to_json(self,...
0.495361
0.072768
import unittest from watcher import Watcher, StoppableThread class WatcherTestCase(unittest.TestCase): def callback(self, message): self.message = message return message def setUp(self): self.watcher = Watcher(self.callback) self.message = '' def test_callback(self): ...
tests/test_watcher.py
import unittest from watcher import Watcher, StoppableThread class WatcherTestCase(unittest.TestCase): def callback(self, message): self.message = message return message def setUp(self): self.watcher = Watcher(self.callback) self.message = '' def test_callback(self): ...
0.596786
0.261794
from pymtl3 import * from pymtl3.stdlib.test import TestSinkCL from pymtl3.stdlib.test.test_srcs import TestSrcRTL from ...lib.opt_type import * from ...lib.messages import * from ...lib.ctrl_helper import * from ...fu.flexible.FlexibleFuRTL import F...
cgra/test/CGRACL_test.py
from pymtl3 import * from pymtl3.stdlib.test import TestSinkCL from pymtl3.stdlib.test.test_srcs import TestSrcRTL from ...lib.opt_type import * from ...lib.messages import * from ...lib.ctrl_helper import * from ...fu.flexible.FlexibleFuRTL import F...
0.249722
0.383699
import os import requests import json import time import datetime # API Tokens # Add api keys to Heroku config vars to access them # Using Openweather API open_weather_token = os.environ.get('WEATHER_KEY') # DS Logic imports import pandas as pd import numpy as np from math import radians, cos, sin, asin, sqrt from ...
Getter_Api/app/functions.py
import os import requests import json import time import datetime # API Tokens # Add api keys to Heroku config vars to access them # Using Openweather API open_weather_token = os.environ.get('WEATHER_KEY') # DS Logic imports import pandas as pd import numpy as np from math import radians, cos, sin, asin, sqrt from ...
0.63409
0.333368
import logging import os logger = logging.getLogger(__name__) class MigratorMixin: """Mixin to allow the running of migrations. Your class must provide a `client` attribute (a PostgreSQLClient), as well as override some class attributes. """ """Name of this migrator (e.g. "storage"). Override t...
kinto/core/storage/postgresql/migrator.py
import logging import os logger = logging.getLogger(__name__) class MigratorMixin: """Mixin to allow the running of migrations. Your class must provide a `client` attribute (a PostgreSQLClient), as well as override some class attributes. """ """Name of this migrator (e.g. "storage"). Override t...
0.777553
0.21844
import os from tqdm import trange import torch from torch.nn import functional as F from torch import distributions as dist from src.common import ( compute_iou, make_3d_grid, add_key, ) from src.utils import visualize as vis from src.training import BaseTrainer class Trainer(BaseTrainer): ''' Trainer object f...
src/conv_onet/training.py
import os from tqdm import trange import torch from torch.nn import functional as F from torch import distributions as dist from src.common import ( compute_iou, make_3d_grid, add_key, ) from src.utils import visualize as vis from src.training import BaseTrainer class Trainer(BaseTrainer): ''' Trainer object f...
0.922416
0.365627