content
stringlengths
5
1.05M
# python peripherals import os import numpy import random import queue from multiprocessing import Process, Queue, cpu_count # torch import torch from torch.utils.data import Dataset # deep_signature from deep_signature.data_generation import curve_generation from deep_signature.data_generation import dataset_generat...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ # standard library # django from django.contrib import admin from django.core.urlresolvers import NoReverseMatch from django.core.urlre...
import pandas as pd from modules.locale_generator.data import LocaleOutData from helper.utils.utils import read_sheet_map_file class LocaleProcessor: def __init__(self, language_name, english_column_name): self.language_name = language_name self.english_column_name = english_column_name ...
from unittest import mock from bgmi.downloader.deluge import DelugeRPC from bgmi.website.model import Episode _token = "token:2334" @mock.patch("bgmi.config.DELUGE_RPC_PASSWORD", _token) @mock.patch("bgmi.downloader.deluge.DelugeRPC._call") def test_init(call): DelugeRPC( download_obj=Episode(name="n", ...
''' a = input("First number") b = input("Second number") a = int(a) b = int(b) print(a+b) print(a-b) print(a*b) print(a/b) result = a/b print(type(result)) print(result) print(a**2) ''' # Логические операции a = True b = False # Отрицание print(not a) # Логическое И print(a and b) # Логическое ИЛИ print(a or b) a ...
from mypackage import shazam shazam()
# query_parser_test.py # Author: Thomas MINIER - MIT License 2017-2018 import pytest from query_engine.sage_engine import SageEngine from query_engine.optimizer.query_parser import parse_query from database.hdt_file_connector import HDTFileConnector from tests.utils import DummyDataset import math hdtDoc = HDTFileCon...
import sys import time from http.client import HTTPSConnection from typing import List def main(argv: List[str]): time.sleep(3) for i in range(3): for j in argv: connection = HTTPSConnection(j) connection.request('GET', '/') connection.getresponse().read() ...
# -*- encoding: utf-8 -*- # Copyright (c) 2015 b<>com # # 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 o...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- import sys from common.Utilities import execute_command, get_file_extension_list, error_exit from ast import ASTGenerator, AST import Mapper import Finder import Logger import Extractor import Emitter def merge_var_info(var_expr_map, var_value_map): Logger.trace(_...
# CONTADOR DE CÉDULAS value = int(input('Digite o valor a ser sacado: ')) total = value # Pegando o valor a ser sacado ced = 50 # Começando na cedula de 50 totced = 0 # Total de cedula por valor while True: if total >= ced: # Enquanto puder retirar o valor da cedula do valor total total -= ced # R...
""" Generate static HTML files for eduid-IdP in all supported languages. """ import os import sys import six import pkg_resources from six.moves import configparser from jinja2 import Environment, PackageLoader from babel.support import Translations __version__ = '0.1' __copyright__ = 'SUNET' __organization__ = 'SUN...
import pywikibot from openpyxl import load_workbook site = pywikibot.Site() ''' page = pywikibot.Page(site, u"Project:Sandbox") text = page.text #page.text = u"DarijaBot kheddam daba" page.save(page.text+u"\n\nawwal edit dial DarijaBot") ''' sandbox = pywikibot.Page(site, 'User:' + site.user() + '/Project:Sandbox'...
import numpy as np from .agent import Agent class RandomAgent(Agent): def __init__(self, actions): super(RandomAgent, self).__init__(actions) def act(self, obs): return np.random.randint(0, self.num_actions)
from rA9.neurons.LIF import LIF def LIF_recall(tau, Vth, dt, x, v_current): model = LIF(tau_m=tau, Vth=Vth, dt=dt) spike_list, v_current = model.forward(x, v_current=v_current) return spike_list, v_current def LIF_backward(tau, Vth, x, spike_list, e_grad, time): model = LIF(tau_m=tau, Vth=Vth) ...
from meido.libs.yuntongxun.sms import CCP from celery_tasks.main import app @app.task(name='send_sms_code') def send_sms_code(mobile, sms_code): ccp = CCP() ccp.send_template_sms(mobile, [sms_code, '5'], 1) @app.task() def test_print(): print(2222)
#!/usr/bin/env python3 def naive_search(l,x): for i in range(len(l)): if l[i]==x: return i n = int(input()) l = list(range(n)) cnt = 0 for x in range(n): i = naive_search(l,x) cnt += 1 print("#query=%d"%cnt)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains artellapipe-tools-welcome view implementation """ from __future__ import print_function, division, absolute_import import os import random from functools import partial from Qt.QtCore import Qt, QSize, QTimer, QByteArray, QBuffer from Qt.QtWidge...
from flask_cors import cross_origin from app.blueprints.base_blueprint import ( Blueprint, BaseBlueprint, request, Security, Auth, ) from app.controllers.user_employment_controller import UserEmploymentController url_prefix = "{}/user_employment_history".format(BaseBlueprint.base_url_prefix) user_...
from django.test import TestCase from django.contrib.auth.models import User from .models import Thread, Message # Create your tests here. class ThreadTestCase(TestCase): def setUp(self): self.user1 = User.objects.create_user("user1", None, "test1234") self.user2 = User.objects.create_user("user2", None, "te...
#!/usr/bin/env python import argparse import sys import Tools from Bio import SeqIO from Bio import SeqRecord from Bio import Seq ap = argparse.ArgumentParser(description="Take an inversion bed file, and print the sequences in inverted format with some flanking part of the genome.") ap.add_argument("bed", help="Input...
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.views.generic import ListView from django.http import JsonResponse from api.models import Country, City class CountryView(LoginRequiredMixin, UserPassesTestMixin, ListView): model = Country response_class = JsonRespons...
from .triplet_generators import generator_from_neighbour_matrix, \ TripletGenerator, UnsupervisedTripletGenerator, SupervisedTripletGenerator from .generators import KerasSequence
import setuptools with open("./README.md", "r") as f: description = f.read() setuptools.setup( name="blive", version="0.0.5", author="cam", author_email="yulinfeng000@gmail.com", long_description=description, long_description_content_type="text/markdown", url="https://github.com/yulinf...
from .md5_database import MD5DB from .paper_database import paperDB
import socket def resolv(hostname): try: return socket.gethostbyname(hostname) except socket.gaierror as e: raise Exception('Cloud not resolv "%s": %s' % (hostname, e)) class FilterModule(object): filter_map = { 'resolv': resolv, } def filters(self): return {'res...
import unittest import mutable_test class TestRemoveShared(unittest.TestCase): '''Tests for function duplicates.remove_shared.''' def test_general_case(self): ''' Test remove_shared where there are items that appear in both lists, and items that appear in only one or the other list...
import numpy as np from .preprocessing import * from .sequence_alignment import * class SemAlign(object): def __init__(self, embeddings_path, kernel_size=1, delimiter=',', verbose=True): self.lookup = load_embeddings(embeddings_path, delimiter) self.kernel_size = kernel_size self.verbose =...
from enum import Enum, auto class Color(Enum): BLACK = 0 WHITE = 1 RED = 2 BLUE = 3 # class TestEnum(Enum): # ONE = 0 # ONE = 1 class TestNewEnum(Enum): ZERO = auto() ONE = auto() TWO = auto() if __name__ == "__main__": print(Color.BLACK) print(Color.BLACK.name) pri...
# Update the paths according to your environemnt OPT = "/data/guide/Trident/llvm-2.9-build/bin/opt" LLVMGCC = "/data/Trident/llvm-gcc4.2-2.9-x86_64-linux/bin/llvm-gcc" LLVMLINK = "/data/guide/Trident/llvm-2.9-build/bin/llvm-link" LLVMPASS_FOLDER = "/data/guide/Trident/llvm-2.9-build/lib/" LLI = "/data/guide/Triden...
def pour(jug1, jug2): capacityA = 5 capacityB = 7 Measure = 4 print("%d \t %d" % (jug1, jug2)) if jug2 is Measure: # jug2 has "measure" amount of water stop return elif jug2 is capacityB: pour(0, jug1) elif jug1 != 0 and jug2 is 0: pour(0, jug1) ...
def isExistingClassification(t): pass def getSrcNodeName(dst): """ Get the name of the node connected to the argument dst plug. """ pass def getCollectionsRecursive(parent): pass def disconnect(src, dst): pass def findVolumeShader(shadingEngine, search='False'): """ Returns ...
import scanpy as sc import numpy as np import pandas as pd from scdcdm.util import cell_composition_data as ccd #%% adata_ref = sc.datasets.pbmc3k_processed() # this is an earlier version of the dataset from the pbmc3k tutorial print(adata_ref.X.shape) #%% cell_counts = adata_ref.obs["louvain"].value_counts() print...
""" :type: tuple :Size: 1.295MB :Package Requirements: * **sklearn** Vec-colnames and neighber matrix used in Substitute DECS. See :py:class:`.DCESSubstitute` for detail. """ import os import pickle from OpenAttack.utils import make_zip_downloader NAME = "AttackAssist.DCES" URL = "https://cdn.data.thunlp.org/TAAD...
#coding:utf-8 """ @file: db_config @author: lyn @contact: tonylu716@gmail.com @python: 3.3 @editor: PyCharm @create: 2016-11-20 12:18 @description: sqlalchemy 配置数据库 """ from JsonConfig import DB_Config for path in ['.','..']: try: db = DB_Config( json_file_path= ...
import os import datetime import dropbox from app import db from app.models import SystemLog from app.enums import LogStatus, LogType from flask import current_app def download(dbx, folder, subfolder, name): """Download a file. Return the bytes of the file, or None if it doesn't exist. """ path = '/%s/...
NumOfRows = int(input("Enter number of rows: ")) coeffcient = 1 for i in range(1, NumOfRows+1): for space in range(1, NumOfRows-i+1): print(" ",end="") for j in range(0, i): if j==0 or i==0: coeffcient = 1 else: coeffcient = coeffcient * (i - j)//j print(...
import abc class ORMDB(abc.ABC): @abc.abstractmethod def parse_sql(self, sql_str): pass
# -*- coding: utf-8 -*- """This python program converts various parts of glowscript from the most convenient format for modification into the most convenient format for deployment. * Take shaders from shaders/*.shader and combine them into lib/glow/shaders.gen.js * Extract glowscript libraries list from ``untrusted/r...
# Copyright (c) 2021 Graphcore Ltd. All rights reserved. import argparse import io import numpy as np import os from PIL import Image import requests import time import yacs import torch from poptorch import inferenceModel, Options from models.detector import Detector from models.yolov4_p5 import Yolov4P5 from utils....
from datetime import datetime import bs4 from bs4 import BeautifulSoup from django.contrib.auth.models import User from bookmarks.models import Bookmark, parse_tag_string from bookmarks.services.tags import get_or_create_tags def import_netscape_html(html: str, user: User): soup = BeautifulSoup(html, 'html.pars...
###exercicio 49 n = int(input('digite um numero: ')) for c in range (1, 11): print (' {} * {} = {}'.format(n, c, n*c)) print ('Fim!!!')
import cv2 import numpy as np from PyQt5.QtCore import Qt, QObject, pyqtSignal from PyQt5.QtGui import QImage, QPixmap, QDropEvent from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizePolicy class QMapCommunicate(QObject): drop_event = pyqtSignal(QDropEvent) class PsQMapWidget(QWidget): def __init...
# coding: utf-8 import torch import torch.nn.functional as F from helpers.utils import int_type, add_noise_to_imgs class NumDiffAutoGradFn(torch.autograd.Function): """ A custom backward pass for our [s, x, y] vector when using hard attention grid = torch.Size([16, 32, 32, 2]) grad_output_shape = ...
import os import shutil # Create a new dummy store to run tests on from tests._stores_for_tests import _TestFixStore # recs = [ # {'fix_id': 'Fix1', 'operands': {'arg1': '1'}, 'ncml': '<NcML1>'}, # {'fix_id': 'Fix2', 'operands': {'arg2': '2'}, 'ncml': '<NcML2>'} # ] recs = [ { "fix_id": "Fix1", ...
import os import lldb class ConcurrentLazyFormatter: def __init__(self, valobj, dict): self.valobj = lldb.value(valobj) def get_child_index(self, name): return 0 # There is only ever one child def num_children(self): if self.has_value: return 1 return 0 def get_child_at_index(self, index): if inde...
import os import re from .models import Photo def generate_photo(file_path): photo_path, width, height = image_utils.fit_and_save(file_path) thumb_path = image_utils.generate_thumbnail(photo_path) photo_path, thumb_path = (relp(rp(p), PARENT_DIR) for p in (photo_path, thumb_path)) photo = Photo(image_...
# project/users/forms.py from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Length, EqualTo, Email class RegisterForm(Form): email = StringField('Email', validators=[DataRequired(), Email(), Length(min=6, max=40)]) password = PasswordField(...
from .libfm import ( RegressionCallback, ClassificationCallback, OrderedProbitCallback, LibFMLikeCallbackBase, )
import tensorflow as tf import numpy as np from tensorflow import keras # Use simple nearest neighbour upsampling, 9x9, 1x1 and 5x5 convolutional layers. MSE: 0.0028712489 # Described in https://towardsdatascience.com/an-evolution-in-single-image-super-resolution-using-deep-learning-66f0adfb2d6b # Article: https://ar...
import logging import os import re from robobrowser import RoboBrowser logger = logging.getLogger(__name__) id_re = re.compile("\(([^)]+)\)") def scrape_snotel_sites(url=None): if not url: url = "http://www.wcc.nrcs.usda.gov/nwcc/yearcount?network=sntl&counttype=statelist&state=" browser = RoboBrowse...
import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import numpy as np import scipy.io from torch.utils.data import Dataset import pickle import os import sys # Data Processing def load_file(path_to_file): return np.genfromtxt(path_to_...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Donny You(donnyyou@163.com) # Loss Manager for Object Detection. from __future__ import absolute_import from __future__ import division from __future__ import print_function from loss.modules.det_modules import SSDFocalLoss, SSDMultiBoxLoss from loss.modules.det...
a = [] # append element at the end. a.append(2) a.append(3) print(a) # insert at a specific location. a.insert(0, 5) a.insert(10, 5) print(a) # when specified a position not in list, it inserts at the end. a.insert(100, 6) print(a) # Deleting elements from a list. a.remove(5) # removes the first occurence of value pa...
from .Ticket import Ticket, StateTicket ################################################################################ ################################################################################ ################################################################################ ###############################...
import numpy as np from sklearn.cluster import MeanShift, estimate_bandwidth import matplotlib.pyplot as plt from PIL import Image import cv2 from copy import deepcopy # image_path = '/home/kshitij/PycharmProjects/Computer_Vision/Assignment_3/Question_2/iceCream1.jpg' # image_path = '/home/kshitij/PycharmProjects/Comp...
import random import networkx as nx import matplotlib.pyplot as plt class graph: __dg = None def __init__(self): #self.__dg = nx.DiGraph() self.__dg = nx.Graph() def add_nodes(self, nodes): for i in range(0, len(nodes)): self.__dg.add_node(nodes[i]) def add_edges...
# coding: utf-8 """ TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in compliance with the...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import datetime from alphalogic_api.protocol import rpc_pb2 from alphalogic_api.attributes import Visible, Access from alphalogic_api.multistub import MultiStub from alphalogic_api import utils from alphalogic_api.logger import log from alphalogic_api.u...
from unittest.mock import ANY, patch from arcsecond import ArcsecondAPI from click.testing import CliRunner from oort.cli.cli import upload from oort.server.errors import InvalidOrgMembershipOortCloudError, UnknownOrganisationOortCloudError from oort.shared.models import Organisation from tests.utils import ( TEL...
from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('../../MNIST_data', one_hot=True) import tensorflow as tf x = tf.placeholder(tf.float32,[None,784])
from aiogram import types from asyncio import sleep from typing import Union import NekoGram async def default_start_function(message: Union[types.Message, types.CallbackQuery]): neko: NekoGram.Neko = message.conf['neko'] if not await neko.storage.check_user_exists(user_id=message.from_user.id): lang ...
import os import pandas as pd import nltk import re import spacy from sklearn.feature_extraction.text import CountVectorizer from data_module.corpus import data_operations as do from data_module.corpus.clean import remove_single_quotes def get_top_n_words(corpus, n=None): """ List the top n words in a vocabul...
import unittest from config import TEST_DB_PATH from repositories.item_repository import ItemRepository from utilities.csv_utilities import clear_csv, read_csv class TestItemRepository(unittest.TestCase): def setUp(self): clear_csv(TEST_DB_PATH) self.item_repo = ItemRepository(TEST_DB_PATH) ...
#!/usr/bin/env python3 import sys import subprocess import requests from datetime import datetime def main(args): if len(args) < 2: print('usage: sync-cloudflare.py [output path]') return output = args[1] now = datetime.utcnow().isoformat() ips = [] resp = requests.get('https://...
import os import sys from urllib2 import urlopen import json import ConfigParser config = ConfigParser.ConfigParser() config.readfp(open(r'config.txt')) apikey = config.get('Sonarr Config', 'apikey') host = config.get('Sonarr Config', 'host') port = config.get('Sonarr Config', 'port') url = 'http://'+host+':'+port+'...
#!/usr/bin/env python from kivy.app import App from kivy.animation import Animation from kivy.uix.floatlayout import FloatLayout from kivy.graphics import Line from kivy.gesture import Gesture, GestureDatabase from kivy.vector import Vector from kivy.properties import NumericProperty,BooleanProperty from museol...
import numpy as np from sympy import simplify, integrate, zeros, S, Matrix, symbols, pi, cos, sin from .funcs_aproximacion import producto_asecas def producto_escalar_trigono(f, g, var=symbols('x'), a=-pi, b=pi, I=None, numeric=False): """Aplica el producto escalar <f,g> = 1/(2pi) ∫_[-pi]^[pi] f.g Args: ...
from ..util.conversion import physical_compatible from ..util import config, conversion class df(object): """Top-level class for DF classes""" def __init__(self,ro=None,vo=None): """ NAME: __init__ PURPOSE: initialize a DF object INPUT: ro= (None)...
#!/usr/bin/python3 # Copyright (c) 2021 by Fred Morris Tacoma WA # # 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 appli...
from enum import Enum class Emoji(Enum): PLAY = "*play*" FACE_HEARTS = "<3" FACE_TONGUE = ":P" FACE_SMILE = ":D" FACE_CRY_LAUGH = "xD" FACE_HALO = "=D" FACE_NERDY = "*nerdy*" FACE_TEAR = "*cry*" FACE_SAD = ":(" FACE_ZZZ = "*sleep*" FACE_ROLLING_EYES = "*rolling-eyes*" F...
"""Dependency injector resource provider unit tests.""" import asyncio import unittest2 as unittest from dependency_injector import containers, providers, resources, errors # Runtime import to get asyncutils module import os _TOP_DIR = os.path.abspath( os.path.sep.join(( os.path.dirname(__file__), ...
# coding: utf-8 # This block of code fetches the data, and defines a function that # splits the data into test/train, and into batches. # Note that this function will only download the data once. Subsequent # calls will load the data from the hard drive def MNIST_Loaders(train_batch_size, test_batch_size=None): i...
import sqlite3 # Configure database connection = sqlite3.connect('map.db') # Cursor for execute DB command c = connection.cursor() # CREATE TABLE # c.execute("""CREATE TABLE map ( # id integer, # lat real, # lng real, # comment text # )""") # INSERT VALU...
from .models import Language from rest_framework import serializers class LanguageSerializer(serializers.ModelSerializer): class Meta: model = Language fields = ('id', 'name', 'paradigm')
""" Playground for downloading GenBank files, wrapping in bowtie2, sCLIP/SOR prep """ from Bio import Entrez import csv import re import requests import subprocess import os from Bio import SeqIO import shutil from urllib.error import HTTPError import time import inv_config as config # TODO Remove .gbk files at the e...
from __future__ import division import os import math import scipy.misc import numpy as np import argparse from glob import glob from pose_evaluation_utils import mat2euler, dump_pose_seq_TUM parser = argparse.ArgumentParser() parser.add_argument("--dataset_dir", type=str, help="path to kitti odometry dataset") parser...
import numpy as np import matplotlib.pyplot as plt with open('timings.txt','r') as inp: inp.readline() times = np.loadtxt(inp, delimiter=',') print(times.shape) selected = list([0,1,3,8,13,18]) # plt.plot((2+np.array(range(19))),times[:,0],'r^-',label="Best first search algorithm") # plt.plot((2+np.array(range(1...
from pessoa import Pessoa class Aluno(Pessoa): def __init__(self, rm, turma_id, rg, nome): super().__init__(rg, nome) self._rm = rm self._turma_id = turma_id self._notas = [] def media(self): if len(self._notas) > 0: return sum(self._notas)/len(self._notas) ...
import numpy as np import torch class FeaturesLinear(torch.nn.Module): def __init__(self, field_dims, output_dim=1): super().__init__() self.fc = torch.nn.Embedding(sum(field_dims), output_dim) self.bias = torch.nn.Parameter(torch.zeros((output_dim,))) self.offsets = np.array((0, ...
# Copyright 2013 - Red Hat, 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 by applicable law or agreed to in writi...
import fileReader import inputHandler import fileHandler import os inputStuff = inputHandler.inputHandler() fileStuff = fileHandler.FileHandler() def getMode(): mode = inputStuff.determineAutoOrManual() if mode == 'man': getFileInfo() loadAudioFile() elif mode =='auto': fileProcesser = fileReader.FileReader()...
from pybullet_utils import bullet_client import math class QuadrupedPoseInterpolator(object): def __init__(self): pass def ComputeLinVel(self,posStart, posEnd, deltaTime): vel = [(posEnd[0]-posStart[0])/deltaTime,(posEnd[1]-posStart[1])/deltaTime,(posEnd[2]-posStart[2])/deltaTime] return vel...
from typing import List from extraction.event_schema import EventSchema from extraction.predict_parser.predict_parser import Metric from extraction.predict_parser.tree_predict_parser import TreePredictParser decoding_format_dict = { 'tree': TreePredictParser, 'treespan': TreePredictParser, } def get_predict...
import os filename = os.path.dirname(__file__) + "\\input" with open(filename) as file: x = [] start = 0 for line in file: text = list(line.rstrip()) if start == 0: x = [0] * len(text) i = 0 for t in text: if t == '1': x[i] += 1 ...
def solve(input): ans = 0 for g in input.split("\n\n"): b = 0 for c in g: if c.isalpha(): b |= 1 << (ord(c) - ord("a")) ans += bin(b).count("1") return ans
# https://www.hackerrank.com/challenges/three-month-preparation-kit-jack-goes-to-rapture/problem #!/bin/python3 import math import os import random import re import sys # # Complete the 'getCost' function below. # # The function accepts WEIGHTED_INTEGER_GRAPH g as parameter. # # # For the weighted graph, <name>: # ...
from typing import List, Callable, Optional, Dict, Set from tqdm import tqdm from src.data.objects.frame import Frame from src.data.objects.stack import Stack from src.data.readers.annotation_reader import AnnotationLoader class LineModifiedClassifier: def __init__(self, user_ids: Set[int], annotation_loader: A...
from scrapy import cmdline name = 'douban_movie_top250' cmd = 'scrapy crawl {}'.format(name) cmdline.execute(cmd.split())
#you += hash(pubkey || index) to both the private scalar and public point #<tacotime> [02:35:38] so to get priv_i and pub_i #<tacotime> [02:36:06] priv_i = (priv + hash) mod N #<tacotime> [02:37:17] pub_i = (pub + scalarbasemult(hash)) import MiniNero import PaperWallet sk, vk, pk, pvk, addr, wl, cks = PaperWallet.key...
class OperationFailed(Exception): pass class ValidationFailed(Exception): pass
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython """ def suma(a: float, b: float) -> float: return a + b def resta(a: float, b: float) -> float: return a - b def multiplicacion(a: float, b: float) -> float: return a * b def division(a: float, b: float) -> float: if b <= 0: ra...
class ArtistCollection(): """ Matplotlib collections can't handle Text. This is a barebones collection for text objects that supports removing and making (in)visible """ def __init__(self, artistlist): """ Pass in a list of matplotlib.text.Text objects (or possibly any ...
from qemuvolume import QEMUVolume from ..tools import log_check_call class VirtualHardDisk(QEMUVolume): extension = 'vhd' qemu_format = 'vpc' ovf_uri = 'http://go.microsoft.com/fwlink/?LinkId=137171' # Azure requires the image size to be a multiple of 1 MiB. # VHDs are dynamic by default, so we add the option ...
import pytest import numpy import os import spacy from spacy.matcher import Matcher from spacy.attrs import ORTH, LOWER, ENT_IOB, ENT_TYPE from spacy.attrs import ORTH, TAG, LOWER, IS_ALPHA, FLAG63 from spacy.symbols import DATE, LOC def test_overlap_issue118(EN): '''Test a bug that arose from having overlapping...
# 3rd party imports import stellar_base.utils from stellar_base.exceptions import * from stellar_base.keypair import Keypair from stellar_base.address import Address STELLAR_MEMO_TEXT_MAX_BYTES = 28 def is_address_valid(address): """ Checks if a given Stellar address is valid. It does not check if it exists ...
# Copyright 2021 Huawei Technologies 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...
"""Converts ECMWF levels into heights""" import numpy as np def readLevels(file_name='supra/Supracenter/level_conversion_ECMWF_37.txt', header=2): """ Gets the conversion of heights from a .txt file, for use with convLevels(). Arguments: file_name: [string] name of conversion file, .txt heade...
# # Copyright 2018 herd-mdl contributors # # 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 ...
import torch.optim import torch.nn as nn class AgentControl: def __init__(self, hyperparameters): self.gamma = hyperparameters['gamma'] self.device = 'cpu'# 'cuda' if torch.cuda.is_available() else 'cpu' self.loss = nn.MSELoss() #Return accumulated discounted estimated reward ...