text
stringlengths
3.07k
12.6k
""" population_visualizer.py Visualize the behaviour of a complete population. """ from math import cos, sin import matplotlib.pyplot as plt from population.utils.visualizing.elite_visualizer import main as elite_visualizer from population.utils.visualizing.specie_distance import main as specie_distance from populat...
# coding=utf-8 import calendar import pytest from betamax import Betamax from datetime import datetime as dt from openprovider.api import api_factory from openprovider.exceptions import BadRequest, NoSuchElement from openprovider.models import DomainDetails, RegistryDetails from . import configure_betamax, betamaxe...
import io import os import sys import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns def read_text_file(filepath): with open(filepath, 'r') as file: return file.read() def get_line_starting_with(txt, starts_with): first_index = txt.find(starts_with) last_i...
from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError from werkzeug.security import check_password_hash, generate_password...
from enum import IntEnum, unique from typing import List import cv2 import numpy as np @unique class CocoPart(IntEnum): """Body part locations in the 'coordinates' list.""" Nose = 0 LEye = 1 REye = 2 LEar = 3 REar = 4 LShoulder = 5 RShoulder = 6 LElbow = 7 RElbow = 8 LWrist...
from SinglyLinkedList import SinglyLinkedList, Node def odd_even(l: SinglyLinkedList) -> SinglyLinkedList: """Groups all nodes at odd positions in the linked list to the begining of the linked list and all nodes at even positions to the end of the linked list. :param l: A singly linked list class obj...
''' Methods for cross validation, including split persistence to disk ''' import os import math import codecs import numpy as np from drgriffis.common import log def readSingleSplits(f, id_cast=int): data = [] with codecs.open(f, 'r', 'utf-8') as stream: for line in stream: (_id, lbl) = [s...
import sys import time import math import numpy as np import matplotlib.pyplot as plt from acs.objective import fitness, fitness_population from acs.instance import Instance, print_instance from utils.timer import Timer from ga.config import Config, Crossover from ga.copying import copying_gene from ga.local_search...
import pandas as pd import numpy as np import json from bs4 import BeautifulSoup import requests import matplotlib.pyplot as plt # save data import pickle def save(data,fileName): with open(fileName+'.dat', 'wb') as f: pickle.dump(data, f) def load(fileName): with open(fileName+'.dat', ...
# -*- coding: utf-8 -*- """ Created on Mon Dec 14 15:17:12 2020 @author: wantysal """ try: import matplotlib.pyplot as plt except ImportError: raise RuntimeError( "In order to perform this validation you need the 'matplotlib' package." ) # Third party imports from os.path import basename, splitex...
""" The MIT License (MIT) Copyright (c) 2021-present Disnake Development Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,...
import itertools import logging from datetime import datetime, timedelta from vintage_stats.data_processing import CacheHandler, check_victory, get_stack_wl from vintage_stats.utility import WLRecord, get_days_since_date from vintage_stats.constants import VERSIONS def generate_winrate_report(players_list, patch_str...
# This is NOT for production BUT just for unit test import argparse import asyncio import json import logging import pickle import ssl import sys import time from collections import deque from typing import Callable, Deque, Dict, List, Optional, Union, cast from urllib.parse import urlparse import os from aioquic.asy...
#!/usr/bin/env python # coding: utf-8 from dask.distributed import Client from glob import glob import dask.dataframe as dd import json import numpy as np import pandas as pd import os import os.path import geopandas from shapely.geometry import Point csv_schema = """trip_duration,start_time,stop_time,start_station...
#!/usr/bin/python # rebeebus.py 1.0 - An rDNS lookup utility. # Compatible with Python 2 and 3 # Copyright 2018 13Cubed. All rights reserved. Written by: <NAME> import sys import json import re import csv import argparse import socket import operator # Handle Python 2 and 3 compatibility for urllib try: from urllib...
############################################################################### # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this fi...
from federatedml.secureprotol.encrypt import Encrypt from arch.api.utils import log_utils import numpy as np from federatedml.secureprotol import gmpy_math import random from multiprocessing import Pool from multiprocessing import cpu_count N_JOBS = cpu_count() LOGGER = log_utils.getLogger() def _static_encrypt(valu...
from django import forms from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.views import View from django.views.generic.list import ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.detail import DetailView...
#!/usr/bin/env python3 from argparse import ArgumentParser, Namespace from contextlib import nullcontext, suppress from fnmatch import fnmatch from locale import strxfrm from pathlib import Path, PurePath from platform import uname from posixpath import normcase from shutil import copy2, rmtree, which from subprocess ...
from __future__ import print_function import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"]="0" import time import numpy as np import tensorflow as tf from src.model import Model from src.data_loader import dataLoader class Test(object): def __init__(self, model, data, **kwargs)...
import numpy as np from sklearn.linear_model import LogisticRegression from sklearn.metrics import f1_score import sys import yaml from vsmlib.benchmarks.sequence_labeling import load_data import argparse import vsmlib import datetime from sklearn import preprocessing def contextwin(l, win): ''' win :: int co...
# -*- coding: utf-8 -*- import numpy as np import numpy.linalg as la import scipy as sp # ================ ARRAY ================ def make_array(array_shape,max_fov,max_n_det): valid_array_types = ['flower', 'hex', 'square'] if array_shape=='flower': phi = np.pi*(3.-np.sqrt(5.)) # golden angle ...
# -*- coding: utf-8 -*- """ KDTree class.""" import numpy as np from utils import squared_euclidean_distance class Node: def __init__(self, values=None, payload=None, left=None, right=None, disc=None, parent=None): self.values = values # Data point that is presented as list of coodinates. self....
#!/usr/bin/env python3 # # record_vizdoom.py # # Tool for recording human gameplay in ViZDoom # and storing the trajectories # from time import sleep, time import os from argparse import ArgumentParser import json import numpy as np from cv2 import resize, imwrite import vizdoom as vzd import keyboard # This code p...
from typing import List, Tuple class Color: """ 手番定数 """ BLACK = 0 # 先手 WHITE = 1 # 後手 COLOR_NB = 2 @staticmethod def invert(color: int) -> int: """ 手番の反転 :param color: :return: """ return 1 - color class Piece: """ 駒定数 "...
# H20.10.06/R02.02.11 by <NAME> from .ply import lex class SyntaxError (Exception): def __init__(self, msg, LEXER, src, lineno=None, lexpos=None): if lineno is None: lineno = LEXER.lex.lineno if lexpos is None: lexpos = LEXER.lex.lexpos msg += " at %d column %d: %r"...
# -*- coding: utf-8 -*- """ Created on Sat May 2 16:03:56 2015 @author: anderson """ from __future__ import division from pyhfo.ui import plot_single_hfo from .HFOSpectrum import HFOSpectrum from pyhfo.sim import filt import scipy.signal as sig import numpy as np from book_reader import BookImporter import matplotlib...
import os import uuid import shutil import logging import requests import tempfile from typing import List, Dict from flask import current_app from security_dependency_check import celery, Project, Vulnerabilities from .helpers import has_valid_format try: import ujson as json except ImportError: import jso...
# -*- coding: utf-8 -*- """ Created on Sat Jun 13 15:54:51 2015 @author: Diego """ import numpy as np import matplotlib.pyplot as plt from nlp_net import word_vec, conv_layer, pool_layer, layer, hinge_loss def test_word_conv_pool(): l1 = word_vec(word_dim=2) l2 = conv_layer(word_dim=2, K=(4,0), lrate=1.0, c=...
""" Utilities for registering basic commands. Commands are triggered by a configurable prefix. """ import re import asyncio import logging import discord from typing import Dict, Iterator, Optional, Callable, Awaitable, Protocol, cast import util.discord import util.db.kv import plugins class CommandsConfig(Protocol)...
import os import sys import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo import torchvision import segmentation_models_pytorch as smp from segmentation_models_pytorch.base.heads import make_layer from segmentation_models_pytorch.unet.decoder import UnetDecoder fr...
# -*- coding: utf-8 -*- # @Author: TD21forever # @Date: 2019-05-30 20:27:33 # @Last Modified by: TD21forever # @Last Modified time: 2019-06-08 15:00:21 from stack import Stack SYNTAX = ["E->Te","e->+Te|#","T->Ft","t->*Ft|#","F->(E)|i"] VT = ['i','+','*','(',')'] FIRST = {} FOLLOW = {} SELECT = {} TABLE =...
from datetime import datetime from typing import ( Optional, Mapping, ) from sqlalchemy import ( create_engine, func, event, and_, inspect, ) from sqlalchemy.orm import sessionmaker from fire.api.model import ( RegisteringTidObjekt, FikspunktregisterObjekt, Sagsevent, Event...
#!/usr/local/bin/python ## ## Application Security Threat Attack Modeling (ASTAM) ## ## Copyright (C) 2017 Applied Visions - http://securedecisions.com ## ## Written by Aspect Security - http://aspectsecurity.com ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except ...
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import os import re import sys def GetScriptName(): return os.path.basename(os.path.abspath(sys.argv[0])) def GetJavaFilePath(java_package, class_name)...
#!/usr/bin/python import radia as rad import uti_plot import numpy import time import matplotlib.pyplot as plt from mpi4py import MPI import parallel_toolbox def Und(lp, mp, np, cp, lm, mm, nm, cm, gap, gapOffset, numPer): zer = [0,0,0] Grp = rad.ObjCnt([]) #Principal Poles and Magnets y = lp[1]/4;...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2019 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions a...
# coding:utf-8 """ Time: 2021/9/8 17:07 Author: eightyninth File: util.py """ import os.path from sklearn import preprocessing import numpy as np import torch import torch.nn.functional as F alpha = 0.5 beta = 0.001 lambda_ = 0.5 def normalize(x): # x_max, x_min = np.max(x), np.min(x) # return (x - x_min) / ...
"""Functions related to converting content into dict/JSON structures.""" import logging from urllib.parse import urlparse import orjson as json from django.conf import settings from django.core.files.storage import get_storage_class from selectolax.parser import HTMLParser log = logging.getLogger(__name__) def g...
# Profibus-DP telegram analysis # Input is segment data from signal analysis # Output is analyzed data of the segments from tabulate import tabulate import numpy as np # Class to store segment data class Segment: def __init__( self, ID, length, start_time, end_time, state, n_bits, bin_form): ...
import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from astropy.table import Table import pandas as pd import seaborn as sns import scipy.stats as st mpl.rcParams["figure.dpi"] = 150 mpl.rcParams["savefig.bbox"] = "tight" mpl.rcParams["savefig.dpi"] = 300 mpl.rcParams["legend.markerscale"] = 1...
# Vanilla GAN implementation import torch from torch import nn, optim from torch.autograd.variable import Variable from torchvision import transforms, datasets from utils import Logger DATA_FOLDER = './torch_data/VGAN/MNIST' # Loading Data and normalizing it def mnist_data(): compose = transforms.Compose( ...
import numpy as np from rom_builder import RomBuilder from gmpe_analytic import get_analytic import matplotlib.pyplot as plt min_vals = [0.0, 0.0, 10.0, 10.0, 0.0] max_vals = [60.0, 360.0, 50.0, 50.0, 90.0] n_vals_grid = [5, 5, 5, 5, 5] npoints_initial = 1000 desired_err = 1e10 n_forwards = 3000 n_err_update = 500 n_s...
import os, re, time, sqlite3, json, logging logger = logging.getLogger(__name__) # Regexp implementation for sqlite # Example code from https://stackoverflow.com/questions/5365451/problem-with-regexp-python-and-sqlite def regexp(expr, item): if item: reg = re.compile(expr) if reg.search(item): return ...
#!/usr/bin/env python3 ''' This is a boiler plate script that contains hint about different services that are to be used to complete the task. Use this code snippet in your code or you can also continue adding your code in the same file This python file runs a ROS-node of name waypoint_Mission which sends the waypo...
""" Load maps """ import json from collections import OrderedDict import os from os.path import isfile, join import arcade from constants import TILE_SCALING from character_sprite import CharacterSprite from path_following_sprite import PathFollowingSprite from arcade.experimental.lights import Light, LightLayer cla...
import argparse import logging from datetime import datetime from api.proto import engine_pb2 from consumers.consumer import Consumer from third_party.python.defectdojo_api import defectdojo logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class DefectDojoConsumer(Consumer): def __ini...
import cmd import db import logging import argparse import re import transaction import account import util logger = util.get_logger("jnab") class ArgumentParserError(Exception): pass class JnabArgparser(argparse.ArgumentParser): # Override the exit function to only throw error instead of exiting def...
from unittest import mock from unittest.mock import ANY from math import nan import pandas as pd from phc.easy.omics.genomic_test import GenomicTest raw_df = pd.DataFrame( # NOTE: Sample is taken and adapted from BRCA data set [ { "sets": [ { "status": "...
# Copyright 2021 Raven Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
import numpy as np import gym import gym_malware import chainer import chainer.functions as F import chainer.links as L import chainerrl from chainerrl.action_value import DiscreteActionValue from chainerrl import links from chainerrl.agents import acer from chainerrl.distribution import SoftmaxDistribution from ch...
import unittest from buster import utils, data import numpy as np import pandas as pd from IPython import embed SAMPLES_2 = np.array([[1, 2, 3], [7, 8, 9], [7, 8, 9]]) SPACE_2 = data.Space.from_df(pd.DataFrame(SAMPLES_2)) DF_1 = pd.DataFrame({ 'int': [-100, 0, 100], 'float': [-100.0, 0.0, 100.0], 'bool':...
from . import cut_texts, creat_dict, text2vec, cal_similarities import pandas as pd import numpy as np import random import warnings from multiprocessing import Process, Queue import pickle warnings.filterwarnings('ignore') def mul_cal_similarities(v, v_list, v_list_index, similarity, modify, path): similarity_a...
from selenium import webdriver from selenium.webdriver.common.by import By import time import random from selenium.webdriver.support.ui import Select DRIVER = webdriver.Chrome(executable_path='..\\part_2_automation\\drivers\\chromedriver.exe') LINK = 'https://www.openstreetmap.org/' CITIES = ['Bucuresti', 'Cluj-Napoca...
# -*- coding: utf-8 -*- # this contains fixtures that can/should be loaded in conftest.py in your project to # override some of the dependent pytest-plugins fixtures import os import pytest import re from django.core.urlresolvers import reverse from splinter.exceptions import ElementDoesNotExist # def pytest_addop...
#!/usr/bin/env python3 import pytest from itertools import cycle from operator import attrgetter DAY='13' VERT='|' HORIZ='-' DIAGDU='/' DIAGUD='\\' INTER='+' CARTUP='^' CARTDOWN='v' CARTLEFT='<' CARTRIGHT='>' CARTS =(CARTUP, CARTDOWN, CARTLEFT, CARTRIGHT) CARTSL='L' CARTSS='S' CARTSR='R' CARTSEQUENCE=(CARTSL, CARTSS,...
import time import sys import warnings import rlp from collections import OrderedDict from ethereum import ethash, ethash_utils, utils from ethereum.block import Block, BlockHeader from ethereum.utils import sha3, encode_hex from ethereum.slogging import get_logger from ethereum.ethpow import check_pow from ethereum.st...
from django.shortcuts import render, redirect from django.http import HttpResponse from django.core.urlresolvers import reverse from . import models # Create your views here. def hello(request, argument): data = "这是一个测试的模板文件" return render(request, "index/hello.html", {'info': data, 'arg': argument}) def nu...
from flask_pymongo import PyMongo import pymongo import click from flask.cli import with_appcontext from flask import current_app import sys from bravo_api.models.readers import read_canonical_transcripts, read_omim, read_hgnc, read_gencode, read_snv, read_qc_metrics from itertools import chain, islice from multiproces...
from concurrent.futures import ThreadPoolExecutor, as_completed from time import time, sleep import requests from logging import getLogger import json # access the base logging object log = getLogger() MAX_RESULT_LIMIT = 1000 class Parameter: """ Class to track the query parameters that can and will ...
import getpass, random from datetime import datetime from os import system, name #asd=getpass.getpass(prompt='enter text : ', stream=None) #print(asd) #for i in range(10): print(random.randint(1,3)) playScore=dict() def clear(): if name=='nt': system('cls') else : system('clear') def getTitle(): ...
import os from typing import Optional, Tuple, Union import numpy as np import pickle import matplotlib matplotlib.use("Agg") from matplotlib import pyplot as plt from .common import get_datetime, mkdir COLOR_LIST = [ 'blue', 'green', 'red', 'cyan', 'magenta', 'yellow', 'black', 'purple', ...
''' ~ Mathematics and Music ~ Code adapted from: https://github.com/weeping-angel/Mathematics-of-Music A piece in Emaj scale ''' #libraries import numpy as np import math from pprint import pprint from scipy.io.wavfile import write samplerate = 44100 def get_wave(freq, duration=0.5): ''' Input: frequecy time...
##HEADING: LONGEST PALINDROMIC SUBSTRING #PROBLEM STATEMENT: """ FIND AND RETURN LONGEST PALINDROMIC SUBSTRING PRESENT IN INPUT STRING. INPUT IS A STRING AND OUTPUT IS A PALINDROMIC STRING WHICH IS A SUBSTRING OF INPUT STRING. ALL SUBSTRINGS OF INPUT STRING OF LENGTH 1 ARE CONSIDERED PALINDROMES. IF IN...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } cities=('chicago','new york city','washington') months=('january','february','march','april','may','june', 'all') days=('sunday',...
"""Describe table row formats for CTAMLDataDumper output files. These row classes below define the structure of the tables in the output PyTables .h5 files. """ from tables import ( IsDescription, UInt32Col, UInt16Col, UInt8Col, Float32Col, StringCol, Int32Col, ) class EventTableRow(IsD...
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, print_function, division from itertools import product import pytest import numpy as np from numpy.testing import assert_equal, assert_allclose from astropy import units as u from astropy.coordinates.angle_utili...
import os from persephone_client.client import PersephoneException, PersephoneClient class PersephoneBuildHelper: """High-level helper to manage builds and upload screenshots in a stateful manner.""" def __init__(self, root_endpoint, username, password, ...
import segmentation.Segmentation as segmentation_subsystem import classifier_subsystem.cnn_with_tfrecords as classifier_subsystem import translator_subsystem.lut_translator as translator_subsystem import utils.preprocess as pp import utils.classify_util as classify_utils import utils.image_augmenting as augment_utils i...
__all__ = [ 'recvfile', ] import contextlib import http.client import logging import re import socket from g1.asyncs.bases import adapters from g1.bases import loggings from g1.bases import pools from g1.bases.assertions import ASSERT LOG = logging.getLogger(__name__) _CHUNK_SIZE = 8192 _BUFFER_POOL = pools.Tim...
import collections import configparser import logging import multiprocessing as mp import os import re import sys import pandas as pd # type: ignore # configuration config = configparser.ConfigParser() config.read('config.ini') PARALLELISM = int(config['environment']['parallelism']) # logging logging.basicConfig(fo...
#!/usr/bin/env python2 # Library for sending UDP commands to an EV3 # Commands include: motors # Message headers: # RQT: RPI -> EV3 request sensor data # SNR: EV3 -> RPI send sensor data # CMD: RPI -> EV3 send motor command # EV3 IP: 169.254.21.39 # RPI IP: 169.254.21.44 from tcpcom_py3 import TCPServer import...
# TODO like in anyHR constraints # TODO enum switch for word sampler, etc # TODO Boltzmann: precompute gen func, modulus # TODO breadth first search: precompute list of paths # import random import warnings from enum import Enum import numpy as np from numpy.polynomial import Polynomial as P from shapex.alphabet.le...
from collections import deque from akf_corelib.random import Random class Stack(object): def __init__(self): self.items = deque([]) def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() de...
from os.path import isfile from pytezos import Contract from pytezos.interop import Interop from pytezos.encoding import is_kt, forge_timestamp from pytezos.repl.control import instruction, do_interpret from pytezos.repl.context import Context from pytezos.repl.parser import get_int, get_string, get_bool, parse_prim_e...
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import tensorflow.keras as keras from tensorflow.keras import Sequential, optimizers from tensorflow.keras.layers import Input, Dense, Flatten, LeakyReLU from tensorflow.keras.models import Model, save_model from tensorflow.keras.activations imp...
import RPi.GPIO as gpio import time from argparse import Namespace def insert_cgram(index): return str(unichr(index)) class LCD: LCD_WIDTH = 16 # LCD Character width LCD_LINES = 2 # LCD Character lines LCD_CHR = gpio.HIGH LCD_CMD = gpio.LOW E_PULSE = 0.0005 E_DELAY = 0....
from ctypes import sizeof import math import pytest from dmm.definitions import * from dmm.controllers.v86d.data import V86DData, V86DRawData dc_270_2_mV = bytes( [0x2B, 0x32, 0x37, 0x30, 0x32, 0x20, 0x34, 0x31, 0x00, 0x40, 0x80, 0x1A, 0x0D, 0x0A] ) temp_31_4_C = bytes( [0x2B, 0x30, 0x33, 0x31, 0x34, 0x20,...
import random import matplotlib.pyplot as plt import numpy as np import math import cv2 import exifread IMG_LIST = [ "IMG_2605.JPG", "IMG_2606.JPG", "IMG_2607.JPG", "IMG_2608.JPG", "IMG_2609.JPG", "IMG_2610.JPG", "IMG_2611.JPG", "IMG_2618.JPG", "IMG_2619.JPG"] #exposure_times = np.array([1/640., 1/320., 1/200...
""" Module that regroups different email backends """ import html import os import smtplib import textwrap from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart from .utils import AllowedList, filter_args, filename_ext class EmailBackend...
import os, sys, time import argparse import warnings import cv2 import numpy as np import sounddevice as sd from scipy.io import wavfile from codec import * from converter import convert def get_parser(): parser = argparse.ArgumentParser( description="Real-time steganography: " "hidin...
# -*- coding: utf-8 -*- """ Implements CephCI logging interface. In this module, we implement a singleton LOG object that can be used by all components of CephCI. It supports the below logging methods - error - warning - info - debug Along with the above, it provides support for pushing events to ...
import copy import inspect import itertools import os from typing import * from deprecation import deprecated T = TypeVar('T') @deprecated("Only to be used by 'normal' configs. PyPlant configs should use pyplant_extras.") def expand_config_placeholders(config: Dict[str, Any], placeholderMap: Dict[str, str]): ...
"""CVR miner. Usage: cvrminer.cvrfile show-file [<filename>] cvrminer.cvrfile write-virksomhed-features-file Description: Handles JSONL files from CVR in Erhvervsstyrelsen (Danish Business Authority) with information about companies, places and participants. JSON file structure ------------------- _id ...
# -*- coding: utf-8 -*- """Visualization methods for learned components. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import cv2 import os from .utils import make_uint8_img, resize_img_stack import numpy as np def plot_components(components, path)...
# # Author: <NAME> # Date: 09.03.2021 # import tensorflow as tf import numpy as np def euler_to_mat(z, y, x): """ Converts euler angles to rotation matrix. Arguments: z: rotation angle along z axis (in radians) -- size = [B, ...] y: rotation angle along y axis (in radians) -- size = [B, ...] x: rot...
"""behaviours.py Add behaviours to hardware inteface connections. """ from .hw_devices import USB, ADC, I2C, SPI, UART, PWM, GPIO, Gpio2Gpio from .hw_devices import Usb2Usb, Adc2Adc, I2c2I2c, Spi2Spi, Uart2Uart, Pwm2Pwm from .hw_devices import Power2Power from .hw_devices import GPIOType from ..exceptions import * ...
# python import re # django from django import forms from django.core.paginator import Paginator from django.template.defaultfilters import slugify # third party #from django_select2 import AutoSelect2TagField #from django_select2.widgets import Select2Widget #from django_select2.util import JSFunction from crispy_fo...
"""Use wraith to compare current version against published docs. """ import unittest import os import copy import re import yaml import subprocess import contextlib from distutils.version import LooseVersion import http.server import socketserver import threading REFERENCE_URL = "https://www.cgat.org/downloads/public...
#! /usr/bin/python3 import os import sys import json ADCs={"name":"ADC"} INPUTS={"name":"INPUT"} OUTPUTS={"name":"OUTPUT"} PPS={"name":"PPS"} UARTS={"name":"UART"} CN7={ "name": "CN7", 1 : "PC10", 3 : "PC12", 5 : "-", 7 : "BOOT0", 9 : "-", 11 : "-", 13 : "PA13", 15 : "PA14", ...
from zeep import Client as zeepClient from zeep.wsse.username import UsernameToken from zeep import xsd from lxml import etree from .Access import Access from .Api import Api from zeep.xsd.schema import Schema class Client: def __init__(self, web_service: Api = None, drm_adapter: Api = None): if web_servi...
from configuration import main_configuration as config from flask import Flask, request from flask import session as user_session from flask.ext.admin import Admin, BaseView, expose from flask.ext.admin.contrib.sqla import ModelView from flask.ext.admin import AdminIndexView import md5 import datetime from database_mo...
from petlib.bn import Bn from petlib.ec import EcGroup, EcPt from bplib import bp from lib.LibRS import RS from lib.LibNIZK import NIZK from lib.LibFBB import FBB from lib.LibBLS import BLS import hashlib def H(otsvk): # 这里要确保这里生成的G和BLCred的self.G是一样的才行 G = bp.BpGroup() X_ = otsvk[0].export() Y_ = otsv...
import os.path as osp import torch import torch.nn.functional as F from torch.nn import Module, Linear, Dropout from torch.optim import Adam from torch_geometric.nn import global_mean_pool as gap from torch_geometric.nn import global_max_pool as gmp from torch_geometric.nn import GlobalAttention from torch_scatter imp...
# Copyright (C) 2019 Greenweaves Software Limited # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, ...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- from gevent import monkey from flask.wrappers import Response if not monkey.is_module_patched('__builtin__'): monkey.patch_all() # causes problems if done twice from flask import Flask, render_template, request, Blueprint, Response from flask_sockets import Sockets i...
#Servidor intermediario para acesso indireto de <NAME>, <NAME> # -*- coding: utf-8 -*- import socket import sys import threading #dados guardados em maps #names = {"1":("localhost","1234")} #keys = {"1":(listaS1)} names = {} keys ={} #Para cada serviço, uma lista com suas palavras-chave #listaS1 = ["video","engraçado...
import random import numpy as np __all__ = ['skipgrams', 'sequence_pad', 'make_sampling_table'] def skipgrams(sequence, vocabulary_size, window_size=4, negative_samples=1., shuffle=True, categorical=False, sampling_table=None, seed=None): """Generates skipgram word pairs. Thi...
from __future__ import annotations import ast import functools import sys from typing import Iterable from tokenize_rt import Offset from tokenize_rt import Token from tokenize_rt import UNIMPORTANT_WS from pyupgrade._ast_helpers import ast_to_offset from pyupgrade._ast_helpers import has_starargs from pyupgrade._as...
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #Signal-To-Noise_Calculator.py #<NAME> #2022/02/15 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import numpy as np import matplotlib.pyplot as plt import os import time from scipy.signal import find_peaks, peak_widths from pyteomics import mzml from csv import wri...