text stringlengths 3.07k 22.1k |
|---|
"""
FILES IN PACKAGE:
snn-stdp.py
get-networks-accuracy.py
read-pkl-spikes.py
iris-train.txt
iris-test.txt
README.md
Files generated after training:
results/input.pkl
results/output.pkl
Files generated after testing:
results/inputTest.pkl
results/outputTest.pkl
Author: <NAME>
Supervisor: Professor Dr. <NAME> (https:... |
# -*- coding: utf-8 -*-
"""
Largely adapted from Keras documentation generation.
TODO: some serious re-engineering of this script
General documentation architecture:
Home
"""
from __future__ import print_function
from __future__ import unicode_literals
import re
import inspect
import os
import shutil
from spiker.... |
import json,random,csv
import numpy as np
from scipy import sparse
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
#code for helper file
#create networkx graph object from node and edge list csv files
def G_from_edge_list(node_filename,edge_filename):
G = nx.DiGraph()
dat... |
import random
import re
import sys
import vkrine
import vkrine.exceptions as exceptions
import vkrine.utils as utils
class Command(object):
def __init__(self, module, name, bot_type=vkrine.ARCHITECTURE_ANY):
self.MODULE = module
self.NAME = name
self.TYPE = bot_type
def get_aliases_k... |
from .db import get_connection, get_data_dict
from flask import render_template, url_for, make_response
import requests
import traceback
import math
import logging
logger = logging.getLogger()
def do_packaging():
context = {'packaging_page': True}
conn = get_connection()
cur = conn.cursor()
query = """... |
#!/usr/bin/env python
from urlparse import urlsplit
import urllib
import os
import runconfig
try:
# for python 2.6
from urlparse import parse_qsl
except:
# for python < 2.6
from cgi import parse_qsl
def looks_like_dir(url):
scheme, host, path, query, fragment = urlsplit(url)
if query != ... |
"""
Script to train the network
"""
import os
import random
import time
import kitti_data
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
VERBOSE = True
DATA_CONST = kitti_data.LabeledImageData
class Profiler:
"""
Simple profiler
"""
def __init__(self, name):
sel... |
#https://www.python-course.eu/neural_networks_with_python_numpy.php
"""
import numpy as np
input_vector = np.array([2,4,11])
input_vector = np.array(input_vector, ndmin=2).T #Makes it horizontal
print(input_vector, input_vector.shape)
"""
"""
sigmoid function = 1 / (1 + e ^ -x)
"""
import numpy as np
from scipy.stat... |
from flask import Blueprint, render_template, Response, request
from sqlalchemy import select, join, func, delete
from forms import *
import json
from datetime import datetime
from app import config
squeaky_puppy = Blueprint(
'squeaky_puppy',
__name__,
)
@squeaky_puppy.route('/')
def home():
the_form = M... |
from curses import meta
from gettext import translation
from importlib.metadata import metadata
from inspect import getmembers, isfunction
import functools
from nis import match
import os
import string
import json
import fitz
import fasttext
fasttext.FastText.eprint = lambda x: None
import enchant
from enchant.check... |
import numpy as np
import scipy.io.wavfile as wav
from audiolazy import lpc
import matplotlib.pyplot as plt
import librosa as lr
def initialize(inputWav):
rate, signal = wav.read(inputWav) # returns a wave_read object , rate: sampling frequency
#sig = wave.open(inputWav)
#print('The sample rate of the aud... |
#Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
#This program is free software; you can redistribute it and/or modify it under the terms of the BSD 3-Clause License.
#This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of ... |
from abc import abstractmethod
from functools import partial, wraps
import os
from typing import Any, Callable, Iterable, Dict, Tuple, Sequence, Union
import flax.linen as nn
from flax import optim, jax_utils
from flax.serialization import to_bytes, from_bytes
from flax.core.scope import Scope
import jax
from jax impo... |
from __future__ import annotations
import json
import re
import subprocess
from itertools import chain, groupby, permutations, product
from operator import itemgetter
from os.path import abspath, dirname, join
from shutil import which
from string import ascii_uppercase, digits
from monty.fractions import gcd
from pym... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 21:07:09 2019
@author: sempronius
"""
import os
import sys
import random
import math
import re
import time
import numpy as np
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Root ... |
import os
import sys
import psutil
import subprocess
import pandas as pd
from time import sleep
class Listener():
def __init__(self, save_every_minutes):
self.save_every_minutes = save_every_minutes
self.devices = []
self.saved = False
self.log_file_name = None
def ready_to_sa... |
from typing import Tuple, Dict, List, Callable, Union
import itertools
import numpy as np
Key = Tuple[int, ...]
Bucket = Tuple[List[int], List[int]]
DistFunc = Callable[[np.ndarray], np.ndarray]
DistFuncArg = Union[str, DistFunc]
OVERHEAD_MULT = 5
NORM, MAX = 'norm', 'max'
def _get_dist_func(dist_metric: DistFuncA... |
import asyncio
import inspect
from collections import abc
from functools import partial
from inspect import BoundArguments, Signature
from typing import Sequence, TYPE_CHECKING, Optional, Callable
from aiosaber import context
from aiosaber.channel import Channel, Consumer
from aiosaber.component import Component
from ... |
import re
import traceback
from numbers import Number
from pathlib import Path
import bw2data as bd
import bw2io as bi
import bw2parameters as bwp
import bw_processing as bp
import numpy as np
from asteval import Interpreter
from bw2data.backends.schema import ActivityDataset as AD
from bw2parameters.errors import Bro... |
import json
import logging
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import requests
from rotkehlchen.typing import AssetData, AssetType, ChecksumEthAddress, EthTokenInfo
log = logging.getLogger(__name__)
asset_type_mapping = {
'fiat': AssetType.FIAT,
'own chain': AssetTyp... |
import json
import os
import pathlib
from os import listdir
from os.path import isfile, join
from unittest.mock import MagicMock, create_autospec
import pytest
import tekore as tk
import yaml
from lyricsgenius import Genius, OAuth2
from telegram import Bot, CallbackQuery, Message, Update
from telegram.ext import Callb... |
from enum import Enum
import time
import copy
import sys
import subprocess
import random
from threading import Thread
def monitorFile(connection, queue):
while True:
try:
line = connection.readline()
except:
break
if not line:
queue.append(None)
break
line = line.rstrip("\n")
queue.append(line)... |
import copy
import datetime
import hashlib
import os
import random
import re
import sys
import time
from multiprocessing import Pool
from jinja2 import Template
from pymongo import MongoClient
from .logging import Log
from .parser import rssParser, rssFullParser, objParser
from .sender import default_sender, loadSend... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 12 16:57:30 2019
@author: bmoseley
"""
# This module defines a SeismicDataset class for easily loading the binary data
# stored in ../generate_data/ as tensorflow tensors (via TensorFlow Datasets) suitable for training and testing
# the WaveNet (a... |
import time
from tcoreapi_mq import *
import tcoreapi_mq
import threading
g_QuoteZMQ = None
g_QuoteSession = ""
BuyerParam = {
"Money":"2000000",
"HoldValue":"0",
"ShortAverage":"0",
"LongAverage":"0",
"Side":"0",
"TradeTimes":0
}
ShoAvg = [0,0,0,0,0]
LonAvg = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,... |
"""
Virtual environment (venv) package for Python. Based on PEP 405.
Copyright (C) 2011-2014 <NAME>.
Licensed to the PSF under a contributor agreement.
"""
import logging
import os
import shutil
import subprocess
import sys
import types
logger = logging.getLogger(__name__)
class EnvBuilder:
"""
This class ex... |
#!/usr/bin/env python
import numpy as np
import argparse
from gurobipy import *
import copy
import sys
import os
import matplotlib.pyplot as plt
# plt.switch_backend('agg')
import seaborn as sns
# sns.set_style("whitegrid")
import math
import scipy
import subprocess
from scipy.stats import *
from scipy.special import... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 15:12:16 2020
@author: medrclaa
Experiment modules for UKF experiment where observations come from within the view
of cone like cameras only
"""
import sys
import os
import numpy as np
from ukf_fx import fx
from sensors import camera_Sensor, g... |
import pygame
import main
import os
import random
import math
import engine
import pickle
class Star:
def __init__(self, position, size, speed=(-2, 0)):
self.speed = [0, 0]
self.speed[1] = speed[1]
self.speed[0] = speed[0]*size
self.x = position[0]
self.y = position[1]
... |
from __future__ import division
import os
import sys
import torch
import torch.nn as nn
import numpy as np
from shutil import copyfile
from pkg.networks import Text2Mel, SuperRes
from pkg.data import BatchMaker, load_data
from pkg.hyper import Hyper
from pkg.utils import PrettyBar, plot_spectrum, plot_attention, plot_... |
from typing import Union, List
import numpy as np
from enum import Enum
from pydantic.dataclasses import dataclass
from ..utils import fix_dataclass_init_docs
def phase_matrix(top: float, bottom: float = 0):
return np.array([
[np.exp(1j * top), 0],
[0, np.exp(1j * bottom)]
])
def coupling_m... |
from typing import Optional, Sequence, TextIO
from ..foundation.pf import pf, tikz_option
from ..node_graph import Edge, NodeText
from .draw import FUNCTION_GRAPH_WIDTH, MARK_HEIGHT, MARK_WIDTH
__all__ = ['Annotation', 'RectAnnotation', 'BraceAnnotation', 'CircleAnnotation', 'EdgeAnnotation']
BRACE_HEIGHT = 0.3
UNC... |
import umap
import trimap
import FlowCal
import json
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn import manifold, datasets
from time import time
from tqdm import tqdm
from sklearn.decomposition import PCA
from PaCMAP import PaCMAP
from sklearn.datasets import make_swiss_roll, ma... |
import numpy as np
import pandas as pd
import math, csv, json, sys, os, glob
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from abc import ABC, abstractmethod
def onlyNumber(dataIN):
"""
Perfom data check; reject all complex or non-numbers (bool... |
import numpy as np
import math
'''
Author: <NAME>
Email: <EMAIL>
Affiliation: School of water resources and hydropower engineering, Wuhan University
'''
# class of the point
class Point(object):
def __init__(self, name, coord):
self.name = name
self.coord = np.array(coord)... |
import datetime
import json
import AlteryxPythonSDK as Sdk
import xml.etree.ElementTree as Et
import requests
from obj_query import AyxDataMap, FieldType, Query
class ForecastKeyData:
def __init__(self):
self.CityId = None
self.CityName = None
self.Timestamp = None
self.Sunrise = ... |
import flask
from jobs_ranker.tasks import configs
from jobs_ranker.webapp import task_sessions
from jobs_ranker.utils.logger import logger, log_path
app = flask.Flask(__name__)
app.secret_key = b'secret'
tasks = task_sessions.TasksSessions()
@app.route('/')
def home():
flask.flash(f'redirected to tasks-list',... |
from shared_lib.utils.constants.general import SEQ_SEP
from shared_lib.metrics.google_rouge_comps.rouge_scorer import RougeScorer
from shared_lib.utils.helpers.analysis import aspect_density, annotate_seq_aspects
from shared_lib.utils.constants.features \
import (SRC_AD1, VERD_AD1, PC_AD1, SRC_VERD_LEN_DIFF, SRC_PC... |
import random
import matplotlib as matplotlib
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
A = 5 # x方向有A个货位
B = 4 # y方向有B个货架
C = 6 # z方向有C层
l = 10 # 货位的长
r = 1 # 货位的宽
h = 20 # 货位的高
vx = 1 # 叉车的x速度
vy = 0.5 # 叉车的y速度
vz = 2 # 叉车的z速度
N = 20 # 货物的数量
L = 20 # 质量上限
m = 400 # 种群数量
c... |
"""Tools for generating MTurk HITS."""
import collections
import csv
import pathlib
import random
from typing import Callable, Mapping, Optional, Sequence
from urllib import request
from src.milannotations import datasets
from src.utils import lang
from src.utils.typing import Layer, PathLike, StrSequence
import spel... |
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import scipy.spatial as scsp
#not used - this was for finding the closest point to the click
def do_kdtree(combined_x_y_arrays, points):
mytree = scsp.cKDTree(combined_x_y_arrays)
return mytree.query(points)
def coordinatesMat(tw... |
import chainer
import chainer.links as L
import chainer.functions as F
from chainer import cuda
def init_conv(array):
xp = cuda.get_array_module(array)
array[...] = xp.random.normal(loc=0.0, scale=0.02, size=array.shape)
def init_bn(array):
xp = cuda.get_array_module(array)
array[...] = xp.random.norm... |
import winsound
import numpy as np
import time
import sklearn
import os
import random
from sklearn.metrics import *
# Written by <NAME>, MD. Dec 2021.
### SOUND DING DONG ###
def dingdong():
duration = 500
winsound.Beep(262, duration)
winsound.Beep(330, duration)
winsound.Beep(392, durati... |
#!/usr/bin/env python
################################################################################
# Copyright 2019 IBM 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
#
# h... |
from enum import Enum
from supproperty import supproperty, decimal, positive_integer, positive_decimal, boolean
from bac.simulate.coding import Encodable
class CutoffSchemeType(Enum):
"""Neighbor search cutoff scheme
:param verlet: Generate a pair list with buffering. The buffer size is automatically set ba... |
#####################################################################
#
# Predictive Failure Analysis (PFA)
# Graph Common Storage ASIDs
#
#This python script is for use with data that is collected, created,
#and written by the PFA_COMMON_STORAGE_USAGE check only. Its
#use wit... |
import os
import time
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
savepath='/home/wangminjie/Desktop/wmj/projects/Part-IBN/features'
if not os.path.exists(savepath):
os.mkdir(savepath)
def draw_features(width,height,x,... |
from tkinter import *
from bs4 import BeautifulSoup
import sqlite3
import urllib.request
import re
#Descarga de una a varias páginas html y realiza scrap sobre ellas.
def scrap():
#Lista que contendra los objetos para la base de dato almacenados durante el scraping
lista = list()
#Iteración por cada págin... |
# 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,... |
import sys
from tsdemux.demux import TsParser
from tsdemux.es import Es
from tsdemux.pes import PesReader
class DvbSubtitlePage:
class Region:
def __init__(self, region_id, x, y):
self.id = region_id
self.x = x
self.y = y
self.fill = False
self... |
#!/usr/bin/env python3
import re
from icu import RuleBasedCollator
# global result, object with the following structure:
# - da_drag
# - ids
#
# da_drag is an object with the following structure:
# keys are syllables where da drag or sandhi appear
# values are:
# - expl (explicit)
# - expl_w_s... |
import torch
import torch.nn as nn
import numpy as np
from scipy.special import comb
from .blocks import get_func
def count_param(model):
param_count = 0
for param in model.parameters():
param_count += param.view(-1).size()[0]
return param_count
def flatten(input_list):
output... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
from zabbix.api import ZabbixAPI
import time
import random
import argparse
import configparser
##########
# 42 total items
##########
colors = {}
# dark colorssc
colors['dark_blue1'] = "5299AD"
colors['dark_violet'] = "5D549A"
colors['dark_green'] = "87B457"
col... |
import os
import attr
import uuid
import shutil
import traceback
import hashlib
import json
import pathlib
import datetime
import pyclamd
import virustotal3.core
from regipy.registry import RegistryHive
from regipy.plugins.utils import dump_hive_to_json
from glob import glob
from typing import Any, List, Tuple, Dict,... |
from data import *
from utils.augmentations import SSDAugmentation
from layers.modules import MultiBoxLoss
from ssd import build_ssd
from os.path import join
import os
import sys
import time
import torch
from pathlib import Path
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
impor... |
class Base(object):
def render(self):
return ""
def convert_column(col, table=None, quote_open="`", quote_close="`"):
"""Turns foo.id into foo.c.id. If a table is given, then id becomes
<table>.c.id"""
col = col.replace(quote_open, "").replace(quote_close, "")
if "." in col and table and n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Script de limpieza para los datos de audiencias
Utiliza el paquete `data-cleaner` para limpiar datos de audiencias aplicando
reglas de limpieza disponibles en el paquete, reglas extendidas sobre el objeto
MyDataCleaner y cualquier script de limpieza custom que deba apl... |
import gensim
from gensim.models import doc2vec
from gensim.models import word2vec
from gensim.models import fasttext
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import TruncatedSVD
import numpy as np
import jaconv
import pickle
import re
from mldatautils.logger import logger_... |
"""Cleanup unhosted and rogue pipe and duct insulation."""
from __future__ import print_function
import collections
import datetime
import itertools
import clr
clr.AddReference("RevitAPI")
clr.AddReference("RevitAPIUI")
import Autodesk.Revit.DB as db
import Autodesk.Revit.UI as ui
clr.AddReference("System.Windows.Form... |
"""
Record field data functions to support entity data testing
"""
from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function
__author__ = "<NAME> (<EMAIL>)"
__copyright__ = "Copyright 2014, <NAME>"
__license__ = "MIT (http://opensource.org/licenses/MIT)"
impo... |
import pyomo.environ as pyo
from coramin.utils.coramin_enums import FunctionShape, RelaxationSide
from .relaxations_base import BasePWRelaxationData, ComponentWeakRef
import warnings
from .univariate import PWXSquaredRelaxationData, pw_x_squared_relaxation
from .pw_mccormick import PWMcCormickRelaxationData, _build_pw_... |
import json
import re
import sys
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import yaml
from datastore.shared.util.key_types import (
collection_regex,
collectionfield_regex,
field_regex,
)
from openslides_backend.shared.patterns import (
COLOR_PATTERN,
DECIMAL_PATTERN,
K... |
import pytest
import os
import pyodbc
import pandas as pd
from tagreader.utils import ReaderType, ensure_datetime_with_tz
from tagreader.odbc_handlers import list_pi_sources
from tagreader.clients import IMSClient, list_sources
is_GITHUBACTION = "GITHUB_ACTION" in os.environ
if is_GITHUBACTION:
pytest.skip(
... |
import time,random
from datetime import datetime
import sqlite3
from apscheduler.schedulers.background import BackgroundScheduler
from src.stockmod import StockMod
from src.robotutils import oplogs
HR__VERSION = "Released on 2019.12.3"
syscmd = ['/cfg','/help', '/show','/add','/delete','/test','/restart... |
import fnmatch
from hither2.runtimehook import PreContainerContext
from .function import FunctionWrapper
from .dockerimage import DockerImage
import importlib
import os
import shutil
import json
from copy import deepcopy
from typing import Dict, List, Union
import kachery_client as kc
from ._safe_pickle import _safe_pi... |
import os
import argparse
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import torch
def single_plot_trajectories(ax, x, y, y_pred):
"""
x shape: T_gt x N x D
y shape: T_pr x N x D
y_pred shape: T_pr x N x D
"""
colors = ['firebrick', 'forestgreen', 'dodgerblue',... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
import time
import argparse
import cv2 as cv
import numpy as np
import tkinter as tk
import tkinter.simpledialog as simpledialog
def model_load():
from midas_predictor.midas_predictor import MiDaSPredictor
model_path = 'midas_predictor/midas_v2_1_sm... |
import argparse
import os
import numpy as np
import torch
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from torchvision import transforms
from torchvision import datasets
from utils.lib import *
from utils.attacks import *
from models.dann_model import DANNModel
from autoattack im... |
import torch
import torch.nn as nn
import logging
# from efficientnet_pytorch.utils import Conv2dSamePadding
def remove_bn_params(bn_module):
bn_module.register_buffer('running_mean', None)
bn_module.register_buffer('running_var', None)
bn_module.register_parameter('weight', None)
bn_module.register_pa... |
import time
import numpy as np
import galsim
import ngmix
from cs_interpolate import interpolate_image_and_noise_cs
def test_interpolate_image_and_noise_cs_gauss_linear(show=False):
"""
test that our interpolation works decently for a linear
piece missing from a gaussian image
"""
rng = np.rand... |
from collections import Counter
import chainer
import chainer.functions as F
import chainer.links as L
import numpy as np
from chainer import reporter
from utils import softsel, get_logits
from ema import ExponentialMovingAverage
class CharacterConvolution(chainer.Chain):
def __init__(self, config):
su... |
import json
import requests
from urllib.parse import quote # TODO REMOVE WHEN DISCORD FUNC IS REMOVED
from django.shortcuts import render
from .common import *
from .constants import *
from .models import *
from .forms import *
from .constants import BANNED_IPS
from .private import NEW_UPLOAD_WEBHOOK_URL
def uplo... |
#!/usr/bin/env python3
# vim: ts=2 sw=2 sts=2 et tw=81 fdm=indent:
import re, math, random, inspect
from types import FunctionType as Fun
import argparse as arg
def duo( BEST: 'ratio of best examples' = .75,
COHEN: 'min interesting xbin size' =.2,
DELIMITER: 'csv column sepera... |
#/*
# * Copyright (c) 2019,2020 Xilinx Inc. All rights reserved.
# *
# * Author:
# * <NAME> <<EMAIL>>
# *
# * SPDX-License-Identifier: BSD-3-Clause
# */
import struct
import sys
import types
import unittest
import os
import getopt
import re
import subprocess
import shutil
from pathlib import Path
from pathlib im... |
import os
import json
import pymel.core as pmc
import pymel.core.datatypes as dt
CONTROLFILENAME = os.path.join(os.environ['MAYA_APP_DIR'],'control_cache.json')
########## Cache Functions ###############
def load_control_cache():
'''
Trys to load the control cache file.
:return: The newly loaded cache f... |
import pytest
from slurmpie import slurmpie
import os
FIXTURE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__)), "test_data",)
@pytest.mark.datafiles(os.path.join(FIXTURE_DIR, "slurm_script.sh"),)
def test_init(datafiles):
script_file = str(datafiles)
job = slurmpie.Job(script_file)
job_2 = ... |
#! /usr/bin/env python3
#! /usr/bin/env python2
#
# pyruss/server.py
# license--start
#
# Copyright 2012 <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/... |
import flask
import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
import dash_dangerously_set_inner_html
import json
import re
import requests
from urllib.error import URLError
import pandas as pd
import geopandas a... |
"""
Low Rank Multivariate Normal: functions to perform calculations on MVNs
parameterized as
x ~ N(mu, Sigma) D-dimensional RV
Sigma = CC^T + eye(D)*exp(v)
Functions to manipulate a 'component' --- right now specific to Gaussian
components that are either (i) diagonal or (ii) low rank + diagonal
The f... |
from collections import namedtuple
from datetime import datetime, timedelta
import calendar
def parse_date(text='', now=None):
if isinstance(text, datetime):
return text
if text == None:
return text
return Parser(now).parse(text)
Token = namedtuple('Token', ['type', 'value'])
punctuati... |
import os
from nipype.pipeline import engine as pe
from nipype.interfaces.utility import IdentityInterface
from arcana.data.file_format import text_format
from arcana.processor import SingleProc
from arcana.data import (
FilesetFilter, FieldSpec)
from arcana.utils import PATH_SUFFIX
from future.utils import with_me... |
from __future__ import annotations
import abc
from abc import ABCMeta
from dataclasses import dataclass
from functools import partial
from itertools import chain
from typing import Callable, Dict, List, Optional, Sequence, Tuple, Type, TypeVar, Union, TYPE_CHECKING
from apispec import APISpec
from apispec.utils impor... |
# Copyright (c) 2021 <NAME>. All rights reserved.
#
# The contents of this file are licensed under the MIT License
# (the "License"); you may not use this file except in compliance with the
# License.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed ... |
# -*- coding: utf-8 -*-
import numpy as np
import ot as pot
import scipy.stats
def transport_stable_learnGrowth(C, lambda1, lambda2, epsilon, scaling_iter, g, numInnerItermax=None, tau=None,
epsilon0=None, extra_iter=1000, growth_iters=3):
"""
Compute the optimal transport wi... |
####################################
# File name: listings.py #
# Description:
# Author: Team-13 #
# Submission: Spring-2019 #
# Instructor: <NAME> #
####################################
import os
from flask import Flask, Blueprint, abort, request, flash, url_for, redirect, render... |
import csv
import itertools
import datetime
import dateutil.parser
class CSVRow(object):
def __init__(self, row):
self.data = tuple(row)
def __iter__(self):
return iter(self.data)
def __eq__(self, other):
return hasattr(other, '__iter__') and self.data == tuple(other)
def __... |
# faça uma funcao ola_fulano, que recebe um nome e um adjetivo,
# e devolve a string "ola NOME, te acho ADJETIVO".
# Por exemplo, ola_fulano(joao,alto) devolve
# "ola joao, te acho alto"
# dica: você pode juntar duas strings com o operador +
# ex: "ola"+"mundo" resulta "olamundo"
def ola_fulano(nome,adj):
re... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# 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 ... |
#!/usr/bin/env python
# This Software (Dioptra) is being made available as a public service by the
# National Institute of Standards and Technology (NIST), an Agency of the United
# States Department of Commerce. This software was developed in part by employees of
# NIST and in part by NIST contractors. Copyright in po... |
from __future__ import absolute_import
from math import log
import operator
from .. import ROOT
from .canvas import _PadBase
from .hist import _Hist, Hist, HistStack
from .graph import _Graph1DBase, Graph
from ..context import preserve_current_canvas, do_nothing
from ..extern.six.moves import range
__all__ = [
'... |
# %%
import os
import re
import torch
import pickle
import torch.nn as nn
import sys
sys.path.append("../")
from rnn_wrap import RNNwrap
class FeedbackModel(nn.Module):
def __init__(self, model, seq_len):
super(FeedbackModel, self).__init__()
self.model = model
self.seq_len = seq_len
... |
##create a copy of an object
import copy
##regular expression library (search pattern)
import re
#lets build a LISP to C compiler!
# from LISP
# i.e (add 2 (subtract 4 2))
# to C
## add(2, (subtract(4, 2))
#There are 3 parts to a compiler
# 1 PARSING
## a. Lexical Analysis/Tokenization (vocabulary)
## b. Syntacti... |
# Copyright 2018 <NAME>. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license" file accompanying this fil... |
#训练文件 通过ImageFolder载入数据 通过DataLoader生成迭代器 使用预训练模型 进行训练
import torchvision
from torch import nn
import os
import torch
import torchvision.models as models
import matplotlib.pyplot as plt
import time
import PIL.Image
import pandas as pd
import sys
root_dir = '/home/ding/DATA/dataset/'
batch_size = 16
norm_mean = [0.4... |
# Copyright 2021 <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, publish, distribute, sub... |
from ...base import *
from ...dialog import *
from ...dialogs import *
from ...panel import *
from ...button import *
class ObjectTypes:
_types = {}
@classmethod
def add_type(cls, obj_type_id, obj_type_name):
cls._types[obj_type_id] = obj_type_name
@classmethod
def get_types(cls):
... |
from flask import render_template, flash, redirect, url_for, request, escape, abort
from flask_login import current_user, login_user, logout_user, login_required
from app import app, cfg, login_manager
from app.forms import LoginForm, PeopleForm, SearchForm
from app.models import User, People
from lunr import lunr
from... |
from decimal import *
import re as regex
getcontext().prec = 9
getcontext().rounding = ROUND_HALF_UP
REGEX_NUM_REAL = r'\d*\.?\d+'
REGEX_NUM_REAL_CIENTIFICO = r'\d*\.?\d+[Ee]\+\d+|\d*\.?\d+[Ee]\-\d+|\d*\.?\d+[Ee]\d+'
def somar(*elementos):
soma = 0
for e in elementos:
soma += Decimal(f'{e}')
r... |
import requests
from flask import Blueprint, request, Response
from sqlalchemy import desc, asc
from models import db
from config import getConfig
from models import Channel, User, UserScore, ChannelScore
from datetime import date
from azure.cognitiveservices.language.textanalytics import TextAnalyticsClient
from msres... |
import copy
import logging
import functools
from typing import List
import home
import lifx
from lifx_plugin import Address
class Description(home.protocol.Description):
"""
A Lifx LAN protocol message description.
The description contains those *fields of interest* for a *Trigger* or a *Command* defi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.