text
stringlengths
3.07k
12.6k
"""LQR, iLQR and MPC.""" import numpy as np import scipy #.linalg.solve_continuous_are as func from ipdb import set_trace as debug def prRed(prt): print("\033[91m {}\033[00m" .format(prt)) def prGreen(prt): print("\033[92m {}\033[00m" .format(prt)) def prYellow(prt): print("\033[93m {}\033[00m" .format(prt)) def pr...
# tree_stages.py from typing import Tuple, List from math import ceil, log2 # import src.tree_support import tree_support def sel_construct_module_declaration( subsequent_module_name: str, subsequent_module_number_of_input: int, num_select_lines: int, ) -> str: '''Declares the module with its name...
# 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 use ...
import os import sys import json import logging import threading from copy import copy from datetime import date, timedelta import boto3 import requests from six.moves.queue import Queue from six import iteritems, iterkeys from sentinel_s3.crawler import get_products_metadata_path, get_product_metadata_path from senti...
import sys sys.path.append('../..') import os import time from collections import namedtuple, defaultdict import tensorflow as tf from tensorflow.python.framework import function os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' import numpy as np from src.models.abstract_model import Model import src.models.neural.tf_utils as...
import typing from BitArray_ import BitArray as bitarray import struct class Huffman: def __init__(self, freq: typing.Optional[typing.List[int]] = None): """ This function initializes the huffman tree with freq as input. self.content: a list with lists inside. [node_id][0] is i...
# Copyright 2015 redisapi authors. All rights reserved. # Use of this source code is governed by a BSD-style # license that can be found in the LICENSE file. import unittest import mock import os from redisapi import hc class FakeHCTest(unittest.TestCase): def setUp(self): from redisapi.hc import FakeH...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # <NAME> (https://sites.google.com/view/a2gs/) from BinanceCTUtil import getTimeStamp from sys import argv, exit, stderr from os import getpid from signal import signal, SIGILL, SIGTRAP, SIGINT, SIGHUP, SIGTERM, SIGSEGV, SIGUSR1 import BinanceCTDB import socket import en...
""" Example implementation - TODO >> I should eventually delete this file altogether """ import numpy as np import matplotlib.pylab as plt # Global Variables __input_file__ = "dataset.txt" __context_size__ = 100 __arm_size__ = 10 # Function to calculate the Cummulative Take Rate def calc_CTR(reward, ctr_num, ctr_de...
from collections import namedtuple from os import path from mimetypes import guess_type from unicodedata import normalize as unicode_normalize from django.conf import settings from django.core import exceptions from django.http import HttpResponseNotFound from django.utils.encoding import force_text from django.utils....
from affine_plane_class import * import math class sl_matrix(object): def __init__(self, matrix): #assume matrix is a 2x2 nested list of finite_field_elements self.matrix = matrix self.p = matrix[0][0].p self.n = matrix[0][0].n assert self.determinant() == finite_field_elemen...
import os import _pickle as pickle from e2efold.common.config import process_config from e2efold.common.utils import get_args args = get_args() config_file = args.config config = process_config(config_file) print("#####Stage 3#####") print('Here is the configuration of this run: ') print(config) os.environ["CUDA_VI...
#! /usr/bin/env python # coding=utf-8 # ================================================================ # # Author : miemie2013 # Created date: 2020-10-15 14:50:03 # Description : pytorch_ppyolo # # ================================================================ import torch # 相交矩形的面积 def intersect(box_...
from .utils import find_shortest_path from datetime import timedelta import networkx as nx from ..common.path import PathEntity, Path def construct_path(rn, mm_traj, routing_weight): """ construct the path of the map matched trajectory Note: the enter time of the first path entity & the leave time of the ...
#!/usr/bin/env python3 import sys import os import argparse import json import copy def read_stat_file(path): with open(path, 'r') as f: json_data = f.read() parsed = json.loads(json_data) return parsed def default_value(key): if key == 'pcf_width': return 1 else: ...
# SimpleLanguageTranslator.py """Use IBM Watson Speech to Text, Language Translator and Text to Speech APIs to enable English and Spanish speakers to communicate.""" from ibm_watson import SpeechToTextV1 from ibm_watson import LanguageTranslatorV3 from ibm_watson import TextToSpeechV1 import keys # contains your A...
#!/usr/bin/env python3 # # Copyright 2018 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Output file plugin. An output file plugin to save all events and their attachments to an "events.json" file and an "attachmen...
from sqlalchemy import create_engine, and_ from sqlalchemy.orm import sessionmaker from models import * import updater import pandas as pd engine = create_engine('sqlite:///data.db', echo=True) Session = sessionmaker(bind=engine) class ServiceError(BaseException): pass # from streamlit.report_thread import get...
import json import re from typing import Tuple, Iterator, Dict, Text, Optional import mpyq import six from absl import logging from pysc2 import run_configs, maps from pysc2.env import sc2_env, environment from pysc2.env.sc2_env import possible_results from pysc2.lib import features from pysc2.lib.actions import Funct...
import os import logging from pyrogram import Client, filters from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup from info import START_MSG, CHANNELS, ADMINS, AUTH_CHANNEL, CUSTOM_FILE_CAPTION from utils import Media, get_file_details, get_size from pyrogram.errors import UserNotParticipant logger = ...
__author__ = '<NAME>' ''' Neural Bayes- Mutual Information Maximization (MIM) ''' from argparse import Namespace import argparse import math import numpy as np import os import torch import torch.nn as nn import pickle as pkl from models import CNN from utils import get_loss, get_noise from data import get_dataset imp...
from django.http import HttpResponse from django.template import RequestContext, loader from .models import PicRepertory, PicInstance, ShipRepertory, ShipPic from django.shortcuts import get_object_or_404 from django.utils import timezone from datetime import datetime import json from .my_http import post_body_to_node,...
import fractions import math import numpy import scipy.signal as signal import scipy.io.wavfile as wavfile import matplotlib.pyplot as plot import sys import wave # port of libresample to python for algorithm evaluation purpose # https://github.com/minorninth/libresample # # Original Copyright: """ Copyright (c) 2003...
#!/usr/bin/env python3 ########################################################## ## <NAME> ## ## Copyright (C) 2019-2020 Lauro Sumoy Lab, IGTP, Spain ## ########################################################## """ Searches for alleles sequences provided """ ## useful imports impo...
# # Copyright (c) 2020 Saarland University. # # This file is part of AM Parser # (see https://github.com/coli-saar/am-parser/). # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://...
from collections import defaultdict from typing import ( Any, Collection, Dict, Iterable, Iterator, List, Optional, Tuple, Type, ) from pyairtable import Table from shillelagh.adapters.base import Adapter from shillelagh.fields import Field, ISODate, ISODateTime, Order, String from ...
import logging from django.conf import settings from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned from django.db.models import Q from django_filters.rest_framework import DjangoFilterBackend from influxdb_metrics.loader import log_metric from rest_framework import mixins, viewsets, parsers...
#!/usr/bin/env python3 """ Copyright © 2020 <NAME> Functions for cell detecting and ROI extraction. Optimysed for confocal images of the individual HEK 293 cells. (mYFP-HPCA project). """ import os import logging import matplotlib import matplotlib.pyplot as plt import numpy as np from skimage.external import tif...
# -*- coding: utf-8 -*- # TextGridTools -- Read, write, and manipulate Praat TextGrid files # Copyright (C) 2011-2013 <NAME>, <NAME> # # 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 ver...
from colassigner import ColAccessor class Sides(ColAccessor): home = "home" away = "away" class CommonCols(ColAccessor): _prefix = "fe" season_id = "season_id" match_id = "match_id" event_id = "event_id" player_id = "player_id" team_id = "team_id" formation_id = "formation_id" ...
#import necessary library that exists in lab machine. import sqlite3 import xml.etree.ElementTree as ET from xml.etree.ElementTree import XMLParser, TreeBuilder #ask user for input, name of database and the inputfile. x = input("Enter name of database you wish to create: ") y = input("Enter inputfile name: ") #dec...
import glob import logging import os import shutil import tempfile from typing import Iterable, Optional from uuid import UUID, uuid4 from .exceptions import StorageError, StorageNotFoundError, StorageNotInitializedError from .storage import Storage from .utils import guess_mime_type class DefaultParams: """Defa...
import requests from urllib import unquote import re import tempfile import os from flask.ext.api import FlaskAPI from flask.ext.api import status from werkzeug.routing import BaseConverter from werkzeug.routing import ValidationError from flask import send_file from omas import meiinfo from omas import meislicer fro...
#!/usr/bin/env python3 # 2019-04-24: Wrote script # 2021-09-08: Update script to work with new star_handler module """ The goal of this script is to take an input micrographs.star file and a list of micrographs (basenames only) and return a new .STAR file where micrographs have been removed. Typically, th...
# Databricks notebook source # MAGIC %md-sandbox # MAGIC # MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;"> # MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px"> # MAGIC </div> # COMMAND ---------- # M...
import matplotlib.pyplot as plt import random from math import * import Replymsg import os from mpl_toolkits.mplot3d import Axes3D # 几个非线性函数 # 形式:(d/dt)^2x+a*(d/dt)x+sum(kn*x^n)+b*cos(c*x) # 取值 -1<=a,kn,γ,b<=1 x=1,y=1 steps=0.002,times=200 def duffing_gain(): try: x_l = [] y_l = [] ...
"""Contains the GUTime wrapper. The wrapper takes all sentences in the TarsqiDocument and creates the input needed by TimeTag.pl, which is the wrapper around TempEx.pm. The input required by TimeTag.pl looks as follows: <DOC> <DATE>20120912</DATE> <s> <lex id=1 pos="NNP">Monday</lex> <lex id=2 p...
# -*- coding: utf-8 -*- from argparse import ArgumentParser from os import listdir from os.path import basename from baselutils import fclrprint, hash_string_md5 from time import time from datetime import timedelta from segment import PostGISChannel, Segment from json import dumps from collections import OrderedDict ...
#!/usr/bin/env python2 """ time.py -- Replacement for coreutils 'time'. The interface of this program is modelled after: /usr/bin/time --append --output foo.txt --format '%x %e' Problems with /usr/bin/time: - Elapsed time only has 2 digits of precision. Apparently it uses times() rather than getrusage()? https:/...
from tqdm import tqdm import argparse import datetime import time import copy import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates def plotLong(): #Plotting messages/day vs day print("OK, now generating a long graph.") plotLongArray = copy.copy(processedArray) #A bi...
__version__ = '20200913' #yyymmdd __author__ = '<NAME> <<EMAIL>>' """Utilities for handling units and units strings. .. automodule:: units """ import numpy as np from astropy import units as u import re ## Allowed units, per category; add more as required UNITS = {\ 'ANGULAR' : ('arcsec','mas','milliarcs...
# https://groups.google.com/forum/#!topic/tvb-users/ODsL9bkGLHQ import warnings warnings.filterwarnings('ignore') import os, sys, scipy.io, json, numpy as np from nipype import Node, Function, Workflow cwd = os.getcwd() # https://miykael.github.io/nipype_tutorial/notebooks/basic_workflow.html def make_model(model_n...
import time import colorama import keyboard class Renderer: # Contains information about the rendered screen def __init__(self, x_res, y_res): # Takes a resolution as an argument self.x_res = x_res # IMPORTANT: X GOES DOWN self.y_res = y_res # IMPORTANT: Y GOES ACROSS self.grid ...
def DataGen(): start_work_age = random.randint(22, 40) exp = random.randint( 0, 25) age = start_work_age + exp edu = random.randint(0, 2) performance = random.randint(0, 2) reward = random.randint( 0, 10) relationship = random.randint(0, 2) label = 1 if relationship >= 1: ...
from typing import Union from pdb import set_trace as st import numpy as np __all__ = ["argtopk", "arg_approx", "arg_approx_signed", "repeat", "concatenate"] def get_int_k(array: np.ndarray, k: Union[int, float]) -> int: if type(k) is float: if 0.0 < k < 1.0: k = round(array.size * k) ...
import numpy import sys import math import matplotlib.pyplot as plt """ This file is used to test how sampling of a linear function should happen. """ class LinearSampler(object): """ LinearSampler is used to investigate different ways of sampling from a linear function. """ def __init__(self,...
''' ======================== efficient_vdf module ======================== Created on Feb.6, 2022 @author: <NAME> @Email: <EMAIL> @TaskDescription: This module provide efficient verifiable delay function implementation. @Reference: Efficient Verifiable Delay Functions (By Wesolowski) C++ prototype: https://github.c...
# this is a port of https://github.com/queueRAM/sm64tools/blob/master/libsm64.c # sm64_update_checksums and sm64_calc_checksums functions import struct def update_checksum(buf): cksum_offset = [0x10, 0x14] cksum = calc_checksum(buf) c0 = struct.pack_into('>I', buf, cksum_offset[0], cksum[0]) c1 =...
# # Copyright (c) 2015-2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # import collections import six from nfv_common import debug from nfv_common.helpers import Constant from nfv_common.helpers import Constants from nfv_common.helpers import Singleton from nfv_common.tasks._task_result import ...
# Copyright 2015-2016 F5 Networks 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 ...
import torch import random import numpy as np # from nasbench import api import torchvision.transforms as transforms class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0 self.cnt = 0 def update(self, val, n=1): se...
""" """ from model import NN # , PNN, FCPNN import numpy as np import tensorflow as tf from collections import defaultdict import random import os import errno import pandas as pd # number of layers in the neural network model LAYERS = [1, 2, 3, 4] # number of nodes in each hidden layer NODES = [64, 256] # learning ...
import sys,re from PySide2 import QtCore, QtGui, QtWidgets from PySide2.QtCore import (QCoreApplication, QPropertyAnimation, QDate, QDateTime, QMetaObject, QObject, QPoint, QRect, QSize, QTime, QUrl, Qt, QEvent,QRegExp) from PySide2.QtGui import (QBrush, QColor, QSyntaxHighlighter,QConicalGradient,QTextCharFormat, QCur...
import subprocess import os from PIL import Image import math import time from decimal import Decimal neuralart_dir = '/home/lukas/Dokumente/neuralart-master/' temp_dir = os.path.abspath('temp') if not os.path.exists(temp_dir): os.makedirs(temp_dir) frame_dir = temp_dir + '/frames/' style = '/home/lukas/Dokumente/...
""" dicthash.dicthash ============= A module implementing an md5 hash function for (nested) dictionaries. Functions --------- generate_hash_from_dict - generate an md5 hash from a (nested) dictionary """ # from future.builtins import str import hashlib import warnings FLOAT_FACTOR = 1e15 FLOOR_SMALL_FLOATS = False...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # <NAME> (<EMAIL>) import rospy import tf import time import math import numpy as np import common_globals import imc_enums import bb_enums from geometry_msgs.msg import PointStamped, Pose, PoseArray from geographic_msgs.msg import GeoPoint from smarc_m...
#!/usr/bin/env python # coding: utf-8 # # Project Amazon Price Tracker # # <NAME> # In[24]: from requests_html import HTMLSession import csv import datetime as datetime import time import re from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from bs4 import BeautifulSoup import p...
# SPDX-FileCopyrightText: 2020 Efabless 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 o...
from bokeh.palettes import Plasma, Plasma256 def light_spec_approximation(x): #map input [0, 1] to wavelength [350, 645] w = 370 + x * (645-370) r = 0.0 g = 0.0 b = 0.0 if w < 440: r = -(w - 440.) / (440. - 380.) b = 1.0 elif w >= 440 and w < 490: g = (w - 440.) / (4...
''' MIT 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 Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distri...
# Copyright 2021 Toyota Research Institute. All rights reserved. from copy import deepcopy import numpy as np from camviz.objects.quaternion import Quaternion from camviz.utils.geometry import unitX, unitY, unitZ from camviz.utils.utils import numpyf, add_col1 def rot2quat(R): """Convert rotation matrix to qu...
import sys import os sys.path.append(os.getcwd()) import time import numpy as np from sklearn.cluster import AffinityPropagation from sklearn import metrics from cluster.prepare_data import get_labels, get_affinity_matrix, \ read_dist_matrix, write_clusterized_data, print_metrics, setup_costs from cluster.prepare...
import numpy as np import matplotlib.pyplot as plt import matplotlib.patheffects as pe import os from modelselection import kfold from fysstatistics import Regressor from typing import Callable, Optional, Tuple, Any from sampler import Sampler from sklearn.model_selection import train_test_split if "JPY_PARENT_PID" in ...
import numpy land_tiles = list(range(51, 65 + 1)) + [73, 81, 89, 97] + list(range(105, 127 + 1)) desert_tiles = [25, 26, 28, 29, 30, 31, 32, 89, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114] possible_desert_coasts = [] coastal_map = numpy.fromfile('./raw/DATA1.010', 'uint8') def fill_deserts(world_map): rows...
#!/usr/bin/python # -*- coding: utf-8 -*- """ This includes necessary functions for CLI and Main. """ __author__ = "<NAME>" __copyright__ = "Copyright (C) 2019 <NAME>" __license__ = "MIT" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" import argparse from ansible_parser import inventory_parser import logging from...
import numpy as np import matplotlib.pyplot as plt import matplotlib.collections as mcoll from matplotlib.patches import Ellipse from shapely import geometry import cv2 import rospy from sensor_msgs.msg import PointCloud2 import sensor_msgs.point_cloud2 as pc2 from geometry_msgs.msg import Point from std_msgs.msg imp...
from numba import njit, prange import numpy as np from scipy.spatial import cKDTree as KDTree from croppreclustering import graph from croppreclustering import kdtree2D from croppreclustering import kdtree3D @njit(parallel=True) def nRAIN(X, limit, leafsize=16, minimum_size=2): parents = np.empty((X.shape[0],), dt...
import tensorflow as tf import itertools class AFMModelParams(object): """ class for initializing weights """ def __init__(self, feature_size, embedding_size, field_size, attention_factor): self._feature_size = feature_size self._embedding_size = embedding_size self._field_size = fiel...
import os import sys import numpy as np import pandas as pd import matplotlib.pyplot as plt # pyburst from pyburst.kepler import kepler_tools from pyburst.grids import grid_strings, grid_tools from pyburst.burst_analyser import burst_tools # ========================================== # Requested data: # ====...
from modules.featrep import FeatureRep from commons import Feature from transformers.modeling_bert import BertModel, BertPreTrainedModel, BertConfig from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence import torch import torch.nn as nn """ Xây dựng class con lấy BertPreTrainedModel làm class cha...
from .config import g_config from .util import to_base import numpy from PIL import Image BILINEAR = Image.Resampling.BILINEAR def array_to_string(arr, base=g_config.visual_hash_base): bit_string = ''.join(str(b) for b in 1 * arr.flatten()) width = len(to_base(int('1' * len(bit_string), 2), base)) retur...
"""Connect to "KivyBLETest" server and test various BLE functions """ import time from able import GATT_SUCCESS, Advertisement, BluetoothDispatcher from kivy.app import App from kivy.clock import Clock from kivy.config import Config from kivy.properties import BooleanProperty, StringProperty from kivy.uix.boxlayout im...
# Copyright 2021 Huawei Technologies Co., Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
###################################################################################################################### # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # ...
''' Main app. Mainly used for marshalling resource provision. ''' import os import json import sys from kivymd.app import MDApp from kivy.metrics import dp from kivy.config import Config from loguru import logger from kivy.properties import ListProperty, NumericProperty, OptionProperty, StringProperty from kivy.cloc...
import pytest import numpy as np from s3netcdfapi import S3NetCDFAPI from s3netcdfapi.data.utils import cleanObject,swapAxe,swapAxes from s3netcdfapi.data.getData import getData,_getData,getDimData input={ "name":"s3netcdfapi_test", "cacheLocation":"../s3", "localOnly":True, "verbose":True, "maxPartitions":...
# -*- coding: utf-8 -*- """ Copyright ©2017. The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and not-for-profit purposes, without fee and without a signed licensing agreement, is he...
#!/usr/bin/env python3 from __future__ import print_function import argparse import json import os import re import sys from datetime import datetime from importlib import import_module from itertools import combinations from pprint import pprint from shutil import copyfile import numpy as np import pandas as pd imp...
from enum import Enum from os import listdir from os.path import isfile, join import logging import os import shutil import tarfile import zipfile logging.basicConfig(level=logging.DEBUG, format="%(asctime)s:%(levelname)s:%(name)s : %(message)s") logger = logging.getLogger("Util - Import") class ImportOptions(Enum)...
#!/usr/bin/env python # -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright (c) 2015-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 Software without restriction, including withou...
import re """ Modified version of https://pypi.org/project/conlleval/ """ def stats(): return {'cor': 0, 'hyp': 0, 'ref': 0} def evaluate(ref, hyp, otag='O'): # evaluation for NLTK aligned = align_hyp(ref, hyp) return conlleval(aligned, otag=otag) def align_hyp(ref, hyp): # ...
#!/usr/bin/env python3 #! coding: utf-8 ''' 関数集 ''' import re from typing import Generator, List def read_file(filepath: str) -> Generator[str, None, None]: """ Return a text content one line at a time. Parameters ---------- filepath : str File path you want to read. Yields --...
"""This module calibrates the parameters used in the parallel Wikipedia extraction pipeline. The objective is to minimize processing time by taking advantage of all available CPUs and keeping them 100% utilized on productive work. See mp_example.md for a motivating example of the architecture. Experimenting wi...
import os import pickle import cv2 import numpy as np import torch from torch.utils.data import DataLoader from collections import OrderedDict import matplotlib.pyplot as plt from tsnecuda import TSNE from scipy.ndimage import gaussian_filter1d from .abstract.abstract_hook import HookBase from lib.datatool...
# pulls out structures to get a better interpretation of what the top tica dimentions are import numpy as np import mdtraj as md import pyemma.coordinates as coor import pyemma.plots as pyemma_plots import pyemma from util.util import check_iter_of_sequences, KDTree import matplotlib.pyplot as plt def heatmap_label(ti...
"""Functional tests using the API with a fake DMAP Apple TV.""" import asyncio import ipaddress from aiohttp.test_utils import unittest_run_loop import pyatv from pyatv import exceptions, interface from pyatv.conf import (AirPlayService, DmapService, AppleTV) from pyatv.dmap import pairing from tests.dmap.fake_dmap_...
import datetime import re import unicodedata from typing import Pattern import pytz from dateutil.parser import parse # create list of currency symbols currencies = ''.join(chr(i) for i in range(0xffff) if unicodedata.category(chr(i)) == 'Sc') vol_units = {"l": 1, "dl": 0.1, "cl": 0.01, "ml": 0.001} weight_units = {...
import discord import datetime import os import string import hidden colour_msg_delete = 15158332 colour_voice = 481716 colour_join = 4304663 colour_leave = 13114910 colour_musical = 6139885 colour_royal_purple = 7885225 colour_birthday = 16428082 colour_admin = 27476 image_uncategorized_ledger = "https://emojipedi...
####################################################################################### # # ObjectID network (based on FaceId) # https://github.com/normandipalo/faceID_beta/blob/master/faceid_beta.py # ####################################################################################### from tensorflow.python.kera...
# !/usr/bin/env python3 # -*- coding:utf-8 -*- # @Time : 2022/04/10 11:57 # @Author : clear # @FileName: rgcn_conv.py.py import tensorlayerx as tlx from gammagl.layers.conv import MessagePassing def masked_edge_index(edge_index, edge_mask): if tlx.BACKEND == 'mindspore': idx = tlx.convert_to_tensor(...
class DLinkedList: # Constructor - return nothing - O(n) of initial arguments def __init__(self, *args): if args != (): self.size = len(args) self.head = Node(args[0]) if len(args) == 2: self.tail = Node(args[-1]) self.head.next = self....
import os import shutil import sys import re import subprocess import time import click import getpass import pypandoc from .topic import Topic from .tplates import Tplates class Md2Tex(object): """A class to hold all static methods to convert a markdown to a latex file content""" _tex_text = '' _config ...
""" find peaks or troughs in sorted bed files for a bedgraph file with pvalues in the 4th column. usage would be: $ python peaks.py --dist 100 --seed 0.01 some.bed > some.regions.bed where some.regions.bed contains the start and end of the region and (currently) the lowest p-value in that region. """ from __futu...
# Copyright 2021 Sony Group Corporation. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
#!/usr/bin/env python ''' Test dicom utils The MIT License (MIT) Copyright (c) 2016-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...
import os import re import torch from torch.autograd import Variable # Starting from sequential data, batchify arranges the dataset into columns. # For instance, with the alphabet as the sequence and batch size 4, we'd get # ┌ a g m s ┐ # │ b h n t │ # │ c i o u │ # │ d j p v │ # │ e k q w │ # └ f l r x ┘. # These col...
import re from .errors import RTextError, RomanValidationError CASE_UPPER = 1 CASE_LOWER = -1 CASE_IGNORE = 0 def rn_validator(rn: str, case: int = CASE_UPPER): """ Check the roman number for validity. :param rn: roman number :param case: upper (1), lower (-1) or ignore (0) case. Default upper (1). ...
#!/usr/bin/env python3 # vim: tw=76 import kxg import random import pyglet LOWER_BOUND, UPPER_BOUND = 0, 5000 class World(kxg.World): """ Keep track of the secret number, the range of numbers that haven't been eliminated yet, and the winner (if there is one). """ def __init__(self): sup...
import nltk import nltk.data # PATH_STOPWORDS = 'textteaser/stopWords.txt' # PATH_PICKLE_EN = 'textteaser/english.pickle' PATH_STOPWORDS = 'doc_summarizer/textteaser/stopWords.txt' PATH_PICKLE_EN = 'doc_summarizer/textteaser/english.pickle' class Parser(object): def __init__(self): self.ideal = 20.0 ...
"""Utility functions.""" from __future__ import print_function import colorsys import requests from os.path import join import numpy as np from keras.models import Model def preprocess_image(img, mean=np.array([[[123.68, 116.779, 103.939]]])): # mean in rgb order """Preprocess an image as input.""" float_im...