filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_0_1861 | import argparse
import sys
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.tensorboard import SummaryWriter
from sklearn.model_selection import train_test_split
import utils
from utils import Dataset
from model import LinearNet
import matplotlib.pyplot as plt
import imageio
impo... |
the-stack_0_1862 | """
Copyright BOOSTRY Co., Ltd.
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 distr... |
the-stack_0_1866 | """Procedures to build trajectories for algorithms in the HMC family.
To propose a new state, algorithms in the HMC family generally proceed by [1]_:
1. Sampling a trajectory starting from the initial point;
2. Sampling a new state from this sampled trajectory.
Step (1) ensures that the process is reversible and thus... |
the-stack_0_1867 | # Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... |
the-stack_0_1869 | # function for bubble sort
def Bubble_Sort(list):
for i in range(0, len(list) - 1):
for j in range(0, len(list) - i - 1):
# do swapping
if list[j] > list[j + 1]:
list[j], list[j + 1] = list[j + 1], list[j]
# function to print list
def Print_list(list):
for i in r... |
the-stack_0_1870 | # model settings
model = dict(
type='CascadeRCNN',
num_stages=3,
pretrained='modelzoo://resnet50',
backbone=dict(
type='IPN_kite',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
with_att=False,
style='pytorch'),
neck=dict(
... |
the-stack_0_1871 | import os
from PIL import Image, ImageDraw, ImageColor, ImageOps
from skimage.feature import hog
import numpy as np
def sliding_window(image, stepSize, windowSize):
for y in range(0, image.size[1], stepSize):
for x in range(0, image.size[0], stepSize):
# If the current crop would be outside of ... |
the-stack_0_1873 | from unittest.mock import patch
from django.core.management import call_command
from django.db.utils import OperationalError
from django.test import TestCase
class CommandTests(TestCase):
def test_wait_for_db_ready(self):
'''Test waiting for db when db is available'''
with patch('django.db.util... |
the-stack_0_1874 | #!/usr/bin/env python3
import subprocess
import re
import sys
RESULT_RE = re.compile(r'(T|F|[^ |])')
BASIC_PROPOSITION_RE = re.compile(r'([A-Za-z]+)')
REPLACEMENTS = {'~': r'\neg', '&': r'\wedge', '|': r'\vee', '<->': r'\leftrightarrow', '->': r'\rightarrow'}
wresult = subprocess.check_output(['hatt', '-e', sys.arg... |
the-stack_0_1875 | # -*- coding: utf-8 -*-
############################ Copyrights and license ############################
# #
# Copyright 2012 Vincent Jacques <vincent@vincent-jacques.net> #
# Copyright 2012 Zearin <zearin@gonk.net> ... |
the-stack_0_1877 | ###############################################################################
#
# ChartStock - A class for writing the Excel XLSX Stock charts.
#
# Copyright 2013-2019, John McNamara, jmcnamara@cpan.org
#
from . import chart
class ChartStock(chart.Chart):
"""
A class for writing the Excel XLSX Stock charts... |
the-stack_0_1878 | from PIL import Image
import os
os.chdir("/Users/Joan/Documents/python/rex1168.github.io")
def change_size(job_name='thumbnails'):
jobs = {"thumbnails":
{'source': './static/thumbnail', 'target': './static/thumbnail-small'},
'course-covers':
{'source': './static/img/co... |
the-stack_0_1879 | # """Assignment 03: Using inverse kinematics
# """
import json
import os
from compas_fab.backends import RosClient
from compas_fab.robots import Configuration
from compas.geometry import Frame
from compas.geometry import Point
from compas.geometry import Vector
from compas_fab.utilities import write_data_to_json
# Th... |
the-stack_0_1881 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
the-stack_0_1887 | # coding: iso-8859-15
import py
import random
from pypy.objspace.std.listobject import W_ListObject, SizeListStrategy,\
IntegerListStrategy, ObjectListStrategy
from pypy.interpreter.error import OperationError
from rpython.rlib.rarithmetic import is_valid_int
class TestW_ListObject(object):
def test_is_true(... |
the-stack_0_1888 | import torch
from torch.autograd import Variable
import time
import sys
from utils import *
def val_epoch(epoch, data_loader, model, criterion, opt, logger):
print('validation at epoch {}'.format(epoch))
model.eval()
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()... |
the-stack_0_1892 | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
the-stack_0_1894 | import logging
import math
import time
from asyncio import Lock
from random import choice, randrange
from secrets import randbits
from typing import Dict, List, Optional, Set, Tuple
from hddcoin.types.peer_info import PeerInfo, TimestampedPeerInfo
from hddcoin.util.hash import std_hash
from hddcoin.util.ints import ui... |
the-stack_0_1895 | # -*- coding: utf-8 -*-
"""
All spiders should yield data shaped according to the Open Civic Data
specification (http://docs.opencivicdata.org/en/latest/data/event.html).
"""
from datetime import datetime
from pytz import timezone
from legistar.events import LegistarEventsScraper
from documenters_aggregator.spider im... |
the-stack_0_1898 | import json
import numpy as np
import os.path, datetime, subprocess
#from astropy.io import fits as pyfits
#from time import sleep
#from scipy.ndimage import gaussian_filter#, rotate
#from scipy.interpolate import interp1d
#from scipy.optimize import curve_fit
from .tools import *
from .phi_fits import *
from .phi_gen... |
the-stack_0_1901 | import ast
import copy
from vyper.exceptions import (
ParserException,
InvalidLiteralException,
StructureException,
TypeMismatchException,
FunctionDeclarationException,
EventDeclarationException
)
from vyper.signatures.function_signature import (
FunctionSignature,
VariableRecord,
)
fr... |
the-stack_0_1902 | import datajoint as dj
import numpy as np
from numpy.lib import emath
from functools import reduce
from .common_session import Session # noqa: F401
schema = dj.schema('common_interval')
# TODO: ADD export to NWB function to save relevant intervals in an NWB file
@schema
class IntervalList(dj.Manual):
definitio... |
the-stack_0_1906 | # Copyright 2018 Microsoft Corporation
#
# 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... |
the-stack_0_1907 | import logging
import sys
import time
class ColorFormatter(logging.Formatter):
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
RESET_SEQ = '\033[0m'
COLOR_SEQ_TEMPLATE = '\033[1;{fore_color_int}m'
LEVELNO_TO_COLOR_INT_DICT = {
logging.WARNING: YELLOW,
logging.... |
the-stack_0_1908 | """ Module who handle updating """
import os
from dataclasses import dataclass
from pathlib import Path
from shutil import copyfile
from typing import Union
from packaging.version import InvalidVersion, Version
from inupdater.config import SettingsManager
from inupdater.ui import UserInterface
@dataclass(eq=False, ... |
the-stack_0_1909 | import yaml
import json
from teuthology.test import fake_archive
from teuthology import report
class TestSerializer(object):
def setup(self):
self.archive = fake_archive.FakeArchive()
self.archive.setup()
self.archive_base = self.archive.archive_base
self.reporter = report.ResultsR... |
the-stack_0_1910 | import sys
import pyportus as portus
class ConstFlow():
INIT_RATE = 1000000
def __init__(self, datapath, datapath_info):
self.datapath = datapath
self.datapath_info = datapath_info
self.rate = ConstFlow.INIT_RATE
self.datapath.set_program("default", [("Rate", self.rate)])
... |
the-stack_0_1911 | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... |
the-stack_0_1912 | import collections
from typing import Any, Iterable, Iterator, Optional, Tuple
from river.base.typing import Dataset
from river.metrics import RegressionMetric
from .base import Forecaster
from .metric import HorizonMetric
TimeSeries = Iterator[
Tuple[
Optional[dict], # x
Any, # y
Itera... |
the-stack_0_1913 | import os
IMAGE_SIZE = 256
NUM_WORKERS = 4
TRAINING_BATCH_SIZE = 8
VAL_BATCH_SIZE = 8
EPOCH = 20
MILESTONES = [5, 10, 15]
SAVE_EPOCH = 5
WARM_EPOCH = 1
CHECKPOINTS_PATH = './checkpoints/'
LEARNING_RATE = 0.1
WEIGHT_DECAY = 5e-4
MOMENTUM = 0.9
GAMMA = 0.2
FRAME_SAMPLE = 10 |
the-stack_0_1915 | #!/usr/bin/env python3
# Publications markdown generator for academicpages
# Data format: JSON, see publications.json for examples
# Caution: Overwrites ../auto-publications.md
import json
JOURNAL_PUB = "journal"
CONFERENCE_PUB = "conference"
SHORT_PUB = "short"
ARXIV_PUB = "arxiv"
DISSERTATION_PUB = "dissertation"
P... |
the-stack_0_1918 | """
Provides functionality to emulate keyboard presses on host machine.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/keyboard/
"""
import voluptuous as vol
from homeassistant.const import (
SERVICE_MEDIA_NEXT_TRACK, SERVICE_MEDIA_PLAY_PAUSE,
... |
the-stack_0_1920 | import random
from datetime import datetime
import csv
import os
import sys
import struct
import argparse
import datetime
import paho.mqtt.client as mqtt
times = []
acc1 = []
acc2 = []
acc3 = []
ane1 = []
ane2 = []
ane3 = []
node = ""
# Buat fungsi umpan balik ketika koneksi ke mqtt berhasil dilakukan.
def on_conne... |
the-stack_0_1923 | # coding=utf-8
import os, re
import time
import string
#统计某一个进程名所占用的内存,同一个进程名,可能有多个进程
def countProcessMemoey(processName):
pattern = re.compile(r'([^\s]+)\s+(\d+)\s.*\s([^\s]+\sK)')
cmd = 'tasklist /fi "imagename eq ' + processName + '"' + ' | findstr.exe ' + processName
result = os.popen(cmd).read(... |
the-stack_0_1924 | import pulumi
import pulumi.runtime
from ... import tables
class CertificateSigningRequestList(pulumi.CustomResource):
def __init__(self, __name__, __opts__=None, items=None, metadata=None):
if not __name__:
raise TypeError('Missing resource name argument (for URN creation)')
if n... |
the-stack_0_1925 | import sys
if sys.version_info[0] < 3:
import configparser
else:
import configparser
if __name__ == '__main__':
import re
CONFIG = [
{
'section_name': 'STARTUP',
'section_title': 'Startup Configuration',
'questions': [
{
... |
the-stack_0_1927 | import torch
import pyredner.transform as transform
import redner
import math
import pyredner
from typing import Tuple, Optional, List
class Camera:
"""
Redner supports four types of cameras\: perspective, orthographic, fisheye, and panorama.
The camera takes a look at transform or a cam_to_world m... |
the-stack_0_1930 | # -*- coding: utf-8 -*-
from openprocurement.api.validation import (
validate_accreditation_level
)
from openprocurement.api.utils import (
get_resource_accreditation
)
def validate_change_ownership_accreditation(request, **kwargs): # pylint: disable=unused-argument
levels = get_resource_accreditation(req... |
the-stack_0_1931 | import asyncio
import zlib
from aiocache import Cache
from aiocache.serializers import BaseSerializer
class CompressionSerializer(BaseSerializer):
# This is needed because zlib works with bytes.
# this way the underlying backend knows how to
# store/retrieve values
DEFAULT_ENCODING = None
def d... |
the-stack_0_1932 | # Copyright 2016 Osvaldo Santana Neto
#
# 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 ... |
the-stack_0_1935 | """This file is used for custom testing."""
import argparse
import os
import sys
import threading
import time
import requests
from google.protobuf import text_format
import Request_pb2
parser = argparse.ArgumentParser()
parser.add_argument('-st', '--start_port', help='Starting port number', type=int)
parser.add_argume... |
the-stack_0_1936 | # pylint: disable=missing-docstring
from unittest.mock import Mock, patch
from peltak import testing
from peltak.core import conf
from peltak.core import context
from peltak.core import fs
from peltak.core import types
@patch('peltak.core.fs.filtered_walk')
@testing.patch_pelconf()
def test_calls_filtered_walk_with_... |
the-stack_0_1938 | """Return True if two arrays are element-wise equal within a tolerance."""
from __future__ import annotations
import numpy
import numpoly
from ..baseclass import PolyLike
from ..dispatch import implements
@implements(numpy.allclose)
def allclose(
a: PolyLike,
b: PolyLike,
rtol: float = 1e-5,
atol: f... |
the-stack_0_1940 | import asyncio
import logging
import time
from typing import Set, List, Tuple, Optional
import ray
from ray.experimental.workflow import workflow_storage
from ray.experimental.workflow.common import (Workflow, WorkflowStatus,
WorkflowMetaData)
from ray.experimental.workfl... |
the-stack_0_1942 | #!/usr/bin/env python
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Modified from go/bootstrap.py in Chromium infrastructure's repository to patch
# out everything but the core toolchain.
#
# https://c... |
the-stack_0_1943 | # -*- coding: utf-8 -*-
"""This file contains the Task Scheduler Registry keys plugins."""
from __future__ import unicode_literals
from dfdatetime import filetime as dfdatetime_filetime
from plaso.containers import events
from plaso.containers import time_events
from plaso.lib import definitions
from plaso.lib impor... |
the-stack_0_1945 | #!/usr/bin/env python3
# Removes old files in media root in order to keep your storage requirements low
from alexacloud import settings
import datetime
import shutil
import os
media_root = settings.MEDIA_ROOT
# Delete directories that were created more than 30 minutes
now = datetime.datetime.now()
ago = now - dateti... |
the-stack_0_1947 | import functools
import operator
from collections import defaultdict
from contextlib import suppress
from typing import TYPE_CHECKING, Any, Dict, Hashable, Mapping, Optional, Tuple, Union
import numpy as np
import pandas as pd
from . import dtypes, utils
from .indexing import get_indexer_nd
from .utils import is_dict... |
the-stack_0_1948 | import cv2
#Global_vars.cap1 = cv2.VideoCapture("rtsp://10.24.72.33:554/0")
cap1 = cv2.VideoCapture(0)
cap2 = cv2.VideoCapture("rtsp://admin:Admin1234@92.125.152.58:6461")
#Global_vars.cap1 = cv2.VideoCapture("rtsp://admin:admin@10.24.72.31:554/Streaming/Channel/101")
## rtsp://192.168.2.109:554/user=admin&password=m... |
the-stack_0_1954 | import json
import logging
import os
from pathlib import Path
import psutil
import time
import signal
from collections import namedtuple
from firexapp.events.model import ADDITIONAL_CHILDREN_KEY
from firexapp.submit.uid import Uid
logger = logging.getLogger(__name__)
DEFAULT_FLAME_TIMEOUT = 60 * 60 * 24 * 2
# This ... |
the-stack_0_1955 | import torch
from torch import nn
from utils.operator import gradient
def activation_name(activation: nn.Module) -> str:
if activation is nn.Tanh:
return "tanh"
elif activation is nn.ReLU or activation is nn.ELU or activation is nn.GELU:
return "relu"
elif activation is nn.SELU:
re... |
the-stack_0_1957 | """Some macros for building go test data."""
load("//testlib:expose_genfile.bzl", "expose_genfile")
load("@io_bazel_rules_go//go:def.bzl", "go_library")
load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
def pb_go_proto_library(name, proto, genfile, visibility = None):
go_proto_library(
name = ... |
the-stack_0_1959 | import numpy as np
import copy
from supervised.algorithms.registry import AlgorithmsRegistry
from supervised.algorithms.registry import BINARY_CLASSIFICATION
class HillClimbing:
"""
Example params are in JSON format:
{
"booster": ["gbtree", "gblinear"],
"objective": ["binary:logistic"],
... |
the-stack_0_1961 | from __future__ import absolute_import
# Copyright (c) 2010-2017 openpyxl
# Simplified implementation of headers and footers: let worksheets have separate items
import re
from warnings import warn
from openpyxl.descriptors import (
Alias,
Bool,
Strict,
String,
Integer,
MatchPattern,
Typed... |
the-stack_0_1963 | # -*- coding: utf-8 -*
# 获得爬取Disasters Accidents推文所需信息
import json
from Config_Disasters_Accidents_od import get_noau_config
from datetime import datetime, timedelta
_, db, r = get_noau_config() # 数据库配置
def get_date(date):
# 获取日期集合
dates = date.split('\n')
date_list = []
for i in dates:... |
the-stack_0_1964 | from logging import getLogger
from typing import Any, Dict, List, NamedTuple, Optional, Set, Tuple
from django.db import IntegrityError
from django.utils import timezone
from eth_account import Account
from packaging.version import Version
from redis import Redis
from web3.exceptions import BadFunctionCallOutput
fro... |
the-stack_0_1965 | #!/usr/bin/env python3
import json
from pathlib import Path
from urllib.parse import urlparse
from tests.mocks.categories import CATEGORIES
from tests.mocks.kit_info import KIT_INFO
from tests.mocks.kit_sha1 import KIT_SHA1
file_path = Path(__file__).resolve()
api_mocks = file_path.parent.joinpath("apis")
ebuilds_mo... |
the-stack_0_1967 | """Pairwise genome alignment
src: {ensemblgenomes.prefix}/fasta/{species}/*.fa.gz
dst: ./pairwise/{target}/{query}/{chromosome}/sing.maf
https://lastz.github.io/lastz/
"""
import concurrent.futures as confu
import gzip
import logging
import os
import shutil
from pathlib import Path
from ..db import ensemblgenomes, p... |
the-stack_0_1968 | from cProfile import label
from IMLearn.learners.regressors import linear_regression
from IMLearn.learners.regressors import PolynomialFitting
from IMLearn.utils import split_train_test
import os
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.io as pio
pio.templates.default = "simple_... |
the-stack_0_1969 | # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (a... |
the-stack_0_1970 | from functools import partial, wraps, update_wrapper
import copy
import re
import clize.errors
from .core import _accepts_context, _call_fragment_body, collect, DROP, many as _many
from .objects import Context
__all__ = ['accumulate', 'callable', 'filter', 'many', 'format', 'regex', 'keywords',
'focus', '... |
the-stack_0_1971 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.CardFundInfo import CardFundInfo
from alipay.aop.api.domain.CardCreditInfo import CardCreditInfo
class AlipayAssetCardNewtemplateCreateModel(object):
def __init... |
the-stack_0_1972 | import pathlib
import requests
import json
import argparse
from folioclient.FolioClient import FolioClient
parser = argparse.ArgumentParser()
parser.add_argument("operation", help="backup or restore")
parser.add_argument("path", help="result file path (backup); take data from this file (restore)")
parser.add_argument(... |
the-stack_0_1973 | #Modules
import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
#Accuracy Threshold
ACCURACY_THRESHOLD = 0.95
class myCallback(tf.keras.callbacks.Callback):
def on_epoch_end(self, epoch, logs={}):
if(logs.get('acc') > ACCURACY_THRESHOLD):
print("... |
the-stack_0_1974 | import json
import sys
import iotbx.phil
import dials.util
from dials.algorithms.spot_finding import per_image_analysis
from dials.util import tabulate
from dials.util.options import OptionParser, reflections_and_experiments_from_files
help_message = """
Reports the number of strong spots and computes an estimate o... |
the-stack_0_1975 | # -*- coding: utf-8 -*-
"""
MIT License
Copyright (c) 2017 Vic Chan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify... |
the-stack_0_1978 | """ Tensorflow implementation of the face detection / alignment algorithm found at
https://github.com/kpzhang93/MTCNN_face_detection_alignment
"""
# MIT License
#
# Copyright (c) 2016 David Sandberg
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated docu... |
the-stack_0_1979 | # SPDX-FileCopyrightText: 2020 The Magma Authors.
# SPDX-FileCopyrightText: 2022 Open Networking Foundation <support@opennetworking.org>
#
# SPDX-License-Identifier: BSD-3-Clause
import time
from abc import ABC, abstractmethod
from collections import namedtuple
from typing import Any, Optional
import metrics
from co... |
the-stack_0_1980 | from struct import Struct
from types import new_class
# class init => python type to obj, value = python type
# obj encode: obj to bytes/array
# classmethod decode: bytes array (array('B', [0, 2, 255, ..])) to python type
# str obj to str, mostly str(value)
# self.value is bytes on Base class
class MetaBluezFormat(t... |
the-stack_0_1985 | #!/usr/bin/env python2
# coding=utf-8
# ^^^^^^^^^^^^ TODO remove when supporting only Python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test Hierarchical Deterministic walle... |
the-stack_0_1986 | from math import log
def tfidf(t, d, d_list):
return tf(t, d) * idf(t, d_list)
def tf(t, d):
r = 0
for term in d.split():
if t == term:
r += 1
return r
def idf(t, d_list):
d_with_t = 0
for d in d_list:
if t in d.split():
d_with_t += 1
return log(... |
the-stack_0_1987 | # pylint: disable=line-too-long, no-member
from __future__ import print_function
import pytz
from django.conf import settings
from django.core.management.base import BaseCommand
from django.db.models import Q
from django.utils import timezone
from ...decorators import handle_lock
from ...models import DataPoint, D... |
the-stack_0_1989 | # model settings
model = dict(
type='TTFNet',
pretrained='modelzoo://resnet18',
backbone=dict(
type='ResNet',
depth=18,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_eval=False,
style='pytorch'),
neck=None,
bbox_head=dict(
... |
the-stack_0_1990 | """Task I/O specifications."""
import attr
from pathlib import Path
import typing as ty
import inspect
import re
from glob import glob
from .helpers_file import template_update_single
def attr_fields(spec, exclude_names=()):
return [field for field in spec.__attrs_attrs__ if field.name not in exclude_names]
de... |
the-stack_0_1991 | """
装饰器使用
"""
import time
import functools
import decorator
def cost(func):
@functools.wraps(func)
def wapper(*args):
t1 = time.time()
res = func(*args)
t2 = time.time()
print(f'运行时间为:{str(t2 - t1)}')
return res
# return wapper()返回的是执行结果了,所以不能加括号
return wapper
... |
the-stack_0_1996 | import datetime
from dataclasses import dataclass
from typing import Dict, List, Tuple
import appdaemon.plugins.hass.hassapi as hass
@dataclass
class Preferences:
input_time: str
input_temperature: str
target_area: str
@classmethod
def from_args(cls, prefs: Dict[str, Dict[str, str]]) -> Dict[str... |
the-stack_0_1997 | from torch import nn
from transformers import BertModel, BertTokenizer, BertConfig
import json
from typing import List, Dict, Optional
import os
import torch
from collections import OrderedDict
import numpy as np
import logging
class BioBERT(nn.Module):
"""Huggingface AutoModel to generate token embeddings.
Lo... |
the-stack_0_1999 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import random
import sys
from inky import InkyWHAT
from PIL import Image, ImageFont, ImageDraw
from font_source_serif_pro import SourceSerifProSemibold
from font_source_sans_pro import SourceSansProSemibold
print("""Inky wHAT: Quotes
Display quotes on I... |
the-stack_0_2000 | #!/usr/bin/env python3
# Copyright (c) 2017-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Class for litecoind node under test"""
import contextlib
import decimal
import errno
from enum import ... |
the-stack_0_2001 | import sys
import unittest
from argparse import Namespace
from .fixtures import set_up_cluster, set_up_subparser
from kafka.tools.assigner.exceptions import ConfigurationException
from kafka.tools.assigner.actions.clone import ActionClone
from kafka.tools.assigner.models.broker import Broker
class ActionCloneTests(... |
the-stack_0_2003 | from dotenv import load_dotenv
load_dotenv("config.env")
BOT_TOKEN = "1840298314:AAFUMtMNiJpyBBt4tyGfuq_yO3ZXl88jxwk"
API_ID = 5119765
API_HASH = "ab310ff746864c1a33f3c590f1598c06"
USERBOT_PREFIX = "."
PHONE_NUMBER = "+16465640536" # Need for Userbot # Sudo users have full access to everything, don't trust anyone
LO... |
the-stack_0_2004 | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# 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 applica... |
the-stack_0_2008 | """Example on regression using YearPredictionMSD."""
import time
import torch
import numbers
import torch.nn as nn
from torch.nn import functional as F
from sklearn.preprocessing import scale
from sklearn.datasets import load_svmlight_file
from torch.utils.data import TensorDataset, DataLoader
from torchensemble.fusi... |
the-stack_0_2010 | import asyncio
import os
import sys
import traceback
import disnake
from disnake.ext import commands
if sys.platform == "win32":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
def fancy_traceback(exc: Exception) -> str:
"""May not fit the message content limit"""
text = "".join(... |
the-stack_0_2011 | import numpy as np
from sklearn.ensemble import RandomForestClassifier as SKRandomForestClassifier
from sklearn.feature_selection import SelectFromModel as SkSelect
from skopt.space import Real
from .feature_selector import FeatureSelector
class RFClassifierSelectFromModel(FeatureSelector):
"""Selects top featur... |
the-stack_0_2014 | import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')
external_stylesheets = ['https://codepe... |
the-stack_0_2015 | """
Chombo frontend tests
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#---------------------... |
the-stack_0_2017 | from jcudc24ingesterapi.models.sampling import _Sampling
from jcudc24ingesterapi import typed, APIDomainObject
from simplesos.client import SOSVersions
from simplesos.varients import _52North, SOSVariants, getSOSVariant
"""
Defines all possible data sources or in other words data input methods that can be provisi... |
the-stack_0_2018 | import torch
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from torch.utils.data import DataLoader
import dataset
import simple_net
def train_one_epoch(network, criterion, trainloader, optimizer):
network.train()
losses = []
correct = 0
total = 0
for idx, (feature, lab... |
the-stack_0_2019 | from typing import List, Optional, Callable, Union, Any, Tuple
import re
import copy
import warnings
import numpy as np
import os.path as osp
from collections.abc import Sequence
import torch.utils.data
from torch import Tensor
from .data import Data
from .utils import makedirs
IndexType = Union[slice, Tensor, np.n... |
the-stack_0_2022 | from time import sleep
import pyautogui
from textblob import TextBlob
from yandex_music_parser import YandexMusicParser
# add your Yandex mail, password and full link to your VK music page
YANDEX_MAIL = "*@yandex.com"
PASSWORD = "*"
VK_MUSIC_LINK = "https://vk.com/audios240917398"
CHROME_ICON = (215, 1055)
CHROME_URL... |
the-stack_0_2023 | from typing import Any
import requests
import pytest
from _pytest.monkeypatch import MonkeyPatch
from unittest.mock import Mock
from weather.libs.api.open_weather_map import OpenWeatherMap
from weather.libs.api.request_flow_controller import RequestFlowController
class TestOpenWeatherMap:
def test_init(self, fake... |
the-stack_0_2025 | from unittest import TestCase
from unittest import main as unittest_main
from offconf import funcs, get_func, pipe
class TestUtils(TestCase):
expr = "foo|prepend('bar_')|append('_can')"
expect = "bar_foo_can"
def test_pipe(self):
self.assertEqual(pipe("foo|b64encode", funcs), "Zm9v")
sel... |
the-stack_0_2026 | """
Copyright 2020 The OneFlow Authors. All rights reserved.
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 agr... |
the-stack_0_2028 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
the-stack_0_2032 | # coding=utf-8
"""TEC === Tools to calculate total electron content value in the ionosphere
using data derived from global navigation satellite systems."""
# Shortcut
from .glo import collect_freq_nums
from .gnss import BAND_PRIORITY
from .rinex import ObsFileV2
from .rinex import ObsFileV3
# General information
__ve... |
the-stack_0_2034 | import random, time
from UNP.Core import Account, ActTable
class Loginer:
def __init__(self):
self.mode = "001"
self.timer = -1
self.file = ""
def __str__(self):
string = "mode-" + self.mode + "_timer-" + str(self.timer)
if self.file != "":
str... |
the-stack_0_2036 | #!/usr/bin/env python
import logging
from contextlib import redirect_stdout
from io import StringIO
from itertools import count
from unittest import main
from unittest.mock import Mock
from cli_command_parser import Command, Action, no_exit_handler, ActionFlag, ParamGroup
from cli_command_parser.actions import help_a... |
the-stack_0_2038 | #!/usr/bin/env python3
"""Fetch RSS feed from phpBB forum and post it to Slack channel.
2017/Nov/15 @ Zdenek Styblik <stybla@turnovfree.net>
"""
import argparse
import logging
import sys
import time
import traceback
from typing import Dict, List
import feedparser
import rss2irc
import rss2slack
CACHE_EXPIRATION = 86... |
the-stack_0_2039 | import math
import random
import smtplib
import re
import json
import pandas as pd
import requests
from bs4 import BeautifulSoup
class PostalUtils:
def __init__(self, pc):
self.pc = str(pc)
self.data = None
def get_details(self):
import requests
self.data = requests.get(f'https... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.