text stringlengths 3.07k 12.6k |
|---|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
from .utils import _gather_feat, _transpose_and_gather_feat
def _nms(heat, kernel=3):
pad = (kernel - 1) // 2
hmax = nn.functional.max_pool2d(
heat, (kernel,... |
import tempfile
import strax
import straxen
from straxen.test_utils import nt_test_run_id, DummyRawRecords, testing_config_1T, test_run_id_1T
def _run_plugins(st,
make_all=False,
run_id=nt_test_run_id,
from_scratch=False,
**process_kwargs):
"""
... |
import os
import re
import time
from random import Random
import pytest
from invoke.context import Context
from src.benchmark_metrics import (
TENSORFLOW2_SM_TRAINING_CPU_1NODE_THRESHOLD,
TENSORFLOW2_SM_TRAINING_CPU_4NODE_THRESHOLD,
TENSORFLOW2_SM_TRAINING_GPU_1NODE_THRESHOLD,
TENSORFLOW2_SM_TRAINING... |
"""Classes for handling geometry.
Geometric objects (see :class:`GeometricObject`) are usually
used in :class:`~ihm.restraint.GeometricRestraint` objects.
"""
class Center(object):
"""Define the center of a geometric object in Cartesian space.
:param float x: x coordinate
:param float y: y co... |
'''
Description: 构造一个数据集类,继承官方的torch.utils.data.Dataset
Author: HCQ
Company(School): UCAS
Email: <EMAIL>
Date: 2021-06-05 11:19:36
LastEditTime: 2021-06-10 10:40:49
FilePath: /pointnet-simple/framework/dataset.py
'''
import torch
import os
import json
from torch.utils.data import Dataset # 官方
from torch.utils.data impo... |
import os
import mistune
from datetime import datetime
from io import BytesIO
from zipfile import ZipFile
from django import http
from django.contrib import messages
from django.views import generic
from django.urls import reverse
from django.utils.timezone import make_aware
from django.shortcuts import redirect
from... |
import numpy as np
import cPickle
import os
import pdb
import cv2
def unpickle(file):
fo = open(file, 'rb')
dict = cPickle.load(fo)
fo.close()
return dict
def load_data(train_path,order,nb_groups, nb_cl, nb_val,SubMean = False):
xs = []
ys = []
for j in range(1):
d = unpickle(train_p... |
#from .nlp_loader import nlp
PREPOSITIONS = ("aboard", "about", "above", "across", "after", "against",
"along", "amid", "among", "around", "as", "at", "before", "behind",
"below", "beneath", "beside", "between", "beyond", "but", "by",
"concerning", "considering", "despite", "down", "during", "except",
... |
import numpy as np
from .parse import parse_xtekct_file
class Config(object):
def __init__(self):
""" Configuration object which contains all settings neccessary for the forward projection
and tomographic reconstruction using the axitom algorithm.
"""
self.n_voxels_x = 2000
... |
# -*- coding: utf-8 -*-
u'''
This script evaluates the performance of the following outlier detection method:
- Consensus Regularized Multi-View Outlier Detection (CMOD)
- DMOD
- HOAD
Arguments:
-c, --config: JSON file with the information required to insert data
-N, --datasetName: name of the im... |
from operator import itemgetter
from collections import defaultdict
import scipy.stats as st
import numpy as np
import pandas as pd
def k_factor(margin_of_victory, elo_diff):
init_k = 20
if margin_of_victory>0:
multiplier = (margin_of_victory+3) ** (0.8) / (7.5 + 0.006 * (elo_diff))
else:
... |
import numpy as np
import torch
import itertools
from torch.autograd import Variable
def getGridMask(frame, dimensions, num_person, neighborhood_size, grid_size, is_occupancy = False):
'''
This function computes the binary mask that represents the
occupancy of each ped in the other's grid
params:
... |
import numpy as np
from sklearn.neighbors import BallTree
from scipy.spatial.qhull import QhullError
from infomap import Infomap
from scipy.spatial import ConvexHull
from tqdm import tqdm
def pass_func(input, **kwargs):
return input
def query_neighbors(coords, r2, distance_metric='haversine', weighted=False):
... |
#
# Code borrowed and modified from https://www.esri.com/arcgis-blog/products/arcgis-pro/health/use-proximity-tracing-to-identify-possible-contact-events/
#
import os
import subprocess
import sys
import winreg
from typing import Dict
import arcpy
import glob
pro_home = arcpy.GetInstallInfo()["InstallDir"]
pro_lib_dir... |
def separador(mano):
lista_valor = []
lista_suit = []
valor_carta = {'2':1, '3':2, '4':3, '5':4, '6':5, '7':6, '8':7, '9':8, 'T':9, 'J':10, 'Q':11, 'K':12, 'A':13}
for i in mano.split(' '):
lista_valor.append(valor_carta.get(i[0]))
lista_suit.append(i[1])
return(sorted(lista_valor), lista_suit)
def Royal_F... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# python3 d_speed_size.py : test speed/compression for folder 'corpus'
# python3 d_speed_size.py indir : test speed/compression for folder 'indir'
import os
import sys
import stat
import time
import shutil
import ntpath
import subprocess
import pandas as pd
def ... |
# -*- coding: utf-8 -*-
import itertools
from collections import Iterable
import torch
class GeneralCollateFunction(object):
"""A Generic `Collate_fn`.
For finetuning-train.
"""
def __init__(self, trfms, times):
"""Initialize a `GeneralCollateFunction`.
Args:
trfms (lis... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import logging as log
import numpy as np
from openvino.tools.mo.front.common.partial_infer.utils import shape_array, dynamic_dimension_value
from openvino.tools.mo.front.tf.common import tf_data_type_decode
from openvino.tools.mo.utils... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from datetime import datetime
from django.http import Http404
from django.http import JsonResponse
import socket as sok
from random import randint
from . import Comunicacion
# Create your views here.
def loguin(request):
if request.... |
from brown.core.accidental import Accidental
from brown.core.music_text import MusicText
from brown.core.object_group import ObjectGroup
from brown.core.staff_object import StaffObject
from brown.models.accidental_type import AccidentalType
from brown.models.clef_type import ClefType
from brown.models.key_signature_typ... |
# -*- coding: utf-8 -*-
import pytest
from girder.exceptions import AccessException
from girder.models.setting import Setting
from girder.models.user import User
from girder.settings import SettingKey
from pytest_girder.assertions import assertStatus, assertStatusOk
def testInitializeOtp(user):
# The logic for t... |
## @file
# Trim files preprocessed by compiler
#
# Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
# Import Modules
#
import os
import sys
import time
import logging
import struct
import datetime
import argparse
import platform
from ... |
# -*- coding: utf-8 -*-
import copy
import json
import logging
import weakref
from collections import namedtuple
import jsonschema
from gevent.queue import Full
from ws4py.websocket import WebSocket as _WebSocket
from h import storage
from h.streamer.filter import FILTER_SCHEMA, SocketFilter
log = logging.getLogger... |
import numpy as np
import pandas as pd
from spandex import TableLoader, TableFrame
from spandex.io import df_to_db
import urbansim.sim.simulation as sim
import utils
loader = TableLoader()
staging = loader.tables.staging
## Assumptions.
# Use codes were classified manually because the assessor classifications
# ... |
import cv2
import numpy as np
import math
import os
from time import sleep
def prewitt(nome):
imagem = cv2.imread(nome)
imagemNova = cv2.imread(nome)
colunas = imagem.shape[1]
linhas = imagem.shape[0]
sizeMask = 3
flagStop = sizeMask**2
pixelB = 0
pixelG = 0
pixelR = 0
p... |
"""Hardware interfaces for triggering"""
# Authors: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import sys
import numpy as np
from ._utils import verbose_dec, string_types, logger
class ParallelTrigger(object):
"""Parallel port and dummy triggering support.
.. warning:: When u... |
#!/usr/bin/env python3
import os
import random
import numpy as np
import pandas as pd
import numpy as np
from numpy.linalg import slogdet
import time
from experiment_runner.experiment_runner_v2 import run_experiments
# from PySSM import Matrix, Vector
from PySSM import RBFKernel
from PySSM import IVM, FastIVM
from... |
# Copyright 2018-2021 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 applicable law or... |
import hydra
import hydra.utils as utils
from pathlib import Path
import torch
import numpy as np
from tqdm import tqdm
import soundfile as sf
from model_encoder import Encoder, Encoder_lf0
from model_decoder import Decoder_ac
from model_encoder import SpeakerEncoder as Encoder_spk
import os
import random
from glob... |
# This file is a part of the Pepper project, https://github.com/devosoft/Pepper
# (C) Michigan State University, under the MIT License
# See LICENSE.txt for more information
"""
This is the abstract symbol tree for PEPPr.
The parser will build the actual tree, so this is really more of a library of nodes that may
be ... |
# coding=utf-8
from functools import partial
from logging import addLevelName, getLogger as _getLogger, setLoggerClass, \
FileHandler, Filter, Formatter, Logger, LogRecord, StreamHandler, CRITICAL, DEBUG, ERROR, INFO, NOTSET, WARNING
from string import Template
from typing import cast, Any, Callable, Iterable, Mapp... |
import pytest
from webbpsf import wfirst
from numpy import allclose
def test_WFI_psf():
"""
Just test that instantiating WFI works and can compute a PSF without raising
any exceptions
"""
wi = wfirst.WFI()
wi.calc_psf(fov_pixels=4)
def test_WFI_filters():
wi = wfirst.WFI()
filter_lis... |
import pickle
import numpy as np
import pytest
from sklearn.neighbors._quad_tree import _QuadTree
from sklearn.utils import check_random_state
def test_quadtree_boundary_computation():
# Introduce a point into a quad tree with boundaries not easy to compute.
Xs = []
# check a random case
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import concurrent.futures
import os
import tempfile
import zipfile
from bs4 import BeautifulSoup
from furigana4epub import yomituki
from furigana4epub.version import version
def unzippen(filename, dst_path):
input_file = zipfile.ZipFile(filename, 'r')
input_file... |
from xml.sax.saxutils import unescape
from Cogs import DL
from Cogs import Nullify
def setup(bot):
# Not a cog
return
def find_last_between( source, start_sep, end_sep ):
result=[]
tmp=source.split(start_sep)
for par in tmp:
if end_sep in par:
result.append(par.split(end_sep)[0])
if len(resul... |
# This file is part of COFFEE
#
# COFFEE is Copyright (c) 2014, Imperial College London.
# Please see the AUTHORS file in the main source directory for
# a full list of copyright holders. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided ... |
from collections import namedtuple
from math import sqrt, log
import random
from pandits import belief
###############################################################################
Observation = namedtuple("Observation", ["arm_id", "reward"])
#######################################################################... |
import os
import asyncio
import sys
import logging
import logging.handlers
import traceback
import aiohttp
import config
import discord
from discord.ext import commands
script_name = os.path.basename(__file__).split('.')[0]
log_file_name = f"{script_name}.log"
# Limit of discord (non-nitro) is 8MB (not MiB)
max_fil... |
import numpy as np
import os
import pdb
import sys
import time
import pickle
from create_pair_set import create
from mediator import train_mediator, test_mediator
def get_hist(cmt):
cmt = [idx for c in cmt for idx in c]
hist = {}
for i in cmt:
if i == -1:
continue
if i in hist.k... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Copyright (c) 2017 The Bitcoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
This test checks simple acceptance of bigger blocks via p2... |
from nltk.corpus import wordnet
from nltk.corpus import semcor
from semcor_chunk import semcor_chunk
import argparse
#debug function to print out the matrix
#taken from https://stackoverflow.com/questions/13214809/pretty-print-2d-python-list
def print_matrix(matrix):
s = [[str(e) for e in row] for row in matrix]
le... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os.path
import shutil
import subprocess
import unittest
class TestProcessBase(object):
def setUp(self):
self.copy_test_project()
self.set_db()
def tearDown(self):
self.delet... |
"""
Program to generate random pseudowords based on an n-gram model learnt from
a dictionary file.
Examples
--------
Generate four random pseudowords:
% python pseudoword.py -n 4
spheatable
soregia
gaded
shiosoprilin
Generate fourty random pseudowords packed in 60 columns:
% python pseudowo... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 12 12:22:38 2020
@author: emc1977
"""
import math as math
def function ( x ):
import numpy as np
#Note that here I have negatived all terms, converting the minimiser into a maximiser.
#The functino value is returned as a negative, though in reality it ... |
# %%
import pandas as pd
from fdevices.hantek.configs import *
from fdevices.hantek.constants import *
from fdevices.hantek.helpers import *
# MDSplus PyDevice Description
from fdevices.hantek.scopes import HT6000SCOPE
## Client script to Hanteck Scope ##
"""
THis code below forms a basic test client to connect to a... |
from ninja.ninja_syntax import Writer
import StringIO
from sys import stdout
from os.path import join, splitext, relpath, split
import os
from clyde2.common import is_c, is_cpp
from clyde2.common import pprint_color, dict_contains
from clyde2.rtems import *
# Tools to walk over the tree collecting includes
import fun... |
#!/usr/bin/env python
#
# Copyright (c) 2011 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
"""A tiny web server.
This is intended to be used for testing.
"""
import BaseHTTPServer
import logging
import os
import... |
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 10 13:24:45 2021
@author: admin
"""
import numpy as np
import struct
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.functional as F
import os
# 测试集文件
test_images_file = 'MNIST/t10k-images.idx3-ubyte'
# 测试集标签文件
test_labels_file = 'MNIS... |
import os
import cv2
import sys
import math
import pyprind
import torch
import numpy as np
import torch.tensor as Tensor
# import torch.nn.functional as F
import torchvision.transforms as transforms
import dl_modules.dataset as ds
epsilon = 0.008
def enhance_images(folder: str, denoise_strength: int,
... |
import cv2
import json
import numpy as np
from rich import print
from PIL import ImageFile
import torch
from torchvision import transforms
from torch.utils.data import Dataset, DataLoader
from constants import NORM_MEAN, NORM_STD, DPAC_AGE_LABEL_TO_IDX, DPAC_GENDER_LABEL_TO_IDX, \
DPAC_EMOTION_LABEL_TO_IDX, IMG_H... |
""" Features selection
- select_features (func) : features selection following method
"""
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import pandas as pd
import numpy as np
class FeatSelector(object):
"""features selection following method
- pca : use pca to redu... |
from ply import lex, yacc
class PyLexer(object):
tokens = (
'DOL_LBRACE',
'PERC_LBRACE',
'COLON',
'PLAINTEXT',
'RBRACE',
'PIPE',
'QUESTION',
'AT',
)
def t_DOL_LBRACE(self, t):
r'\${'
self.nesting_depth += 1
return t
... |
from peewee import *
from .base import BaseModel
from . import climate
from . import hru as hru_db
from . import routing_unit
from . import aquifer
from . import channel
from . import reservoir
from . import exco
from . import dr
from . import simulation
from . import recall
class Con(BaseModel):
"""Inheritable base... |
#!/usr/bin/env python3
# %%
import logging
import functools
import collections
###############################################################################
#
# list of operations, each operation mutates cpu state in-place
#
def op_set(x, y, cpu, id_):
try:
cpu[id_][x] = int(y)
except ValueError:
... |
import os
import numpy as np
import torch
from torch.utils.data import DataLoader,TensorDataset
DATA_DIR="./dataset"
WALK=["35_01","35_02","35_03","35_04","35_05","35_06","35_07","35_08","35_09","35_10",
"35_11","35_12","35_13","35_14","35_15","35_16"]
RUN=["35_17","35_18","35_19","35_20","35_21","35_22",... |
#!/usr/bin/env python
import rclpy
import sys
import time
from std_msgs.msg import String
from om_aiv_util.socket_listener import *
from om_aiv_msg.msg import Status, Location
from rclpy.node import Node
class LdStatePublisher(Node):
def __init__(self, listener):
super().__init__('ld_states_publisher_node... |
# Copyright 2021 Foundries.io
#
# 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,... |
# -*- coding: utf-8 -*-
# upd dist
import sys
import sqlite3
import time
from typing import List, Dict
from collections import namedtuple, defaultdict
from common import upcase_regex, pos2pos, penn2pos, is_stop_ngram
Record = namedtuple('Record', ['word', 'lemma', 'sublemma', 'tag', 'abs', 'arf'])
def create_tabl... |
# -*- coding: utf-8 -*-
import furl
import urllib
import urlparse
import bson.objectid
import httplib as http
from datetime import datetime
import itsdangerous
from flask import request
from werkzeug.local import LocalProxy
from weakref import WeakKeyDictionary
from framework.flask import redirect
from framework.mo... |
#
# Copyright 1993-2017 NVIDIA Corporation. All rights reserved.
#
# NOTICE TO LICENSEE:
#
# This source code and/or documentation ("Licensed Deliverables") are
# subject to NVIDIA intellectual property rights under U.S. and
# international Copyright laws.
#
# These Licensed Deliverables contained herein is PROPRIETAR... |
# -*- coding: utf-8 -*-
import warnings
from contextlib import redirect_stderr, redirect_stdout, suppress
from copy import deepcopy
from logging import Logger, LogRecord
from os import devnull
from typing import Optional, Sequence, Sized, Tuple, TypeVar
import numpy as np
import pandas as pd
import sklearn.datasets
fr... |
#!/usr/bin/python
# coding=utf-8
#
# Font build utility
#
import sys
import time
import os
import fontforge
import psMat
from tempfile import mkstemp
from fontTools.ttLib import TTFont
from fontTools.ttx import makeOutputFileName
import argparse
def flattenNestedReferences(font, ref, new_transform=(1, 0, 0, 1, 0, 0)... |
# Copyright Pincer 2021-Present
# Full MIT License can be found in `LICENSE` at the project root.
from typing import Optional
class PincerError(Exception):
"""Base exception class for all Pincer errors"""
class InvalidPayload(PincerError):
"""Exception which gets thrown if an invalid payload has been receiv... |
###############################################################################
# Copyright (c) 2012 <NAME>. Licensed under the MIT License. #
# See LICENSE.txt for full details. #
###############################################################################
# I M ... |
import bsdiff4
import yaml
import os
import lzma
import hashlib
import threading
import concurrent.futures
import zipfile
import sys
from typing import Tuple, Optional
import Utils
from Rom import JAP10HASH, read_rom
def get_base_rom_path(file_name: str = "") -> str:
options = Utils.get_options()
if not file... |
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
from dataclasses import dataclass
from typing import Tuple
from manim import config
from manim import DEFAULT_MOBJECT_TO_EDGE_BUFFER
from manim import DEFAULT_MOBJECT_TO_MOBJECT_BUFFER
from manim import DOWN
from manim import LEFT
from manim import Mobject
from manim import np
from manim import ORIGIN
from manim impor... |
import argparse
import configparser
import torch
import os
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from model import ValueNetwork
from env import ENV
from train import run_one_episode
def visualize(model_config, env_config, weight_path, case, save):
state_dim = ... |
'''
Created on Jan 16, 2017
@author: bardya
'''
import pandas as pd
import numpy as np
import scipy.stats as stats
import argparse
import statsmodels.sandbox.stats.multicomp as sm
import seaborn as sns
import os
def parse_args(args):
parser = argparse.ArgumentParser(description='From a set of multi fasta files i... |
import abc
import copy
import re
import pandas as pd
class Feature(metaclass=abc.ABCMeta):
def __init__(self, name, path):
self.name = name
self.path = path
self._data = None
def data(self):
if self._data is None:
self.load_data()
return self._data
@... |
import json
import uuid
from enum import Enum
from allauth.socialaccount.models import SocialAccount
from django.contrib.auth.models import AbstractUser
from django.db import models
from rest_framework import serializers
class EmailSocialAccount(SocialAccount):
class Meta:
proxy = True
def __str__(s... |
def bio2span(labels):
spans = []
span = [None, -1, -1]
for i, tag in enumerate(labels):
if tag.startswith('B-'):
if span[2] != -1:
spans.append(span)
span = [tag.split('-')[1], i, i]
if i == len(labels) - 1: # 最后一个tag
spans.append(... |
# -*- coding: utf-8 -*-
# Authors: <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import numpy as np
from os import path as op
from .utils import _check_pytables
from .externals.six import string_types, text_type
##############################################################################
# WRITE
def write_hdf5(fn... |
#
# Copyright 2013 Red Hat, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
import numpy as np
import time
import ray
import ray.autoscaler.sdk
from ray._private.test_utils import Semaphore
import json
import os
from time import perf_counter
from tqdm import trange, tqdm
MAX_ARGS = 10000
MAX_RETURNS = 3000
MAX_RAY_GET_ARGS = 10000
MAX_QUEUED_TASKS = 1_000_000
MAX_RAY_GET_SIZE = 100 * 2**30
... |
from passlib.hash import ldap_salted_sha1
from passlib.hash import ldap_pbkdf2_sha256
from sshpubkeys import SSHKey
import datetime
class Usermgmt(object):
def attrs(self):
raise NotImplementedError
def get_dict(self):
return dict((key, value) for key, value in self.__dict__.items()
... |
# -*- coding: utf-8 -*-
#
# Copyright 2017 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compli... |
import logging
log = logging.getLogger(__name__)
import datetime
import re
import requests
import requests.exceptions
import botologist.plugin
def format_number(number):
if not isinstance(number, int):
number = float(number)
if number % 1 == 0.0:
number = int(number)
if isinstance(number, int):
f_number... |
# -*- coding: utf-8 -*-
from functools import reduce
from operator import mul
from string import ascii_lowercase
from io import open
import time
import math
import pkg_resources
import os
import struct
from .constants import *
__all__ = [
"clean_word_list",
"permutations",
"calculate_entropy",
"load... |
import ctypes
import numpy
import pygame
import time
from OpenGL.GL import *
from OpenGL.GL.shaders import *
from pygame.locals import *
width = 1024
height = 768
def getFileContents(filename):
return open(filename, 'r').read()
def init():
vertexShader = compileShader(getFileContents("data/shaders/triangl... |
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserve.
#
# 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 applic... |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file acc... |
# -*- coding: utf-8 -*-
from typing import List, Union
import pandas as pd
from sqlalchemy.orm import Session
from zvt.accounts.ccxt_account import CCXTAccount
from zvt.api.common import get_data, decode_security_id
from zvt.api.common import get_security_schema, get_kdata_schema
from zvt.domain import get_db_engine,... |
"""
The Yahoo finance component.
https://github.com/iprak/yahoofinance
"""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Final, Union
from homeassistant.const import CONF_SCAN_INTERVAL
from homeassistant.core import HomeAssistant
from homeassistant.helpers impor... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Helpers for setting `stat (2)` options on files, directories, etc, which
we are creating inside the image.
"""
impo... |
"""This module contains the general information for FirmwarePolicy ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class FirmwarePolicyConsts():
DEPLOYMENT_MODE_IMMEDIATE = "immediate"
DEPLOYMENT_MODE_MA... |
import sys, socket, pytest, py, pathlib
from xprocess import ProcessStarter
from pathlib import Path
import subprocess
import platform
import os
import hashlib
import time
import json
from urllib.request import urlopen
@pytest.fixture
def get_proj_root(cwd=os.getcwd()):
proj_root = cwd
if not Path(proj_root)... |
import logging
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from polymorphic_sqlalchemy import (create_polymorphic_base, Relation,
PolyField, NetRelationship, NetModel, BaseInitializer)
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm ... |
from typing import List
class Solution:
@staticmethod
def fib(n: int) -> int:
"""
Offer 10-I 斐波那契数列
:param n:
:return:
"""
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a % 1000000007
@staticmethod
def fib_2(n: int) -... |
# <NAME> (<EMAIL>)
#
# Based on dragonfly-plus-topo-gen-v2.py,
# implements relative global link arrangement
#
# Assumptions: num_router_per_group = router_radix, half spine half leaf,
# a -- number of routers in a group; h -- number of global link per spine;
# r -- router radix; g -- number of groups
# a == r, and ... |
# dependencies
from lifelines import KaplanMeierFitter
from lifelines.statistics import pairwise_logrank_test
from bokeh.io import output_file, output_notebook
from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, HoverTool,Band
from bokeh.layouts import row, column, gridplot
from bokeh.mod... |
import os
import glob
import pandas as pd
import datetime as dt
from typing import Any, Iterator, Sequence, Optional, Union
from ..logger import get_logger
from .. import files, sql
from . import connection
logger = get_logger(__name__)
def upload_csv(
csv_path: str,
schema: str,
table: str,
*,
... |
import os
import numpy as np
import argparse
import os.path as osp
import json
from tqdm import tqdm
from mmcv import mkdir_or_exist
def getFlying3dMetas(root, Type, data_type='clean'):
Metas = []
imgDir = 'flyingthings3d/frames_' + data_type + 'pass'
dispDir = 'flyingthings3d/disparity'
Parts = ['A'... |
import os
import os.path
import tempfile
import unittest
import xen.xend.XendOptions
xen.xend.XendOptions.XendOptions.config_default = '/dev/null'
import xen.xm.create
from xen.util import auxbin
class test_create(unittest.TestCase):
def assertEqualModuloNulls_(self, a, b):
for k, v in a.iteritems():
... |
# -*- coding: utf-8 -*-
import argparse
import json
import datetime
import re
import mmap
from mpi4py import MPI
TWITTER_FILE = None
GRID_FILE = None
SCORE_FILE = None
class Utils:
coordinates_pattern = re.compile(r'"coordinates":\[(.*?)]')
text_pattern = re.compile(r'"text":"(.*?)","loc')
punctuation_p... |
from collections import Mapping, Iterable
import copy as copy_
import numpy as np
import datetime as dt
from . import misc
def select_var(d, name, sel):
var_dims = list(d['.'][name]['.dims'])
d['.'][name]['.dims'] = var_dims
for key, value in sel.items():
if isinstance(value, Mapping):
if len(sel) > 1: raise V... |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## This is a sample controller
## - index is the default action of any application
## - user is required for authentication and authorization... |
"""
Support for Chuang Mi IR Remote Controller.
Thank rytilahti for his great work
"""
import logging
from datetime import timedelta
import asyncio
from random import randint
import voluptuous as vol
from socket import timeout
import homeassistant.loader as loader
from homeassistant.components.switch import (SwitchDe... |
import torch
from torch import nn
def conv_bn(in_c, out_c, kernel_size, stride=1, padding=0, groups=1):
return nn.Sequential(
nn.Conv2d(in_c, out_c, kernel_size, stride, padding, groups=groups),
nn.BatchNorm2d(out_c)
)
# Used to upscale the image (height and width) after global average pooling
def scale_dim(... |
from __future__ import annotations
import numpy as np
import scipy.signal
from functools import partial
from typing import Callable
try:
import simpleaudio as sa
except ModuleNotFoundError:
raise ModuleNotFoundError("Please install simpleaudio to use this module.\n"
"pip install ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.