text
stringlengths
3.07k
12.6k
""" Node composer. -------------- A composer that composes different quantities onto AiiDA data nodes. """ from warnings import warn import math import numbers from aiida_vasp.utils.aiida_utils import get_data_class NODES_TYPES = { 'dict': [ 'total_energies', 'maximum_force', 'maximum_stress', 'symmetri...
import mmh3 import redis class RedisSetFilter: """Trivial redis based filter, utilize set datatype to store values This could be used to filter relatively small amount of values. The max number of members in a redis set is 232 - 1 (4294967295, more than 4 billion of members per set). Useful to f...
''' 14.40b - Combine an 1.3" OLED with the SH1106 controller, a BME280 sensor and Wifi/IFTTT Contains supporting variables and functions needed by oled_bme_280_IFTTT_modular.py". Course: MicroPython with the ESP32 https://techexplorations.com ''' import ntptime from machine import RTC, Pin import ujson as json...
# -*- coding: utf-8 -*- """Find a Supplier - Company's Business Profile page""" import logging from urllib.parse import urljoin from behave.model import Table from requests import Response, Session from scrapy import Selector from directory_tests_shared import PageType, Service, URLs from directory_tests_shared.const...
# Copyright 2019 QuantRocket - 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 ...
from datetime import datetime from Queue import Queue, Empty from flask import request, jsonify, Response from flexget.options import get_parser from flexget.api import api, APIResource from flexget.utils import json from json import JSONEncoder from flexget.event import event from flexget.utils.lazy_dict import Lazy...
# -*- coding: utf-8 -*- """ Test fixture definitions. These fixtures are automatically imported for test files in this directory. """ import collections import random import uuid from mock import MagicMock, PropertyMock import pytest import psycopg2 @pytest.fixture def mock_connection(): mock_connection = Prop...
import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, Sequential, optimizers import numpy as np from tensorflow.compat.v1.keras.backend import set_session config = tf.compat.v1.ConfigProto() config.gpu_optio...
#!/usr/bin/python import urllib2 import time import os logo = """ ___ _ _ ___ _ / __| ___ __ (_) __ _ | | / __| _ _ __ _ __ | |__ \__ \/ _ \/ _|| |/ _` || || (__ | '_|/ _` |/ _|| / / |___/\___/\__||_|\__,_||_| \___||_| \__,_|\__||_\_\ // if there's a hint, t...
import argparse import sys import numpy as np import pandas as pd from pathlib import Path import itertools import json import yaml from qng import qng from obflowsim.mm.mm_dataprep import qng_approx_from_inputs def scenario_grid_to_csv(scenario_recipe_yaml_file, _csv_output_file_path): """ Creates obsimpy ...
# Copyright 2015 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 ...
# -*- coding: utf-8 -*- """ Created on Thu Jan 30 23:12:29 2020 @author: akshay """ import matplotlib.pyplot as plt import numpy as np def loadData(): with np.load('notMNIST.npz') as data: Data, Target = data['images'], data['labels'] posClass = 2 negClass = 9 dataI...
from absl import app import jax from jax._src.numpy.lax_numpy import argsort, interp import jax.numpy as jnp from jaxopt import implicit_diff from jaxopt import linear_solve from jaxopt import OptaxSolver, GradientDescent from matplotlib.pyplot import vlines import optax from sklearn import datasets from sklearn import...
#!/usr/bin/env python import numpy as np import pandas as pd import matplotlib.pyplot as plt import yt v0 = 15.0 # geostrophic wind, from prob.V_0 or erf.geostrophic_wind Az = 5.0 # kinematic viscosity [m^2/s], from erf.dynamicViscosity / prob.rho_0 earth_period = 86164.0900027328 # erf.rotational_time_period ymax_plo...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import os import tensorflow as tf import tensorflow.keras.backend as K @tf.keras.utils.register_keras_serializable() class Embedding(tf.keras.layers.Layer): def __init__(self, vocab_size, model_dim, **kwargs): self._vocab_size = vocab_size self._model_di...
import json from django.http import HttpResponse from django.test import RequestFactory, TestCase from .decorators import json_validator JSON_SCHEMA = { "type" : "object", "required": [ 'status', 'card_type', 'request_type', 'products', 'payment_type', 'total_value', 'distributor_id', 'addre...
from PIL import Image from PIL import ImageDraw import numpy as np import matplotlib.pyplot as plt from Utils import joinPath, saveData, setDir from PlotTools import plotMyFigureOnAxes def extractSelectedRegion(selected_data): img_array = selected_data['image_array'] W_R = int(selected_data['W_R']) H_R = i...
from sqlalchemy import Column, ForeignKey, Boolean, Integer, BigInteger, Float, String, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship Base = declarative_base() class Harness(Base): __tablename__ = 'harness' id = Column(Integer, primary_key=True, null...
#!/usr/bin/env python3 """ Created on September 21 2019 @author: <NAME> @description: rpSelenzyme REST entry script """ import os import json import libsbml import io import tarfile import csv import sys import glob import tempfile import logging sys.path.insert(0, '/home/') import rpSBML import rpTool def runSel...
from ray.util.multiprocessing import Pool #from multiprocessing import Pool import copy from control import Agent import numpy as np def set_seq_and_batch_vals(inp, batch_size_to_seq_len_multiple, dim=1): # get all of the rollout lengths: rollout_lengths = [] for worker_rollouts in inp: # iterat...
import time import os import board import json import busio from digitalio import DigitalInOut from digitalio import Direction from adafruit_espatcontrol import adafruit_espatcontrol import adafruit_espatcontrol.adafruit_espatcontrol_socket as socket import displayio import adafruit_imageload from adafruit_st7735r imp...
#!/usr/bin/env python3 """Recipe for training a Language Model with ksponspeech train-965.2 transcript and lm_corpus. To run this recipe, do the following: > pip install datasets > python train.py hparams/<hparam_file>.yaml \ --data_folder <local_path_to_librispeech_dataset> Authors * <NAME> 2021 * <NAME> 2020 ...
import numpy as np from keychest.keychestenv import KeyChestEnvironment # the environment is NP-hard due to reduction from TSP # (imagine a setting where only 1 combination leads to enough food) # https://en.wikipedia.org/wiki/Travelling_salesman_problem # this file provides a heuristic "solving" the environment (to ...
from hps import Hyperparams, cifar10, parse_args_and_update_hparams from train_helpers import set_up_hyperparams, load_vaes, add_vae_arguments from train import set_up_data, get_sample_for_visualization import argparse, imageio import matplotlib.pyplot as plt import numpy as np import torch.distributed as dist from tor...
import os import numpy as np import tensorflow as tf from google.protobuf import text_format from tensorflow.python.tools import freeze_graph from tensorflow.python.framework import meta_graph def create_and_save_model(): inputs = tf.placeholder(tf.float32, shape=(1, 10), name='input') x = tf.keras.layers.Dens...
from argparse import ArgumentParser import os import traceback import random import math import pysam def mixshuffle(input_files, output_files, abundance, input_files2=None, seed=None, k=None): # check if out filename exists, exit if it does out_exists = os.path.isfile(output_files[0]) if out_exists: ...
from MCFlow.file_formatting.reader import Movie from MCFlow.structure_analysis import Struc def writeXY(x,y,name): with open(name,'w') as f: for i,j in zip(x,y): f.write('%e %e\n'%(i,j)) class S_k(Movie): def __init__(self, file_name, *args): Movie.__init__(self, file_name, *args)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Apr 4 19:55:24 2019 @author: avelinojaver """ import sys from pathlib import Path root_dir = Path(__file__).resolve().parents[1] sys.path.append(str(root_dir)) sys.path.append(str(root_dir / 'scripts') ) import numpy as np from cell_localization.uti...
import modules.bcolours as bcolours from modules.bcolours import * ############################################## # Write in Markdown with python ############################################## # ---------------------------------- Tables ------------------------------------ # Translation dictionaries for table alignm...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 26 10:42:33 2020 @author: jaime """ import tdt import cv2 as cv import pandas as pd import numpy as np import matplotlib.pyplot as plt from pathlib import Path import dill import trompy as tp def make_ppp_video_dict(rat, diet, box, tank, cam,...
import argparse import sys import collections import numpy as np import pandas as pd import matplotlib import seaborn as sns import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import PdfPages from ast import literal_eval parser = argparse.ArgumentParser(description='Compare predictions from HMM model...
import os, random, time from googletrans import Translator import unidecode from pyppeteer import launch import bs4 import pandas as pd from gtts import gTTS import asyncio import pycountry import shutil from icrawler.builtin import GoogleImageCrawler import lib.const as const p_JPG_NAME_CONV = '000001.jpg' p_PNG_NAME...
# # Copyright 2021 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
# sched_timetable.py: Generate a HTML timetable from course schedule structures # This file is from Minervac, a command-line client for Minerva # <http://npaun.ca/projects/minervac> # (C) Copyright 2016-2017 <NAME> from __future__ import print_function from __future__ import absolute_import from __future__ import divi...
# Original Author: <NAME> # Modified: <NAME> # Date: October 14, 2017 # # Description: A multiprocess python application to cluster still camera images. The script read images data from a local directory and writes # its output to a local directory. The output is a text file containing image name and the ...
from typing import List, Optional from objects.linesegment import LineSegment from objects.point import Point from structures.avltree import AVLTree def find_intersections_slow(line_segments: List[LineSegment]) -> List[Point]: result = set() for i in range(len(line_segments)): for ls in line_segments...
class Node(): def __init__(self,value='',left=None,right=None): self.value = value self.left = left self.right = right self.next = None def __str__(self): return str(self.value) class BinaryTree(): def __init__(self, node=None): self.root = node # CC15 def pre_order(self)...
#I employ a genetic algorithm to try to find the collective optimal outcome of the climate game. The climate game is based on #the paper: "The collective-risk social dilemma and the prevention of simulated dangerous climate change" written by #Milinski et al. - http://www.pnas.org/content/105/7/2291. I also drew insp...
from __future__ import print_function from keras.models import Model from keras.layers import Input, LSTM, Dense, Embedding import numpy as np #Variables training_batch_size = 64 # Batch size for training batch_size = 20 loop_count = 5 epochs = 200 # Number of epochs to train for latent_dim = 256 # Latent dimension...
""" Utilization file for scraping environment. Includes: * get_file_list * product_file_mapping * vendor_folder_mapping * menu_add_vendors * menu_add_products * timeout * product_subpage_aligner * instructions """ import os import asyncio from pathlib import Path from src import s...
import boto3 from botocore.exceptions import ClientError import json import os import sys import time import zipfile #Sets up our boto3 clients iamClient = boto3.client('iam') eventsClient = boto3.client('events') lambdaClient = boto3.client('lambda') #This is the policy we'll attach to the role policy_document = { ...
import sys import math import numpy as np try: import cord_park except ImportError: raise def input_cars_init_gidx(park): """ Specify the initial indices of cars by the user return 1*car_dim np.array 'car_ini_gidx' where car_dim is the number of cars """ g_dim = park.g_dim pk_dim =...
import torch import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn import SignedGCN, GCNConv, SAGEConv, ChebConv, MessagePassing, TopKPooling, global_mean_pool as gap, global_max_pool as gmp from torch_geometric.utils import (negative_sampling, remove_self_loops, add_self_loops) from torch_geome...
"""Sentence Embedding related modeling class""" from typing import Dict, List, Optional import numpy as np from sentence_transformers import util from pororo.tasks.utils.base import PororoFactoryBase, PororoSimpleBase from pororo.tasks.utils.download_utils import download_or_load class PororoSentenceFactory(Pororo...
import os import json import numpy as np import matplotlib.pyplot as plt def compute_iou(box_1, box_2): ''' This function takes a pair of bounding boxes and returns intersection-over- union (IoU) of two bounding boxes. ''' # [x1, y1, x2, y2] # intersection coordinates x1 = max(box_1[0], box...
import numpy as np import pandas as pd import scipy.stats def my_bimodal(n): """ defines a bimodal distribution (with mean 1, overall sd = 1, and pi = .5) Arguments: ---------- n : int number of samples to draw Returns: -------- vector of random samples """ mean_shift = .9 ...
""" File for loading the IHDP semi-synthetic dataset. Hill (2011) took the real covariates from the IHDP data and generated semi-synthetic data by generating the outcomes via random functions ("response surfaces"). Response surface A corresponds to a linear function; we do not provide that data in this file. Response ...
import configparser from functools import wraps import inspect import logging import shelve from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, ConversationHandler) logger = logging.getLogger(__name__) def partial_commandhandler(): commandhandler_sign = inspect...
from ase.calculators.singlepoint import SinglePointCalculator as sp from finetuna.calcs import DeltaCalc from ase.io import write import numpy as np import subprocess import re import tempfile import random def convert_to_singlepoint(images): """ Replaces the attached calculators with singlepoint calculators ...
from bs4 import BeautifulSoup as Soup from shifts.models import Shift from django.contrib.auth.models import User from .views import render_calendar import datetime import pytest import pytz def test_homepage(client): response = client.get("/") html = response.content.decode("utf-8") assert "<title>Pillar...
#!python3 import numpy as np from magLabUtilities.signalutilities.signals import SignalThread, Signal from magLabUtilities.signalutilities.calculus import integralTrapQuadrature # from internal.terminalInterface import printMsg # from internal.exceptions import IncompatibleArgumentError, DataShapeError def ne...
import base64 import datetime from email.mime.audio import MIMEAudio from email.mime.base import MIMEBase from email.mime.image import MIMEImage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import mimetypes import os import time from apiclient import errors, discovery import argp...
from algoritmia.datastructures.doubleendedpriorityqueues.interfaces import IDoubleEndedPriorityQueue class IntervalHeap(IDoubleEndedPriorityQueue): #[interval1 def __init__(self, data: "Iterable<T>"=[], capacity: "int"=0): capacity = max(capacity, len(data)) self._heap = data + [None] * (capac...
# Copyright 2021 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
# -*- coding: utf-8 -*- import numpy as np import scipy import scipy.linalg import scipy.optimize import scipy.spatial from ..util import constants as c def vector(x, y, z): """ A shortcut for creating 3D-space vectors; in case you need a lot of manual np.array([...]) """ return np.array([x, y, z]) def ...
#!/usr/bin/env python import rospy import rospkg import tf2_ros import numpy as np from random import uniform from threading import Event from std_srvs.srv import Empty from gazebo_msgs.srv import DeleteModel, SpawnModel from gazebo_msgs.msg import ContactsState from geometry_msgs.msg import Pose, Point, Quaternion fr...
#!/usr/bin/python3 # -*- coding = utf-8 -*- import json,time, csv, argparse from Request import * from prettytable import PrettyTable class AggregatedBookRequest(Request): subsbribetype = "1" delay = "800" def __init__(self, token, symbol): Request.__init__(self, token, "quotes", "aggregatedBook") ...
from django.http import HttpResponse from django.template import loader from django.contrib.auth.views import PasswordResetView from .settings import SITE_NAME_SHORT, SITE_NAME_LONG, ALLOW_ERROR_URL from django.http import Http404 from mxv.settings import TRACK3_VOTING_VISIBLE_TO_NON_STAFF, CONSULTATIONS_VISIBLE_TO_NON...
import functools import json import os.path as path import cv2 import numpy as np def exist_file_path(file_id): if not path.exists(file_id): raise FileNotFoundError(f'index: {file_id}\n') else: image_path = path.abspath(file_id) return image_path def match_file_path(file_id): fi...
############################################################################### # Copyright (c) 2019 Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory # # Written by <NAME>, <NAME> # <EMAIL> # # LLNL-CODE-805904 # # All rights reserved. # # Permission is hereby granted,...
# analysis profile data from .base import * class FDPSProfile(DictNpArrayMix): """ FDPS time profile for tree for one tree step """ def __init__ (self, _dat=None, _offset=int(0), _append=False, **kwargs): keys = [["collect_sam_ptcl",1], ["decompose_domain",1], ["exchange_ptcl",1], ["make_local_tre...
""" Copyright 2018 EPAM Systems, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed...
import pygame from config import Constants, Aim, Images, Lives from config import display_lives, update_live, play_music, loser, reset_game, victory from players import Player from ball import Ball from sys import exit # screen screen = pygame.display.set_mode(Constants.SCREEN_SIZE) pygame.display.set_caption("DODGE-...
from __future__ import absolute_import, unicode_literals from django.conf import settings from django.contrib import messages from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth.views import redirect_to_login from django.core.exceptions import ImproperlyConfigured, PermissionDenied from django...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import contextlib import os import sys import textwrap import warnings import pytest import sh from IPython.terminal.embed import InteractiveShellEmbed from dotenv import dotenv_values, find_dotenv, load_dotenv, set_key from dotenv.compat import PY2, St...
""" Copyright © <01/08/2017>, <<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, distrib...
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # 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 ...
"""Commands that produce fox creatures.""" import random from sailor import commands from sailor.exceptions import UserInputError FOXWHALE = R""" /\_/\{0} ____ / {1}\_/ / \ | . . {1} \ \ | ^ {1} _ / / \_____{0}/ \__\_/ """.strip("\n") FOXSQUID = R""" /\_/\ / \ | . . | \ ^ /{0} | | /...
from __future__ import division import math import sys def alpha_t(t,itask,i): l=i sumT=0 numcseg=len(itask["Cseg"]) while 1: if l%numcseg!=numcseg-1: sumT+=itask["Cseg"][l%numcseg]+itask["Sseg"][l%numcseg]*itask['minSr'] else: if l <=numcseg: sumT+=itask["Cseg"][numcseg-1]+itask["...
import folium import settings as sgs import numpy as np def get_beautiful_base_image_map(df_flux, thin=False): """ Create the beautiful folium map containing routes, with blur effect """ # Initialize folium map parameters folium_map = folium.Map(location = sgs._location_map, ...
from django.shortcuts import render, render_to_response, get_list_or_404 from tracker.models import * from django.views.generic import ListView, CreateView from tracker.forms import * from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse, reverse_lazy from django.contri...
#!/usr/bin/env python # encoding: utf-8 # # Copyright SAS Institute # # 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 b...
from collections import OrderedDict from dowel import logger, tabular from garage.np.algos import BatchPolopt import torch from torch.distributions.kl import kl_divergence from torch.nn.utils.convert_parameters import (vector_to_parameters, parameters_to_vector) from met...
#!/usr/bin/env python from __future__ import print_function import math import sys import argparse import quakelib scipy_available = True try: import scipy.stats except ImportError: scipy_available = False def check_self_consistent(events): error = False for event in events: elements = event...
# Copyright 2020 Spotify AB # # 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, so...
#!/usr/bin/env python # coding:utf8 import os from collections import namedtuple from ansible.parsing.dataloader import DataLoader from ansible.vars.manager import VariableManager from ansible.executor.playbook_executor import PlaybookExecutor from ansible.plugins.callback import CallbackBase import ansible.constants ...
# %% imports from helpers.generic import ensureFolderExists, nfttToFrequencies import tensorflow as tf import tensorflow_io as tfio from pathlib import Path import shutil import subprocess from tqdm import tqdm import librosa # %% Definitions SAMPLE_RATE = 16000 # SAMPLE_RATE = 22050 SLICE_WIDTH = 72 SLICE_WIDTH_GENER...
import interpreter from bsddb3 import db import numpy as np from functools import reduce import re #https://stackoverflow.com/questions/22821124/berkeley-db-equivalent-of-select-count-all-select-count-where-like global brief brief = True def FindFilename(column_name): if column_name in ["subject", "body"]: ...
# -*- coding: utf-8 -*- """ Copyright (c) 2020, University of Southampton All rights reserved. Licensed under the BSD 3-Clause License. See LICENSE.md file in the project root for full license information. """ # Workaround to dump OrderedDict into YAML files from collections import OrderedDict import yaml from .cons...
#!/usr/bin/env python # # LMS-Material # # Copyright (c) 2018 <NAME> <<EMAIL>> # MIT license. # import hashlib import os import re import requests import shutil import subprocess import sys INSTALL_XML = "MaterialSkin/install.xml" PUBLIC_XML = "public.xml" BUILD_FOLDER = "build" MINIFY_CODE = False # Change to true...
import cv2 import numpy as np import cropdata640 from matplotlib import pyplot as plt def getCroppedImage(image, crop_array): croppedImage = image[crop_array[0] :crop_array[1], crop_array[2]:crop_array[3]] return croppedImage def findPins(img): global x, x1, y, y1 global priorP...
import re import urllib.request import json import math class DMGException(Exception):pass ScoreURL = "" RawJSON = "" with open("config.json", "r") as f: data = json.loads("\n".join(f.readlines())) ScoreURL = data["ScoreURL"] RawJSON = data["RawURL"] ScorePriority = { "Assigned Score":"Assigned", "Assigned Tot...
# -*- coding: UTF-8 -*-# """Serialize the scheduled action.""" import datetime from builtins import object import pytz from django.conf import settings from django.utils.translation import ugettext, ugettext_lazy as _ from rest_framework import serializers from rest_framework.exceptions import APIException from ont...
""" author: <NAME> (<EMAIL>) dob: 13 Nov 2015 purpose: Provide the utilities to create watershed catchment areas using whitewater reach data. Copyright 2015 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the ...
from nltk.corpus import wordnet as wn import csv import re import json from collections import OrderedDict from pathlib import Path from hyposet import hyposet from new_word import new_word from word_cleaner import word_cleaner from stopwords import stopword_generator # Initialize dictionaries of hyposet and new_word...
from collections import defaultdict from django.http import HttpResponse from django.template import loader from django.template.context import RequestContext from boris.reporting.forms import OUTPUT_BROWSER, OUTPUT_OFFICE class hashdict(dict): """ A dict that is hashable. BEWARE not to mutate it.. """ ...
import numpy as np import math from backtester.strategy import Strategy, StrategyLeg from backtester.enums import Type, Direction from backtester import Backtest def test_sell_some_options_1legs(options_data_2puts_buy, ivy_portfolio_5assets_datahandler, ivy_5assets_portfolio): options_data = options_data_2puts_b...
# Copyright (c) 2021, Innomat, Asprotec and libracore and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ import ast # to parse str to dict (from JS calls) def execute(filters=None): columns = get_columns() data...
import random as rnd from sklearn.preprocessing import MultiLabelBinarizer def convert_prod_to_index(cust_list: list, prod_dict: dict) -> list: """ Function to convert lists of customers/baskets/products to customer/baskets/product indices as required by the downstream sequence models Parameters ...
import os import sys import shutil sys.path.append(os.path.join(sys.path[0],'trainedmodel')) from flask import Flask, flash, request, redirect, url_for, render_template, send_file from werkzeug.utils import secure_filename from helper.image import findSubPlots from trainedmodel import detect from distances import findC...
#!/usr/bin/env python3 from flask import Flask from threading import Thread import json, random, sys, time, hashlib app = Flask(__name__) @app.route('/OTR/api/v1.0/otr/<string:api_key>',methods=['GET']) def get_otr(api_key): if auth_api_key(api_key) == True: OTR = create_one_time_rotor_setting() ...
import os import gensim from collections import Counter from typing import Dict, List import torch from torchtext.vocab import Vocab from torchtext.data import Field, BucketIterator, NestedField from torchtext.datasets import SequenceTaggingDataset class BuildData: __datanames__ = ["train.txt", "dev.txt", "test....
import argparse import itertools import os import time from multiprocessing import Pool import numpy as np import torch def iou(i, m2): for j in range(m2): shared_array[i][j] = np.minimum(I1[i], I2[j]).sum() / np.maximum(I1[i], I2[j]).sum() def iou_bin(m1, j, I_1, I_2): for i in range(m1): ...
""" Created on 28 Oct 2017 @author: <NAME> (<EMAIL>) example: { "on": true, "bri": 254, "hue": 8418, "sat": 140, "effect": "none", "xy": [0.4573, 0.41], "ct": 366, "alert": "select", "color_mode": "ct", "reachable": true } """ from collections import OrderedDict from scs_core...
import json import unittest import os from md_utils import data2pdb from md_utils.data2pdb import main from md_utils.md_common import diff_lines, silent_remove, capture_stdout, capture_stderr import logging # logging.basicConfig(level=logging.DEBUG) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__...
""" tools to manipulte data files includes bin, trim, stitch, etc also include interpolation stuff """ import numpy as np from scipy import stats from scipy import interpolate def trim_data(xlist,ylist,up,down): for i,info in enumerate(xlist): if info > up: start = i ...
# search.py # --------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # A...
#!/usr/bin/env python # # Example of one object under gravity with one contactor and a ground # using the Siconos proposed mechanics API # from siconos.mechanics.collision.convexhull import ConvexHull2d from siconos.mechanics.collision.tools import Contactor from siconos.io.mechanics_run import MechanicsHdf5Runner imp...
import os from jinja2 import Template import pandas as pd from bokeh.plotting import figure, output_file, save from bokeh.models import BoxZoomTool, ResetTool, PanTool from bokeh.models import WheelZoomTool def generate_html_page(html_folder, html_folder_gene, html_folder_protein, rna_seq_file, name_column_rna, ...
import shutil import hashlib import json import os import logging from logging.handlers import RotatingFileHandler import numpy as np def override_config_recurs(config, config_extension): try: config_extension['name'] = config['name']+'_'+config_extension['name'] except KeyError: pass fo...