text
stringlengths
3.07k
22.1k
# -*- coding: utf-8 -*- """ Created on Fri Dec 30 11:48:43 2016 @author: <NAME> Feed-forward ResNet-101 convolutional model: https://arxiv.org/pdf/1512.03385v1.pdf """ import sys sys.path.append('../') from Lib.TensorBase.tensorbase.base import Model from Lib.TensorBase.tensorbase.base import Layers from Lib.Tenso...
from abc import ABC, abstractmethod from typing import List, Dict, Set, Pattern, Match from copy import deepcopy from collections import namedtuple from itertools import chain import regex from recognizers_text.utilities import RegExpUtility from recognizers_text.extractor import Extractor, ExtractResult from recogniz...
import requests from bs4 import BeautifulSoup import os #from pyaria2 import Aria2RPC import time import sys def get_file_from_url(links): """使用aria2下载文件,经常下载不成功""" file_num = 0 for link in links: file_num += 1 if link[:5]=="Error" or link[:5]=="Warn ":#如果网址为错误提示 print("Error: ...
from lxml import etree import csv import gzip import json from io import StringIO def _strip_ns_prefix(tree): """strip the namespace prefixes from all elements in a tree""" #thank you to https://stackoverflow.com/questions/30232031/how-can-i-strip-namespaces-out-of-an-lxml-tree query = "descendant-or-self:...
""" /******************************************************************************* * Copyright (C) 2021 Maxim Integrated Products, Inc., All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to d...
# # Copyright (c) 2013, Prometheus Research, LLC # Released under MIT license, see `LICENSE` for details. # import itertools import types class registry: # Stores registered test types and respective record types. case_types = [] input_types = [] output_types = [] class FieldSpec(object): # R...
# Copyright 2009 by <NAME>. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Unit tests for Bio.SeqIO.convert(...) function.""" import unittest import warnings from Bio impor...
""" (C) 2009-2016 <NAME> """ import os import sys from copy import copy sys.path.append(os.environ["QUEX_PATH"]) from quex.engine.misc.utf8 import utf8_to_unicode, \ unicode_to_utf8, \ ...
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from django.db import models from django.conf import settings from django.db import transaction from django.utils.encoding import smart_text import datetime AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', ...
""" Main program to run the detection """ import socket import time from argparse import ArgumentParser from typing import Optional import cv2 import numpy as np from vtuber.facial_features import FacialFeatures, Eyes from vtuber.facial_landmark import FaceMeshDetector from vtuber.pose_estimator import PoseEstimator...
from concurrent import futures from dataclasses import dataclass import grpc import logging import json from queue import Queue import socket from threading import Thread, Lock import time from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple from ray.job_config import JobConfig import ray.core.gener...
# ********************************************************************** # Copyright (C) 2020 Johns Hopkins University Applied Physics Laboratory # # All Rights Reserved. # For any other permission, please contact the Legal Office at JHU/APL. # # Licensed under the Apache License, Version 2.0 (the "License"); # y...
import numpy as np import cv2 import copy import hm_class_counting from imutils.video import VideoStream from imutils.video import FPS import time import dlib class Mkmap(): vidpath=str() outvidpath=str() modelpath=str('MobileNetSSD_deploy.caffemodel') prototxtpath=str('MobileNetSSD_deploy.prototxt.tx...
import torchgen.api.cpp as cpp from torchgen.context import native_function_manager from torchgen.model import ( Argument, BaseTy, FunctionSchema, OptionalType, SelfArgument, BaseType, NativeFunctionsGroup, TensorOptionsArguments, Type, ) from torchgen.static_runtime import config i...
from __future__ import print_function, absolute_import, division from six import itervalues from lxml import etree as ET from sphinx.ext.autodoc import Documenter, members_option, ALL from sphinx.errors import ExtensionError from . import get_doxygen_root from .xmlutils import format_xml_paragraph class DoxygenDocu...
""" Used to transform data based on contents of the transformation configuration file. """ import json import logging import os.path import constants # pylint: disable=logging-format-interpolation, logging-not-lazy LOGGER = logging.getLogger(__name__) def validateType(dataType): """ Transformation types are d...
# -*- coding: utf-8 -*- """ Created on Thu Sep 26 19:50:14 2019 @author: mayan """ import requests import json import numpy as np import base64 import sys from flask import Flask, render_template, redirect, url_for,request from flask import make_response import png app = Flask(__name__) # command to...
import json import open3d import numpy as np import numpy.linalg as la from typing import Dict, Any, Type, List, Sequence, Optional, Union import cv2 """ Audi A2D2 Utils Primarily taken from the tutorial on their website for converting labels and points together """ EPSILON = 1.0e-10 # norm should not be small ...
import torch from transboost.weak_learner import * from transboost.label_encoder import LabelEncoder, OneHotEncoder, AllPairsEncoder from transboost.callbacks import CallbacksManagerIterator, Step, ModelCheckpoint, CSVLogger,\ Progression, BestRoundTrackerCallback,BreakOnMaxStepCallback, \ BreakOnPerfectTrainA...
import os import pathlib import sys from enum import unique from typing import TYPE_CHECKING, List, Optional from dictor import dictor from loguru import logger from pydantic import BaseModel, DirectoryPath, Field, FilePath, constr from sel4.conf import settings from ...core import constants from ...utils.enumutils ...
#!/usr/bin/env python import rospy import handleInvalidState as his from sailbot_msg.msg import AISMsg, GPS, path, latlon, globalWind from geopy.distance import distance import time import sys import utilities as utils # Parameters MAX_NUM_AIS_SHIPS = 50 # Limit number of AIS ships used in full pipeline, makes large ...
assert False import os import numpy as np import json from PIL import Image, ImageDraw from matplotlib import pyplot as plt assert False # Red light filter parameter tuning: # filter shape params: red_diameter, black_edge, blue_padding filter_paras = [(7,2,0),(7,2,3),(23,3,0),(23,3,5)] strides = [5,5,10,10] th...
import json import logging.handlers import os import requests import subprocess import threading import time import socket import websocket from . import config from . import __version__ AUTH = None # COMMON ################################################################################ class ReconnectingWebSoc...
import tensorflow as tf import tensorflow_probability as tfp import numpy as np tf_type = tf.float32 def quadrl(degree): if degree == 3: nd = tf.constant([1.73205080756888, 0, -1.73205080756888], dtype=tf_type) w = tf.constant([0.16666666666667, 0.66666666666667, 0.16666666666667], dty...
"""Miscellaneous utility functions.""" import os import random from functools import reduce from PIL import Image import numpy as np from matplotlib.colors import rgb_to_hsv, hsv_to_rgb # 创建初始项目相关文件夹 def mkdir_for_newProject(prefix, project_name): os.mkdir(os.path.join(prefix, project_name)) os.mkdir(os.pat...
import re import random from functools import total_ordering from errors import * class Dice: SYNTAX = re.compile(r'[+-]?(\d+)d(\d+)') MAX_DICE = 100 MAX_SIDES = 1000 def __init__(self, quantity, die, negative=False): if quantity < 1 or quantity > self.MAX_DICE: raise OutOfRange...
import os from time import time import numpy as np from numpy.random import choice import pandas as pd import igraph as ig import networkx as nx from node2vec import Node2Vec import xgboost as xgb from sklearn.metrics import roc_auc_score, accuracy_score from common import * datadir_graphs = 'data/graphs_reduced' ...
import os import json import numpy as np import scipy from scipy import io class MPIIMeta: def __init__(self,image_path,annos_list): #print(f"test get meta with img_path:{image_path} annos_list:{annos_list}\n\n") image_name=os.path.basename(image_path) self.image_id=int(image_name[:image_na...
# Author: SiliconSloth 18/1/2018 from threading import Thread, Timer import numpy as np import cPickle, serial, os, time, subprocess import cv2 # PyCharm seems to need this to work properly. # try: # from cv2 import cv2 # except: # pass # This script is responsible for actually driving the robot...
import os import re import shutil import numpy as np from collections import defaultdict def test1(): name_test_path = '/home/gysj/pytorch-workspace/pytorch-study/data/VeRi/name_test.txt' name_train_path = '/home/gysj/pytorch-workspace/pytorch-study/data/VeRi/name_train.txt' name_query_path = '/home/gysj/...
import json import base64 import logging from flask import Blueprint, render_template, request, redirect, url_for, abort, current_app, session from acoustid.web import db from acoustid.web.utils import require_user from acoustid.models import TrackMBIDChange, TrackMeta from acoustid.data.track import resolve_track_gid ...
import collections import torch from torch import fx from e3nn import o3 from e3nn.math import group, orthonormalize from e3nn.util import explicit_default_types from e3nn.util.jit import compile_mode _TP = collections.namedtuple('tp', 'op, args') _INPUT = collections.namedtuple('input', 'tensor, start, stop') def ...
#!/usr/bin/env python # Copyright (c) 2017 Polytechnique Montreal <www.neuro.polymtl.ca> # # About the license: see the file LICENSE.TXT """ Qt dialog for manual labeling of an image """ from __future__ import absolute_import, division, print_function import logging import numpy as np from PyQt5 import QtCore, QtW...
#!/usr/libexec/platform-python -tt import os import time from datetime import datetime import sys import subprocess import re import atexit sys.path.append("/usr/share/fence") from fencing import * from fencing import is_executable, fail_usage, run_delay import logging #BEGIN_VERSION_GENERATION RELEASE_VERSION="172.1...
#!/usr/bin/env python3 import gym import numpy as np from itertools import product import matplotlib.pyplot as plt def print_policy(Q, env): """ This is a helper function to print a nice policy from the Q function""" moves = [u'←', u'↓', u'→', u'↑'] if not hasattr(env, 'desc'): env = env.env ...
# Licensed to Cloudera, Inc. under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. Cloudera, Inc. licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file ex...
# -*- coding: utf-8 -*- import flask import mwapi import mwoauth import os import random import requests_oauthlib import string import toolforge import yaml import json import mwparserfromhell app = flask.Flask(__name__) user_agent = toolforge.set_user_agent('musikverket-description-translations', email='<EMAIL>') t...
#!/bin/env python3 import sys, os from . import devices debug = "DEBUG" in os.environ if len(sys.argv) < 2: print(sys.argv[0], "<rom>") exit() with open(sys.argv[1], "rb") as file: ram = bytearray(file.read()) ram += bytearray((256 ** 3) - len(ram)) pc = 0x0000 ps = 0x0000 rs = 0xff00 ws = 2 def read...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # dist...
# coding=utf-8 """ GraN-DAG Copyright © 2019 <NAME>, <NAME>, <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, modi...
import collections import torch import torch.nn as nn import geotorch.parametrize as P class AbstractManifold(P.Parametrization): def __init__(self, dimensions, size): r""" Base class for all the manifolds. This class implements some basic printing and creates some helper attributes to ha...
# (C) Copyright 2020 ECMWF. # # This software is licensed under the terms of the Apache Licence Version 2.0 # which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. # In applying this licence, ECMWF does not waive the privileges and immunities # granted to it by virtue of its status as an intergovernmenta...
import json import logging from sqlalchemy.orm import Session import datetime from full_incidents.thehive_to_dwh.postgresql.models import InteractionDescription, InteractionCategory, Asset, \ Organizations, Privilege, Entity, Rule, UseCase, Raws, DataPayLoad, InteractionStatus, Ticket, SeverityLevel, \ Event...
import logging import time from collections import defaultdict, OrderedDict, deque from p4pktgen.config import Config from p4pktgen.core.strategy import PathCoverageGraphVisitor, EdgeCoverageGraphVisitor from p4pktgen.core.solver import PathSolver from p4pktgen.core.test_cases import TestCaseBuilder, record_test_case...
import torch import torch.nn as nn from scipy.spatial.distance import cdist import numpy as np def train_target(args): dset_loaders = digit_load(args) ## set base network if args.dset == 'u2m': netF = network.LeNetBase().cuda() elif args.dset == 'm2u': netF = network.LeNetBase().cuda() ...
"""Convert Relational Algebra to Python AST. """ import astor import ast import inspect import logging import uuid from functools import singledispatch from ast import ( And, Compare, FunctionDef, Load, Name, Or, ) from . import relational_algebra as ras from . import ast_transformer logge...
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2016-2021 <NAME> (The Compiler) <<EMAIL>> # # This file is part of qutebrowser. # # qutebrowser 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, e...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT license. import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import torchvision import torchvision.models as models import torchvision.transforms as trans...
""" Generate the operator data in csv file. CSV file Encoding : UTF-8 CSV Table Fields Operator_Name Text string Date 8 digits YYYYMMDD IMEI 14-16 digits IMSI 14-15 digits MSISDN Up to 20 digits IMSI Pakistan MCC MNC Network Operator or brand name Status 410 1 Mobilink-PMCL Mobilink Operational 410 3 ...
#!/usr/bin/env python3 """ Generate a Dutch week calendar for an entire year. The generated calendar is in odt format. This script accepts a YAML data file which must contain the fields ``special dates``, ``birthdays`` and ``weddings``. Example data file .. code-block:: yaml year: 2016 special dates: ...
"""Wire data in JSON format. This is good for fast prototyping but should not be used in production as, for now, it lacks crucial features needed in protocol evolution. For ease of use, this module does not require you to provide wire data metadata, such as (stable) "wire names" of Python types or enum members. Inste...
import corenlp import os import pdb import ast import argparse import requests import random from nltk.corpus import stopwords import json class Data_Processor: def __init__(self, corenlp_path): self.keyPhrases={} self.rels = ['IsA', 'UsedFor', 'PartOf', 'HasA', 'CreatedBy', 'MadeOf'] os...
import sys sys.path.append('~/anaconda3/lib/python3.7/site-packages/panda/') from panda import Panda import binascii import bitstring import time import datetime #import serial import csv import cantools import pandas as pd import numpy as np import simpleaudio as sa import matplotlib.pyplot as plt import liveTools as ...
import os import yaml import argparse import pyshark import pywav import pydub from pydub import AudioSegment from pathlib import Path import multiprocessing from threading import Thread from queue import Queue from time import sleep import time import logging as logger from datetime import date today = date.today(...
import os from multiprocessing import cpu_count import cv2 import numpy as np import tensorflow as tf from tensorflow.python.data.experimental import AUTOTUNE from tensorflow.python.ops.image_ops_impl import convert_image_dtype, ResizeMethod from consts import INPUT_IMG_SHAPE, OUTPUT_IMG_SHAPE, BATCH_SIZE, CROP_SIZE,...
# -*- coding: utf-8 -*- """ @author:XuMing(<EMAIL>) @description: refer https://github.com/yangjianxin1/GPT2-chitchat """ import argparse import os import sys import torch import torch.nn.functional as F from transformers import BertTokenizerFast from transformers import GPT2LMHeadModel sys.path.append('../..') from...
# -------------------------------------------------------- # Deep Iterative Matching Network # Licensed under The Apache-2.0 License [see LICENSE for details] # Written by <NAME>, <NAME> # -------------------------------------------------------- from __future__ import print_function, division import numpy as np import...
import random import uuid import chess from django.contrib.auth import get_user_model from django.utils import timezone from .constants import K_FACTOR from .models import Board, Game, Move, Result RESULTS_DICT = { "1-0": Result.WHITE_WINS, "1/2-1/2": Result.DRAW, "0-1": Result.BLACK_WINS, } User = get_...
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # ...
# TODO: why isn't this implemented as a class singleton, the same as God ? import logging from django.utils.translation import ugettext_noop from django.db import models from django.contrib.auth.models import User from wouso.core import signals from wouso.core.user.models import Player from wouso.core.scoring.models im...
"""AIGER circuit class based on https://github.com/mvcisback/py-aiger/blob/main/aiger/parser.py""" import re class Header: def __init__(self, max_var_id: int, num_inputs: int, num_latches: int, num_outputs: int, num_ands: int): self.max_var_id = max_var_id self.num_inputs = num_...
import logging from typing import Any, Dict, Optional, Type import pydantic from datahub.configuration.common import ( ConfigModel, ConfigurationError, DynamicTypedConfig, ) from datahub.configuration.source_common import DatasetSourceConfigBase from datahub.ingestion.api.common import PipelineContext fro...
"""Provide strategies for given endpoint(s) definition.""" import asyncio import re from base64 import b64encode from functools import partial from typing import Any, Callable, Dict, Generator, Optional, Union from urllib.parse import quote_plus import hypothesis import hypothesis.strategies as st from hypothesis_json...
import string import random import datetime from dateutil.relativedelta import relativedelta from sqlalchemy import or_ from tornado.web import RequestHandler from libs.base_handler import BaseHandler from libs.pagination import pagination_util from websdk.db_context import DBContext from models.user import User, mode...
import numpy as np from astropy.wcs import WCS from astropy.table import Table from astropy import units as u from astropy.coordinates import SkyCoord from astropy.io import fits import sys import urllib from .mast import * from .utils import * __all__ = ['Source', 'multi_sectors'] def multi_sectors(sectors, tic=No...
__author__ = '<NAME>' __all__ = ['EulerianGrid'] import os import numpy as np class EulerianGrid(object): def __repr__(self): return f'{self.__class__.__name__}()' def __init__(self): """ Класс реализует общие методы, для расчетов в газодинамической постановке "...
# The specific stylometric calculations in this file are modified versions of code from here. # We changed them to compose with our existing pipeline infrastructure. # https://github.com/Hassaan-Elahi/Writing-Styles-Classification-Using-Stylometric-Analysis #===========================================================...
''' SUG Engine v1.2.0 SUGE.py -n number -px position-x -py position-y -vx velocity-x -vy velocity-y -g gravity[1] [-r radii<0.3>] -c gravity[1] [-sac simulate-accuracy<0.001>] [-dfq display-frequncy<1000>] [-bg background_color<black>] SUGE.py [-f...
# -*- coding: utf-8 -*- """ werkzeug.http ~~~~~~~~~~~~~ Various WSGI related helper functions and classes. :copyright: 2007 by <NAME>. :license: BSD, see LICENSE for more details. """ try: set = set except NameError: from sets import Set as set import re _accept_re = re.compile(r'([^\s;...
"""Persistent token cache management for the Flickr API""" import os.path import logging import time from flickrapi.exceptions import LockingError, CacheDatabaseError from flickrapi.auth import FlickrAccessToken LOG = logging.getLogger(__name__) __all__ = ('SimpleTokenCache', 'OAuthTokenCache') class SimpleTokenC...
import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output from helper import * import cloudpickle from params import MATCH, LIV_GOALS, SCORER from tqdm.auto import tqdm external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash...
"""*********************************************************** *** Copyright Tektronix, Inc. *** *** See www.tek.com/sample-license for licensing terms. *** ***********************************************************""" import socket import struct import math import time import sys echo_cmd =...
# Copyright (c) 2019 <NAME> # # This file is part of FFmpeg. # # FFmpeg is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # FF...
from . import Stmt from . import Expr from .Token import * from .PyLoxExceptions import PyLoxStaticError __all__ = ["Resolver"] """ The resolver analyzes the syntax tree, to determine if the program violates certain consistency requirements, such as binding references to 'super', 'this' and variables to...
""" This app creates time series movies """ import click import fiona import xarray as xr import numpy as np import rasterio import subprocess from glob import glob from dateutil.parser import parse from datetime import datetime, timedelta, time, date from datacube.storage.masking import make_mask from datacube.u...
import pymysql import csv import setup notes = ''' This script will tell you how to format your queries accordingly. You have to follow this pattern. Add necessary triggers to CreateDatabase.sql file and make a pull request. I will further update this file with more required queries and you can fill them. ''' reg_id_...
from db import db from utils import extract_remainder_after_fragments, extract_time, epoch_time_to_digital from game import lookup_game_by_name_or_alias, get_known_games, lookup_known_game_by_name_or_alias, \ write_games_dict, read_games_dict, create_mention from response import TextResponse from dotenv import load...
import datetime import json import logging import os import sys import re logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) SPEC_PAGE_HEADER = r"""import chai from 'chai' import {startQuestionnaire} from '../helpers' """ SPEC_PAGE_IMPORT = r"""import {pageName} from '../pages/{pageDir}{p...
""" .. currentmodule:: arraycontext .. autoclass:: PytestPyOpenCLArrayContextFactory .. autofunction:: pytest_generate_tests_for_array_contexts .. autofunction:: pytest_generate_tests_for_pyopencl_array_context """ __copyright__ = """ Copyright (C) 2020-1 University of Illinois Board of Trustees """ __license__ = "...
""" Copyright 2008-2017 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion 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 l...
import time import threading from traceback import print_tb import serial class protocol: """used for discriminating between line messages other than the `DELIMITER`, usages are completely up to the implementor.""" DEBUG = '.' INFO = '>' CONFIG = '@' RESULT = '+' ...
import os, sys currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os.path.dirname(currentdir) parentdir = os.path.dirname(parentdir) print(parentdir) sys.path.append(parentdir) from performance_eval import * import csv from collections import defaultdict # get diagnoses from radiologists' rating form...
#!/usr/bin/python # -*- coding: UTF-8 -*- import os import shutil from xml.dom.minidom import Document import numpy as np import cv2 rootdir = "../../../dataset/facedata/wider_face" if not os.path.exists(rootdir): os.makedirs(rootdir) retinaface_gt_file_path = "../../../dataset/facedata/retinaface_labels/" convet2...
""" Tests for :func:`acoustics.signal` """ from acoustics.signal import convolve as convolveLTV from scipy.signal import convolve as convolveLTI import numpy as np import itertools from acoustics.signal import * #decibel_to_neper, neper_to_decibel, ir2fr, zero_crossings from numpy.testing import assert_almost_equal, a...
from django.db import models import math import decimal class DenormalizeManagerMixin(object): def update_cohort(self, cohort, date_provided=False, **kwargs): """ Save each of the fields for ``PositionStats`` and ``OrganizationStats`` models, which provide filtered ``Employee`` objects as t...
import dis import os import sys from collections import deque from compiler import pyassem from compiler.pyassem import Instruction from compiler.pycodegen import CodeGenerator from functools import partial from io import SEEK_END from re import escape from .common import CompilerTest, glob_test def format_oparg(ins...
import importlib import tkinter as tk import traceback from functools import lru_cache from pathlib import Path from queue import Queue from threading import Thread from time import time, sleep from tkinter import filedialog from tkinter import ttk import PIL.Image import PIL.ImageTk import torch import tvl data_dir...
# NOTE: This script assumes that type data has been generated using generate_typedata.py script # If that's not the case, don't worry yourself with modifying this script; writing your own will be easier. #---------------------------------------------------------------------------------- import os, sys, pickle, ntpath, ...
import copy import time from typing import Union import cv2 import numpy as np from .board import Board from .pieces import Piece, Tetrominoes def nes_prng(value: int): bit1 = (value >> 1) & 1 bit9 = (value >> 9) & 1 lmb = bit1 ^ bit9 return (lmb << 15) | (value >> 1) class GameState: def __in...
""" The following code has been translated from R package pagoda2, if you use any of these functions please cite: <NAME>, <NAME>, <NAME> and <NAME> (2021). pagoda2: Single Cell Analysis and Differential Expression. R package version 1.0.2. """ from anndata import AnnData import pandas as pd import numpy as np import ...
from pathlib import Path import re import logging import requests from bs4 import BeautifulSoup import shutil def download_file(url): """ Download file from URL """ local_filename = url.split("/")[-1] with requests.get(url, stream=True) as r: with open(f"audios/{local_filename}", "wb") as f: ...
#!/usr/bin/env python import numpy as np import pandas as pd import re from os import listdir from os.path import isfile, isdir def getAllData_IBL(sourceDir, mouseIdx, **kwargs): ''' 03/20/2018 NAR Get data from all sessions and all trials for specified mouse Args: sourceDir : path to ...
import numpy as np import tensorflow as tf from hrl.elegant.utils import categorial_entropy, categorial_log_prob, categorial_sample class ReplayBuffer: def __init__(self, max_len, state_dim, action_dim, on_policy): self.max_len = max_len self.now_len = 0 self.next_idx = 0 self.ful...
import tensorflow as tf initializer = lambda: tf.contrib.layers.variance_scaling_initializer(factor=1.0, mode='FAN_AVG', uniform=True, d...
import json import os import pandas def filter_word(input_word): tmp_output = '' for c in input_word: if c in 'zxcvbnmasdfghjklqwertyuiopZXCVBNMASDFGHJKLQWERTYUIOP': tmp_output += c return tmp_output def counting_pairs_from_yelp_parsed_data(parsed_data, verb_nsubj_amod_dict, verb_dobj...
#!/usr/local/bin/python ''' Convert a sam file to a tab-limited file that contains position-specific representation of the CIGAR flag BEGIN COPYRIGHT NOTICE sam2Flat code -- (c) 2017 <NAME> -- ICR -- www.icr.ac.uk Copyright 2017 <NAME> Licensed under the Educational Community License, Version 2.0 ...
""" This file integrates open-source code (https://github.com/ramvasudevan/soft-robot-koopman) with Sofa. Open-source code accompanies following papers:https://arxiv.org/abs/1902.02827 (Modeling and Control of Soft Robots Using the Koopman...
"""Property Scout Dash - Created by <NAME>.""" import concurrent.futures import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output import pandas as pd import numpy as np from jitcache import Cache cache = Cache() app = dash.Dash(__name__) LA_DATA...
import copy import datetime import json import time import warnings from pathlib import Path from typing import Optional, Union import attr import h5py import numpy as np import acconeer.exptool import acconeer.exptool.structs.configbase as cb from acconeer.exptool import configs, modes @attr.s class Record: # ...
# FIXME: this covers a lot of constants, so we should consider getting rid of # all these extraneous objects and just have dictionaries which can be imported from .sss_logging import logging ssslog = logging.getLogger(__name__) # FIXME: this is a poorly constructed object class Namespaces(object): """ This cl...