text stringlengths 3.07k 12.6k |
|---|
from typing import Iterable, Tuple, List
from cobra.core import Model
import pandas as pd
import numpy as np
def get_shared_metabolites_counts(model1: Model, model2: Model) -> Tuple[int, int]:
"""This method return the number of unique metabolites in both models .
Args:
model1 (Model): Fi... |
import datetime as dt
from pathlib import Path
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from metpy.interpolate import interpolate_to_grid
import numpy as np
import pandas as pd
from basmati.hydrosheds import load_hydrobasins_geodataframe
from cosmic.util import load_cmap_data
from basmati.utils impo... |
"""Class :py:class:`QWTree` is a QTreeView->QWidget for tree model
===================================================================
Usage ::
# Run test: python lcls2/psana/psana/graphqt/QWTree.py
from psana.graphqt.QWTree import QWTree
w = QWTree()
Created on 2019-11-12 by <NAME>
"""
import logging... |
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from hello.forms import *
from hello.models import *
from django.contrib import messages
from django.contrib.aut... |
import pandas as pd
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import logging
import requests
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 200)
pd.set_option('display.max_rows', 10)
def search_data(sentence, language="en", show_header=False, dataset_sc... |
#!/usr/bin/env python
# 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
#
# Authors:
# - <NAME>, <EMAIL>, 2017
import os
import re
from string import... |
import warnings
import aiohttp
from discord import Color, Embed
from discord.ext import commands, flags
from bot.bot import TechStruckBot
from bot.utils import fuzzy, rtfm
class RTFM(commands.Cog):
"""Search through manuals of several python modules and python itself"""
targets = {
"python": "https... |
#!/usr/bin/env python3.5
"""Test init methods of encoders."""
import unittest
import copy
from typing import Dict, List, Any, Iterable
from neuralmonkey.encoders.recurrent import SentenceEncoder
from neuralmonkey.encoders.sentence_cnn_encoder import SentenceCNNEncoder
from neuralmonkey.model.sequence import Embedded... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017-2018 KuraLabs S.R.L
#
# 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... |
#!/usr/bin/env python3 -u
# 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.
import argparse
import pathlib
import sys #tmp debug
import time
import wandb
import torch
from tqdm import tqdm
f... |
from itertools import combinations
import numpy as np
import pandas as pd
from tqdm import tqdm
from multiprocessing import Pool
import pickle
from matplotlib import pyplot as plt
import pystan
from sklearn.decomposition import PCA
def stanmodel(modelname, overwrite):
picklefile = modelname + ".pkl"
try:
... |
"""
launch_autohorovod.py is the default launch layer for Determined.
It launches the entrypoint script under horovodrun when slots_per_trial>1, or as a regular
subprocess otherwise.
"""
import copy
import json
import logging
import os
import socket
import subprocess
import sys
import time
from typing import Dict
im... |
from typing import List, Any
from ppq.IR import Operation
from ppq.IR.quantize import QuantableOperation
from ppq.core import ppq_warning
import torch
class TorchBackendContext:
def __init__(self, executing_device: str) -> None:
self.executing_device = executing_device
def ASSERT_ALL_TENSORS_AT_CPU(op: Op... |
#!/usr/bin/env python
"""
Dummy server used for unit testing.
"""
from __future__ import print_function
import errno
import logging
import os
import random
import string
import sys
import threading
import socket
from tornado.platform.auto import set_close_exec
import tornado.wsgi
import tornado.httpserver
import tor... |
# pylint: skip-file
import pyomo.environ as pe
import pytest
from hypothesis import given, assume
from hypothesis.strategies import integers, lists
from pyomo.core.kernel.component_map import ComponentMap
from suspect.fbbt.propagation.rules import *
from suspect.fbbt.propagation.visitor import BoundsPropagationVisitor... |
# encoding=UTF-8
# Copyright © 2009-2019 <NAME> <<EMAIL>>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the “Software”), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modif... |
#!/usr/bin/env python
import abc
import logging
import os
from glob import glob
from bs4 import BeautifulSoup
LOGGER = logging.getLogger(__name__)
class TextExtractor:
"""
Extract text from a HTML file.
"""
def __init__(self, filepath):
with open(filepath) as f:
html = f.read(... |
#!/usr/bin/env python3
import os, sys, time
sys.path.append("train")
from dewarp import warp
from networks.models import fba_decoder, MattingModule, ResnetDilated
from networks.resnet_GN_WS import l_resnet50
from PIL import Image
import urllib.request
import numpy as np
import torch
import torch.nn.functional as F
IMA... |
import bpy
from . import node_utils
from . import shader_function
def GetDefaultValue(socket):
if socket.type == 'SHADER':
shader = node_utils.PBRShader()
shader.Mute()
return shader
if type(socket.default_value) == bpy.types.bpy_prop_array:
return list(socket.default_value... |
#!/usr/bin/env python3
# standard library
import time
import os
import json
from datetime import datetime
# display drivers
import subprocess
import digitalio
import board
from PIL import Image, ImageDraw, ImageFont
import adafruit_rgb_display.st7735 as st7735
# my utility libraries
from .trains_util import get_tr... |
from collections import namedtuple
from copy import copy
from itertools import count
import torch
import torch.nn as nn
import torch.nn.functional as F
from .utils.copy_and_replace import do_not_copy, copy_and_replace
from .utils.ingraph_update import IngraphGradientDescent
class BaseEditable(nn.Module):
EditRes... |
from pylabnet.gui.pyqt.external_gui import Popup, InternalPopup
import sys
from PyQt5 import (QtCore, QtGui, QtWidgets)
from PyQt5.QtWidgets import (
QApplication, QDialog, QMainWindow, QMessageBox)
from scipy.optimize import curve_fit # is not automatically installed?
import numpy as np
def exp_decay(t, a, b, T1... |
"""Flashpoint Feed Test File."""
import json
import io
import pytest
from unittest.mock import patch
from test_data import input_data
from FlashpointFeed import Client, HTTP_ERRORS, MESSAGES, MAX_FETCH
from CommonServerPython import DemistoException
from requests.exceptions import HTTPError
BASE_URL = "https://fp.too... |
#!/usr/bin/env python
# Copyright (C) 2010 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 ... |
# encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
#-*- coding: utf-8 -*-
from __future__ import absolute_import, with_statement
__all__ = ['ProjectHandler',
'TaskStatusHandler',
'MilestoneHandler',
'TaskHandler',
... |
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: <EMAIL>
# Maintained By: <EMAIL>
from sqlalchemy import and_
from ggrc import db
from ggrc.converters import errors
from ggrc.converters.handlers... |
import datetime
import json
import pickle
import time
import redis
import requests
from crawler import leave_crawler
from utils import config, error_code
from utils.session import get_session
red_string = redis.StrictRedis.from_url(
url=config.REDIS_URL, db=4, charset="utf-8", decode_responses=True)
red_bin = re... |
import bpy, bgl, blf
import numpy as np
from bpy_extras.view3d_utils import location_3d_to_region_2d
from bgl import glEnable, glDisable, glColor3f, glColor4f, glVertex3f, glPointSize, glLineWidth, glBegin, glEnd, glLineStipple, GL_POINTS, GL_LINE_STRIP, GL_LINES, GL_LINE_STIPPLE
from mathutils import Vector, Matrix
d... |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import torch
import sys
def uniform_multinomial(batchsize, num_action, use_cuda=True):
''' Samp... |
#!/usr/bin/env python
#####################
# Simple MD program #
#####################
import time
import numpy as np
def create_molecule(n=3, element='He'):
"""
Create a molecule as atoms in a cube.
Parameters
----------
n: integer
number of atoms in each dimension of the cube
elem... |
import logging
import re
from typing import *
from pycparser import c_parser, c_ast, parse_file
from tapaconverter.common import get_func_range
def get_fake_type(template_type: str) -> str:
return template_type.replace('<', '_ANGLE_BRACKET_BEG_') \
.replace('>', '_ANGLE_BRACKET_END_') \
... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Run the first page of one benchmark for every module.
Only benchmarks that have a composable measurement are included.
Ideally this test would be compreh... |
from .i2c_device import *
import numpy as np
# HTS221 I2C Slave Address
_HTS221_ADDRESS = 0x5f
_HTS221_REG_ID = 0x0f
_HTS221_ID = 0xbc
# Register map
_HTS221_WHO_AM_I = 0x0f
_HTS221_AV_CONF = 0x10
_HTS221_CTRL1 = 0x20
_HTS221_CTRL2 = 0x21
_HTS221... |
# coding=utf-8
# Copyright 2021 TF.Text 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 or ag... |
#!/usr/bin/env python3
import functools
import json
import os
import re
import shutil
import sys
config_path = os.path.expanduser('~') + '/.xclmrc'
try:
with open(config_path, 'r') as f:
config = json.loads(f.read())
except FileNotFoundError:
config = json.loads("{}")
config['__INSTALL_PATH'] = in... |
import torch
import torch.nn as nn
class ActionClassification(nn.Module):
def __init__(self, feature_size, num_classes, opts):
super(ActionClassification, self).__init__()
self.opts = opts
self.attention_flow_stream = StreamModule(feature_size)
self.attentition_rgb_stream = StreamModule(feature_size... |
import threading
import collections
from multiprocessing.pool import RUN, job_counter, TimeoutError, mapstar
from multiprocessing.queues import Empty, Full
from torch.multiprocessing import Queue
from torch.multiprocessing.pool import Pool
#
# Class whose instances are returned by `Pool.imap()`
#
class sIMapIterato... |
"""Removes old images from ECR."""
import argparse
import datetime
import json
import logging
import sys
import boto3
import pytz
def init():
"""Initialize system."""
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
... |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import numpy as np
import pytest
import torch
# [1,4c,h,w]
input_arr = [[[[1., 2., 3., 4.], [5., 6., 7., 8.], [9., 10., 11., 12.]],
[[6, 7, 5, 8], [2, 1, 3, 4], [12, 9, 11, 10]],
[[-2, -3, 2, 0], [-4, -5, 1, -1], [-1, -1, -1, -1]]... |
import sys
from typing import Callable, List, Dict, Tuple, Union
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.tensor import Tensor
from utility.helper import show
SAMPLE_RATE = 16000
class Hook:
def __init__(self, module_path, transform, unique_identifier=Non... |
"""
Implementation of two dataloader, one for the training and the other one for inference.
Both are based on 3D patch samplers allowing a less greedy memory consumption.
"""
import torch
import torch.utils.data
import torchio as tio
from segmentation_rt.util.util import get_subjects
class DatasetSingle:
"""
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 <NAME>
#
# 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 b... |
# -*- coding: utf-8 -*-
#
# Copyright 2018-2020 Data61, CSIRO
#
# 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... |
import numbers
import math
import numpy as np
import os
from sklearn.feature_extraction.image import extract_patches
from contextlib import contextmanager
class AverageMeter:
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val... |
# SPDX-FileCopyrightText: Copyright 2021, <NAME> <<EMAIL>>
# SPDX-License-Identifier: BSD-3-Clause
# SPDX-FileType: SOURCE
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the license found in the LICENSE.txt file in the root directory
# of this source tree.
# =======
#... |
#! /usr/bin/env python
import numpy as np
import os
import h5py
import sys
import scipy.signal
import argparse
def minor_format(x, i=None):
return x
def main():
parser = argparse.ArgumentParser(description='Generating CSR Spectrogramms from Inovesa result files')
parser.add_argument('directory', type=str, he... |
from fsUtils import setDir, isDir, setFile, isFile
from webUtils import getURL, getHTML
from time import sleep
from timeUtils import getDateTime, isDate
from ioUtils import getFile, saveFile
class top40:
def __init__(self, debug=False):
self.chartsDir = "/Volumes/Piggy/Charts"
if not isDir(self.ch... |
# Copyright 2020 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, softw... |
import argparse
import os
import os.path as osp
import warnings
import mmcv
import numpy as np
import onnxruntime as ort
import torch
from mmcv.parallel import MMDataParallel
from mmcv.runner import get_dist_info
from mmcv.utils import DictAction
from mmseg.apis import single_gpu_test
from mmseg.datasets import build... |
"""
Unified implementations of tokenizers.
Created by <NAME>, Dec. of 2018
"""
class Tokenizer(object):
"""
A abstract class that needs the implementation of the following functions:
to_ids() : function that converts list of tokens/ a string to list of tokens
to_tokens() : function that converts list o... |
# Copyright 2020 Soil, Inc.
from oslo_log import log as logging
from soil.exception import SoilException
from soil.utils.request import get_request, post_request, delete_request
from soil.i18n import _, _LE
LOG = logging.getLogger(__name__)
INSTANCES_URL = '/servers/detail'
INSTANCE_URL = '/servers/{instance_id}'
... |
#!/usr/bin/env python
"""
The WiPy firmware update script. Transmits the specified firmware file
over FTP, and then resets the WiPy and optionally verifies that software
was correctly updated.
Usage:
./update-wipy.py --file "path_to_mcuimg.bin" --verify
Or:
python update-wipy.py --file "path_to_mcuimg.bin"... |
"""
Provides the Merkle-proof object.
"""
import os
import json
from time import time, ctime
from pymerkle.hashing import HashEngine
from pymerkle.utils import log10, generate_uuid
PROOF_TEMPLATE = """
----------------------------------- PROOF ------------------------------------
uuid : {uuid}
... |
"""
This defines a Lakehouse with two options for storage and two options for data-processing. Both
storage options work with both processing options.
The storage options are local filesystem and S3. In both cases, data is stored in Parquet files
using the "Hadoop-style" layout in which each table corresponds to a d... |
# -*- coding: utf-8 -*-
import pykd
import color
import sys
import traceback
ARCH = None
MAX_DEREF = 20
cpu_mode = pykd.getCPUMode()
if cpu_mode == pykd.CPUType.I386:
ARCH = 'x86'
elif cpu_mode == pykd.CPUType.AMD64:
ARCH = 'x64'
else:
pykd.dprintln("CPU mode: {} not supported.".format(cpu_mode))
s... |
def printHSP(hsp, indent=''):
for attr in ['bits', 'expect', 'frame', 'query_end', 'query_start',
'sbjct', 'query', 'sbjct_end', 'sbjct_start']:
print('%s%s: %s' % (indent, attr, hsp[attr]))
def normalizeHSP(hsp, readLen, blastApplication):
"""
Examine an HSP and return informatio... |
# Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agre... |
"""Test for pydent.relationships.py."""
from pydent import ModelBase
from pydent.relationships import HasMany
from pydent.relationships import HasManyGeneric
from pydent.relationships import HasManyThrough
from pydent.relationships import HasOne
from pydent.relationships import Many
from pydent.relationships import One... |
import json
from importlib.util import module_from_spec, spec_from_file_location
from inspect import stack
from os.path import basename, abspath, dirname
from pathlib import Path
from urllib.parse import urlparse
import yaml
from falcon import routing
from falcon.routing.compiled import CompiledRouter
class OpenApiR... |
'''
Physical quantities and functions
'''
import yt, numpy as np
from yt.utilities.cosmology import Cosmology
from yt.units import speed_of_light_cgs as speed_of_light
## units of physical quantities
units = {
'DM' :r"pc cm$^{-3}$",
'RM' :r"rad m$^{-2}$",
'SM' :r"kpc m$^{-20/3}$",
# ... |
"""
Auteur main module.
usage: auteur.py [-h] [-d] {add,build} ...
Create an entire blog website from simple Markdown files.
positional arguments:
{add,build}
add Add an article to the blog.
build Build or rebuild the entire blog website.
optional arguments:
-h, --help show this help messa... |
from .DS2dataset import Dataconnector
from .util import Util
import requests as req
import json
class Opsproject(object):
utilClass = Util()
def __init__(self, info, user):
if not isinstance(info, dict):
raise Exception(str(info))
if info.get('error'):
raise Exception(i... |
import os
import re
import logging
from enum import Enum
from typing import Iterable
from urllib.parse import urlsplit
from datetime import datetime, timezone
try:
import ujson as json
except ImportError:
import json
import requests
from .config import CONFIG_PER_NETLOC
logger = logging.getLogger(__name__)
... |
import logging
import mysql.connector
import os
import re
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, Job, MessageHandler, Filters, CallbackQueryHandler, JobQueue
import parser
class UserChat:
def __init__(self, chat_id, bot):
self.id... |
# -*- coding: utf-8 -*-
from itertools import product
# Use Python 2 map here for now
from funcy.py2 import map, cat
from django.db.models.query import QuerySet
from django.db.models.sql import OR
from django.db.models.sql.query import Query, ExtraWhere
from django.db.models.sql.where import NothingNode
# This thing e... |
"""Tests for server.py."""
import pytest
import os
from client import client
from server import (
parse_request,
resolve_uri,
folder_contents_html,
get_path,
response_ok,
response_error
)
walk_dir = os.getcwd()
if walk_dir.split()[-1] != 'src': # code to make tox work
walk_dir += '/src'
wa... |
import numpy as np
from .tree import Tree
def parse_xgb_ensemble(model):
"""
Parse XGBoost model based on its string representation.
"""
# validation
model_params = model.get_params()
assert model_params['reg_alpha'] == 0
assert model_params['tree_method'] == 'hist'
string_data = _g... |
import time
import argparse
import torchvision
import torch
import torch.nn as nn
import torch.nn.functional as F
from util import AverageMeter
from encoder import SmallAlexNet
def parse_option():
parser = argparse.ArgumentParser('STL-10 Representation Learning with Alignment and Uniformity Losses')
parser... |
from django.contrib import admin
from django.utils.safestring import mark_safe
from django.utils.html import format_html
from django.shortcuts import get_object_or_404
from .models import (
Item,
ItemImages,
OrderItem,
Order,
Category,
Payment,
Coupon,
Address,
Refund,
UserProfil... |
import numpy as np
from scipy.optimize import linear_sum_assignment
import tensorflow as tf
import tensorflow.contrib.slim as slim
SMALL_EPSILON = 1e-10
def compute_assignments(locations, confidences, gt_bboxes, num_gt_bboxes, batch_size, alpha):
"""
locations: [batch_size * num_predictions, 4]
confidences: [ba... |
import smtplib , os , sys , time
Count = 0
_Count = 0
def Banner():
Ban = "\n\t\t\t[>] SimpleGMailBruter [<]\n"; print(Ban)
def StartBruteAccount(Passlist,account,SMTPServer,Count,_Count,Time):
with open('{0}'.format(Passlist),'r') as PasswordsFile:
for Password in PasswordsFile:
Password = Passwor... |
#!/usr/bin/env python
###############################################################################
# Copyright Kitware 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
#
# ht... |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmcv.ops import nms
from torch import Tensor
from torch.onnx import symbolic_helper as sym_help
from mmdeploy.core import SYMBOLIC_REWRITER
class ONNXNMSop(torch.autograd.Function):
"""Create onnx::NonMaxSuppression op.
NMS in mmcv only suppo... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import warnings
from unittest import SkipTest
import numpy as np
import pytest
import nevergrad.common.typing as tp
impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Archivo mapa.py que sirve para dibujar el mapa
de méxico
"""
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation
from pylab import *
import numpy as np
import time
import generacion
#... |
from string import capwords
class Restaurant():
# 3 arguments, self, r_n, and c_t
def __init__(self, restaurant_name, cuisine_type):
""" Create a restaurant with a name and food type."""
# Each instance types restaurant name = the argument we give to restaurant
# name. Same for cuisine_... |
import logging
import time
from celery.exceptions import SoftTimeLimitExceeded
from redash import models, redis_connection, settings, statsd_client
from redash.models.parameterized_query import (InvalidParameterError,
QueryDetachedFromDataSourceError)
from redash.tasks.fa... |
from re import A
import sys
import glob
from turtle import fd
import pandas as pd
"""A script to take monthly data in separate train/validate/test folders,
and produce a single file for each train/validate/test.
We also caculate the "delta features" i.e. V20 - V15 for the time constant features
All feat... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from opt_einsum import contract as einsum
import copy
import dgl
import torch_geometric
from torch_geometric.data import Data
# hk VarianceScaling(1.0, "fan_in", "truncated_normal")
#def init_lecun_normal(module, scale=1.0):
# de... |
"""
Like image_sample.py, but use a noisy image classifier to guide the sampling
process towards more realistic images.
"""
import argparse
import os
from PIL import Image
import glob
import numpy as np
import torch as th
import torch.distributed as dist
import torch.nn.functional as F
from transformers import GPT2T... |
#! /usr/bin/env python3
# _*_coding:utf-8 -*_
import json, os, time, logging, shutil
logger = logging.getLogger("Server")
def singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
re... |
# 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.
import distutils.spawn
try:
import importlib.resources as pkg_resources
except ImportError: # For <=3.6
import importlib_resources ... |
import requests
import zlib
import json
import base64
import time
import copy
import random
from cqhttp import CQHttp
from apscheduler.schedulers.blocking import BlockingScheduler
def addSalt(ori: bytearray):
# 从网页JS当中提取到的混淆盐值,每隔一位做一次异或运算
Salt = '%#54$^%&SDF^A*52#@7'
i = 0
for ch in ori:
if i ... |
"""
IxLoad package testing.
"""
import inspect
import logging
import time
from pathlib import Path
from typing import Optional
from ixload.ixl_app import IxlApp
from ixload.ixl_statistics_view import IxlStatView
logger = logging.getLogger('ixload')
def test_hello_world(ixload: IxlApp) -> None:
""" Fufu test ju... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from . import utilities, tables
class GetAvai... |
"""DICOM dataset utility functions."""
import logging
import os
import zlib
from pydicom.filebase import DicomBytesIO
from pydicom.filereader import read_dataset, read_preamble
from pydicom.filewriter import write_dataset, write_data_element
from pynetdicom.utils import pretty_bytes
LOGGER = logging.getLogger('pyn... |
import os
import numpy as np
import cv2
import matplotlib.pyplot as plt
def APCE(response_map):
Fmax=np.max(response_map)
Fmin=np.min(response_map)
apce=(Fmax-Fmin)**2/(np.mean((response_map-Fmin)**2))
return apce
def PSR(response):
response_map=response.copy()
max_loc=np.unravel_... |
__all__ = ['Project', 'Experiment', 'Result', 'Stat', 'Variation', 'Goal', 'Audience']
import json
import urllib
class ResourceGenerator(object):
def __init__(self, client=None, resource=None):
if client is None:
raise ValueError('Must specify client.')
if resource is None:
raise ValueError('Mu... |
# Copyright 2020 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import requests
try:
import ujson as json
except ImportError:
import json
import pandas as pd
from datetime import datetime
from socketIO_client_nexus import SocketIO, BaseNamespace
from sseclient import SSEClient
from six import string_typ... |
# From https://github.com/tartley/colorama
# Copyright <NAME> 2013
# 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... |
#!/usr/bin/env python3
import argparse
import matplotlib.pyplot as plt
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from torchdiffeq import... |
import hashlib
import re
from datetime import datetime
from typing import Iterator
import requests
from ay_advance import chinese_to_int, AyStr
from ay_advance.GocqConnection import CqCode
import random
from sqlalchemy import Column, Integer, String, DateTime, or_, LargeBinary
from sqlalchemy.ext.declarative import d... |
"""Utility functions."""
import datetime as dt
import functools
import inspect
import urllib
from . import movable_feasts
from .movable_feasts import AshWednesday
from .movable_feasts import MovableFeast
from .movable_feasts import PalmSunday
from .movable_feasts import PassionSunday
ORDINALS = {
1: 'First',
... |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
This file contains components with some default boilerplate logic user may need
in training / testing. They will not work for everyone, but many users may find them useful.
The behavior of functions/classes in this file ... |
"""
Copyright (c) Microsoft Corporation.
Licensed under the MIT license.
Uniter for VQA model
"""
import json
from os.path import abspath, dirname
from collections import defaultdict
import torch
from torch import nn
from torch.nn import functional as F
from torch.distributions import Beta
from apex.normalization.fus... |
from functools import lru_cache
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import numpy as np
import plotly.graph_objs as go
from components.synergy_info.syn_info import infoblock_matrix
from app import app
from db im... |
import logging
import numpy as np
import torch
from ml.losses import round_loss
from .data_utility import (
expand_dic,
get_all_vids,
get_batch_r,
get_mask,
one_hot_vids,
rescale_rating,
reverse_idxs,
sort_by_first,
)
"""
To prepare data from training and reshape it after training
M... |
from neuwon.database import Database, Function, Method, TimeSeries
import math
import random
import pytest
def test_basic_function():
@Function
def foo(x):
""" Foo's help message! """
return x + 3
help(foo)
assert foo(3) == 6
qq = Function(lambda: 42)
assert qq() == 42
def ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Implementing Friedlander 1987
=============================
Friedlander 1987 [1] formulates the localisation problem as the source being the
intersection point of multiple major axis lines. Each set of three mics
lies on... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.