text stringlengths 3.07k 12.6k |
|---|
import torch
def _is_tensor_video_clip(clip):
if not torch.is_tensor(clip):
raise TypeError("clip should be Tesnor. Got %s" % type(clip))
if not clip.ndimension() == 4:
raise ValueError("clip should be 4D. Got %dD" % clip.dim())
return True
def crop(clip, i, j, h, w):
"""
... |
import pandas as pd
import itertools as it
import numpy as np
import os
import sys
import pickle
from feature_creation_scripts.tail_num_tracking import get_n_prior_flights
from feature_creation_scripts.flight_load import LoadDFClass
from feature_creation_scripts.holidays import get_holiday_features_dict
from feature_c... |
#!/usr/local/bin/env python
# =============================================================================================
# MODULE DOCSTRING
# =============================================================================================
"""
Run YANK self tests after installation.
"""
# ===========================... |
import uuid
from typing import Any, Callable, Dict, Iterable, Optional, TypeVar, Union
from globus_sdk import client, response, scopes, utils
from globus_sdk.authorizers import GlobusAuthorizer
from globus_sdk.types import UUIDLike
from .data import CollectionDocument
from .errors import GCSAPIError
from .response im... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 31 10:34:08 2017
@author: paddy
"""
import numpy as np
class Stone:
Empty = 0
Black = -1
White = 1
colour_names = { Stone.Empty:"Empty", Stone.Black:"Black", Stone.White:"White", }
def flipped_stone(stone):
if stone == Stone.Empty:... |
import os
import numpy as np
import scipy.sparse as sp
import pickle
import torch
from torch.utils.data import DataLoader
from dgl.data.utils import download, _get_dgl_url, get_download_dir, extract_archive
import random
import time
import dgl
from utils import shuffle_walks
#np.random.seed(3141592653)
def ReadTxtNet(... |
# DO NOT EDIT THIS FILE!
#
# This code is generated off of PyCDP modules. If you need to make
# changes, edit the generator and regenerate all of the modules.
from __future__ import annotations
import typing
from ..context import get_connection_context, get_session_context
import cdp.browser
from cdp.browser import ... |
# 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 ... |
# Copyright 2010-2018 Google LLC
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from ctypes import *
class TSCLib:
""" TSC Printer object """
handle = None
def __init__(self, width=60, height=40, paper='label'):
""" 纸张类型 paper = label or thermal """
if self.handle is None:
self.handle = WinDLL(... |
import sys
import functools
from .. import aspp
class Indices(object):
def __init__(self, indexNames = '', shape = ()):
self._indices = tuple(indexNames)
self._size = dict()
assert len(self._indices) == len(set(self._indices)), 'Repeated indices are not allowed ({}).'.format(indexNames)
assert l... |
__all__ = ['halfband1d','residual1d','upsample1d','downsample1d']
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import lfilter, filtfilt
from scipy.signal.windows import blackman, hann
import tensorflow as tf
import tensorflow.keras as tfk
# Windowed sinc kernel
kernel_size = 15
t = np.arange(... |
# Copyright (c) 2014 EMC Corporation.
# 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... |
"""
Create the relational ERM sampler for the network data
"""
import argparse
import numpy as np
import tensorflow as tf
try:
import mkl_random as random
except ImportError:
import numpy.random as random
from relational_erm.sampling import adapters, factories
from relational_erm.data_cleaning.pokec import ... |
"""
kwik structure based on:
https://github.com/kwikteam/phy-doc/blob/master/docs/kwik-format.md
cluster_group defaults based on:
https://github.com/kwikteam/phy-doc/blob/master/docs/kwik-model.md
04/08/20
"""
from spikeextractors import SortingExtractor
from spikeextractors.extractors.bindatrecordingextractor impo... |
from __future__ import print_function
from contextlib import contextmanager
from flask import Flask, request
from multiprocessing import Process, Queue
import os
import time
import subprocess
import json
from boxsdk import OAuth2
from boxsdk import Client
import logging
from StringIO import StringIO
# Remove logging f... |
from pkg_resources import resource_filename
import pandas as pd
import numpy as np
import re
import pyfasta
from keras.models import load_model
class annotator():
def __init__(self, ref_fasta, annotations):
if annotations is None:
annotations = resource_filename(__name__, 'annotations/GENCOD... |
#Based on paper Protein Interaction Network Reconstruction Through Ensemble Deep Learning With Attention Mechanism by <NAME>, Ling, and Liu
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
class ModelLiDeep(nn.Module):
def __in... |
import math
#Test Values
X_VAL = 10.109
Y_VAL = -17.242
Z_VAL = -220.737
X_THETA = 0.0
Y_THETA = 0.0
Z_THETA = 0.0
#Physical dimensions (in mm)
e = 72.0 #End triangle
f = 173.205 #Base triangle
re = 300.0 #Forearm length
rf = 210.0 #Bicept length
dps = 0.225 ... |
import psycopg2
import testing.postgresql
import pytest
import pandas as pd
from datetime import timedelta
import src.ooni.utils as ooni_utils
import src.ooni.types as ooni_types
import src.shared.types as shared_types
import src.shared.utils as shared_utils
# TODO make DRY with other test - test utils?
@pytest.fix... |
import tensorflow as tf
from tensorflow.contrib import slim
import matplotlib.image as mpimg
import cv2
import os
import random
import numpy as np
import base64
from PIL import Image
import io
import boto3
import time
import tempfile
# queue_name = os.environ['QUEUE_NAME']
# bucket_name = os.environ['BUCKET_NAME']
s3... |
import json
import os
import pytest
import re
from io import BytesIO
from tempfile import TemporaryDirectory
from unittest.mock import patch
from urllib.request import urlopen, Request
from repo2docker.contentproviders import Dataverse
test_dv = Dataverse()
harvard_dv = next((_ for _ in test_dv.hosts if _["name"] =... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
"""
importguests command
Parse a guest list csv file to store them in the guest list
Created by lmarvaud on 03/11/2019
"""
import csv
import itertools
import logging
import operator
from argparse import RawDescriptionHelpFormatter
from django.conf import settings
from django.core.management import BaseCommand, Comma... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 <NAME> <<EMAIL>>
# Licensed under the MIT License - https://opensource.org/licenses/MIT
import argparse
import logging
import os
import re
from builtins import map
from builtins import str
from future.utils import iteritems
from scaf.data import Ba... |
# 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
# d... |
import sys
import getopt
from tinydb import TinyDB, Query
import time
import random
import string
#import the librarys used in this program
Colours = ["red", "orange", "yellow", "green",
"blue", "purple", "pink", "brown"] #setup the colours
Objects = [] #set up a list for the GameObjects
DB = TinyDB('Datab... |
"""get data from npse"""
import re
import time
from collections import defaultdict
from functools import lru_cache
import pandas as pd
from util_nepse import get_text, get_soup, chunks, get_date_range, write_csv, clean_names
#-------------------------------------------------------------------
def company_listed(url... |
# -*- coding: utf-8 -*-
def recover_label(tags, seq_lens, id2tag):
"""
ID->tag
:param tags:
:param seq_lens:
:param id2tag:
:return:
"""
labels = []
for tag, seq_len in zip(tags, seq_lens):
pre = [id2tag.get(_id, 'O') for _id in tag[:seq_len]]
labels.append(pre)
return labels
def get_ner_fmeasure(gold... |
import numpy as np
import math
import itertools
from collections import namedtuple
from .coco_format import CocoPairs, CocoPairsNetwork
from .human import Human
from scipy.ndimage import maximum_filter, gaussian_filter
heatmap_supress = False
heatmap_gaussian = True
adaptive_threshold = False
NMS_Threshold = 0.15
Lo... |
import pickle as pkl
import scipy.sparse
import numpy as np
import pandas as pd
from scipy import sparse as sp
import networkx as nx
from collections import defaultdict
from scipy.stats import uniform
import tensorflow as tf
from sklearn import preprocessing
def masked_softmax_cross_entropy(preds, labels, mask):
... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# This sub-module is destined for common non-package specific utility
# functions.
import warnings
import numpy as np
from numba import njit
from .. import units as u
from .data import RemoteData # noqa: F401
def has_polarization(m):
"""Checks i... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
class Discriminator(nn.Module):
# Network Architecture is exactly same as in infoGAN (https://arxiv.org/abs/1606.03657)
# Architecture : (64)4c2s-(128)4c2s_BL-FC1024_BL-FC1_S
def __init__(self, dataset='mnist', conditional=Fa... |
# coding: utf-8
__author__ = 'IDM.IPPM (<NAME>)'
import subprocess
import re
import os
import sys
def get_project_directory():
project_directory = os.path.dirname(os.path.dirname(__file__))
return project_directory
# Call external program (very fast) to calculate vulnerability map for circuit
# If iter1 == -... |
# Copyright (c) 2006-2013 Regents of the University of Minnesota.
# For licensing terms, see the file LICENSE.
import conf
import g
from util_.streetaddress import ccp_stop_words
log = g.log.getLogger('srch_fll_txt')
# ***
# FIXME: Implement this?
# See Postgis Geometry Relationship Functions:
# http://postgis.... |
import os
import numpy as np
import scipy.ndimage
import torch
from matplotlib import pyplot as plt
from scipy.ndimage import gaussian_filter
from classic_methods.thresholding import normalize, read_case, focus_on_liver, normalize_intencities, get_dice
from datasets.data_utils import read_volume
from datasets.visuali... |
from collections import MutableSet
from math import hypot
def _build_variant(cls, opname):
fn = getattr(cls, opname)
if hasattr(fn, 'im_func'):
fn = fn.im_func
def method(self, other, fn=fn):
if not isinstance(other, MutableSet):
other = self._from_iterable(other)
return... |
# -*- coding: utf-8 -*-
"""
"""
"""
basic_sentiment_analysis
~~~~~~~~~~~~~~~~~~~~~~~~
This module contains the code and examples described in
http://fjavieralba.com/basic-sentiment-analysis-with-python.html
"""
from pprint import pprint
import nltk
import yaml
import sys
import os
import re
class Splitter(obj... |
"""
Classes and functionality to store TQ images and styling.
"""
import glob
import logging
import os
import subprocess
from PIL import Image
from shutil import rmtree
class SpriteCreator:
"""
SpriteCreator class.
Class that takes the bitmap outputs from the TQDB Parser and creates a
single sprite... |
"""Evaluation script for the DeepLab-ResNet network on the validation subset
of PASCAL VOC dataset.
This script evaluates the model on 1449 validation images.
"""
from __future__ import print_function
import argparse
from datetime import datetime
import os
import sys
import time
from PIL import Image
import tens... |
import dask.array as da
from dask import delayed
import numpy as np
import os
from pathlib import Path
import re
import skimage.io as io
LINE = '------------------------------------------------------------'
def get_files(
data_dir,
x_regex=r'\d{6}_\d{6}_\d{1,3}_image.tif',
... |
from numbers import Number
from python_helper.api.src.domain import Constant as c
from python_helper.api.src.service import ObjectHelper, StringHelper, ReflectionHelper
def getColorValue(thing, color) :
return color if ObjectHelper.isNotNone(color) else c.NATIVE_PROMPT_COLOR.get(
ReflectionHelper.getName(t... |
try:
from datacube.model import Product
except ImportError:
from datacube.model import DatasetType as Product
from datacube.model import Measurement
from datacube.utils.geometry import GeoBox
from datacube.api.grid_workflow import Tile
from datacube_stats.statistics import STATS
import warnings
class StatsT... |
import pandas as pd
from datetime import date
from pyspark.sql import SparkSession, DataFrame
from ophelia import FormatRead
from ophelia.generic import union_all
from ophelia import OpheliaReadFileException
from .._logger import OpheliaLogger
__all__ = ["Read", "SparkReadWrapper"]
class Read:
__logger = Opheli... |
#!/usr/bin/env python3
__author__ = ('<NAME> (<EMAIL>)')
__version__ = '0.01'
__date__ = 'Oct 21, 2020'
import os, requests, utils, xmltodict
# Define supported input file extensions
def supported_ext( ):
return [ "xml" ]
# header.schema definition
def dump_schema( convert_dir ):
pass
# Define the conversi... |
"""API views providing responses to api requests
Definition of logic after receiving requests to API endpoints
"""
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.exceptions import PermissionDenied
from rest_framework.decorators... |
import os
import os_tools.logger_handler as lh
import os_tools.tools as tools
import os_file_handler.file_handler as fh
import time
from os_btns_automation import btns_automation
from os_android_launcher_creator.LauncherObj import LauncherObj
from os_file_stream_handler import file_stream_handler as fsh
#############... |
from __future__ import absolute_import, division
import os.path
from math import sqrt
from random import random
import numpy as np
def euler(angle, axis):
cos_a = np.cos(angle)
sin_a = np.sin(angle)
if axis == 'x':
matrix = [[1, 0, 0], [0, cos_a, -sin_a], [0, sin_a, cos_a]]
elif axis == 'y':
... |
import argparse
import os
import re
from pathlib import Path
from typing import List, Optional
from git import Repo
from FileErrorDatabase import RepoFile, Repository, Repositories, FileErrorDatabase
ExtensionsOfInterest = ['*.OBK', '*.OLB', '*.DSN', '*.DBK']
def get_files_of_interest(path: str, file_extensions:... |
# Databricks CLI
# Copyright 2017 Databricks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"), except
# that the use of services to which certain application programming
# interfaces (each, an "API") connect requires that the user first obtain
# a license for the use of the APIs from Databricks,... |
from skimage import util
import numpy as np
import utils
def confusion_matrix(data_true, data_test):
"""Compares reference and test data to generate a confusion matrix.
Parameters
----------
data_true : ndarray
Reference binary data (ground truth).
data_test : ndarray
Test binary ... |
# -*- coding: utf-8 -*-
import pandas as pd
import re
import unicodedata
import urllib
import os.path
import glob
import yaml
"""
This script imports the updated 2020 titles for goals, targets, and indicators.
In keeping with past imports, the id numbers (eg, 1.1.1, 1.1, etc) are stripped
from the beginnings of the ti... |
# -*- coding: utf-8 -*-
#
# djangoplicity-contacts
# Copyright (c) 2007-2011, European Southern Observatory (ESO)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source ... |
# Copyright (c) 2019-2021 - for information on the respective copyright owner
# see the NOTICE file and/or the repository
# https://github.com/boschresearch/pylife
#
# 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 co... |
import tensorflow as tf
from tensorflow.keras.layers import Conv2D, Input, MaxPool2D, add, Flatten, Dense
def PEPXModel(input_tensor, filters, name):
x = Conv2D(filters=filters, kernel_size=(1, 1), activation='relu', name=name + 'FP')(input_tensor)
x = Conv2D(filters=filters, kernel_size=(1, 1), activation='r... |
import sys
import calendar
import datetime
# problem one
# --start=2021/2/14 --end=2021/2/14 --file=one.ics
def open_and_store_file(filename):
path_to_file = filename
open(path_to_file, 'r')
with open( path_to_file ) as f:
contents = f.read()
return contents
def file(filename):
filenam... |
"""Multivariate Normal Distribution."""
import numpy
from scipy import special
from chaospy.bertran import bindex
from .normal import normal
from ..baseclass import Dist
class MvNormal(Dist):
"""
Multivariate Normal Distribution.
Args:
loc (float, Dist): Mean vector
scale (float, Dist):... |
import os
import sys
import locale
import codecs
import argparse
import boto3
import logging
from botocore.client import ClientError
from termcolor import colored
from . import exceptions
from .core import AWSLogs
from ._version import __version__
def main(argv=None):
if sys.version_info < (3, 0):
sys.st... |
# 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
# distributed under th... |
# 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... |
# Copyright 2016 Huawei, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from .framework_pb2 import ProgramDesc
import os
def is_paddle_model(model_path):
model_file_path = os.path.join(model_path, "__model__")
if not os.path.exist... |
#!/usr/bin/python2.4
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of... |
import urllib2
from simplemediawiki import MediaWiki
from bs4 import BeautifulSoup
import nltk
import nltk.data
import os.path
#from nltk.tokenize import word_tokenize, workpunct_tokenize, sent_tokenize
class dispParameters:
def __init__(self, band, frame):
self.isBand = band #if there should be a band for the eve... |
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
"""
Some code used from from https://github.com/Newmu/dcgan_code
"""
import math
import numpy as np
import tensorflow as tf
from tensorflow.python.framework import ops
from utils import *
try:
image_summary = tf.image_summary
scalar_summary = tf.scalar_summary
histogram_summary = tf.histogram_summary
merge_... |
"""Testing numerical differentiation using diff.
<NAME>, September 2005.
"""
from numpy.testing import assert_almost_equal, assert_array_almost_equal
from numpy import (
abs,
allclose,
array,
diag,
ones,
sqrt,
zeros,
)
from numpy.random import random
from PyDSTool import (
diff,
... |
import asyncio
import datetime
from sprayit import logger
class SprayitProgress:
def __init__(self, domain, username, password, error, total, current):
self.username = username
self.password = password
self.error = error
self.total = total
self.current = current
class Sprayer:
def __init__(self, module,... |
"""Defines the `SiteMap` object, for storing the parsed ToC."""
from collections.abc import MutableMapping
from dataclasses import asdict, dataclass
from typing import Any, Dict, Iterator, List, Optional, Set, Union
from ._compat import (
DC_SLOTS,
deep_iterable,
field,
instance_of,
matches_re,
... |
"""
Copyright (c) 2016 <NAME>
See the file 'LICENSE' for copying permission
"""
from __future__ import print_function
import logging
import os
import sys
import time
from pyarplib import *
from scapy.all import *
import subprocess
import netifaces
import cmd
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)... |
import numpy as np
from sklearn.linear_model import LogisticRegression
from joblib import Parallel, delayed
from cvxopt import matrix, solvers
import cvxopt.glpk
import cvxopt
from .robust_nn.eps_separation import find_eps_separated_set
solvers.options['show_progress'] = False
cvxopt.glpk.options["msg_lev"] = "GLP_MS... |
#!/usr/bin/env python3
# coding: utf-8
#
# $Id: ibmap2slurm.py 3525 2021-11-02 11:06:57Z ltaulell $
# SPDX-License-Identifier: BSD-2-Clause
#
#
# some code from ibtoviz, Copyright (C) 2020 <NAME> (No license specified)
#
"""
create snippet for slurm topology.conf file from infiniband topology, hostname
mapping and s... |
import enum
import typing
import ci.util
from concourse.model.job import (
JobVariant,
)
from concourse.model.step import (
PipelineStep,
StepNotificationPolicy,
)
from concourse.model.base import (
AttributeSpec,
ModelBase,
Trait,
TraitTransformer,
ScriptType,
)
import concourse.model... |
#!/usr/bin/python
"""
"""
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
import imp
import numpy as np
import random
from random import shuffle as random_shuffle
from pyTools import display
from ioTools import readwrite
def lstdirNoExt(fileDir, ext=None):
""" ret... |
import numpy as np
import pandas as pd
import logging
import math as m
from scipy.optimize import root, curve_fit
from .models import (powerLaw, nsbContribution, ratescan_func)
logging.basicConfig(format='%(asctime)s|%(levelname)s|%(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p', level=logging.INFO)
l... |
#!/usr/bin/env python3
import sys
import wordvecutil
import tokenizer
import fst
import math
import functools
import operator
import getopt
import subprocess
import os
import argparse
import kenlm
# we can optionally use nltk to tag the text
# and focus on replacement of specific categories
#
# import nltk
parser ... |
import inspect as _inspect
from collections.abc import Callable, Awaitable
from typing import Literal
from bolinette import blnt, core, web, BolinetteExtension
from bolinette.blnt.commands import Command as _Command, Argument as _Argument
from bolinette.utils import InitProxy as _InitProxy
def model(model_name: str,... |
#!/bin/env python3
import os
import psycopg
import subprocess
ROOTPATH = os.path.split(os.path.realpath(__file__))[0]
cfg = {
'dbname': 'postgres',
'dbuser': 'postgres',
'dbpass': None
}
dbscripts = [
{
"label": "Database creation statements",
"filename": os.path.join(ROOTPATH,... |
# 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
# distributed u... |
import cv2
import numpy as np
def task_1():
def empty(_):
pass
image = cv2.imread('./../_data/s01e08/tomatoes_and_apples.jpg')
image = cv2.resize(image, (image.shape[0] // 2, image.shape[1] // 2), interpolation=cv2.INTER_AREA)
image_hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
cv2.named... |
#!/usr/bin/env python
# encoding: utf-8
import gym
from gym import spaces
from gym.utils import seeding
# Card score(A=1, 2-10=card point, J/Q/K= 0.5)
deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0.5, 0.5, 0.5]
# Person card
p_val = 0.5
# limit value
dest = 10.5
def draw_card(np_random):
return np_random.choice(deck... |
import os
import daggit
import requests
import io
import re
import shutil
import json
import numpy as np
import pandas as pd
import Levenshtein
from pyemd import emd
import ast
import copy
import json
def filterText(text, apply=True):
# get rid of newlines
if apply:
text = text.strip().replace("\n",... |
"""
Trains the VAE model and saves it inside models for later use
"""
import string
from collections import Counter
import numpy as np
import pandas as pd
import nltk
# nltk.download()
from nltk.tokenize import word_tokenize
from sklearn.model_selection import train_test_split
from lstm_vae import create_lstm_vae, ... |
from typing import List
from dataclasses import dataclass, field
from numba import cuda, float32
from numba.cuda.compiler import compile_ptx_for_current_device
from math import cos, sin, tan, exp, log, log10, log2, pow
from operator import truediv
import numpy as np
from numba.cuda.testing import CUDATestCase, skip_on_... |
#!/usr/bin/env python3
from __future__ import print_function
import subprocess
import argparse
import os
import sys
import csv
import glob
import shutil
# local paths
#KPATH = '/home/mdulac/knime_3.6.1/knime'
#RP_WORK_PATH = '/home/mdulac/Downloads/RetroPath2.0_docker_test/RetroPath2.0/RetroPath2.0.knwf'
#docker path... |
#!/usr/bin/env python3
import logging
import os
import signal
import sys
import threading
import click
import typing
from datetime import datetime
from kubernetes import client, config
from util import label_selector, parse_time, parse_duration, time_to_str
from logging import getLogger
logger = getLogger(__name__)... |
import unittest
import asyncio
import time
import random
import sys
from db import DB
from config import Config as C
from node import Node, encode_advance_area_table, encode_advance_bonus_table
def async_test(coro):
def wrapper(*args, **kwargs):
return loop.run_until_complete(coro(*args, **kwargs))
re... |
from flask import jsonify, request
from app import app
from .schema import schema_validation, aftale_post_schema, aftale_patch_schema
from app import config_data
from app import oauth_connect
@app.route('/aftale', methods=['POST'])
def create_aftale():
config = config_data.ConfigData()
aftale_response = {
'conta... |
#!/usr/bin/env python
# Libensemble for parameter optimization
from __future__ import division
from __future__ import absolute_import
from mpi4py import MPI # for libE communicator
import sys, os # for adding to path
import numpy as np
import socket
from libensemble.libE import libE
from libensemble.gen_funcs.pers... |
"""
Copyright 2020 The OneFlow 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 agr... |
from flask import request, Response, make_response, jsonify
from flask_restplus import Resource,Namespace, marshal_with, fields
from bson import json_util
import json
from config import Config
from .model import addBusinessModel,addgellaryModel, addDetailsModel, billing, addServiceModel,upload_documents, outletImagesMo... |
"""Created by <NAME>, @bizzfitch on github
>>> test_miller_rabin()
"""
def miller_rabin(n: int, allow_probable: bool = False) -> bool:
"""Deterministic Miller-Rabin algorithm for primes ~< 3.32e24.
Uses numerical analysis results to return whether or not the passed number
is prime. If the passed... |
from CodeGenerator.parser import Spreadsheet
from CodeGenerator.generators import Generator_BuR
from CodeGenerator.generators import Generator_SIE
from CodeGenerator.conf.config import *
import glob
import os
import json
from gooey import Gooey, GooeyParser
import logging
logging.basicConfig(format='%(asctime)s - %(me... |
"""
1. 注册链接: https://www.bybit.com/app/register?ref=yXjOz
推荐码:yXjOz, 目前官方有推荐返佣和奖励,以及各种活动奖励.
2. 官方网址:www.bybit.com, 注册需要科学上网,以后访问不需要.
api文档: https://bybit-exchange.github.io/docs/zh-cn/inverse/#rest-api
3. 微信: 51bitquant, 网易云课程链接: https://study.163.com/course/introduction/1209509824.htm
或者网易云课堂(https://study.163.com)搜... |
from __future__ import print_function, division
from modinv import modinv
"""
By <NAME> <<EMAIL>>
Operations modulus a prime number
"""
class FiniteField:
"""
FiniteField implements a value modulus a number.
"""
class Value:
"""
represent a value in the FiniteField
this class ... |
#-----------------------------------------------------------------------
#
# Description:
#
# views
#
#-------------------------------------------------------------------------------
#
# Project: EOxServer <http://eoxserver.org>
# Authors: <NAME> <<EMAIL>>
#
#---------------------------------------------------------... |
import expresso as ex
from .printer import latex
def S(expr):
if isinstance(expr,ex.core.Expression):
return Expression(expr)
if isinstance(expr,Expression):
return expr
if isinstance(expr,str):
return Expression(ex.core.create_symbol(expr))
if isinstance(expr,int):
if ... |
from __future__ import annotations
import typing as tp
from itertools import chain
if tp.TYPE_CHECKING:
from blox_old.block.base.block_base import BlockBase
from blox_old.block.base.port_section import BlockPortsSection
from blox_old.block.base.port_base import Port
class PortsHub:
""" This class hol... |
"""
Test consensus beam search.
To run
python -m explainx.run
"""
import os
import fire
import torch
from swissknife import utils
from .BLIP.models import blip, blip_vqa
from .misc import load_image_pil, load_image_tensor, show
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dump_dir = "/n... |
#!/usr/bin/env python3
import os
import sys
import copy
import glob
import json
import praw
import shutil
import fnmatch
import datetime
import tinycss
import operator
import textwrap
import webbrowser
import subprocess
import collections
from PIL import Image
with open('config.json') as fh:
CONFIG = json.load(fh)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.