text
stringlengths
3.07k
12.6k
# adapted from SVM from Scratch in Python by <NAME> # https://medium.com/deep-math-machine-learning-ai/chapter-3-1-svm-from-scratch-in-python-86f93f853dc from matplotlib import pyplot as plt from sklearn.datasets.samples_generator import make_blobs import math import numpy as np def SVM_Training(data_dict, ...
"""SCons.Tool.xetex Tool-specific initialization for xelatex. Generates .pdf files from .latex or .ltx files There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # __COPYRIGHT__ # # Permission is hereby granted...
import os import zipfile from .metadata import Metadata from .util import hash_zip class MetadataNotFoundError(Exception): """ Thrown when no metadata was found in the data container loaded """ class DataContainer: """ Represents a data container which holds both data and metadata. Responsibi...
""" Inventory Steps Steps file for Inventory.feature """ from os import getenv import logging import json import requests from behave import * from compare import expect, ensure from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support.ui impor...
from flask_wtf import FlaskForm from flask_wtf.file import FileField, FileRequired, FileAllowed from wtforms import (BooleanField, SelectField, SubmitField, IntegerField, DecimalField, RadioField, StringField, validators) from wtforms.validators import DataRequired from flask_uploads import UploadSet, ARCHIVES fro...
#!/usr/bin/env python import argparse import os import shutil import time from Dataset import CtDataset #from utils.loss import DiceLoss from utils.diceloss import DiceLoss import vnet import torch import torch.nn as nn import torchvision.transforms as transforms import torch.optim as optim import torch.utils.data a...
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
# Imports from scipy.io import loadmat from scipy.signal import fftconvolve import numpy as np import gc as garbageCollector ######################################################################################################################## # Load signals from a specific file in the source files # Convenience fu...
import os import queue import shlex import select import threading as mt import subprocess as sp from .constants import RUNNING, DONE, FAILED from .misc import is_string # ------------------------------------------------------------------------------ # def sh_callout(cmd, stdout=True, stderr=True, shell=Fals...
import datetime import os from django.conf import settings # Logging setup if not os.path.isdir(f"{settings.BASE_DIR}/logs/"): os.makedirs(f"{settings.BASE_DIR}/logs/") log_file_no = 1 while True: if not os.path.isfile(f"{settings.BASE_DIR}/logs/python_log_{log_file_no:03d}.txt"): log_file_no -= 1 ...
""" LO-PHI's database interface (and extra functions) for tracking binary files and analysis jobs (c) 2015 Massachusetts Institute of Technology """ # Native import shutil import random import string import os import errno import time import logging logger = logging.getLogger(__name__) # LO-PHI import l...
from PyQt5 import QtWidgets, QtCore from xldigest.widgets.returns_tab_ui import Ui_ReturnsUI from xldigest.database.base_queries import (project_names_per_quarter, single_project_data) # All this from https://www.youtube.com/watch?v=VcN94yMOkyU&t=71s class Node: def ...
# -*- coding: utf-8 -*- # Copyright (c) 2016, 2017, 2018, 2019 Sqreen. All rights reserved. # Please refer to our terms for more information: # # https://www.sqreen.io/terms.html # """ Low-level HTTP interaction with sqreen API """ import codecs import collections import json import os import sys from datetime impo...
import validators, requests, re # Import external import apikey, wifi, url, file # Import local from io import BytesIO apikey = apikey.apikey() url_class = None wifi_class = None file_class = None headers = {"Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded", "x-apikey": apikey} ...
import sys from absl import flags import baselines.common.tf_util as U import numpy as np from baselines import deepq from baselines_legacy import cnn_to_mlp, BatchInput from pysc2.env import environment from pysc2.env import sc2_env from pysc2.lib import actions from pysc2.lib import actions as sc2_actions from pysc2...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import math import os import random import zipfile import cPickle as pickle import numpy as np from six.moves import urllib from six.moves import xrange # pylint: disable from scipy.sparse i...
import csv from twitter_specials import * from math import * import string word_counts_dict = {} # "word": [positive, negative, neutral, irrelevant, total counts] category_to_num = {"positive": 0, "negative":1, "neutral":2, "irrelevant": 3} num_to_category = {0: "positive", 1: "negative", 2: "neutral", 3: "irrelevant"...
""" Migrating database """ import datetime from typing import Optional, Set from django.db import DEFAULT_DB_ALIAS as DJANGO_DEFAULT_DB_ALIAS from django.db.models.signals import post_migrate from django.dispatch import receiver # In order to support all operations import here from infi.clickhouse_orm.migrations impo...
import time # read sudo file to list def read_sudo_file(in_file): original_sudo = [] with open(in_file,'r',encoding='utf-8') as f: lines = f.readlines() for line in lines: line = line.strip() if not line: continue one_sudo = [] for...
# asteroid game from PIL import ImageFont, ImageDraw, Image import cv2 import random import numpy as np import pathlib from playsound import playsound class AsteroidGame: def __init__(self, width, height): self.asteroid_image = cv2.imread('assets/asteroid.png', cv2.IMREAD_UNCHANGED) self.astero...
# cython: language_level=3 # cython: boundscheck=False # cython: wraparound=False # cython: initializedcheck=False # cython: cdivision = True # cython: always_allow_keywords =False # cython: unraisable_tracebacks = False # cython: binding = False import cython if cython.compiled: from cython.cimports.cpython impo...
import warnings from multiprocessing import Queue import numpy as np import spacy from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.decomposition import NMF, LatentDirichletAllocation warnings.filterwarnings("ignore", category=DeprecationWarning) warnings.filterwarnings("ignore...
from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from collections import defaultdict import random as r import math as m import numpy as np from keras import backend as K from random import Random INTERVENTION_SIM_THRESHOLD=0.1 MAXLEN = 50 SEED=314159 # first digits...
import requests from datetime import datetime, timedelta from requests.auth import HTTPBasicAuth from django.db.models import Count from django.conf import settings from django.views.decorators.csrf import csrf_exempt from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse from rest_f...
import copy from queue import Queue import time import pickle from base import Network # import matplotlib.pyplot as plt from info_str import NAS_CONFIG # from .base import NetworkUnit, NETWORK_POOL # TODO Please fix your variables and functions naming. # Ref: Google Code Style (Python) - Python 風格規範 “命名...
from __future__ import annotations from typing import Any, List import yaml from pydantic import BaseModel def _from_file(path: str, typ: Any) -> Any: with open(path, "r") as f: raw_config = yaml.load(f, Loader=yaml.Loader) return typ(**raw_config) class GenericQDeviceConfig(BaseModel): # ...
import fire import os from deepar.dataset.time_series import TimeSeries, TimeSeriesTest import pandas as pd import numpy as np from deepar.model.learner import DeepARLearner from sklearn.metrics import mean_squared_error from math import sqrt import sys import tensorflow as tf from tensorboard.plugins.hparams import ap...
import torch import pandas as pd from sklearn.model_selection import train_test_split import torch.nn as nn import torch.nn.functional as F import torch.optim as optim unique_tags =['PRP$', 'WP$', 'JJR', 'VBP', 'FW', 'IN', 'NNS', 'VBD', 'VBG', 'LRB', 'WP', 'RP', 'NNP', 'JJS', 'PDT', 'RBS', 'PRP', 'DT', 'CD', 'NN', 'VB...
import os, cv2, shutil import numpy as np import argparse def read_coords(coord_file): coord_data, inds_pos = [], [] assert os.path.exists(coord_file), "File does not exist! %s"%coord_file with open(coord_file, 'r') as f: for ind, line in enumerate(f.readlines()): x_coord = int(line.str...
import matplotlib import matplotlib.pyplot as plt import os import random import io import imageio import glob import scipy.misc import numpy as np from six import BytesIO from PIL import Image, ImageDraw, ImageFont from IPython.display import display, Javascript from IPython.display import Image as IPyImage import t...
import os import pandas as pd import numpy as np import warnings import math from sklearn.ensemble import ExtraTreesRegressor, AdaBoostRegressor, GradientBoostingRegressor, RandomForestRegressor from sklearn.model_selection import KFold, LeaveOneGroupOut, GroupKFold from sklearn.model_selection import cross_val_score,...
import torch import torch.nn as nn import numpy as np import torch.nn.functional as F from torch.autograd import Variable from model.models import FewShotModel class BidirectionalLSTM(nn.Module): def __init__(self, layer_sizes, vector_dim): super(BidirectionalLSTM, self).__init__() """ ...
from tkinter import Tk, Canvas, Button from random import randint, random from PIL import ImageTk, Image import time POCET = 50 # POCET_MIN = 10 VELIKOST = int(500/POCET) OBTIZNOST = 0.1 BARVY = [ "#000", "blue", "green", "red", "#007", "brown", "#A4A", "yellow", "black" ] flaged =...
import os import time import csv import requests from logger import logger from parsing_gpx import get_gpx_activity_type from parsing_json import get_json_activity_type from parsing_csv import parsing_data_from_csv URL_CREATE_ACTIVITY = 'https://www.strava.com/api/v3/activities' URL_UPLOADS = 'https://www.strava.co...
import os import cv2 import numpy as np def pad_to_square(image): """ Pad image to square shape. """ height, width = image.shape[:2] if width < height: border_width = (height - width) // 2 image = cv2.copyMakeBorder(image, 0, 0, border_width, border_width, ...
#!/usr/bin/env python3 import pygame from pygame import mixer import random import math # Initialize the pygames library pygame.init() # create our first screen screen = pygame.display.set_mode((800, 600)) # Background background = pygame.image.load('Sprites/background.png') # Sound mixer.music.load("Sounds/backgr...
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under t...
""" """ from collections import defaultdict import logging import os from ctseg.config import DEFAULT_CONFIG logger = logging.getLogger(__name__) def validate_schema(d): """Validate the schema of a config dict against the DEFAULT_CONFIG Args: d (dict): the config to validate Raises: ...
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import datetime import json import mock from components import utils utils.fix_protobuf_package() from test import test_util from testing_utils import test...
import matplotlib.pyplot as plt import numpy as np from RBSpy import rbsSpectra import RBSpy.rbsAux as raux class multi_rbs(): def __init__(self, file_path_array, type_file = 'exp', offset = 90, **kwarg): self.file_path_array = file_path_array self.type_file = type_file self.offset = off...
import os import sys import importlib import logging from http import HTTPStatus as status from functools import wraps # from flask_restful import Resource, Api from flask import jsonify, request from . import openflix_config as config from . import db from . import app from .openflix_utils import route from .interfa...
import sys sys.path.append("/scratch/wdjo224/deep_protein_binding") import os import torch from torch.utils.data.sampler import SubsetRandomSampler import numpy as np import pandas as pd from torch.utils.data import DataLoader from src.utils import get_parser, update_tensorboard, collate_fn, get_loss from src.MoleculeD...
"""Keras implementation of TextBoxes++.""" from keras.layers import Activation from keras.layers import Conv2D from keras.layers import Dense from keras.layers import Flatten from keras.layers import GlobalAveragePooling2D from keras.layers import Input from keras.layers import MaxPooling2D from keras.layers import co...
#!/usr/bin/env python3 # coding:utf-8 import asyncio import functools import logging;logging.basicConfig(level=logging.INFO) import inspect import os from aiohttp import web from myerror import APIError # 定义url处理函数,添加请求方式标记;按RESTFULL规定,有四种请求GET,POST,PUT,DELETE def re_method(path, *, method): def decorator(func):...
import json import logging import time from multiprocessing import Process, Queue from time import sleep from unittest import TestCase, mock from unittest.mock import call from hoststats.app import app from hoststats.collection import SLEEP_INTERVAL_MS, collect_metrics from hoststats.stats import FORWARD_HEADER SLEEP...
# # Calibration of CIR85 model # to Euribor Rates from 30. September 2014 # 11_cal/CIR_calibration.py # # (c) Dr. <NAME> # Derivatives Analytics with Python # import sys sys.path.append('10_mcs') import math import numpy as np np.set_printoptions(suppress=True, formatter={'all': lambda x: '%7.6f' % ...
import gym import time import keyboard import math import random import matplotlib.pyplot as plt class QLearning: def __init__(self): self.exploration = 0.6 self.learning_rate = 0.3 self.discount_rate = 0.99 self.degrees = [2 * math.pi * x / 360 for x in range(360)] self.st...
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import select import logging log = logging.getLogger(__name__) class Server: def __init__(self, relays, timeout=0.3): self._relays = list(relays) self.timeout = timeout self.input_map = {} self.links = {} def main_...
import sys import importlib import click @click.group() def main(): pass def extra_commands_callback_decorator(callback): def _callback(*args, **kwargs): exit(0 if callback(*args, **kwargs) else 1) return _callback kubernetes_not_configured = False for daemon in [ {'name': 'initializer'...
import abc import tkinter as tk from tkinter import font as tkfont import logging as log import sys FORMAT = '[%(asctime)s] [%(levelname)s] : %(message)s' log.basicConfig(stream=sys.stdout, level=log.DEBUG, format=FORMAT) class TitlePage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init...
import re import random from math import ceil from typing import Callable, Optional from sys import stdin from dataclasses import dataclass from syllable import Syllable, HEH_SYLLABLES, MAX_SIMILARITY from constants import HEH_LEVEL, HEH_RATE, VOWELS, CONSONANTS settings: Optional['Settings'] = None @dataclass clas...
import objects from os import listdir from datetime import datetime def choose_account(): exit_bol = False while True: account_number_choice = input('what account should this statement go to? >> ') try: result_account = objects.Account.objects.get(number=int(account_number_choice)...
# -*- coding: utf-8 -*- import pytest import os from datetime import datetime from slickqa import * def pytest_addoption(parser): group = parser.getgroup('slickqa') env = os.environ group.addoption("--slick-url", action="store", default=env.get('SLICK_URL'), metavar="SLICK_URL", dest=...
# Copyright 2006-2012 <NAME> # this module is tested by pycbio/src/progs/gbff/gbffGenesToGenePred from pycbio.sys import PycbioException from Bio import SeqFeature class GbffExcept(PycbioException): pass def featHaveQual(feat, key): "does a feature have a qualifier?" return (key in feat.qualifiers) ...
import networkx as nx import matplotlib.pyplot as plt import numpy as np import random from scipy import stats from sklearn.metrics import mutual_info_score np.set_printoptions(precision=4) class Mimic(object): """ Usage: from mimicry import Mimic :param domain: list of tuples containing the min and max...
""" Usage example: ```sh # To train model on all words: python model.py "${HOME}/ml-data/speech-command-browser" 232 # To train model on a subset of the words (in addition to _background_noise # and _unknown_): python model.py \ --include_words=left,right,up,down \ "${HOME}/ml-data/speech-command-browser" 232...
""" Script for filtering key term matched documents from S2 corpus. inCitations -> citations outCitations -> references @author: <NAME> """ import os import json import codecs import re from langdetect import detect import pandas as pd def readTxtFile(filePath): fileObject = codecs.open(filePath,"r", "utf-8") ...
""" Generator ========= """ import pygame pygame.init() SIZES = [12, 15, 20] FAMILIES = ( "Ubuntu", "Ubuntu Condensed", "Ubuntu Mono", "Bookerly", "Press Start 2P", ) FONTS = [] for font in FAMILIES: for size in SIZES: FONTS.append((font, size)) SAMPLE_TEXT = "micropython-...
import random import math import numpy as np from environment.core import World, BranchyModel, Service, Agent, BaseStation from environment.hyperParameters import RHO, DROP_PENALTY, ACCURACY_PENALTY # branchy DNN model info #COMP_INTENSITY = [97, 124, 139, 165] COMP_INTENSITY = [100, 150, 200, 250] ACC_TABLE = [0.59 ,...
import pandas as pd import lightgbm as lgb import gc ################################################## # LightGBM model declaration # ################################################## def lgb_modelfit_nocv(params, dtrain, dvalid, predictors, target='target', objective='binary', metrics='...
""" oTree page extensions. March 2021, <NAME> <<EMAIL>> """ import settings from django import forms from django.utils.translation import ugettext as _ from otree.api import Page, WaitPage APPS_DEBUG = getattr(settings, 'APPS_DEBUG', False) class AllGroupsWaitPage(WaitPage): """A wait page that waits for al...
from click.testing import CliRunner import pytest from javaproperties_cli.__main__ import javaproperties INPUT = ( b"foo = bar \n" b"test \n" b" baz = glarch \\\n" b" quux \\\n" b" # comment\n" b"xyzzy\n" b"\n" b"plugh = plo\\\n" b" ver \\\n" b" \\\n" b" s...
from sdurw_proximity import * from sdurw import * from sdurw_proximitystrategies import* import time CDQueryType = ["AllContactsFullInfo","AllContanctsNoInfo","FirstContactFullInfo","FirstContactNoInfo"] CSQueryType = ["FirstContact","AllContacts"] def printPSD(data:"ProximityStrategyData"): print(" Proximity...
import bz2 import gzip import io import lzma import os import psutil import pytest import pshell as sh compression_param = pytest.mark.parametrize( "openfunc,ext,compression", [ (open, "", "auto"), (gzip.open, ".gz", "auto"), (bz2.open, ".bz2", "auto"), (lzma.open, ".xz", "aut...
"""Sloan course catalog ETL""" import logging import re from datetime import datetime from decimal import Decimal from urllib.parse import urljoin import requests from bs4 import BeautifulSoup as bs from django.conf import settings from course_catalog.constants import OfferedBy, PlatformType, see_edx_mapping from cou...
"""Preprocessing of training and validation data sets.""" import os import csv import random import scipy import numpy as np import dicom from .image_op import gen_augmented_frames # TODO handle sax files with n != 30 dicom images # TODO explore 2ch and 4ch folders # TODO order images by slice depth def gen_fram...
''' Command line interface to the ACME data processing pipeline ''' import sys import argparse import glob import os import os.path as op import time import logging import warnings import multiprocessing from pathlib import Path from sys import platform from tqdm import tqdm sys.path.append(op.dirname(op.dirna...
#!/usr/bin/python # -*- coding: utf-8 -*- # # The MIT License (MIT) # # Copyright (c) 2015 Tintri, 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 withou...
"""\ Spacers to use in sizers @copyright: 2002-2007 <NAME> @copyright: 2014-2016 <NAME> @copyright: 2016-2019 <NAME> @license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY """ import wx import common, misc from tree import Node import new_properties as np from edit_windows import ManagedBase class Ed...
import gd import time import datetime import sys import os import json from json_abs import * from db import * from cep import * import discord from discord.ext import commands F_CONFIG = 'config' F_SQL = 'modbuddy.sqlite' intents = discord.Intents.default() intents.members = True bot_prefix = "??" client = commands....
#!/usr/bin/env python3 import os import re import sys import send2trash import time #To do: implement this into the docker pipeline as an option #inputs: fasta_file = "repset.fasta" taxonomy_file = "repset.taxonomy.txt" mapping_file = "readyForQiime.allsamples_otus.txt" #warning: warning_message = "This program req...
from typing import Union, Dict, Any, Optional import numpy as np import networkx as nx import pandas as pd from geopy.distance import distance import matplotlib.pyplot as plt from optinet import mutate from optinet import cross_section def gaussian(x, mu, sig): return np.exp(-np.power(x - mu, 2.) / (2 * np.powe...
# Copyright 2021 Population Health Sciences and Image Analysis, German Center for Neurodegenerative Diseases(DZNE) # # 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://...
from twitchio.ext import commands import asyncio import csv import tempfile import os import sys import subprocess from obswebsocket import obsws, requests, events import zipfile from pathlib import Path import threading import signal import time import my_settings global plz_stop plz_stop = False printing = "Loa...
# Import all modukes that needed for this solution import requests import json import urllib import os import pandas as pd from dns import resolver import re import socket import smtplib # Import Configuration from config import apikey as hapikey from config import smtp_host from config import filename from config im...
from io import StringIO from contexts.plugins.reporting import cli from contexts import action from .. import tools class VerboseReporterSharedContext: def context(self): self.stringio = StringIO() self.reporter = cli.VerboseReporter(self.stringio) self.outputs = [] class WhenPrintingVer...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: <NAME> @organization: CHArt - Université Paris 8 """ from Box2D import b2 from Box2D import (b2Body, b2World, b2Vec2) import numpy as np """ Vehicle based on Chris Campbell's tutorial from iforce2d.net: http://www.iforce2d.net/b2dtut/top-down-car """ class Tir...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import glob import numpy as np import six from scipy.fftpack import fft from scipy.io import wavfile import chainer import chainer.functions as F import chainer.links as L from chainer import computational_graph from chainer import ...
import datetime import pkg_resources import alabaster import ablog ablog_builder = 'dirhtml' ablog_website = '_website' project = 'PyGears' this_year = datetime.date.today().year copyright = f'{this_year}, <NAME>' author = '<NAME>' version = pkg_resources.get_distribution("pygears").version release = version extens...
import requests import ast import shutil import traceback as tb import time import pandas as pd from slugify import slugify import os LGTM_ACCESS_TOKEN="62a92b7d201c7def5c1ae347e254cc35345f8a24e7db0a19744b0d4d7193c5ad" lgtm_session = requests.Session() lgtm_session.headers.update({'authorization': 'bearer ' + LGTM_ACC...
# process scene graph annotations of CLEVR # each attribute value (e.g. 'blue') is considered as a **special node**, whose v_h is one-hot vector # in every scene, att nodes are after object nodes and index from len(objects) # each attribute field/type (e.g. 'color') is considered as a special relationship # object attr...
#!/usr/bin/env python 3 # -*- coding: utf-8 -*- # # Copyright (c) 2021 PanXu, Inc. All Rights Reserved # """ 图注意力模型 Authors: PanXu Date: 2021/02/14 10:00:00 """ import torch from torch import nn from torch.nn import Dropout, Parameter, Linear, LeakyReLU, ModuleList from torch.nn import ELU, LogSoftmax import torc...
import logging import multiprocessing as mp import sys from typing import Any, List import io import numpy as np import pandas as pd from tqdm import tqdm import matplotlib.pyplot as plt import vis from preprocessing import center_crop from synthetic import SyntheticPSF from wavefront import Wavefront logging.basic...
#!/usr/bin/python3 import os import subprocess import docker import utils import signal def setup(coin, stage): os.chdir(f"../docker-compose/{stage}") print(f"Starting {coin}_{stage}_api node...") sp = subprocess.Popen(["docker-compose", "-f", f"{coin}.yml", "-p", f"{coin}_{stage}_api", "up", "--build", "...
import tensorflow as tf import scipy as sp import numpy as np import pandas as pd import re import hashlib from sklearn.preprocessing import StandardScaler import librosa import os from pathlib import Path import IPython.display as ipd import cProfile import numpy as np # linear algebra import pandas as pd # data ...
import numpy as np import tensorflow as tf from mher.algos.sac_utils import apply_squashing_func, mlp_gaussian_policy from mher.algos.util import nn, store_args class ActorCritic: @store_args def __init__(self, inputs_tf, dimo, dimg, dimu, max_u, o_stats, g_stats, hidden, layers, sess): """The actor-...
# https://github.com/marc1701/area-beamforming/blob/SRP_dev/utilities.py import numpy as np from scipy.spatial.distance import cdist # golden ratio R = (1 + np.sqrt(5)) / 2 def cart_to_sph(cart_co_ords, return_r=False): # transformation between co-ordinate systems x, y, z = cart_co_ords[:,0], cart_co_ords[:,1]...
from parcels import FieldSet, ParticleSet, JITParticle from parcels import Variable, ErrorCode, Field from datetime import timedelta from datetime import datetime from parcels import GeographicPolar, Geographic import numpy as np import sys import local_kernels as kernels import xarray as xr series = 8 resusTime = 171...
import numpy as np import random from generate import generate from search import query from search import makeMove flat = 1 hilly = 2 forested = 3 caves = 4 def manhattanDistance(x1,y1,x2,y2): delta_x = abs(x2-x1) delta_y = abs(y2-y1) return delta_x+delta_y def move(x1,y1,x2,y2): if x1==x2 and y1==...
# Copyright 2018 <NAME> <<EMAIL>> # # 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 writ...
""" Demo Flask application to test the operation of Flask with socket.io Aim is to create a webpage that is constantly updated with random numbers from a background python process. 30th May 2014 =================== Updated 13th April 2018 + Upgraded code to Python 3 + Used Python3 SocketIO implementation + Updated...
import os from bellbird.equation import * from bellbird.operators import * from bellbird.writer import Writer class Model: def __init__(self, name, equationsStr, variables, properties, boundaryConditions, definitions=[], meshPath="", sparse=False, timeStep=0.1, tolerance=1e-4, maxNumberOfIterations=300): """ - D...
""" pybiotransformer/wrapper.py <NAME> 2018/11/19 description: Python wrapper (class) for using BioTransformer to identify drug metabolites. """ from subprocess import run, DEVNULL from tempfile import NamedTemporaryFile from csv import DictReader import os class PBTMetabolite: """ PBTM...
#!/usr/bin/python3 import datetime, threading, time import statistics import RPi.GPIO as GPIO import sys, os import signal import requests import json import logging ############################################################################### # function: test_threshold - will send a notification if a threshold is ...
from io import BytesIO from random import randint import pytest from d2lib.utils import ( ReverseBitReader, _BytesJSONEncoder, _reverse_bits, calc_bits_to_align, is_set_bit, obj_to_dict, read_null_term_bstr, stripped_string_concat, to_dict_list, ) TEST_STRING = b'ReadNullTermStr' ...
# Copyright 2008-2018 Univa 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...
# coding: utf-8 # In[1]: """ Ingest the inundation maps to earthegine ------------------------------------------------------------------------------- Author: <NAME> Date: 20180816 Kernel: python35 Docker: rutgerhofste/gisdocker:ubuntu16.04 Args: SCRIPT_NAME (string) : Script name OUTPUT_VERSION (integer)...
# -*- coding: utf-8 -*- """ Created on Sun Feb 13 16:28:38 2022 @author: vedhs """ #Imports import tkinter as tk import numpy as np import data import cv2 from PIL import Image, ImageTk import queue, threading # bufferless VideoCapture class VideoCapture: def __init__(self, ip): #Setting width and height ...
from __future__ import absolute_import from __future__ import division # Copyright (c) 2010-2014 openpyxl # # 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 wit...
""" This module provides a Splunk Modular input that operates a DNS proxy. The DNS proxy logs requests and replies in Splunk. """ import sys import os import binascii path_to_mod_input_lib = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'modular_input.zip') sys.path.insert(0, path_to_mod_input_lib) from mo...