text stringlengths 3.07k 12.6k |
|---|
#.!/usr/bin/env python3
import sys, json, os, argparse
# import from the 21 Developer Library
from two1.commands.config import Config
from two1.lib.wallet import Wallet
from two1.lib.bitrequests import BitTransferRequests
# set up bitrequest client for BitTransfer requests
wallet = Wallet()
username = Config().usern... |
# The MIT License (MIT)
#
# Copyright (c) 2018 <NAME>
# https://www.linkedin.com/in/federicosaldarini
# https://github.com/saldavonschwartz
# https://0xfede.io
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal... |
# Copyright 2020 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 agreed to... |
import logging
import os
import unittest
from distutils.util import strtobool
from nlp import cached_path, hf_bucket_url
def parse_flag_from_env(key, default=False):
try:
value = os.environ[key]
except KeyError:
# KEY isn't set, default to `default`.
_value = default
else:
... |
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404, render, redirect
from . import models
from .restapis import get_dealers_from_cf, get_dealer_by_id_from_cf, post_request
from django.c... |
from dataclasses import dataclass
import numpy as np
import imports as imp
import sys
# TODO: Maybe separate the matching and executing into diferent threads.
class order:
def __init__(self, acc : int, sec : str, otype : str, prc : float, qty : int):
#assert isinstance(acc, int) and isinstance(prc, float... |
#! encoding: UTF-8
import os
import opts
import ipdb
import time
import random
import numpy as np
import cPickle as pickle
import keras
from keras.datasets import mnist
import tensorflow as tf
class LSTM():
def __init__(self, opt):
self.lstm_step = opt.lstm_step
self.batch_size = opt.batch_size
... |
from ucca import layer1
from actions import Actions
LABEL_ATTRIB = "label"
COMPOUND = "compound"
class InvalidActionError(AssertionError):
def __init__(self, *args, is_type=False):
super().__init__(*args)
self.is_type = is_type
#modified from: https://github.com/danielhers/tupa/blob/master/t... |
#!/usr/bin/env python
"""Fleetspeak-facing client related functionality.
This module contains glue code necessary for Fleetspeak and the GRR client
to work together.
"""
import logging
import os
import pdb
import Queue
import struct
import threading
import time
from fleetspeak.src.client.daemonservice.client import ... |
import _hashlib # for typing
import io
import os
from hashlib import sha256
from tempfile import TemporaryFile
from typing import Generator
from typing import IO
from typing import Optional
import colorlog
from backuppy.exceptions import DoubleBufferError
from backuppy.exceptions import FileChangedException
logger ... |
from collections import defaultdict, namedtuple
from random import choice, random, seed
from typing import Hashable
import gym
from numpy import Inf
Action = int
Reward = float
Obs = Hashable
Step = tuple[Obs, Action, Reward]
Episode = list[Step]
episode_step = namedtuple('EpisodeStep', field_names=['obs', 'action', '... |
# Copyright 2017 SAP SE
#
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
# -*- coding: utf-8 -*-
"""
Qinstor storage backend
@author:knktc
@contact:<EMAIL>
@create:2018-08-31 15:41
"""
import base64
import hmac
import os
import time
import urllib
from hashlib import sha256
from tempfile import SpooledTemporaryFile
from django.conf import settings
from django.core.exceptions import Impro... |
# coding: utf8
import requests
import re
import os
import json
import time
from fastapi import FastAPI
from PIL import Image
from lxml import etree
BASE_PATH = os.path.join(
os.path.dirname(
os.path.abspath(__file__)
)
, "img"
)
TEXT_TEMPLATE = """
作者:{0}
发布时间:{1}
内容:{2}
"""
WRITE_TEXT_API_URL ... |
from gevent import monkey
monkey.patch_all()
import serial #install pySerial
import time
import threading
from flask_bootstrap import Bootstrap
from flask import Flask, render_template, request, json
from flask_socketio import SocketIO, emit, join_room, leave_room
from dataclasses import dataclass
# Flask Setup... |
#!/usr/bin/env python3
"""
Script to collect MAC addresses of endpoints in old and new ISE deployments for the migration purposes and comparison/
Idea:
- Predefined and equal Group in both ISE clusters
- API to old ISE, check groups, collect endpoints from those groups and keep them in the file - ise_groups_o... |
# Copyright 2013 Cloudbase Solutions Srl
# 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 r... |
# pylint: disable=wildcard-import
# pylint: disable=unused-wildcard-import
import os
import pytest
import sbk.gf
import sbk.primes
import sbk.gf_poly
from sbk.enc_util import *
def test_bytes2hex():
assert bytes2hex(b"test data") == '746573742064617461'
assert hex2bytes('746573742064617461') == b"test data... |
import unittest
from databricksbundle.widgets.DatabricksWidgets import DatabricksWidgets
from databricksbundle.widgets.testing import DbUtilsTesting, TestingDbUtilsWidgets
def set_input(**kwargs):
TestingDbUtilsWidgets.set_raw_values(kwargs)
class DatabricksWidgetsTest(unittest.TestCase):
def setUp(self):
... |
# Copyright (C) 2014-2020 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
# 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.a... |
import math
import pathlib
import tarfile
import urllib.request
import ase
import ase.io
import matplotlib.pyplot as plt
import numpy as np
import plotly
from plotly import graph_objects
from IPython import display
def split_data(features, objectives, train_ratio):
"""Split data into a fitting and training set""... |
import argparse
import os, sys
import numpy as np
from scipy.ndimage import rotate
from tqdm import tqdm
def rotate_gt(args, categories_dict, scannet_shape_ids, angles):
for category in categories_dict:
cat_path = categories_dict[category] + '_geo'
cat_save_path = os.path.join(args.data_dir, cat... |
import numpy as np
import scipy.sparse as sp
from joblib import Memory
from pathlib import Path
from sklearn.decomposition import TruncatedSVD
from sklearn.datasets import (make_blobs, fetch_20newsgroups,
fetch_openml, load_digits, make_regression,
make_class... |
# coding: utf-8
from __future__ import absolute_import, division, print_function
from threading import Lock
import attr
import six
from arpeggio import NoMatch, PTNodeVisitor, Terminal, visit_parse_tree
from arpeggio.cleanpeg import ParserPEG
from . import _segments as segment
from ._helpers import IMPLICIT_ZERO, UN... |
import os
import subprocess
import time
from multiprocessing import Process
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
from redis import Redis
import pexpect
import wget
import datetime
from firebase_admin import storage
import shutil
import urllib.request
cli = Redis('l... |
import os
import sys
import v20
import yaml
DEFAULT_ENV = "bitbot"
DEFAULT_PATH = "../.account.conf"
class ConfigPathError(Exception):
"""
Exception to catch when the account.conf file is not found.
"""
def __init__(self, path):
self.path = path
def __str__(self):
return f'Config... |
from math import *
from NodeGeneratorBase import *
from Spheral import Vector3d, Tensor3d, SymTensor3d, Plane3d, rotationMatrix
from SpheralTestUtilities import *
import mpi
procID = mpi.rank
nProcs = mpi.procs
#-------------------------------------------------------------------------------
# The sign function
#----... |
from random import choice
from copy import deepcopy
import numpy as np
class CarganGrilleError(Exception):
pass
class Field:
def __init__(self, value: int, cond: bool = False):
self.value = value
self.cond = cond
def __str__(self):
return f"{self.value}"
def __repr__(self)... |
# *** tensorrt校准模块 ***
import os
import torch
import torch.nn.functional as F
import tensorrt as trt
import pycuda.driver as cuda
import pycuda.autoinit
import numpy as np
import ctypes
import logging
import util_trt
logger = logging.getLogger(__name__)
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_char_p
... |
import requests
import json
# import related models here
from requests.auth import HTTPBasicAuth
# Create a `get_request` to make HTTP GET requests
# e.g., response = requests.get(url, params=params, headers={'Content-Type': 'application/json'},
# auth=HTTPBasicAuth('apikey', api_k... |
import torch
from torch import nn
import numpy as np
class InvertiblePriorLinear(nn.Module):
"""docstring for InvertiblePrior"""
def __init__(self):
super(InvertiblePriorLinear, self).__init__()
self.p = nn.Parameter(torch.rand([2]))
def forward(self, eps):
o = self.p[0] * eps + s... |
import time, math, os, json, sys
import data as enum
from Person import Person
from Events import getEvent
from time import sleep as wait
from Plot import plot as _Plot
from inspect import signature
def set_resp(e, v):
tempv = {}
with open("resp.json", "r") as j:
tempv = json.load(j)
tempv[e] ... |
"""
MAUS is the MIG AHB Utility stack.
This module contains methods to merge data from Message Implementation Guide and Anwendungshandbuch
"""
from itertools import groupby
from typing import List, Sequence
from maus.models.anwendungshandbuch import AhbLine, DeepAnwendungshandbuch, FlatAnwendungshandbuch
from ... |
from collections import OrderedDict, Iterable
from django.utils import six
from django.utils.functional import LazyObject
from json_api.exceptions import ErrorList, NotFound, ParseError
from json_api.settings import api_settings
from json_api.utils import view_meta
# TODO: could probably use a rewrite, but is a good ... |
import argparse
import math
import numpy
import os
import time
from functools import partial
from math import ceil, floor
from multiprocessing import cpu_count, Manager, Pool, Queue
from numpy import ndarray
from PIL import Image
from numpy.lib.function_base import place
from sklearn.cluster import KMeans
from typing ... |
#!/usr/bin/env python3
# Developed by <NAME>
# Covered by the LICENSE file in the root of this project.
# Brief: This demo shows how to generate the overlap and yaw ground truth files for training and testing.
import os
import matplotlib.pyplot as plt
import numpy as np
import json
# this function obtains the loop ... |
from discord.ext import commands
import discord
from mcstatus import MinecraftServer
import socket
from pyraklib.protocol.EncapsulatedPacket import EncapsulatedPacket
from pyraklib.protocol.UNCONNECTED_PING import UNCONNECTED_PING
from pyraklib.protocol.UNCONNECTED_PONG import UNCONNECTED_PONG
import aiohttp
import bas... |
import kopf
import yaml
import kubernetes
import time
import logging
from jinja2 import Environment, FileSystemLoader
from kubernetes.stream import stream
from kubernetes.client.api import core_v1_api
logger = logging.getLogger(__name__)
def wait_until_job_end(jobname):
api = kubernetes.client.BatchV1Api()
j... |
from flask import Blueprint, jsonify, request
from psycopg2 import sql
from app.postgres import Database
from app.models import check_auth, authorize
create_new_vacancy_bp = Blueprint('create_new_vacancy', __name__)
@create_new_vacancy_bp.route('/create_new_vacancy', methods=["POST"])
def create_new_vacancy():
u... |
import pytest
import numpy as np
from ..interval_set import IntervalSet
@pytest.fixture()
def isets():
a = IntervalSet(np.array([[49, 73], [53, 54], [33, 63], [65, 80],
[51, 80], [100, 126], [38, 68], [61, 72],
[74, 102], [27, 43]], dtype=np.uint64))
b = IntervalSet(np.array([[17, 26], [17, 41... |
import django
import logging
# from nltk import word_tokenize
import os
# import re
from slacker import Slacker
from sutime import SUTime
import tweepy
from tweepy.api import API
from slack_msg import send_slack_message
# need to point Django at the right settings to access pieces of app
os.environ["DJANGO_SETTINGS_MO... |
import numpy as np
from scipy import constants
import matplotlib.pyplot as plt
import matplotlib as mpl
import meep
import meep_ext
import pinboard
job = pinboard.pinboard()
nm = 1e-9
um = 1e-6
### geometry
radius = 75*nm
gold = meep_ext.material.Au()
# gold = meep.Medium(index=3.5)
### source
wavelength = 550*nm
fc... |
# coding=utf-8
"""
@author: <NAME>
@date: 02/01/2020
@description: This file aims to extract English reviews with gender and age information in the user profiles.
"""
import pandas as pd
import numpy as np
import os
from sklearn.utils import shuffle
import fasttext
import ast
import argparse
# Define file path
WWW201... |
import logging
import time
import cv2
import numpy as np
from djitellopy import tello
import keypress as kp
from time import sleep
def findFace(img):
faceCascade = cv2.CascadeClassifier("Resources/haarcascade_frontalface_default.xml")
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.dete... |
from django.shortcuts import render, redirect
from django.core.urlresolvers import reverse
from manage_tools.models import Tool, ToolCategory
from shared_zone.models import SharedZone
from user.models import User
from request.models import Request, Notification
# from faker import Faker
from django.core.paginator impor... |
import time
from typing import List, Set, Tuple
from src.Dto.operation import Operation
from enum import Enum
from src.Dto.keywords import Method
from itertools import groupby, permutations, combinations
from random import choice
class Node:
def __init__(self, operations: List[Operation]):
self.operations... |
''' Imports '''
def warn(*args, **kwargs):
pass
import warnings
warnings.warn = warn
import performance
import get_images
import get_landmarks
import pandas
from sklearn.multiclass import OneVsRestClassifier as ORC
from sklearn.model_selection import train_test_split
''' Import classifier '''
fr... |
# from parent folder, run 'python -m xutil.tests.database_test'
# coverage run -m xutil.tests.database_test
# coverage report
# coverage html
import sys
from unittest import TestCase, main
from copy import deepcopy
from xutil.database.base import get_conn
from xutil.helpers import get_profile, get_databases, elog
fro... |
# -*- coding: utf-8 -*-
import logging
from flask import current_app, jsonify
from jsonschema import ValidationError
from patientMatcher.__version__ import __version__
from patientMatcher.auth.auth import authorize
from patientMatcher.constants import STATUS_CODES
from patientMatcher.match.handler import external_matc... |
from abc import abstractmethod
from ast import literal_eval
from collections import namedtuple
import contextlib
import csv
import logging
import urllib2
from StringIO import StringIO
from fabric.operations import sudo, put, run
from cgcloud.core.box import fabric_task
from cgcloud.core.init_box import UpstartBox, Sy... |
from autograder.box_extractor import box_extraction
from autograder.character_predictor import predict
from autograder.spelling_corrector import fix_spellings
from autograder.text_similarity import check_similarity, get_marks
from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from typing import List
im... |
# SPDX-License-Identifier: BSD-2-Clause
""" This module provides classes for content generation. """
# Copyright (C) 2019, 2020 embedded brains GmbH (http://www.embedded-brains.de)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following condition... |
import base64
from typing import List, Optional
from electrum_gui.common.basic.functional.require import require
from electrum_gui.common.basic.functional.text import force_text
from electrum_gui.common.basic.request.exceptions import RequestException, ResponseException
from electrum_gui.common.basic.request.restful i... |
#!/usr/bin/env python3
# coding: utf-8
# Copyright 2016 <NAME>, https://github.com/tywtyw2002, and https://github.com/treedust
#
# 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:/... |
import pickle
import os
import time
import shutil
import torch
import data
#from vocab import Vocabulary # NOQA
from vocab import Vocabulary, deserialize_vocab
from model import VSRN
from evaluation import i2t, t2i, AverageMeter, LogCollector, encode_data, nDCG5_t2i, nDCG5_t2i_rerank, nDCG5_t2i_atten_rerank
import l... |
'''
Task 6.
Продолжить работу над вторым заданием.
Реализуйте механизм валидации вводимых пользователем данных.
Например, для указания количества принтеров, отправленных на склад, нельзя использовать строковый тип данных.
Подсказка:
постарайтесь по возможности реализовать в проекте «Склад оргтехники» максимум возможн... |
import time
import os, re
import subprocess
import numpy as np
from collections import OrderedDict
from . import LSST_INSTALLED
scratch_dir = '/scratch/gpfs/jgreco/hugs-io/'
slurm_options = OrderedDict([
('job-name', 'slurm-driver'),
('output', scratch_dir + 'slurm-%j.out'),
('error', scratch_dir + 'slurm-... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: pragadesh06
"""
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.utils.data
from torch.autograd import Variable
#importing data
movies = pd.read_csv('ml-1m/movies.dat',sep = '::',
... |
import time
from time import sleep
import client
from logic import epoch_logic, validator_logic, shard_logic
import config
VALIDATOR_LENGTHS = []
MAX_VALIDATOR_LENGTHS = 20
def get_validators_and_bid_if_necessary(bidding_enabled=False):
debug_json = {}
my_validator = validator_logic.get_my_validator()
i... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2021 <NAME>.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Grants classes for the access system field."""
from base64 import b64decode, b64enco... |
#coding=utf-8
from sys import argv
import string
#Strutture dati Globali
vocali = ('a','e','i','o','u')
mesi = ('a','b','c','d','e','h','l','m','p','r','s','t')
comuni = {'udine':'l483', 'verona':'l781', 'legnago': 'e512', 'negrar':'f861', 'bassano del grappa': 'a703'}
#CODICI DI CONTROLLO
regole_pari = {}
alfabeto =... |
# -*- coding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
STOP_RENDERING = runtime.STOP_RENDERING
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1523548573.8053489
_enable_loop = True
_template_filename = 'C:/Users/Linds/desktop/intex2_fomo/ca... |
import os, csv, time
from .constants import TENSE, TENSE_NAMES, TENSE_VALUES
from requests_html import HTMLSession
KEY_FIELD = ("inf",)
SUPPLIED_FIELDS = (
"hint", "hint-rules", "use-eng-defs",
"eng-inf", "eng-gerund",
"eng-1", "eng-3", "eng-p",
"eng-past", "eng-past-perf"
)
BASIC_FIELDS = KEY_FIEL... |
# Copyright (c) <NAME>
# See LICENSE for details.
"""Check HTTP server for responsiveness"""
import collections
import functools
import json
import sys
import six
import twisted
from twisted.application import internet as tainternet
from twisted.internet import defer, reactor
from twisted.web import client
import... |
import os
import tensorflow as tf
from badgr.file_manager import FileManager
from badgr.datasets.tfrecord_rebalance_dataset import TfrecordRebalanceDataset
from badgr.jackal.envs.jackal_env_specs import JackalPositionCollisionEnvSpec
from badgr.jackal.models.jackal_position_model import JackalPositionModel
from badgr.... |
import logging
import os.path as op
from functools import partial
from itertools import chain
import sublime
import sublime_plugin
import flower
from . import manager
from .utils import rootSplit, getBinaryFolder
from .compilerutils import getCompiler, COMPILER_KEY
from .process import Executor, Callback, Default
fro... |
import os
import math
import calendar
import datetime
import configparser
from flask import Flask, render_template, abort, jsonify
from pymongo import MongoClient
TITLE = 'DevDiary - samhattangady'
BLOG_LIMIT = {'chars': 300, 'number': 2}
# Did some prototyping in Inkscape. 690*80, 12.5 sq days, 4 rows, 5 months look... |
# Copyright 2021 <NAME> (https://github.com/jack1142)
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import glob
import multiprocessing as mp
import torch
import time
import os
import json
from pycocotools.coco import COCO
from pycocotools import mask as cocomask
from pycocotools.cocoeval import COCOeval
import numpy as np
from det... |
from __future__ import annotations
import typing
from ctc import binary
from ctc import rpc
from ctc import spec
from ctc.toolbox import backend_utils
from .event_backends import filesystem_events
from .event_backends import node_events
from .. import block_utils
from .. import abi_utils
def is_event_hash(data: sp... |
import numpy as np
import matplotlib.pyplot as plt
from mpi4py import MPI
from pymgrit.heat.heat_1d import Heat1D
from pymgrit.core.at_mgrit import AtMgrit
def compute_analytical_solution():
x = np.linspace(0, 3, 1025)
analytical_sol = np.zeros((len(heat0.t), 1025))
for i in range(len(heat0.t)):
... |
"""
This module benchmarks multi-agent evacuation algorithms.
It allows running evacuation planning algorithms on multiple maps and scenarios,
optionally in parallel, and then calculates various statistics about the plans
that were produced.
"""
from __future__ import annotations
from json import dumps
from multiproc... |
#!/usr/bin/env python3
# Standard libraries
from time import time
# Components
from ..prints.colors import Colors
from ..system.platform import Platform
# TimedHistory class
class TimedHistory:
# Members
__duration = 0
__start_time = 0
# Constructor
def __init__(self):
self.__duration =... |
#!/usr/bin/env python3
import os
import sys
import argparse
from argparse import RawTextHelpFormatter
import logging
from process import *
__author__ = "<NAME> (based upon Arlo White's original)"
__version__ = "0.1"
__title__ = "Sentry"
__license__ = "GPLv3"
__author_email__ = "<EMAIL>"
# TODO:
# - Sentry should per... |
# %%
# Detrending PEMS measurements affected by sensor temperature changes
# <NAME>, Ph.D. Candidate
# %%
# Load required libraries
import pandas as pd
import obspy
import matplotlib.pyplot as plt
import seaborn as sns
import datetime as dt
from obspy.signal.detrend import polynomial
# %%
# Load data from Excel to p... |
# coding=utf-8
# Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
# Copyright 2018 The HuggingFace Inc. team.
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Y... |
# -*- coding: utf-8 -*-
#
# __init__.py
#
# This file is part of NEST.
#
# Copyright (C) 2004 The NEST Initiative
#
# NEST 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
# ... |
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
import numpy as np
from libs.models.utils.utils import upsample_bilinear
from libs.models.utils.utils import _ConvBatchNormReLU
from libs.models.utils.utils import init_weigh... |
import cv2
import glob
import os
import numpy as np
# comment out to use main function
from styx_msgs.msg import TrafficLight
class TLClassifier(object):
def __init__(self):
#TODO load classifier
self.red_lower_mask = [(0,164,160), (10,255,255)]
self.red_upper_mask = [(170,164,160), (179,... |
import datetime
import numpy as np
import pandas as pd
from scipy import stats
from collections import Counter
from tqdm import tqdm
tqdm.pandas(desc="progress")
#================================================================================
#Don't change the code below!!! 以下代码请勿轻易改动。
#==========================... |
# coding=utf-8
# Copyright 2021 The HiT-GAN Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
import asyncio
from datetime import timedelta
from typing import Dict, Optional, List, NamedTuple, Mapping, Union
import aiohttp
import backoff
from .decorators import timed_async_cache
BASE_URL = "https://api.twitch.tv/helix"
USER_ENDPOINT = BASE_URL + "/users"
STREAM_ENDPOINT = BASE_URL + "/streams"
JSON = Union[... |
from pyomo.environ import *
from pyomo.solvers.plugins import *
from pyomo.opt import SolverFactory
from bentso.filesystem import create_dir
from bentso.client import CachingDataClient
import pandas as pd
import os
def LoadModelData():
cwd = os.getcwd()
temp_path = os.path.join(cwd,'temp_opt')
data = DataP... |
'''
api.py
<NAME> and <NAME>, 8 November 2021
Flask API to support the final project application.
When comparing strings in SQL calls, case is always ignored.
'''
import sys
import flask
import json
import config
import psycopg2
api = flask.Blueprint('api', __name__)
def get_connection():
''' Returns a con... |
# Copyright 2018-2022 Xanadu Quantum Technologies 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 applicabl... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import collections
import typing
from enum import Enum
from itertools import chain
from bravado_core.spec import Spec
from swagger_spec_compatibility.spec_utils import get_prop... |
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio
import torchaudio.functional as AF
import librosa
import math
import sys
import numpy as np
import time
from conf.feature import *
from conf.inference import *
def align(a, b, dim):
return a.transpose(0, dim)[:b.shape[d... |
from __future__ import absolute_import
import functools
import logging
from pprint import pformat
from urllib import urlencode
import flask
from flask import request, current_app
from flask_login import current_user
import werkzeug as wz
from flask_acl.core import iter_object_acl, get_object_context, check
from flas... |
import os
from flask import Blueprint
from jmapp.lib.auth import jwt_required
from model import job_mod, apply_mod, offer_mod
fname = os.path.basename(__file__).split(".")[0]
job = Blueprint(fname, __name__)
job_m = job_mod()
apply_m = apply_mod()
offer_m = offer_mod()
@job.route("/", methods=["GET"])
@jwt_require... |
"""
Helper functions to manage amazon cloud
"""
import boto.ec2
import boto.ec2.elb
import boto.rds
import time
from fabric.api import env, run
from fabric.exceptions import NetworkError
from fabric.context_managers import settings
from fabric.colors import red, green, blue
from fabric.utils import abort
def ad... |
'''
Author : now more
Connect : <EMAIL>
LastEditors : now more
Description :
LastEditTime: 2019-08-26 17:52:59
'''
from importer import *
from ignite.metrics import Metric
def _fast_hist(label_true, label_pred, n_class):
mask = (label_true >= 0) & (label_true < n_class)
hist = np.bincount(
n_... |
import os
import random
import subprocess
from multiprocessing.dummy import Pool as ThreadPool
from sys import platform
from zipfile import ZipFile
import requests
import torch
from PIL import Image
from torch.utils import data
from torchvision import transforms
from tqdm import tqdm
from base import BaseDataLoader
f... |
"""
Views for django-skip-logic. Handles surveys, survey results, call to action.
"""
import random
import string
from ipware.ip import get_ip
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.views import generic
from dja... |
#import cherrypy
import re
import string
import os
import pickle
import urllib
import base64
import inspect
import logging
def set_log_level(log_level=None):
logging.basicConfig(level=logging.ERROR)
# https://stackoverflow.com/a/57896847
logging.Logger.root.level = logging.ERROR
if not log_level:
... |
import numpy as np
import pyroomacoustics as pra
import soundfile as sf
from src.utils.dsp_utils import normalize, center
def callback_mix(premix, snr=0, sir=0, ref_mic=0, n_src=None, n_tgt=None):
I, J, N = premix.shape
# first normalize all separate recording to have unit power at microphone one
p_mic... |
'''
Copyright (C) 2021 CG Cookie
http://cgcookie.com
<EMAIL>
Created by <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 version 3 of the License, or
(at your op... |
import pandas as pd
import numpy as np
from transforms3d.euler import mat2euler
def construct_df_trajectories_per_trial(hd, ed):
"""
This function takes in the Head Data (hd) and Event Data (ed) frames, and constructs a DataFrame that is indexed
on time stamp, but contains just the trajectories between th... |
# Copyright 2019 The TensorFlow 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 applica... |
# vim: set fileencoding=utf8 :
import sys, re, os
from itertools import chain, groupby
import click
import pkg_resources # part of setuptools
version_str = pkg_resources.require("linkermap")[0].version
ffmt = '{:>50} |'
sfmt = '{:>8}'
class Objectfile:
def __init__ (self, section, offset, size, comment):
... |
# coding: latin-1
"""
Apply stage-III of HAnDS framework.
"""
import os
import sys
import glob
import gzip
import json
from helper import ensure_directory
__author__ = "Abhishek, <NAME>, and <NAME>"
__maintainer__ = "Abhishek"
def read_frequent_sentence_starters(file_path, top_x):
"""
Load top x number of lin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.