text
stringlengths
3.07k
12.6k
import os import six from os.path import expanduser, exists, dirname from CloudFlare import CloudFlare from CloudFlare.exceptions import CloudFlareAPIError import logging as log # for verbose output from netaddr import IPNetwork, IPAddress # long story short, "configparser" Python 2 backport RPM package is no good be...
import time import os import re import argparse import subprocess import locale g_DebugEnabled=False def get_locale_lang() ->str: ret_locale = list(locale.getdefaultlocale()) if ret_locale[1] == 'cp950': return 'Big5' elif ret_locale[1] == 'cp1252': return 'utf8' else: return '...
import matplotlib.pyplot as plt import numpy as np import torch from torch import nn from torch import tensor from torch import optim import torch.nn.functional as F from torch.autograd import Variable from torchvision import datasets, transforms import torchvision.models as models from collections import OrderedDict i...
# 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, software # d...
from flask import Flask from nose.tools import raises from flask_oauthlib.client import encode_request_data from flask_oauthlib.client import OAuthRemoteApp, OAuth from flask_oauthlib.client import parse_response from oauthlib.common import PY3 try: import urllib2 as http http_urlopen = 'urllib2.urlopen' excep...
from http.server import * from http import HTTPStatus import urllib.parse as uparse import airspeed from ruamel.yaml import YAML import os import subprocess import json import dbus import glob import utils import namedtupled yaml = YAML() import sys def eprint(*args, **kwargs): print(*args, file=sys.stderr, **kw...
# Copyright 2017-2020 <NAME> # # 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, soft...
#!python import os, sys, string, time, BaseHTTPServer, getopt, re, subprocess, webbrowser from operator import itemgetter from utils import * from annotate import Annotate from scaffold import Scaffold from findscforfs import FindScaffoldORFS from abundance import Abundance sys.path.append(INITIAL_UTILS) from ruffus...
""" Module used to describe all of the different data types """ import time import datetime class OrderType: """ Enum used to describe all of the different order types available for use """ MARKET = 'MARKET' LIMIT = 'LIMIT' STOP = 'STOP' STOP_LIMIT = 'STOP LIMIT' TRAILING_STOP = 'TRAIL...
import re from typing import Iterable, Tuple, List import distlib.markers import pkg_resources from distlib.markers import DEFAULT_CONTEXT from packaging.specifiers import SpecifierSet from mach_nix.cache import cached from mach_nix.versions import PyVer, Version def context(py_ver: PyVer, platform: str, system: st...
from PIL import Image from PIL.ExifTags import TAGS, GPSTAGS import os import os.path import time # Returns a human readable string representation of bytes. def human_readable_size(n_bytes, units=None): if units is None: units = [' bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'] return str(n_bytes) + unit...
import re import json import subprocess import xml.etree.ElementTree as ET from tqdm import tqdm from collections import Counter from transition_amr_parser.amr import AMR def read_amr(file_path, ibm_format=False, tokenize=False, bar=True): with open(file_path) as fid: raw_amr = [] raw_amrs = [] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Aug 25 20:29:36 2019 @author: charleshen The calculation of 63 molecular constitutional indices based on its topological structure. Including MQNs(molecular quantum numbers.) Nguyen et al. ChemMedChem 4:1803-5 (2009) """ from rdkit import Chem fro...
""" filename chapter_id speaker_id dataset_id 0 1272/128104/1272-128104-0000.wav 128104 1272 dev-clean 1 1272/128104/1272-128104-0001.wav 128104 1272 dev-clean 2 1272/128104/1272-128104-0002.wav 128104 1272 dev-clean 3 1272/128104/1272-128104-0003.wav ...
""" Set-MNIST dataset Mostly copy-and-paste from https://github.com/Cyanogenoid/dspn """ import os import urllib import numpy as np import torch import torch.utils.data from torch.utils.data import DataLoader import torchvision import torchvision.transforms as transforms from torchvision import datasets datasets.MNIS...
#! /usr/bin/python # -*- coding: utf-8 -*- """MobileNet for ImageNet.""" import os import tensorflow as tf from tensorlayer import logging from tensorlayer.files import (assign_weights, load_npz, maybe_download_and_extract) from tensorlayer.layers import (BatchNorm, Conv2d, DepthwiseConv2d, Flatten, GlobalMeanPool2d,...
# 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 file # to you under the Apache License, Version 2.0 (t...
from typing import List from bleu import * import math import pandas as pd import fasttext import numpy as np from pathlib import Path from tqdm import tqdm from subprocess import PIPE, run import json # LM for perplexity model = None tokenizer = None def out(command): result = run(command, stdout=PIPE, stderr=P...
from src.APIs import FacebookAPI, OpenWeatherMapAPI, NewsAPI, SchedulerAPI from src.NLP import NLP, Multimedia from src.Utils import Utils from flask import Flask, request, session, url_for, redirect from src.Models import Session, Client import traceback, json, argparse, os import google.oauth2.credentials import go...
"""My Simple MetaReacher domain.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections from rlkit.envs.dmcs_envs.meta_env import MetaEnvironment from rlkit.envs.dmcs_envs.meta_task import MetaTask # Internal dependencies. from dm_control ...
# NOTE: this script processes results for ONE listener group or test directory, # if your experiment has more than one group, use stitch.py # NOTE: make sure to call source setup.sh before calling this script! # how to run this script: python3 custom_post_process [EXPERIMENT_NAME] [NUMBER_OF_STIMULI] # example run: p...
import simpy from client import Client from scheduler import WFQScheduler, DRFScheduler from seda_resource import Resource from stage import Stage, OnDemandStage from stage_req import StageReq class TwoStageServer(object): """ A two stage server, where stage2 suffers the no scheduling problem """ de...
#!/usr/bin/python # Copyright (c) 2020, 2021 Oracle and/or its affiliates. # This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license. # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for d...
from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.shortcuts import redirect, render from django.views import View from rest_framework.utils import json from django.contrib.auth.models import Group from django.contrib import messages from time impo...
# Copyright (c) 2018 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 appli...
import numpy as np from freetype import Face import trimesh from shapely import geometry from objects.parameters import FONT_PATH, INTERFACE_WIDTH, LABEL_DEPTH, POST_LENGTH, POST_OFFSET, POST_RADIUS from objects.utilities import calc_R_euler_angles, fuse_meshes # Parameters for font face glyph HEIGHT = 2200 WIDTH = 16...
import model import paddle import numpy as np import argparse from reprod_log import ReprodLogger import argparse import os import pickle import random import numpy as np import csv reprod_logger = ReprodLogger() parser = argparse.ArgumentParser(description='PyTorch Relational-Network sort-of-CLVR Example') parser.ad...
""" Common Python utilities for interacting with the dashboard infra. """ import argparse import datetime import json import logging import os import sys def print_log(msg, dec_char='*'): padding = max(list(map(len, str(msg).split('\n')))) decorate = dec_char * (padding + 4) print(f'{decorate}\n{msg}\n{de...
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch from torch.utils import data import numpy as np from functools import reduce from egg.zoo.objects_game.util import compute_binomia...
#!/usr/bin/env python # Copyright (c) 2015-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. from __future__ import print_function from clang.cindex import Cursor, CursorKind, TokenKind from utils i...
# # @lc app=leetcode id=297 lang=python3 # # [297] Serialize and Deserialize Binary Tree # # https://leetcode.com/problems/serialize-and-deserialize-binary-tree/description/ # # algorithms # Hard (51.39%) # Likes: 4821 # Dislikes: 214 # Total Accepted: 480.7K # Total Submissions: 935.3K # Testcase Example: '[1,2...
"""Routines for Stage Two of CUSP: Training the Quantum Autoencoder.""" import numpy as np from multiprocessing import Pool from cirq import Circuit, MeasurementGate, ParamResolver from cirq.ops import * from cirq.google import ExpZGate, XmonQubit, XmonSimulator from cirq.circuits import InsertStrategy from cirq.cont...
# This file is part of ReACORN, a reimplementation by <NAME> of the ACORN # paper by Martel et al. published at SIGGRAPH 2021. # # Copyright (c) 2021 -- <NAME> (<NAME> <<EMAIL>>) # # The MIT license: # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated docume...
from copy import copy from typing import List, Tuple, Union, Iterator, Iterable import numpy as np class Size: def __init__(self, size: Union[int, None]): """ Create a Size object with the given size. If the size passed in is None, then it is treated as infinite :param size: ...
# -------------------------------------------------------------------------------------------------- # SSH: Single Stage Headless Face Detector # Main training module # This file is a modified version from https://github.com/rbgirshick/py-faster-rcnn # Modified by <NAME> # ----------------------------------------------...
from pathlib import Path from time import time ### XXX Fix for Python 3.8 bug (https://github.com/prompt-toolkit/python-prompt-toolkit/issues/1023) import asyncio import selectors selector = selectors.SelectSelector() loop = asyncio.SelectorEventLoop(selector) asyncio.set_event_loop(loop) ### XXX End of fix from pygm...
#!/usr/bin/env python """ Python script for building documentation. To build the docs you must have all optional dependencies for pandas installed. See the installation instructions for a list of these. Usage ----- $ python make.py clean $ python make.py html $ python make.py latex """ import sys import o...
# Importing Libraries import tkinter as tk from PIL import ImageTk, Image from tkinter.scrolledtext import ScrolledText from tkinter.messagebox import askyesno from tkinter.filedialog import asksaveasfilename, askopenfilename # Defining Colors text_color = '#fffacd' menu_color = '#dbd9db' root_color = '#6c809a' # De...
# ********************************************************************************************************************** # # brief: read image data from ros bag files and persist it # # author: <NAME> # date: 23.04.2020 # # ***************************************************************************************...
""" @Author: <NAME> @Email: <EMAIL> """ import tensorflow as tf import numpy as np from aide.aide_ import AIDE, AIDEModel from aide.model_config import Config from aide.utils_tf import get_optimizer, get_dist_func from aide.constant import OPTIMIZER_ADAM, RELU, TRAIN_MODE, EVAL_MODE, PREDICT_MODE from aide.constant i...
### # (C) Copyright [2019-2020] Hewlett Packard Enterprise Development LP # # 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 ...
import tempfile import tensorflow as tf from six.moves import urllib import pandas as pd flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string("model_dir","","Base directory for output models.") flags.DEFINE_string("model_type","wide_n_deep","valid model types:{'wide','deep', 'wide_n_deep'") flags.DEFINE_int...
from datetime import datetime from django.db import models class WithScrobbleCountsManager(models.Manager): """ Adds a with_scrobble_counts() method. """ # Can we filter these (things) by Album? is_filterable_by_album = True # Can we filter these (things) by Artist? is_filterable_by_art...
# # Copyright 1993-2019 NVIDIA Corporation. All rights reserved. # # NOTICE TO LICENSEE: # # This source code and/or documentation ("Licensed Deliverables") are # subject to NVIDIA intellectual property rights under U.S. and # international Copyright laws. # # These Licensed Deliverables contained herein is PROPRIETAR...
# 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 file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
import os, sys import gzip import json import argparse sys.path.append(os.getcwd()) import pandas as pd import numpy as np import text_process def get_df(path): """ Apply raw data to pandas DataFrame. """ i = 0 df = {} g = gzip.open(path, 'rb') for line in g: df[i] = json.loads(line) ...
import numpy as np from pytest import raises, fail, approx from depynd.information import mutual_information, conditional_mutual_information X = np.random.multivariate_normal(np.zeros(2), np.eye(2), 10) w = np.random.randint(0, 2, 10) x = np.random.normal(0, 1, 10) y = np.random.normal(0, 1, 20) z = np.empty([10, 0])...
############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this # distribution. # # THIS SOFTWARE IS PROVIDED "...
import bisect import mmap import os import sys import tempfile import threading from .context import reduction, assert_spawning from . import util __all__ = ['BufferWrapper'] if sys.platform == 'win32': import _winapi class Arena(object): _rand = tempfile._RandomNameSequence() def __init__(se...
#!/usr/bin/env python3 # coding: utf-8 # Copyright 2016 <NAME>, https://github.com/tywtyw2002, and https://github.com/treedust # # 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 # # ...
from typing import Union from flask import Blueprint, current_app, jsonify, request, json from app import SessionKey, socketio from app.models import KeyLookupTable from app.utils import error_respond from app.utils.decorators import session_verify, master_password_verify from app.utils.master_password import MasterP...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 Intel, Inc. # Copyright (c) 2011-2012 OpenStack, LLC. # 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 Li...
import os import uuid from datetime import datetime from django.conf import settings from django.template.defaultfilters import filesizeformat from appvalidator.constants import PRERELEASE_PERMISSIONS import commonware.log from PIL import Image from tower import ugettext as _ import mkt from lib.video import library...
from os.path import exists, expanduser from typing import Optional, Union from pytezos.context.impl import DEFAULT_IPFS_GATEWAY, ExecutionContext # type: ignore from pytezos.crypto.encoding import is_pkh, is_public_key from pytezos.crypto.key import Key, is_installed from pytezos.jupyter import InlineDocstring from p...
#!/usr/bin/env python3 # encoding: utf-8 # @Time : 2019/5/9 14:18 # @Author : <NAME> import glob import os import numpy as np import nibabel as nib import torch from torch.utils.data import Dataset, DataLoader import random class Brats2018(Dataset): def __init__(self, patients_dir, crop_size, modes, train=Tru...
# -*- coding: utf-8 -*- """ Created on Fri Mar 23 10:56:37 2018 @author: mpinkert My personal directories """ import os def create_test_dictionary(test_dir='tests'): test_files_dir = os.path.join(test_dir, 'test_files') test_dict = { 'test_dir': test_dir, 't...
import json from typing import Dict, Generic, List, Optional, Set, Tuple, TypeVar, Union class NamedIO(object): def __init__(self, node: Union[str, "Node"], io_name: Optional[str]): self.node = node self.io_name = io_name def to_dict(self): return { "key": self.key, ...
# This file is part of the Reproducible and Reusable Data Analysis Workflow # Server (flowServ). # # Copyright (C) 2019-2021 NYU. # # flowServ is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Unit tests for the manager that maintains...
import threading from queue import Queue, Empty from threading import Thread from PyQt5.QtCore import QCoreApplication from flask import Flask, request import json from src.gui.input_manager import InputManager from src.gui.ui_manager import UIManager class Order: def __init__(self, command, args=[]): s...
# Pymongo import pymongo from pymongo import MongoClient from pymongo.collection import ReturnDocument # Other imports from datetime import datetime from bson.objectid import ObjectId MONGO_URL = 'localhost' MONGO_PORT = '27017' DB_NAME = 'scale-db' TASKS_COLLECTION = 'tasks' SCALERS_COLLECTION = 'scalers' class Tas...
import numpy as np import networkx as nx from collections import OrderedDict NODE_FDIM = 12 EDGE_FDIM = 2 * NODE_FDIM def minmax(it): return min(it), max(it) def get_edge_incidence_size(graph): degrees = np.array(graph.degree)[:, 1] return np.sum(degrees * (degrees - 1)) def _get_graph_edges(graph, ...
from tokenize import String import numpy as np import os import sys import pickle import argparse from tqdm import tqdm sys.path.append('../') from gan_models.dcgan.model import gen_random #sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'tools')) from attack_models.tools.utils import * from sklearn.neigh...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals import time import inspect import logging import warnings import six import requests from wechatpy.constants import WeChatErrorCode from wechatpy.utils import json, get_querystring from wechatpy.session.memorystorage import MemoryStorage...
# Copyright 2012, <NAME> # Code at http://inamidst.com/duxlot/ # Apache License 2.0 import multiprocessing import os import re import socket import socketserver import sys import time if not os.path.isfile("duxlot"): print("Error: Not running in the duxlot directory") sys.exit(1) sys.path[:0] = [os.getcwd()]...
# -*- coding: utf-8 -*- # # Copyright 2017 Google LLC. 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 requir...
import torch from torch.utils.data import DataLoader import horovod.torch as hvd from deepqmc.solver.solver_base import SolverBase from deepqmc.utils.torch_utils import (DataSet, Loss, OrthoReg) def printd(rank, *args): if rank == 0: print(*args) class SolverOrbital(SolverBase): def __init__(self,...
# -*- coding: utf-8 -*- ## 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...
import itertools import re from collections.abc import Iterable from typing import Any, Union Number = Union[int, float] class Problem: def __init__(self): """Initiates Problem space.""" pass def expand(self, state) -> Iterable[tuple[Number, Any]]: """Given a state, returns all neigh...
"""Undocumented Module""" __all__ = ['ExclusiveObjectPool', 'ObjectReport'] from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase import DirectObject, ObjectPool, GarbageReport from direct.showbase.PythonUtil import makeList, Sync import gc import sys import __builtin__ """ >>> from di...
# -*- coding:utf-8 -*- from base.base_data_loader import BaseDataLoader import os import numpy as np import scipy.io as sio import torch from SampleData import sampledata class MRIData(BaseDataLoader): ''' 把一个getter方法变成属性,只需要加上@property就可以了, 此时,@property本身又创建了另一个装饰器@score.setter, 负责把一个setter方法变成属性赋值....
# Imports from torch.utils.data import DataLoader, Dataset from torchvision import transforms import os import glob import torch from PIL import Image from sklearn.model_selection import train_test_split from shutil import copy2 import tqdm class RagDataset(Dataset): """ Custom pytorch dataset c...
#!/usr/bin/env python3 # Copyright 2021 Canonical Ltd. # See LICENSE file for licensing details. """ # alertmanager library This library is designed to be used by a charm consuming or providing the `alerting` relation. """ import ops from ops.framework import EventSource, EventBase from ops.relation import ConsumerB...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ------------------------------------------...
# coding=UTF-8 __author__ = 'Jonarzz' """Module used to transfer from usage of dictionaries to databases for the bot to use.""" import sqlite3 import os import datetime import re from responses_wiki import dota_wiki_parser as parser import dota_responses_properties as properties SCRIPT_DIR = os.path.dirname(__fi...
from io import BytesIO, StringIO import contextlib import csv import datetime import logging import astropy.time import astropy.units as u import pytz import voeventparse as vp from astropy.coordinates import SkyCoord from fourpisky.feeds.feedbase import FeedBase from fourpisky.voevent import ( create_skeleton_4p...
#!/usr/bin/env python # coding: utf-8 # # Risk Premia Estimation using GMM # Start by importing the modules and functions needed # In[ ]: from numpy import hstack, ones, array, mat, tile, reshape, squeeze, eye, asmatrix from numpy.linalg import inv from pandas import read_csv, Series from scipy.linalg import kron...
import re, spacy import numpy as np import pandas as pd import pdfminer from gc import collect from collections import Counter from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter, XMLConverter from pdfminer.layout import LAParams from pdfminer.pdfpage impor...
# wujian@2019 import torch as th import numpy as np from queue import PriorityQueue from torch.nn.utils.rnn import pad_sequence from kaldi_python_io import ArchiveReader, ScriptReader, Reader def make_pitloader(feats_scp, feats_kwargs, loader_kwargs, batch_s...
#! /usr/bin/python # Copyright 2004 <NAME> # # 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, publi...
# 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...
import tensorflow as tf # from tensorflow.contrib.data import Dataset, Iterator class DatasetReader: filenames = [] tf_filenames = tf.convert_to_tensor([]) label_filenames = [] image_options = {} def __init__(self, records_list, image_options={}, batch_size=1, pwc=False): """ Intia...
import os from twisted.internet import reactor from twisted.internet.error import ConnectionRefusedError from twisted.protocols.policies import WrappingFactory from twisted.python import log from twisted.python.filepath import FilePath from twisted.python.failure import Failure from twisted.test.test_sslverify import ...
# Copyright 2019 Shift Cryptosecurity AG # # 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...
from machine import Pin, I2C import math import time class ADXL345_SPI: SPI_READ = 1 << 7 SPI_MULTIPLE_BYTES = 1 << 6 ADXL345_DATAX0 = 0x32 # https://github.com/DFRobot/micropython-dflib/blob/master/ADXL345/user_lib/ADXL345.py def __init__(self, hspi, cs): self.spi = hspi self.cs ...
#!/usr/bin/python2 import math import sys def distance(x1,y1,x2,y2): return math.ceil( (abs(x1-x2) + abs(y1-y2))**0.5 ) class Drone: def __init__(self, index, x, y, PL): self.index = index self.x = x self.y = y self.max_weight = PL self.items={} def load_product(s...
"""Provide tests for the model base.""" from collections import deque from unittest.mock import patch import pytest from openzwavemqtt import base class Level3(base.ZWaveBase): """Represent a level 3 descendant.""" EVENT_ADDED = "level3_added" EVENT_CHANGED = "level3_change" EVENT_REMOVED = "level3...
from hybrid.flicker.flicker_mismatch import * from hybrid.flicker.shadow_flicker import create_turbines_in_grid, get_turbine_grid_shadow from hybrid.log import flicker_logger as logger sys.path.append('.') lat = 39.7555 lon = -105.2211 dx_multiples = range(3, 12, 2) dy_multiples = range(3, 12, 2) deg_multiples = rang...
from datetime import datetime from pathlib import Path from typing import List, Optional import tensorflow as tf from zookeeper import ComponentField, Field from larq_zoo.training.knowledge_distillation.knowledge_distillation import ( TeacherStudentModelFactory, ) from larq_zoo.training.train import TrainLarqZooM...
# Copyright (c) 2013 OpenStack Foundation # 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 ...
import math import numpy as np import pretty_midi from midi2audio import FluidSynth from config.load_yaml import configs # 从轻快到沉重 instruments = ['Music Box', 'Cello', 'Acoustic Grand Piano', 'Pan Flute', 'Viola', 'Electric Piano 1', 'Church Organ', 'Acoustic Guitar (nylon)', ' Fretless Bass'] # instrume...
from __future__ import annotations from typing import Dict, List, Union """ PRA9103/PRA9104 Lab solution for: Race Registry ============= Context: a system for organizing a 5K running race. When runners register for a race, they provide their name, email address and their speed category. A speed category indicates...
import requests from bs4 import BeautifulSoup import re import random import time """以下填写参数""" fill_url = 'https://www.wjx.cn/jq/12345678.aspx' n = 99 interval = 1.5 """n是次数 interval是刷卷间隔时间单位为秒""" session = requests.Session() # 获取调查问卷的页面 def get_fill_content(url): headers = { 'user-agent': 'Mozilla/5.0 (...
import torch import torch.nn.init as torchInit import numpy as np import math from scipy.stats import gengamma from scipy.stats import uniform class UnsupportedInitMethod(ValueError): pass class UnsupportedDistribution(ValueError): pass ######### Normal Distribution ############### def getNormalXavierStd(tenso...
from django.conf import settings from django.contrib.auth import get_user_model from django.db.models import ForeignKey, CASCADE, CharField, Model, TextField, \ IntegerField, BooleanField, URLField from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.translation impo...
# version 0 # 1 byte, version # 1 byte, command ## 0 - create account ### data: ascii username ## 1 - list accounts ### data: (optional) ascii text wildcard ## 2 - send message ### data: ascii sender username DELIM ascii recipient username DELIM ascii message ## 3 - deliver undelivered messages ### data: none ## 4 - de...
# coding=utf-8 # Copyright 2019 The TensorFlow Datasets Authors. # # 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 appl...
import logging from collections import Counter import numpy as np from nltk.translate import bleu_score from nltk.translate.bleu_score import SmoothingFunction from dgmvae.utils import get_dekenize, get_tokenize import logging from dgmvae.dataset.corpora import EOS, BOS from collections import defaultdict import torch ...
from unittest import TestCase from irlib.matrix import Matrix class TestMatrixDocs(TestCase): def setUp(self): self.mxds = MatrixDocs() def test_doc_fields(self): self.assertEqual( self.mxds.doc_fields(), set(['id', 'class', 'terms']) ) def test_is_va...
from apis import JsonResponseContainer from sources.base import MediaSource, PictureSource, TextSource, CommonSource,SearchResult,SearchResults from sources.base.interface import SearchableSource from utils.vhttp import httpGet from sources.bilibili import BilibiliSource from config import Config import apis.bilibili.a...
# RUN: %PYTHON %s 2>&1 | FileCheck %s # pytype: skip-file import sys, time import os from typing import List from collections import namedtuple from collections.abc import Callable from itertools import chain from typing import Sequence, Optional import numpy as np from mlir.ir import * from mlir.dialects import ari...