id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
43467 | from __future__ import absolute_import
__author__ = '<NAME>'
import time
import struct
try:
from pebble import pulse2
except ImportError:
pass
from . import BaseTransport, MessageTargetWatch
from libpebble2.exceptions import ConnectionError, PebbleError
class PULSETransport(BaseTransport):
"""
Repr... |
43490 | import symjax
import symjax.tensor as T
import matplotlib.pyplot as plt
import numpy as np
J = 5
Q = 4
scales = T.power(2, T.linspace(0.1, J - 1, J * Q))
scales = scales[:, None]
print(scales.get())
wavelet = symjax.tensor.signal.complex_morlet(5 * scales, np.pi / scales)
waveletw = symjax.tensor.signal.fourier_comp... |
43526 | import torchvision.transforms as T
from torchvision.datasets import ImageFolder
class WHURS19(ImageFolder):
""" WHU-RS19 dataset from'Structural High-resolution Satellite Image Indexing', Xia at al. (2010)
https://hal.archives-ouvertes.fr/file/index/docid/458685/filename/structural_satellite_indexing_XYDG.pdf... |
43534 | from lcu_driver import Connector
connector = Connector()
@connector.ready
async def connect(connection):
print('LCU API is ready to be used.')
@connector.close
async def disconnect(connection):
print('Finished task')
connector.start()
|
43568 | import theano.tensor as tt
from theano import scan
from . import multivariate
from . import continuous
from . import distribution
__all__ = [
'AR1',
'GaussianRandomWalk',
'GARCH11',
'EulerMaruyama',
'MvGaussianRandomWalk',
'MvStudentTRandomWalk'
]
class AR1(distribution.Continuous):
"""
... |
43571 | import pytest
from monty.serialization import MontyDecoder
from monty.serialization import loadfn
from emmet.core.thermo import ThermoDoc
@pytest.fixture(scope="session")
def Fe3O4_structure(test_dir):
structure = loadfn(test_dir / "thermo/Fe3O4_structure.json")
return structure
@pytest.fixture(scope="sessi... |
43591 | from colorama import Fore, Style
def console_log(text, _type=None, title=None, space=False, space_number=0):
# Checking text instance is string
if isinstance(text, str):
if title is None:
if _type == 'success':
return print(Style.DIM + Fore.GREEN + '[SUCCESS]'
... |
43611 | import torch
import torch.nn.functional as F
from exptune.exptune import ExperimentSettings, Metric, TrialResources
from exptune.hyperparams import (
ChoiceHyperParam,
LogUniformHyperParam,
UniformHyperParam,
)
from exptune.search_strategies import GridSearchStrategy
from exptune.summaries.final_run_summari... |
43614 | import angr
######################################
# accept (but not really)
######################################
class accept(angr.SimProcedure):
#pylint:disable=arguments-differ
def run(self, sockfd, addr, addrlen):
conc_addrlen = self.state.mem[addrlen].int.concrete
addr_data = self.stat... |
43627 | import panel as pn
def test_alert():
my_alert = pn.pane.Alert("foo", alert_type="primary")
my_button = pn.widgets.Button(name="Toggle")
def toggle(event):
if my_alert.alert_type == "primary":
my_alert.alert_type == "success"
else:
my_alert.alert_type = "... |
43653 | import torch
import torch.nn as nn
import argparse
from torch.utils.data import Dataset
import sys
'''
Block of net
'''
def net_block(n_in, n_out):
block = nn.Sequential(nn.Linear(n_in, n_out),
nn.BatchNorm1d(n_out),
nn.ReLU())
return block
class M... |
43688 | import copy
import torch as th
from torch.optim import Adam
import torch.nn.functional as F
from torch.nn.utils import clip_grad_norm_
class SACLearner:
def __init__(self, mac, args):
self.args = args
self.mac = mac
self.params = list(mac.parameters())
self.learn_cnt= 0
sel... |
43697 | import numpy as np
import pytest
import pytoolkit as tk
def test_load_voc_od_split(data_dir):
ds = tk.datasets.load_voc_od_split(data_dir / "od", split="train")
assert len(ds) == 3
assert tuple(ds.metadata["class_names"]) == ("~", "〇")
ann = ds.labels[0]
assert ann.path == (data_dir / "od" / "JP... |
43700 | try:
from . import generic as g
except BaseException:
import generic as g
class AdjacencyTest(g.unittest.TestCase):
def test_radius(self):
for radius in [0.1, 1.0, 3.1459, 29.20]:
m = g.trimesh.creation.cylinder(
radius=radius, height=radius * 10)
# remov... |
43711 | import datetime
import io
import json
import zipfile
from pathlib import Path
import pyrsistent
import pytest
import yaml
from aiohttp import web
from openapi_core.shortcuts import create_spec
from yarl import URL
from rororo import (
BaseSettings,
get_openapi_context,
get_openapi_schema,
get_openapi_... |
43714 | import gensim
import sys
import glob
import codecs
from nltk.tokenize import RegexpTokenizer
import glob
import sys
class CorpusReader():
"""
Reads corpus from gzip file.
"""
def __init__(self, files):
if isinstance(files, str):
self.files = [files]
else:
self... |
43792 | from bokeh.models.sources import ColumnDataSource
from bokeh.transform import cumsum
from functools import partial
from typing import List, Type
from jira_analysis.chart.base import Axis, IChart, Chart
from jira_analysis.defect_rate.issue import Issue
from .plot.donut import DefectRateDonut
def generate_defect_chart... |
43799 | import soundfile as sf
import torch
import torch.nn.functional as F
from fairseq.data import Dictionary
from bol.utils.helper_functions import move_to_cuda
def get_feature(filepath):
def postprocess(feats, sample_rate):
if feats.dim == 2:
feats = feats.mean(-1)
assert feats.dim() == ... |
43844 | from datetime import datetime
from getopt import GetoptError, getopt
from socket import AF_INET, SOCK_STREAM, socket as Socket
from sys import stderr
from typing import List, NoReturn
from ..io import DVRIPClient
from ..message import EPOCH
from . import EX_USAGE, guard, prog_connect
def usage() -> NoReturn:
print('... |
43858 | import torch.utils.data as data
import os
import numpy as np
import cv2
#/mnt/lustre/share/dingmingyu/new_list_lane.txt
class MyDataset(data.Dataset):
def __init__(self, file, dir_path, new_width, new_height, label_width, label_height):
imgs = []
fw = open(file, 'r')
lines = fw.readlines()
... |
43859 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="workdown",
version="0.0.4",
author="<NAME>",
author_email="<EMAIL>",
description="Write Markdown and have it published and hosted on Cloudflare Workers",
long_description=long_descript... |
43873 | from ChipseqReport import *
import xml.etree.ElementTree
import Glam2
def computeMastCurve(evalues):
'''compute a MAST curve.
see http://www.nature.com/nbt/journal/v26/n12/extref/nbt.1508-S1.pdf
returns a tuple of arrays (evalues, with_motifs, explained )
'''
if len(evalues) == 0:
rais... |
43874 | import unittest
from django.apps import apps
from tethys_config.apps import TethysPortalConfig
class TethysConfigAppsTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_TethysPortalConfig(self):
app_config = apps.get_app_config('tethys_config')
... |
43910 | import fileinput as fin
# funcs:
def findValWithFormat(line):
lines.append(line)
taken = line.split(" ")
raw_val = taken[-1]
val = raw_val.split("/")[-1]
val = val[0:-2]
if 'us' in val:
val = float(val[0:val.find('us')])
val = val/1000
else:
val = float(val[0:val.find('ms')])
return val
def getCellNum(l... |
43945 | from overrides import overrides
from allennlp.data import Instance
from allennlp.common.util import JsonDict
from allennlp.predictors.predictor import Predictor
@Predictor.register('nfh_classification')
class NfhDetectorPredictor(Predictor):
""""Predictor wrapper for the NfhDetector"""
@overrides
def _js... |
43947 | import numpy as np
from unityagents import UnityEnvironment
"""UnityEnv is a wrapper around UnityEnvironment
The main purpose for this Env is to establish a common interface which most environments expose
"""
class UnityEnv:
def __init__(self,
env_path,
train_mode = True... |
43949 | import torch
from torch import nn
import pdb, os
from shapely.geometry import *
from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.signal import argrelextrema
import random
import string
all_types = [[1,2,3,4],[1,2,4,3],[1,3,2,4... |
43950 | import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
perc_heads = st.number_input(label='Chance of Coins Landing on Heads', min_value=0.0, max_value=1.0, value=.5)
graph_title = st.text_input(label='Graph Title')
binom_dist = np.random.binomial(1, perc_heads, 1000)
list_of_means =... |
43953 | import sys
import emailprotectionslib.dmarc as dmarc
from MaltegoTransform import *
mt = MaltegoTransform()
mt.parseArguments(sys.argv)
domain = mt.getValue()
mt = MaltegoTransform()
try:
dmarc_record = dmarc.DmarcRecord.from_domain(domain)
#print spf_record
mt.addEntity("maltego.Phrase","DMARC Record: "... |
44005 | import tkinter as tk
class ScrolledFrame(tk.Frame):
def __init__(self, parent, vertical=True, horizontal=False):
super().__init__(parent)
# canvas for inner frame
self._canvas = tk.Canvas(self)
self._canvas.grid(row=0, column=0, sticky='news') # changed
# create right scr... |
44012 | import os
import sys
import unittest
from test.support import run_unittest, import_module
# Skip tests if we don't have threading.
import_module('threading')
# Skip tests if we don't have concurrent.futures.
import_module('concurrent.futures')
def suite():
tests = unittest.TestSuite()
loader = unittest.TestL... |
44029 | import ipaddress
from collections import defaultdict
from autonetkit.design.utils import filters
from autonetkit.design.utils.general import group_by
from autonetkit.network_model.types import LAYER3_DEVICES
def assign_loopbacks(topology):
"""
@param topology:
"""
layer3_nodes = [n for n in topology... |
44041 | from django import VERSION
if VERSION < (1, 6):
# Before django 1.6, Django was not able to find tests in tests/tests.py
from .tests import *
|
44051 | import discord
from discord.ext import commands
class UserBlacklisted(commands.CommandError):
"""
An exception when the user is blacklisted from the bot
"""
pass
|
44082 | from django.core.files.uploadedfile import SimpleUploadedFile
from easy_tenants import tenant_context_disabled
from easy_tenants.storage import TenantFileSystemStorage
def test_default_storage(tenant_ctx, settings):
tenant_id = str(tenant_ctx.id)
s = TenantFileSystemStorage()
file = SimpleUploadedFile("t... |
44105 | import os
import sys
import imp
import argparse
import time
import math
import numpy as np
from utils import utils
from utils.imageprocessing import preprocess
from utils.dataset import Dataset
from network import Network
from evaluation.lfw import LFWTest
def main(args):
paths = [
r'F:\data\face-recog... |
44144 | from collections import namedtuple
from turtle import fd, heading, lt, pd, position, pu, rt, setheading, setposition # pylint: disable=no-name-in-module
from pudzu.utils import weighted_choice
class LSystem:
Rule = namedtuple("Rule", "predecessor successor weight", defaults=(1.0,))
def __init__(self, axio... |
44155 | from starling_sim.basemodel.output.kpis import KPI
import logging
import pandas as pd
class KpiOutput:
def __init__(self, population_names, kpi_list, kpi_name=None):
# name of the kpi, will compose the kpi filename : <kpi_name>.csv
if kpi_name is None:
if isinstance(population_names... |
44156 | import torch
from torch import nn as nn
from torch.nn import functional as F
from torch.autograd import Variable
from model.tensorized_layers.graphsage import BatchedGraphSAGE
class DiffPoolAssignment(nn.Module):
def __init__(self, nfeat, nnext):
super().__init__()
self.assign_mat = BatchedGraph... |
44157 | import os
import pyblish.api
from openpype.lib import OpenPypeMongoConnection
class IntegrateContextToLog(pyblish.api.ContextPlugin):
""" Adds context information to log document for displaying in front end"""
label = "Integrate Context to Log"
order = pyblish.api.IntegratorOrder - 0.1
hosts = ["web... |
44182 | from .model_action import ModelAction
class HVACTemplate(ModelAction):
# this shows the ip to si conversion rate
# if unit is 'ip', then multiply this rate.
# for window it is the U-value
# convert U-value IP to SI
# The conversion will change w/ft2 to w/m2 if ip shows
NUM_HVAC = 14
def _... |
44209 | import matplotlib.pyplot as plt
import numpy as np
def plot_convolution(f, g):
fig, (ax1, ax2, ax3) = plt.subplots(3, 1)
ax1.set_yticklabels([])
ax1.set_xticklabels([])
ax1.plot(f, color='blue', label='f')
ax1.legend()
ax2.set_yticklabels([])
ax2.set_xticklabels([])
ax2.plot(g, color=... |
44224 | import logging
import math
import torch
import torch.nn as nn
from vedastr.models.bodies import build_sequence_decoder
from vedastr.models.utils import build_torch_nn
from vedastr.models.weight_init import init_weights
from .registry import HEADS
logger = logging.getLogger()
@HEADS.register_module
class Transforme... |
44233 | from django.db import models
__all__ = ('PostSaveImageField',)
class PostSaveImageField(models.ImageField):
def __init__(self, *args, **kwargs):
kwargs['null'] = True
kwargs['blank'] = True
super(PostSaveImageField, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls,... |
44236 | import sys
import soundcard
import numpy
import pytest
skip_if_not_linux = pytest.mark.skipif(sys.platform != 'linux', reason='Only implemented for PulseAudio so far')
ones = numpy.ones(1024)
signal = numpy.concatenate([[ones], [-ones]]).T
def test_speakers():
for speaker in soundcard.all_speakers():
ass... |
44280 | from pycoin.networks.bitcoinish import create_bitcoinish_network
network = create_bitcoinish_network(
network_name="Monacoin", symbol="MONA", subnet_name="mainnet",
wif_prefix_hex="b0", sec_prefix="MONASEC:", address_prefix_hex="32", pay_to_script_prefix_hex="37",
bip32_prv_prefix_hex="0488ade4", bip32_pu... |
44299 | import sublime
def pkg_settings():
# NOTE: The sublime.load_settings(...) call has to be deferred to this function,
# rather than just being called immediately and assigning a module-level variable,
# because of: https://www.sublimetext.com/docs/3/api_reference.html#plugin_lifecycle
return sublime.loa... |
44308 | import torch
from torch import nn, Tensor
from typing import Tuple
from ..components import ResidualRNN
__all__ = ['Encoder', 'RNNEncoder', 'GRUEncoder']
class Encoder(nn.Module):
def __init__(self, input_size, hidden_size, embedding_dim, num_layers, bidirectional, device, pad_token=0, drop_rate=0.1):
s... |
44309 | import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
class LabelSmoothingCrossEntropy(torch.nn.Module):
def __init__(self):
super(LabelSmoothingCrossEntropy, self).__init__()
def forward(self, x, target, smoothing=0.1):
confidence = 1. - smoothing... |
44312 | import matplotlib
import numpy as np
import time
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
VOC_BBOX_LABEL_NAMES = (
'fly',
'bike',
'bird',
'boat',
'pin',
'bus',
'c',
'cat',
'chair',
'cow',
'table',
'dog',
'horse',
'moto',
'p',
'plant',
... |
44332 | from .abc import ABCTokenGenerator, Token
from .consistent import ConsistentTokenGenerator
from .single import SingleTokenGenerator
from .util import get_token_generator
|
44383 | from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('libretto', '0009_auto_20150423_2042'),
]
operations = [
migrations.AlterModelOptions(
name='pupitre',
options={'ordering': ('-soliste', 'partie'), 'verbose_name': 'p... |
44404 | from system import System
from src.basic.sessions.cmd_session import CmdSession
class CmdSystem(System):
def __init__(self):
super(CmdSystem, self).__init__()
@classmethod
def name(cls):
return 'cmd'
def new_session(self, agent, kb):
return CmdSession(agent, kb)
|
44412 | import re
from typing import List
from .consts import *
# =================== #
# INTERNALS FUNCTIONS #
# =================== #
def my_re_escape(text):
escape_char = r"[]"
returned_text = ""
for c in text:
if c in escape_char:
returned_text += "\\"
returned_text += c
retur... |
44458 | import torch
import torch.nn.functional as F
from ..models.progressive import ProGANGenerator, ProGANDiscriminator
from ..modules.gan_loss import ImprovedWGANLoss
from ..modules.instance_refiner import InstanceRefiner
from tools.utils import to_cuda
from models import load_network, save_network, print_network
... |
44465 | from chroma_core.lib.storage_plugin.api import attributes
from chroma_core.lib.storage_plugin.api.identifiers import GlobalId, ScopedId
from chroma_core.lib.storage_plugin.api.plugin import Plugin
from chroma_core.lib.storage_plugin.api import resources
from chroma_core.lib.storage_plugin.api import relations
version ... |
44469 | from .functions import *
from .sources import *
from .sinks import *
from .transfers import *
from .discrete import *
from .linalg import *
from .displays import *
from .connections import *
url = "https://petercorke.github.io/bdsim/" + __package__
|
44502 | import torchvision
__all__ = ["plot_compare"]
def plot_compare(sr, hr, baseline, filename):
"""
Plot Super-Resolution and High-Resolution image comparison
"""
sr, hr, baseline = sr.squeeze(), hr.squeeze(), baseline.squeeze()
grid = torchvision.utils.make_grid([hr, baseline, sr])
torchvision.... |
44505 | import numbers
import xnmt.tensor_tools as tt
import xnmt.modelparts.decoders as decoders
import xnmt.transducers.recurrent as recurrent
import xnmt.transducers.base as transducers_base
import xnmt.expression_seqs as expr_seq
import xnmt.vocabs as vocabs
class SimultaneousState(decoders.AutoRegressiveDecoderState):
... |
44512 | TEST_TEMP_RAW = 529191
TEST_TEMP_CMP = 24.7894877676
TEST_PRES_RAW = 326816
TEST_PRES_CMP = 1006.61517564
TEST_ALT_CMP = 57.3174
def test_temperature():
from tools import SMBusFakeDevice
from bmp280 import BMP280
from calibration import BMP280Calibration
dev = SMBusFakeDevice(1)
# Load the fake ... |
44555 | import sys
sys.path.insert(0, '../')
from mocap.settings import get_amass_validation_files, get_amass_test_files
from mocap.math.amass_fk import rotmat2euclidean, exp2euclidean
from mocap.visualization.sequence import SequenceVisualizer
from mocap.math.mirror_smpl import mirror_p3d
from mocap.datasets.dataset import Li... |
44558 | from django.test import TestCase
from review.models import Review
class TestReviewModel(TestCase):
'''
Test suite for review modules.
'''
def setUp(self):
'''
Set up test data for the review model.
'''
Review.objects.create(
feedback='Test rev... |
44560 | from openprocurement.tender.core.procedure.serializers.base import ListSerializer
from openprocurement.tender.core.procedure.serializers.document import ConfidentialDocumentSerializer
from openprocurement.tender.core.procedure.serializers.parameter import ParameterSerializer
from openprocurement.tender.esco.procedure.s... |
44675 | import networkx as nx
class Hierarchy:
def __init__(self, tree, column):
self.tree = tree
self.column = column
def _leaves_below(self, node):
leaves = sum(([vv for vv in v if self.tree.out_degree(vv) == 0]
for k, v in nx.dfs_successors(self.tree, node).items()),
... |
44688 | import orderedset
def find_cycle(nodes, successors):
path = orderedset.orderedset()
visited = set()
def visit(node):
# If the node is already in the current path, we have found a cycle.
if not path.add(node):
return (path, node)
# If we have otherwise already visit... |
44757 | from typing import Callable, AsyncGenerator, Generator
import asyncio
import httpx
import pytest
from asgi_lifespan import LifespanManager
from fastapi import FastAPI
from fastapi.testclient import TestClient
TestClientGenerator = Callable[[FastAPI], AsyncGenerator[httpx.AsyncClient, None]]
@pytest.fixture(scope="s... |
44767 | from data_types.user import User
class PullRequestReview:
"""
GitHub Pull Request Review
https://developer.github.com/v3/pulls/reviews/
Attributes:
id: Review id
body: Review body text
html_url: Public URL for issue on github.com
state: approved|commented|changes_requ... |
44811 | from .base_dataset import BaseDataset
from .baseline_dataset import BaselineDataset
from .refinement_dataset import RefinementDataset
__all__ = [
'BaseDataset',
'BaselineDataset',
'RefinementDataset'
]
|
44814 | import aiohttp
import asyncio
import json
import logging
import requests
from typing import cast, Iterable, List, Optional
from electrumsv.constants import TxFlags
logging.basicConfig(level=logging.DEBUG)
class TxStateWSClient:
def __init__(self, host: str="127.0.0.1", port: int=9999, wallet_name: str="worker1... |
44821 | from opendatatools.common import RestAgent, md5
from progressbar import ProgressBar
import json
import pandas as pd
import io
import hashlib
import time
index_map = {
'Barclay_Hedge_Fund_Index' : 'ghsndx',
'Convertible_Arbitrage_Index' : 'ghsca',
'Distressed_Securities_Index' : 'ghsds',
'Emerg... |
44826 | import networkx as nx
import matplotlib.pyplot as plt
from nxviz import GeoPlot
G = nx.read_gpickle("divvy.pkl")
print(list(G.nodes(data=True))[0])
G_new = G.copy()
for n1, n2, d in G.edges(data=True):
if d["count"] < 200:
G_new.remove_edge(n1, n2)
g = GeoPlot(
G_new,
node_lat="latitude",
nod... |
44838 | import numpy as np
import pandas as pd
import torch
import src.configuration as C
import src.dataset as dataset
import src.models as models
import src.utils as utils
from pathlib import Path
from fastprogress import progress_bar
if __name__ == "__main__":
args = utils.get_sed_parser().parse_args()
config =... |
44870 | import torch
import torch.nn as nn
from torch.nn import init
from torchvision import models
from torch.autograd import Variable
from resnet import resnet50, resnet18
import torch.nn.functional as F
import math
from attention import IWPA, AVG, MAX, GEM
class Normalize(nn.Module):
def __init__(self, power=2):
... |
44891 | import logging
import collections
import json
import time
import string
import random
logger = logging.getLogger(__name__)
from schematics.types import BaseType
from schematics.exceptions import ValidationError
from nymms.utils import parse_time
import arrow
class TimestampType(BaseType):
def to_native(self, ... |
44906 | from .kfold import PurgedKFold, CPKFold, generate_signals
from .score import cv_score
from .pipeline import Pipeline
from .hyper import clf_hyper_fit
from .distribution import LogUniformGen, log_uniform
from .utils import evaluate |
44907 | import tensorflow as tf
def touch(fname: str, times=None, create_dirs: bool = False):
import os
if create_dirs:
base_dir = os.path.dirname(fname)
if not os.path.exists(base_dir):
os.makedirs(base_dir)
with open(fname, 'a'):
os.utime(fname, times)
def touch_dir(base_di... |
44958 | class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
sums = sum(nums)
index = 0
res = 0
for ele in nums:
res += index*ele
index += 1
ans = res
for i in range(1,len(nums)):
res = res + sums - (len(nums))*nums[len(nums... |
44962 | import os
import re
import shutil
from ._base import DanubeCloudCommand, CommandOption, CommandError, lcd
class Command(DanubeCloudCommand):
help = 'Generate documentation files displayed in GUI.'
DOC_REPO = 'https://github.com/erigones/esdc-docs.git'
DOC_TMP_DIR = '/var/tmp/esdc-docs'
options = (
... |
44966 | import json
import os
from eg import config
from eg import substitute
from eg import util
from mock import Mock
from mock import patch
PATH_UNSQUEEZED_FILE = os.path.join(
'test',
'assets',
'pwd_unsqueezed.md'
)
PATH_SQUEEZED_FILE = os.path.join(
'test',
'assets',
'pwd_squeezed.md'
)
def _cr... |
44968 | def format_card(card_num):
"""
Formats card numbers to remove any spaces, unnecessary characters, etc
Input: Card number, integer or string
Output: Correctly formatted card number, string
"""
import re
card_num = str(card_num)
# Regex to remove any nondigit characters
return re.sub(... |
45026 | import typing as t
__all__ = ["Cell", "ListObject", ]
class Cell(t.NamedTuple):
"""Field data representation for html template"""
value: t.Any
url: t.Tuple[str, t.Dict[str, t.Union[str, int]]]
is_safe: bool = False
class ListObject(t.NamedTuple):
rows: t.List[t.List[Cell]]
has_next: bool
... |
45039 | import FWCore.ParameterSet.Config as cms
BtagPerformanceESProducer_TTBARWPBTAGCSVL = cms.ESProducer("BtagPerformanceESProducer",
# this is what it makes available
ComponentName = cms.string('TTBARWPBTAGCSVL'),
# this is where it gets the payload from
PayloadName =... |
45057 | from datetime import datetime, timezone
from ..exceptions import *
class Orders(object):
def __init__(self, session, trading_types):
super(Orders, self).__init__()
self._session = session
self._trading_types = trading_types
def generateOrderObject(self, legacy_contract_id, issuer, quan... |
45073 | import hou
import husdoutputprocessors.base as base
import os
class StagingDirOutputProcessor(base.OutputProcessorBase):
"""Output all USD Rop file nodes into the Staging Directory
Ignore any folders and paths set in the Configured Layers
and USD Rop node, just take the filename and save into a
singl... |
45074 | def useless_print(content):
'''Print the argument recieved'''
print(content)
if __name__ == "__main__":
import sys
useless_print(sys.argv[1]) |
45090 | from flask import Blueprint
order_api_blueprint = Blueprint('order_api', __name__)
from . import routes |
45112 | def version():
"""Function takes no aruguments and returns a STR value of the current version of the library. This value should match
the value in the setup.py
:param None
:return str value of the current version of the library
:rtype str
>>> version()
1.0.33
"""
print ('1.0.34') |
45120 | import boto3
import os
import uuid
from urllib.parse import unquote_plus
from PIL import Image
s3_client = boto3.client('s3')
def resize_image(picture_file_path, crop_dimensions=None):
# get the profile pics store ready
image = Image.open(picture_file_path)
if crop_dimensions:
image = image.crop(c... |
45126 | from git import Repo
import subprocess
import os, shutil
# I use this later to lazily generate an error with a message
class CustomError(Exception):
pass
repo_path = "../../"
r = Repo(repo_path)
repo_heads = r.heads # or it's alias: r.branches
repo_heads_names = [h.name for h in repo_heads]
#kokkos_src = '/Users... |
45133 | import json
from django.core.management.base import BaseCommand, CommandError
from users.models import User
class Command(BaseCommand):
help = "Exports a user information as a set of environment variables"
def add_arguments(self, parser):
parser.add_argument("user_id", type=int)
def handle(sel... |
45171 | import torch
import torchvision
from torchvision import transforms
def load_mnist_dataset(train_batch_size, test_batch_size=1):
train_set = torchvision.datasets.MNIST(".", train=True, transform=transforms.Compose([transforms.ToTensor()]), download=True)
test_set = torchvision.datasets.MNIST(".", train=False, ... |
45176 | from __future__ import absolute_import, print_function, unicode_literals
import os
import shutil
import stat
import sys
import tempfile
from io import StringIO, open
from subprocess import list2cmdline
from textwrap import dedent
import ksconf.ext.six as six
from ksconf.__main__ import cli
from ksconf.conf.parser im... |
45184 | from django.db import models
# from django.contrib.auth.models import User
from apps.users.models import CustomUser
# 引入Enum类型
from enum import Enum
from enumfields import EnumIntegerField
class BillType(Enum):
OUTGO = 0 # 账目类型.支出
INCOME = 1 # 账目类型.收入
class Categorys(models.Model):
"""
账目明细分类表
... |
45189 | from common import *
os.chdir(EXTERNAL_DIR)
PKGS = env('PKGS', 'all')
ninja_template = read_file(f'{SCRIPT_DIR}/install_deps_{OS_LOWER_CASE}.ninja.in')
write_file(f'install_deps_{OS_LOWER_CASE}.ninja', ninja_template.format(**ENV_PARAMS))
for key, val in ENV_PARAMS.items():
print(f'{key} = {val}')
shel... |
45208 | from RecoEgamma.EgammaElectronProducers.gsfElectrons_cfi import ecalDrivenGsfElectrons
lowPtGsfElectronsPreRegression = ecalDrivenGsfElectrons.clone(gsfElectronCoresTag = "lowPtGsfElectronCores")
from Configuration.Eras.Modifier_fastSim_cff import fastSim
fastSim.toModify(lowPtGsfElectronsPreRegression,ctfTracksTag =... |
45275 | explanations = {
'gamma': '''
Proportion of tree modifications that should use mutrel-informed choice for
node to move, rather than uniform choice
''',
'zeta': '''
Proportion of tree modifications that should use mutrel-informed choice for
destination to move node to, rather than uniform choice
... |
45292 | import pytest
import numpy as np
from csgo.analytics.distance import (
bombsite_distance,
point_distance,
polygon_area,
area_distance,
)
from csgo.analytics.coords import Encoder
class TestCSGOAnalytics:
"""Class to test CSGO analytics"""
def test_bombsite_distance(self):
"""Test bo... |
45316 | import logging
logger = logging.getLogger(__name__)
# Pump rate in mL/s (4.3 L/min)
_PUMP_RATE_ML_PER_SEC = 4300.0 / 60.0
# Default amount of water to add to the plant (in mL) when pump manager detects
# low soil moisture.
DEFAULT_PUMP_AMOUNT = 200
class Pump(object):
"""Wrapper for a Seaflo 12V water pump."""... |
45327 | import datetime
import app.helpers.helpers
from app.controllers.api import record as record_api
from app.helpers import helpers
class TestRecord:
def get_record(self, records, type_):
for record in records:
if record["type"] == type_:
return record
def test_list_no_Record... |
45333 | import subprocess
import os
def download_task_model(task):
m_path = os.path.join('/home/ubuntu/s3', "model_log_final", task,
"logs/model.permanent-ckpt")
dirs, fname = os.path.split(m_path)
dst_dir = dirs.replace('/home/ubuntu/s3', "s3://taskonomy-unpacked-oregon")
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.