id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1654907 | import os
import numpy as np
import sys
import gc
import torch
from .tools import fix_seed
from torch_geometric.utils import is_undirected
fix_seed(1234)
class AutoEDA(object):
"""
A tool box for Exploratory Data Analysis (EDA)
Parameters:
----------
n_class: int
number of classes
------... |
1654948 | import os
import importlib.util
import click
import sys
sys.path.append("libraries/common")
sys.path.append("libraries/layouts")
sys.path.append("libraries/keycodes")
def load_module(file, name):
spec = importlib.util.spec_from_file_location(name, file)
foo = importlib.util.module_from_spec(spec)
spec.load... |
1654962 | import sqlite3
from argparse import ArgumentParser
import numpy as np
from openDAM.dataio.create_dam_db_from_csv import insert_in_table, create_tables
PUN_ZONES = {"SICI": 17, "SVIZ": 6}
MIN_RATIO = 0.1
PERIODS = range(9, 21)
N_BLOCKS_PER_ZONE = 25
QUANTITY_RANGE = [1, 75]
MEAN_PRICE = 50
STDEV_PRICE = 10
def popu... |
1654963 | import collections
from contextlib import contextmanager
from functools import wraps
import io
from itertools import cycle
import logging
import os
import pprint
import re
import shutil
import socket
import subprocess
from sys import version, stderr
import sys
import threading
import time
import uuid
f... |
1654980 | data = (
'syae', # 0x00
'syaeg', # 0x01
'syaegg', # 0x02
'syaegs', # 0x03
'syaen', # 0x04
'syaenj', # 0x05
'syaenh', # 0x06
'syaed', # 0x07
'syael', # 0x08
'syaelg', # 0x09
'syaelm', # 0x0a
'syaelb', # 0x0b
'syaels', # 0x0c
'syaelt', # 0x0d
'syaelp', # 0x0e
'syaelh', # 0x... |
1654988 | import itertools as it, operator as op, functools as ft
from pathlib import Path
import unittest
from . import _common as c
@c.tb.u.attr_struct
class TestTripStop: keys = 'stop_id dts_arr dts_dep'
@c.tb.u.attr_struct
class TestFootpath: keys = 'src dst dt'
class SimpleTestCase(unittest.TestCase):
dt_ch = 2*60 # f... |
1654998 | from keras import backend as K
import os
# Parameters
candle_lib = '/data/BIDS-HPC/public/candle/Candle/common'
def initialize_parameters():
print('Initializing parameters...')
# Obtain the path of the directory of this script
file_path = os.path.dirname(os.path.realpath(__file__))
# Import the ... |
1655032 | from rest_framework import viewsets
from rest_framework.decorators import detail_route
from rest_framework.response import Response
from .models import CopyFileDriver
from .serializers import CopyFileDriverSerializer
class CopyFileDriverViewSet(viewsets.ModelViewSet):
queryset = CopyFileDriver.objects.all()
... |
1655043 | import tensorflow as tf
from extra_layers.Clip import Clip
from extra_layers.OutputSplit import OutputSplit
from extra_layers.Padding import ReflectPadding2D
from extra_layers.BinaryOp import Div
from extra_layers.UnaryOp import Sqrt
from extra_layers.UnaryOp import Swish
from extra_layers.Resize import Interp
from ext... |
1655047 | import os
import re
import nibabel as nib
import numpy as np
from glob import glob
from sys import argv
dirname=argv[1]
print(dirname)
### COLLECT ALL MNCs
all_fls = []
for dirs, things, fls in os.walk(dirname):
if len(fls) > 0:
for fl in fls:
all_fls.append(os.path.join(dirs,fl))
all_mncs = ... |
1655048 | def could_be(original, another):
if not original.strip() or not another.strip():
return False
return set(another.split()).issubset(original.split())
|
1655049 | import cv2
import numpy as np
image = cv2.imread('calvinHobbes.jpeg')
height, width = image.shape[:2]
quarter_height, quarter_width = height/4, width/4
T = np.float32([[1, 0, quarter_width], [0, 1, quarter_height]])
img_translation = cv2.warpAffine(image, T, (width, height))
cv2.imshow("Originalimage", image... |
1655053 | from fastai.basic_train import load_learner
import pandas as pd
from pydub import AudioSegment
from librosa import get_duration
from pathlib import Path
from numpy import floor
from audio.data import AudioConfig, SpectrogramConfig, AudioList
import os
import shutil
import tempfile
def load_model(mPath, mName="stg2-rn... |
1655061 | import logging
import json
from datetime import datetime, timedelta
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from requests import (Request, Session)
_LOGGER = logging.getLogger(__name__)
from homeassistant.helpers.entity import Entity
from homeassistant.components.sensor import PLA... |
1655086 | import jsonschema
import pytest
from barrage import config, defaults as d
def test_merge_defaults_dataset():
cfg = {}
result = config._merge_defaults(cfg.copy())
assert isinstance(result, dict)
assert result["dataset"]["transformer"] == d.TRANSFORMER
assert result["dataset"]["augmentor"] == d.AU... |
1655125 | from django.contrib.auth.models import User
from restless.dj import DjangoResource
from restless.preparers import FieldsPreparer
from posts.models import Post
class PostResource(DjangoResource):
preparer = FieldsPreparer(fields={
'id': 'id',
'title': 'title',
'author': 'user.username',
... |
1655130 | from .keys import (BadSignatureError, BadPrefixError,
create_keypair, SigningKey, VerifyingKey,
remove_prefix, to_ascii, from_ascii)
(BadSignatureError, BadPrefixError,
create_keypair, SigningKey, VerifyingKey,
remove_prefix, to_ascii, from_ascii) # hush pyflakes
from ._version i... |
1655131 | from typing import TypeVar, List, Callable # noqa: F401
from functools import reduce
from operator import add
T = TypeVar('T')
S = TypeVar('S')
def flatten(l):
# type: (List[List[T]]) -> List[T]
return reduce(add, l, [])
def flat_map(f, l):
# type: (Callable[[S], List[T]], List[S]) -> List[T]
retu... |
1655135 | from math import ceil
from typing import Optional
from typing import Union
import torch
import torch.nn.functional as fn
from torch import Tensor
from torch.distributions.normal import Normal
from torch.distributions.utils import broadcast_all
from pfhedge._utils.typing import TensorOrScalar
def european_payoff(inp... |
1655153 | from __future__ import division, print_function
__author__ = 'saeedamen' # <NAME> / <EMAIL>
#
# Copyright 2019 Cuemacro
#
# See the License for the specific language governing permissions and limitations under the License.
#
from flask import Flask, request, jsonify
# hack to get Flask RestPlus to work!
import werk... |
1655174 | import torch
from .batch import BatchMeter
class CategoricalAccuracy(BatchMeter):
""" Accuracy on categorical targets
"""
name = 'acc'
DEFAULT_MODE = 'max'
INVALID_BATCH_DIMENSION_MESSAGE = (
'Expected both tensors have at less two dimension and same shape'
)
INVALID_INPUT_TYPE_M... |
1655177 | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'', include('osmaxx.excerptexport.urls', namespace='excerptexport')),
url(r'^admin/django-rq/', include('django_rq.urls')),
url(r'^admi... |
1655180 | import os
import numpy as np
import astrodash
directoryPath = '/Users/dmuthukrishna/Documents/OzDES_data/ATEL_9742_Run26'
atel9742 = [
('DES16E1ciy_E1_combined_161101_v10_b00.dat', 0.174),
('DES16S1cps_S1_combined_161101_v10_b00.dat', 0.274),
('DES16E2crb_E2_combined_161102_v10_b00.dat', 0.229),
('DES... |
1655225 | from typing import Dict, NewType, Any, Union, Optional, List
from typing_extensions import (
TypedDict
)
SystemId = int
Identifier = Union[str, int]
ParameterId = Identifier
Parameter = Dict[str, Any]
StatusItemIcon = Dict[str, Any]
ParameterSet = Dict[ParameterId, Parameter]
SecurityLevel = Dict[str, Any]
Connec... |
1655226 | import torch
import pandas as pd
import numpy as np
import pickle as pkl
import yaml
import cv2
from io import BytesIO
from .utils import make_detections_from_segmentation
from .datasets_cfg import make_urdf_dataset
from pathlib import Path
import torch.multiprocessing
torch.multiprocessing.set_sharing_strategy('file_s... |
1655310 | from app.HTMLScraper import SiteExplorer
import argparse
CLASSES = {
'textblock': ['.jumbotron', '.footer-single', '.timeline-panel', '.post-preview', '.masthead-content',
'.intro-text', '.p-5', '.lead', '.blockquote', '.blog-post', '.featurette-heading', '.article', 'p',
'h1', ... |
1655330 | import pickle
from ..data import Dataset
def GMM2d(path='./data'):
with open('{}/GMMs/gmm-2d-syn-set.pkl'.format(path), 'rb') as f:
raw_dataset = pickle.load(f)
return Dataset(raw_dataset['x'], raw_dataset['y'])
|
1655337 | import io
import functools
import PIL.Image
import numpy as np
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.responses import JSONResponse
from starlette.responses import StreamingResponse
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
from sm.browser import utils
from sm.... |
1655340 | from dota2.features.player import Player
from dota2.features.match import Match
from dota2.features.lobby import Lobby
from dota2.features.chat import ChatBase
from dota2.features.sharedobjects import SOBase
from dota2.features.party import Party
class FeatureBase(Player, Match, Lobby, Party, ChatBase, SOBase):
"... |
1655393 | classes = {}
def get_class(obj):
return classes.get(name_key(obj.__class__.__name__))
def get_class_by_name(name):
return classes.get(name_key(name))
def setup_class(cls):
classes[name_key(cls.name)] = cls
def name_key(name):
return name.lower().replace("_", "")
class Class:
def __init__(self, ... |
1655424 | from __future__ import print_function
import cw
import bluelet
class Master(object):
def __init__(self):
self.queued_tasks = [] # (TaskMessage, client connection) pairs
self.idle_workers = [] # connections
self.active_tasks = {} # {jobid: client connection}
self.connections = se... |
1655425 | import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
# Hyper parameters
n_epochs = 5
num_classes = 10
batch_size = 100
learning_rate = 0.001
interval = 100
# MNIST dataset
train_dataset = torchvision.datasets.MNIST(root=... |
1655460 | import inspect
from abc import ABCMeta, abstractmethod
class BaseStorageBackend(metaclass=ABCMeta):
"""Abstract class of storage backends.
All backends need to implement two apis: `get()` and `get_text()`.
`get()` reads the file as a byte stream and `get_text()` reads the file
as texts.
"""
... |
1655492 | def batch(iterable, n=1):
size = len(iterable)
for ndx in range(0, size, n):
yield iterable[ndx:min(ndx + n, size)]
|
1655531 | from rest_framework import pagination
class UserPagination(pagination.PageNumberPagination):
page_size = 1000
|
1655579 | def matching_parens(a, b):
return (
(a == '(' and b == ')') or
(a == '{' and b == '}') or
(a == '[' and b == ']')
)
def has_valid_parens(text):
stack = []
for c in text:
if c in ['(', '[', '{']:
stack.append(c)
elif c in [')', ']', '}']:
... |
1655649 | from fabric.api import cd, run
app_name = "flask-api"
def deploy():
run("rm -fr %s" % app_name)
run("mkdir %s" % app_name)
with cd("%s" % app_name):
run("virtualenv %s-env" % app_name)
run("source %s-env/bin/activate" % app_name)
run("sudo pip install supervisor gunicorn")
... |
1655669 | ReferenceArchitectureSpec = {
'EDB-RA-1': {
'pg_count': 1,
'pem_server': True,
'barman': True,
'barman_server_count': 1,
'bdr_server_count': 0,
'bdr_witness_count': 0,
'pooler_count': 0,
'pooler_type': None,
'pooler_local': False,
'efm'... |
1655691 | from helper import *
def doTest():
equal(getFixed('.test {margin:0 0 0 0}', 'margin'), '0', 'margin is fixed')
equal(getFixed('.test {margin:0 auto 0 auto}', 'margin'), '0 auto', 'margin 2 is fixed')
equal(getFixed('.test {margin:auto 0 0 auto}', 'margin'), 'auto 0 0 auto', 'margin 3 is fixed')
equal(g... |
1655715 | import sys
import csv
import os.path as path
base_directory = path.dirname(path.dirname(path.abspath(__file__)))
sys.path.append(path.join(base_directory, 'engine'))
from deparse import feature_string
from segment import Segment
def test_feature_string():
segment = Segment(['consonantal', 'voice', 'labial'],
... |
1655725 | import collections.abc
import itertools
Seq = collections.abc.Sequence
_chain = itertools.chain
_repeat = itertools.repeat
_islice = itertools.islice
# noinspection PyMethodParameters,PyMethodFirstArgAssignment
class List(Union):
"""
An immutable singly-linked list.
"""
@property
def uncons(self... |
1655741 | import logging
import flask_profiler
logger = logging.getLogger(__name__)
def setup_profiler(app):
profiler = app.config['POLYSWARMD'].profiler
if not profiler.enabled:
return
if profiler.db_uri is None:
logger.error('Profiler enabled but no db configured')
return
app.confi... |
1655751 | import conans
class PMM(conans.ConanFile):
name = 'pmm'
version = '1.5.1'
settings = None
exports_sources = '*'
generators = 'cmake'
# build_requires = (
# 'libman-generator/[*]@vector-of-bool/test'
# )
# generators = 'cmake', 'LibMan'
def build(self):
cmake = con... |
1655762 | from pymacaroons.binders import *
from pymacaroons.utils import *
class HashSignaturesBinder1(HashSignaturesBinder):
def __init__(self, root):
super(HashSignaturesBinder1, self).__init__(
root, truncate_or_pad(b'12345')
)
class HashSignaturesBinder2(HashSignaturesBinder):
def __i... |
1655826 | from django.core.exceptions import ImproperlyConfigured
import pytest
from pretix_eth.network.tokens import IToken
from pretix_eth.network import helpers
def create_token():
class Test(IToken):
NETWORK_IDENTIFIER = "Test"
NETWORK_VERBOSE_NAME = "Test Network"
TOKEN_SYMBOL = "T"
CHA... |
1655846 | from aws_cdk import (
core,
aws_lambda,
aws_ec2 as ec2,
aws_cloudwatch as cloudwatch,
aws_logs as logs,
)
from . import names
class ZipFunction(core.Construct):
def __init__(
self,
scope: core.Construct,
id: str,
name,
lambda_code_bucket,
environ... |
1655872 | import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import onqg.dataset.Constants as Constants
from onqg.models.modules.Attention import ConcatAttention
from onqg.models.modules.MaxOut import MaxOut
from onqg.models.modules.DecAssist import StackedRNN,... |
1655933 | from pathlib import Path
from .text_files import write_text_files
from .xlsx import write_xlsx_files
from .xlsx.templates.submission import SubmissionDocumentParams
from .xlsx.templates.dataset_description import DatasetDescriptionParams
from .xlsx.templates.code_description import CodeDescriptionParams
def write_s... |
1655942 | MODE_ZWSP = 0
MODE_FULL = 1
ZERO_WIDTH_SPACE = '\u200b'
ZERO_WIDTH_NON_JOINER = '\u200c'
ZERO_WIDTH_JOINER = '\u200d'
LEFT_TO_RIGHT_MARK = '\u200e'
RIGHT_TO_LEFT_MARK = '\u200f'
list_ZWSP = [
ZERO_WIDTH_SPACE,
ZERO_WIDTH_NON_JOINER,
ZERO_WIDTH_JOINER,
]
list_FULL = [
ZERO_WIDTH_SPACE,
ZERO_WIDTH_... |
1655960 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
with open("requirements.txt") as fh:
requirements = fh.readlines()
setuptools.setup(
name="tiara",
version="1.0.2",
description="A tool for classifying metagenomic data",
author="<NAME> and <NAME>",
author_e... |
1656013 | from collections import OrderedDict
import logging
import os
import pandas as pd
import seaborn as sns
import torch
log = logging.getLogger('main')
class ResultPack(object):
def __init__(self, exp_name, columns=None, metadata={}):
self.exp_name = exp_name.split('/')[-1] # get basename
self.meta... |
1656028 | import typing
import asyncio
from datetime import datetime, timedelta
import discord
from discord.ext import commands
from nerdlandbot.translations.Translations import get_text as translate
from nerdlandbot.helpers.TranslationHelper import get_culture_from_context as culture
from nerdlandbot.helpers.channel import get... |
1656034 | def get_variables(m, n):
candidates = list()
for a in range(m // 2 + 1):
b = m - a
if a ^ b == n:
candidates.append((a, b))
return candidates
# Tests
assert get_variables(100, 4) == [(48, 52)]
|
1656079 | from QuickPotato.harness.results import BoundariesTestEvidence
from functools import wraps
from datetime import datetime
def save_boundary_evidence(fnc):
"""
Parameters
----------
fnc
Returns
-------
"""
@wraps(fnc)
def encapsulated_function(*args, **kwargs):
"""
... |
1656131 | import numpy as np
import h5py
import sys
import logging
sys.path.append('..')
# Neural network stuff
from fielutil import load_verbatimnet
from demo_pipeline.featextractor import extract_imfeats
#pdb
# Logging
# logging.getLogger('featextractor').setLevel(logging.DEBUG)
shingle_dims=(120,120)
# ### Parameters
# Do ... |
1656165 | import numpy as np
import pandas as pd
import anndata as ad
import squidpy as sq
import eggplant as eg
from scipy.spatial.distance import cdist
import torch as t
import unittest
import gpytorch as gp
from . import utils as ut
class GetLandmarkDistance(unittest.TestCase):
def test_default_wo_ref(
self,
... |
1656174 | import pandas as pd
from marcottievents.models.common.enums import (ConfederationType, ActionType, ModifierType,
ModifierCategoryType, NameOrderType, PositionType,
GroupRoundType, KnockoutRoundType, SurfaceType)
from marcot... |
1656181 | import re
import glob
from json import dumps
from os.path import curdir, abspath, join, splitext, isfile
from os import walk
rfc_2119_keywords_regexes = [
r"MUST",
r"REQUIRED",
r"SHALL",
r"MUST NOT",
r"SHALL NOT",
r"SHOULD",
r"RECOMMENDED",
r"SHOULD NOT",
r"NOT RECOMMENDED",
r"M... |
1656218 | testinfra_hosts = ['instance-3', 'instance-4']
def test_node_is_worker(docker_info):
assert "Is Manager: false" in docker_info
|
1656266 | from rlbench.backend.task import Task
from typing import List
from pyrep.objects.shape import Shape
from pyrep.objects.proximity_sensor import ProximitySensor
from rlbench.backend.conditions import GraspedCondition, DetectedCondition
class ScoopWithSpatula(Task):
def init_task(self) -> None:
spatula = Sh... |
1656282 | from abc import ABC, abstractmethod
import numpy as np
import logging
from ..ring_buffer import RingBuffer
pmm_logger = None
class BaseTrailingIndicator(ABC):
@classmethod
def logger(cls):
global pmm_logger
if pmm_logger is None:
pmm_logger = logging.getLogger(__name__)
re... |
1656299 | import pika
import requests
class ExchangeReceiver(object):
def __init__(self, username, password, host, port, exchange, exchange_type, service, service_name, logger):
self.service_worker = service
self.service_name = service_name
self.exchange = exchange
self.logger = logger
... |
1656346 | import requests
r = requests.post('INVOKE_URL/STAGE/RESOURCE_NAME',
headers={'x-api-key': 'API KEY'},
json={'test':'test'})
print(r.text) |
1656419 | import os
import logging
logger = logging.getLogger(__name__)
import numpy as np
import astropy.io.fits as fits
import matplotlib.pyplot as plt
from ...echelle.imageproc import combine_images
from ...echelle.trace import find_apertures, load_aperture_set
from .common import (get_bias, get_mask, correct_overscan,
... |
1656424 | import numpy as np
import pandas as pd
import datetime
from sklearn import preprocessing
from sklearn.decomposition import PCA
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, GradientBoostingClassifier
from sklearn.feature_... |
1656445 | import random
import numpy as np
import torch.utils.data as data
from PIL import Image
def default_loader(path):
return Image.open(path).convert('RGB')
class Reader(data.Dataset):
def __init__(self, image_list, labels_list=[], transform=None, target_transform=None, use_cache=True,
loader=d... |
1656478 | from tkinter import *
from BlurWindow.blurWindow import GlobalBlur
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
from threading import Thread
class BlurBG(QWidget):
def __init__(self):
super(BlurBG, self).__init__()
self.setAttribute(Qt.WA_TranslucentBackground)
self.s... |
1656486 | import sys
import os
import pandas as pd
import seaborn as sns
STALE_THRESHOLD = 90 * 24 * 60 * 60 # 90 days in seconds
if len(sys.argv) < 2:
print("Path to a csv required as the first argument")
sys.exit(1)
OUTSIDER_ONLY = False
if len(sys.argv) == 3:
OUTSIDER_ONLY = sys.argv[2] == "--outsiders"
path =... |
1656505 | import io
import pytest
from tentaclio import urls
from tentaclio.clients import exceptions, s3_client
@pytest.fixture()
def mocked_conn(mocker):
with mocker.patch.object(s3_client.S3Client, "_connect", return_value=mocker.Mock()) as m:
yield m
class TestS3Client:
@pytest.mark.parametrize(
... |
1656527 | from pyworkflow.node import VizNode, NodeException
from pyworkflow.parameters import *
import pandas as pd
import altair as alt
class GraphNode(VizNode):
"""Displays a pandas DataFrame in a visual graph.
Raises:
NodeException: any error generating Altair Chart.
"""
name = "Graph Node"
nu... |
1656532 | from py4web import action, request
# pls, run socketio server - look at utils/wsservers.py
# test example for python-socketio
@action("socketio/index")
@action.uses("socketio/index.html")
def index():
return dict()
@action('socketio/echo/<path:path>', method=["GET", "POST"])
def echo(path=None):
print (pat... |
1656555 | from diagrams import Diagram
from diagrams.generic.blank import Blank
with Diagram("example_dag", show=False):
run_this_1 = Blank("run_this_1")
run_this_2a = Blank("run_this_2a")
run_this_3 = Blank("run_this_3")
run_this_2b = Blank("run_this_2b")
run_this_1 >> run_this_2a
run_this_2a >> ru... |
1656580 | import glob
import pickle
import os
import tqdm
data_type=1
test_set=0
processed_data_dir = "../data/raw_data/ann_data_roberta-base_512/"
trec_save_path = glob.glob(f"data-type-{data_type}_test-set-{test_set}_ckpt-*.trec")
with open(os.path.join(processed_data_dir,'qid2offset.pickle'),'rb') as f:
qid2offset = pi... |
1656596 | from ckan.plugins import toolkit as tk
def archiver_resource_show(resource_id):
data_dict = {'id': resource_id}
return tk.get_action('archiver_resource_show')(data_dict)
def archiver_is_resource_broken_html(resource):
archival = resource.get('archiver')
if not archival:
return tk.literal('<!... |
1656597 | from django import forms
from django.conf import settings
from django.contrib.admin import widgets
from django.utils.translation import gettext_lazy as _
class ExportDBForm(forms.Form):
from_date = forms.DateField(label=_('from date'),
widget=widgets.AdminDateWidget)
to_date = ... |
1656634 | import torch
import torch.nn as nn
from lie_conv.utils import Expression
class ResidualBlock(nn.Module):
def __init__(self, module, dim=None):
super().__init__()
self.module = module
self.dim = dim
def forward(self, input):
if self.dim is None:
return input + self... |
1656683 | from setuptools import setup, find_packages
def get_version(path):
""" Parse the version number variable __version__ from a script. """
import re
string = open(path).read()
version_re = r"^__version__ = ['\"]([^'\"]*)['\"]"
version_str = re.search(version_re, string, re.M).group(1)
return versi... |
1656694 | import numpy as np
import pandas as pd
import io
from sklearn.utils.validation import check_array, column_or_1d, check_consistent_length
from sklearn.utils import assert_all_finite
from sklearn.utils.multiclass import type_of_target
from ._utils import _assure_2d_array
class DoubleMLData:
"""Double machine lear... |
1656725 | from tlxzoo.datasets import DataLoaders
from tlxzoo.module.wav2vec2 import Wav2Vec2Transform
from tlxzoo.speech.automatic_speech_recognition import AutomaticSpeechRecognition
import tensorlayerx as tlx
import numpy as np
if __name__ == '__main__':
transform = Wav2Vec2Transform(vocab_file="./demo/speech/automatic_... |
1656737 | import io
import json
import os.path
from typing import Any, BinaryIO, Callable, Dict, List, Optional
import numpy as np
import pandas as pd
import zstandard
from databento.common.data import BIN_COLUMNS, BIN_RECORD_MAP, DERIV_SCHEMAS
from databento.common.enums import Compression, Encoding, Schema
class Bento:
... |
1656764 | from .. import common # ensure that libdyndt is loaded
from .type import make_fixed_bytes, make_fixed_string, make_struct, \
make_tuple, make_fixed_dim, make_string, make_var_dim, \
make_fixed_dim_kind, type_for
from .type import *
# Some classes making dimension construction easier
from .dim_helpers import *... |
1656784 | import datetime
import unittest
from zoomus import components, util
import responses
def suite():
"""Define all the tests of the module."""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(GetDailyReportV1TestCase))
suite.addTest(unittest.makeSuite(GetDailyReportV2TestCase))
return s... |
1656792 | from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import pickle
def poly(x, c2, c3):
return c2*x**2 + c3*x**3
df = pd.read_excel('curved_data.xlsx', sheet_name = 'FEA (3D, c3=0.25, F=-10)')
skip_lines = 0 # -1 of what you think it should be
plt.figure()
... |
1656852 | from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from ..settings import Settings
settings = Settings()
SQLALCHEMY_DATABASE_URL = settings.SQLALCHEMY_DATABASE_URI
if "sqlite:///" in SQLALCHEMY_DATABASE_URL:
engine = create_engine(... |
1656858 | class Solution:
"""
@param nums: a mountain sequence which increase firstly and then decrease
@return: then mountain top
"""
def mountainSequence(self, nums):
# write your code here
if not nums or len(nums) == 0:
return None
start, end = 0, len(nums) - 1
... |
1656885 | def default_builtins():
a = str()
b = bool()
c = int()
assert a == ""
assert b == False
assert c == 0
a = max(1, 2)
print(a)
b = min(1, 2)
print(b)
|
1656911 | class SearchPage(object):
def __init__(self, page, per_page, pages=0, total=0):
self._page = page
self._per_page = per_page
self._pages = pages
self._total = total
@property
def page(self):
return self._page
@page.setter
def page(self, page):
self._p... |
1656925 | from brainslug.database import AsyncTinyDB
from brainslug.remote import Remote
#: Global application state
AGENT_INFO = AsyncTinyDB()
def get_resources(loop, store, spec):
resources = dict()
for name, query in spec.items():
found = store.search(query)
if found:
# TODO: Implement ... |
1656937 | PRIMITIVE_TYPES = (int, str, float, bool)
SEQUENCE_TYPES = (tuple, set, list)
MAPPING_TYPES = dict
ComponentName = str
TargetName = str
|
1656959 | import numpy as np
import os
from qtpy import QtGui, QtCore, QtWidgets
import sharppy.sharptab.params as params
import sharppy.sharptab.winds as winds
import sharppy.sharptab.interp as interp
import sharppy.databases.inset_data as inset_data
from sharppy.sharptab.constants import *
## routine written by <NAME> and <NA... |
1656992 | import io
import os
import stat
import struct
from enum import IntEnum, unique
from pathlib import Path
from typing import Dict, Optional
from structlog import get_logger
from unblob.extractor import is_safe_path
from ...file_utils import Endian, InvalidInputFormat, read_until_past, round_up
from ...models import Ex... |
1657001 | import unittest
import unidecode
import random
from core.lists.listutils import ListUtils
PEOPLE = [
{ "name": "Adam", "age": 60 },
{ "name": "Adam", "age": 40 },
{ "name": "Łukasz", "age": 40 },
{ "name": "Lucia", "age": 30 },
{ "name": "Lucia", "age": 48 },
{ "name": "Luca", "age": 35 },
{ "name": "Luc... |
1657010 | from __future__ import annotations
from typing import (
TypeVar,
Mapping,
Dict,
Sequence,
Iterator,
overload,
Any,
Iterable,
AbstractSet,
)
TYPE = TypeVar("TYPE")
KEY_TYPE = TypeVar("KEY_TYPE")
VALUE_TYPE = TypeVar("VALUE_TYPE")
class FList(Sequence[TYPE]):
def __init__(self,... |
1657015 | from logger import log_info
from Classes.Metadata import Metadata
from Classes.PortablePacket import PortablePacket
from timeit import default_timer as timer
from extension import write, write_debug
from colorama import Fore
from zip_utils import *
import os
import sys
home = os.path.expanduser('~')
def install_port... |
1657020 | import math
def std(subject_marks, avg, n):
ans = 0
for i in subject_marks:
ans += (avg - i) ** 2
return math.sqrt(ans / (n - 1))
def cof(u, v, avg_u, avg_v, std_u, std_v, n):
ans = 0
for i in range(n):
ans += u[i] * v[i]
ans -= (n * avg_u * avg_v)
retu... |
1657022 | from __future__ import print_function
import pyxb
import po1
xml = open('badcontent.xml').read()
try:
order = po1.CreateFromDocument(xml, location_base='badcontent.xml')
except pyxb.ValidationError as e:
print(e.details())
|
1657078 | from flask import g, abort
from flask_restplus import Resource
from pyinfraboxutils.ibflask import auth_required, OK
from pyinfraboxutils.ibrestplus import api
ns = api.namespace('api/v1/user',
description="Users related operations")
@ns.route('/')
class User(Resource):
@auth_required(['user'... |
1657080 | class Solution:
def findMaxLength(self, nums: List[int]) -> int:
dic = {0: -1}
ps = 0
max_length = 0
for idx, number in enumerate(nums):
if number:
ps += 1
else:
ps -= 1
if ps in dic:
max_length = max... |
1657087 | import time
from __init__ import print_msg_box
def counting_sort(array, unit):
n = len(array)
output = [0]*n
count = [0]*10
for i in array:
pos = (i/unit)
count[int(pos%10)] +=1
for i in range(1, 10):
count[i] += count[i-1]
for i in range(n-1, -1, -1):
p... |
1657116 | from setuptools import setup
setup(
name="mkdocs-autodoc",
version="0.1.2",
url="https://github.com/restaction/mkdocs-autodoc",
license="MIT",
description="Auto generate API document in MKDocs",
author="guyskk",
author_email="<EMAIL>",
keywords=["mkdocs"],
packages=["mkdocs_autodoc"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.