text
stringlengths
3.07k
12.6k
# -*- coding: utf-8 -*- """ Created on Tue Jun 16 18:26:18 2020 @author: Wilson """ import json, requests, time, random from pytube import YouTube from datetime import datetime from sys import exit import re, io count = 0 countDL = 0 countSkip = 0 starttime = datetime.now() #random timer wait def wait(start, end): ...
from mcot.core.surface.test_data import rectangle from mcot.core.surface.grid import closest_surface, intersect, intersect_resolution import numpy as np def generate_closest(mesh, arrc, slices, notslices=None): print(arrc) if notslices is None: notslices = (slice(0, 0), slice(0, 0)) eslices = list...
import csv import cv2 import numpy as np import sklearn import seaborn as sns import matplotlib.pyplot as plt from skimage import transform from sklearn.model_selection import train_test_split from random import shuffle DATA_PATH = './data/data1/' # sample are line from driving_log.csv. # the format are [center_img...
from .. import util import os from shapely.geometry import Point import pyproj import csv import fiona import geojson TEST_FP = os.path.dirname(os.path.abspath(__file__)) def test_read_geojson(): res = util.read_geojson(TEST_FP + '/data/processed/maps/inters.geojson') assert len(res) == 6 assert type(re...
# # Pyserini: Reproducible IR research with sparse and dense representations # # 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...
import json import requests import click from haiku_node.babel.babel_db import (BabelDatabase, default_db as default_babel_db) from haiku_node.blockchain.eos.mother import UnificationMother from haiku_node.blockchain.eos.uapp import UnificationUapp from haiku_node.client import ...
import mxnet as mx import argparse import logging import os # load data def get_mnist_iter(args): train_image = os.path.join(args.data_url + 'train-images-idx3-ubyte') train_label = os.path.join(args.data_url + 'train-labels-idx1-ubyte') try: import moxing.mxnet as mox except: assert os....
import subprocess import string import random import sys import os import yaml import logging logger = logging.getLogger("ipns") IPCOMMAND = '/bin/ip' KILLCOMMAND = '/bin/kill' SYSCTLCOMMAND = '/sbin/sysctl' class IPException(Exception): pass def random_string(prefix="", length=16): return prefix + ''.j...
import os import json import subprocess from datetime import datetime, timezone import numpy as np import iris import boto3 from pyspark.sql import SparkSession from pyspark.sql.types import * from pyspark.sql.functions import * spark = SparkSession.builder.appName('AWS-Take-Home').getOrCreate() def get_bucket_links...
#!-*-encoding:utf-8-*- import datetime import os from os.path import dirname from scrapy.spiders import Spider import scrapy from scrapy.exceptions import CloseSpider from webspider.itemLoaders import SeeBugLoader from webspider.items import SeeBugItem from webspider.settings import TOP_DIR #from webspider.util impo...
import numpy as np from pyquante2.grid.lebedev import lebedev class atomic_grid(object): def __init__(self,atom,**kwargs): atno,x,y,z = atom.atuple() if kwargs.get('radial','EulerMaclaurin') == 'Legendre': grid_params = LegendreGrid(atno,**kwargs) else: grid_params ...
import json import os import numpy import subprocess from numpy import exp, polyval, log, pi, unwrap, angle from matplotlib import pyplot from scipy import signal error_cnt = 0 prog_rc = 0 def send(f, v, n): e = json_dict[n] base = e["base_addr"] for j, x in enumerate(v): f.write("%d %x\n" % (base...
# -*- coding: utf-8 -*- # pylint: disable=line-too-long,import-error """Namespace: ``Broker``.""" from zlogging._compat import enum @enum.unique class DataType(enum.IntFlag): """Enum: ``Broker::DataType``. Enumerates the possible types that ``Broker::Data`` may be in terms of Zeek data types. See Also:...
# Generates tokens which are defined in hazel/grammar/Tokens # The files are (relative to the root) are: # 1. hazel/compiler/tokens/token.h # 2. hazel/compiler/tokens/token.c NT_OFFSET = 256 def load_tokens(path): token_names = [] string_to_token = {} ERRORTOKEN = None with open(path) as fp: ...
##################################### # LICENSE # ##################################### # # Copyright (C) 2020 <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 Softw...
from datetime import date, timedelta import calendar import os import math from copy import copy, deepcopy from reportlab.lib.units import inch from reportlab.lib import colors from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfbase.pdfmetrics import stringWidth m...
from RainbowChain import Dictogram from collections import deque class RainbowChain: """ Basically a Markov Chain that generates sentences. """ # Max amount of attempts we have to generate a new sentence MAX_ITERATION_ATTEMPTS = 100 def __init__(self, corpus, max_order): """ Constructing the...
#! /usr/bin/env python # Class for storing user-specific data import reservoirGrid import wx import wx.grid as gridlib class ScoreDataTable(reservoirGrid.TrayDataTable): def __init__(self, data): reservoirGrid.TrayDataTable.__init__(self, data) self.colLabels = ["ScoreNr","Descript...
from scipy.spatial import ConvexHull, convex_hull_plot_2d import numpy as np from spinup.my_env.rtd.utils.vert2lcon import vert2lcon def buffer_box_obstacles(B,b,N): B=np.concatenate((B,np.full([2,1],np.nan)),axis=1) # get x and y coords Bx=B[0,:] By=B[1,:] Bx=Bx.reshape(1,-1) By=By.reshape(1,...
import dace import numpy as np import sys from dace.transformation.subgraph import ReduceExpansion, SubgraphFusion, MultiExpansion import dace.transformation.subgraph.helpers as helpers import dace.dtypes as dtypes from dace.sdfg.graph import SubgraphView import dace.libraries.standard as stdlib import dace...
import time import datetime import aiohttp import asyncio from xml.etree.ElementTree import fromstring import requests import m3u8 import os from typing import List, Optional, TypeVar URI = str Tag = str Path = str EpisodeID = str EpisodeInstance = TypeVar('Episode') Semaphore = Optional[asyncio.Semaphore] class Str...
# -*- coding: UTF-8 -*- # This file is a part of pycerberus. # The source code contained in this file is licensed under the MIT license. # See LICENSE.txt in the main project directory, for more information. # SPDX-License-Identifier: MIT from __future__ import absolute_import, print_function, unicode_literals import...
import discord from discord.ext import commands from datetime import datetime import asyncio self_id=742371009352433714 class Help(commands.Cog): def __init__(self, bot): self.bot = bot #言語ページめくり関数 async def commands_pages(self, ctx, msg, com): langs_list = self.bot.get_cog('Contents')...
# -*- coding: utf-8 -*- from datetime import datetime import re from django.dispatch.dispatcher import Signal from vkontakte_api.parser import VkontakteParser, VkontakteParseError post_parsed = Signal(providing_args=['instance', 'raw_html']) comment_parsed = Signal(providing_args=['instance', 'raw_html']) def get_ob...
# Import Modules import re import json import requests as r from geopy.distance import great_circle import ghcnpy as gp ################################################# # MODULE: find_station # Find stations by certain Search Criteria # 1 Arg: Search by Name # 3 Arg: Search by Lat Lon Distance limit ########...
import PyPDF2 import xlrd, tabula import pandas as pd from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render,get_object_or_404,redirect from django.contrib.auth.models import User from django.contrib.auth import logout as do_logout, authenticate, login as do_login import os, logg...
import sedate from datetime import datetime from libres.db.models import ReservedSlot from onegov.core.orm.mixins import meta_property, content_property from onegov.core.orm.types import UUID from onegov.form.models import FormSubmission from onegov.org.models.extensions import ContactExtension, \ ResourceValida...
import copy from seraphim.mod_arithmetics.modulare_arithmetic_efficient import RestclassEfficient class Polynomial(object): """Klasse zur Darstellung von Polynomen in Form einer Koeffizientenliste aufsteigend von Grad 0 bis n""" def __init__(self, coefficients): self.coefficients = coefficients ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import math import numpy as np from detectron.core.config import cfg from detectron.utils.c2 import const_fill from detectron.utils.c2 import gauss_fill from detectron.u...
#!/usr/bin/env python3 #------------------------------------------------------------------------------ # Description of the header clean process #------------------------------------------------------------------------------ # Here is the list of actions performed by this script to clean the original # kernel headers....
#!/usr/bin/env python # -*- coding: utf-8 -*- """POS and NER Taggers. Part of speech taggers (POS) classifies words into 17 syntactic category. Named entity Recognition extractors (NER) Detect three types of entities: {Person, Location, Organization.} """ import numpy as np from six.moves import range from ..decor...
""" to_polar_coordinates ==================== """ from ansys.dpf.core.dpf_operator import Operator from ansys.dpf.core.inputs import Input, _Inputs from ansys.dpf.core.outputs import Output, _Outputs, _modify_output_spec_with_one_type from ansys.dpf.core.operators.specification import PinSpecification, Specification "...
#!/usr/local/greenplum-db-6.10.0/ext/python/bin/python # coding=utf-8 try: from debug.debug_tools import plpy except ImportError: import plpy import os import uuid import json from .conf import MODEL_SAVE_PATH import re import graphlearn as gl import pandas as pd int_pattern = re.compile("^-?[1-9]\d*$") float_...
from decimal import Decimal from falcon.base.event import BaseEvent from falcon.base.order import OrderType from falcon.base.symbol import get_mt4_symbol class EventType(object): DEBUG = 'DEBUG' STARTUP = 'STARTUP' # system start up SHUTDOWN = 'SHUTDOWN' # system shutdown HEARTBEAT = 'HEARTBEAT' ...
import re from typing import List, Callable, Tuple, Union _Tokenizer = Callable[[bytes], Tuple[List[int], List[int]]] ZWSP = "\u200B" class Segmenter(): def __init__(self, tokenizer: _Tokenizer, separator: bytes): self._tokenizer = tokenizer self._separator = separator escaped_separator = re.escape(separa...
# synthetic airspeed experiment import math import numpy as np from scipy.interpolate import Rbf # x, y, z, d = np.random.rand(4, 50) # rbfi = Rbf(x, y, z, d) # radial basis function interpolator instance # xi = yi = zi = np.linspace(0, 1, 20) # di = rbfi(xi, yi, zi) # interpolated values # di.shape # (20,) phi_l...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals, print_function import argparse import base64 import hashlib import struct import sys import zlib import M2Crypto import utils __version__ = '1.0' class LicenseDecodeError(Exception): pass class AtlassianLicenseDecoder(object...
from . import * def test_raises_attr_error_if_function_not_overloaded(overloaded): def foo(): ... with pytest.raises(AttributeError): overloaded.foo() def test_basic_same_function_name(overloaded): @overloaded def foo(a, b): return a ** b assert overloaded.foo(2, 3) == 8 assert...
#! /usr/bin/env python3 """ Tapeimgr, automated reading of tape Command-line interface Author: <NAME> Research department, KB / National Library of the Netherlands """ import sys import logging import argparse import uuid from .tape import Tape from . import config class tapeimgrCLI: """This class defines the...
# Input Optimization Algorithm Tests # ReverseLearning, 2017 # Linear :: f(x) = 2x + 3 # 17.0 # CALCULATED : f(6.9999) = 16.9999 # TARGET : f(7) = 17 # EPOCHS : 35 (Beat Error) # Positive Quadratic :: f(x) = x^2 - 8x + 15 # Minimum # CALCULATED : f(3.99999) = -1 # TARGET : f(4.0) = -1 # EPOCHS : 71 (L...
# -*- coding: utf-8 -*- # This program converts an prepped Urdu text file containing a Bible book to USFM form. # Extra-biblical content (book overview, outline, footnotes, etc.) has been removed. # Chapters are already marked. # Verse numbers all begin on a new line. # Leaves .txt file unchanged. # Writes .us...
""" Copyright 2012 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
import tensorflow as tf from utils import tf_util2 from utils.pointnet_util import pointnet_sa_module,pointnet_fp_module def placeholder_inputs(batch_size, num_point,up_ratio = 4): pointclouds_pl = tf.placeholder(tf.float32, shape=(batch_size, num_point, 6)) pointclouds_gt = tf.placeholder(tf.float32, shape=(b...
import abc from dataclasses import dataclass import numpy as np from .. import gl glsl_types = { 'float': gl.GL_FLOAT, 'vec2': gl.GL_FLOAT_VEC2, 'vec3': gl.GL_FLOAT_VEC3, 'vec4': gl.GL_FLOAT_VEC4, 'int': gl.GL_INT, 'ivec2': gl.GL_INT_VEC2, 'ivec3': gl.GL_INT_VEC3, 'ivec4': gl.GL_INT_V...
import contextlib import itertools import logging # noqa import os.path import typing as ta # noqa from omnibus import check from omnibus import collections as ocol from omnibus import dataclasses as dc from omnibus import inject as inj from omnibus import lang # noqa from omnibus import logs # noqa from omnibus i...
from copy import deepcopy import numpy as np import time import sklearn from sklearn.linear_model import LinearRegression, Ridge, RidgeCV """ Generates the data by sampling it from a centered Gaussian distribution with a certain covariance matrix. It also generates the ground truth function and the values of the pred...
import datetime import json import logging import multiprocessing import time import traceback import requests from gcloud.rest.core import backoff from gcloud.rest.core.util import decode from gcloud.rest.taskqueue.error import FailFastError from gcloud.rest.taskqueue.queue import TaskQueue log = logging.getLogger...
#!/usr/local/bin/python # -*- coding: utf-8 -*- '''Generalized Bayes Classifiers ''' import numpy as np from sklearn import svm from thomas.field import * from thomas.bayes import * from neupy import algorithms, environment environment.reproducible() model_dict={'svm':svm.SVC(kernel='rbf'), 'grnn':algorithms.GRNN...
#!/usr/bin/env python3 import signal, sys, os, getopt d = os.path.dirname(sys.argv[0]) sys.path.append(d) pid_dir = "/tmp" import pywind.evtframework.evt_dispatcher as dispatcher import fdslight_etc.fn_server as fns_config import fdslight_etc.fn_client as fnc_config import freenet.lib.fdsl_ctl as fdsl_ctl import free...
# -*- coding:utf-8 -*- from owlmixin import OwlMixin, TOption from owlmixin.owlcollections import TList, TDict from jumeaux.addons.judgement import JudgementExecutor from jumeaux.utils import ( exact_match, when_optional_filter, get_jinja2_format_error, get_by_diff_key, ) from jumeaux.logger import Lo...
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
#load the iris data set to program import tkinter.messagebox as m from sklearn.datasets import load_iris iris=load_iris() X=iris.data Y=iris.target ########split the dataset for training and testing from sklearn.model_selection import train_test_split X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size...
from tsbenchmark.tasks import TSTask from tsbenchmark.callbacks import ReporterCallback from hypernets.utils import logging import os import tempfile from pathlib import Path import pytest from hypernets.hyperctl.appliation import BatchApplication from hypernets.utils import ssh_utils from tsbenchmark.benchmark imp...
# Copyright 2017 BBVA # # 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, softwar...
"""Run the jobs in this file. Example running jobs. Make a <username>_jobs.py and have it call do_jobarray. """ import itertools import os import socket import sys import getpass hostname = socket.gethostname() is_cims = any([ hostname.startswith('cassio'), hostname.startswith('dgx'), hostname.startswit...
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # ME...
import time from PIL import ImageFont from PIL.ImageDraw import ImageDraw from luma.core.device import device from luma.core.interface.serial import spi, noop from luma.core.render import canvas from luma.core.virtual import viewport from luma.emulator.device import pygame from luma.led_matrix.device import max7219 ...
""" template_test_harness.py Template which loads the context of a process into a Unicorn Engine, instance, loads a custom (mutated) inputs, and executes the desired code. Designed to be used in conjunction with one of the Unicorn Context Dumper scripts. Author: <NAME> <<EMAIL>> """ i...
from pathlib import Path import torch from torch.utils.data import DataLoader from tqdm import tqdm import cv2 from torchvision.utils import save_image import numpy as np from perception.custom_datasets import ComparisonDataset, DepthDataset, SegmentationDataset from perception.training.models import createUNet, crea...
# -------------------------------------------------------------------------------------- # Copyright 2016, <NAME>, <NAME>, <NAME>, <NAME> # Hummingbird is distributed under the terms of the Simplified BSD License. # ------------------------------------------------------------------------- """Coordinates data reading, t...
# -*- coding: utf-8 -*- import cv2 import numpy as np import matplotlib.pyplot as plt import os import sys from tqdm import tqdm import multiprocessing.dummy as multiprocessing from pathos.multiprocessing import ProcessingPool as Pool from functools import partial IMG_BIT_DEPTH = 2**8 num_workers = multiprocessing.cpu...
import tensorflow as tf import numpy as np # FlopcoKeras install is broken on pip 20.1 due to use of pip internals in setup.py # https://www.gitmemory.com/issue/Aloomaio/alooma-python/120/629762153 # from flopco_keras import FlopCoKeras ProfileOptionBuilder = tf.compat.v1.profiler.ProfileOptionBuilder def calculate...
import os import pickle import numpy as np import pandas as pd import feature_impact from feature_generation import add_features RESULT_DTYPES = {'BusinessModelRisk': np.int32, 'DesireToInvest': np.int32, 'ManagementShareholdersConflict': np.int32, 'NegativeSharehol...
import click import sys import pandas as pd # Fix Python 2.x. try: UNICODE_EXISTS = bool(type(unicode)) except NameError: unicode = lambda s: str(s) def printDebug(text, mystyle="", **kwargs): """ util for printing in colors using click.secho() :kwargs = you can do printDebug("s", bold=True) ...
"""Path and path finding related functions.""" from __future__ import annotations import sys from collections import defaultdict from dataclasses import dataclass, field from itertools import islice from operator import attrgetter from typing import (TYPE_CHECKING, DefaultDict, Dict, Iterator, List, Set, ...
"""Use ctypes to load libOdb.so and access symbols""" import ctypes from ctypes.util import find_library from .util import suppress_stdout _LIB = find_library("Odb") if _LIB is None: raise OSError("Could not find libOdb. Try updating your LD_LIBRARY_PATH.") _ODBQL = ctypes.CDLL(_LIB) _ODBQL.odbql_column_name.re...
# Code by <NAME> # Edited by <NAME> 07/2015 from builtins import zip from builtins import range import numpy as np from cosmosis.datablock import names as section_names from cosmosis.datablock import option_section import scipy.interpolate import warnings def gaussian(z, mu, sigma): g = np.exp(-0.5 * (z - mu)**2...
from typing import List import argparse import configparser import logging import codecs import json import pickle import pandas as pd import numpy as np logging.basicConfig(format='{asctime} : {levelname} : {message}', level=logging.INFO, style='{') logger = logging.getLogger(__name__) def get_parser(): """ ...
import os from lingvo import model_registry from lingvo.core import base_model_params from lingvo.core import datasource from lingvo.core import program from lingvo.core import py_utils from lingvo.core import schedule from lingvo.core import tokenizers from lingvo.tasks.asr import input_generator from lingvo.tasks.as...
import numpy as np import pandas as pd import re from functools import partial from nltk import word_tokenize, pos_tag from nltk.corpus import wordnet as wn from nltk.stem import WordNetLemmatizer from nltk.stem.snowball import SnowballStemmer import multiprocessing import enchant # nltk.download('wordnet') # nltk.dow...
#!/usr/bin/env python from __future__ import unicode_literals import json import io import sys from onnx import defs from onnx.defs import OpSchema from onnx.backend.test.case import collect_snippets snippets = collect_snippets() categories = { 'Constant': 'Constant', 'Conv': 'Layer', 'ConvTranspose':...
''' Convenient functions ''' import numpy as np, yt, os, h5py as h5, sys from Physics import * from Models import * ### Probability / Likelihood Functions def histogram( data, bins=10, range=None, density=None, log=False ): ## compute histogram of data array, allows for log-scaled binning and probability de...
import nonechucks as nc from .. import transforms as TC from .custom import CustomDataset from .synthtext import SynthTextDataset from torch.utils.data.dataloader import DataLoader mean_norm = [0.485, 0.456, 0.406] std_norm = [0.229, 0.224, 0.225] def trainset_transform(resize_size=(224, 224), img_size=(224, 224)...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright 2013 Kitware 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 cop...
import tensorflow as tf from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense from tensorflow.keras.layers import Activation, BatchNormalization, Flatten from tensorflow.keras.models import Sequential from keras.models import Model from functools import partial import cv2 import numpy as np # AUTOTU...
import enum import multiprocessing as mp from typing import Dict import numpy as np import torch from cid.rollouts.base import BaseRolloutGenerator class ParallelRolloutGenerator(BaseRolloutGenerator): """Generator producing multiple environment rollouts in parallel Parallel rollouts are generated in worke...
from rest_framework import serializers, fields from .models import GreenUser from supplier.models import Supplier from hubmanager.models import HubManager, LogicHub from loader.models import HubLoader from django.contrib import auth from rest_framework.exceptions import AuthenticationFailed from rest_framework_simplejw...
# Author: <NAME> # Email alejandro.bernardis at gmail.com # Created: 2019/11/05 07:22 import sys import json import docopt import collections from inspect import getdoc from functools import partialmethod from docopt import DocoptExit from pathlib import Path from tomlkit import api from tomlkit.container import Conta...
from elftools.elf.elffile import ELFFile from binascii import hexlify from unicorn import * from unicorn.arm64_const import * import struct import re global instructions_run, current_id instructions_run = 0 current_id = 0 module_functions = [] module_names = [] SMASH_REGISTER_MODULE = 0x29570e0 SMASH_REGISTER_FUNCT...
""" EXAMPLE 08: WAGON EXCHANGE --------------------------- TOPIC: Multiple Trains, Driving, Steering, Wagon Decoupling, Snap Command Events SETUP: build a track with nested loops on both sides (using 4x splits, 2x straights, 12x curves). Add snap commands as follows: - WHITE-MAGENTA-WHITE: double sided snap comman...
from flask import Flask, jsonify from scipy import stats import numpy as np import pandas as pd import datetime as dt from datetime import datetime from dateutil.relativedelta import relativedelta import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import...
import logging import onnx from onnx import numpy_helper from onnx.helper import make_model, make_tensor_value_info, make_opsetid from furiosa_sdk_quantizer.frontend.onnx.quantizer.utils import __PRODUCER__ from furiosa_sdk_quantizer.frontend.onnx import __DOMAIN__, __OPSET_VERSION__ logger = logging.getLogger("Furio...
import gzip import logging import os import shutil import tensorflow as tf from six.moves import urllib MNIST_MIRROR = 'http://yann.lecun.com/exdb/mnist/' FI = ['train-images-idx3-ubyte', 'train-labels-idx1-ubyte', 't10k-images-idx3-ubyte', 't10k-labels-idx1-ubyte'] logging.basicConfig(level=logging.INFO) logger = log...
# 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ from datetime import datetime import numpy as np from numpy import ma from pyWOA.woa import WOA def test_import(): # A shortcut from pyWOA import WOA db = WOA() def test_available_vars(): db = WOA() for v in ['TEMP', 'PSAL']: ...
import numpy as np """ This class loads a PACMAN control file (pcf) and lets you querry the parameters and values. Constructor Parameters: ----------------------- file : A control file containing the parameters and values. Notes: ------ A parameter can have one or more values, differe...
#!/usr/bin/env python ############################################################################### # # utilities.py # # Copyright (C) 2011 <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 ...
import pandas as pd from rebar import arrdict import numpy as np import matplotlib.pyplot as plt import torch import torch.distributions import torch.testing from torch import nn import geotorch from . import expectations, common from logging import getLogger log = getLogger(__name__) μ0 = 0 σ0 = 10 def pairwise_ind...
from collections import defaultdict import argparse class Dictionary(object): """A mapping from symbols to consecutive integers""" def __init__(self, input, word_dict_min_num=2): self.files = ['train.0', 'dev.0', 'test.0', 'train.1', 'dev.1', 'test.1'] self.files = [input+"/"+f for f in self.fi...
#!/usr/bin/env python """ Functions for reading and writing nifti volume files. Authors: - <NAME>, 2012-2016 (<EMAIL>) http://binarybottle.com Copyright 2016, Mindboggle team (http://mindboggle.info), Apache v2.0 License """ def convert2nii(input_file, reference_file, output_file='', interp='continuous'): ...
''' Parse yml files to markdown Execute this script from root python scripts/parse.py Urmi ''' import yaml import glob import os import sys import traceback from operator import itemgetter datasets=[] #is a list of lists, each inner-list is a row resources=[] #is a list of lists #headers datasets_h1=['S.No.','Date'...
from numba import cuda from numba import * import numpy as np from PIL import Image, ImageDraw, ImageFont from constants import palette import json import sys import math targetObject = sys.argv[1] #load calibration JSON from standard with open("calibration.json", 'r') as f: calibration = json.load(f) #load target m...
from __future__ import print_function import os, time import torch import torch.nn.functional as F from datasets import get_img_loader from nets import ConvODENet from trainer import TrainerBase import util, options import easydict from torch.optim import SGD, Adam from torchdiffeq import odeint_adjoint as odesolve ...
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import csv import argparse import torch import torchaudio import string from tqdm import tqdm from pathlib import Path from typing import Dict,...
""" From <NAME>'s fft-gal-convolution paper... """ import numpy as np def fftgalmog(re, e1, e2, profile, cdmatrix, dx, dy, psfshape): # Compute galaxy affine transform terms # eqn (2) e = np.hypot(e1, e2) orig_e = e # add this max() to handle e1=e2=0. e = max(e, 1e-16) # eqn (A9) # c2...
#!/usr/bin/env python # # Read Greenhouse sensor data from an XBee. # # Written by <NAME> # from xbee import ZigBee import sys import serial import struct import yaml import paho.mqtt.client as mqtt import json import sys import time import signal import logging # Set the logging level logging.basicConfig(level=logg...
from .common import * class LinearSolver(Enum): default = 0 mumps, petsc, superlu, umfpack = 1, 2, 3, 4 bicgstab, cg, gmres, minres, richardson, tfqmr = 5, 6, 7, 8, 9, 10 class Preconditioner(Enum): default = 0 none, icc, jacobi, ilu, sor = 1, 2, 3, 4, 5 amg, hypre_amg, petsc_amg = 6, 7, 8 ...
from .utils.coordinates_helper import view2pixel from .neural_network.NeuralNetwork import NeuralNetwork from .utils.sky_extractor import extract_sky from .utils.fixes import fix_dead_pixels from datetime import datetime, timedelta from matplotlib import path import matplotlib.patches as patches import matplotlib.pyplo...
import matplotlib.pyplot as plt from tkinter import * from tkinter.filedialog import askopenfilename from PIL import Image, ImageTk import matplotlib.image as mpimg from scipy import misc import math import numpy as np import sys as sys from point import P2_Point from point import R2_Point import copy def normalizeIm...
"""Platform to control a Zehnder ComfoAir ventilation unit.""" import logging from pycomfoconnect import ( SENSOR_BYPASS_STATE, SENSOR_DAYS_TO_REPLACE_FILTER, SENSOR_FAN_EXHAUST_DUTY, SENSOR_FAN_EXHAUST_FLOW, SENSOR_FAN_EXHAUST_SPEED, SENSOR_FAN_SUPPLY_DUTY, SENSOR_FAN_SUPPLY_FLOW, SENS...