content
stringlengths
5
1.05M
#!/usr/bin/env python3 import sys import os if sys.version_info[0] != 3: print("This script requires Python 3") exit(1) if 'py-json' not in sys.path: sys.path.append(os.path.join(os.path.abspath('..'), 'py-json')) import argparse import LANforge from LANforge.lfcli_base import LFCliBase from LANforge impo...
# Copyright 2018 Eddie Schoute # # 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...
# SPDX-License-Identifier: Apache-2.0 # Copyright Contributors to the Rez Project """ Creates the system platform package. """ from __future__ import absolute_import from rez.package_maker import make_package from rez.vendor.version.version import Version from rez.bind._utils import check_version from rez.system impo...
from django.forms import ModelForm from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile, Project, Rating class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] class Profil...
""" Copyright © 2021, SAS Institute Inc., Cary, NC, USA. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 """ import os import json import urllib3 import boto3 from botocore.exceptions import ClientError print("Initializing function") # Get the service resource dynamodb = boto3.resource('dynamodb') # Initi...
#!/usr/bin/python3 # -*- encoding=utf8 -*- from uuid import uuid4 import flask from flask import Flask from flask import request from flask import abort from flask_basicauth import BasicAuth app = Flask(__name__) app.config['BASIC_AUTH_USERNAME'] = 'test_user' app.config['BASIC_AUTH_PASSWORD'] = 'test_password' basi...
"""Abstract descriptions of a network analyzer. """ import base64 import csv import io import os import pickle import shutil import tarfile import numpy as np from PIL import Image import imageio from pysyrenn import Network from syrenn_proto import syrenn_pb2 as syrenn_pb class Experiment: """Abstract class descr...
import numpy as np from time import time from helpers.simulator.sim_bots import * import math import os import matplotlib.pyplot as plt class MarketGenerator(object): def __init__(self): self.market_path = "helpers/simulator/market_sim" self.s0 = None self.miu = None self.sigma = No...
from .authenticators import authenticator class DBUser(object): def __init__(self, db, username, name, email, flags=""): self.Username = username self.Name = name self.EMail = email self.Flags = flags self.DB = db self.AuthInfo = {} # type -> [secret,...] ...
from Graph import * from itertools import * from time import * ## Hamilton path algorithms def Brutal(G, latlong = True): """return the hamilton path and it's cost by comparing EVERY possibilities""" n = len(G.nodes) MinPath = G.nodes MinCost = 0 for k in range (n-1): MinCost += G.distNod...
#!/usr/bin/env python import os import sys import json from argparse import ArgumentParser from mglib import merge_biom, AUTH_LIST, VERSION, safe_print prehelp = """ NAME mg-tab-merge VERSION %s SYNOPSIS mg-biom-merge [ --help --retain_dup_ids ] biom1 biom2 [ biom3 biom4 ... ] DESCRIPTION Tool to m...
import urllib import http.cookiejar import ssl import xml.etree.ElementTree as ET import json import argparse from paepy.ChannelDefinition import CustomSensorResult parser = argparse.ArgumentParser() parser.add_argument("prtg", help="PRTG String") args = parser.parse_args() context = ssl.create_default_context() conte...
# Robot Frameworkからインスタンス変数・クラス変数を扱うためには、ファイル名と同じにする必要がある class variable_file_class: class_val = 'python' def __init__(self): self.instance_val = 'self val' instance_from_class = variable_file_class() class diff_variable_file: diff_class_val = 'diff class' def __init__(self): self....
class Config(object): DEBUG = False TESTING = False SECRET_KEY = "B\xb2?.\xdf\x9f\xa7m\xf8\x8a%,\xf7\xc4\xfa\x91" MONGO_URI="mongodb://localhost:27017/test" IMAGE_UPLOADS = "/home/username/projects/my_app/app/static/images/uploads" SESSION_COOKIE_SECURE = False class ProductionConfig(Config): ...
import paho.mqtt.client as mqtt import json import time broker_url = "" broker_port = 1883 client = mqtt.Client() client.connect(broker_url, broker_port) image = [[1, 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 2, 3]] dictionary = {0: 10.3, 100: 40.5, 200: 51.2, 300: 91.2, 359: 2.0} wheel_payload = json.dumps(image...
import os.path import shutil def publish_api(output_dir): if os.path.exists(output_dir): shutil.rmtree(output_dir) print("succeeded")
import os from datetime import datetime, timedelta import boto3 from app import db, bucket from app.models import Event def delete_user(u): highlights=u.highlights.all() topics = u.topics.all() articles = u.articles.all() tags = u.tags.all() senders = u.approved_senders.all() comms = u.comms ...
import matplotlib.pyplot as plt from fhir_parser import FHIR fhir = FHIR() patients = fhir.get_all_patients() marital_status = {} for patient in patients: if str(patient.marital_status) in marital_status: marital_status[str(patient.marital_status)] += 1 else: marital_status[str(patient.marital...
import pytest import respx @pytest.fixture() async def httpx_mock(): async with respx.mock(base_url='http://example.com') as _http_mock: yield _http_mock
''' PROG II - Segunda Avaliação - Integrantes: ADALINE NOGUEIRA FERNANDES FIRMO THIAGO VINICIOS LIMA DE ARAUJO SOUSA MATHEUS DA COSTA DA SILVA Questão 02 ''' from typing import List class Ticket: def __init__(self, val: str): self.number = int(val) class OccurrencesCounter: ...
import uuid from mixer.backend.django import mixer __all__ = [ mixer, ] def _random_user_name() -> str: return str(uuid.uuid4()) def _random_email() -> str: uuid_as_str = str(uuid.uuid4()).replace('-', '_') return f'{uuid_as_str}@mail.com' mixer.register('users.User', username=_random_user_name,...
try: from setuptools import setup except ImportError: from distutils.core import setup import sys setup( name='tabpy-server', version='0.2', description='Web server Tableau uses to run Python scripts.', url='https://github.com/tableau/TabPy', author='Tableau', author_email='github@tablea...
import warnings import numpy as np import torch import torch.nn.functional as F import torchtuples as tt def pad_col(input, val=0, where='end'): """Addes a column of `val` at the start of end of `input`.""" if len(input.shape) != 2: raise ValueError(f"Only works for `phi` tensor that is 2-D.") pad ...
"""Script to train pixelCNN on the CIFAR10 dataset.""" import random as rn import time import matplotlib import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from tensorflow import keras class MaskedConv2D(keras.layers.Layer): """Convolutional layers with masks. Convolutional layers wi...
import sys from app import create_app, create_manager sys.path.insert(0, "/root/flask-hellogit") # 选择配置模式 app = create_app('development') manager = create_manager(app) if __name__ == "__main__": manager.run()
import argparse from functools import partial from os.path import join import torch import torch.optim as optim from torch.utils.data import DataLoader from torch.optim.lr_scheduler import ReduceLROnPlateau from torch_optimizer import RAdam from utils import collate_fn, build_vocab from data import Im2LatexDataset fr...
import unittest from rdflib import RDF from rdflib.graph import ConjunctiveGraph testgraph = """\ @prefix : <http://example.org/> . @prefix rdf: <%s> . :foo rdf:value 1 . :bar rdf:value -2 .""" % RDF.uri testquery = """\ SELECT ?node WHERE { ?node rdf:value ?val . FILTER (?val < -1) }""" class TestIssue...
from fractions import Fraction from variations.scaler import Scaler class TestScaler: def test_scaler_str(self): s = Scaler(300, 600) assert str(s) == "300x600" def test_scaler_repr(self): s = Scaler(300, 600) assert repr(s) == "Scaler(300, 600)" def test_scaler_ratio(se...
from unittest import TestCase from src.util.load_data import load_data from src.year2020.day02 import part_1, part_2, PasswordEntry, prepare_data from test.decorators import sample data = load_data(2020, 2) @sample class Test2020Day02Samples(TestCase): prepared_data: list[PasswordEntry] @classmethod ...
# tuplas são variaveis compostas; tuplas são imutaveis lanche = ('Hamburguer', 'Suco', 'Pizza', 'Pudim') print(lanche) print(lanche[0]) print(lanche[1:3]) print(lanche[2:]) print(lanche[:2]) print(lanche[-3:]) print(sorted(lanche)) for c in lanche: print(f'Vou comer um {c}') print('OUTRA MANEIRA:') for cont in rang...
# Copyright (c) OpenMMLab. All rights reserved. from typing import List, Optional, Union import mmcv import torch from mmcv.utils import Registry from torch.utils.data import DataLoader, Dataset from mmdeploy.codebase.base import CODEBASE, BaseTask, MMCodebase from mmdeploy.utils import Codebase, get_task_type def ...
import cv2 import numpy as np from PIL import Image, ImageDraw def transform_roi_to_quad(simg, dimg, src, dst): ''' Transforms a source rectangle image into a destination quad. Parameters ---------- simg : ndarray Source image as generated by `np.asarray(Image.open(...))` dimg : ndarra...
import hypothesis import hypothesis.strategies as st import cb58ref @hypothesis.given(st.binary()) def test_decode_inverts_encode(s): assert cb58ref.cb58decode(cb58ref.cb58encode(s)) == s
'''[CT5148] Assignment 3 Student Name: Narae Kim Student ID: 19240062 ''' import sys import json import numpy as np import codecs class SolutionFor1f0c79e5: def __init__(self, filename): self.filename = filename def split_json_into_train_test(self): with open(self.filename) as file: ...
#!/usr/bin/env python3 """ Given the names and grades for each student in a class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. Ref: https://www.programiz.com/python-programming/list-comprehension """ if __name__ == '__main__': records = [] f...
# coding: utf-8 """ VAAS API No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: 0.0.1 Generated by: https://openapi-generator.tech """ try: from inspect import getfullargspec except Import...
from pathlib import Path import pandas as pd from XGEN_flux_file_parsing import get_dataframes_from_XGEN_files, default_flux_data_folder from input_dialogs import get_files_from_user thisdir = Path(__file__).parent.resolve() def add_cell_info(data_summ: pd.DataFrame): cell_info = pd.read_csv(thisdir / 'cell_info...
"""hosts and interfaces Revision ID: 6f1a37baa574 Revises: cd588620e7d0 Create Date: 2018-09-17 15:38:56.401301 """ from alembic import op import sqlalchemy as sa from sqlalchemy import table, column, String import pycroft # revision identifiers, used by Alembic. revision = '6f1a37baa574' down_revision = 'cd588620...
# =============================================================================== # # # # This file has been generated automatically!! Do not change this manually! # # ...
import random import datetime from airflow import models from airflow.operators import bash_operator from airflow.operators import python_operator from airflow.operators import dummy_operator yesterday = datetime.datetime.combine( datetime.datetime.today() - datetime.timedelta(1), datetime.datetime.min.time()...
## exercise 0.4.5 import numpy as np # Setup two ararys x = np.arange(1,6) y = np.arange(2,12,2) # Have a look at them by typing 'x' and 'y' in the console # There's a difference between matrix multiplication and elementwise # multiplication, and specifically in Python its also important if you # are using the mult...
import sys from PyQt5.QtWidgets import QComboBox,QStatusBar,QHBoxLayout,QWidget,QApplication,QMainWindow from PyQt5.QtCore import * class QStatusBarDemo(QMainWindow): def __init__(self): super(QStatusBarDemo, self).__init__() #设置窗口大小 self.resize(400, 150) #设置窗口标题 self.setWi...
# -*- coding: utf-8 -*- import json, re from SPARQLWrapper import SPARQLWrapper, JSON ### START SPARQL header SPARQL_HOST = '''http://localhost:8890/sparql''' SPARQL_PREFIXES = ''' PREFIX obo: <http://purl.obolibrary.org/obo/> PREFIX owl: <http://www.w3.org/2002/07/owl#> PREFIX efo: <http://www.ebi.ac.uk/efo/> ''' # ...
n = input() a = [int(x) for x in raw_input().split()] s = sum(a) d = {} for i in a: if i in d: d[i] += 1 else: d[i] = 1 if s%3 == 0 and 0 in d and d[0] != n: a.sort(reverse=True) res = "" for i in a: res += str(i) print res else: rem = s%3 if rem == 1: if 1 in d: d[1] -= 1 rem = 0 elif 4 in d: ...
from nbconvert.preprocessors import Preprocessor from nbformat import NotebookNode class SkipIgnored(Preprocessor): def preprocess(self, nb, resources): def included(cell): cell.metadata.ipub = cell.metadata.get("ipub", NotebookNode()) return not cell.metadata.ipub.get("ignore", ...
from __future__ import division import numpy as np import pandas as pd from sklearn.dummy import DummyClassifier from sklearn.model_selection import StratifiedShuffleSplit, LeavePGroupsOut from sklearn.utils import resample, check_X_y from sklearn.utils.validation import check_is_fitted from prep import SITES from me...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('groups', '0003_add_foreign_keys'), ] operations = [ migrations.AlterModelOptions( name='group', opti...
from .matchresult import MatchResult from .predthread import PredictionThread __all__ = [MatchResult, PredictionThread]
from hail.expr.expressions import * from hail.expr.expressions.expression_typecheck import * from hail.expr.types import * from hail.typecheck import * from hail.expr.functions import _func @typecheck(ac=expr_int32, an=expr_int32, ci=expr_float64) def filtering_allele_frequency(ac, an, ci) -> Float64Expression: "...
#!/usr/bin/env python # -*- coding:UTF-8 -*- import os.path as osp from easydict import EasyDict as edict import math __C = edict() # Consumers can get config by: import config as cfg cfg = __C # Selected object __C.TRACK_OBJ = 'Car' # Pedestrian/Cyclist if __C.TRACK_OBJ == 'Car' or __C.TRACK_OBJ == 'Van': __C....
import nose.tools as nt import logging from topik.fileio.in_elastic import read_elastic from topik.fileio.project import TopikProject from topik.fileio.tests import test_data_path from ._solutions import solution_elastic from elasticsearch.exceptions import ConnectionError from nose.plugins.skip import SkipTest INDEX...
import re from django.contrib.auth import login from apps.shop.forms import PaymentChoiceForm from django.db.models import query from django.shortcuts import get_object_or_404, render, redirect from django.http.response import HttpResponse, JsonResponse from django.http.request import HttpRequest from django.views.gen...
"""Pre-run modifier that excludes tests that run PASS last time. """ import os from robot.api import ExecutionResult, ResultVisitor, SuiteVisitor from robot.running.model import Variable class rerunfailed(SuiteVisitor): def __init__(self, original_output_xml): if not os.path.isfile(original_output_xml)...
from typing import Tuple from UE4Parse import DefaultFileProvider from UE4Parse.BinaryReader import BinaryStream from UE4Parse.Versions import VersionContainer class StreamedFileProvider(DefaultFileProvider): def __init__(self, versions: VersionContainer = VersionContainer.default(), isCaseInse...
#!/usr/bin/env python2 import time import rospy from sensor_msgs.msg import JointState from std_msgs.msg import Header from visualization_msgs.msg import Marker import tf def talker(): rospy.init_node("following_marker", anonymous=True) pub_marker = rospy.Publisher("visualization_marker", Marker, queue_size...
#!/usr/bin/env python3 from json import dumps as json_dumps from logging.config import dictConfig as logging_dict_config from modules.api_client import ApiClient from modules.cache import PickledDictCache from modules.config import config def create_client(): return ApiClient( user=config.github.user, ...
from django.http import JsonResponse from django.shortcuts import render from django.contrib import sessions from django.views.generic import View from django.utils import timezone from app.RoleMethod.PublicMethod import PublicMethod from django.views import View from app.serialize.serializer_user import * from django....
import torch import torch.nn.functional as F from .strategy_utils import top_k_top_p_filtering import utils from decoding_strategy import BaseDecoding class SinglePassDecoding(BaseDecoding): def generate(self, model, batch): net_input = utils.move_to_cuda(batch['net_input']) encoder_input_ids = ...
# -*- coding: utf-8 -*- from base64 import b64encode, b64decode from datetime import datetime, timedelta import os import stat import yaml __virtualname__ = 'metalk8s_kubeconfig' def __virtual__(): return __virtualname__ def _validateKubeConfig(filename, expected_ca_data, ...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import unittest import torch from models.matcher import HungarianMatcher from models.position_encoding import PositionEmbeddingSine, PositionEmbeddingLearned from models.backbone import Backbone from util import box_ops from util.misc import neste...
from optparse import make_option from django.core.management.base import BaseCommand from django.db.models import Q import amo from addons.models import Addon from amo.utils import chunked from devhub.tasks import convert_purified, flag_binary, get_preview_sizes from market.tasks import check_paypal, check_paypal_mul...
import psutil _pids_data = {'lock_pid': None, 'last_pids': set()} def is_locked(lock_name='i3lock') -> bool: pids = set(psutil.pids()) if _pids_data['lock_pid']: if _pids_data['lock_pid'] in pids: return True else: _pids_data['lock_pid'] = None _pids_data[...
# Generated by Django 2.0.4 on 2018-04-18 01:34 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('blog', '0007_auto_20180418_0102'), ] operations = [ migrations.RenameField( model_name='index',...
""" acl backend """ import dnmetis_backend as dnmetis_backend import backend.backend as backend import numpy as np import os import pdb class AclBackend(backend.Backend): def __init__(self): super(AclBackend, self).__init__() self.ACL=5 self.outputs = "" self.inputs = "" s...
from .data_structures import \ SDFDataset from .io import \ IOHandlerSDF from .fields import \ SDFFieldInfo
from sage.all import Zmod, Matrix, factor def build_matrix(P, M, c=1000): factors_M = factor(M) rows = [] # add logarithms for p in P: row = [] for q, e in factors_M: row.extend(Zmod(q ** e)(p).generalised_log()) # generalised_log() uses unit_gens() generators row...
import os import pytest from flask import url_for from . import BrewlogTests @pytest.mark.usefixtures('client_class') class TestMainPageAnonUser(BrewlogTests): TEMPLATES_DIR = os.path.join( os.path.dirname(os.path.dirname(__file__)), 'src/brewlog/templates', ) @pytest.fixture(autouse=T...
"""Support for the PostgreSQL database via the psycopg2 driver. Driver ------ The psycopg2 driver is supported, available at http://pypi.python.org/pypi/psycopg2/ . The dialect has several behaviors which are specifically tailored towards compatibility with this module. Note that psycopg1 is **not** supported. Co...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
"""Views for archivists to edit and manage mods on the archive""" from tempfile import NamedTemporaryFile from flask import Blueprint, render_template, request, url_for, redirect, flash, abort from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileRequired from sqlalchemy.orm.exc import NoResultFou...
from typing import List, Dict, Tuple, Set, NamedTuple import os import csv import warnings import time import shutil import requests from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditi...
#!/usr/bin/env python3 # Run a command under gvisor, setting environment variables and sharing certain # directories in read only mode. Specialized for running python, and (for testing) # bash. Does not change directory structure, for unprivileged operation. # Contains plenty of hard-coded paths that assume we are ...
# # Copyright (c) 2019 UAVCAN Development Team # This software is distributed under the terms of the MIT License. # Author: Pavel Kirienko <pavel.kirienko@zubax.com> # import sys import typing import dataclasses @dataclasses.dataclass(frozen=True) class TransportConfig: cli_args: typing.Sequence[str] can...
from math import cos, sin from typing import List import bot.injector as injector from bot.hooks import hookable from sc2 import BotAI from sc2.pixel_map import PixelMap from sc2.position import Point2 from sc2.unit import Unit from sc2.units import Units class UnitObservation: def __init__(self, unit: Unit, tim...
import os import setuptools import versioneer LOCAL_DIR = os.path.dirname(os.path.abspath(__file__)) def read_requirements(path="requirements.txt"): """Read requirements file relative to setup.py""" full_path = os.path.join(LOCAL_DIR, path) if not os.path.exists(full_path): return [] def y...
import torch from xallennlp.modules.span_extractors import PoolingSpanExtractor def test_pooling_span_extractor() -> None: inputs = torch.rand((2, 4, 5)) spans = torch.LongTensor([[[0, 2], [1, 1]], [[1, 2], [2, 3]]]) extractor = PoolingSpanExtractor(input_dim=5) output = extractor(inputs, spans) ...
# xpyBuild - eXtensible Python-based Build System # # This module holds definitions that are used throughout the build system, and # typically all names from this module will be imported. # # Copyright (c) 2019 Software AG, Darmstadt, Germany and/or its licensors # # Licensed under the Apache License, Version 2.0 (...
#!/usr/bin/python3 from scapy.all import * import netifaces as ni import uuid import datetime import time # Our eth0 IP ipaddr = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr'] # Our Mac Addr macaddr = ':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1]) # destination ip we arp spoofed...
# coding=utf-8 """ Problem 89 18 February 2005 For a number written in Roman numerals to be considered valid there are basic rules which must be followed. Even though the rules allow some numbers to be expressed in more than one way there is always a "best" way of writing a particular number. For example, ...
import PyCmdMessenger import threading import time SERIAL_PORT = "/dev/cu.usbmodem1421" BAUD_RATE = 9600 ARDUINO_INTERFACE = PyCmdMessenger.ArduinoBoard(SERIAL_PORT, baud_rate = BAUD_RATE) MESSENGER_COMMANDS= [["get_rocket_location",""], ["rocket_location_response","s"], ["sen...
from PDA import PDA import math EMPTY_STRING = '' def int_to_bin(x): return x.__format__('b') def s_2(x): return int_to_bin(x).count('1') def base_b(n,b): s = EMPTY_STRING while n > 0: s += str(n % b) n //= b return s[::-1] def s_b(n,b): count = 0 while n > 0: ...
# startup.py # points gunicorn at our main.py within the src/app directory from src.app.main import app
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Test h2o initialization / startup options. Currently, our R/Python test suite is executed against an established h2o cluster (run.py sets up the cluster). However, we ignore the mode of operation where the h2o cluster is created by the client. Consequently, we may no...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # [The "New BSD" license] # Copyright (c) 2014 The Board of Trustees of The University of Alabama # All rights reserved. # # See LICENSE for details. if __name__ == '__main__': import nose nose.main() from nose.tools import * import unittest import src class T...
# ================================================================= # # Authors: Ricardo Garcia Silva <ricardo.garcia.silva@gmail.com> # # Copyright (c) 2017 Ricardo Garcia Silva # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the...
# -*- coding: utf-8 -*- from openprocurement.api.utils import json_view from openprocurement.tender.core.utils import optendersresource from openprocurement.tender.core.validation import ( validate_patch_contract_data, validate_update_contract_value, validate_update_contract_only_for_active_lots, valida...
from model.group import Group import random def test_edit_group_name(app, db): if app.group.count() == 0: app.group.create(Group(name="test")) old_groups = db.get_group_list() group = random.choice(old_groups) new_group = Group(name="new name") app.group.edit_group_by_id(group.id, new_grou...
from egat.testset import SequentialTestSet from egat.testset import UnorderedTestSet from selenium import webdriver # In the SequentialTestSet, the setup and teardown methods will be called before any # tests are executed and after all tests are finished, respectively. If you run # these tests you will see that the b...
# Nuthouse01 - 08/24/2020 - v5.00 # This code is free to use and re-distribute, but I cannot be held responsible for damages that it may or may not cause. ##################### # first, system imports from typing import List, Tuple # second, wrap custom imports with a try-except to catch it if files are missing try: ...
from finbot.providers.errors import RetiredProviderError from typing import Any, Type, TypeVar, TypedDict, Optional class Account(TypedDict): id: str name: str iso_currency: str type: str class BalanceEntry(TypedDict): account: Account balance: float class Balances(TypedDict): accounts...
"""Module defining classes and functions related to website accounts. Uses Google Python Style Guide: https://google.github.io/styleguide/pyguide.html """ class Account: """Represents a website account. Attributes: password: A string containing the password of the user's account. username: An...
from pathlib import Path from setuptools import setup, find_packages setup( name="metovhooks", version="0.1.8", description="My personal git hooks.", url="https://github.com/metov/metovhooks", long_description=Path("README.md").read_text(), long_description_content_type="text/markdown", au...
class Solution: def subsets(self, nums: List[int]) -> List[List[int]]: ret = [] n = len(nums) for i in range(2 ** n): tmp = [] idx = 0 while i: if i & 1: tmp.append(nums[idx]) i >>= 1 idx ...
from arm.logicnode.arm_nodes import * class StringNode(ArmLogicTreeNode): """Stores a string as a variable.""" bl_idname = 'LNStringNode' bl_label = 'String' arm_version = 1 def init(self, context): super(StringNode, self).init(context) self.add_input('NodeSocketString', 'String In...
import psutil nome = input("Entre com o nome do processo a ser buscado: ") ip = psutil.pids() lista_pid = [] for i in ip: p = psutil.Process(i) if p.name() == nome: lista_pid.append(str(i)) if len(lista_pid) > 0: print(f"O(s) PID(s) de {nome} são:") print(','.join(lista_pid)) else: print(n...
# Written in Python 2 from __future__ import division from PIL import Image im = Image.open( './images/256x256bb.jpg') matrixWidth = 30 matrixHeight = 22 imgWidth = im.width imgHeight = im.height print "imgSize", imgWidth, " x ", imgHeight wBuffer = round(imgWidth/matrixWidth) hBuffer = round(imgHeight/matrixHei...
from twisted.internet import reactor from twisted.web.resource import Resource from twisted.web.server import Site import time class ClockPage(Resource): isLeaf = True def render_GET(self, request): return "The local time is %s" % (time.ctime(),) resource = ClockPage() factory = Site(resource) reactor...
import pickle import math import torch import re from tqdm import tqdm from PIL import Image from pathlib import Path from torch.utils.data import Dataset from torchvision import transforms class DatasetSYNTH(Dataset): def __init__(self, cfg): self.cfg = cfg with open(cfg.data_path, 'rb') as f: ...
import datetime import jcudc24ingesterapi import os.path import unittest from jcudc24ingesterapi.models.dataset import Dataset from jcudc24ingesterapi.models.locations import Location, Region, LocationOffset from jcudc24ingesterapi.schemas.data_types import FileDataType, Double, String, DateTime from jcudc24ingestera...
import unittest import sbol2 class TestSequenceAnnotation(unittest.TestCase): def test_add_remove_role(self): sa = sbol2.SequenceAnnotation() self.assertEqual([], sa.roles) sa.addRole(sbol2.SO_PROMOTER) self.assertEqual([sbol2.SO_PROMOTER], sa.roles) sa.addRole(sbol2.SO_MI...