id
stringlengths
3
8
content
stringlengths
100
981k
3308233
import os from os.path import basename, dirname, relpath from test.framework.base_unit_test_case import BaseUnitTestCase class TestTest(BaseUnitTestCase): """ This test class is a place for "meta-tests" that attempt to ensure that our tests are being run correctly. """ def test_all_test_subdirectorie...
3308244
from itertools import count import torch import torch.optim as optim from torch.utils.data import DataLoader from tqdm import tqdm import numpy as np import os from collections import deque from autoencoder import Autoencoder from config import * device = torch.device("cuda" if torch.cuda.is_available() else "cpu") ...
3308248
import matplotlib.pyplot as plt from tick.plot import plot_hawkes_kernels from tick.hawkes import SimuHawkesSumExpKernels, SimuHawkesMulti, \ HawkesSumExpKern end_time = 1000 n_realizations = 10 decays = [.5, 2., 6.] baseline = [0.12, 0.07] adjacency = [[[0, .1, .4], [.2, 0., .2]], [[0, 0, 0], [.6, ...
3308257
class Solution: def exclusiveTime(self, n: int, logs: List[str]) -> List[int]: time = [0] * n prev = 0 St = [] for log in logs: fid, start, timestamp = log.split(':') fid = int(fid) timestamp = int(timestamp) if start == 'start': ...
3308277
import random import json from requests.models import Response from localstack import constants, config from localstack.services.awslambda import lambda_api from localstack.utils.common import to_str def update_kinesis(method, path, data, headers, response=None, return_forward_info=False): action = headers['X-Amz...
3308294
import cPickle import argparse import numpy as np import pandas as pd from sklearn import ensemble parser = argparse.ArgumentParser(description='ML module for Pegasus') parser.add_argument('-i','--infile', help='path to the transcript annotation report', required=True) parser.add_argument('-m','--modelfile', help='pat...
3308314
import pytest import subprocess def test_struct_test(): return_code = subprocess.call("./racket-tests.sh pycket/test/struct-test.rkt", shell=True) assert return_code == 0 @pytest.mark.xfail def test_struct_test_object_name(): return_code = subprocess.call("./racket-tests.sh pycket/test/struct-test-objec...
3308319
import os import albumentations import numpy as np import torch.nn as nn from PIL import Image from torch.utils.data import Dataset, DataLoader import matplotlib.pyplot as plt # --------------------------------------------- # # Data Utils # --------------------------------------------- # ...
3308321
from flask import Flask, session from secrets import token_urlsafe from .prefixmiddleware import PrefixMiddleWare app = Flask(__name__) app.config['SECRET_KEY'] = token_urlsafe(64) # Way stronger than recommended but hey... app.config['SESSION_TYPE'] = "redis" app.wsgi_app = PrefixMiddleWare(app.wsgi_app, prefix='/...
3308347
import math import torch import torch.nn as nn from torch.nn import functional as F from cvpods.layers import ShapeSpec from cvpods.layers.metrics import accuracy class EncoderWithProjection(nn.Module): def __init__(self, cfg): super(EncoderWithProjection, self).__init__() self.proj_dim = cfg.MO...
3308361
import numpy as np import MNN nn = MNN.nn F = MNN.expr v0 = F.const([0.3,0.1, -0.3,0.4], [4]) v2 = F.const([0.3,0.1, -0.3,0.4], [4]) v1 = v0 * v0 outputDiff = F.const([0.05, 0.03, 0.02, 0.01], [4]) v0Grad = nn.grad(v1, [v0, v2], [outputDiff], "") print(v0Grad) print(v0Grad[0].read()) F.save(v0Grad, "temp.grad")
3308384
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.cuckoos import cuckoos def test_cuckoos(): """Test module cuckoos.py by downloading cuckoos.csv and testing shape of extracted data has 12...
3308395
from __future__ import print_function, division, absolute_import from collections import deque import random import numpy as np import torch from torch import nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable from simulator import dialog_config from rl.utils.replay_memor...
3308418
import os, sys sys.path.append(os.path.join(os.getcwd(), os.path.pardir)) import unittest from union_find.unionfind import UnionFind class test_unionfind(unittest.TestCase): def setUp(self): self.uf = UnionFind() self.uf.insert("a", "b") self.uf.insert("b", "c") self.uf.insert("i",...
3308452
import unittest import os from selenium import webdriver from selenium.webdriver.common.keys import Keys from time import sleep from pyramid import testing from .models import Session DEFAULT_WAIT = 5 SCREEN_DUMP_LOCATION = os.path.join( os.path.dirname(os.path.abspath(__file__)), 'screendumps' ) class TestMyV...
3308461
from __future__ import annotations import sys from argparse import ArgumentParser, Namespace import pytermgui as ptg def _process_arguments(argv: list[str] | None = None) -> Namespace: """Processes command line arguments. Note that you don't _have to_ use the bultin argparse module for this; it is just...
3308469
import os from scale import constants from utils.util_log import test_log as log from common import common_func as cf from scale import scale_common as sc class HelmEnv: milvus_chart_path = sc.get_milvus_chart_env_var() def __init__(self, release_name=None, **kwargs): self.release_name = release_nam...
3308543
def main(): if True: print "single 8 column tab for indentation" print "this lines up with previous line"
3308549
from pycsp3.problems.tests.tester import Tester, run run(Tester("cop_real") .add("Amaze", data="Amaze_simple.json") # optimum 12 .add("Amaze", data="Amaze_2012-03-07.dzn", prs_py="Amaze_ParserZ.py", prs_jv="") # optimum 315 .add("Auction", data="Auction_example.json") # optimum 54 .add("Auction", da...
3308564
from ..RESTapiwrap import * class Stickers(object): __slots__ = ['discord', 's', 'log'] def __init__(self, discord, s, log): #s is the requests session object self.discord = discord self.s = s self.log = log def getStickers(self, directoryID, store_listings, locale): store_listings = str(store_listings).lo...
3308569
import numpy as np import matplotlib.pyplot as plt from .utils import rotate_coords,rotate_to_obs_plane def get_wake_cartesian(rp,phip,npts,rmin,rmax,HonR,q): ''' planet wake formula from Rafikov (2002) ''' rplot = np.linspace(rmin,rmax,npts) rr = rplot/rp phi = phip + np.sign(rmax-rmin)*(1....
3308631
import pytest import hls4ml import numpy as np from pathlib import Path from tensorflow.keras.models import Model from tensorflow.keras.layers import Input, Embedding test_root_path = Path(__file__).parent @pytest.fixture(scope='module') def data(): X = np.random.randint(10, size=(32, 100)) return X @pytest....
3308636
import pandas as pd import numpy as np import re import bayesianpy import logging import os from sklearn.cross_validation import KFold from sklearn.metrics import r2_score import matplotlib.pyplot as plt pattern = re.compile("([A-Z]{1})([0-9]{1,3})") def get_cabin_floor_and_number(cabin): if not isinstance(cabi...
3308637
from leapp.models import Model, fields from leapp.topics import SystemFactsTopic class SELinuxFacts(Model): topic = SystemFactsTopic runtime_mode = fields.Nullable(fields.StringEnum(['enforcing', 'permissive'])) static_mode = fields.StringEnum(['enforcing', 'permissive', 'disabled']) enabled = fields...
3308656
import pickle import os import numpy as np import argparse from matplotlib import pyplot as plt import matplotlib import glob import pandas as pd from tqdm import tqdm parser = argparse.ArgumentParser(description='save annotations') parser.add_argument('--vis', action='store_true', default=False, h...
3308661
import numpy as np from keras.layers.embeddings import Embedding from keras.callbacks import Callback import csv def make_fixed_embeddings(glove, seq_len): glove_mat = np.array(glove.values()) return Embedding(input_dim = glove_mat.shape[0], output_dim = glove_mat.shape[1], weights = [g...
3308699
import requests import logging import os import re from syzscope.interface.utilities import request_get, extract_vul_obj_offset_and_size, regx_get from bs4 import BeautifulSoup from bs4 import element syzbot_bug_base_url = "bug?id=" syzbot_host_url = "https://syzkaller.appspot.com/" num_of_elements = 8 class Crawler...
3308783
from __future__ import print_function import Pyro4 @Pyro4.behavior(instance_mode="single") class SingleInstance(object): @Pyro4.expose def msg(self, message): print("[%s] %s.msg: %s" % (id(self), self.__class__.__name__, message)) return id(self) @Pyro4.behavior(instance_mode="session", inst...
3308799
DOCKER_CONTENTS = """ ##################################### APT ###################################### RUN apt-get -o Acquire::ForceIPv4=true update \\ && apt-get -o Acquire::ForceIPv4=true install -yq --no-install-recommends \\ %s && apt-get clean \\ && rm -rf /var/lib/apt/lists/* """ def write(DOCKER_FILE, packag...
3308808
from typing import List class Solution: def my_sum(self, code, l, s, e): return sum(code[(i + l) % l] for i in range(s + l, e + l)) def decrypt(self, code: List[int], k: int) -> List[int]: ls, l = [], len(code) for i, e in enumerate(code): if k > 0: n = sel...
3308817
import numba as nb import numpy as np from math import lgamma as _lgamma from . import norm as _norm, t as _t @nb.njit def _qexp(x, q): if q == 1: return np.exp(x) alpha = 1.0 - q arg = 1.0 + alpha * x if arg <= 0: return 0 le = np.log(arg) / alpha return np.exp(le) @nb.njit ...
3308822
from __future__ import print_function def main(): print('__name__ is', __name__) print('__package__ is', __package__) from . import SPAM print(SPAM) if __name__ == '__main__': print('__name__ IS __main__') print('__package__ is', __package__) main()
3308840
from __future__ import annotations import math import os import logging import pathlib import threading from collections import defaultdict from dataclasses import dataclass from tempfile import TemporaryFile from typing import List, Optional, Union, Tuple, Dict, Generator, IO, Callable from .tools import ( gener...
3308856
from .basemodel import BaseModel from .gcn import GCN from .savn import SAVN __all__ = ["BaseModel", "GCN", "SAVN"] variables = locals()
3308869
class C(object): @property def p1(self): return 1 @p1.setter def p1(self, val): pass @property def p2(self): return 1 @p2.deleter def p2(self, val): pass def p3(self): return 1 p3 = property(p3) def p3...
3308895
from setuptools import setup, Extension setup( name = 'secure-graphene', packages = ['secure_graphene'], version = '0.1.2', license='MIT', description = 'Python library that assists you in securing your GraphQL API against malicious queries', author = '<NAME>', autho...
3308969
import numpy as np import pickle import os import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import style from PIL import Image, ImageDraw, ImageFont from sklearn.cluster import DBSCAN from scipy.spatial import distance # OnNotOn ################################################...
3308981
import io import logging from PIL import Image from pyscreenshot.plugins.backend import CBackend log = logging.getLogger(__name__) class PySide2BugError(Exception): pass app = None class PySide2GrabWindow(CBackend): name = "pyside2" def grab_to_buffer(self, buff, file_type="png"): from PyS...
3308986
import json import os.path import uuid from typing import Iterable, Mapping, Optional import storage class FileStorage(storage.Storage): def __init__(self, base_dir: str): self._base_dir = base_dir def _user_path(self): return os.path.join(self._base_dir, "users.json") def create_user(s...
3309026
import matplotlib matplotlib.use('Agg') # or 'PS', 'PDF', 'SVG' import matplotlib.pyplot as plt import numpy as np import seaborn as sns def plot_2Dscatter(data, title, export_pdf=False, show=False): sns_style = "white" sns_palette = "colorblind" sns.set(style=sns_style, palette=sns_palette) # n_s...
3309072
import math import torch import torch.nn.functional as F from torch import nn from typing import List from timm.models.layers import trunc_normal_ from .grained_sample import ( grained_sample_compress, grained_sample_decompress, grained_sample_index_to_patch, grained_sample_compress_dense, grained...
3309096
from eospy.cleos import Cleos ce = Cleos(url='https://api.eosargentina.io') # Get info get_info=ce.get_info() print(get_info) # Get head block number from info head = get_info['head_block_num'] print('Head Block number is', head)
3309114
from typing import Any, Dict, Optional from appdaemon.plugins.hass.hassapi import Hass from cx_const import DefaultActionsMapping from cx_core.integration import EventData, Integration LISTENS_TO_ID = "id" LISTENS_TO_UNIQUE_ID = "unique_id" class DeCONZIntegration(Integration): name = "deconz" def get_defa...
3309126
from scapy.all import * def scan(target,interface=None): try: os_ttl = {'Linux/Unix 2.2-2.4 >':255,'Linux/Unix 2.0.x kernel':64,'Windows 98':32,'Windows':128} pkg = IP(dst=target,ttl=128)/ICMP() if interface: ans, uns = sr(pkg,retry=5,timeout=3,inter=1,verbose=0,iface=i...
3309137
import numpy as np def value_iteration(transitions, rewards, gamma=0.95, theta=1e-5): rewards = np.expand_dims(rewards, axis=2) values = np.zeros(transitions.shape[0], dtype=np.float32) delta = np.inf while delta >= theta: q_values = np.sum(transitions * (rewards + gamma * values), axis=2) ...
3309143
import logging, sys, time, os, re, binascii, subprocess, ast import serial, socket, serial.tools.list_ports, select import websocket # the old non async one serialtimeout = 0.5 serialtimeoutcount = 10 wifimessageignore = re.compile("(\x1b\[[\d;]*m)?[WI] \(\d+\) (wifi|system_api|modsocket|phy|event|cpu_start|heap_ini...
3309148
import unittest import numpy as np import prml.nn as nn class TestAdd(unittest.TestCase): def test_add(self): npa = np.random.randn(4, 5) npb = np.random.randn(4, 5) a = nn.asarray(npa) b = nn.asarray(npb) c = a + b self.assertTrue(np.allclose(c.value, npa + npb)) ...
3309154
from typing import List from geom2d import Circle, Rect, Segment, Point, Polygon, Vector from graphic.svg.attributes import attrs_to_str from graphic.svg.read import read_template __segment_template = read_template('line') __rect_template = read_template('rect') __circle_template = read_template('circle') __polygon_te...
3309165
import pathlib import setuptools HERE = pathlib.Path(__file__).parent README = (HERE / "README.md").read_text() setuptools.setup( name="aws-lambda-publish-shared-event", version="0.15.0", entry_points={ "console_scripts": [ "publish-shared-event=aws_lambda_publish_shared_event.__main_...
3309180
import argparse import csv import os import random from functools import partial from math import ceil, sqrt from multiprocessing import Pool, cpu_count from pathlib import Path from typing import List import librosa import torch import torchaudio from pesq import pesq from pystoi import stoi from scipy.io import wavf...
3309290
import torch import numpy as np import random from copy import deepcopy def corrupt_spans(text, mask_ratio=0.15, prefix=None): """T5-style Masked Language Modeling with corrupted span prediction Args: text Returns: source_text (masked_text) target_text Ex) (in ...
3309329
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer # create sentiment analyzer object analyzer = SentimentIntensityAnalyzer() def sentiment_analyzer_scores(text): score = analyzer.polarity_scores(text) lb = score['compound'] if lb >= 0.05: return 'positive' elif (lb > -0.05) ...
3309345
import keras.backend as K def focal_loss(target, output, gamma=2): output /= K.sum(output, axis=-1, keepdims=True) eps = K.epsilon() output = K.clip(output, eps, 1. - eps) return -K.sum(K.pow(1. - output, gamma) * target * K.log(output), axis=-1)
3309371
import unittest import numpy as np from numpy.testing import assert_array_almost_equal from skgstat import models, stmodels class TestSumModel(unittest.TestCase): def setUp(self): # spatial range = 10; spatial sill = 5 self.Vx = lambda h: models.spherical(h, 10, 5) # temporal range = 5;...
3309396
from dataflows import Flow, dump_to_sql from datapackage_pipelines.wrapper import ingest from datapackage_pipelines.utilities.flow_utils import spew_flow def flow(parameters): return Flow( dump_to_sql( parameters['tables'], engine=parameters.get('engine', 'env://DPP_DB_ENGINE'), ...
3309418
import threading def sum_and_product(a, b): s, p = a + b, a * b print(f'{a}+{b}={s}, {a}*{b}={p}') t = threading.Thread( target=sum_and_product, name='SumProd', args=(3, 7) ) t.start() """ $ python start.py 3+7=10, 3*7=21 """
3309467
from __future__ import print_function, division from fenics import * import collections def epsilon(u): """ Define strain. """ return 0.5 * (nabla_grad(u) + nabla_grad(u).T) def sigma(u, mu=1, lmbda=1.25): """ Define stress. """ d = u.geometric_dimension() return lmbda * nabla_div(u) * Identity(...
3309501
import os import numpy as np from discretize.utils import mkvc from discretize.utils.code_utils import deprecate_method import warnings try: from discretize.mixins.vtk_mod import InterfaceTensorread_vtk except ImportError: InterfaceTensorread_vtk = object class TensorMeshIO(InterfaceTensorread_vtk): """...
3309512
import uuid from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("labels", "0013_populate_uuid_values"), ] operations = [ migrations.AlterField( model_name="category", name="uuid", field=models.UUIDField(de...
3309591
from importlib import reload import partition import partition.Partitioner #import partition.Analyzer import partition.Propagator #from partition.models import model_xiang_2020_robot_arm, model_gh1, model_gh2, random_model, lstm import numpy as np import pandas as pd import itertools import matplotlib.pyplot as plt fro...
3309603
from enum import Enum, auto class DataLevel(Enum): """Enum of the different Data Levels""" R0 = auto() # Raw data in camera or simulation format R1 = auto() # Raw data in common format, with preliminary calibration DL0 = auto() # raw archived data in common format, with optional zero suppression ...
3309656
def get_diffs(list1, list2): """Finds new users and lost users and returns a tuple containing them in this order. If there's no difference return false.""" new = list(set(list1) - set(list2)) lost = list(set(list2) - set(list1)) if bool(new + lost): return (new, lost) else: ret...
3309667
from functools import partial, cached_property from types import MappingProxyType as mappingproxy from .core_functions import arity, declaration, to_callable, make_xor, signature from .fn_placeholders import compile_ast, call_node from .signature import Signature from .utils import mixed_accessor, lazy_string from .._...
3309670
import torch from torchvision import transforms def get_transform(): return transforms.Compose([ transforms.Resize(224), transforms.CenterCrop(224), _convert_image_to_rgb, transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], s...
3309715
from celery.utils.log import get_task_logger import json import datetime # setup the mappings for the index volmap = """ { "mappings" : { "volperf":{ "properties":{ "name":{"type":"string","index":"not_analyzed"}, "vol_name":{"type":"string","index":"not_analyze...
3309736
import torch from torch import nn from transformers import BertModel import numpy as np class JointBERT(nn.Module): def __init__(self, model_config, device, slot_dim, intent_dim, req_dim, dataloader, intent_weight=None,req_weight=None): super(JointBERT, self).__init__() self.slot_num_la...
3309740
import numpy as np import matplotlib.pyplot as plt def graph(formula, x_range, xlabel, ylabel, filename): x = np.array(x_range) y = eval(formula) plt.plot(x, y) plt.xlim(0, 5000) # plt.xscale("log", nonposx='clip') # plt.yscale("log", nonposy='clip') # plt.show() plt.xlabel(xlabel) ...
3309754
from PIL import Image files = dataAvailable = [32,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,...
3309769
from xendit.models._base_model import BaseModel class InvoiceRetailOutlet(BaseModel): """Retail Outlet data detail in Invoice (API Reference: Invoice) Attributes: - retail_outlet_name (str) - payment_code (str) - transfer_amount (int) """ retail_outlet_name: str payment_code: s...
3309782
import munch DEFAULTS = {} # data paths DEFAULTS['psp_data_root'] = 'samples/psp' # train.py DEFAULTS['logdir'] = 'logs' DEFAULTS['vgg_weights_dir'] = 'checkpoints' # cloth dataloader DEFAULTS['verts_mask_path'] = 'data/vertices_cloth_mask.pkl' DEFAULTS['smpl_faces_path'] = 'data/smplx_faces.npy' DEFAULTS['sample_i...
3309789
import os from config import Config from controllers.imageInfo import routes from database import db from database.entities.images import DatabaseImage from database.entities.objectInfo import DatabaseObject from database.models.Cars import Cars from database.models.Coordinates import Coordinates from database.models.O...
3309827
import argparse import json import logging from collections import defaultdict from pathlib import Path from script_utils.common import common_setup from tqdm import tqdm from tao.utils.download import are_tao_frames_dumped def main(): # Use first line of file docstring as description if it exists. parser =...
3309851
import unittest import os import numpy as np import cvxpy as cvx from statistical_clear_sky.algorithm.minimization.right_matrix\ import RightMatrixMinimization class TestRightMatrixMinimization(unittest.TestCase): def test_minimize_with_large_data(self): input_power_signals_file_path = os.path.abspath( ...
3309898
from bibliopixel.animation.matrix import Matrix from bibliopixel.colors import COLORS import os class Mainframe(Matrix): COLOR_DEFAULTS = ('bgcolor', COLORS.Off), ('color', COLORS.Red) def __init__(self, layout, scroll=True, **kwds): super().__init__(layout, **kwds) self.scroll = scroll ...
3309944
import time # Global paths glob_lib_paths = [r'C:\Git\pyDMPC\pyDMPC\ModelicaModels\ModelicaModels', r'C:\Git\modelica-buildings\Buildings', r'C:\Git\AixLib-master\AixLib'] glob_res_path = r'C:\TEMP\dymola' glob_dym_path = r'C:\Program Files\Dymola 2020\Modelica\Library\python_interface\dymola.egg' # Working d...
3309947
import tensorflow as tf from tensorflow.keras.layers import * from tensorflow.keras.models import Model ''' model architecture with Batch Normalization ''' def normalize_tensor_image(inp): out = tf.convert_to_tensor(inp) out = tf.dtypes.cast(out, tf.float32) out = (out - 127.5) / 127.5 return out d...
3309956
import tensorflow.keras as keras def create_dnn_model(img, params): nfil = params.get('nfil', 5) dprob = params.get('dprob', 0.05 if params['batch_norm'] else 0.25) nlayers = params.get('nlayers', 3) x = keras.layers.BatchNormalization()(img) for layer in range(nlayers): numnodes = (nlayers - layer) * nf...
3309975
from insights.contrib.soscleaner import SOSCleaner from mock.mock import Mock from pytest import mark def _soscleaner(): soscleaner = SOSCleaner() soscleaner.logger = Mock() return soscleaner @mark.parametrize(("line", "expected"), [ ("radius_ip_1=10.0.0.1", "radius_ip_1=10.230.230.1"), ( ...
3309990
import info class subinfo(info.infoclass): def setTargets(self): self.svnTargets["master"] = "https://github.com/lukesampson/concfg.git" self.targetInstallPath["master"] = "dev-utils/concfg/" self.description = "Concfg is a utility to import and export Windows console settings like fonts ...
3309996
import os import sys import os.path as path # Path to where the bindings live sys.path.append(os.path.join(os.path.dirname(__file__), "../build/")) sys.path.append(os.path.join(os.path.dirname(__file__), "../src/")) import polyscope import potpourri3d as pp3d import sys import argparse import numpy as np def main()...
3310018
import os from ..package import Package from ..util import run from .python import Python class PyElfTools(Package): """ :identifier: pyelftools-<version> :param version: version to download :param python_version: which Python version to install the package for """ def __init__(self, version:...
3310025
import re import os import time import argparse import tweepy import datasets import logging import stanza import random from word_generator import WordGenerator logger = logging.getLogger(__name__) MAX_TWEET_LENGTH = 250 def _inverse_definition_str(word_with_definition): return f"{word_with_definition.word}: {...
3310072
from py_ecc.bls import G2ProofOfPossession as bls # Enough keys for 256 validators per slot in worst-case epoch length privkeys = [i + 1 for i in range(32 * 256)] pubkeys = [bls.SkToPk(privkey) for privkey in privkeys] pubkey_to_privkey = {pubkey: privkey for privkey, pubkey in zip(privkeys, pubkeys)}
3310091
class PrintTemplateService(object): """ :class:`fortnox.PrintTemplateService` is used by :class:`fortnox.Client` to make actions related to PrintTemplate resource. Normally you won't instantiate this class directly. """ """ Allowed attributes for PrintTemplate to send to Fortnox backend se...
3310096
import logging from tenacity import after_log, before_log, retry, stop_after_attempt, wait_fixed from app.db.database import get_default_bucket from app.tests.api.api_v1.test_login import test_get_access_token logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) max_tries = 60 * 5 # 5 minut...
3310155
import dash_core_components as dcc import dash_html_components as html import pandas as pd from dash.dependencies import Input, Output, State import pathlib # get relative data folder PATH = pathlib.Path(__file__).parent DATA_PATH = PATH.joinpath("data").resolve() def demo_explanation(demo_mode): if demo_mode: ...
3310183
from inventory import Inventory from item import Item import pygame import unittest from buffalo import utils import os utils.init( caption='Adept', fullscreen=True ) class TestCharacter: def init(self): from createCharacter import CreateCharacter self.c = CreateCha...
3310213
import tensorflow as tf import tensorlayer as tl import helpers def focal_lossIII(prediction_tensor, target_tensor, weights, gamma=2., epsilon=0.00001, ): """Compute loss function. This function was adapted from the Ten...
3310221
import logging import traceback from datetime import datetime as dt from pathlib import Path from typing import List, Optional import pytz from .components import ( Backtester, Configuration, MarketClosedException, MarketProvider, NotSafeToTradeException, TimeAmount, TimeProvider, Trad...
3310240
from PDFSegmenter.util import constants class TableClusterMerging(object): def __init__(self, result): self.result = result def get_merged_results(self): """ :return: """ for page in self.result: prev = None for elt in ["table"]: # TODO possi...
3310265
import pytest from runboat.exceptions import RepoOrBranchNotSupported from runboat.settings import BuildSettings, settings def test_get_build_settings() -> None: assert settings.get_build_settings("OCA/mis-builder", "15.0") == [ BuildSettings(image="ghcr.io/oca/oca-ci/py3.8-odoo15.0:latest") ] wi...
3310281
from . import _ffi as ffi from wasmtime import WasmtimeError from ctypes import byref, POINTER, pointer from typing import Union, List, Optional, Any class ValType: _ptr: "pointer[ffi.wasm_valtype_t]" _owner: Optional[Any] @classmethod def i32(cls) -> "ValType": ptr = ffi.wasm_valtype_new(ffi...
3310290
from invoke import task from faasmcli.util.config import get_faasm_config @task def create(ctx): """ Set up skeleton Faasm config """ get_faasm_config()
3310295
from nose.tools import (assert_equal, raises) from mock import Mock from s3_encryption.envelope import EncryptionEnvelope from s3_encryption.exceptions import IncompleteMetadataError from . import BaseS3EncryptTest class TestEnvelope(BaseS3EncryptTest): def setUp(self): self.mock_materials = Mock(descr...
3310312
from src.util.oracle.gas_source_base import GasSourceBase class ZoltuGasOracle(GasSourceBase): API_URL = "https://gas-oracle.zoltu.io/" async def gas_price(self) -> int: resp = await self._base_request() # To convert the provided values to gwei, divide by 10 # https://docs.ethgasstati...
3310326
from CommonTools.RecoAlgos.trackingParticleConversionRefSelectorDefault_cfi import trackingParticleConversionRefSelectorDefault as _trackingParticleConversionRefSelectorDefault trackingParticleConversionRefSelector = _trackingParticleConversionRefSelectorDefault.clone() from Configuration.ProcessModifiers.premix_stage...
3310329
from datetime import datetime import json import logging import re import requests import time import zlib from urllib.parse import urlencode from zentral.core.events import event_from_event_d from zentral.core.stores.backends.base import BaseEventStore logger = logging.getLogger('zentral.core.stores.backends.datadog...
3310332
import enum from dataclasses import dataclass class VoyagerConnectionStatus(enum.Enum): DISCONNECTED = 0 CONNECTING = 1 CONNECTED = 2 class VoyagerAuthenticationStatus(enum.Enum): SUCCESS = 0 AUTHENTICATING = 1 AUTHENTICATION_FAILED = 2 @dataclass class HostInfo: host_name: str = 'loca...
3310336
from queue import Queue, LifoQueue from .bulk_subtitle import process_series from .conf import settings from .utils import mpv_color_to_plex from .video_profile import VideoProfileManager from .svp_integration import SVPManager import time import logging log = logging.getLogger('menu') TRANSCODE_LEVELS = ( ("1080...
3310353
import unittest from nlglib.microplanning import * from nlglib.macroplanning import * from nlglib.realisation.basic import Realiser, RealisationVisitor def get_clause(): clause = Clause(NounPhrase(Word('you', 'NOUN')), VerbPhrase(Word('say', 'VERB'), String('hello'))) return clause def ...