text stringlengths 3.07k 12.6k |
|---|
import pandas as pd
import numpy as np
import statsmodels.formula.api as smf
# The standard deviation of contestant skill. This is a normalization.
STD_AGENT_SKILL = 1
def create_contestants(parameters):
"""Returns a series with contestant ids and skill"""
return pd.Series(np.random.normal(0, STD_AGENT_SKILL, ... |
import re
from django.shortcuts import render, get_object_or_404, redirect
from django.db.models import Count, Q
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.contrib import messages
from django.http import HttpResponse
from django.views.decorators.http import require_GET
from col... |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import wandb
import os
import torch
import constants
# Set default settings on import
plt.rcParams.update({'font.size': 13})
plt.rc("axes", labelsize=18)
plt.rc("axes", titlesize=21)
plt.rc("legend", fontsize=18)
def save_plot... |
import os
import sys
import argparse
import numpy as np
import pandas as pd
import datetime
import bisect
import re
from clean import simple_clean
from clean import complex_clean
from sklearn.feature_extraction.text import CountVectorizer
#
# create a training set from speeches, statements, prior minutes
#
# convert ... |
import random
def create_ships(ships, shipPos, size):
while True:
coords = []
# Choose random coordinates and orientation, restrict placement space
isVert = random.choice([True, False])
if isVert:
x, y = random.randint(0, 9), random.randint(0, 10 - size)
else:
... |
import torch.nn as nn
from mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,
kaiming_init)
from torch.nn.modules.batchnorm import _BatchNorm
from collections import OrderedDict
import torch
from ..builder import BACKBONES
import torch.utils.model_zoo as model_zoo
def _make_divi... |
# This file is part of the Jsonify.
#
# Copyright (C) 2021 <NAME> <<EMAIL>>
#
# For the full copyright and license information, please view
# the LICENSE file that was distributed with this source code.
import codecs
from os import path
from setuptools import setup, find_packages
import re
def locate_package_direct... |
# -*- coding: utf-8 -*-
import telegram
from database.gaedb import (register_new_user, get_wallet_info, get_transferees, get_transferrer_wallet_addr,
get_user_pvt_chat_id, retrieve_transactions, generate_transaction)
from telegram.ext import ConversationHandler
SELECT_TRANSFEREE, SET_TRANSFER_AMT = range(2)
def st... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 28 22:21:25 2019
@author: raz
"""
import pandas as pd
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn import preprocessing
import matplotlib.pylab as plt
## For OMP error
import os
os.environ['KMP_DUPLICATE_LIB_... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import re
import sys
import os
import argparse
import numpy as np
import subprocess
# Grep deliminator for new runs in the same log (only happens on certain server preempt)
grep_new_run = r"""grep "STARTING NEW MASTER COORDINATOR RUN" {fn}"""
#... |
from collections import OrderedDict
from functools import singledispatch, reduce
import numpy as np
import operator as op
from gym.spaces import Box
from gym.spaces import Discrete
from gym.spaces import MultiDiscrete
from gym.spaces import MultiBinary
from gym.spaces import Tuple
from gym.spaces import Dict
@single... |
import os
import numpy as np
from netCDF4 import Dataset, Group, Variable
from iasi.util import dimensions_of
class QuadrantException(Exception):
pass
class Quadrant:
"""Transformation of matrices for decomposition and compositions
Gas var quadrant shape
WV avk 4 (1, 2, 2, 29, 29... |
import re
from django.contrib.auth.models import User
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from sideloader.db import models
class BaseModelForm(forms.ModelForm):
helper = FormHelper()
helper.form_class = 'form-horizontal'
helper.label... |
import itertools, functools, copy, re
# x%7 == 0 dfa
DFA = {str(x): { "0": str((x*2)%7), "1": str((x*2+1)%7) } for x in range(7) }
DFA_START = "0"
DFA_ACCEPT = {"0"}
# Make sure there's a unique start and end state with no transitions in or out
DFA["start"] = copy.copy(DFA[DFA_START])
DFA["end"] = {}
for state in DF... |
import os
import random
import numpy as np
import pandas as pd
import networkx as nx
from sklearn.decomposition import PCA
from .. import ZairaBase
from ..descriptors.baseline import Fingerprinter
from ..tools.fpsim2.searcher import SimilaritySearcher, RandomSearcher
from ..tools.autogluon.multilabel import Multilabel... |
# pylint: disable=no-member, invalid-name, line-too-long
"""
Gradient flow for any model using pytorch backprop
"""
import copy
import math
import torch
from ._flow import flow
from ._gradient import gradient
class _ContinuousMomentum(torch.optim.Optimizer):
r"""Implements a continuous version of momentum.
... |
from dcase_models.util.files import load_json
from dcase_models.data.features import MelSpectrogram, Spectrogram
from dcase_models.data.dataset_base import Dataset
from dcase_models.data.data_generator import DataGenerator
from dcase_models.data.scaler import Scaler
import os
import numpy as np
import pytest
import gl... |
"""
This is a reworked version of code started by <NAME> (cchriste/dataflow)
and <NAME> (gkthiruvathukal/simple-map-scala) that benchmarks
Apache Spark performance.
"""
#from __future__ import print_function
import argparse
import glob
import json
import numpy as np
import os
import re
import sys
import time
import ... |
import torch
import pdb
from torch.utils.data import DataLoader
import pruning
@torch.no_grad()
def test(model, predictor, x, edge_index, split_edge, evaluator, batch_size, args):
model.eval()
predictor.eval()
h = model(x, edge_index)
pos_train_edge = split_edge['train']['edge'].to(h.device)
pos_... |
from dictionary import *
import numpy as np
from sympy import * # used for differentiation
import math # used for natural log
from decimal import Decimal # Used for results reporting calculations
from brian2 import *
import sys
testingEpochs = 100
trainingEpochs = 300
spikeMiliseconds = 100
dictionaryLongitude = 26
t... |
from __future__ import division
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import cv2
import matplotlib.pyplot as plt
from util import count_parameters as count
from util import convert2cpu as cpu
from PIL import Image, ImageD... |
import argparse
import os
from datetime import datetime
from numpy import mod
from tqdm.std import tqdm
from mcsce.libs.libstructure import Structure
# Argument parser
parser = argparse.ArgumentParser()
parser.add_argument("input_structure", help="A single PDB file for the backbone conformation, or a folder in whic... |
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr
import numpy as np
import pycountry_convert
from infographics import Figure, Infographic
from covid19 import covid_data
MW = 7
DAYS_PLOT = 90
POPULATION = 21_800_000
PADDING = 0.12
Q_PEOPLE = 100_000
random.seed(1)
def _p... |
import json
import pathlib
import logging
from align.cell_fabric.canvas import Canvas
from align.cell_fabric import Wire, Via, Region
from align.cell_fabric import CenterLineGrid, EnclosureGrid, SingleGrid
from align.schema.pdk import LayerMetal, LayerVia, PDK
from align.cell_fabric import Pdk
logger = logging.getLogg... |
import numpy as np
import scipy as sp
import sigpy
import sigpy.mri
import math
def poisson_trajectory(kspace_shape, accel_factor, *args):
"""
This function returns the poisson mask for a given kspace size and accel_factor.
Inputs:
:param kspace_shape: the size of the kspace to use in determining the ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 <NAME> <<EMAIL>>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline in source files... |
import subprocess
import sys
import os
import time
import psutil
from multiprocessing import Process, Queue, current_process, Lock
class MemoryUsage:
def __init__(self, process_name, timestamp, memory_usage):
self.process_name = process_name
self.timestamp = timestamp
self.memory_usage = ... |
from tequila.circuit.gates import X, Y, Z, Rx, Ry, Rz, H, CNOT, QCircuit, RotationGate, Phase
from tequila.wavefunction.qubit_wavefunction import QubitWaveFunction
from tequila.circuit._gates_impl import RotationGateImpl
from tequila.objective.objective import Variable
from tequila.simulators.simulator_api import simul... |
from functools import wraps
from concurrent.futures import ThreadPoolExecutor
from . import util
from .mp import cpu_count
def init_executor(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if not hasattr(self, "_executor"):
self._executor = self._get_executor()
return func... |
import autograd.numpy as np
from autograd import jacobian
from trajopt.envs.quanser.common import VelocityFilter
from trajopt.envs.quanser.qube.base import QubeBase, QubeDynamics
class Qube(QubeBase):
def __init__(self, fs, fs_ctrl):
super(Qube, self).__init__(fs, fs_ctrl)
self.dyn = QubeDynamics... |
import torch
import cv2
import numpy as np
import argparse
from utils.safedist_utils import draw_RiskLine, show_Detection, get_Centroids_Lis
mouse_pts = []
image = None
np.random.seed(42)
def get_Points(event, x, y, flags, params):
"""Get the points from opencv's setMouseCallBack function."""
if event == cv2... |
import sys
import re
import textwrap
import commonmark
import pygments
import pygments.lexers
import pygments.styles
import pygments.formatters
from .styler import Styler, Style
from .escapeseq import EscapeSequence, _true_color
import logging
logger = logging.getLogger('consolemd')
endl = '\n'
def debug_tag(obj,... |
#!/usr/bin/env python2
# Copyright (C) <2019> Intel Corporation
# SPDX-License-Identifier: MIT
# Author: <NAME>
from segway_transforms import TFParser, tf_values_to_matrix, tf_matrix_to_values
import tf
import numpy as np
def get_tfs():
tf_tree = [
('tree', 'base_link', 'laser', [0.35,0.0,1.28,-0.009737,... |
import kenlm
import argparse
import pandas as pd
import numpy as np
import torch
import os
import pickle as pkl
import datasets
from pathlib import Path
from sklearn.model_selection import ParameterGrid
from datasets import load_metric, load_dataset
from datasets import Dataset, DatasetDict, Metric, IterableDatasetDi... |
import json
import os
import requests
import pytest
from tests.helpers.common import (
assert_jsonrpc11_result,
assert_jsonrpc11_error
)
from tests.helpers.integration_setup import (
do_rpc,
load_data_file, assert_equal_results
)
def test_search_objects_public(service):
"""A search against public ... |
#!/usr/bin/python
import requests
import sys
import time
import hashlib
import os
from requests.cookies import create_cookie
import json
def timestamp():
return str(int(time.time() * 1000))
class YoudaoNoteSession(requests.Session):
user_api_base = 'https://note.youdao.com/yws/api/personal'
doc_downloa... |
"""
Prepare graphs from PDB cif files using DSSR annotation software.
Ligand and Ion annotations are manually annotated by neighbor search on PDB structures.
Write graphs in JSON format to output directory
Run with -u to update the PDB atleast once a week
EXTERNAL PACKAGES:
rcsbsearch : `pip install rcsbsearch`
"""... |
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 13:47:01 2019
@author: abibeka
Read data from travel time files
"""
#0.0 Housekeeping. Clear variable space
from IPython import get_ipython #run magic commands
ipython = get_ipython()
ipython.magic("reset -f")
ipython = get_ipython()
import os
import pandas as pd
... |
from __future__ import print_function, division
import os
import torch
import pandas as pd
#from skimage import io, transform
import cv2
import numpy as np
import random
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import pdb
import math
import os
import imgaug.augme... |
from uuid import uuid4
from behave import given, when, then
# Create Organization Service
@given("I created an Organization Service")
@when("I create an Organization Service")
def create_service(context):
context.sent_kwargs = kwargs = {
"name": str(uuid4())
}
context.organization_service_manage... |
# write code that trains human to compute the doomsday algorithm
# georgian calendar
import datetime
from datetime import date
from typing import Iterable, Tuple, Generator
from .iox import stdio, p_factory, tcprint
from .const import (
leap_doomdays,
doomdays,
weekdays,
styleFor,
WeekdayDisplayT,
... |
import base64
import io
import json
import os
import sys
import cv2 as cv
import jsonpickle
import numpy as np
import requests
from flask import Flask, Response, jsonify, request
from PIL import Image, ImageFont, ImageDraw
def analyze_img(rdata):
#receive base64 encoded string and convert it to binary
decode... |
"""Code, which deals with bencoded data."""
from dataclasses import dataclass
from typing import Union
COLON = ord(":")
END_MARKER = ord("e")
START_DICT = ord("d")
START_INTEGER = ord("i")
START_LIST = ord("l")
@dataclass
class BencodedString:
"""An internal container for bencoded strings"""
def __init__(se... |
""" Standard SQL Linting Rules """
from .crawler import BaseCrawler
from ..parser_2.segments_base import RawSegment
def L001_eval(segment, raw_stack, **kwargs):
""" We only care about the segment the preceeding segments """
# We only trigger on newlines
if segment.raw == '\n' and raw_stack[-1].name == 'w... |
import unittest
import os
import sys
import tempfile
import shutil
import json
import random
import string
import logging
import subprocess
from unittest.mock import patch, MagicMock
from cryptography.fernet import Fernet
import boto3
from botocore.exceptions import ClientError
import util
import archive
class TestU... |
"""Tag and node definition for the built-in "tablerow" tag."""
import math
import sys
from itertools import islice
from typing import Any
from typing import Dict
from typing import List
from typing import Mapping
from typing import Optional
from typing import TextIO
from typing import Iterator
from liquid.token imp... |
import requests
#import queue
#from multiprocessing.managers import BaseManager
import multiprocessing.managers
import os
import shutil
import sys
#from socket import *
import glob
import subprocess
import time
def write(url,fname,t,ra,c=0):
s = requests.session()
#if t >= 10 and t1 < 10:
# t1 = '0' + str(t1)
##t ... |
import logging
import os
import time
import uuid
from azure.common.exceptions import CloudError, AuthenticationError
from azure.common.client_factory import get_client_from_cli_profile
from azure.mgmt.authorization import AuthorizationManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.m... |
#!/usr/bin/env python3
from aiogram import Bot, Dispatcher, executor, types
import json
import toml
import re
help_text = """I mean, if you really wanted to know :/
`/help` - Nah, you figured this one out
`/join groupname` - join the group :o
`/leave groupname` - exercise for reader
`/groups` - lists available grou... |
import os
import cv2
import easyocr
import numpy as np
import pandas as pd
import streamlit as st
import matplotlib.pyplot as plt
from glob import glob
from typing import Union
from io import BytesIO, StringIO
from scipy.stats import norm, percentileofscore
if not os.path.exists('processed_images'):
os.makedirs('... |
import numpy as np
DEFAULT_PRNG = np.random
# def transformBbox(matrix, translate, center, box):
#
# '''
# Note that in SimpleITK transform parameters are applied from output sapce to input space.
# xi = A(Xo - C) + T + C
# where A:linear transform matrix, C:center, T:translate, which implies:
# ... |
import numpy as np
import torch
import math
from torch.nn import Module, Sequential, Conv2d, ReLU,AdaptiveMaxPool2d, AdaptiveAvgPool2d, \
NLLLoss, BCELoss, CrossEntropyLoss, AvgPool2d, MaxPool2d, Parameter, Linear, Sigmoid, Softmax, Dropout, Embedding
from torch.nn import functional as F
from torch import nn
#tor... |
from argparse import ArgumentParser
from functools import partial
from typing import Iterable, Tuple
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.metrics import classification_report
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC
import spac... |
import pandas as pd
import numpy as np
from . import filters
import os
def _check_event_format(events):
if not isinstance(events, pd.DataFrame):
return False
if not set(events.columns.values).issubset(["start_idx","end_idx","target_rtn","side"]):
return False
return True
def _get_label(pr... |
import json
import time
import datetime
import os
import csv
jsonDir = "./data/json"
csvDir = "./data/csv"
def convertToCsv(jsonFileName,csvFileName) :
with open(csvFileName, 'w', newline='') as csvfile :
with open(jsonFileName, 'r') as orcidJson :
orcidRecords = json.load(orcidJson)
... |
import numpy as np
import os
from argparse import ArgumentParser
from typing import Tuple, Union
import torch
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from fastmri import complex_abs
from fastmri.data import transforms as T
from kernprior import data
from kernprior import met... |
'''
Created on 2021-12-09
@author: wf
'''
import re
import requests
from typing import Optional
from enum import Enum, auto
from lodstorage.query import Query
from wikibot.wikiuser import WikiUser
from wikibot.wikiclient import WikiClient
from wikibot.smw import SMWClient
#from wikibot.wikipush import WikiPush
from sp... |
# MIT License
#
# Copyright (c) 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publi... |
#Importing Libraries/Modules
import sys, math
import pygame
from UltraColor import Color
from tiles import Tiles
# Size of the window
window_width = Tiles.size * 30
window_height = Tiles.size * 20
# Menu Size
x_menu = int((int(window_width / Tiles.size) - 6) / 2) * Tiles.size
y_menu = (int(window_height / Tiles.size) ... |
from exp.exp_multi import Exp_Multi
from exp.exp_single import Exp_Single
from utils import logger
from torch.utils.data import SubsetRandomSampler
from utils.data import SubsetSequentialSampler
from torch.utils.data import DataLoader
import torch
import torch.nn as nn
import os
from args import args
from utils.constan... |
import sys
sys.path.append('..')
import numpy as np
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from tensorflow.keras.optimizers import *
from utils import *
from Network import *
"""
NeuralNet for the game of TicTacToe.
Author: <NAME>, github.com/yamsgithub
"""
class TicTacToeNN... |
import os
import logging
from pathlib import Path
from functools import reduce
from operator import getitem
from datetime import datetime
from logger import setup_logging
from utils import read_json, write_json
class ConfigParser:
def __init__(self, args, options='', timestamp=True):
# parse default and c... |
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.cast
~~~~~~~~~
Provides type casting capabilities
"""
from decimal import Decimal, InvalidOperation
from json import loads
from operator import add, sub
from time import gmtime
from datetime import timedelta
from calendar import timegm
from urllib.parse import... |
from .layers import *
from .metrics import *
flags = tf.app.flags
FLAGS = flags.FLAGS
class Model(object):
''' 一个抽象类,实现了部分逻辑 '''
def __init__(self, **kwargs):
# kwargs已经是个字典
allowed_kwargs = {'name', 'logging'}
for kwarg in kwargs.keys():
assert kwarg in allowed_kwargs, 'I... |
import pytest
from werkzeug.exceptions import Forbidden
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import InternalServerError
from werkzeug.exceptions import NotFound
import flask
def test_error_handler_no_match(app, client):
class CustomException(Exception):
pass
class U... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# 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 applicab... |
import sqlite3
# noinspection SqlDialectInspection,SqlNoDataSourceInspection
class AddressBook:
def __init__(self, filename=None):
if filename is None:
filename = ':memory:'
self._connection = self._init_db(filename)
def add_person(self, person):
c = self._connection.curso... |
from json import JSONDecoder, JSONEncoder
import aiofiles
from .utils import run_command, Path
import os
from aiohttp import web
import hashlib
from difflib import SequenceMatcher
from itertools import islice
decoder = JSONDecoder()
encoder = JSONEncoder()
async def stat_data(path: Path) -> dict:
"""
only ca... |
import enchant
import re
import itertools
# derived from a google image search of an "old fashioned" phone
letters_from_numbers_lookup = {'2': ['A', 'B', 'C'],
'3': ['D', 'E', 'F'],
'4': ['G', 'H', 'I'],
'5': ['J', 'K', 'L'],
... |
#!/usr/bin/env python
import argparse
import binascii
import json
import subprocess
import sys
from pycoin.wallet import Wallet, PublicPrivateMismatchError
def gpg_entropy():
output = subprocess.Popen(["gpg", "--gen-random", "2", "64"], stdout=subprocess.PIPE).communicate()[0]
return output
def dev_random_e... |
import os
import mysql.connector
import logging
from robot.api import ExecutionResult, ResultVisitor
import datetime
from datetime import timedelta
def generate_report(opts):
path = os.path.abspath(os.path.expanduser(opts.path))
# output.xml files
output_names = []
# support "*.xml" of output files
... |
# ***************************************************************
# Copyright (c) 2021 Jittor. All Rights Reserved.
# Maintainers: <NAME> <<EMAIL>>.
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
# ****************************************... |
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil; coding: utf-8 -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and license terms... |
import pytest
import json
from ANYRUN import underscore_to_camel_case, images_from_report
from ANYRUN import make_capital, make_singular, make_upper
from ANYRUN import generate_dbotscore
from ANYRUN import taskid_from_url
HEADERS = {'Authorization': 'Basic Og=='}
USE_SSL = False
@pytest.fixture(scope="module")
def ge... |
## Copyright 2018-2020 Intel Corporation
## SPDX-License-Identifier: Apache-2.0
import struct
import numpy as np
# Tensor Archive (TZA) file format
VERSION = (2, 0)
_MAGIC = 0x41D7
# Writes tensors to a TZA file
class Writer(object):
# Creates a new file
def __init__(self, filename):
self._table = []
sel... |
# encoding=utf-8
import warnings
from collections import OrderedDict
from airtest.core.android.touch_methods.minitouch import Minitouch
from airtest.core.android.touch_methods.maxtouch import Maxtouch
from airtest.core.android.constant import TOUCH_METHOD
from airtest.utils.logger import get_logger
LOGGING = get_logg... |
import scipy.stats.distributions as sc_dst
import inspect
import numpy as np
from . import Stochastic
from copy import copy
from .distributions import *
"""
Wraps a SciPy rv object in a PyMC random variable object.
Needs to wrap the following methods:
generic.rvs(<shape(s)>,loc=0,scale=1)
- random variates
gener... |
#Test file
import requests
import yaml
j = []
w2 = None
# Creates a list of various data inputs for weather.
def gather_info():
global j
j.append({})
j.append({'coord': {'lon': -77.35, 'lat': 38.85}, 'weather': [{'id': 803, 'main': 'Clouds', 'description': 'broken clouds', 'icon': '04d'}], 'base': 'stations', 'm... |
import csv
import os
from pathlib import Path
from typing import Any, Dict, List
import numpy as np
from amp.config import KL_ANNEALRATE, MAX_KL, MAX_LENGTH, MAX_TEMPERATURE, MIN_KL, MIN_TEMPERATURE, TAU_ANNEALRATE
from amp.data_utils import sequence
from amp.models.model import Model
from amp.utils.basic_model_serial... |
# 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 warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
import numpy as np
import random
from collections import namedtuple, deque
from model import QNetwork
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e3) # replay buffer size
BATCH_SIZE = int(1e2) # minibatch size
GAMMA = 0.99 # discount factor
TAU = 1e-3... |
import os
import cv2
import time
import argparse
import torch
import warnings
import numpy as np
from detector import build_detector
from deep_sort import build_tracker
from utils.draw import draw_boxes
from utils.parser import get_config
from utils.log import get_logger
from utils.io import write_results
class Vide... |
from unittest import TestCase
import plotly.io as pio
import subprocess
import os
from distutils.version import LooseVersion
import requests
import time
import psutil
import pytest
import plotly.graph_objects as go
# Fixtures
# --------
from plotly.io._orca import find_open_port, which, orca_env
@pytest.fixture()
d... |
### Imports for selenium
from msilib.schema import Class
from pydoc import locate
from tokenize import Name
from turtle import down
from selenium import webdriver
from selenium.webdriver.common.keys import Keys ##adds the ability to use keys such as enter and space
from selenium.webdriver.common.action_chains import A... |
#!/usr/bin/env python3
# stdlib
import sys
import datetime
from collections import defaultdict
from tabulate import tabulate
from tqdm import tqdm
# project
import tool.discovery as discovery
from tool.config import CONFIG
from tool.model import Result, Submission
from tool.utils import BColor
class DifferentAnswers... |
import tensorflow as tf
from tensorflow.keras.layers import Layer, BatchNormalization, Dropout, Dense, Activation
from tensorflow.keras.layers import Bidirectional, LSTM # for speaker encoder
from .utils import get_mask_from_lengths
import numpy as np
from debugprint import print_debug
"""
Adapted from:
Adversarial D... |
import matplotlib.pyplot as plt
import pytest
from qm.qua import *
from qm.QuantumMachinesManager import QuantumMachinesManager
from qm import SimulationConfig
import numpy as np
from qualang_tools.bakery.bakery import baking
from copy import deepcopy
def gauss(amplitude, mu, sigma, length):
t = np.lin... |
# -*- coding: utf-8 -*-
import datetime
import logging
import json
LOG = logging.getLogger(__name__)
def hpo_terms(case_obj):
"""Extract all phenotype-associated terms for a case. Drawback of this method is that
it returns the same phenotype terms for each affected individual
of the case.
... |
from bs4 import BeautifulSoup as soup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from database.dbExecutor import... |
#!/usr/bin/python -u
# Copyright (c) 2010-2012 OpenStack, 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 applica... |
""" Export a Guidebook schedule CSV file with the currently accepted
talks.
Usage: manage.py guidebook_csv ep2015 gb.csv
Guidebook CSV format (UTF-8 encoded):
-------------------------------------
Session Title,Date,Time Start,Time End,Room/Location,Schedule Track (Optional),Description (Optiona... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import numpy as np
import os
from PIL import Image
import cv2
import struct
from subprocess import call
import warnings
import six
if six.PY2:
class ResourceWarning(RuntimeWarning):
pass
# Needed to suppress Resou... |
import re
from functools import reduce
_M = 'ျ ြ ွ ှ'
_V = 'ါ ာ ိ ီ ု ူ ေ ဲ'
_S = '္'
_A = '်'
_F = 'ံ ့ း'
_I = 'ဤ ဧ ဪ ၌ ၍ ၏'
_E = 'ဣ ဥ ဦ ဩ ၎'
_G = 'ဿ'
_D = '၀ ၁ ၂ ၃ ၄ ၅ ၆ ၇ ၈ ၉'
_P = '၊ ။'
_C = 'က ခ ဂ ဃ င စ ဆ ဇ ဈ ည ဋ ဌ ဍ ဎ ဏ တ ထ ဒ ဓ န ပ ဖ ဗ ဘ မ ယ ရ လ ဝ သ ဟ ဠ အ'
M = _M.split()
V = _V.split()
S = _S... |
import re
import functools
from eth_utils import (
is_string,
coerce_args_to_text,
pad_left,
to_checksum_address,
)
from web3.utils.validation import (
validate_address,
)
def pad_left_hex(value, num_bytes):
return pad_left(value, num_bytes * 2, '0')
def iso13616Prepare(iban):
"""
... |
import re
from pathlib import Path
import matplotlib.pyplot as plt
from textwrap import dedent
from .df_styles import get_spread
def wrap_hebtext(string):
"""Wrap hebrew text with Latex polyglossia tag."""
return '\\texthebrew{%s}'%string
class Exporter:
"""Provide export capabilities for notebooks."""
... |
# Copyright 2016 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""GPIO monitor module.
Before using, please make sure the correspondent pins are configured as GPIO in
SocKit IO pinmux setting.
For those GPIO which ar... |
# 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 itertools
import os
import shutil
import subprocess
import tempfile
import time
import typing as tp
from pathlib import Path
# pylin... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Tests for physical functions."""
# pylint: disable=no-member, invalid-name
import pytest
import numpy as np
from astropy.modeling.physical_models import BlackBody
from astropy.modeling.fitting import LevMarLSQFitter
from astropy.tests.helper import as... |
from django.contrib import messages
from django.forms import ValidationError
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from allauth.account import app_settings as account_settings
from allauth.account.adapter import get_adapter as get_account_adapt... |
import warnings
import six
from .physics import Physics, State, struct, _ChainedPhysics, _as_physics
class StateCollection(dict):
def __init__(self, states=None):
"""
Create a state collection from a dictionary of states.
:param states: dict mapping from state names to states
:type state... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.