content
stringlengths
5
1.05M
import pytest # No need for cleanup @pytest.mark.admin def test_001_i_want_to_force_unsupported_operation_towards_admin_interface(h2ac_admin): requestBody = { "foo":"bar" } responseBodyRef = { "result":"false", "response":"unsupported operation" } # Send POST response = h2ac_admin.postDict("/admin/v1/foo"...
offer_service = paymill_context.get_offer_service() offers_list = offer_service.list()
# Copyright 2020 Alejandro Suazo # # 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 writi...
# -*- coding: utf-8 -*- import hashlib def hashfile(path, algorithm='md5', blocksize=65536): hasher = hashlib.new(algorithm) with open(path, 'rb') as afile: buf = afile.read(blocksize) while len(buf) > 0: hasher.update(buf) buf = afile.read(blocksize) return ha...
""" Script used to test the adaptive interpolation and the evaluation of said interpolant """ from __future__ import absolute_import import os import time import numpy as np import numpy.linalg as la import scipy.special as spec import matplotlib as mpl mpl.use("Agg") import matplotlib.pyplot as plt fr...
import pandas as pd from pandas.core.indexes.base import Index import scipy.sparse as sparse import numpy as np import random import implicit from sklearn.preprocessing import MinMaxScaler from sklearn import metrics import yaml import logging grouped_df = '' df = '' event_type_strength = '' interactions_df = '' arti...
import numpy as np import time import os import glob from obspy import Trace, Stream def test_multi_channel_xcorr(): from eqcorrscan.utils.correlate import get_stream_xcorr chans = ['EHZ', 'EHN', 'EHE'] stas = ['COVA', 'FOZ', 'LARB', 'GOVA', 'MTFO', 'MTBA'] n_templates = 20 stream_len = 10000 ...
import argparse import os from datasets_util.celeb_dataset_utils import ClebAMaskedFaceDatasetCreator from datasets_util.fei_face_dataset_util import FeiFaceFrontAlignMaskedFaceDatasetCreator, \ FeiFaceOriginalMaskedFaceDatasetCreator from datasets_util.georgia_tech_face_dataset import GeorgiaTechMaskedFaceDataset...
from functools import wraps from inspect import signature from .container import IOCContainer _container = IOCContainer() def _get_filled_arguments(func, *args, **kwargs): function_signature = signature(func) ba = function_signature.bind_partial(*args, **kwargs) return ba.arguments def inject(**dec_...
# -*- coding: utf-8 -*- import bpy SHAPE_SPHERE = 0 SHAPE_BOX = 1 SHAPE_CAPSULE = 2 MODE_STATIC = 0 MODE_DYNAMIC = 1 MODE_DYNAMIC_BONE = 2 def shapeType(collision_shape): return ('SPHERE', 'BOX', 'CAPSULE').index(collision_shape) def collisionShape(shape_type): return ('SPHERE', 'BOX', 'C...
""" You are given a two-dimensiona array(matrix) of potentially unequal height and width containing letters. This matrix repreents a boggle board. You are also given a list of words. Write a fucntion that returns an array of all the words contained in the boggle board. A word is constructed in the boggle board by conn...
import numpy as np import torch import torch.nn as nn from torch.nn import Module, init from torch.distributions.multivariate_normal import MultivariateNormal from utils.ops import * initializers={'w': init.kaiming_normal_, 'b': lambda b: truncated_normal(b, std=1e-3)} down_sampling_op = nn.AvgPool2d(kernel_size=2...
"""Implementation of MLP-Mixer model.""" from typing import Optional, Sequence import flax.linen as nn import jax.numpy as jnp import ml_collections from scenic.model_lib.base_models.multilabel_classification_model import MultiLabelClassificationModel from scenic.model_lib.layers import attention_layers from scenic.m...
# coding=utf-8 import enum class HTTPMethod(enum.Enum): """HTTP methods supported.""" GET = 'GET' POST = 'POST' DELETE = 'DELETE' PUT = 'PUT' class DestinationTypes(enum.Enum): """Destination types supported.""" AZURE_SQL_DW = 'azuresql_dw' POSTGRES = 'postgres' REDSHIFT = 'red...
from typing import Union, List, Dict from renormalizer.mps import Mpo, Mps, MpDm class Property(): ''' class to store the properties mpos and expectation results. Property can be added in any TdMpsJob class (see example in thermalprop) to define the user-defined mpos whose expectation values shoul...
# Database from Metamusic import database import multiprocessing import os import traceback import sys from Metamusic import decoder from Metamusic import fingerprint from Metamusic.recognize import FileRecognizer, MicrophoneRecognizer import binascii from typing import Union, Iterator, Optional class MetaMusic(): ...
import sys, os import subprocess import pprint import re class BGS_P4Error(Exception): pass def _p4run(cmd, workspace): cmd = ["p4", "-c", workspace] + cmd p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (i, o, e) = (p.stdin, p.stdout, p.std...
#!/usr/bin/env python """ This is an example script showing how to do parallel regridding with ESMPy. ESMPy abstracts some of the parallel components from the user so that very few calls to mpi4py methods are necessary. """ import ESMF import matplotlib.pyplot as plt from mpi4py import MPI import numpy as np __autho...
from django.contrib.auth import authenticate, login from OctaHomeCore.baseviews import * from OctaHomeCore.models import * from models import * import json import base64 class appSecrityClass(object): def securityFails(self, request): if 'HTTP_AUTHORIZATION' in request.META: auth = request.META['HTTP_AUTHORIZATI...
#!/usr/bin/env python import sys import random import time inp = open(sys.argv[1], "r") try: num = int(inp.read()) except: num = -1 inp.close() delay = random.randrange(0,5) time.sleep(delay) result = open("result.txt", "w") result.write("{} {}".format(num,random.randrange(0,10))) result.close() print(num)
""" A collection of utilities for cinema camera handling. """ import numpy as np import math def convert_pose_to_camera(iPosition, iFocalPoint, iViewUp, pose, camType): """Converts input eye, focal point and view up using the pose and camType and returns (neweye, newfp, newviewup)""" def VecNormalize(V1)...
# façaum programa que leia os nome dos alunos r mostre a ordem sorteada from random import shuffle n1 = input('Digite o nome do aluno 1: ') n2 = input('Digite o nome do aluno 2: ') n3 = input('Digite o nome do aluno 3: ') n4 = input('Digite o nome do aluno 4: ') lista = [n1,n2,n3,n4] shuffle(lista) #embaralha a lista...
#!/usr/bin/python #encoding:utf-8 import random import sys #参数1 LANDSCAPE/PORTRAIT 是否横屏,默认横屏 #参数2 实际分辨率(x,y),例如:2560*1440 #参数3 apk包名package和活动进程名,例如:com.boyaa.enginegzguiyangqp.main*com.boyaa.enginegzguiyangqp.main.Game #参数4 fileName #命令如:python customizationMonkeyTest.py LANDSCAPE 2560*1440 # com.boyaa.engi...
from domain.ErrorTypes import ErrorTypes from validity import IncomingEdgeValidityChecker from utils import CodeGenerationUtils import os def generate_code(args): node = args["node"] requireds_info = args["requireds_info"] edges = args["edges"] checklist={"df_count": {1}, "model_count": {0}} erro...
import unittest from solution import * from pprint import pprint from time import time class ZeroMatrixTest(unittest.TestCase): def setUp(self) -> None: self.sol = Solution1() def test_1(self) -> None: matrix = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 1], [1, 1, ...
# Copyright (c) 2015 Presslabs SRL # # 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 writ...
import pytest used = False @pytest.fixture(autouse=True) def one(): global used used = True pass @pytest.fixture(params=[1, 2]) def two(): pass def test_me(two): global used assert used
"""Request Common Models. These are only for internal module use.""" # pylint: disable=invalid-name, too-many-instance-attributes, line-too-long, too-many-lines from __future__ import annotations from dataclasses import dataclass from datetime import datetime from .base import BaseModel from .const import ProtocolTyp...
"""Resource module for main view.""" import logging from aiohttp import web import aiohttp_jinja2 from sprint_webserver.services import ( InnstillingerService, ) class Main(web.View): """Class representing the main view.""" async def get(self) -> web.Response: """Get route function that return ...
import textwrap from PIL import ImageDraw def draw_multiple_line_text(image, text, font, text_color, text_start_height): """Calculates center of image and separate lines""" draw = ImageDraw.Draw(image) image_width, image_height = image.size y_text = text_start_height lines = textwrap.wrap(text, w...
__all__ = ('undefined',) class Undefined: def __bool__(self): return False def __repr__(self): return '<undefined>' undefined = Undefined()
import xgboost as xgb #Using the XGBoost Classifier. I have used just a few combinations here and there without GridSearch or RandomSearch because the dataset was pretty small xg_cl = xgb.XGBClassifier(objective='binary:logistic', n_estimators=500,seed=42,learning_rate=0.01,max_depth=5,colsample_bytree=0.75,subsample=...
import time import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set_theme(style="whitegrid") tips = sns.load_dataset("tips") rand_funcs = [ ("uniform", np.random.uniform), ("normal", np.random.uniform), ("lognormal", np.random.uniform) ] def one_swarm(randoms, compact): start...
from ignite.handlers.checkpoint import ModelCheckpoint from ignite.handlers.timing import Timer from ignite.handlers.early_stopping import EarlyStopping
from typing import Union, List import numpy as np import torch import abc class WriterBase(object): @abc.abstractmethod def plot_lines(self, legend_str, tb_str, arrays_to_plot, step, x_lim = None, ...
from lib.utils import preview_generator, gen_even_batches, batching_row_gen, randomize_and_loop, str_to_labels, load_img from lib.config import gen_config import numpy as np from fire import Fire import pandas as pd def row_has_class(class_id): def row_has_class_i(row): target = str_to_labels(row['Target...
from django.views import generic from .models import Book from djando.views.generic.edit import CreateView class IndexView(generic.ListView): table_name = 'books/index.html' def get_queryset(self): return Book.objects.all() class BookCreate(CreateView): model = Book fields = ['name', 'autho...
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. # See file LICENSE for terms. from . import _version from ._lib import libkvikio # type: ignore from .cufile import CuFile # noqa: F401 __version__ = _version.get_versions()["version"] def memory_register(buf) -> None: return libkvikio.memo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import functools from typing import List, Tuple, Generator, Sequence import numpy from trolls.spaces.range import Range # from typing import Type, TypeVar, Union, from warg import Number, cached_property # SpaceType = TypeVar("Space", bound=Space) from typing import It...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ("news", "0001_initial"), ] operat...
# Generated by Django 2.2.7 on 2020-06-24 15:31 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('rooms', '0002_cruduser'), ] operations = [ migrations.RemoveField( model_name='student', ...
def capitalize_name(name: str) -> str: capitalized_name = name.capitalize() return capitalized_name def uppercase_name(name: str) -> str: return name.upper() def foo(number: int) -> bool: return number > 0
#TODO #Calculate interventions when AP is engaged and accelerator is pressed #Find blinker Data to use in interventions # Created by Chuck Cook on Jan 28 2022 # # import os #OS level functions import os from paho.mqtt import client as mqtt_client import time # The time library is useful for delays from datetime impo...
def area (largura, altura): Area = largura * altura print(f"A área de um terreno {largura}x{altura} é de {Area}m².") print("-- Controle de Terrenos --\n", "- " * 20) Largura = float(input("Largura (m): ")) Altura = float(input("Alutra (m): ")) area(Largura, Altura)
import numpy as np import cv2 as cv from umucv.util import ROI, putText from umucv.stream import autoStream from umucv.util import Help help = Help( """ HELP WINDOW Press left-click to create a ROI C: captures the ROI and show the difference between capture and live ROI X: deletes the ROI ESC: exit h: show/hide ...
# -*- coding: utf-8 -*- from __future__ import division import sys, os def test_ner_parser__presentation_for_long_sentences(dataset, recognize_function=None ,verbose = True): ''' :function_parser: function that takes string sentence and return list of ner_objects :param :dataset: test_dataset :fu...
"""Bass sounds""" from . import Sample BASS_DNB_F = Sample('bass_dnb_f', 0.8705442176870748) BASS_DROP_C = Sample('bass_drop_c', 2.3589115646258505) BASS_HARD_C = Sample('bass_hard_c', 1.5) BASS_HIT_C = Sample('bass_hit_c', 0.6092517006802721) BASS_THICK_C = Sample('bass_thick_c', 3.9680725623582767) BASS_VOXY_C = S...
# Volatility # Copyright (C) 2007-2013 Volatility Foundation # # This file is part of Volatility. # # Volatility is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your o...
from django.conf import settings from django.db import models from django.utils import timezone from django.contrib.postgres.fields import ArrayField class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) excerpt = m...
import logging def get_mailing_list(): try: with open("/tmp/mailing_list.csv") as mailing_list: return mailing_list.read().split(",") except FileNotFoundError: logging.warning("Mailing list file not found, attempting download from bucket.") from app import cloud_stores ...
# Copyright (c) Paul Tagliamonte, 2012, under the terms and conditions of the # COPYING file. import datetime as dt from geoparse.point import Point from geoparse.defuzz import defuzz_raw, defuzz_feet, defuzz_meters, \ rolling_average d = 1234567890 delt = 3 # if it's outside this, per se...
import numpy as np import matplotlib.pyplot as plt import sys #if your computer doesn't have matplotlib,you should install it on cmd by using following code. #python -mpip install -U matplotlib #Assuming near plane is the image plane class Camera: ''' define a class named "camera" with the parameters saved in...
import os import platform from selenium import webdriver ''' Here we initialise basic WebDriver We use Webdrivber 2.42, Chromedriver https://sites.google.com/a/chromium.org/chromedriver/downloads DO NOT forget to update the webdriver ''' ''' Webdriver initialization If host is darwin - use Chromedirver for MAC Else...
#!/usr/bin/env pytest import functools import inspect import itertools import operator import torch from torch import sub from torch.nn import functional as F import torchdynamo.testing from torchdynamo.testing import requires_static_shapes d = torch.ones(10, 10) e = torch.nn.Linear(10, 10) flag = True def constan...
# Copyright (c) 2019 Graphcore Ltd. All rights reserved. """ Tests covering ResNeXt training. """ import pytest import unittest import statistics from test_common import get_csv, run_train, cifar10_data_dir @pytest.mark.category2 @pytest.mark.ipus(1) class TestCifar10ResNeXtTraining(unittest.TestCase): """Testi...
from TableauApi import TableauApi
import pickle from collections import deque memory = deque(maxlen=20000) print(len(memory)) memory.append((1,2,3,4)) memory.append((5,6,7,8)) print(len(memory)) print(memory) with open('trial.dump', 'wb') as f: pickle.dump(memory,f) # memory_copy = deque(maxlen=20000) # print(len(memory_copy)) with open('trial.d...
from app.vocabulary import parse_annotation_into_token_groups # annotations[image][staff] REAL_RAW_ANNOTATIONS = { "001-cavatine-01.png": [ "clef.G-2 b0 b3 b-1 b2 time.C q-4 | h-4 ( q-3 q2 | ) h1 * q1 ( | q0 q3 q0 q1 | ) h2 * q2 |", "clef.G-2 b0 b3 b-1 b2 q2 ( s=3 =e=2 =e=1 =e2 q4 ) q3 | q2 ( q1 q3...
#! /usr/bin/env python from nexson.syntax import detect_nexson_version, get_empty_nexson from peyutil import UNICODE from nexson import validate_nexson from nexson.test.support.pathmap import get_test_path_mapper from peyutil.test.support.helper import testing_write_json as twj from peyutil.test.support.helper import t...
seeds = { 'glider': { 'seed': [ [1,0,0], [0,1,1], [1,1,0] ], 'co': [1,1] }, 'beacon': { 'seed': [ [1,1,0,0], [1,1,0,0], [0,0,1,1], [0,0,1,1] ], 'co': [1,1] }, 'glider_g...
# -*- coding: utf8 -*- import Board import gaddag from Player import Player from AI import StrategyMoveGeneration from Interface import Iface def main(): b = Board.Board() b.LoadSquares() p1 = Player(); p2 = Player(); s = StrategyMoveGeneration(); iface = Iface(player1=p1,player2=p2); s.board = iface.boa...
#!python39 ## # デイリーイベントを各2回(1日に参加できる上限)挑戦する # 事前準備 # - バトルがautoモードになっていること # - バトルが早送りになっていること # - 戦闘力が40,000以上になっていること ## from lib.adb import Adb from lib import last_bullet from time import sleep # デイリーイベント画面を開く def go_to_daily_event(adb): last_bullet.go_to_home(adb) sleep(3) last_bullet.go_to_battle(adb) slee...
import os import numpy as np import pysam import pytest from .. import barcode, encodings, platform, consts data_dir = os.path.split(__file__)[0] + '/data/' # TEST BARCODES @pytest.fixture def barcode_set(): return barcode.Barcodes.from_whitelist( data_dir + '1k-august-2016.txt', barcode_length=16) ...
import socket, select server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_sock.bind(("0.0.0.0", 8888)) server_sock.listen(16) CONNECTIONS = [server_sock] UNAMES = {} class Room: def __init__(self, name): self.nam...
import os, sys # read which disk this is about target = str(np.loadtxt('whichdisk.txt', dtype='str')) # make a FITS file of the CLEAN model image exportfits('data/'+target+'_data.model', 'data/'+target+'_data.cleanmodel.fits', overwrite=True)
#!/usr/bin/env python # Copyright (c) 2016 Intel, Inc. # # 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 b...
import asyncio import hashlib import time import typing import aiormq from aiormq.types import ConfirmationFrameType from pamqp import specification as spec from bspider.config.default_settings import QUEUE_ARG from bspider.utils import singleton from .session import ChannelSession from .pool import Pool @singleto...
from flask import Blueprint, request, Response, jsonify from db_credentials import cur, connection admin_bp = Blueprint('admin_bp', import_name=__name__) @admin_bp.route('/admin/review',methods=['POST']) def review_product(): product_id = request.form['product_id'] decision = request.form['decision'] if(...
# coding: utf-8 """ Cloudbreak API Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloud...
""" # 500 G, 特殊一行 f = open() # 方法1 for line in f: pass # 方法2 f.readlines() # 方法3 # 读取一行 f.read(4096) """ def my_read_lines(fb, sep_symbol): # 读取缓存,解决一次while循环里 残余数据的遗留,将其合并到下一次读取的 chunk buff = "" while True: while sep_symbol in buff: pos = buff.index(sep_symbol) yield buff[:pos] # 更新缓存为 记号加上分隔符的长度 b...
import scrapy from scrapy import Spider from scrapy.http import Request from scrapy.loader import ItemLoader from PluMA.items import PlumaItem #import requests from scrapy.crawler import CrawlerProcess import string import os.path, time class PluginnamesSpider(scrapy.Spider): name = 'pluginNames' allowed_doma...
import pytest import yass def test_can_initialize_config(path_to_config): yass.Config.from_yaml(path_to_config) def test_throws_error_if_channels_mismatch(path_to_config_with_wrong_channels): with pytest.raises(ValueError): yass.Config.from_yaml(path_to_config_with_wrong_channels) def test_cannot_...
from Source.Modulation.Digital import FSK from Source.Tools.SignalFactory import cosFactory import numpy as np import matplotlib.pyplot as plt import math from scipy import signal def window_rms(a, window_size): a2 = np.power(a,2) window = np.ones(window_size)/float(window_size) return np.sqrt(np.convolve(a2, w...
import random # Randomize the number def randomize(): return random.randrange(1,2000)
# Generated by Django 3.1.14 on 2022-02-15 11:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("vote", "0009_votingevent_polling_period"), ] operations = [ migrations.AddField( model_name="votingevent", name="di...
#----- A simple TCP based server program in Python using send() function ----- import socket # Create a stream based socket(i.e, a TCP socket) # operating on IPv4 addressing scheme serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM); # Bind and listen serverSocket.bind(("127.0.0.1",9090)); # c...
import os import numpy as np import pandas as pd import xgboost import xgboost as xgb from sklearn.impute import KNNImputer from sklearn.model_selection import train_test_split import time import pickle from .preprocess import preprocess_data data_path = os.path.join(os.path.dirname(__file__), "Data", "database.csv") ...
from flask import request from assemblyline.al.common.security import get_password_hash, check_password_requirements from assemblyline.common.isotime import now_as_iso from assemblyline.common.user_defaults import ACCOUNT_DEFAULT from al_ui.apiv3 import core from al_ui.api_base import api_login, make_api_response fro...
# Copyright 2019 Takenori Yamamoto # # 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 agre...
# Simple modalities test import atomica as au from atomica.programs import Covout import sciris as sc import numpy as np def test_modalities(): old_settings = np.seterr(all="raise") def run_test(coverage, outcomes, baseline, expected=None, imp_interaction=None): # cov - 1D vector of coverages ...
# Copyright (c) 2021 PaddlePaddle 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 app...
from twisted.cred.portal import IRealm from twisted.internet.defer import maybeDeferred from twisted.web.resource import IResource from zope.interface import implements from jumpmaplist.cred.guard import ExpireTokenResource from jumpmaplist.routers import PublicRouter, PrivateRouter from jumpmaplist.resource import Ap...
#!/usr/bin/env python3 """problem_179.py Problem 179: Consecutive positive divisors Find the number of integers 1 < n < LIMIT, for which n and n + 1 have the same number of positive divisors. For example, 14 has the positive divisors 1, 2, 7, 14 while 15 has 1, 3, 5, 15. """ __author__ = 'Curtis Belmonte' import c...
from sympy import * from Irene import * # introduce symbols and functions x = Symbol('x') y = Symbol('y') z = Symbol('z') s = Symbol('s') # objective function obj = -((pi**2 + 12**2 * (x**2 + y**2)) + (pi**2 - 4 * 12**2 * (x**2 + y**2)) ) / (((pi**2 + 12**2 * (x**2 + y**2))) * (2 + .5 * (x**2 + y**2))) # numera...
''' Collaborators: none jake shienberg ''' def add(x,y): return x + y def subtract(x,y): return x-y def divide(x,y): return x/y def multiply(x,y): return x*y calc_num_one = int(input("enter a number ")) calc_num_two = int(input("enter another number ")) input_one = int(input("enter 1 to add, 2 to subtrac...
from textwrap import dedent import pragma from .test_pragma import PragmaTest global_x = 10 def global_f(y): return global_x + y class TestLambdaLift(PragmaTest): def test_basic(self): x = 3 @pragma.lift(annotate_types=True, imports=False) def f(y): return x + y ...
""" Tools for working with collections """ import itertools import sys if sys.version_info < (3, 3): from collections import Iterable else: from collections.abc import Iterable __author__ = "Vince Reuter" __email__ = "vreuter@virginia.edu" __all__ = ["is_collection_like", "powerset"] def is_collection_lik...
from collections import namedtuple from .processing_utils import stat_per_interval SimpleStatProcessingData = namedtuple('SimpleStatProcessingData', ['name', 'processor', 'field']) def process(old_stats, new_stats, interval): stat_data = [SimpleStatProcessingData(name='rx_bps', processor=stat_per_interval, field...
import pytest from .. import * # this is not necessary but mypy complains if it's not included from .. import CompileOptions options = CompileOptions() def test_and_two(): args = [Int(1), Int(2)] expr = And(args[0], args[1]) assert expr.type_of() == TealType.uint64 expected = TealSimpleBlock([ ...
""" benchmarking """ from conformation.calc_energy_benchmark import calc_energy_benchmark, Args if __name__ == '__main__': calc_energy_benchmark(Args().parse_args())
import os from setuptools import setup, find_packages def read(fname): with open(os.path.join(os.path.dirname(__file__), fname)) as f: return f.read() setup( name='airavata-python-sdk', version='1.0.1', packages=find_packages(), package_data={'transport': ['*.ini'], 'sample': ['*.pem']}...
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2012, Yujin Robot # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must r...
# -*- coding: utf-8 -* from flask_restful import Api # default api first from lingobarter.core.app import LingobarterModule class LingobarterApi(Api): """ The Lingobarter Api class. You need to initialize it with each Flask Blueprint object. >>> module = LingobarterModule('name', __name__) >>>...
""" @package mi.dataset.parser @file marine-integrations/mi/dataset/parser/flort_kn_auv @author Jeff Roy @brief Parser and particle Classes and tools for the flort_kn_auv data Release notes: initial release """ __author__ = 'Jeff Roy' __license__ = 'Apache 2.0' import ntplib from mi.core.log import get_logger log =...
try: from browser import timer except: class ajax: pass from . import futures class HTTPException(Exception): """ A class representing a HTTPRequest error """ def __init__(self, request): super(HTTPException, self).__init__() self.req = request class HTTPRequest(f...
import os import requests as rq import time def download_season(season: int) -> str: # cookies = { # "fsbotchecked": "true" # } print(f"Downloading data for {season} season...") url = f"https://www.footballdb.com/games/index.html?lg=NFL&yr={season}" print("\t\t" + url) headers = { ...
import pandas as pd import numpy as np # from copy import deepcopy from sklearn.utils.metaestimators import _BaseComposition from sklearn.preprocessing import LabelEncoder from sklearn.externals.joblib import Parallel, delayed from gravity_learn.utils import (force_array, check_is_fitte...
from django.contrib.auth.forms import PasswordChangeForm from django.shortcuts import render, redirect from django.urls import reverse from django.views import View from django.views.generic import FormView from accounts.forms import TelemetryForm from utils.mixins import PaginateObjectMixin from django.views.generic.b...
import os from flask import Flask, request, send_from_directory, redirect from flask_cors import CORS from server.app import register_blueprints, register_extensions from server.config import Config """ Create flask app and routing""" app = Flask( __name__, static_url_path="", static_folder="server/src/...
num = int(input('Digite um número: ')) print('O número {}, tem como antecessor {} e como seu sucessor o número {}.'.format(num, num-1, num+1))