text
stringlengths
3.07k
12.6k
#!/usr/bin/python3 from sense_hat import SenseHat from time import sleep import requests import RPi.GPIO as GPIO import time from datetime import datetime import sqlite3 conn = sqlite3.connect('intruders.sqlite3') ''' # Sqlite3 Schema: sqlite> CREATE TABLE intruders (clocktime TEXT, timestamp TEXT, pm10 TEXT, pm25 T...
# uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\audio\primitive.py # Compiled at: 2019-09-23 19:34:26 # Size of source mod 2**32: 9459 bytes from pr...
""" Contains functions to test given lotlan files and strings as well as a test enviroment for validating lotlan grammar and semantic checks """ # standard libraries import sys from contextlib import contextmanager import codecs import errno import argparse # 3rd party lib from antlr4 import InputStream, Comm...
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 # Distributed training via Horovod. # # This tutorial demonstrates how to distribute SVI training across multiple # machines (or multiple GPUs on one or more machines) using the Horovod # library. Horovod enables data-parallel training...
#!/usr/bin/env python3 # 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. """ Helper script to pre-compute embeddings for a flashlight (previously called wav2letter++) dataset """ import argpa...
from cPickle import dumps from cPickle import loads from types import NoneType from pyavro_rs._lowlevel import ffi, lib CODEC_NULL = lib.AVRO_CODEC_NULL CODEC_DEFLATE = lib.AVRO_CODEC_DEFLATE lib.avro_init() class AvroError(Exception): def __init__(self, err, message): self.err = err self.messa...
# Copyright 2019 United Kingdom Research and Innovation # Author: <NAME> (<EMAIL>) """Pure numpy implementation of RALEIGH dense algebra. """ import numpy from .dense_ndarray import NDArrayVectors, NDArrayMatrix class Vectors(NDArrayVectors): '''Pure numpy implementation of ndarray-based Vectors type. '''...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Mar 25 14:39:46 2020 @author: charlotte """ import argparse parser = argparse.ArgumentParser() parser.add_argument('--nbands',type=int, help='number of bands; default = 10', default=10) parser.add_argument('--kgrid',type=int, help='number of kpoints pe...
from datetime import datetime, timedelta import pytest from django.urls import reverse import recurrence from cash.models import Expense, Income, Transaction from cash.views import UpdateIncomeRelationsMixin @pytest.mark.django_db def test_create_expense(client, income_series): income_in_the_middle = income_s...
# Copyright iris-abf contributors # # This file is part of iris-abf and is released under the BSD 3-clause # licence. See LICENSE in the root of the repository for full licensing # details. """ Unit tests for `iris.io.plugins.abf`. """ from unittest.mock import Mock, call, patch, sentinel import numpy as np import pyt...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import os import subprocess import tempfile from typing import Hashable, Sequence import click import numpy as np import xarray as xr from .gsutil import authenticate, download_directory, cp MOSAIC_FILES_URL_DEFAULT = ( "gs://vcm-ml-raw/2020-11-12-gridspec-orography-and-mosaic-data" ) class FregridLatLon: de...
from typing import Optional, Dict, List, Any import radixlib as radix import config import json def get_all_transactions( wallet: radix.Wallet ) -> List[Dict[str, Any]]: """ Gets all of the transactions where this wallet was involved. """ current_cursor: Optional[str] = None transactions: List[Dict[st...
# -*- coding: utf-8 -*- import re import requests from bs4 import BeautifulSoup from bs4.element import Tag from django.utils.translation import get_language import six if six.PY3: unicode = str class BaseDataProvider(object): """ Basic data provider with base methods, helpers and universal parsers "...
# Create your views here. from django.shortcuts import render_to_response, get_object_or_404 from ox.django.shortcuts import render_to_json_response, get_object_or_404_json from django.template import RequestContext from models import Feature, FeatureType, AuthorityRecord, Relationship from django.core.exceptions impor...
from micromort.resources.configs.mongodbconfig import mongodb_config import pymongo from datetime import datetime import re import micromort.constants as constants import os from tqdm import tqdm import pickle import h5py FILE_PATHS = constants.PATHS OUTPUTS_DIR = FILE_PATHS['OUTPUTS_DIR'] ARTICLE_LENGTH_THRESHOLD = c...
"""Thomson Problem solver""" import itertools import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d.art3d import Poly3DCollection from scipy.spatial import ConvexHull # Plot creation and parameters fig = plt.figure() ax = Axes3D(fig) ax.set_aspect("equal"...
import re import os import six import socket import time import threading import datetime from six.moves.queue import Empty from Utils import readDelimitedData, timeoutSecs #------------------------------------------------------------------------------ # JChip delimiter (CR, **not** LF) CR = u'\r' #---------------...
import math def distance( p1, p2 ): return math.sqrt( ( p1[0] - p2[0] ) ** 2 + ( p1[1] - p2[1] ) ** 2 ) #returns a path (list of points) through s with high value def ellinit_replacement( s1, start_point, end_point, tmax ): s = list( s1 ) path = [ start_point, end_point ] length = distance( start_poin...
# Copyright 2021 The BladeDISC 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 applicable law or ...
# rule is a class that describes a transition between states import abc from dataclasses import dataclass, field, replace from typing import Callable, List, Union, NamedTuple, Tuple, Any from lru import LRU from pampy import match from tabulate import tabulate import hashlib @dataclass() class RuleEdge: converte...
#!/usr/bin/env python # -*- coding: utf-8 -*- # I waive copyright and related rights in the this work worldwide # through the CC0 1.0 Universal public domain dedication. # https://creativecommons.org/publicdomain/zero/1.0/legalcode # Author(s): # <NAME> <<EMAIL>> """Retrieve files from GINA """ import json impo...
from django.http import HttpResponse from django.contrib.auth.decorators import login_required, permission_required from ui.models import Game, Turn, Field, UnitType, City, Unit, Country, CityCommand, Command from ui.engine.TurnProcessor import TurnProcessor from ui.engine.Engine import Engine @login_required d...
import torch.nn as nn from .resnet_layers import BasicBlock, Bottleneck from maskrcnn_benchmark.utils.model_zoo import cache_url __all__ = ['resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152'] model_urls = { # MBv2-encoder pre-trained on ImageNet 'mobilenetv2' : ['mobilenetv2-e6e8dd43.pth', ...
"""RGCN layer implementation""" import torch as th import torch.nn as nn import torch.nn.functional as F import dgl.nn as dglnn from . import BaseModel, register_model @register_model('RGCN') class RGCN(BaseModel): @classmethod def build_model_from_args(cls, args, hg): return cls(args.in_dim, ...
import sympy as sp import numpy as np from scipy.stats import cauchy, laplace from typing import Sequence import abc class KoopmanObservable(abc.ABC): def __init__(self): pass def __call__(self, X: np.ndarray) -> np.ndarray: return self.obs_fcn(X) @abc.abstractmethod def obs_fcn(self...
""" OTWindow allows running wxPython widgets Widgets using wxPython must all be created and run in the same thread. This class creates a wxPython App in a separate thread and allows starting new widgets in this same thread. New widgets can be created using the functions newMsgWin(tw) create message windiow and execut...
import logging # logger.basicConfig(filename=f"{__name__}.log") logger = logging.getLogger(__name__) sHandler = logging.StreamHandler() sHandler.setLevel(logging.INFO) logger.addHandler(sHandler) logfilenode = __file__.rsplit('.')[0] handler = logging.FileHandler(f"{logfilenode}.log") handler.setLevel(logging.INFO) for...
import os import pickle import sys import traceback import typing from collections import defaultdict from typing import Tuple, Optional from sherpa import Client from d3m import container, runtime, primitives from d3m import index from d3m.metadata import base as metadata_base, pipeline, problem, pipeline_run from d3...
"""Function to be called by workflow""" import os from datetime import datetime from .query import Query from .utils import ( load_rates, load_currencies, refresh_rates, refresh_currencies, calculate, generate_items, currencies_filter ) __all__ = [ "load", "convert", "add", ...
""" 本模块的所有内容都只针对于认证模块的app, """ # from aiomotorengine import DateTimeField # from aiomotorengine import FloatField # from aiomotorengine import IntField # from aiomotorengine import ReferenceField # from aiomotorengine import StringField # # from xt_base.document.auth2_docs import ProductResource # from xt_base.document...
from utils.encoders import IEncoder import numpy as np import torch import torch.nn as nn # for now i ported only FasterGRUEncoder, LSTM + classic GRU in in TODO list class GruLayer(nn.Module): def __init__(self, in_count, out_count, bias): super().__init__() self.net = nn.GRU( i...
#!/usr/bin/env python3 import os, logging, sys, webbrowser from kiyoproctrls import KiyoProCtrls, find_usb_ids_in_sysfs, get_device_capabilities, V4L2_CAP_VIDEO_CAPTURE try: from tkinter import Tk, ttk, PhotoImage except Exception as e: logging.error(f'tkinter import failed: {e}, please install the python3-tk...
import re import typing as t from collections import defaultdict, namedtuple from types import SimpleNamespace from .exceptions import InvalidUsage, ParameterNameConflicts, RouteExists from .patterns import REGEX_TYPES from .utils import Immutable, parts_to_path, path_to_parts ParamInfo = namedtuple( "ParamInfo",...
# VARIABLES GLOBALES MISMATCH = -1 MATCH = 1 GAP = -2 matrix = [] def clean_matrix(): global matrix matrix = [] # MODIFICA LOS VALORES DE MATCH, MISMATCH Y GAP SI EL USUARIO LO SOLICITA def setValues(new_match, new_mismatch, new_gap): global MISMATCH global MATCH global GAP if(new_mismatch ...
from config import * from google.appengine.ext import ndb from google.appengine.api import search from google.appengine.api import users from decimal import * import logging class DynamicPropertyMixin(object): def is_prop(self, name): return name in self._properties def set_dynamic_prop(self, cls,...
import json import os from collections import defaultdict import numpy as np from imblearn.combine import SMOTEENN, SMOTETomek from imblearn.over_sampling import ADASYN, SMOTE, SVMSMOTE, RandomOverSampler from scipy.sparse import coo_matrix from sklearn.model_selection import (RandomizedSearchCV, StratifiedKFold, ...
import math from datetime import timedelta import numpy as np from libraries.tsdb.opentsdb_helper import OpentsUtil from libraries.tsdb.tsdb_helper import TSdbUtil from pii.libraries.utils.time_util import TimeUtil from model.gf_device_attr import DeviceAttrModel from pii.vendors.pii_dsl.PiiDsl.PiiDslParser import Pi...
from __future__ import division from __future__ import print_function import os import glob import numpy as np import cv2 from skimage.metrics import peak_signal_noise_ratio as compare_psnr from skimage.metrics import structural_similarity as compare_ssim import skimage.data import skimage.transform from multiprocessin...
import numpy as np import cv2 import tensorflow as tf from weapons.Se_0a import seg_model def seg_to_vertices(img, use_dilated = False): if use_dilated: # dilate thresholded image - merges top/bottom kernel = np.ones((3,3)) dilated = cv2.dilate(img, kernel, iterations=3) current_im...
# Copyright (c) 2013 <NAME> <<EMAIL>> # 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 requ...
# -*- coding: cp1252 -*- # ------------------------- # # Description: # A collection of functions which implement special maths functions in my Masters dissertation. # ------------------------- # # Created by: <NAME>, RRSG, UCT. # Date created: 21 July 2016 # Edits: 22 July 2016: added fn_Create_Concatenated_Blo...
''' @Author: <NAME> @Date: 2019-10-28 01:01:52 @LastEditors : <NAME> @LastEditTime : 2020-01-07 01:33:49 @Description: file content ''' import numpy as np import os import torch from torch.utils.data import TensorDataset,DataLoader class ModelWrapper: def __init__(self,model,batch_size = 128): self.mode...
# Some sample inputs: # 123456078 523184760 502143786 import pygame, random, sys from queue import Queue GREEN = (144, 232, 76) BLACK = (0, 0, 0) RED = (255, 0, 20) WINDOW_HEIGHT = 400 WINDOW_WIDTH = 400 board = [[None for i in range(3)] for j in range(3)] index = () val = None def computeHash(board): val =...
"""container_rack_overhaul Revision ID: 1d6d30bd88b6 Revises: <PASSWORD> Create Date: 2015-01-07 10:54:12.903913 """ from thelma.entities.rack import RACK_TYPES from thelma.entities.container import CONTAINER_TYPES # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '4cc7cebe2c0' from alembi...
""" 本ライブラリ実行前に、h2dbを以下のオプションで起動する java -cp h2-1.4.200.jar org.h2.tools.Server -webAllowOthers -tcpAllowOthers -pgAllowOthers -baseDir ../data/ -ifNotExists -tcpAllowOthers 外部からの接続を許す -pgAllowOthers postgresql互換形式 -baseDir データが保存される先のDB DB名を mem:hoge とすることで、インメモリDBとして動くので何も保存されない -ifNotExists 外部接続時にテーブル作成を許可する """ impo...
import Gestion_joueur import Gestion_jeton from Strategies import * import math def fin_de_partie(cls_grille,couleur): """ Cette fonction permet de vérifier la potentielle fin de partie match nul ou un gagnant (en appelant les méthodes coup_gagnant et est_pleine de la classe Grille). Param...
from pydub import AudioSegment import os import numpy as np from tqdm import tqdm from joblib import Parallel, delayed from python_speech_features import logfbank import scipy.io.wavfile as wav import argparse parser = argparse.ArgumentParser(description='Librispeech preprocess.') parser.add_argument('root', metav...
# -*- coding: utf-8 -*- """ Tokenization tests. """ from deepmoji.tokenizer import tokenize import sys from nose.tools import nottest from os.path import dirname, abspath sys.path.append(dirname(dirname(abspath(__file__)))) TESTS_NORMAL = [ ('200K words!', ['200', 'K', 'words', '!']), ] TESTS_EMOJIS = [ ('i \...
import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.interpolate import interp2d import numpy as np import os def plot_data(ID, model_dir='./Data/', Rm_Outliers=False, Filter=True, Plot_Error=False, HIRES=False, COEFF=False): mpl.style.use('classic') ...
#!/usr/bin/python3 import os, sys, inspect top_folder = os.path.split(os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])))[0] if top_folder not in sys.path: sys.path.insert(0, top_folder) import unittest import importlib def runalltests(**kwargs): settings = {'ve...
""" This module provides functions for creating ``matplotlib`` plots of "raw" and calibrated light curves as well as folded time series. :License: :doc:`LICENSE` .. moduleauthor:: <NAME> <<EMAIL>> """ import os import numpy as np import matplotlib.pyplot as plt def _bin_folded_points(tls_results, duration_period_...
#!/usr/bin/env python # encoding: utf-8 from typing import List import numpy as np from transformers import BertModel, BertConfig from torch.nn import TransformerDecoder, TransformerDecoderLayer, Module, Linear, \ Sigmoid, LayerNorm, Embedding from torch import Tensor, arange def total_params(module): """B...
import torch import torch.nn as nn class MultiHeadAttention3d(torch.nn.Module): def __init__(self, in_channels, total_key_filters, total_value_filters, out_channels, num_heads, dropout_prob=0.5, layer_type='SAME'): super(MultiHeadAttention3d, self).__init__() if total_key_filters...
from json import load import os import sys import time import argparse import numpy as np from tqdm import tqdm from tensorflow.keras.models import load_model import tensorflow.lite as tflite def time_tf_model(model, num_timesteps, num_features, model_type, num_runs): # define model input shape if model_...
import os import os.path as osp import torch import torchvision import argparse import yaml import tqdm import glob import cv2 import numpy as np import utils.util as util import data.util as data_util import models.archs.EDVR_arch as EDVR_arch class EDVRWrapper: def __init__(self, **conf): self.CUDA_VIS...
from __future__ import division from __future__ import print_function import argparse import numpy as np import os import tensorflow as tf from utils.data import load_data from utils.data import one_hot_encode BATCH_SIZE = "batch_size" CELL_SIZE = "cell_size" def predict(dataset, model, model_path, **kwargs): ...
''' dataset specific layer for megadepth ''' import os import json import random from collections import namedtuple import numpy as np from COTR.datasets import colmap_helper from COTR.global_configs import dataset_config from COTR.sfm_scenes import knn_search from COTR.utils import debug_utils, utils, constants Sc...
''' Detects anomalies in sounds ''' import numpy as np import unittest from numpy.testing import assert_array_almost_equal,assert_almost_equal, assert_equal from abc import ABCMeta, abstractmethod import math class AnomalyDetector(object): # basic dependency injection def __init__(self, logger, repository): ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 14 15:48:33 2021 @author: nicolasnavarre """ from collections import defaultdict import pickle import pandas as pd df_save = 'df/' def save_data(POM_global, POM_data): df1 = POM_global df_dict = df1.to_dict(orient = 'index') dict_...
#unicode Python3 Steven import pandas as pd import numpy as np import matplotlib.pyplot as plt from time import time from sklearn.metrics import silhouette_score from sklearn.metrics import silhouette_samples from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler,MinMaxScaler from sklear...
""" Module for comparing different cluster algorithms. - cluster analysis """ import abc import typing as tp import warnings from itertools import islice, cycle import matplotlib.pyplot as plt import numpy as np import seaborn as sns from sklearn import cluster, mixture from sklearn.neighbors import kneighbors_graph ...
class Node: def __init__(self, value): self.val = value self.next = None self.prev = None class MyLinkedList: def __init__(self): """ Initialize your data structure here. """ self.head = None self.tail = None sel...
import os import requests import shutil import six import unittest from . import server from nose.tools import eq_, ok_ from orderedattrdict import AttrDict tempfiles = AttrDict() folder = os.path.dirname(os.path.abspath(__file__)) def setUp(): # Remove uploads folder before Gramex locks .meta.h5 # This may ...
''' Copyright (C) 2016 Turi All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. ''' from .config import DEFAULT_CONFIG as CONFIG from .metric_mock import MetricMock from .sys_info import get_distinct_id, get_sys_info, get_version, get...
# -*- coding: utf-8-*- # # The MIT License (MIT) # # Copyright (c) 2017 <NAME> <<EMAIL>> # # 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 th...
import numpy as np import matplotlib.pyplot as plt import cv2 from Finding_Lane import find_lane_pixels from Binary_Img import threshold_binary def generate_polynomials(binary_warped, ym_per_pix, xm_per_pix): ''' Generates the second order polynomial ''' # Find our lane pixels leftx, lefty, right...
from functools import partial from operator import ge, le from typing import Callable, Dict, List, Tuple import numpy as np import zarr from fixpoint import * from numpy import linalg as LA from utils import * def jacobi_diis(A, b, rtol=1.0e-8, etol=1.0e-8, ...
# -*- coding: utf-8 -*- from __future__ import print_function import os import numpy as np import argparse import paddle import paddle.fluid as fluid from paddle.fluid.incubate.fleet.collective import fleet, DistributedStrategy from paddle.fluid.incubate.fleet.base import role_maker import model import utils parser ...
# Copyright 2014 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, ...
""" I/O module for BRAIN files (Matlab NDT library of Universiy of Bristol). Implemented as of 20/6/2016: - dtype of variables is according to settings.py - get element dimensions from el_x1, el_y1, el_z1, el_x2, el_y2, el_z2: Information calculated is probe orientation dependent. """ import numpy as np from ...
''' Created on 22/05/2015 @author: user ''' from optparse import OptionParser import numpy from convert_geo_pca_to_nmd import load_sequences from pyRMSD.RMSDCalculator import RMSDCalculator from pca.emPCA import empca from anmichelpers.writers.pronmd import ProdyNMDWriter def get_seq_positions_with_known_residues(seq...
# Copyright 2009-2017 <NAME>. # This program is distributed under the MIT license. '''Module for doing a binary search in a sequence.''' # Todo: wrap all things in tuples? # # todo: add option to specify `cmp`. # # todo: i think `binary_search_by_index` should have the core logic, and the # other one will use it. I...
import os import numpy as np import tensorflow as tf import collections import logging from utils import tokenizer logging.basicConfig(level=logging.INFO) class InputExample(object): def __init__(self, guid, x, y=None): self.guid = guid self.x = x self.y = y class InputFeatures(object):...
""" This module contains data structures for the Tactics level of STP. """ from abc import ABC, abstractmethod from typing import Dict, Generic, List, Optional, Tuple, Type, TypeVar import stp.action as action import stp.rc as rc import stp.role as role import stp.skill as skill import stp.utils.enum as enum import s...
import argparse import sys from twisted.internet import reactor import core import clients.logging def _run(args, known_arg_options): retval = 1 logger = clients.logging. \ Client('manof', initial_severity=args.log_severity, initial_console_severity=args.log_console_se...
"""Rule Generator for Forseti's IAM Scanner. Creates global rules to require a domain group as owner and a blacklist to prevent user members in project-level roles. Also creates a global bucket whitelist, restricting to Google groups, users and service accounts. Project-specific whitelists are created for project-lev...
import time import select import socket import struct import threading import errno from .amspacket import AmsPacket from .adsconnection import AdsConnection from .adsexception import AdsException from .commands import * class InvalidPacket(AdsException): pass class AdsClient: def __init__(self, adsConnecti...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright 2021 Recurve Analytics, 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...
"""Movie Voting System: Optimize your movie choices""" import inspect from textwrap import wrap import gspread import numpy import terminaltables from google_auth_oauthlib.flow import Flow class Credentials: "This is a complete hack to work with gspread and google-auth." def __init__(self, token, refresh): ...
# -*- coding: utf-8 -*- """ Created on Thu Jul 19 09:17:25 2018 @author: zyv57124 """ import numpy as np import pandas import sys import matplotlib.pyplot as plt import scipy.io as sio import tensorflow as tf import sklearn from tensorflow import keras from sklearn.model_selection import train_test_split import math ...
import unittest from unittest import TestCase import e2cnn.nn.init as init from e2cnn.nn import * from e2cnn.gspaces import * import torch from torch.optim import SGD from torch import nn import numpy as np class TestModuleList(TestCase): def test_expand(self): for gs in [Rot2dOnR2(9), Fl...
# -*- coding: utf-8 -*- import numpy as np from collections import Counter from more_itertools import unique_everseen from xarl.utils.running_statistics import RunningStats import itertools from sklearn.cluster import * class none(): def __init__(self, **args): pass def get_episode_type(self, episode): return '...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Perform syntax highlighting on Scribe logs. """ import sys, os, re import time import errno import instabot # Hard-coded ANSI escape sequences for coloring. COLORS = {None: '\033[0m', 'bold': '\033[1m', 'black': '\033[30m', 'red': '\033[31m', 'green': '\033[32m...
import numpy as np import tensorflow as tf from tensorflow import keras from tensorflow.compat.v1 import ConfigProto from tensorflow.compat.v1 import InteractiveSession import custom_layer import train_gen import compare import pickle def log_amps(data): # the commentet out lines are required if amp...
#!/usr/bin/env python import asyncio import logging import socket import sys import time import unittest from argparse import ArgumentParser from concurrent import futures from contextlib import suppress from pathlib import Path from unittest.mock import MagicMock from httpx import AsyncClient from requests import Re...
import json from abc import ABC, abstractmethod from random import randrange from .AudioTrack import * from .Events import * from .Player import * class PlayerManager: def __init__(self, bot): self.bot = bot self._players = {} def __len__(self): return len(self._player...
from github import Github import github from github import NamedUser, PaginatedList, Organization import os import typing as t import time from collections import defaultdict g = Github() class User: #user has to be github object def __init__(self, user : NamedUser): self.user = user def getinfo(self): pri...
import csv import json import jwt import requests from django.conf import settings from django.contrib import messages from django.contrib.auth import authenticate from django.contrib.auth import login as log_in from django.contrib.auth import logout as log_out from django.contrib.auth.decorators import login_required...
# Load the necessary libraries import matplotlib.pyplot as plt import numpy import pandas # Define a function to visualize the percent of a particular target category by a nominal predictor def TargetPercentByNominal ( targetVar, # target variable targetCat, # target category predictor, ...
from mach_utils import * import logging from argparse import ArgumentParser from fc_network import FCNetwork import tqdm from dataset import XCDataset import json from typing import Dict, List from trim_labels import get_discard_set from torchnet.meter import APMeter import sklearn.metrics as sm def get_args(): p...
from ctypes import * import subprocess import numpy as np import os import cv2 import time os.system('go build -o talkdet.so -buildmode=c-shared talkdet.go') pigo = cdll.LoadLibrary('./talkdet.so') os.system('rm talkdet.so') MAX_NDETS = 2024 ARRAY_DIM = 6 MOUTH_AR_THRESH = 0.2 MOUTH_AR_CONSEC_FRAMES = 5 def verify...
from helpers import perror, pdebug, pout from exceptions import TaskExecutionException import traceback import time import json """ TODO redo task return values as enums """ """ TODO remove explicit file dependencies and replace them with tasks and provides_for relationships """ class ContextEntry(object): "...
import numpy as np import pandas as pd from scipy.spatial.transform import Rotation as R from scipy import interpolate def get_matrix_from_ext(ext): N = np.size(ext,0) if ext.ndim==2: rot = R.from_euler('ZYX', ext[:,3:], degrees=True) rot_m = rot.as_matrix() tr = np.zeros((N,4,4))...
import re import sys from pathlib import Path C_INSTRUCTION_PTRN = "(?P<dest>[AMD]{1,3}=)?(?P<comp>[01\-AMD!|+&><]{1,3})(?P<jump>;[JGTEQELNMP]{3})?" JUMP_REG_GROUP = "jump" COMP_REG_GROUP = "comp" DEST_REG_GROUP = "dest" VARIABLE_START_ADDR = 16 LABEL_PREFIX_AND_SUFFIX = "()" LABEL_SUFFIX = ")" LABEL_PREFIX = "(" A_...
# importing time module import time start = time.time() #countdown start # request library is used for establishing and fetching data from internet import requests # bs4 library is used for parsing and extracting text data from webpage import bs4 # sys library is for system calls import sys # re library ...
# Copyright European Organization for Nuclear Research (CERN) # # 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 # # Authors: # - <NAME>, <<EMAIL>>, ...
"""Tooling to calculate Standardized Precipitation Index (SPI).""" from math import log, sqrt import numba import numba.core.types as nt import numba_scipy # pylint: disable=unused-import import numpy as np import scipy.special as sc @numba.njit def brentq(xa, xb, s): """ Root finding optimization using Bre...
import pytest import random from collections import defaultdict, namedtuple from functools import reduce from itertools import chain from typing import List, NewType from odin.dag import ( Graph, Node, rev_graph, topo_sort, topo_sort_kahn, topo_sort_parallel, find_children, _find_childre...
from django.db import models from django.urls import reverse from django.utils import timezone from django.contrib.auth.models import AbstractUser from django.utils.translation import gettext_lazy as _ from imagekit.models import ProcessedImageField from imagekit.processors import ResizeToFill from itez.beneficiary.m...