id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
426014 | from rest_framework import viewsets
from api.suids.serializers import SuidSerializer
from api.base import ShareViewSet
from share.models import SourceUniqueIdentifier
class SuidViewSet(ShareViewSet, viewsets.ReadOnlyModelViewSet):
serializer_class = SuidSerializer
ordering = ('id', )
def get_queryset(... |
426015 | from __future__ import absolute_import,print_function,unicode_literals
_E='.env'
_D='always'
_C=True
_B=False
_A=None
import io,logging,os,re,shutil,sys,tempfile
from collections import OrderedDict
from contextlib import contextmanager
from .compat import IS_TYPE_CHECKING,PY2,StringIO,to_env
from .parser import Binding... |
426058 | from lazypredict.Supervised import LazyClassifier
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.linear_model import SGDClassifier
from sklearn.discriminant_analysis import (
LinearDiscriminantAnalysis,
QuadraticDiscriminantAnalysis,
)
from sklearn.model_selection import ... |
426090 | import unittest
import sys
from conveyor.multinb import Pipeline
class TestPipelineRun(unittest.TestCase):
def setUp(self):
if not sys.warnoptions:
import warnings
warnings.simplefilter("ignore")
def test_pipeline_additions(self):
data_processing1 = Pipeline()
... |
426121 | from __future__ import unicode_literals, print_function
import unittest
import boto3
import sys
import os
import uuid
import json
from os.path import dirname, join
from moto import mock_dynamodb2
from todo.api.create import create
from todo.api.delete import delete, handler
from todo.api.get import get_one
from dbconf... |
426145 | def make_cmd_params(command, nodes, env, sourcehash):
inputs = {}
outputs = []
files = [] #to be monitored
refs = []
output_refs = []
params = {
"lineno": command["cmd"]["lineno"],
"source": command["cmd"]["source"],
"sourcehash": sourcehash,
"refs": refs,
... |
426180 | import functools
import time
from typing import Optional
def on_interval(seconds: int): # in seconds
def wrapper(fn):
_last_called_time: Optional[float] = None
@functools.wraps(fn)
def inner(*args, **kwargs):
nonlocal _last_called_time
now = time.time()
... |
426215 | import logging
logger = logging.getLogger('awx.main.migrations')
def migrate_to_multi_cred(app, schema_editor):
Job = app.get_model('main', 'Job')
JobTemplate = app.get_model('main', 'JobTemplate')
ct = 0
for cls in (Job, JobTemplate):
for j in cls.objects.iterator():
if j.crede... |
426218 | from __future__ import print_function
import boto3
import os
S3 = boto3.client("s3")
BUCKET = "asi-lens-test-data"
def check_report_bom(name):
"""Check whether the report has Byte Order Marks
Parameters
----------
name : str
Filename of the report.
"""
with open(name, "r") as f:
... |
426233 | class SchemaAlreadyRegistered(Exception):
"""Error raised while trying to register a Schema that has already
been registered
"""
def __init__(self, name):
"""
Args:
name (str): schema name
"""
super(SchemaAlreadyRegistered, self).__init__("Schema \"%s\" has al... |
426238 | import torch
import torch.nn as nn
from block.models.networks.mlp import MLP
from .utils import grad_mul_const # mask_softmax, grad_reverse, grad_reverse_mask,
eps = 1e-12
class CFVQA(nn.Module):
"""
Wraps another model
The original model must return a dictionnary containing the 'logits' key (predictions... |
426263 | from abc import ABC, abstractmethod
import threading, uuid, datetime, traceback
class Task(threading.Thread, ABC):
def __init__(self):
self.running: bool = False
self._on_finish_events = []
self._on_error_events = []
self._on_start_events = []
self._id = str(uuid.uuid4())
... |
426300 | import logging
from ..analyzer.timewindowanalyzer import TimeWindowAnalyzer
###
L = logging.getLogger(__name__)
###
class TimeSeriesPredictor(TimeWindowAnalyzer):
'''
Trained model based time window analyzer, which collects
data into time series and predicts certain value.
'''
ConfigDefaults = {
'path': ... |
426310 | import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
def get_house_prices_and_rooms():
# getting the data
interesting_columns = ['house_price', 'number_of_rooms']
houses_df = pd.read_csv('data/HousingData.csv')[interesting_columns]
# getting data without outliers
number_o... |
426320 | from core.case.base import TestCaseBase, TestType
from core.case.decorator import case, data_provider
from core.config.setting import TestSettingBase
from core.resource.pool import ResourcePool
from core.result.reporter import StepResult
@case(priority=1, test_type=TestType.SANITY)
class HelloWorldTest(TestCaseBase):... |
426343 | import pyaudio
import time
import threading
import os
import sys
import select
import numpy as np
import audio_streamer
import effector
import graceful_killer as kl
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
PB_FILE = './frozen_model/frozen.pb'
UFF_FILE = './frozen_model/frozen.uff... |
426377 | from __future__ import annotations
import asyncio
from datetime import datetime, timedelta
from typing import Any, Literal, Optional
import httpx
from ._httpx_args import merge_with_default_httpx_args
from ._lib.utils import remove_none
from ._resources import (
AdminEvents,
AttachedResources,
Authentica... |
426438 | import acurl_ng
def create_request(
method,
url,
headers=(),
cookies=(),
auth=None,
data=None,
cert=None,
):
# Cookies should be the byte string representation of the cookie
if isinstance(method, str):
method = method.encode()
headers = tuple(h.encode("utf-8") if hasatt... |
426443 | from typing import Union
from scrapy.http import Response, TextResponse
from scrapypuppeteer import PuppeteerRequest
from scrapypuppeteer.actions import GoTo, PuppeteerServiceAction
class PuppeteerResponse(Response):
def __init__(self,
url: str,
puppeteer_request: PuppeteerRequ... |
426445 | from . import prefix
from fastapi import APIRouter
from fastapi.responses import JSONResponse
import starlette.status as status_code
from src.domain_logic.engagement_domain import EngagementDomain
from src.usecases.insert.insert_engagement import insert_engagement
from ..usecases.update.update_engagement import update_... |
426470 | from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
from random import randint #, shuffle, sample
import numpy as np
import pytest
from mmgroup import MM0, MMV, MMSpace, Cocode
from mmgroup.clifford12 import leech2matrix_eval_A_odd_mod15_aux
from mmgroup.cliff... |
426489 | import logging
import sys
import requests
import unicodecsv as csv
from utils import validate_basic_params, is_int_string
log = logging.getLogger()
"""
Read in threat intel csv file and post as json to cluster.
@return Nothing, will raise an exception if failed.
@param cluster: The name of your cluster, i.e. custome... |
426555 | from django.conf.urls import patterns, url
from webalyzer.collector import views
urlpatterns = patterns(
'',
url(
'^check/(?P<source_type>[\w]+)/'
'(?P<domain>[\w\.]+)/'
'(?P<source_hash>[\-\w\.]+)$',
views.collect_check,
name='collect_check'
),
url(r'^$', views... |
426573 | import torch
from en_transformer.utils import rot
from en_transformer import EnTransformer
torch.set_default_dtype(torch.float64)
def test_readme():
model = EnTransformer(
dim = 512,
depth = 1,
dim_head = 64,
heads = 8,
edge_dim = 4,
neighbors = 6
)
feats =... |
426577 | import sys
## Helper script to convert from simple keyframe-list formatted results to the temporal refinement results file format ('frames' mode)
## Not necessary to use this script, just a convenience if you want to print your system's results in a simple
## keyframe-list format and then use this script to conve... |
426589 | from subprocess import call
CWD = "../"
DEGREE = [8, 16, 32, 48, 64]
DELTA = [0.1, 0.2, 0.3, 0.4, 0.5]
call(['make'], cwd=CWD)
call(['./bin/decode_client', '-s'], cwd=CWD)
for degree in DEGREE:
for delta in DELTA:
print(degree, delta)
call(['./bin/decode_server', '--degree', str(degree), '--delta',... |
426602 | from django.utils.deprecation import MiddlewareMixin
from django.conf import settings
from django.utils import translation
class LanguageURLSpecifyMiddleware(MiddlewareMixin):
"""
Checks if url is containing language code like "domain.com/ru/something/",
and then middleware is activating this language for... |
426633 | import httplib2
from lxml.html import parse
from .pastesource import PasteSource
class PastebinSource(PasteSource):
baseurl = 'http://pastebin.com'
def __init__(self, *args, **kwargs):
pass
def new_urls(self, backend):
doc = parse('http://pastebin.com/archive').getroot()
for l... |
426664 | import abc
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from torchvision import transforms
class SiameseNetwork(nn.Module):
def __init__(self, model_path):
super(SiameseNetwork, self).__init__()
self.conv = models.__dict__['resn... |
426668 | try:
from source.utils import *
except:
from utils import *
class Metadata_SQLITE_Connector():
def __init__(self,metadata_file):
self.metadata_file_tsv=metadata_file
self.db_file=metadata_file.replace('.tsv','')+'.db'
if not file_exists(self.metadata_file_tsv):
print(f'... |
426671 | import logging
import os
import numpy as np
_log = logging.getLogger('test_webbpsf')
_log.addHandler(logging.NullHandler())
from .. import webbpsf_core
# ------------------ MIRI Tests ----------------------------
from .test_webbpsf import generic_output_test, do_test_source_offset, do_test_set_position_from_... |
426697 | import datetime
from unittest import TestCase
from ocd_backend.models.postgres_database import PostgresDatabase
|
426706 | import jupytext
def test_remove_encoding_907(tmp_path, python_notebook):
# Pair all notebooks to py:percent files
(tmp_path / "jupytext.toml").write_text('formats="ipynb,py:percent"')
# Create a contents manager
cm = jupytext.TextFileContentsManager()
cm.root_dir = str(tmp_path)
# Save the n... |
426727 | import argparse
from tensorflow.keras.datasets import mnist
from keras.utils.np_utils import to_categorical
from onnx2keras import onnx_to_keras
import onnx
parser = argparse.ArgumentParser(description='Keras MNIST ONNX import example')
parser.add_argument('--model-path', type=str, default="onnx_models/conv2D_mnist.o... |
426732 | import mmcv
import numpy as np
import torch
from torch.utils.data import Dataset
from openselfsup.utils import build_from_cfg
from torchvision.transforms import Compose
import torchvision.transforms.functional as TF
from .registry import DATASETS, PIPELINES
from .builder import build_datasource
from .utils import to... |
426763 | from setuptools import setup
from codecs import open
from os import path
# from peewee_validates import __version__ # the build requires preinstalled peewee and datautils
__version__ = '1.0.8'
root_dir = path.abspath(path.dirname(__file__))
with open(path.join(root_dir, 'README.rst'), encoding='utf-8') as f:
lo... |
426766 | from nnunet.training.network_training.nnUNetMultiTrainierV2 import nnUNetMultiTrainerV2
# from nnunet.training.dataloading.dataset_loading import DataLoader3DwithTag as DataLoader3D
from nnunet.training.dataloading.dataset_loading import DataLoader3DmergeTag as DataLoader3D
from nnunet.training.dataloading.dataset_load... |
426781 | import mock
from django.test import SimpleTestCase
from ..base import mock_class_instance
from contentcuration.models import ContentNode
from contentcuration.utils.cache import ResourceSizeCache
class ResourceSizeCacheTestCase(SimpleTestCase):
def setUp(self):
super(ResourceSizeCacheTestCase, self).setUp... |
426785 | import wx
from math import radians
from util.primitives.funcs import do
from gui.windowfx import ApplySmokeAndMirrors
from common import pref
from logging import getLogger; log = getLogger('OverlayImage')
class SimpleOverlayImage(wx.PopupWindow):
"""
Used for tab previews when dragging them around... |
426824 | import torch
import os
import shutil
import datetime
from utils.util import *
class Log(object):
def save_train_info(self, epoch, batch, maxbatch, losses, top1, top5):
"""
loss may contain several parts
"""
loss = losses[0]
loss1 = losses[1]
loss2 = losses... |
426886 | import requests
from django.conf import settings
from care.users.models import phone_number_regex
def _opt_in(phone_number):
url_data = {
"method": "OPT_IN",
"auth_scheme": "plain",
"v": "1.1",
"phone_number": phone_number,
"password": settings.WHATSAPP_API_PASSWORD,
... |
426904 | import numpy as np
from n2v.utils import n2v_utils
from n2v.utils.n2v_utils import tta_forward, tta_backward
def test_get_subpatch():
patch = np.arange(100)
patch.shape = (10, 10)
subpatch_target = np.array([[11, 12, 13, 14, 15],
[21, 22, 23, 24, 25],
... |
426908 | import arcpy
#Makes sure Spatial Analyst is turned on.
if arcpy.CheckExtension("Spatial")== "Available":
arcpy.CheckOutExtension("Spatial")
from arcpy.sa import *
else:
arcpy.AddError("You do not have the Spatial Analyst Extension, and therefore cannot use this tool.")
#Input folder.
folder_path= raw_i... |
426925 | import os
from distutils.dir_util import copy_tree
import time
import pytest
from nixui.graphics import main_window
from nixui import state_model
from nixui.options.option_tree import OptionTree
from nixui.options.attribute import Attribute
SAMPLES_PATH = 'tests/sample'
def pytest_addoption(parser):
parser.ad... |
426961 | from core.advbase import *
class Beautician_Zardin(Adv):
def x_proc(self, e):
if self.buff("s2"):
self.afflics.stun.on(f"{e.name}_stunning_beauty", 1.0, 5.5)
variants = {None: Beautician_Zardin}
|
426977 | import numpy as np
import datetime
from collections import defaultdict
from argparse import Namespace
import json
import os
import copy
from shutil import copyfile
from pointcloud import translate_transform_to_new_center_of_rotation
def ns_to_dict(ns):
return {k: ns_to_dict(v) if type(v) == Namespace else v for k... |
426979 | from dino.config import ConfigKeys
from dino import environ
import eventlet
import traceback
import logging
import sys
import os
from dino.endpoint.base import PublishException
logger = logging.getLogger(__name__)
DINO_DEBUG = os.environ.get('DINO_DEBUG')
if DINO_DEBUG is not None and DINO_DEBUG.lower() in {'1', 'tr... |
426988 | x = [1, [2, None]]
y = [1, 2]
z = [1, 2]
x[1][0] = y # should nudge y to over the right
z[1] = x # should nudge BOTH x and y over to the right
|
426992 | import responses
from tests.util import random_str
from tests.util import mock_http_response
from binance.spot import Spot as Client
mock_item = {"key_1": "value_1", "key_2": "value_2"}
key = random_str()
secret = random_str()
@mock_http_response(
responses.GET, "/sapi/v1/lending/daily/product/list", mock_item... |
426998 | import itertools
import re
import time
from typing import Optional
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.ui import WebDrive... |
427018 | from unittest.mock import create_autospec, ANY
import pytest
from operator import itemgetter
from stack.argument_processors.repo import RepoArgProcessor
from stack.commands import DatabaseConnection
from stack.exception import ArgError
FAKE_REPO_DATA = {
'name': 'fakename',
'alias': 'fakealias',
'url': 'uri:///',... |
427023 | import json
import requests
from requests.api import get, head
import csv
def get_octopus_resource(uri, headers, skip_count = 0):
items = []
skip_querystring = ""
if '?' in uri:
skip_querystring = '&skip='
else:
skip_querystring = '?skip='
response = requests.get((uri + skip_query... |
427026 | import sys
from setuptools import setup, find_packages
if sys.version_info < (3, 7):
sys.exit('Sorry, Python 3.7+ is required for Lunas.')
with open('requirements.txt') as r:
requires = [l.strip() for l in r]
setup(
name='Lunas',
version='0.5.1a',
author='<NAME>',
author_email='<EMAIL>',
... |
427036 | import rest_framework_filters as filters
from django.db.models import DateTimeField
from ..models import Contact, Comment, Category
NAME_FILTERS = ['exact', 'in', 'startswith', 'endswith', 'contains']
class CharArrayFilter(filters.BaseCSVFilter, filters.CharFilter):
pass
class CategoryFilter(filters.FilterSet... |
427054 | def Union2SortedArrays(arr1, arr2):
m = arr1[-1]
n = arr2[-1]
ans = 0
if m > n:
ans = m
else:
ans = n
returner = []
newtable = [0] * (ans + 1)
returner.append(arr1[0])
newtable[arr1[0]] += 1
for i in range(1, len(arr1)):
if arr1[i] != arr1[i - 1]:
returner.append(arr1[i])
n... |
427061 | import os
from collections import defaultdict
from copy import deepcopy
graph = defaultdict(set)
class Param:
layer = None
kernel_height = None
kernel_width = None
pad = 0
pad_x = None
pad_y = None
nhidden = None
nchannel = None
threshold = None
stride = 1
kernel_size = 1
... |
427071 | import abc
class MediaLoader(metaclass=abc.ABCMeta):
@abc.abstractmethod
def play(self):
pass
@abc.abstractproperty
def ext(self):
pass
@classmethod
def __subclasshook__(cls, C):
if cls is MediaLoader:
attrs = set(dir(C))
if set(cls.__abstractme... |
427082 | import board
import busio
i2c = busio.I2C(board.SCL, board.SDA)
count = 0
# Wait for I2C lock
while not i2c.try_lock():
pass
# Scan for devices on the I2C bus
print("Scanning I2C bus")
for x in i2c.scan():
print(hex(x))
count += 1
print("%d device(s) found on I2C bus" % count)
# Release the I2C bus
i2c... |
427098 | import redis
class PlayerStatus:
def __init__(self):
self.redis_connection = redis.StrictRedis()
self.key = "score_1"
def accumulate_points(self, new_points):
current_score = int(self.redis_connection.get(self.key) or 0)
score = current_score + new_points
self.redis_c... |
427116 | import pytest
from qcodes.utils.helpers import is_function
def test_non_function():
assert not is_function(0, 0)
assert not is_function('hello!', 0)
assert not is_function(None, 0)
def test_function():
def f0():
raise RuntimeError('function should not get called')
def f1(a):
rai... |
427124 | from polyglotdb import CorpusContext
from polyglotdb.syllabification.probabilistic import split_ons_coda_prob, split_nonsyllabic_prob, norm_count_dict
from polyglotdb.syllabification.maxonset import split_ons_coda_maxonset, split_nonsyllabic_maxonset
from polyglotdb.syllabification.main import syllabify
def test_fin... |
427189 | import atexit
import click
import logging
import orrb
import orrb.utils as utils
import os
import sys
import time
import numpy as np
from mpi4py import MPI
from queue import Queue
def _load_states():
return np.loadtxt(utils.package_relative_path('assets/states/qpos.csv'), delimiter=',')
def _build_renderer(nu... |
427213 | import angr
import time
# pylint: disable=arguments-differ,unused-argument
class gettimeofday(angr.SimProcedure):
def run(self, tv, tz):
if self.state.solver.is_true(tv == 0):
return -1
if angr.options.USE_SYSTEM_TIMES in self.state.options:
flt = time.time()
r... |
427215 | from typing import Dict, List, Optional
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import QGridLayout, QGroupBox, QApplication
from PyQt5.uic import loadUi
from .option_items import (
CapsuleOptionItem,
EnumOptionItem,
FloatOptionItem,
IntOptionItem,
BoolOptionItem
)
from brainfr... |
427220 | import os
import docker
def start_nginx():
os.system("docker rm -f migrate")
os.system("mkdir ~/migrate")
os.system("mkdir -p ~/migrate/html/checkpoints")
os.system("mkdir -p ~/migrate/html/images")
# ~/migrate/html是存储html的位置,资源也存在这个目录,方便读取
os.system("docker run --name migrate -itd -p 8080:80 -... |
427228 | from ggplot import *
import pandas as pd
df = pd.DataFrame({
"x": [0, 1, 1, 0] + [5, 10, 10, 5],
"y": [0, 0, 1, 1] + [10, 10, 20, 20],
"g": ["a", "a", "a", "a"] + ["b", "b", "b", "b"]
})
print ggplot(df, aes(x='x', y='y', fill='g')) + geom_polygon()
print ggplot(df, aes(x='x', y='y', color='g')) + geom_... |
427230 | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import pymc3 as pm
import theano
import theano.tensor as tt
#load data
train_df = pd.read_csv('redwoods.csv')
#scale it so it is a bit easier to work with
xloc = train_df['redwoodfull.x']*100
yloc = train_df['redwoodfull.y... |
427236 | import os
import sys
import time
import torch
import torchaudio
import numpy as np
from ronn.model import ronnModel
from ronn.utils import calculate_receptive_field
sample_rate = 44100
params = {
"n_inputs": 2,
"n_outputs": 2,
"n_layers": 7,
"n_channels": 4,
"kernel_size": 3,
"activation": "R... |
427259 | c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.open_browser = False
# Python
c.NotebookApp.password = '<PASSWORD>' |
427282 | from django import template
from main.models import Warden, HostelSuperintendent, Security
register = template.Library()
@register.simple_tag
def active_page(request, view_name):
from django.urls import resolve, Resolver404
path = resolve(request.path_info)
if not request:
return ""
try:
... |
427321 | from magma import *
__all__ = ['PS7Wrap']
def PS7Wrap():
PS7Path = os.path.dirname(__file__) + "/vsrc/"
vlibs = [PS7Path+"ps7_wrap.v",PS7Path+"axi_master_stub.v",PS7Path+"axi_master32_stub.v",PS7Path+"axi_slave_stub.v"]
verilogFile = PS7Path + "ps7_stub.v"
ps7 = DefineCircuit("ps7_stub",
"inout... |
427330 | import numpy as np
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import paddlenlp as nlp
from paddlenlp.data import Stack, Tuple, Pad
def predict(model, data, tokenizer, label_map, batch_size=1):
"""
Predicts the data labels.
Args:
model (obj:`paddle.nn.Layer`): A model t... |
427394 | import os
from generate_matches import generate_matches_carla, ImageIndex
from display_matches import display_correspondences
if __name__ == '__main__':
benchmark_folder = '/media/lukas/storage04/benchmarkpublic/GNNET_BENCHMARK_PUBLIC' # set this to the folder you have downloaded the benchmark to.
carla_fold... |
427442 | import asyncio
import logging
from unittest import TestCase
import src.async_kinesis_client.kinesis_producer
from tests.mocks import KinesisProducerMock
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
class TestProducer(TestCase):
def setUp(self):
try:
... |
427462 | from thenewboston.blocks.signatures import generate_signature
from thenewboston.utils.tools import sort_and_encode
from thenewboston.verify_keys.verify_key import encode_verify_key, get_verify_key
def generate_signed_request(*, data, nid_signing_key):
"""Generate and return signed request"""
node_identifier =... |
427492 | from desktop_local_tests.local_ip_responder_test_case_with_disrupter import LocalIPResponderTestCaseWithDisrupter
from desktop_local_tests.windows.windows_adapter_disrupter import WindowsAdapterDisrupter
class TestWindowsIPResponderDisruptAdapter(LocalIPResponderTestCaseWithDisrupter):
'''Summary:
Tests whet... |
427519 | from fastapi_utils.api_model import APIModel
from tifa.apps.admin.local import g
from tifa.apps.admin.router import bp
from tifa.models.gift_card import GiftCard
class TGiftCard(APIModel):
id: str
name: str
@bp.list("/gift_cards", out=TGiftCard, summary="GiftCard", tags=["GiftCard"])
async def gift_cards_i... |
427537 | import struct
from terrabot.util.streamer import Streamer
class Packet14Parser(object):
def parse(self, world, player, data, ev_man):
pass
|
427540 | import unittest
from torchimage.misc import outer
from torchimage.pooling.base import SeparablePoolNd
from torchimage.pooling.gaussian import GaussianPoolNd
from torchimage.pooling.uniform import AvgPoolNd
from torchimage.padding.utils import same_padding_width
import numpy as np
import torch
from torch import nn
f... |
427575 | import csv
import collections
import re
# this opens and reads a csv data as a list
def read(filename):
data = []
with open(filename, 'rU') as f:
f = csv.reader(f)
for row in f:
data.append(row)
return data
# this opens and reads csv data as a dict
def read_as_dict(filename)... |
427579 | import slideseg
import os
def main():
"""
Runs SlideSeg with the parameters specified in Parameters.txt
:return: image chips and masks
"""
def str2bool(value):
return value.lower() in ("true", "yes", "1")
params = slideseg.load_parameters('Parameters.txt')
print('running __main__ ... |
427600 | import itertools
import cmath
import h5py
from pauxy.systems.hubbard import Hubbard
from pauxy.trial_wavefunction.free_electron import FreeElectron
from pauxy.trial_wavefunction.uhf import UHF
from pauxy.trial_wavefunction.harmonic_oscillator import HarmonicOscillator
from pauxy.estimators.ci import simple_fci_bose_fer... |
427664 | from __future__ import print_function
import os
import sys
import datetime
import configparser
from LSP import proc_lsp
from LSPET import proc_lspet
from MPII import proc_mpii
from COCO import proc_coco
from H36M import proc_h36m
sys.path.append("../src/")
from utility import take_notes
# parse configures
conf = conf... |
427665 | from click.testing import CliRunner
from inenv.cli import print_version, autojump
from inenv.inenv import autojump_enabled
from inenv.version import __version__
class TestCli(object):
def setup_method(self):
self.runner = CliRunner()
def invoke(self, command, args=None):
if args is None:
... |
427686 | import pytest
from encoded.tests.features.conftest import app, app_settings, index_workbook
pytestmark = [
pytest.mark.indexing,
pytest.mark.usefixtures('index_workbook'),
]
def test_reports_search_batched_search_generator_init(dummy_request):
from encoded.reports.search import BatchedSearchGenerator
... |
427702 | import torch
import random
import librosa
import numpy as np
import nlpaug.flow as naf
import nlpaug.augmenter.audio as naa
import nlpaug.augmenter.spectrogram as nas
from torchvision.transforms import Normalize
from torch.utils.data import Dataset
from torchaudio.datasets import LIBRISPEECH
BAD_LIBRISPEECH_INDICES =... |
427745 | class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
if t < 0 or k <= 0:
return False
table = {}
w = 1 + t
for i, num in enumerate(nums):
curr = num // w
if curr in table:
return True
... |
427761 | from setuptools import setup
import versioneer
from os import path
here = path.abspath(path.dirname(__file__))
# Read the requirements from requirements.txt
requires = open('requirements.txt').read().strip().split('\n')
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding=... |
427833 | from math import pi, cos, sin, log, acos, sqrt, pow
"""
Equations source:
a) https://vismor.com/documents/power_systems/transmission_lines/S2.SS1.php
b) <NAME> - Distribution system modelling (3rd Ed.)
Typical values of earth
10 Ω/m3 - Resistivity of swampy ground
100 Ω/m3 - Resistivity of average damp earth
10... |
427840 | expected_output = {
"configuration": {
"vpg_name": "VirtualPortGroup2",
"vpg_ip_addr": "192.168.2.1",
"vpg_ip_mask": "255.255.255.0",
"sng_name": "SNG-APPQOE",
"sng_ip_addr": "192.168.2.2",
},
"status": {"operational_state": "RUNNING"},
}
|
427851 | import inspect
import os
import types
import chainer_chemistry.functions
import chainer_chemistry.links
import chainer_chemistry.models
def _is_rst_exists(entity):
return os.path.exists('source/generated/{}.rst'.format(entity))
def check(app, exception):
missing_entities = []
missing_entities += [
... |
427875 | from arche.tools import bitbucket
import pytest
urls = [
(
"https://bitbucket.org/scrapinghub/customer/src/master/customer/schemas/ecommerce.json",
"https://api.bitbucket.org/2.0/repositories/scrapinghub/customer/src/master"
"/customer/schemas/ecommerce.json",
),
(
"https:/... |
427882 | import os
import random
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.ticker import NullLocator
import numpy as np
import torch
from PIL import Image
from detection.src.yolov3.model import Darknet
from detection.src.yolov3.utils.datasets import ListDataset
from detection.src.y... |
427900 | import sys, asyncio, os
from catalog import searchDomains, findOpenPorts, kafkaProducer
from aux import consumer, producer
async def main():
tasks = []
foundDomains = asyncio.Queue()
portsQueue = asyncio.Queue()
tasks.append(asyncio.create_task(producer(searchDomains, sys.argv[1], foundDomains)))
t... |
427944 | from collections import defaultdict
import re
import pymysql as mysql
MYSQL_FIELD_TYPES = {
0: 'DECIMAL',
1: 'TINY',
2: 'SHORT',
3: 'LONG',
4: 'FLOAT',
5: 'DOUBLE',
6: 'NULL',
7: 'TIMESTAMP',
8: 'LONGLONG',
9: 'INT24',
10: 'DATE',
11: 'TIME',
12: 'DATETIME',
13... |
427969 | from setuptools import setup, find_packages
long_description = open('README.rst').read()
version = '0.0.3'
setup(name='keras-adversarial',
version=version,
description='Adversarial models and optimizers for Keras',
url='https://github.com/bstriner/keras-adversarial',
download_url='https://gith... |
427982 | import argparse
import numpy as np
import math
import os
import time
from six.moves import cPickle # six.moves is used to self-adjust the change of python 2 and python 3
import yaml
import itertools
from multiprocessing.dummy import Pool as ThreadPool
import torch
import torch.optim as optim
from torch.optim.lr_sched... |
427994 | from __future__ import absolute_import
import base64
import contextlib
import typing as tp
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
# noinspection PyProtectedMember
from applitools.core import logger
from applitools.core.ey... |
428009 | import argparse
from ..github import GithubClient
from .utils import ensure_github_token, get_current_pr
def merge_command(args: argparse.Namespace) -> None:
github_client = GithubClient(ensure_github_token(args.token))
github_client.merge_pr(get_current_pr())
|
428023 | H = [[0, -1, [68.16,1]], [0, -1, [10.2465,1]], [0, -1, [2.34648,1]],
[0, -1, [0.67332,1]], [0, -1, [0.22466,1]], [0, -1, [0.082217,1]],
[1, 0, [1.3,1]], [1, 0, [0.33,1]],
[2, 0, [1.0,1]], ]
C = [[0, -1, [16371.074,1]], [0, -1, [2426.9925,1]], [0, -1, [544.54418,1]],
[0, -1, [150.80487,1]], [0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.