text
stringlengths
3.07k
12.6k
# -*- coding: utf-8 -*- """ Examples for use the python functions: get push data """ from futuquant.open_context import * class USOrderPushHandler(USTradeOrderHandlerBase): """ 美股定单 """ def on_recv_rsp(self, rsp_str): """数据响应回调函数""" ret_code, content = super(USOrderPushHandler, self).on...
import logging from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from django.views.generic import View from .forms import DiaryCreateForm from .models import Diary, Qu...
# Copyright 2019-, <NAME> and the QuantumFlow contributors # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. """ .. contents:: :local: .. currentmodule:: quantumflow.xqiskit Interface between IBM's Qiskit and QuantumFlow ...
import os from pathlib import Path import numpy as np import pytest from jax import numpy as jnp from slzero import dataset, hmm from slzero.hmm.functions import Params, predict @pytest.fixture def dataset_path() -> Path: path = Path(os.path.dirname(__file__)) / "data" / "test.conllu" return path @pytest....
import logging import os import os.path as path from typing import Iterable, Optional, Sequence, Hashable from collections import Counter import numpy as np import emloop.api # avoids circular dependency from .abstract_model import AbstractModel from ..utils import load_config from ..datasets import AbstractDatase...
import numpy as np import matplotlib.pyplot as plt import scipy as sp import scipy.optimize import math import sys # x = [b (scale), q (polynomial order), a (sparsity), s (lengthscale)] def psi(x, cos_theta): b,q,a,s = x ri = np.cosh(s**2 * cos_theta) / np.cosh(s**2) - a ri = np.nan_to_num(ri) power = ...
import math from typing import ( Callable, Collection, Dict, FrozenSet, Generic, ItemsView, Iterable, KeysView, List, Optional, Set, TypeVar, Union, ) import graphviz import networkx as nx N = TypeVar("N") class DiGraph(nx.DiGraph, Generic[N]): def __init__(s...
import numpy as np def ptnghb(nk, nth): """Short description. Long description if required. Args: - `nk`: number of frequencies/wavenumbers in spectrum. - `nth`: number of directions in spectrum. Returns: - `neigh`: add description. """ # build list of neighbours fo...
from enum import Enum import tkinter as tk from tkinter import ttk from tkinter import messagebox import itertools class Direction(Enum): """ The direction we are traveling through the edit graph.""" unknown = 0 from_above = 1 from_left = 2 from_diagonal = 3 class Node: """ A...
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
""" test_lfi.py - Test class for LFI problems """ import random from problog import root_path import unittest import os import sys import glob from problog.learning.lfi import lfi_wrapper, LFIProblem try: from pysdd import sdd has_sdd = True except Exception as err: print("SDD library not available due t...
# Copyright 2016-2017 Open Source Robotics Foundation, 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 applicabl...
"""Utils for auto classification estimator.""" import math # pylint: disable=bad-whitespace,missing-function-docstring import os from functools import partial import numpy as np import pandas as pd import torch from PIL import Image, ImageOps from torchvision import datasets, transforms from autotimm.data.autoaugment...
#!/usr/bin/env python # -*- coding: utf-8 -*- # 3rd party imports import numpy as np import xarray as xr import pandas as pd from cdflib import cdfepoch, cdfread from dateutil import parser as date_parser __author__ = "<NAME>" __email__ = "<EMAIL>" __copyright__ = "Copyright 2020-2021" __license__ = "MIT" __version_...
""" test_groups.py: test the implementation of "contest groups" in 'OpenAuditTool' (as implemented in groups.py) """ import OpenAuditTool import groups import warnings def graph_1(e): e.gids = [1, 2, 3, 4, 5, 6, 7] e.cids = [11, 22, 33, 44, 55, 66, 77] e.cgids_g[1] = [11, 2] e.cgids_g[2] = ...
import numpy as np from skimage.transform import resize from skimage import transform from skimage import exposure import torch from torch.nn.utils.rnn import pack_padded_sequence as pack, pad_packed_sequence as unpack # ------------------------------------------------ ''' In this block : collate function for DataLo...
import json from basic import Datastore, ShimDatastore default_serializer = json class Serializer(object): '''Serializing protocol. Serialized data must be a string.''' @classmethod def loads(cls, value): '''returns deserialized `value`.''' raise NotImplementedError @classmethod def dumps(cls, ...
""" App configuration ================= """ from typing import Callable, List, NamedTuple, Optional import json from flask import Flask from flask.sessions import SecureCookieSessionInterface import itsdangerous import toml import yaml from . import logger from .auth import current_auth from .views import current_v...
# -*- coding: utf-8 -*- # Copyright (c) 2016-present, CloudZero, Inc. All rights reserved. # Licensed under the BSD-style license. See LICENSE file in the project root for full license information. import os import random from collections import namedtuple import pytest import json import src.app as app from src imp...
from selenium import webdriver from selenium.webdriver.chrome.options import Options import os import _thread import threading import pickle from time import sleep from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditio...
#!/usr/bin/python3 # # BHParse : Parse BurpSuite Generated XML (intercept history) files into html. # author : https://github.com/ajaytekam # usage : ./bhparse -f BurpFile.xml # import sys import os import base64 import random import argparse import xml.etree.ElementTree as ET from hashlib import md5 from shuti...
#!/usr/bin/env python3 import warnings from copy import deepcopy from typing import List, Callable, Optional, Tuple, Set import click as click from rossum.lib import DataPointDict, DataPoints def traverse_datapoints( datapoints: List[dict], transformation: Callable, parent_categories: List[str] = None, **kwargs...
import pandas as pd from utils import * from statsmodels.distributions.empirical_distribution import ECDF # Adapt from the R code in https://sites.google.com/view/ACIC2019DataChallenge/data-challenge # Simulating observational and clinal trial data based on credit card fraud dataset # The dataset consists of 30000 ob...
import functools import importlib import itertools import json import logging import math import operator import os import torch from torchdynamo import config from torchdynamo.utils import check_is_cuda from torchdynamo.utils import checkpoint_params from torchdynamo.utils import is_jit_model from torchdynamo.utils ...
import retworkx from retworkx.visualization import mpl_draw import matplotlib.pyplot as plt from qiskit import * import numpy as np from numpy import linalg as la from scipy.linalg import expm from qiskit.extensions import HamiltonianGate from qiskit.visualization import plot_histogram import imageio def pad_zeros(ad...
# NEON AI (TM) SOFTWARE, Software Development Kit & Application Framework # All trademark and other rights reserved by their respective owners # Copyright 2008-2022 Neongecko.com Inc. # Contributors: <NAME>, <NAME>, <NAME>, <NAME>, # <NAME>, <NAME>, <NAME>, <NAME> # BSD-3 License # Redistribution and use in source and ...
#!/usr/bin/env python """ robhttp2.py - module to handle http communications for robot client apps Version 2 externalizes environment dependencies and prepares the module to support robiot and refactors. Also supports python3 and python2. """ __author__ = "<NAME>" __copyright__ = "Copyright (C) 2009-2020 <NAM...
import torch.multiprocessing as mp import os, time, random from othello import Othello from othello_utils import * from MCTS import MCTS import numpy as np import torch.nn as nn import torch import torch.nn.functional as F import torch.optim as optim import warnings warnings.filterwarnings('ignore') def weights_init(...
""" for generating arguments files for regression.py can be used for reduced splits, hyperparameter sweeps, HTCondor runs, etc """ import os from os.path import join, basename, isfile, isdir import itertools import argparse import re import copy import yaml from parse_reg_args import save_args import utils def...
#!/usr/bin/env python import os import youtube_dl import spotipy import spotipy.util as util from spotipy.oauth2 import SpotifyClientCredentials import spotipy.oauth2 as oauth2 from youtube_search import YoutubeSearch import json import webbrowser ## YouTube downloader options ydl_opts = { 'format': 'bestaudio/be...
""" Command based interactive access control app Usage: access.py [--debug-flag=<bool>] Options: [--debug-flag=<bool>] Set this to true to turn on debugging """ import hashlib, binascii import os import time from docopt import docopt from db import DatabaseConnection from user import User import ...
import sys,os sys.path.append('D:\\chenchuyang\\learning\\lc-model-compression\\') import examples.cvpr2020.cifar10_exp_setups #import cifar10_exp_setups from examples.cvpr2020.modified_lc import RankSelectionLcAlg as LCAlgorithm #from modified_lc import RankSelectionLcAlg as LCAlgorithm import argparse import time fro...
from sklearn.model_selection import train_test_split import cv2 import os from tensorflow import keras import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix import itertools #function to load images to an array def load_images(folder): images = [] for filen...
# coding: utf-8 """ Convert metadata into the new format """ from io import open from click import echo, style from tmt.utils import ConvertError, StructuredFieldError import fmf.utils import tmt.utils import pprint import yaml import re import os log = fmf.utils.Logging('tmt').logger # Import nitrate conditionall...
from collections import namedtuple import pprint from enum import Enum class Direction(Enum): NO_SIDE = 0 LEFT = 1 RIGHT = 2 TOP = 3 BOTTOM = 4 Track = namedtuple('Track', 'direction x_low x_high y_low y_high') def print_tracks(tracks): pprint.pprint(tracks) def make_tracks(xs, ys, points): ...
import cv2 import numpy as np import posenet.constants def valid_resolution(width, height, output_stride=16): target_width = (int(width) // output_stride) * output_stride + 1 target_height = (int(height) // output_stride) * output_stride + 1 return target_width, target_height def _process_input(source_...
''' extract the "viscom"-style calibration grid with big and small markers where big markers are not filled and contain zero (origin), one (x), two (y) dots ''' # pylint: disable=invalid-name # (migrate old tested code) import cv2 import numpy as np def child_object_count(hierarch, idx): ''' ...
import keras from keras.layers import * from keras.activations import * from keras.models import * from keras import backend as K def convBlock(inputs, n_filters, kernel=3, strides=1): net = Conv2D(n_filters, kernel_size=[kernel, kernel], activation = 'relu', strides=1, padding ='same')(inputs) return net def...
import os,cv2,json import numpy as np import torch import torch.nn as nn from torch.utils import data class LSMI(data.Dataset): def __init__(self,root,split,image_pool,image_size, input_type='uvl',output_type=None, mask_black=None,mask_highlight=None): self.root = root ...
from functools import partial from src.unconstrained_min import line_search import numpy as np from src.unconstrained_min import wolf_condition from src.unconstrained_min import report from src.unconstrained_min import check_converge import numdifftools as nd def interior_pt(func, x0, ineq_constraints, eq_co...
import ast import glob import os from collections import defaultdict, MutableMapping from json import dumps from six import string_types from dyson.errors import DysonError from dyson.vars.parsing import parse_keyvalue, iterate_dict from dyson import constants def combine_vars(first_dict, second_dict): """ ...
import torch from torch.autograd import Variable import numpy as np ################################################################################# # # ################################################################################# GPU ...
""" Python function to bridge between the server and the Prolog logic. """ from os import path from typing import List, Optional from itertools import islice from pyswip_mt import PrologMT from jinja2 import Template BASE_PROLOG_FILE = "tic-tac-toe.pl" STACK_LIMIT = 4000000000 # Limit to about 30 seconds runtime ...
from datetime import date from calendar import Calendar from flask import url_for, request, g import json import os import copy import csv from zipfile import ZipFile import urllib.request as url import urllib.error as url_errors # Dictionary to link choices to icons label_icons = { 'Shopping' : 'shopping_cart', ...
# Copyright 2021 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 required by applicable law or a...
import os import json import gzip import time import tempfile import warnings import torch from functools import partial from markovdwp.source.datasets import utils from markovdwp.runtime.trainer import get_trainer from markovdwp.runtime.utils.common import linear from markovdwp.runtime.utils.reconstruction_logger ...
import os # Duplicated in case someone puts stuff in package __init__.py from os.path import join, dirname, realpath, exists from leaderboard_generator.common import get_botleague_db os.environ['SHOULD_USE_FIRESTORE'] = 'false' os.environ['SHOULD_MOCK_GIT'] = 'true' os.environ['SHOULD_MOCK_GCS'] = 'true' os.environ[...
from .BaseParser import BaseDataParser, BaseLabelParser from ...Data.AcousticData import AcousticData as AuDataObj,PureAcousticData import os import numpy as np from ...utils.tools import _md5 from .Features.stft import _parse_one_audio_stft from .Features.mfcc import _parse_one_audio_melspec # from ...utils.t...
import copy from copy import deepcopy import inspect import jinja2 import os import pytest import sys import lena from lena.output.render_latex import ( RenderLaTeX, _Template, _Environment, _select_template_or_default ) from lena.context import get_recursively, update_recursively def test_template(): # Chec...
import logging import psycopg2 from psycopg2.extras import RealDictCursor from psycopg2.extensions import TRANSACTION_STATUS_UNKNOWN, TRANSACTION_STATUS_IDLE from flask import g import threading import tenacity import uuid import pwd import os # we want to set up a separate logger logger = logging.getLogger(__name__)...
import sys from time import sleep import ddddocr import requests from prettytable import PrettyTable from selenium import webdriver from selenium.webdriver.chrome.options import Options def get_driver(driver_path, headless=True): if headless: chrome_options = Options() chrome_options.add_argument(...
# Data Science with SQL Server Quick Start Guide # Chapter 03 # This is a comment print("Hello World!") # This line is ignored - it is a comment again print('Another string.') print('O"Brien') # In-line comment print("O'Brien") # Simple expressions 3 + 2 print("The result of 5 + 30 / 6 is:", 5 + 30 / 6)...
""" Parse command-line arguments. """ from argparse import ArgumentParser import datetime from getpass import getuser import logging import logging.handlers from pathlib import Path import sys import toml import pkg_resources CODELOG = logging.getLogger(__name__) EPIVIZ_LOG_DIR = Path("/ihme/epi/dismod_at/logs") COD...
from collections import defaultdict import pytest import numpy as np import torch from rl.policies import GaussianMLP from rl.algos import PPO class SampleTesterEnv: def __init__(self, obs_dim, action_dim, done_state=10, gamma=0.99): """ A simple environment that unit tests whether or the ...
# Please create a simple example use of the pynn library for your end user. Assume that the end # user knows a lot about their subject matter but has only a basic understanding of Python. # Meaningful examples may include reading a file, finding a few nearby points and writing them # out to the console. from pynn im...
################################################################################ # populate_obs_general.py # # Routines to populate fields in the obs_general table. ################################################################################ import json import os import traceback import julian import pdsfile fro...
import subprocess from datetime import datetime from flask import Blueprint, render_template, request, session, make_response, abort from flowapp import auth_required, constants, models, app, validators, flowspec from flowapp.constants import RULE_TYPE_DISPATCH, SORT_ARG, ORDER_ARG, DEFAULT_ORDER, DEFAULT_SORT, RULE_T...
"""ML-Ensemble :author: <NAME> :license: MIT :copyright: 2017-2018 Global backend configurations. Variables 1. ``DTYPE``: data type of prediction arrays. Must be a numpy dtype. Default is ``float32``. 2. ``TMPDIR``: path to directory where temprorary caches will be hosted. Default is to use system ``tmp`` st...
# vim: expandtab:ts=4:sw=4 from __future__ import division, print_function, absolute_import import argparse import os import cv2 import numpy as np from application_util import preprocessing from application_util import visualization from deep_sort import nn_matching from deep_sort.detection import Detection from de...
from kivymd.toast.kivytoast import toast from kivymd.app import MDApp from kivy.lang import Builder from kivy.garden.mapview import MapView import json from kivy.uix.screenmanager import ScreenManager, Screen from kivy.interactive import InteractiveLauncher from kivy.uix.popup import Popup from kivymd.theming i...
# Can download files needed from here #https://www.senate.gov/legislative/Public_Disclosure/database_download.htm import os import csv import xml.etree.ElementTree as ET # set up function to get xml files you want to use def get_filepaths(directory): # got this function from here http://stackoverflow.com/questions/...
#! /usr/bin/env python3 # # Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
""" Based on: https://github.com/gaganbahga/time_stretch https://github.com/sannawag/TD-PSOLA """ import librosa import numpy as np from numpy.fft import fft, ifft def shift_pitch(signal, fs, factor, psola_params): """ Changing speech tone in 'factor' times. :param signal: :param fs: :param fact...
import ast import typing from abc import ABC, abstractmethod from collections import defaultdict from ..ast import Characters, Fragmented, Grammar, Keywords, Section, Tokens from ..ast.base import Name, Node, Ref, Wrapper from ..ast.characters import CharClass, CharClassUnion, CharRange, WellKnownChars from ..ast.prod...
from typing import Final, List, Set, Dict, Tuple, Any from collections import defaultdict from functools import total_ordering @total_ordering class Point(object): def __init__(self, x: int, y: int, z: int) -> None: self.x: Final = x self.y: Final = y self.z: Final = z def __repr__(s...
import os import gc import psutil import random import time from importlib import reload import mxnet as mx import prepare import util import memonger ins_num = 5 ins_prices = [0.085, 0.17, 0.34, 0.68, 1.53] #ins_mems = [4, 8, 16, 32, 72] #ins_cores = [2, 4, 8, 16, 36] ins_prices =[0.17] ins_num = 1 ins_mems = [8] ...
import numpy as np import matplotlib import matplotlib.pyplot as plt from mpl_toolkits import mplot3d import quadprog from util import plot_neuron_voltages, plot_readout, plot_raster def plot_line_2D(f,g,t,x,y): return ( (f @ x) - (g[:,0][:,None] * y) - t) / g[:,1][:,None] def evaluate_constraints(F,x,G,y,T): ...
import itertools from sqlalchemy import or_, func from flask import Blueprint, render_template, request, current_app, redirect, url_for from flask.ext.login import current_user from flask.ext.security import login_required from flask.ext.security import roles_required from .tokengen import generate_token from .forms i...
try: from json import dumps, loads except: from simplejson import dumps, loads try: # Python 2 from urllib2 import urlopen from urllib import urlencode except: # Python 3 from urllib.request import urlopen from urllib.parse import urlencode __all__ = ['WebAPI'] ...
import sqlite3 import os from flask import Flask, abort, g, flash, render_template, redirect, request, session, url_for from flask.helpers import make_response from flask_login import LoginManager, current_user, login_user, login_required, logout_user from werkzeug.security import generate_password_hash, check_passwor...
''' Created on Aug 19, 2016 @author: wjadams ''' import numpy as np import plotly.graph_objs as go from plotly.offline import download_plotlyjs, init_notebook_mode, iplot from math_calcs import largest_eigen, random_consistency from math import floor def add_place(np_array): if np_array.shape == (0, 0): ...
import numpy as np from psana.detector.detector_impl import DetectorImpl from amitypes import Array1d, Array2d, Array3d class hsd_raw_0_0_0(DetectorImpl): def __init__(self, *args): super(hsd_raw_0_0_0, self).__init__(*args) def calib(self, evt) -> Array1d: return np.zeros((5)) class hsd_fex_4...
import torch import torch.nn.functional as F def cholesky(M, eps=1e-4): ''' Compute L, where M = LL^T. ''' I = torch.eye(M.size(-1), device=M.device) L = torch.cholesky(M + eps * I , upper=False) return L def rev_cholesky(L): ''' Compute M = LL^T. ''' M = torch.einsum('...ij,...kj->...ik', L, L)...
from datetime import date from os.path import isdir, exists from typing import Tuple, List, Optional from mkck.config import EVENTS_WITHOUT_PHOTOS_PER_YEAR, DIR_PHOTOS, FILE_PHOTOS, FILE_STORY, DIR_DOCS_BASE, \ DIR_DOCS_SPECIAL_BASE, INVALID_STORY_EVENTS_PER_YEAR from mkck.errors import EventError from mkck.galle...
#!/usr/bin/env python3 import collections import math import itertools # Constants PENNY_VALUE = 0.01 NICKEL_VALUE = 0.05 DIME_VALUE = 0.10 QUARTER_VALUE = 0.25 AMOUNT_VALUES = [PENNY_VALUE, NICKEL_VALUE, DIME_VALUE, QUARTER_VALUE] # The order of coin types that maps to the sequence of values COIN_TYPES = ['pennie...
#!/usr/bin/env python3 # ---------------------------------------------------------------------------- # Copyright (c) 2020--, <NAME>. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. # ---------------------------------------------...
import collections import io import typing from urllib.parse import urlparse Method = typing.NewType('Method', str) Scheme = typing.NewType('Scheme', str) Host = typing.NewType('Host', str) Port = typing.NewType('Port', int) Path = typing.NewType('Path', str) QueryString = typing.NewType('QueryString', str) QueryParam...
""" Handles player roles and factions. Hopefully more extensible than the last system and a whole load more magical. An instance of Player is created for each role in the game, initialised by a subclass of Role and then updated to add passive roles (additional roles such as with the passive cupid mode) and additional i...
""" Benchmark key generation, encryption and decryption. """ import random import resource import time import sys sys.path.append("..") import phe.paillier as paillier def bench_encrypt(pubkey, nums): for num in nums: pubkey.encrypt(num) def bench_decrypt(prikey, nums): for num in nums: pr...
import copy, time # A change in a solution in the form: move taskId from curCPUId to newCPUId. # This class is used to carry sets of modifications. # A new solution can be created based on an existing solution and a list of # changes can be created using the createNeighborSolution(solution, changes) function. class Ch...
import threading import time import sublime import sublime_plugin from .existing_packages_command import ExistingPackagesCommand from .advanced_uninstall_package_command import AdvancedUninstallPackageThread from .. import text from ..show_quick_panel import show_quick_panel from ..thread_progress import ThreadProgr...
from django.shortcuts import render, redirect import calendar from calendar import HTMLCalendar from datetime import datetime from django.http import HttpResponseRedirect from .models import Event, Venue from .forms import VenueForm, EventForm from django.http import HttpResponse import csv # Import PDF Stuff from dja...
import typing as ty import warnings import numba as nb import numpy as np from numba.core.errors import NumbaWarning from .. import utility from ..paths import Box, Path, Paths from ..shape import Shape warnings.simplefilter("ignore", category=NumbaWarning) class Sphere(Shape): def __init__(self, center=None,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import argparse import sys from logging import getLogger logging = getLogger(__name__) PLATFORM = 'eth-evm' def error_print(msg): print('[X] %s for %s' % (msg, PLATFORM)) sys.exit() def main() -> None: parser = argparse.ArgumentParser( descripti...
import math import time import os import numpy as np from keras.engine.training import GeneratorEnqueuer from tools.save_images import save_img3 from keras import backend as K def channel_idx(): if K.image_dim_ordering() == "th": return 1 else: return 3 class Model: """ Interface for normal (one net) models ...
import argparse import rospy import numpy as np import copy from gps.agent.utils.gazebo_spawner import GazeboModels from gps.agent.utils.model import Model from gps.agent.utils.basic_models import SPHERE, PEG_BOARD rospy.init_node('gazebo_spawner_ur3e') def place_target(): sphere = SPHERE % ("target", "0.025", "...
import discord import textwrap import time from discord.ext import commands from utils import permissions from utils import randomness import aiohttp import asyncio import subprocess import rethinkdb as r class Admin: def __init__(self, bot): self.bot = bot self.conn = bot.conn self._eval =...
# 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 # distributed under th...
import asyncio import pytest from asynctest.mock import MagicMock, patch from kutana import Kutana, Plugin from kutana.storage import OptimisticLockException from kutana.storages import MemoryStorage from kutana.backends import Debug from testing_tools import make_kutana def test_happy_path(): app = Kutana() ...
############################################################################## # # Copyright (c) 2001, 2002, 2009 Zope Foundation and Contributors. # All Rights Reserved. # # 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...
import glob import random import re import string import sys import uuid from typing import Callable, Dict def html_classes_obfuscator(htmlfiles = (), cssfiles = (), jsfiles = (), class_generator : Callable[[Dict], str] = lambda current_classes_list : "_" + str(uuid.uuid4())): # Dict<HTMLClasses, ObfuscatedHTMLC...
import os import tensorflow as tf import las import utils __all__ = [ 'las_model_fn', ] def compute_loss(logits, targets, final_sequence_length, target_sequence_length, mode): assert mode != tf.estimator.ModeKeys.PREDICT if mode == tf.estimator.ModeKeys.TRAIN: target_weights = tf.sequence_mask...
from __future__ import print_function import argparse import torch import numpy as np #np.random.seed(0) from sacred import Experiment from sacred.observers import MongoObserver from sacred.utils import apply_backspaces_and_linefeeds from sacred.stflow import LogFileWriter from collections import namedtuple import p...
""" factor.util -- utility module for factorization. """ import nzmath.arith1 as arith1 import nzmath.gcd as gcd import nzmath.prime as prime Unknown = None class FactoringMethod (object): """ Base class of factoring methods. """ def __init__(self): # verbosity self._verbose = False ...
import torch from torch import nn, optim from torchtext import data, datasets import numpy as np import random from datetime import datetime from progress.bar import Bar # set random seeds for reproducibility torch.manual_seed(12) torch.cuda.manual_seed(12) np.random.seed(12) random.seed(12) USE_GPU=0 # check if cud...
import numpy as np import scipy as scipy from numpy.random import uniform import scipy.stats import cv2 np.set_printoptions(threshold=3) np.set_printoptions(suppress=True) # The code is copied from http://ros-developer.com/2019/04/10/parcticle-filter-explained-with-python-code-from-scratch/. def drawLines(img, poin...
import _init_paths from net import Network from config import cfg, update_config from dataset import * import numpy as np import torch import os import pickle from torch.utils.data import DataLoader from tqdm import tqdm import argparse from core.evaluate import FusionMatrix def parse_args(): parser = argparse.Ar...
""" Provides various classes to aide with Layout of an app. """ from typing import Iterable from typing import Optional from typing import Tuple from typing import Union from . import node from ..tools.common import Origin __author__ = '<NAME>' __license__ = 'MIT' __version__ = '0.1' __copyright__ = """Copyright (c) ...
import os from datetime import datetime import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import util.io as mio from util import statsUtil from model.message import Message SAVE_PLOT = False def plotBasicLengthStatsByYearAndMonth(data, yearsToShow=None, targetStats=None, ...
# Published Jan 2013 # Revised Jan 2014 (to add new modules data) # Revised Nov 2017 (to add support for Vaillant vSmart authentication) # Forked from jabesq repo, added philippelt changes for file credentials # Author : <NAME>, <EMAIL> # Public domain source code """ This API provides access to the Netatmo weather sta...