text
stringlengths
3.07k
12.6k
import numpy as np import tensorflow as tf import time from common import * from _datetime import timedelta def new_weights(shape,name): return tf.Variable(tf.truncated_normal(shape, stddev=0.05), name=name) def new_biases(length,name): return tf.Variable(tf.constant(0.05, shape=[length]), name=name) def new...
#!/usr/bin/env python3 import itertools import re __all__ = [ 'Puzzle3', 'Puzzle8', 'Puzzle15', 'puzzle_class', 'make_puzzle', 'read_puzzle', 'write_puzzle', ] from .config import config_getkey from .driver import make_driver, Node from .utils import ( flatten, ) class PuzzleMeta(t...
""" Process a pickled DataFrame of annotations so that the labels assigned by the annotators (`label` column) are parsed into separate columns (e.g. `ENR`, `ENR_lvl`, 'background', etc.). Save the resulting parsed DataFrame in pkl format. The input pickled DataFrame is created from a batch of annotated tsv files with ...
import torch from torch import nn from utils import compute_gradient_penalty, optimizer_to from block import Block, ResBlock class Generator(nn.Module): def __init__(self, domain_dim: int, begin_conv_dim: int): super().__init__() self.begin_layers = Block(domain_dim + 3, begin_conv_dim, ...
from django.db import models from phone_field import PhoneField from localflavor.in_.models import INStateField from django.core.mail import send_mail GENDER_CHOICES = ( ("Male", "Male"), ("Female", "Female"), ("Other", "Other"), ) # Create your models here. class Student(models.Model): id = models.A...
# coding=utf-8 #! /usr/bin/env python3.4 """ MIT License Copyright (c) 2018 NLX-Group 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...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jun 18 12:40:54 2018 reference: https://github.com/prateekroy/Computer-Vision/blob/master/HW3/ detection_tracking.py @author: lrianu """ # import sys import cv2 import numpy as np # Read the video file video = cv2.VideoCapture('FishVideo.mp4') file_na...
import sys, os, pkg_resources, zipfile from PIL import Image from PyQt5 import QtCore from PyQt5.QtGui import QPixmap, QIcon from PyQt5.QtWidgets import QMainWindow, QApplication, QLabel, QFileDialog ,QPushButton,QListWidget, QCheckBox, QListWidgetItem, QComboBox """This section is needed so relative paths still work...
""" These are utility functions for doing dense prediction of an image. We want to take multiple crops from the image and process them. We want to take the union of all proposals, and then do some non-max-suppression. """ from matplotlib import pyplot as plt import numpy as np def extract_patches(image, patch_dims...
# Copyright 2022 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...
''' a package of functions to convert data architecture formats ''' __author__ = 'rcj1492' __created__ = '2017.06' __licence__ = 'MIT' def _to_camelcase(input_string): ''' a helper method to convert python to camelcase''' camel_string = '' for i in range(len(input_string)): if input_string[i] == '_...
#%% from kdg import kdf from kdg.utils import get_ece import openml import multiprocessing from joblib import Parallel, delayed import numpy as np import pandas as pd from sklearn.model_selection import StratifiedKFold from sklearn.ensemble import RandomForestClassifier as rf from sklearn.metrics import cohen_kappa_sco...
import math from scipy.stats import norm import pandas as pd, numpy as np from datetime import date from matplotlib import ticker import matplotlib.dates as mdates def set_plot(ax): ax.set_axisbelow(True) # Turn on the minor TICKS, which are required for the minor GRID ax.minorticks_on() # Customize th...
import math import numpy as np from PIL import Image from skimage import color, io def load(image_path): """Loads an image from a file path. HINT: Look up `skimage.io.imread()` function. Args: image_path: file path to the image. Returns: out: numpy array of shape(image_height, imag...
import datetime import re from os import walk, listdir from os.path import exists, relpath, splitext import markdown from yaml import safe_load as load from babel.messages.catalog import Catalog from babel.messages.pofile import write_po, read_po from flask import safe_join from bolttools.common import UNITS def spli...
""" Only testing custom functionality not (re-)testing django model framework. Uses tests.utils.ModelTesterMixin to patch out model save() methods to make unit tests that avoid slow calls to database when testing custom save methods on models. """ from django.test import TestCase, override_settings from mixer.backend...
#!/usr/bin/env python3 """ Train ranfom forest classifier on Boston dataset """ import argparse import pickle import numpy as np import sklearn.datasets import sklearn.ensemble import sklearn.model_selection import termcolor def parse_args(): """ Parse command line arguments. Returns: args (ar...
#!/usr/bin/python # # Copyright (C) 2016 Google, Inc # Written by <NAME> <<EMAIL>> # # SPDX-License-Identifier: GPL-2.0+ # import struct import sys import fdt from fdt import Fdt, NodeBase, PropBase import fdt_util import libfdt # This deals with a device tree, presenting it as a list of Node and Prop # objects...
from .languages import Language import os import time class Compile: """ This class works as a wrapper class for receiving the run events for different languages. The main job of this class is to factor out the common patterns in various language compilation flow and called the relevant class ...
from django.contrib.auth import login, views from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.contrib.sites.shortcuts import get_current_site from django.core.mail import EmailMessage from django.http import HttpResponse from django...
import cv2 import time import secrets import numpy as np import face_recognition from models import cnn_model_2 img_file_ext = '.jpg' vid_file_ext = '.mp4' class_labels = {0: 'Anger', 1: 'disgust', 2: 'fear', 3: 'Happy', 4: 'Sad', 5: 'Surprise', 6: 'Neutral'} # load model and model.predict_class def l...
# -*- coding: utf-8 -*- """The App Engine Transport Adapter for requests. .. versionadded:: 0.6.0 This requires a version of requests >= 2.10.0 and Python 2. There are two ways to use this library: #. If you're using requests directly, you can use code like: .. code-block:: python >>> import requests ...
# The MIT License (MIT) # # Copyright (c) 2019 <NAME> for Algebra Global, Inc. # # 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 #...
# Copyright (c) 2017 Orange. # 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 a...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Readers for the pke module.""" import os import sys import json import logging import xml.etree.ElementTree as etree import spacy from pke.data_structures import Document class Reader(object): def read(self, path): raise NotImplementedError class Minim...
import gym import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from torch.utils.tensorboard import SummaryWriter # The network of the actor class Actor(nn.Module): def __init__(self, state_dim, action_dim, hidden_width): super(Actor, self).__init__() s...
""" Contains utility functions for saving / retrieving menus from / to SQL """ from datetime import datetime, timedelta import json import pymysql from menu2 import WebCrawler from menu2.models import Dish from sql import SQLConnectionHandler as sqlhandler #import serverlessHandlers.HandleMessage as messageHandler fr...
from scipy.ndimage import rotate from cil.framework import ImageGeometry from cil.framework import AcquisitionGeometry import matplotlib.pyplot as plt from scipy.fft import fft, ifft, fftshift, fftfreq, ifftshift import numpy as np from cil.utilities.display import show2D from cil.utilities import dataexample from PIL ...
from lxml import etree angular_shells = ["s", "p", "d", "f", "g", "h", "i"] class Shell: def __init__(self, lval = 0, nexp = 0, nbfs = 0): self.lval = lval self.powers = [] self.nexp = nexp self.exps = [] self.contr = [] class Atom: def __init__(self, name="X", nshells...
# This file is part of QuTiP: Quantum Toolbox in Python. # # Copyright (c) 2011 and later, <NAME> and <NAME>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # 1. Redistrib...
# from tapis_cli.main import PKG_NAME, About, VersionInfo import requests import curlify from json import JSONDecodeError from requests.auth import HTTPBasicAuth from agavepy.agave import Agave from tapis_cli.utils import print_stderr from tapis_cli.settings import TAPIS_CLI_SHOW_CURL, TAPIS_CLI_VERBOSE_ERRORS from tap...
from cv2 import reduce import pandas as pd import numpy as np import re as re from sklearn.preprocessing import StandardScaler from base import Feature, get_arguments, generate_features Feature.dir = 'features' # class Pclass(Feature): # def create_features(self): # self.train['Pclass'] = train['Pclass']...
"""housing.py framework entity module """ #print("module {0}".format(__name__)) import pdb import copy from collections import deque from ..aid.sixing import * #from .globaling import * from ..aid.odicting import odict from . import excepting from . import registering from . import storing #needed by house and f...
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appl...
#!/usr/bin/env python -W ignore::DeprecationWarning import argparse import asyncio from _weakref import ref import torchvision.transforms from absl import app from stable_baselines3.common.vec_env import CloudpickleWrapper from rgb_stacking.run import init_env import tensorflow as tf import socket from numpy import u...
import sys sys.path.append("/home/ray__/ssd/BERT/") # gpt model utils location from gpt_feat_utils import GPT_Inference import json from copy import deepcopy import pickle, json import numpy as np from scipy.spatial.distance import cosine from collections import Counter sys.path.append("../") # grouping functions mai...
import json from copy import deepcopy import sys def calinout(intermediateStates): global dfa mp=[] for x in range(len(intermediateStates)): ie=0 oe=0 for j in range(len(dfa["transition_function"])): if dfa["transition_function"][j][2] == intermediateStates[x]: ...
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
#!/usr/bin/env python u""" read_ee_phase.py Written by <NAME>' (02/2022) Compute the complex difference between two coregistered interferograms. usage: read_ee_phase.py [-h] [--directory DIRECTORY] [--outdir OUTDIR] reference secondary TEST: Compute the complex difference between two coregistered interferogra...
"""Optionally test filters.""" import logging from itertools import repeat from typing import Any, Callable, List import pytest from sunsynk.definitions import ALL_SENSORS from tests.conftest import import_module _LOGGER = logging.getLogger(__name__) MOD_FOLDER = "hass-addon-sunsynk-dev" @pytest.fixture def filter...
import os import tensorflow as tf from tensorflow import keras import cv2 import numpy as np from scipy.io import loadmat from sklearn.preprocessing import LabelBinarizer def prepare_not_mnist(): home_dir = os.path.expanduser('~') data_dir = home_dir+"/Datasets" os.system(f"gsutil cp -r gs://custom_datase...
#%% import numpy as np import pandas as pd import cremerlab.hplc import matplotlib.pyplot as plt import scipy.signal import scipy.special import scipy.stats import imp imp.reload(cremerlab.hplc) start = 0 end = 45 * 60 step = 0.5 time = np.arange(start, end, step) # Define peaks and width intensities = np.array...
#!/usr/bin/env python # -*- coding: utf-8 -*- class Digit: def __init__(self, segments): self.segments = segments def length(self): return len(self.segments) def __sub__(self, d): segments = [n for n in self.segments] for segment in d.segments: if segment in segments: segments.remove(segment) ret...
# Licensed under a 3-clause BSD style license - see LICENSE.rst """Source catalog and object base classes. """ from __future__ import absolute_import, division, print_function, unicode_literals from collections import OrderedDict from copy import deepcopy import numpy as np from ..extern import six from astropy.utils i...
# all the imports import os import re import sys import glob import time import uuid import atexit import requests import subprocess import pandas as pd import seaborn as sns import pybtex.database from datetime import datetime from contextlib import closing from numpy import array, random from os.path import abspath, ...
import time import machine from machine import I2C, Pin from leddriver import Max7219Chain from textmatrix import TextFinder from lightsensor import BH1750 from touch import TouchSensor from localtime import LocalTime from common import get_main_cfg, get_custompos_cfg CURRENT_MODE = 0 # 0: Time, 1: Temperature, 2: ...
""" Utilities for pushing models to the Hugging Face Hub ([hf.co](https://hf.co/)). """ import logging import shutil import tarfile import tempfile import zipfile from os import PathLike from pathlib import Path from typing import Optional, Union from huggingface_hub import HfApi, HfFolder, Repository from allennlp....
# -*- coding: utf-8 -*- """ Example of g-function calculation using non-uniform segment lengths along the boreholes. The g-functions of a field of 6x4 boreholes are calculated for two boundary conditions : (1) a uniform borehole wall temperature along the boreholes equal for all boreholes, and (2) an e...
""" Wrapper script around compliance-checker to automatically find and run the relevant YAML checks for AMF datasets. """ from __future__ import print_function import os import subprocess import sys import re import argparse from netCDF4 import Dataset import cchecker from amf_check_writer.spreadsheet_handler import ...
"""Graph encoders.""" import manifolds import layers.hyp_layers as hyp_layers import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import utils.math_utils as pmath from layers.layers import GraphConvolution, Linear, get_dim_act class Encoder(nn.Module): """ Encoder abstract cl...
# -*- coding: utf-8 -*- """ vitals.api.base ~~~~~~~~~~~~~~~ :author: <NAME> :copyright: © 2014-2015, Fog Mine LLC :license: Proprietary, see LICENSE for more details. templated from https://github.com/ryanolson/cookiecutter-webapp """ import logging from flask import request from flask.ext.cl...
from keras.applications import InceptionV3 from keras.models import Model from keras.layers import Input, Dropout, Dense, BatchNormalization from keras.layers import GlobalAveragePooling2D, Concatenate import tensorflow as tf import pandas as pd import os import numpy as np from sklearn.model_selection import train_tes...
import scipy.ndimage as ndimage import numpy as np from PIL import Image import pycocotools.mask as cocomask from .pycococreater import binary_mask_to_rle def __bbox_from_bboxes(bboxes: list): """ Compute the overall bbox of multiple bboxes :param bboxes: list of bounding boxes. (should be list of list) ...
import os, stat, sys import shutil import dsz, dsz.env, dsz.version import ops, ops.db, ops.survey, ops.data import util from ops.pprint import pprint BAD_PROCS = os.path.normpath(('%s/Ops/Data/bad_processes.txt' % ops.RESDIR)) def main(args): bad = [] with open(BAD_PROCS) as input: for i in input: ...
from django.db import models from django.conf import settings from django.dispatch import receiver import uuid import os import urllib from custom_storages import PublicMediaStorage from .services.create_update_delete import create_row_w_validated_params from .services.create_update_delete import update_row_w_validat...
# %% import os import traceback from ctrace.utils import calculateD, calculateExpected, calculateMILP import numpy as np from ctrace import PROJECT_ROOT from ctrace.simulation import InfectionState from ctrace.exec.param import GraphParam, SIRParam, FileParam, ParamBase, LambdaParam from ctrace.exec.parallel import Csv...
#Imports & Dependencies from splinter import Browser from bs4 import BeautifulSoup #pip install ipython #pip install nbconver import requests import pandas as pd #Site Navigation def init_browser(): executable_path = {"executable_path": '/usr/local/bin/chromedriver'} return Browser("chrome", **executable_path...
# # Copyright 2020 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
from abc import abstractmethod import json import os import shutil from typing import List, Union, cast import tarfile from numpy import source from .dockerimage import DockerImage, RemoteDockerImage from ._bindmount import BindMount def run_scriptdir_in_container(*, scriptdir: str, image_name: str, bind_...
import os import ltron.ldraw.paths as ldraw_paths from ltron.ldraw.commands import ( LDrawCommand, LDrawFileComment, LDCadSnapInclCommand, LDrawImportCommand, LDrawTriangleCommand, LDrawQuadCommand, ) from ltron.ldraw.exceptions import LDrawException class LDrawMissingFileComment(LDrawExceptio...
import unittest import numpy as np import tensorflow as tf import tensorflow_probability import mvg_distributions.gamma as custom_dist from mvg_distributions.test.test_losses_base import LossesTestBase tf_dist = tensorflow_probability.distributions tf_bij = tensorflow_probability.bijectors class TestGamma(LossesTe...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # @created: 21.05.2014 # @author: <NAME> # @contact: <EMAIL> from trseeker.tools.ngrams_tools import print_next_cutoff from trseeker.tools.ngrams_tools import print_prev_cutoff # def extend_with_consensus(kmer, kmer2tf, tf_cutoff=0, fraq_cutoff=0.0, verbose=False, lyre...
from __future__ import absolute_import from __future__ import print_function from uncertainties import ufloat, umath from pychron.processing.arar_constants import ArArConstants from six.moves import zip def mcalc_fractional_error(*args): ''' args= a,b,...,k,T where fa**2+fb**2+...+fk**2=fT**2 ...
# -*- coding: utf-8 -*- """ Project: China-idiom Creator: DoubleThunder Create time: 2019-10-12 11:45 Introduction: """ import re import pandas as pd from china_idiom.constants import ( idiom_df, clean_complie ) __all__ = [ 'is_idiom', 'is_idiom_solitaire', 'next_idioms_solitaire', 'auto_idioms_solitaire',...
#!/usr/bin/env python3 # License: CC0 import csv import re import requests import datetime PROG_MAP = {"UK": "United Kingdom", "US": "United States"} def mysql_quote(x): ''' Quote the string x using MySQL quoting rules. If x is the empty string, return "NULL". Probably not safe against maliciously formed...
''' Tasks which don't include any visuals or bmi, such as laser-only or camera-only tasks''' from riglib.experiment import LogExperiment, Sequence from features.laser_features import DigitalWave from riglib.experiment import traits import itertools import numpy as np MAX_EDGES = 1000 class Conditions(Sequence): ...
# TODO: Remove this file raise ValueError('Deprecated file') import matplotlib import numpy as np import sys from os.path import expanduser home = expanduser("~") sys.path.append(home) sys.path.append(home + '/neurogym') sys.path.append(home + '/gym') import gym from neurogym.wrappers import trial_hist from neurogym....
""" ================================ K-means clustering - PyTorch API ================================ The :meth:`pykeops.torch.LazyTensor.argmin` reduction supported by KeOps :class:`pykeops.torch.LazyTensor` allows us to perform **bruteforce nearest neighbor search** with four lines of code. It can thus be used to i...
import requests from bs4 import BeautifulSoup import lxml import pandas from datetime import datetime from datetime import timedelta import time import re reqheaders = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36', 'accept'...
import numpy as np from matplotlib import gridspec from matplotlib import pyplot as plt from abc import ABCMeta, abstractmethod from sklearn.utils.extmath import softmax from sklearn.preprocessing import LabelBinarizer from sklearn.utils.validation import check_is_fitted from sklearn.utils import check_array, check_X_...
############################################################################### # # Copyright 2014 by Shoobx, Inc. # ############################################################################### from typing import TypeVar, Dict, List, Tuple, Generic import logging import multiprocessing import functools from migrant...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from . import ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Advent of Code 2019 day 15 module.""" from collections import defaultdict from queue import Queue def get_params(mem, input_params, modes, base): params = [] for i, param in enumerate(input_params): if i >= len(modes): mode = 0 else...
# Author: <NAME> # Project: Kaggle Competition - TalkingData AdTracking Fraud Detection Challenge # File: model and predict using processed data # In[7]: import numpy as np from pyspark.sql import SparkSession, SQLContext from pyspark.sql.functions import when, sum from pyspark.ml.classification import LogisticReg...
import numpy as np import cochlea import scipy.signal #import matplotlib.pyplot as plt def peripheralSpikes(sound, par, fs = -1): if fs == -1: fs = par['periphFs'] anfTrains = cochlea.run_zilany2014(sound, fs, anf_num = [60, 25, 15], ...
from tinygrad.tensor import Tensor import tinygrad.nn as nn from extra.utils import fetch, fake_torch_load, get_child import numpy as np class BasicBlock: expansion = 1 def __init__(self, in_planes, planes, stride=1): self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=Fals...
from .db import * from flask import render_template, request, send_from_directory, url_for, redirect from flask_security import current_user, login_required import json from flask import Markup import markdown2 from .app import app import sys import os @app.route('/') def home(): txt = open('README.md', 'r', encod...
from collections import namedtuple from games import (Game) from queue import PriorityQueue from copy import deepcopy class GameState: def __init__(self, to_move, board, label=None, depth=8, score=0): self.to_move = to_move self.board = board self.label = label self.maxDepth = dept...
import inspect, os, re, time, hashlib from urllib import parse import logging from aiohttp import web from www.apis import APIError from www.model import User RE_EMAIL = re.compile(r'^[a-z0-9\.\-\_]+\@[a-z0-9\-\_]+(\.[a-z0-9\-\_]+){1,4}$') RE_SHAL = re.compile(r'^[0-9a-f]{40}$') COOKIE_NAME = 'awesome-cookie' COOKIE...
import cv2 import heapq import numpy as np def get_intersection(a, b): y = (a[1] * np.cos(b[0]) - b[1] * np.cos(a[0])) / (np.sin(a[0]) * np.cos(b[0]) - np.sin(b[0]) * np.cos(a[0])) x = (a[1] * np.sin(b[0]) - b[1] * np.sin(a[0])) / (np.cos(a[0]) * np.sin(b[0]) - np.cos(b[0]) * np.sin(a[0])) return (x, y) ...
import logging from typing import Dict, Optional, Set import asyncpg.exceptions from aiohttp import web from aiopg.sa.result import RowProxy from models_library.users import GroupID, UserID from simcore_postgres_database.errors import DatabaseError from . import users_exceptions from .db_models import GroupType from ...
import datetime from dataclasses import dataclass, field import pytz from typing import Sequence, Dict, Optional, List, Tuple from vardb.datamodel import assessment, sample, attachment from api.schemas import AlleleAssessmentSchema, ReferenceAssessmentSchema from api import ApiError import logging log = logging.get...
import os import pandas as pd from jinja2 import Environment, PackageLoader from tqdm import tqdm, tqdm_notebook from datetime import datetime import shutil import uuid import argparse from .utils_automl import * def automl_grid_search(csv_path, target_field, target_metric=None, ...
from itertools import chain from lazylawyer.nlp.helpers import cosine_similarity from lazylawyer.models.word2vec_training_dataset import Word2VecTrainingDataset import numpy as np import os import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.opt...
from gensim.corpora import Dictionary from src.clean_text import TextCleaner from gensim.models import TfidfModel, LsiModel, LdaModel from gensim.similarities import MatrixSimilarity from src.clean_tools import * from abc import abstractmethod class WikiModel: def __init__(self, wiki_tokens_path='data/token_sents...
from policy.picker import pick_clear, pick_strike from plays.defense.defense import Defense from rlutilities.linear_algebra import dot, norm from rlutilities.simulation import Car from util.game_info import GameInfo from util.intercept import Intercept from tools.vector_math import align, ground, ground_distanc...
import pandas as pd import numpy as np class EMA_class: def __init__(self,df, base, target, period, alpha=False): self.df=df self.base=base self.target=target self.period=period self.alpha=alpha def EMA(self): con = pd.concat([self.df[:self.period][self.base].ro...
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
import asyncio, telnetlib3 import re import sys import traceback import datetime import time import json from sqlalchemy import create_engine import os import threading class CustomRoutine: device = None db = None table = None # Load Config Elements param_interest_power = ["LED[0-99]_P", "vRELAY...
# coding=utf-8 """ 定义VGG16网络层 """ import tensorflow as tf import tools def VGG16(x, n_classes, is_pretrain=True): """ :param x: 输入数据 :param n_classes: 输出类别数量 :param is_pretrain: 是否对网络层进行训练 :return: 输出向量 """ x = tools.conv('conv1_1', x, 64, kernel_size=[3,3], stride=[1,1,1,1], is_pretrain...
from pygp_retina.rgc import RGC import cv2 import pickle as pickle import numpy as np if False: from typing import Tuple, List, Any import math #https://isotope11.com/blog/storing-surf-sift-orb-keypoints-using-opencv-in-python def pickle_keypoints(keypoints, descriptors): i = 0 temp_array = [] for poin...
from grafana_api.grafana_api import GrafanaClientError, GrafanaBadInputError from grafana_api.grafana_face import GrafanaFace from .config import * from .helpers import * import logging grafana_api = "" configuration = "" logger = logging.getLogger() logger_mut = logging.getLogger("mutate") def setup_grafana(config_...
import os import sys import urllib.request import re import socket from concurrent.futures import ThreadPoolExecutor from time import gmtime, strftime, time from typing import List, Optional, Union def get_size(start_path: str) -> int: total_size = 0 for dirpath, _, filenames in os.walk(start_path): ...
from __future__ import print_function #import sys import os import os.path as op import traceback #from os import listdir #from os.path import isfile, join import re import logging from seqcluster.libs.classes import sequence_unique from seqcluster.libs.classes import quality from seqcluster.libs.fastq import is_fastq,...
import numpy as np from PyQt5 import QtCore, QtGui, QtWidgets from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import struct import pyaudio from scipy.fftpack import fft import peakutils import padasip as pa #separate timer class to handle 'multi-threading' class Thread(QtCore.QThread): def __init__(s...
# Copyright (c) 2013, erpcloud.systems and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ def execute(filters=None): columns, data = [], [] columns=get_columns() data=get_data(filters,columns) return columns, data def get_...
from smach_based_introspection_framework.offline_part.model_training import train_anomaly_classifier from smach_based_introspection_framework._constant import ( anomaly_classification_feature_selection_folder, ) from smach_based_introspection_framework.configurables import model_type, model_config, score_metric fro...
from datetime import datetime import os import reframe as rfm import reframe.utility.sanity as sn class HelloWorldBaseTest(rfm.RegressionTest): lang = parameter(['c', 'cpp', 'f90']) prgenv_flags = {} sourcepath = 'hello_world' build_system = 'SingleSource' prebuild_cmds = ['_rfm_build_time="$(date...
# impy - a post-processor for HYADES implosion simulations # Copyright (c) Massachusetts Institute of Technology / <NAME> # Distributed under the MIT License __author__ = '<NAME>' import tkinter as tk import tkinter.font as tkFont import tkinter.ttk as ttk import platform def __sortby__(tree, col, descending): "...
import numpy as np from matplotlib import cm from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d, axis3d, proj3d from sklearn import decomposition from mpl_toolkits.mplot3d import Axes3D from matplotlib.patches import FancyArrowPatch def colormap_2d(length_x=40, length_y=40): x = np.lins...