text
stringlengths
3.07k
12.6k
from typing import Optional, Sequence from waitlist.storage.database import Waitlist, Character, Shipfit, WaitlistGroup, SolarSystem, Constellation, Station,\ Account Optionalcharids = Optional[Sequence[int]] def make_json_wl_entry(entry, exclude_fits: bool = False, include_fits_from: Optionalcharids = None, ...
"""Placeholder for the controller class""" import logging from typing import List from ..exceptions import UnexpectedError from . import types as mt from .arec import ActivationRecord from .future import Future from .probe import Probe from .state import State from .thread_failure import StackTraceItem, ThreadFailure...
#!/usr/bin/env python3 # Software License Agreement (MIT License) # # Copyright (c) 2017, DUKELEC, Inc. # All rights reserved. # # Author: <NAME> <<EMAIL>> # import struct as _struct from .cdnet_def import * def _get_port_size(val): if val == 0x00: return (0, 1) if val == 0x01: return (0, 2) if val == 0x...
BEAN = 10 DANGER = -100 WEAK_DANGER = -90 TAIL = 100 ENOUGH_LEN = 23 class Action: top = [1, 0, 0, 0] bottom = [0, 1, 0, 0] left = [0, 0, 1, 0] right = [0, 0, 0, 1] actlist = [(-1, 0), (1, 0), (0, -1), (0, 1)] mapAct = { actlist[0]: top, actlist[1]: bottom, actlist[2]: l...
from OpenSSL import SSL from OpenSSL.crypto import get_elliptic_curve from twisted.application import internet, service from twisted.internet import reactor from twisted.internet import ssl from twisted.logger import Logger from twisted.python.threadpool import ThreadPool from twisted.web import server from hendrix.fa...
import pytest import numpy as np from ..esn import ESN from ..utils import compute_spectral_radius, chunk_data, to_forecast_form def test_initialize_hidden_layer(): # Check that error is raised when distribution is not uniform or normal with pytest.raises(ValueError): esn = ESN(input_dim=1, hidden_dim...
''' allocator.py Outlines a Bitmap Allocator, with emphasis on efficiency. Heavily influenced by: (1) https://github.com/ngiambla/libmem/blob/master/allocators/libbitmem.c (2) https://tspace.library.utoronto.ca/bitstream/1807/101133/3/Giamblanco_Nicholas_Vincent_202006_MAS_thesis.pdf Author: <NAME> Date: June 16, 20...
from pymol import cmd, stored import pymol import numpy as np import os import urllib import pandas as pd from Bio import pairwise2 """ needs the libraries listed above accessible in PyMOL In PyMOL: PyMOL> run path/to/visualize_sensitivity.py PyMOL> color_sensitivity(file, # sensitivity value file, name...
#!/bin/env python # Copyright 2018 Google Inc. 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 appl...
from sqlalchemy.engine import Connection, Engine from sqlalchemy.event import contains, listen, remove from sqlalchemy.orm import Session g_tracer = None g_trace_all_queries = False g_trace_all_engines = False def init_tracing(tracer, trace_all_engines=True, trace_all_queries=True): ''' Set our global tracer....
import pprint pp = pprint.PrettyPrinter(indent=1) class Entity: def __init__(self, cli_object): self.cli_object = cli_object self.name = cli_object["metadata"]["name"] self.kind = cli_object["kind"] self.namespace = "" self.match_labels = {} # only for Deployment and Serv...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging from placethings.config.wrapper.config_gen import Config from placethings.config.wrapper.task_gen import TaskFlavor from placethings.demo.base_test import...
""" Make stamps using t80share machine. """ from __future__ import print_function, division import os import warnings from getpass import getpass import numpy as np import astropy.units as u from astropy.table import Table from astropy.io import fits from astropy.coordinates import SkyCoord from astropy.wcs import WC...
import serial import json import numpy as np class Potentiostat(serial.Serial): MAX_ABS_VOLTAGE = 1.65 ALLOWED_CURRENT_RANGE = ('1uA', '10uA', '100uA', '1000uA') ALLOWED_TEST_NAMES = ['cyclic'] def __init__(self, port): port_param = {'port': port, 'baudrate': 115200, 'timeout': 0.1} ...
import logging as _logging # noqa idiom if True: logger = _logging.getLogger(__name__) logger.addHandler(_logging.NullHandler()) from pathlib import Path from typing import Any, List, MutableMapping, Tuple, cast import toml from pkg_resources import to_filename from .domain import _load_proj_to_modules fro...
import mlconfig import torch import torch.nn as nn import torch.nn.functional as F class ConvBlock(nn.Sequential): def __init__(self, in_channels, out_channels, kernel_size=1, stride=1, nonlinearity='linear'): assert (kernel_size % 2 == 1) padding = int((kernel_size - 1) / 2) if nonlinea...
import nbt import os import json import sys import argparse import shutil def clean_mkdirs(path): if os.path.exists(path): shutil.rmtree(path) os.makedirs(path) def write_lang_file(lang,filepath,output_format): with open(filepath,'w') as f: if output_format=="lang": for key in l...
import os import apteco_api as aa import numpy as np import pandas as pd from apteco.query import SelectorClause def get_selector_variable_codes(session, var_name): """ Return list of codes possible for a selector variable. """ api_client = session.api_client fss_api = aa.FastStatsSystemsApi(api_client) ...
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # 不显示等级2以下的提示信息 import tensorflow as tf import numpy as np from tensorflow.keras.layers import Conv2D, MaxPool2D, Dense, BatchNormalization, Activation, GlobalAveragePooling2D from tensorflow.keras import Model from matplotlib import pyplot as plt # 设置输出样式 np.set_pri...
import numpy as np from math import * class FC: def __init__(self, W, b, lr, regu_rate, optimizer='SGD'): self.W = W.copy() self.b = b.copy() self.lr = lr self.regu_rate = regu_rate if optimizer == 'SGD': self.optimizer = SGD() elif optimizer == 'Momentum...
""" The ``base_optimizer`` module houses the parent classes ``BaseOptimizer`` and ``BaseScipyOptimizer``, from which all optimisers will inherit. The later is for optimisers that use the scipy solver. Additionally, we define a general utility function ``portfolio_performance`` to evaluate return and risk for a given s...
from jnius import autoclass from konduit.base_inference import * try: SchemaTypeUtils = autoclass("ai.konduit.serving.util.SchemaTypeUtils") except Exception as e: raise Exception( "We couldn't initialize the Java classes used by Konduit. " "Make sure to have a konduit.jar available on your PAT...
import argparse from datetime import datetime from pathlib import Path from time import sleep import DataLoad as DL from AdversarialTrainer import AdversarialTrainer LOADERS = {"cifar10": DL.get_loaders_cifar10, "cifar100": DL.get_loaders_cifar100} MODELS = { "cifar10": "cifar10_resnet18_baseline_nat_acc_94.pt",...
from rest_framework import serializers from django.utils import timesince from .models import ( Machine, BaseScript, Test, Scenario, MasterScenario, DryRunData, WAITING ) class BaseScriptModelSerializer(serializers.ModelSerializer): timestamp_start = serializers.DateTimeField(format="%...
from __future__ import absolute_import import sys import os import random from qmla.exploration_strategies.exploration_strategy import ExplorationStrategy import qmla.shared_functionality.experiment_design_heuristics from qmla.construct_models import alph, get_num_qubits __all__ = [ 'FullAccessNVCentre' ] class ...
from __future__ import annotations import os import random from collections.abc import Callable from typing import Union import torch import torchvision.transforms as T import torchvision.transforms.functional as TF import numpy as np from torch.utils.data import Dataset, DataLoader from PIL import Image as pilImage...
# coding: utf-8 from fastcache import clru_cache from empyrical.stats import cum_returns_final from FactorLib.data_source.trade_calendar import to_offset as _to_offset, tc, bday_chn_ashare import pandas as pd import numpy as np def _convert_to_nav(ret, ret_freq=None): """ 从收益率转成净值数据 :param re...
import frappe, calendar from frappe import _ from datetime import date, timedelta def get_residential_columns(year): columns = [ {"fieldname": "apartment_no", "label": _("Apartment No."), "fieldtype": "Data", "width": 150}, {"fieldname": "client", "label": _("Client"), "fieldtype": "Data", "width": ...
from sqlalchemy import * from sqlalchemy.sql import * from classGen import * import tkinter as Tk import tkinter.constants as cnsts import tkinter.ttk as ttk import tkinter.filedialog as tkFileDialog import tkinter.messagebox as MB import json import pickle import sys import time champs = {} bd_con_inf...
''' Copyright 2016 <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, software distributed...
# -*- coding: utf-8 -*- # Copyright 2016 Resonai Ltd. 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...
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt """ Data loading utiliy functions """ import scipy.io as sio import numpy as np import itertools from sklearn import datasets from dkmeans.util import split_chunks, local_maxima DEFAULT_DATASET = "real_fmri_exemplar" DEFAULT_THETA = [[0, 1]] DEFAULT_WINDOW = 22...
import os class FileTypes: byml = { 'signature': b'BY\x00\x02', 'name': 'byml', } prod = { 'signature': b'PrOD', 'name': 'prod' } aamp = { 'signature': b'AAMP', 'name': 'aamp' } bfev = { 'signature': b'BFEV', 'name': 'bfev' ...
import numpy as np import nibabel as nib import scipy.ndimage import warnings import PP import sys #--------------------------------------------- #Functions for image augmentations on 3D input #--------------------------------------------- #img_b, label_b is (batch_num) x 1 x dim1 x dim2 x dim3 #takes in a list of 3D...
# # wiki test module - create, edit, delete version, delete page with all versions # """ MIT License Copyright (c) 2017, 2018 <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 res...
from __future__ import absolute_import from __future__ import print_function import six import csv import unicodecsv import re import sys from six import BytesIO from zipfile import ZipFile from six.moves.urllib import request from six.moves.urllib.error import URLError from ..get_database_connection import get_databas...
try: import io except ImportError: # probably linux import StringIO io = StringIO import tokenize import re import sublime, sublime_plugin def find(collection, f): for i in collection: if f(i): return i return None def search_points_to_replace(command): points_to_replace = set() for region i...
import base64 import json import logging from collections import defaultdict from typing import TYPE_CHECKING, Any, Callable, Dict, List from django.core.cache import cache from django.db.models import QuerySet from graphql import GraphQLError from prices import Money from ...graphql.core.utils import from_global_id_...
import csv import os import pickle import numpy as np import torch from torch.autograd import Variable from tqdm import tqdm import torch.nn.functional as F from datasets_natasha.masks_dataset import resize_image, flip_h_w, flip from utils.crf import dense_crf from utils.util import rle_encode, RLenc def outputs_fo...
# -*- encoding: utf-8 -*- import random import time from typing import List, Union, Tuple import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from loguru import logger from sklearn import metrics from torch.utils.data import DataLoader, Dataset from tqdm import tqdm from transformers...
from unittest import TestCase from MetaModels import MetaModelConstructor as MMC import numpy as np class test_constructors(TestCase): """ A test case for all constructors of the MetaModelConstructor file """ __database_1 = np.mat([[1.3, 4.2, 5.6, 3.5], [2.5, 4.1, 6.4, 0.3], [3.5, 2.3, 1.4...
from flask import Flask from flask_login import current_user import math from sql.store import get_store_item_list, get_store_item, confirm_order from tool.typing import * from tool.page import get_page from tool.login import create_uid from core.garbage import GarbageType from sql import DBBit from sql.db import D...
from awacs import aws, sts from awacs.aws import Allow, Principal, Statement from troposphere import Base64, GetAtt, Join, Output, Parameter, Ref, Split, Template from troposphere.autoscaling import AutoScalingGroup, LaunchConfiguration, Tag from troposphere.ec2 import BlockDeviceMapping, EBSBlockDevice from tropospher...
#!/usr/bin/env python3 import logging import operator from pathlib import Path from hashlib import md5 from argparse import ArgumentParser from translator import elffile import sys def md5sum(filename): with open(filename, 'rb') as fh: hsh = md5() for blck in iter(lambda: fh.read(4096), b""): hsh.upda...
# Software License Agreement (BSD License) # # Copyright (c) 2008, <NAME>, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyri...
import math import os from ctypes import * import struct from contextlib import closing import quick2wire.syscall as syscall # From <time.h> time_t = c_long clockid_t = c_ulong class timespec(Structure): _fields_ = [("sec", time_t), ("nsec", c_long)] __slots__ = [name for name,type i...
from operator import attrgetter from airdrop.config import SEPT_15, ZERO_ADDR, USDC_ADDR, USDT_ADDR, DAI_ADDR from airdrop.structs import LPTransfer, TokenTransfer, Operation, Price def _get_1inch_users(trades): user_trades = dict() for t in trades: if t.tx_from not in user_trades: user_...
""" Unit-distance embeddings of snarks (3-connected cubic graphs with chromatic index 4), including the Tietze graph. """ from mpmath import * from shibuya.generators import cu, star_radius, ring_edges, all_unit_distances from shibuya.generators import fixparams_unitdist, symmetrise def tietze(): """Return a unit-...
#!/usr/bin/env python # coding: utf-8 # In[1]: from IPython.conftest import get_ipython from keras.applications.vgg16 import VGG16 model = VGG16() # In[2]: from keras.applications.vgg16 import VGG16 model = VGG16() print(model.summary()) # In[8]: from keras.applications.vgg16 import VGG16 # load the model mode...
import heapq import json import math import os import re import pandas from IPython.display import display import vocabularize as voc # pre-process the query to get it the same kind of entity as the synopsis def clean_query(porter, query): pp_query = voc.info_pre_processing_f(query) query = voc...
from __future__ import absolute_import, unicode_literals import sys from case import Mock, mock, patch from celery.concurrency.base import BasePool from celery.five import monotonic from celery.utils.objects import Bunch from celery.worker import autoscale, state class MockPool(BasePool): shrink_raises_except...
"""connection.py: Connection for connecting to serial or sf ports.""" import logging import threading import time from codecs import encode from six.moves import queue from moteconnection.connection_events import ConnectionEvents from moteconnection.connection_forwarder import SfConnection from moteconnection.connec...
"""Split a bank (basically a feature file) to its feature definition and its scenarios.""" import re from .errors import ParsingError REGEX_FEATURE_START = re.compile(r"^\s*Feature:") REGEX_TAGS = re.compile(r"^\s*(?:@\w+(?:\s+@\w+)*)") REGEX_SCENARIO_START = re.compile(r"^\s*Scenario(?: Outline)?:") REGEX_MULTILINE_...
#! -*- coding:utf-8 -*- from keras.layers import * from keras.models import Model import keras.backend as K from keras.callbacks import Callback from keras.optimizers import Adam from keras.regularizers import l2 from keras_bert import load_trained_model_from_checkpoint from utils import seq_gather, extract_ite...
#!/usr/bin/env python # Copyright 2011-2017 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
import configparser import logging import logging.config import requests import re import os import db_manage as db import sys import yaml # absolute imports from bs4 import BeautifulSoup from requests import get from urllib.parse import urljoin def request_get(url): """ Request and get the url :param url...
import copy import numpy as np from liegroups.numpy import SE3 def test_identity(): T = SE3.identity() assert isinstance(T, SE3) def test_dot(): T = np.array([[0, 0, -1, 0.1], [0, 1, 0, 0.5], [1, 0, 0, -0.5], [0, 0, 0, 1]]) T2 = T.dot(T) as...
import datetime import json import logging import os import time # https://github.com/jschneier/django-storages/issues/281#issuecomment-288377616 import tempfile tempfile.SpooledTemporaryFile = tempfile.TemporaryFile from flask import Flask, abort, jsonify, request, Response from flask_api import status from google....
import os import sys import pickle import numpy as np import pandas as pd from sklearn import mixture from sklearn.metrics import roc_auc_score def get_machine_ids(machines, mode): mid_dict = {} if mode == 'd': path = '../../saved_iVectors/ivector_mfcc_100' folder = 'test' for m in machines: file_list = os...
import time import numpy as np from optimisation.utils import get_items_opt_cost, get_market_coordinates, get_items_expiring_soon, \ get_geodesic_distance def crossover(parent_a, parent_b): parent_a = parent_a.copy() parent_b = parent_b.copy() cross_index = np.random.randint(0, len(parent_a)) of...
import os import json from sqlalchemy import Column, Integer, String, Enum, ForeignKey from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, backref from utils.exceptions import ImproperlyConfigured Base = declarative_base() class Provider(Base): __tablename__ = "cra...
#!/usr/bin/env python # coding: utf-8 # Author: <<EMAIL>> # License: MIT License """ This module includes utility imports and functions for the project "Machine Learning applied to Shipbuilding Market Analysis". """ #Global imports import os import sys import time import json import warnings from copy...
import requests import json import pymongo import time client = pymongo.MongoClient('localhost', 27017) def saveDocToMongo(doc): """" 保存数据至 MongoDB """ db = client.spider db.ip.insert_one(doc) def saveErrorToMongo(doc): """" 保存 Error 至 MongoDB """ db = client.spider db.err.i...
"""The 'View' Module of the application: The Keys window. This file contains the implementation for the key area: +------+--------------+ | Key | Details | | Area | Area | | | | +------+--------------+ The key area displays the keys filtered-in by the user. License: ...
import asyncio import imghdr import re import textwrap from io import BytesIO from math import sqrt from os import environ from time import perf_counter from typing import Literal, Optional import discord import httpx from discord.ext import commands from PIL import Image, ImageDraw, ImageFont from .. import PATH fro...
"""Simple implementation of the RSA cryptosystem. This module is meant to show a simple and clear implementation of the RSA algorithm: http://en.wikipedia.org/wiki/RSA_(cryptosystem). It is meant to be readable, not fast. The usage is simple. First, create a random key pair: >>> public_key, private_key = make_ke...
from django.http import HttpResponse from django.shortcuts import render from django.template import loader from administrator.models import Student, Class from django.db import connection import datetime def index(request, course_id, date): super = request.user.is_superuser with connection.cursor() as cursor...
""" Song pool analysis module """ import os from gig.song import Song from gig.song_pool import SongPool class NumericSongStatistic: """ Numeric song statistic, containing average, min, max, etc values """ def __init__(self): self.max_song = None self.max_value = -999999 self.min_song ...
# -*- coding: utf-8 -*- from util import * import argparse import xgboost as xgb try: from lightgbm import LGBMClassifier except: print('import lgb fail') from catboost import CatBoostClassifier pd.set_option('display.max_rows', 1000) import gc # f1 = load_feature('inv_feature_1.dump') ###################...
import math from typing import Dict import torch import torch.nn as nn class SignLanguageTransformer(nn.Module): """ Sign Language Transformer https://www.cihancamgoz.com/pub/camgoz2020cvpr.pdf """ __max_len = 10000 def __init__( self, feature_extractor_parameters: Dict = No...
""" classify.py """ import re import pickle import configparser from collections import Counter, defaultdict from itertools import chain, combinations import glob import numpy as np import os from scipy.sparse import csr_matrix from sklearn.cross_validation import KFold from sklearn.linear_model import LogisticRegress...
# 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 t...
"""This module contains functions for doing complex Gaussian math. Everything is hard coded for adiabatic/diabatic representation""" import math import cmath import numpy as np def overlap_nuc(positions_i, positions_j, momenta_i, momenta_j, widths_i, widths_j, numdims): """Compute the overlap of ...
import ast from typing import cast from typing import Iterable from typing import List from typing import Tuple from typing import Type from typing import Union from tokenize_rt import Offset from tokenize_rt import Token from pyupgrade._ast_helpers import ast_to_offset from pyupgrade._ast_helpers import is_name_attr...
"""PyCX 0.31 Complex Systems Simulation Sample Code Repository 2008-2013 (c) Copyright by <NAME> 2012 (c) Copyright by <NAME> & <NAME> ("pycxsimulator-old.py", "realtime-simulation-template-old.py") 2013 (c) Copyright by <NAME> & <NAME> Extensions to GUI module, some revisions All rights reserved. ...
"""Helpers for config validation using voluptuous.""" from datetime import timedelta import jinja2 import voluptuous as vol from homeassistant.loader import get_platform from homeassistant.const import ( CONF_PLATFORM, CONF_SCAN_INTERVAL, TEMP_CELCIUS, TEMP_FAHRENHEIT) from homeassistant.helpers.entity import val...
import os, json, random import numpy as np import matplotlib.pyplot as plt import torch import torchvision import torchvision.datasets as dset import detectron2 import detectron2.data.transforms as T from detectron2.data.datasets import register_coco_instances from detectron2 import model_zoo from detectron2.engine i...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import base64 import hashlib import logging import os import shutil import subprocess from tempfile import mkdtemp from distutils import version from distutils.spawn import find_executable from flask import Flask, send_file, abort f...
from __future__ import annotations import matplotlib.pyplot as plt from typing import Tuple, Optional import numpy as np from mathplotlib.base import BaseElement, Curve2D from mathplotlib.style import Style class Line(Curve2D): def __init__( self, slope: float = 1, intercept: float = 0, ...
import re import os import datetime import pandas as pd import numpy as np from glob import glob import warnings import news._news_yh as news_yh import visualization._plot_method as senti_ploter import processor._automail as automail import processor._senti_process as senti_process import statistics._twitter_stats as ...
# This file is part of GridCal. # # GridCal is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # GridCal is distributed in the hope that...
import os import configparser import logging from enum import IntEnum, auto # Configuration of the product INI_FILENAME = 'philler.ini' DEFAULT_PRODUCT = 'PRODUCT1' class CFG(IntEnum): """ The master list of what can be configured with an INI file. """ #SPECIFIC_GRAVITY = auto() #FILL_VOLUM...
from django.test import TestCase, Client from api.models import Tournament from api.models import Round from api.models import Team from api.models import Club import datetime from api import views from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase, APIRequest...
from .__core__ import PyotCore, PyotStatic from pyot.utils import champion_id_by_key, champion_id_by_name from pyot.utils.cdragon import cdragon_url, start_k, cdragon_sanitize from typing import Any, List # PYOT STATIC OBJECTS class ChampionTacticalData(PyotStatic): style: int difficulty: int damage_type...
import cv2 import numpy as np from scipy import spatial import itertools from scipy.spatial.distance import pdist, cdist, squareform from sklearn.cluster import dbscan def unique_transforms(transforms): ids = set(np.arange(len(transforms))) indices = [] while len(ids) > 0: i = ids.pop() ind...
#!/usr/bin/env pytest -vs """Tests for postfix container.""" # Standard Python Libraries from email.message import EmailMessage from imaplib import IMAP4_SSL import os import smtplib import time # Third-Party Libraries import pytest ARCHIVE_PW = "<PASSWORD>" ARCHIVE_USER = "mailarchive" DOMAIN = "example.com" IMAP_P...
""" This file contains "Models" that can be used for exercising the ParM deployment scripts locally. Each model simply returns lists of random floating point values. Models are thus computationally inexpensive and are unlikely to overload a single machine when multiple of them are run concurrently. NOTE: This script s...
#!/usr/bin/env python # # NopSCADlib Copyright <NAME> 2018 # <EMAIL> # hydraraptor.blogspot.com # # This file is part of NopSCADlib. # # NopSCADlib is free software: you can redistribute it and/or modify it under the terms of the # GNU General Public License as published by the Free Software Foundation, either version...
import pdb import math import warnings import random import pandas as pd import numpy as np import torch import matplotlib.pyplot as plt from .sampler import Sampler def timeRescaling(Y, pk): n = int(torch.sum(Y).item()) rISIs = torch.zeros(n-1, dtype=torch.double) spikeindicies = Y.nonzero() for r in...
import os _FILE_PATH = os.path.dirname(__file__) _HEADER_T_FN = os.path.join(_FILE_PATH,'model',"awral_t.h") _SOURCE_T_FN = os.path.join(_FILE_PATH,'model',"awral_t.c") _HEADER_FN = os.path.join(_FILE_PATH,'model',"awral.h") _SOURCE_FN = os.path.join(_FILE_PATH,'model',"awral.c") _LIB_FN = os.path.join(_FILE_...
import os.path import numpy as np import itertools import Tools from scipy import signal #from pylab import figure, clf, plot, xlabel, ylabel, xlim, ylim, title, grid, axes, show,semilogx, semilogy import math # Those patterns are used for tests and benchmarks. # For tests, there is the need to add tests for saturatio...
# IMPORT PACKAGES import pandas as pd import nltk from nltk.util import ngrams import sklearn from sklearn.model_selection import train_test_split import ast import dask.dataframe as dd from dask.multiprocessing import get import spacy import gensim from gensim import corpora, models from gensim.utils impor...
#!/usr/bin/env python import os,sys thispath = os.path.dirname(os.path.abspath(__file__)) import subprocess import hashlib from datetime import datetime #------------------------------------------------------------------------ # Hash and zip all script/config files in a directory (including subfolders) # # Optional: s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This...
# Copyright 2019 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Copyright 2021 <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, ...
import json import logging import time from typing import Dict from typing import Optional from typing import Sequence from urllib.parse import ParseResult from urllib.parse import quote from urllib.parse import urljoin from urllib.parse import urlparse from django.conf import settings from django.templatetags.static ...
# Copyright (c) 2019 Intel Corporation # # 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...
""" Contains small helper classes used as abstraction for various templating macros. """ from random import choice from lxml.html import builder, tostring from onegov.core.elements import Element from onegov.org import _ from purl import URL class AccessMixin(object): @property def access(self): "...
# -*- coding: utf-8 -*- """ Created on Fri Nov 24 23:24:10 2017 @author: HCHO """ import re import string import operator import math import syllables_en import sqlite3 conn=sqlite3.connect('fictData.db') cur=conn.cursor() def getAllWords(): allwordsDict={} sql_select="SELECT id,TFIDF FROM fiction;" dat...