text
stringlengths
3.07k
12.6k
# -*- coding: utf-8 -*- # Copyright 2015-2016 Telefónica Investigación y Desarrollo, S.A.U # # This file is part of FIWARE project. # # 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: # # htt...
import sqlalchemy as sa import numpy as np import datetime as dt from faker import Faker from jinja2 import Environment, PackageLoader from database.models.core import ( Base, Products, Customers, TransactionDetails, Transactions, ) import logging logging.basicConfig() logger = logging.getLogger(...
#!/usr/bin/env python3 from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import numpy as np import torch as th import torchvision from tqdm import tqdm def main(args): trainloader, testloader = get_loaders(args.batch_size, args.fashion)...
#!/usr/bin/python3 ''' parse large XML files which stores funtional annotations of features infact, we do not need xml module such as SAX at here ''' import sys # import datetime ''' re_match_tag -- using regexp to match tag of xml string: line of xml file tag: <tag> or </tag> status: 0 or 1, 0 match start, 1 ...
import torch from collections.abc import Iterable def _get_layers(model, all_layers=None, all_names=None, top_name=None, fn=None, sep='_'): """Auxiliar function. Recursive method for getting all in the model for which `fn(layer)=True`.""" if all_names is None: all_names = [] if all_layers is None:...
from PIL import Image, ImageDraw # depth = 6084 # target = (14,709) # depth = 510 # target = (10,10) # depth = 4848 # target = (15, 700) depth = 9171 target = (7,721) # depth = 11820 # target = (7,782) buffer = 50 def getErrosion(index): return (index + depth) % 20183 def getType(errosion): return...
#!/usr/bin/env python # -*- coding:utf-8 -*- import os import sys import re import urllib import json import socket import time import multiprocessing from multiprocessing.dummy import Pool from multiprocessing import Queue import requests timeout = 5 socket.setdefaulttimeout(timeout) class Image(object): """图...
# This program imports the federal reserve economic data consumer price index # values from 1990 and uses those values to get the real values or infaltion adjusted # values of the sepcific commodities/markets. # Then when a commdoity hits a specific low infaltion based price, the algo # enters into a long psoiton and ...
from sympy import * # Implementation of QuaternionBase<Derived>::toRotationMatrix(void). # The quaternion q is given as a list [qw, qx, qy, qz]. def QuaternionToRotationMatrix(q): tx = 2 * q[1] ty = 2 * q[2] tz = 2 * q[3] twx = tx * q[0] twy = ty * q[0] twz = tz * q[0] txx = tx * q[1] txy = ty * q[...
import os from importlib import import_module from django.apps import apps from django.db.migrations.loader import MigrationLoader from django.db.migrations.serializer import serializer_factory from django.db.models import ForeignKey, ManyToManyField from django.utils.inspect import get_func_args from django.utils.mod...
#!/usr/bin/env python # coding: utf-8 # In[10]: import os import pandas as pd import networkx as nx import matplotlib.pyplot as plt import random as rd # In[11]: def readFile(folderPath): with open(folderPath, 'r') as f: fileContents = f.readlines() return fileContents # In[12]: def fillI...
import datetime from cerberus import Validator as _Validator from sqlalchemy import inspect from sqlalchemy.orm.collections import InstrumentedList from sqlalchemy.exc import NoInspectionAvailable def is_sqla_obj(obj): """Checks if an object is a SQLAlchemy model instance.""" try: inspect(obj) ...
""" from https://github.com/PoonLab/MiCall-Lite, which was forked from https://github.com/cfe-lab/MiCall. MiCall is distributed under a dual AGPLv3 license. """ import sys import argparse from csv import DictWriter from struct import unpack import csv import os from operator import itemgetter import sys import math ...
""" Import wikidata nodes into KGTK file """ def parser(): return { 'help': 'Import wikidata nodes into KGTK file' } def add_arguments(parser): """ Parse arguments Args: parser (argparse.ArgumentParser) """ parser.add_argument("-i", action="store", type=str, dest="wikidat...
import os import re import gzip import argparse import pandas as pd import numpy as np from collections import defaultdict def get_args(): """ Parse command line arguments """ parser = argparse.ArgumentParser(description="Method to create track for escape mutations") parser.add_argument("-xlsx",...
from twisted.plugin import IPlugin from twisted.words.protocols import irc from txircd.config import ConfigValidationError from txircd.module_interface import Command, ICommand, IModuleData, ModuleData from txircd.modules.xlinebase import XLineBase from txircd.utils import durationToSeconds, ircLower, now from zope.int...
#!/usr/bin/env python3 """ Easy to use Websocket Server. Source: https://github.com/rharder/handy June 2018 - Updated for aiohttp v3.3 August 2018 - Updated for Python 3.7, made WebServer support multiple routes on one port """ import asyncio import logging import weakref from functools import partial from typing imp...
import unittest import numpy as np from dolo.numeric.ncpsolve import ncpsolve, smooth def josephy(x): # Computes the function value F(x) of the NCP-example by Josephy. n=len(x) Fx=np.zeros(n) Fx[0]=3*x[0]**2+2*x[0]*x[1]+2*x[1]**2+x[2]+3*x[3]-6 Fx[1]=2*x[0]**2+x[0]+x[1]**2+3*x[2]+2*x[3]-2 F...
""" propertylist """ from __future__ import absolute_import, division, print_function from collections import namedtuple import logging from PySide.QtCore import Qt from mceditlib import nbt from PySide import QtGui, QtCore from mcedit2.util.load_ui import registerCustomWidget log = logging.getLogger(__name__) cl...
import torch, math, copy import scipy.sparse as sp import numpy as np from torch.nn.modules.module import Module import torch.nn as nn from torch.nn.parameter import Parameter def normalize(adj, device='cpu'): if isinstance(adj, torch.Tensor): adj_ = adj.to(device) elif isinstance(adj, sp.c...
# -*- coding: utf-8 -*- # © 2016 <NAME>, Trustcode # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). # ############################################################################# # # <NAME> Sigep WEB # Copyright (C) 2015 KMEE (http://www.kmee.com.br) # @author: <NAME> <<EMAIL>> # @auth...
import os """ # If you have multi-gpu, designate the number of GPU to use. os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = "6" """ import argparse import logging from tqdm import tqdm # progress bar import numpy as np import matplotlib.pyplot as plt from keras import optimizers from...
""" Start local development server """ import argparse import logging import shlex import subprocess import webbrowser from contextlib import suppress from http.server import HTTPServer, SimpleHTTPRequestHandler from pathlib import Path from ssl import wrap_socket from tempfile import NamedTemporaryFile from threading ...
from __future__ import unicode_literals import os, sys, subprocess, ast from nbconvert.preprocessors import Preprocessor from holoviews.core import Dimensioned, Store from holoviews.ipython.preprocessors import OptsMagicProcessor, OutputMagicProcessor from holoviews.ipython.preprocessors import StripMagicsProcessor fr...
import logging import os import pathlib import requests import shutil from typing import Dict, List, Optional, Union from PIL import Image, UnidentifiedImageError from mir import scm # project def project_root() -> str: root = str(pathlib.Path(__file__).parent.parent.parent.absolute()) return root # mir r...
import math import os import tempfile from contextlib import contextmanager from soap import logger from soap.common.cache import cached from soap.expression import operators, OutputVariableTuple from soap.semantics.error import IntegerInterval, ErrorSemantics flopoco_command_map = { 'IntAdder': ('{wi}', ), ...
# -*- coding: utf-8 -*- from coralquant.models.odl_model import BS_Stock_Basic, BS_SZ50_Stocks, TS_Stock_Basic, TS_TradeCal from coralquant.spider.bs_stock_basic import get_stock_basic from coralquant import logger from datetime import date, datetime, timedelta from sqlalchemy import MetaData from coralquant.database i...
"""Defines useful types and utilities for working with bytestrings.""" from __future__ import annotations import zlib from abc import abstractmethod, ABCMeta from collections.abc import Iterable, Sequence from io import BytesIO from itertools import chain from typing import cast, final, Any, Final, TypeVar, SupportsB...
import numpy as np import numpy.testing as npt import noisyopt def test_minimize(): deltatol = 1e-3 ## basic testing without stochasticity def quadratic(x): return (x**2).sum() res = noisyopt.minimize(quadratic, np.asarray([0.5, 1.0]), deltatol=deltatol) npt.assert_allclose(res.x, [0.0, 0....
import json import os import pymongo ''' fileService.py Author: <NAME> ''' mongo_client = pymongo.MongoClient() #db = {} ''' initialize Takes a 'unique_id'entifier and sets up a database in MongoDB and ensures that that database has collections associated with the various file types that are stored. ''' def init...
import datetime import cv2 import numpy as np from artsci2019.lib.frame_checker import FrameChecker from artsci2019.lib.util import scale_frame, scale_point, is_in_frame from artsci2019.lib.face_recog import get_faces from artsci2019.lib.sound import SoundPlayer def draw_checked_frame(frame, checked_frame, factor): ...
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, recall_score, precision_score, f1_score import torch from transformers import TrainingArguments, Trainer from transformers import BertTokenizer, BertForSequenceClassification from tran...
""" Plot an all-sky average proper motion map, using statistics downloaded from the Gaia archive with a query similar to the following: select gaia_healpix_index(5, source_id) as healpix_5, avg(pmra) as avg_pmra, avg(pmdec) as avg_pmdec from gaiaedr3.gaia_source where parallax_over_error>=10 and parallax*paralla...
""" `bq25883` ==================================================== CircuitPython driver for the BQ25883 2-cell USB boost-mode charger. * Author(s): <NAME> Implementation Notes -------------------- """ from micropython import const from adafruit_bus_device.i2c_device import I2CDevice from adafruit_...
import logging import random from collections import namedtuple from typing import NamedTuple from queue import PriorityQueue from objects import BaseObject from constants import NORTH, SOUTH, EAST, WEST Space = namedtuple("Space", ["x", "y"]) # TODO: Big TODO - Re-implement space with z/t value for terrain??? # Sp...
# -*- coding: utf-8 -*- import datetime from django.db.models import Count, Q from django.utils import timezone from trojsten.events.models import EventParticipant from trojsten.people.constants import SCHOOL_YEAR_END_MONTH from trojsten.results.constants import COEFFICIENT_COLUMN_KEY from trojsten.results.generator...
#!/usr/bin/env python3 import os import sys import subprocess import traceback from datetime import datetime try: sys.path.append(snakemake.config['args']['mcc_path']) import scripts.mccutils as mccutils import config.preprocessing.trimgalore as trimgalore from Bio import SeqIO except Exception as e: ...
from __future__ import division, print_function import os import os.path as fs import numpy as np import pandas as pd import re ### PURPOSE: Takes a directory containing N files of the form mXXXXXX.ovf ### ### and imports them to an N x X x Y x Z x 3 numpy array ### ### where X,Y,Z are the number of cells in x,y...
# Copyright 2016 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 applicable law or ...
import os import sys import json import argparse script_content = """\ #!/bin/sh gpython=${PYENV_ROOT}/versions/$(pyenv global)/bin/python gproj=${PYENV_ROOT}/versions/$(pyenv global)/bin/proj if [[ $1 =~ ^[^\-] ]] ; then result=$(exec $gpython $gproj --echo $1) exit_code=$? if test $exit_code -eq 0 ; th...
from tkinter import Tk, Canvas # This is an emulated display with the same API interface as for the Unicorn HAT/pHAT hardware. # Thus, it relies upon (in part) code from: https://github.com/pimoroni/unicorn-hat/blob/master/library/UnicornHat/unicornhat.py # Note that only the pHAT is supported, and rotation of the di...
# Python plan -> Open Workbench XML converter. # # Python plan defines a Work Breakdown Structure where # tasks are dictionaries and children are defined in a list. # Children can contain sequences, to simplify data input; # sequenced tasks are automatically chained (dependencies). import sys import math from ...
from pyqchem.structure import Structure import numpy as np # Ethene parallel position def dimer_ethene(distance, slide_y, slide_z): coordinates = [[0.0000000, 0.0000000, 0.6660120], [0.0000000, 0.0000000, -0.6660120], [0.0000000, 0.9228100, 1.2279200], ...
"""Manage the directories This includes options to store the hashtable in a file or keep it temporarily, where it will be returned from the function... """ import json import os import platform from typing import Tuple, Union from .errors import FilenameError, PathError, SystemNotSupported __all__ = [ "set_dire...
import re def le_assinatura(): """[A funcao le os valores dos tracos linguisticos do modelo e devolve uma assinatura a ser comparada com os textos fornecidos] Returns: [list] -- [description] """ print("Bem-vindo ao detector automático de COH-PIAH.") print("Informe a assinatura típica de...
""" Test script for utils.py function. """ import os import numpy as np import pytest from astropy import units as u from cwinpy.utils import ( ellipticity_to_q22, gcd_array, get_psr_name, initialise_ephemeris, int_to_alpha, is_par_file, logfactorial, q22_to_ellipticity, ) from lalpuls...
import unittest from typing import Tuple from neofoodclub import NeoFoodClub # type: ignore from neofoodclub.types import RoundData # type: ignore # i picked the smallest round I could quickly find test_round_data: RoundData = { "currentOdds": [ [1, 2, 13, 3, 5], [1, 4, 2, 4, 6], [1, 3, ...
from configparser import ConfigParser import os from dotenv import load_dotenv import pathlib from shutil import copyfile from execution_engine2.db.models.models import Job, JobInput, Meta from dateutil import parser as dateparser import requests import json from datetime import datetime from execution_engine2.exceptio...
import decimal import itertools import random from datetime import date, timedelta import factory from applications.enums import ApplicationStatus, ApplicationStep, BenefitType from applications.models import ( AhjoDecision, Application, APPLICATION_LANGUAGE_CHOICES, ApplicationBasis, ApplicationBa...
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint T = 200 h = 1e-2 t = np.arange(start=0, stop=T + h, step=h) bet, gam = 0.15, 1 / 50 # todo: zmienic poziej na randoma # S_pocz = np.random.uniform(0.7, 1) S_start = 0.8 I_start = 1 - S_start R_start = 0 N = S_start + I_start + R_sta...
import glob import os # os.environ["IMAGEIO_FFMPEG_EXE"] = "C:/ffmpeg-4.4.1-essentials_build/ffmpeg-4.4.1-essentials_build/bin" import re import sys import urllib from tkinter import (BOTH, RIGHT, YES, Button, Entry, Label, Listbox, Menu, Scrollbar, StringVar, Tk, Y) from tkinter import messagebox ...
#!/usr/bin/python #-*- coding: utf-8 -*- # >.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>. # Licensed under the Apache License, Version 2.0 (the "License") # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # --- File Name: shapes3d.py # --- Creation Date: 16-01-2021 # --- Last Modified: Tue 13 A...
from functools import reduce import numpy as np import json import tensorflow as tf from scipy.optimize import linear_sum_assignment import os import time def deleteDuplicate_v1(input_dict_lst): f = lambda x,y:x if y in x else x + [y] return reduce(f, [[], ] + input_dict_lst) def get_context_pair(resp, l): label_w...
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to...
from blockchain import Blockchain, Transaction from nacl.signing import SigningKey from hashlib import sha256 from time import sleep from threading import Thread import random class Node: """Represent a Node.""" def __init__(self, neighbours, unverified_transactions_pool): """ Initialize the ...
import re import os from prob import trans_P, emit_P, start_P from preprocess import preprocess, recov, UNK DATAROOT = '/home/luod/class/nlp/HanTokenization/datasets' RESULTROOT = '/home/luod/class/nlp/HanTokenization/results' VOCAB_FILE = os.path.join(DATAROOT, 'training_vocab.txt') VOCAB_FREQ = os.path.join(RESULTR...
''' Main function to be called from GCE's cloud function This function is in charge of adding training data to the datastore for later generation of models and feature study ''' import sys import os import time import numpy as np from google.cloud import datastore from google.cloud import storage from google.api_core...
import xarray as xr from .basic import zonal_mean, zonal_wave_coeffs, zonal_wave_covariance def _print_if_true(msg, condition, **kwargs): r"""Simple utility function to print only if the given condition is True. Parameters ---------- msg : string The message to print condition : bool ...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# -*- coding: utf-8 -*- import tensorflow as tf import matplotlib.pyplot as plt import matplotlib as mpl import simulators import derivatives import utils import books import hedge_models import preprocessing import approximators from constants import FLOAT_DTYPE class BrownianMotion(simulators.GBM): def __init_...
"""Constant and messages definition for MT communication.""" class MID: """Values for the message id (MID)""" ## Error message, 1 data byte Error = 0x42 ErrorCodes = { 0x03: "Invalid period", 0x04: "Invalid message", 0x1E: "Timer overflow", 0x20: "Invalid baudrate", 0x21: "Invalid parameter" } # Stat...
import torch import numpy as np import cv2 def tonumpyimg(img): """ Convert a normalized tensor image to unnormalized uint8 numpy image For single channel image, no unnormalization is done. :param img: torch, normalized, (3, H, W), (H, W) :return: numpy: (H, W, 3), (H, W). uint8 """ ...
#appModules/msimn.py - Outlook Express appModule #A part of NonVisual Desktop Access (NVDA) #Copyright (C) 2006-2012 NVDA Contributors #This file is covered by the GNU General Public License. #See the file COPYING for more details. import winUser import controlTypes import displayModel import textInfos import api impo...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
""" Useful functions for the admin panel of ImageLabeller. In particular: * Download labels from database to json or csv * Upload images to the database, from json (catalogue of image locations) or zip archive NOTE: When uploading files, or an archive full of files, we will attempt to match the filename to a regex wi...
# The original GA algorithm is here: import numpy as np, random, operator, pandas as pd, matplotlib.pyplot as plt import math class City: def __init__(self, x, y): self.x = x self.y = y def distance(self, city): xDis = abs(self.x - city.x) yDis = abs(self.y - city.y) ...
# Copyright (c) 2016-2018, University of Idaho # All rights reserved. # # <NAME> (<EMAIL>) # # The project described was supported by NSF award number IIA-1301792 # from the NSF Idaho EPSCoR Program and by the National Science Foundation. import os from os.path import exists as _exists from os.path import join as _joi...
from django.shortcuts import render,get_object_or_404, redirect from django.http import HttpResponseRedirect, HttpResponse, JsonResponse from monitor.models import Machine, Crash, Testcase, Profile, DupCrash from track.models import Issue from django.http import Http404 from django.conf import settings from django.core...
from pettingzoo import AECEnv from pettingzoo.utils import agent_selector from pettingzoo.utils import wrappers from pettingzoo.utils.conversions import parallel_wrapper_fn from gym_stag_hunt.envs.hunt import HuntEnv from gym.spaces import Box import cv2 import numpy as np def env(grid_size=(5, 5), screen_size=(600,...
import argparse import cv2 import numpy as np from inference import Network from openvino.inference_engine import IENetwork, IECore import pylab as plt import math import matplotlib from scipy.ndimage.filters import gaussian_filter INPUT_STREAM = "emotion.mp4" CPU_EXTENSION = "C:\\Program Files (x86)\\IntelSWTools\\o...
############################################################ # Dev: <NAME> # Class: Machine Learning # Date: 2/23/2022 # file: utils.py # Description: utility functions for artificial neural # network learning ############################################################# import random class Data: '''c...
import sys, numpy from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import MultinomialNB #0=drama,1=comedy,2=animated,3=action/adventure def random_forest_class(raw_test_set): x_train=[] y_train=[] count=0 vectorize...
#!/usr/bin/env python3 """ Models that maps to Cloudformation functions. """ def replace_fn(node): """Iteratively replace all Fn/Ref in the node""" if isinstance(node, list): return [replace_fn(item) for item in node] if isinstance(node, dict): return {name: replace_fn(value) for name, val...
import numpy as np import queue import cv2 import os import datetime SIZE = 32 SCALE = 0.007874015748031496 def quantized_np(array,scale,data_width=8): quantized_array= np.round(array/scale) quantized_array = np.maximum(quantized_array, -2**(data_width-1)) quantized_array = np.minimum(quantized_array, 2**...
import numpy as np from typing import Tuple import plotly.io from IMLearn.metalearners.adaboost import AdaBoost from IMLearn.learners.classifiers import DecisionStump from IMLearn.metrics import accuracy from utils import * import plotly.graph_objects as go from plotly.subplots import make_subplots plotly.io.rendere...
import time from datetime import datetime as dt import colorama from colorama import Fore, Back, Style import socket import os import sys def CS(X): time.sleep(X) os.system("clear") def socknames(): myHostName = socket.gethostname() myIP = socket.gethostbyname(myHostName) print("\033[35m[\033...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import sys import os.path from PIL import Image import logging import numpy as np from .base_analyzer import BaseAnnotator if os.environ.get('PYTORCH_MODE',False): import dvalib.crnn.utils as ut...
"""Calculators for different values. In order to approximate the emissions for a single kWh of produced energy, per power source we look at the following 2016 data sets. * Detailed EIA-923 emissions survey data (https://www.eia.gov/electricity/data/state/emission_annual.xls) * Net Generation by State by Type of Pr...
#encoding=utf8 import time import numpy as np import tensorflow as tf from tensorflow.contrib import crf import cws.BiLSTM as modelDef from cws.data import Data tf.app.flags.DEFINE_string('dict_path', 'data/your_dict.pkl', 'dict path') tf.app.flags.DEFINE_string('train_data', 'data/your_train_data.pkl', 'tr...
from datetime import datetime, timedelta from auth import * from edit import video_length_seconds, get_total_length, change_fps, is_copyright, merge_videos from upload_video import * from random import randrange import os # if __name__ == '__main__' auth = createAuthObject() def get_clips_by_cat(daysdiff, category)...
# Copyright 2014 SolidBuilds.com. All rights reserved # # Authors: <NAME> <<EMAIL>> from flask import Blueprint, redirect, render_template from flask import request, url_for from flask_user import current_user, login_required, roles_required from app import db from app.models.user_models import UserProfileForm boo...
import gi import ctypes as pyc from ctypes import pythonapi from gi.repository import GObject as GO pyc.cdll.LoadLibrary('libgobject-2.0.so') lego = pyc.CDLL('libgobject-2.0.so') lego.g_type_name.restype = pyc.c_char_p lego.g_type_name.argtypes = (pyc.c_ulonglong,) pythonapi.PyCapsule_GetName.restype = pyc.c_char_p pyt...
# 3rd party import import tensorflow as tf from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.framework import dtypes # stdlib import # module import import model_utils def UQP_nce_loss(model, user_idxs, query_word_idxs, product_idxs, word_idxs): """ Arg...
import random import logging from math import sqrt from rec.dataset.dataset import Dataset from rec.recommender.base import SessionAwareRecommender from collections import defaultdict, Counter import tqdm class SessionKnnRecommender(SessionAwareRecommender): def __init__(self, k=100, sample_size=1000, similarity...
""" Copyright (c) 2018 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 wri...
""" This file will stored all dynamic class and methods. These methods will be used throughout the whole program. """ import sys import concurrent.futures as cf import threading from functools import wraps from ..utils.request import Session from ..errors import BuildError def Threader(f): @wraps(f)...
# coding=utf-8 # Copyright 2014, <NAME> http://github.com/rafi # vim: set ts=8 sw=4 tw=80 et : import logging import requests from beets.plugins import BeetsPlugin from beets import ui from beets import dbcore from beets import config log = logging.getLogger('beets') api_url = 'http://ws.audioscrobbler.com/2.0/?meth...
# Notes from this experiment: # 1. adapt() is way slower than np.unique -- takes forever for 1M, hangs for 10M # 2. TF returns error if adapt is inside tf.function. adapt uses graph inside anyway # 3. OOM in batch mode during sparse_to_dense despite of seting sparse in keras # 4. Mini-batch works but 15x(g)/20x slower ...
""" Script to make nucleosome occupancy track! @author: <NAME> """ ##### IMPORT MODULES ##### # import necessary python modules #import matplotlib as mpl #mpl.use('PS') import matplotlib.pyplot as plt import multiprocessing as mp import numpy as np import traceback import itertools import pysam from pyatac.utils impo...
#!/usr/bin/env python3 import numpy as np import copy import itertools import sys import ete3 import numpy as np from Bio import AlignIO # import CIAlign.cropSeq as cropSeq # from AlignmentStats import find_removed_cialign def writeOutfile(outfile, arr, nams, rmfile=None): ''' Writes an alignment stored in ...
import torch import torch.nn.utils import torch.cuda.amp as amp import torchvision.ops as cv_ops import utils.bbox_ops as bbox_ops def train_one_epoch(model, optimizer, criterion, lr_scheduler, data_loader, dist_logger, epoch_idx): losses, cls_losses, bbox_losses, centerness_losses = [], [], [], [] model.tr...
#!/usr/bin/env python # # fsl_ents.py - Extract ICA component time courses from a MELODIC directory. # # Author: <NAME> <<EMAIL>> # """This module defines the ``fsl_ents`` script, for extracting component time series from a MELODIC ``.ica`` directory. """ import os.path as op import sys import a...
import collections import io import numpy as np import tensorflow as tf hidden_dim = 1000 input_size = 28 * 28 output_size = 10 train_data_file = "/home/harper/dataset/mnist/train-images.idx3-ubyte" train_label_file = "/home/harper/dataset/mnist/train-labels.idx1-ubyte" test_data_file = "/home/harper/dataset/mnist/t...
import json import tempfile from collections import OrderedDict import os import numpy as np from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval from utils import BoxList #from utils.pycocotools_rotation import Rotation_COCOeval def evaluate(dataset, predictions, result_file, score_...
import pytest from helpers.cluster import ClickHouseCluster import urllib.request, urllib.parse import ssl import os.path HTTPS_PORT = 8443 NODE_IP = '10.5.172.77' # It's important for the node to work at this IP because 'server-cert.pem' requires that (see server-ext.cnf). NODE_IP_WITH_HTTPS_PORT = NODE_IP + ':' + st...
import numpy as np import pandas as pd import pandas.api.types as pdtypes from ..utils import resolution from ..doctools import document from .stat import stat @document class stat_boxplot(stat): """ Compute boxplot statistics {usage} Parameters ---------- {common_parameters} coef : flo...
# # Copyright 2017 Import.io # # 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 numpy as np def fit_MRF_pseudolikelihood(adj_exc,adj_inh,y): ''' Fit a Markov random field using maximum pseudolikelihood estimation, also known as logistic regression. The conditional probabilities follow y_i ~ Logistic(B[0] + B[1] A1_{ij} y_j + A1[2] X_{ij} (1-y_j) + B[...
from __future__ import print_function import numpy as np import treegp from treegp_test_helper import timer from treegp_test_helper import get_correlation_length_matrix from treegp_test_helper import make_1d_grf from treegp_test_helper import make_2d_grf @timer def test_hyperparameter_search_1d(): optimizer = ['l...
""" (C) Copyright 2021 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software d...