text
stringlengths
3.07k
22.1k
#!/usr/bin/env python # usage: completeness_check.py __author__ = "<NAME>" __copyright__ = "Copyright (c) 2019-2020 <NAME> All Rights Reserved." __email__ = "<EMAIL>" __license__ = "Apache 2" import copy import math from statistics import mean, stdev import csv import json import urllib import requests from pprint imp...
from intcode.intcode import intcode, chain_intercodes, looping_intcodes from collections import defaultdict # Day 2 def test_day2_part1_examples(): assert intcode([1, 0, 0, 0, 99])[1] == defaultdict(int, enumerate([2, 0, 0, 0, 99])) assert intcode([2, 3, 0, 3, 99])[1] == defaultdict(int, enumerate([2, ...
""" A python interface for parsing web browser user-agent strings. Uses database from http://user-agent-string.info/ . (c) 2014 <NAME> <<EMAIL>> Loosely based on the version by - <NAME> <<EMAIL> AT <EMAIL> DOT <EMAIL>> - <NAME> http://molhanec.net Licensed under the MIT license. Copyright (c) 2014 <NAME> <<EMAIL>...
import copy import math import torch import torch.nn as nn import torch.nn.functional as F def self_attention(query, key, value, mask=None, dropout=None): """ Compute 'Scaled Dot Product Attention' """ d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k) i...
# Copyright 2015 Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by...
#!/usr/bin/env python # Copyright (c) 2017 Vantiv eCommerce # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, mo...
""" Peer monitoring: knowing which other operators do run, and exchanging the basic signals with them. The main use-case is to suppress all deployed operators when a developer starts a dev-/debug-mode operator for the same cluster on their workstation -- to avoid any double-processing. See also: `kopf freeze` & `kopf...
import os import warnings from collections import OrderedDict from distutils.version import LooseVersion import numpy as np from .. import DataArray from ..core import indexing from ..core.utils import is_scalar from .common import BackendArray from .file_manager import CachingFileManager from .locks import Serializa...
import FnAssetAPI import hiero.core from QtExt import QtGui, QtWidgets, QtCore from .. import specifications from . import actions from . import utils __all__ = [ 'createStaticActions', 'reconfigureActions', 'updateActionState', 'buildStaticUI', 'bootstrapManagerUI', 'populateBinContextMenu', 'populat...
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
from ctreport_selenium.ctreport_html import dashboard_view, detail_view, footer_view from ctreport_selenium.ctreport_html.charts import status, priority, assertion, verification, timeline from ctreport_selenium.ctreport_html.scripts import filter, search, footer, tooltip, toggle, detailmodal, imagemodal, \ toastr f...
import copy from datetime import datetime import pytz from dateutil.rrule import rrule from dateutil import parser from django.contrib.postgres.fields import JSONField from django.db import models, transaction from django.utils.module_loading import import_string from fleming import fleming from manager_utils import b...
from copy import deepcopy from decimal import Decimal from django.core.exceptions import ValidationError from django.core.management import call_command from django.test import TestCase from django.test import Client from django.core.handlers.base import BaseHandler from django.test.client import RequestFactory fro...
import numpy as np def softmax(predictions): if (predictions.ndim == 1): predictionsTmp = np.copy(predictions) predictionsTmp -= np.max(predictions) divider = 0; for i in range(len(predictions)): divider += np.exp(predictionsTmp[i]) probs = np.exp(predictionsTmp...
from ..globals import GlobalVariables as Gb from ..const_general import (NOT_HOME, ICLOUD3_ERROR_MSG, EVLOG_DEBUG, EVLOG_ERROR, STATIONARY, NEW_LINE, CRLF, CRLF_DOT, DATETIME_ZERO, RARROW, ) from ..const_attrs import (NEXT_UPDATE_TIME, INTERVAL, LOCATION, ID, ...
from .main import ElegantRunToolkit from pyelegantsdds.sdds import SDDSCommand import numpy as np import pandas as pd from scipy import constants as const def GenerateNDimCoordinateGrid(N, NPOINTS, pmin=1e-6, pmax=1e-4, man_ranges=None): """ Method to generate an N dimensional coordinate grid for tracking, ...
# coding=utf-8 # Copyright 2020 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...
#!/usr/bin/env python3 """ Communicate with the UPS. Store data from a supported UPS in an sqlite3 database. """ import configparser import datetime as dt import os import sqlite3 import subprocess import sys import syslog import time import traceback import mausy5043funcs.fileops3 as mf import mausy5043libs.libsign...
""" Module for PAMPAC action classes. """ from abc import ABC, abstractmethod from gatenlp import Annotation from gatenlp.features import Features class Getter(ABC): """ Common base class of all Getter helper classes. """ @abstractmethod def __call__(self, succ, context=None, location=None): ...
# # Copyright (c) 2018-2021, NVIDIA 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 ag...
from os import listdir from os.path import isfile, join import gc import copy import pickle import math import sys import random import resource from random import randrange, seed from threading import current_thread import os import time import numpy as np from multiprocessing import cpu_count np.set_printoptions(sup...
import mindspore.nn as nn import mindspore.ops as ops from mindspore import Parameter, Tensor from mindspore import dtype as mstype from mindspore.common import dtype as mstype from mindspore.common.initializer import initializer from mindspore.ops import functional as F from mindspore.ops import operations as P from m...
import random from librosa.filters import mel import torch from torch._C import dtype import torch.nn as nn import torchvision import ffmpeg import torchaudio import torchvision.transforms as transforms import cv2 import sys import traceback import os import math import numpy as np import json from torch.utils.data imp...
import argparse import os import shutil import sys import numpy as np import tensorflow as tf from tensorflow.python.framework.errors_impl import OutOfRangeError from tensorflow.python.saved_model.simple_save import simple_save from settings import model_dir, path_to_test_data from annotation_predictor.util.util impo...
import numpy as np import xarray as xr import geopandas as gpd import pandas as pd from shapely.geometry import Point from feedinlib.cds_request_tools import get_cds_data_from_datespan_and_position def get_era5_data_from_datespan_and_position( start_date, end_date, variable="feedinlib", latitude=None...
# This code is built from the PyTorch examples repository: https://github.com/pytorch/vision/tree/master/torchvision/models. # Copyright (c) 2017 Torch Contributors. # The Pytorch examples are available under the BSD 3-Clause License. # ==================================================================================...
import sys import re import json import traceback if sys.version_info[0] == 2: # Python 2.x shlex doesn't support unicode import ushlex as shlex else: import shlex try: import yaml except ImportError as err: import yaml3 as yaml class HostsParser(object): """ Parse Ansible hosts inventory ...
from hls4ml.model.optimizer import OptimizerPass, ConfigurableOptimizerPass, register_pass from hls4ml.model.layers import BatchNormalization, Dense, Conv1D, Conv2D, register_layer, layer_map from hls4ml.model.types import IntegerPrecisionType, FixedPrecisionType, ExponentPrecisionType, NamedType import tensorflow as t...
import json import hashlib from module.time import read_config_time, crate_config_time, wait_input import subprocess from module.mail import mail, mail_format # 异常 class NoSuchFile(Exception): def __init__(self, code=1): self.code = code # md5文件 def md5_file(fp="config/md5.json"): try: with ...
import tensorflow as tf from distutils.version import LooseVersion if LooseVersion(tf.__version__) > LooseVersion("1.14"): import tensorflow.compat.v1 as tf if LooseVersion(tf.__version__) > LooseVersion("2.0"): tf.disable_v2_behavior() import numpy as np import scipy.sparse as sp from tensorflow.keras.initial...
""" Generates a report of statistics for CCS reads mapped to a reference genome with Blasr/pbalign. """ from collections import namedtuple import logging import os.path as op import sys import numpy as np from pbcommand.models import get_pbparser, FileTypes from pbcommand.models.report import Report, Attribute, Col...
#https://towardsdatascience.com/transformers-can-you-rate-the-complexity-of-reading-passages-17c76da3403 import numpy as np import pandas as pd import transformers from matplotlib import pyplot as plt from sklearn.model_selection import StratifiedKFold import torch import torch.nn as nn # Dubious! Why are we mixing ...
import tensorflow as tf import numpy as np import time import os import argparse import sys import elpips import train_dataset parser = argparse.ArgumentParser() parser.add_argument('--net', type=str, required=True, help='[squeeze], [vgg], [squeeze_ensemble] or [vgg_ensemble] for network architectures') parser.add...
#------------------------------------------------------------------------------- # Name: Excel MultiLine TimeSaver # Purpose: Takes input from an excel file, searches Clinicaltrials.gov for # information, then extracts it and records in a separate sheet. # # Author: <NAME> # Licence...
import math import pickle import numpy as np import basis.robot_math as rm def define_grasp(hnd_s, objcm, gl_jaw_center_pos, gl_jaw_center_z, gl_jaw_center_y, jaw_width, toggle_flip=True, toggle_debu...
"""A cache for thumbnailed images.""" from __future__ import unicode_literals import collections import sys import os.path try: from io import BytesIO as StringIO except Exception as e: from cStringIO import StringIO from PIL import Image from django.core.files.base import File from optimizations.assetcach...
# coding: utf-8 """ Name: equivpotential_temp.py Calcurate equivalent potential temperature. example: Author: <NAME> Date: 2021/09/18 """ import argparse #from datetime import datetime, timedelta import os from os.path import abspath, dirname, join import re import sys from metpy.units import units import metpy.calc...
""" ================================================= Example of pattern recognition on simulated data ================================================= This example simulates data according to a very simple sketch of brain imaging data and applies machine learning techniques to predict output values. We use a very s...
import logging; logger = logging.getLogger("minimalKB."+__name__); DEBUG_LEVEL=logging.DEBUG import time import datetime import sqlite3 from minimalkb.backends.sqlite import sqlhash from minimalkb.kb import DEFAULT_MODEL REASONER_RATE = 5 #Hz class OntoClass: def __init__(self, name): self.name = name ...
import logging from datetime import datetime from galaxy import model from galaxy.jobs.runners import JobState from ._safe_eval import safe_eval __all__ = ('failure', ) log = logging.getLogger(__name__) MESSAGES = dict( walltime_reached='it reached the walltime', memory_limit_reached='it exceeded the amount...
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distrib...
"""BDD100K tracking evaluation with CLEAR MOT metrics.""" import time from multiprocessing import Pool from typing import List, Tuple, Union import motmetrics as mm import numpy as np import pandas as pd from ..common.logger import logger from ..common.typing import DictAny METRIC_MAPS = { "idf1": "IDF1", "m...
# Copyright 2014 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
''' Contains methods for converting the units of data. Mainly used for model benchmarking purposes. ''' import numpy as np import xarray as xr def adjust_units(units): ''' Creates a consistent unit string that will be used in the unit conversion routines below. Args: units : str ...
import tia.trad.tools.ipc.naming_conventions as names import tia.trad.tools.arithm.floatArithm as fl import tia.trad.market.orders as orders; reload(orders) from tia.trad.tools.dicDiff import DictDiff import tia.trad.market.events as event; reload(event) import logging import tia.trad.tools.ipc.processLogger as pl LOGG...
import csv import numpy as np import matplotlib.pyplot as plt from sklearn import preprocessing from sklearn.metrics import accuracy_score def getTrainingTestValidationData(): TrainX=[] TestX=[] ValidationX=[] Trainy=[] Testy=[] Validationy=[] X = [] y = [] f=op...
from jsonrpcbase import ServerError class EmptyWorkspaceMock: def __init__(self, *args, **kwargs): self.user = "some_user" self.shared_user = "some_other_user" def list_workspace_info(self, params): return [] class WorkspaceMock: ws_info_meta = { 1: {}, 2: {"narra...
#The MIT License (MIT) # #Copyright (c) 2015,2018 <NAME> # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, mer...
import requests import base64 import zlib import re from urllib.parse import quote, unquote import urllib3 from flask import Flask, redirect, request, Response from uuid import uuid4 from textwrap import wrap from lxml import etree urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) xdmod = Flask(__name...
#! -*- coding:utf-8 -*- # qt sim 任务训练:非冻结, 最后做cosin import os import sys import tensorflow as tf from keras.models import Sequential from bert4keras.backend import keras, set_gelu, search_layer, K from bert4keras.tokenizers import Tokenizer from bert4keras.models import build_transformer_model from bert4keras.optimize...
from __future__ import print_function __copyright__ = """ Copyright 2019 <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 ...
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http:#www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.db import models from django.conf import settings from paypal.standard.signals import payment_was_successful, payment_was_flagged # ### ToDo: would be cool if PayPalIPN.query was a JSON field # ### or something else that let you get at the data better. # ### ...
from datetime import timedelta import pandas as pd def twdb_dot(df_row, drop_dcp_metadata=True): """Parser for twdb DOT dataloggers.""" return _twdb_stevens_or_dot(df_row, reverse=False, drop_dcp_metadata=drop_dcp_metadata) def twdb_fts(df_row, drop_dcp_metadata=True): """Parser for twdb fts dataloggers...
""" See https://github.com/airysen/irlbpy for full repo. """ import numpy as np import scipy.sparse as sparse import warnings from numpy.fft import rfft, irfft import numpy.linalg as nla # Matrix-vector product wrapper # A is a numpy 2d array or matrix, or a scipy matrix or sparse matrix. # x is a numpy vector only....
#!/usr/bin/env python3 from __future__ import print_function from builtins import range import ROOT import re import pprint import sys import inspect import optparse defsDict = { 'int' : '%-40s : form=%%%%8d type=int', 'float' : '%-40s : form=%%%%7.2f prec=', 'str' : '%-40s : form=%%%%20s ...
# Deep Convolutional GANs # Importing the libraries # from __future__ import print_function import os import random import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as transforms import torc...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= # Created: 01-July-2014 - Revised Date: 21-Mar-2017 # File: backup-files.py # Depends: colorama # Compat: 2.7+ # Author: Cashiuus - Cashiuus{a...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_calc ---------------------------------- Acceptance tests for MVP. """ import os import pytest import logging from assertpy import assert_that from pytest_bdd import scenario, given, when, then #SUT infrastructure from tango import DeviceProxy, DevState # type: ig...
""" Animation library for hoverset authors. Allows for animation of various properties using various easing functions """ from threading import Thread import time class CubicBezier: # FIXME Bezier does not function with very small duration values, at least for tkinter """ KSpline bezier curve engine impl...
# !pip install imutils import numpy as np import cv2 from sklearn.cluster import KMeans from collections import Counter import imutils import pprint from matplotlib import pyplot as plt import random import os def extractSkin(image): # minRange for min skin color Rnage # maxRange for maximum skin color Range ...
from __future__ import print_function, division import pandas as pd from IPython.display import Image import PIL import torch import torch.nn as nn import torch.optim as optim from torch.optim import lr_scheduler import numpy as np import torchvision from torchvision import datasets, models, transforms import matplotl...
# -*- coding: utf-8 -*- import os import queue import socket import threading import time import manta_lab as ml from manta_lab.tuning.interface.agent import ( Agent, Command, CommandType, Job, RunStatus, terminate_thread, ) # TODO: api.register_agent, request_tune_schedule # TODO: os.environ...
from copy import deepcopy import os import json from pyspark.sql.session import SparkSession from .settings import Settings, complete_settings_dict from .charts import ( load_chart_definition, altair_if_installed_else_json, _load_multi_chart_template, _load_external_libs, _make_json, ) import log...
""" Helpers for Socrata Export Author: Austin Transportation Department, Data & Technology Services Description: This script contains methods that help in the download of records from Hasura and upserting into an existing Socrata data table. The application requires the requests and sodapy libraries: https://pypi...
# Copyright 2019 The FastEstimator Authors. 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...
# -*- coding: utf8 -*- import os import unittest import tempfile import sys IS_PY3 = sys.version_info[0] == 3 if IS_PY3: unicode = str skipUnless = getattr(unittest, "skipUnless", None) if not skipUnless: def skipUnless(*args, **kwargs): def wrapper(thing): return thing return wrapper ...
import copy import sys import torch import torch.nn as nn import spacy # from pytorch_transformers import BertModel, BertConfig from pytorch_transformers import BertModel, BertConfig from torch.nn.init import xavier_uniform_ from bert_models.decoder import TransformerDecoder from bert_models.encoder import Classifier,...
#!/usr/bin/env python """ Use this to help speed up manual conversion of e.g. GWT Java to e.g. Pyjamas python TODO: in java2pythonlinebyline and redofunctions, identify a list of variables and functions, and do replace "variable" with "self.variable" """ import sys import string def import_gwt_to_pyjamas...
import torch import numpy as np import torch.nn as nn import torch.nn.functional as F from sklearn.metrics import log_loss class BaselineTrainable(): def __init__(self, net, optimizer, criterion, train_dataset, val_dataset, batch_size=128, save_dir="best_checkpoint.pth", num_epoch=10): ...
import os import sys import json import math import shlex import click import shutil import logging import subprocess import multiprocessing from fnmatch import fnmatch from collections import defaultdict, deque from hpsspy import HpssOSError from hpsspy.os.path import isfile from emmet.cli.utils import VaspDirsGenera...
import h5py import os import re import numpy as np import glob import json import os def dumper(obj): try: return obj.toJSON() except: return obj.tolist() def read_avg(filepath): with open(filepath, encoding="utf8", errors='ignore') as f: lines = [line for line in f.readlines() ...
import logging from queue import Empty from dateutil.relativedelta import relativedelta import settings from event.event import * from mt4.constants import PERIOD_CHOICES, get_candle_time, PERIOD_H1, get_mt4_symbol, PERIOD_D1 from utils.market import is_market_open from utils.redis import system_redis, set_last_tick,...
import torch import copy import os import operator import re import json import numpy as np import torch.nn as nn from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate from torch.utils.data.sampler import BatchSampler, SequentialSampler, RandomSampler from vilmedic.networks ...
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from Bio.SeqUtils.ProtParam import ProteinAnalysis import numpy as np import os from datetime import datetime def create_sequence_properties_dataframe(sequences): print("---- Creating properties for the all data. This may take a few mins de...
# Copyright [2020] [Toyota Research Institute] # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
from datetime import datetime, timedelta, timezone from tinydb import TinyDB, Query import ftx import pandas as pd class FTXObject: def __init__(self, token): for key in token: setattr(self, key, token[key]) class LeveragedToken(FTXObject): def calc_pending_rebalance(self): """...
import torch,torchvision import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision.utils import save_image from utils import * class Generator(nn.Module): """ Generator class. """ def __init__(self): super(Generator, self).__init__() self...
#!/usr/bin/env python2.7 # Author : <NAME> (<EMAIL>) # # Description : This code reads the KSTAR MIR data via the iKSTAR server # # Acknowledgement : Dr. Y. Nam and Prof. G.S. Yun # import numpy as np import h5py MNUM = 10000000 # totla number of samples in an ECEI channel VN = 16 # number of vertical arrays cla...
#!/usr/bin/env python3 import configparser import logging import os import threading import time import lights from lights.device_unicornhat import UnicornHat from lights.device_osc_grid import OSCGrid import lights.programs as light_programs logging.basicConfig(level=logging.DEBUG, format='%(lev...
from datetime import datetime from os import PathLike, scandir from pathlib import Path from subprocess import DEVNULL, Popen, check_output from typing import Iterable, Sequence, Tuple TIMESTAMP_FORMAT = '%Y%m%d-%H%M%S' DATA_PATH = Path('data') OUTPUT_PATH = Path('output') SLURM_PATH = Path('slurm_generated') data_p...
from __future__ import print_function import os from skimage.transform import resize from skimage.io import imsave import numpy as np from keras.models import Model from keras.layers import Input, concatenate, Conv2D, MaxPooling2D, Conv2DTranspose from keras.optimizers import Adam from keras.callbacks import ModelChec...
import logging from typing import Dict #import game constant and make them available to the program from lux.constants import Constants from lux.constants import GAME_CONSTANTS UNIT_TYPES = Constants.UNIT_TYPES RESOURCE_TYPES = Constants.RESOURCE_TYPES from lux.game_map import Position from lux.game_map i...
import discord import random import os from discord.ext import commands, tasks from discord.ext.commands import Context from dotenv import load_dotenv load_dotenv() DISCORD_TOKEN = os.getenv("discord_token") # Get the API token from the .env file. PREFIX = os.getenv("command_prefix") # Get the command prefix from the...
import dataclasses import datetime import logging import re from dataclasses import dataclass, field from functools import partial from multiprocessing.dummy import Pool as ThreadPool from typing import Dict, List, Set import pkg_resources import yaml # pylint: disable=wrong-import-order import dateutil.parser # py...
"""KDE and histogram plots for multiple variables.""" import numpy as np from ..data import convert_to_dataset from ..stats import hpd from .kdeplot import _fast_kde from .plot_utils import ( _scale_fig_size, make_label, xarray_var_iter, default_grid, _create_axes_grid, ) from ..utils import _var_n...
import logging import os import sys from pathlib import Path import numpy as np from scipy import spatial from lib.dataset import VoxelizationDataset, DatasetPhase, str2datasetphase_type from lib.pc_utils import read_plyfile, save_point_cloud from lib.utils import read_txt, fast_hist, per_class_iu CLASS_LABELS = ('w...
import os, time, multiprocess import configparser import subprocess from compute import Config_ini from compute.log import Log import json from compute.db import add_info, get_available_gpus, confirmed_used_gpu import random def parse_nvidia_info(gpu_enabled_list, nvidia_info): # 2. split the output ...
from __future__ import unicode_literals from __future__ import absolute_import, division, print_function """ This module provides an object cacheing framework for arbitrary Python values. The intent is thatall cacghe logic can be isolated, and may be re-implemented using a network cache faclity such as MemCache or Red...
import cv2 import json from tqdm import tqdm import pandas as pd from .bb_polygon import * def draw_arrow(image, start_point, end_point, color): start_point = tuple(start_point) end_point = tuple(end_point) image = cv2.line(image, start_point, end_point, color, 3) image = cv2.circle(image, end_point, 8...
### Rubik's cube solver ### # Inspired from http://beust.com/rubik/ and personal knowledge # Imports functions to do the movements from cube_functions.fonctions_logique import * from cube_functions.constantes import * # DEFINE SEARCH FUNCTION def _cubesearch(rubik, side_filter, color_filters, xyz_filter = (-1, -1, -...
import datetime import numpy as np import pandas as pd from six import iteritems from six.moves import zip from zipline.utils.numpy_utils import NaTns, NaTD def next_date_frame(dates, events_by_sid, event_date_field_name): """ Make a DataFrame representing the simulated next known date for an event. Pa...
# -*- coding: UTF-8 -*- # # Authors: <NAME> <<EMAIL>> # # # License: BSD (3-clause) import os.path as op from collections import namedtuple import re import numpy as np from ..base import BaseRaw from ..meas_info import create_info from ..utils import _read_segments_file, _mult_cal_one from ..constants import FIFF fr...
import torch import torch.nn as nn import torch.nn.functional as F import omni_torch.networks.initialization as init from omni_torch.networks import blocks as omth_blocks # Compare with the vanilla implementation here: # https://github.com/pytorch/vision/blob/master/torchvision/models/inception.py class InceptionNet_...
""" Environment for training, validation, and testing A state consists of a batch of partially parsed sentences The environment takes a bactch of actions to update the state It also pre-computes the token embeddings and splits a data batch in to multiple subbatches """ import torch import torch.nn as nn from torch.uti...
"""Config flow for Meross IoT local LAN integration.""" from typing import OrderedDict from time import time from uuid import uuid4 from hashlib import md5 from base64 import b64encode from logging import DEBUG import async_timeout import voluptuous as vol from homeassistant import config_entries from homeassistant.c...
""" Finite difference weights ========================= This module implements an algorithm for efficient generation of finite difference weights for ordinary differentials of functions for derivatives from 0 (interpolation) up to arbitrary order. The core algorithm is provided in the finite difference weight generat...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import random import numpy as np import logging import tensorflow as tf from tensorflow.contrib.keras import utils from constant import * import utility from dataset import DataBatchIter...
import os from datetime import datetime import requests import xmltodict from flask import Flask, jsonify, request, send_file, abort app = Flask(__name__) url = 'http://opendata-tr.ratp.fr/wsiv/services/Wsiv' line_id_transco = { 'metro': 'M', 'rer': 'R', 'sncf': None, 'noctilienratp': 'B', 'busra...
# plays conway game of life, showing a set of initial boards # that will lead to the provided end board import os ############################## # create combination of characters # construct recursively def combSimp(val,numVal,soFar,left,acc): # go through each val if len(left) == 0 or numVal == 0: acc.append...