text stringlengths 3.07k 12.6k |
|---|
# VectorMath.py
import math
class Vector:
def __init__( self, x = 0.0, y = 0.0, z = 0.0 ):
self.x = float( x )
self.y = float( y )
self.z = float( z )
def __add__( self, other ):
sum = Vector()
sum.x = self.x + other.x
sum.y = self.y + other.y
sum.z = s... |
#! -*- coding:utf-8 -*-
"""Authorization for yuqing
.. moduleauthor:: <NAME> <<EMAIL>>
"""
import hmac
import hashlib
import urllib.parse
import datetime
import time
import json
# secrets
SECRET_NAMES = set(['access_key',
'secret_key',
'api_key',
'api_secr... |
import json
from adsimulator.templates.default_values import DEFAULT_VALUES
def print_all_parameters(parameters):
print("")
print("New Settings:")
print(json.dumps(parameters, indent=4, sort_keys=True))
def get_perc_param_value(node, key, parameters):
try:
if 0 <= parameters[node][key] <= 10... |
import abc
import numpy
from collections import defaultdict
from smqtk.representation import SmqtkRepresentation
from smqtk.utils.dict import merge_dict
from smqtk.utils.plugin import Pluggable
from smqtk.utils.parallel import parallel_map
from ._io import elements_to_matrix
def _uuid_and_vector_from_descriptor(de... |
"""
Split ramps into individual FLT exposures.
To use, download *just* the RAW files for a given visit/program.
>>> from wfc3dash import process_raw
>>> process_raw.run_all()
"""
def run_all(skip_first_read=True):
"""
Run splitting script on all RAW files in the working directory.
First ... |
import numpy as np
import scipy.fftpack as fft
import sys
sys.path.append('../laplace_solver/')
import laplace_solver as lsolve
from scipy.integrate import cumtrapz
def fourier_inverse_curl(Bx, By, Bz, x, y, z, method='fourier', pad=True):
r"""
Invert curl with pseudo-spectral method described in MacKay 2006.
... |
"""
Bridging Composite and Real: Towards End-to-end Deep Image Matting [IJCV-2021]
Dataset processing.
Copyright (c) 2021, <NAME> (<EMAIL>)
Licensed under the MIT License (see LICENSE for details)
Github repo: https://github.com/JizhiziLi/GFM
Paper link (Arxiv): https://arxiv.org/abs/2010.16188
"""
from config impor... |
from Bio import SeqIO
import gzip
import os
import sys
from seqtools.general import rc, translate
def parse_gtf_dict(gtf_str):
return {i.split(' "')[0]:i.split(' "')[1] for i in gtf_str.split('"; ')}
def gtf_to_gene_length(gtf_file, outfile, sum_type='transcript_longest'):
"""
Get Gene length, 3 option... |
#!/usr/bin/env python3
#
# Copyright (c) 2020 Google LLC.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... |
"""
This is the start page for the application and includes all the
different application modules listed in the PAGES variable.
Renders the login page as well as the index page.
"""
from collections import defaultdict
from flask import escape
from flask.ext.login import current_user
from page import Page
from pages... |
import sys
import traceback
import numpy as np
from shapely import geometry as g
import multiprocessing as mp
from . import abCellSize
from . import abUtils
class abLongBreakWaterLocAlphaAdjust:
def __init__(self, cell, neighbors, coastPolygons, directions, alphas, betas):
self.cell = cell
self.neigh... |
import gym
import numpy as np
import tensorflow as tf
import time
from actor_critic import RandomActorCritic
from common.multiprocessing_env import SubprocVecEnv
from common.model import NetworkBase, model_play_games
from environment_model.network import EMBuilder
from tqdm import tqdm
class EnvironmentModel(Networ... |
from rest_framework import serializers
from battles.models import Battle, Team, TeamPokemon
from battles.services.api_integration import (
check_pokemons_exists_in_pokeapi,
get_or_create_pokemon,
get_pokemon_info,
)
from battles.services.email import email_invite
from battles.services.logic_team import (
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.pipeline import Pipeline
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.preprocessing import StandardScaler, Imputer
from wakeful import log_munger, pipelining, preprocessing
def get_feature_impor... |
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, List, Optional, Union
import datetime
from ..utils import Snowflake
from .embed import Embed
from .threads import Thread
from .attachments import Attachment
from .components import ActionRow
if TYPE_CHECKING:
from ..state import State
... |
# Correr el servidor python manage.py runserver
# Request: Para realizar peticiones al servidor.
# HttpResponse: Para enviar la respuesta usando el protocolo HTTP.
from typing import Text
from django.http import request
from Usuario_PostgreSQL.models import Agenda, Pacientes, Notamedica
from Usuario_PostgreSQL.models... |
""" This module helps out with generating text using templates """
import json
import random
import re
from functools import lru_cache
import tracery
from tracery.modifiers import base_english
from talkgenerator.sources import conceptnet
from talkgenerator.sources import phrasefinder
from talkgenerator.sources import... |
# SetupProject DaVinci v36r2
import sys
from GaudiConf import IOHelper
from Configurables import LHCbApp, ApplicationMgr, DataOnDemandSvc
from Configurables import SimConf, DigiConf, DecodeRawEvent
from Configurables import ConfigTarFileAccessSvc
from Configurables import CondDB, DaVinci
from Configurables import LoKi... |
"""
============================
Typing (:mod:`numpy.typing`)
============================
.. warning::
Some of the types in this module rely on features only present in
the standard library in Python 3.8 and greater. If you want to use
these types in earlier versions of Python, you should install the
typing-... |
from sortedcontainers import SortedSet
import math
EPSILON = 0.001
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K:
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __g... |
from .models import Node
from django.shortcuts import render
from django.http import JsonResponse, Http404
from django.core.exceptions import PermissionDenied
#from pprint import pprint
import re
import os
from django.conf import settings
from django.db.models import Q, Case, When
from django.shortcuts import redirect
... |
import unittest
from metapack import MetapackDoc
from metapack_db import Database, MetatabManager
from metapack_db.document import Document
from metapack_db.term import Term
from os import remove
from os.path import exists
from sqlalchemy.exc import IntegrityError
def test_data(*paths):
from os.path import dirn... |
import os
import shutil
import numpy as np
import mxnet as mx
from mxnet import gluon
from mxnet.gluon import nn
from mxnet import autograd as ag
def train_one_epoch(epoch, optimizer, train_data, criterion, ctx):
train_data.reset()
acc_metric = mx.metric.Accuracy()
loss_sum = 0.0
count = 0
... |
import pandas as pd
from enum import Enum
class EQUI(Enum):
EQUIVALENT = 1
DIF_CARDINALITY = 2
DIF_SCHEMA = 3
DIF_VALUES = 4
"""
UTILS
"""
def most_likely_key(df):
res = uniqueness(df)
res = sorted(res.items(), key=lambda x: x[1], reverse=True)
return res[0]
def uniqueness(df):
r... |
"""
"""
import pandas as pd
import numpy as np
import os
class IntensitySuperStructure:
def __init__(self, parent_source_directory):
self.sources = set()
self.df = pd.DataFrame(dtype=object)
self.par = parent_source_directory
self.info = dict()
self.output = os.path.joi... |
# noinspection PyUnresolvedReferences
from pythoncom import com_error
from datetime import date
from datetime import datetime
from .. util.text import vengeance_message
from .. util.iter import force_two_dimen
from .. util.iter import is_iterable
from .. util.iter import is_vengeance_class
from .. excel_com.excel_a... |
import numpy as np
from scipy import signal, ndimage
from hexrd import convolution
def fast_snip1d(y, w=4, numiter=2):
"""
"""
bkg = np.zeros_like(y)
zfull = np.log(np.log(np.sqrt(y + 1.) + 1.) + 1.)
for k, z in enumerate(zfull):
b = z
for i in range(numiter):
for p in... |
from collections import namedtuple
import cv2
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
import random
from os.path import join
from prettyparse import Usage
from torch.utils.data.dataset import Dataset as TorchDataset
from autodo.dataset import Dataset
k = np.array([[2304.5479, 0, 1686.23... |
import numpy as np
import tensorflow as tf
def get_lr_schedule(lr_decay_rate=None,
lr_decay_step=None,
lr_decay_per_iter=True,
lr_decay_start_step=0,
lr_decay_end_step=np.inf,
lr_warmup_init=1e-9,
l... |
from datetime import date, timedelta, datetime, time
from django.contrib.contenttypes.models import ContentType
from django.conf import settings
from django.db import models
from django.db import connections
from django.utils import timezone
from .models import Period, StatisticByDate, StatisticByDateAndObject
clas... |
__author__ = '<NAME> <<EMAIL>>'
__date__ = ' 16 December 2017'
__copyright__ = 'Copyright (c) 2017 <NAME>'
import dg
import pandas as pd
from copy import deepcopy
from dg.utils import bar
from dg import persistence
from dg.config import Config
from dg.enums import Mode, Dataset
def train_model(model, train_set, eva... |
from common import *
def test_virtual_columns_spherical():
df = vaex.from_scalars(alpha=0, delta=0, distance=1)
df.add_virtual_columns_spherical_to_cartesian("alpha", "delta", "distance", "x", "y", "z", radians=False)
x, y, z = df['x'].values[0], df['y'].values[0], df['z'].values[0]
np.testing.asser... |
# Name: <NAME>
# Date: 2 March 2020
# Program: biot_helix.py
import numpy as np
import matplotlib.pyplot as plt
import time as time
from matplotlib.patches import Circle
def biot(Rvec, wire, I):
mu_4pi = 10
dB = np.zeros((len(wire), 3))
R = Rvec - wire
Rsqr = np.sum( R**2, axis = 1 )
d... |
import torch.nn as nn
import torch.nn.functional as F
import torch
from utils.conv_block import ConvBlock
from utils.common import pairwise_distances, split_support_query_set
device = 'cuda' if torch.cuda.is_available() else 'cpu'
class Classifier(nn.Module):
def __init__(self, in_channel):
super().__in... |
from collections import deque
class BinarySearchTree:
class GraphNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __str__(self):
return f"Data:{self.data}"
def __init__(self):
self.root_node = None
... |
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import albumentations
import albumentations.pytorch
import numpy as np
import math
import pandas as pd
import random
import os
import matplotlib
import argparse
import wandb
from EnD import *
from configs import *
from collections im... |
# Copyright (c) 2015
#
# All rights reserved.
#
# This file is distributed under the Clear BSD license.
# The full text can be found in LICENSE in the root directory.
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import random
import re
import string
import time
from devices import prompt
wlan_iface = None
d... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gym
from ray.rllib.models.action_dist import (
Categorical, Deterministic, DiagGaussian)
from ray.rllib.models.preprocessors import (
NoPreprocessor, AtariRamPreprocessor, AtariPixelPreprocessor... |
""" A PointSampleCam emulates a camera which has been calibrated to associate real-world coordinates (xr, yr) with each pixel position (xp, yp). A calibration data file is consulted which provides these associations. """
import pymunk
import numpy as np
from math import atan2, sqrt, fabs
from common import *
from pym... |
from datetime import datetime, timedelta
import pytz
import json
import urllib
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.views.decorators.csrf... |
#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-
import os
import re
import sys
import sqlite3
from collections import defaultdict
def value2list(text):
text = re.sub(r'(^\[|\]$)', '', text)
value_list = text.split(',') if text != "" else []
value_list = [value.strip() for value in value_list]
retur... |
from collections import defaultdict
from collections import Counter # Pakiet ten nie jest ładowany domyślnie.
users = [
{"id": 0, "name": "Hero"},
{"id": 1, "name": "Dunn"},
{"id": 2, "name": "Sue"},
{"id": 3, "name": "Chi"},
{"id": 4, "name": "Thor"},
{"id": 5, "name": "Clive"},
{"id": 6,... |
import os
import pickle
import sys
import icdiff
from util import data_io
sys.path.append(".")
import difflib
from typing import Optional, List, Tuple
import numpy as np
from nemo.collections.asr.parts.preprocessing import AudioSegment
from speech_to_text.transcribe_audio import (
SpeechToText,
AlignedTrans... |
"""
QP-BASIL - Quantiphyse processes for ASL data
These processes use the ``oxasl`` and `fslpyt` python libraries which involves
the following key mappings between Quantiphyse concepts and
oxasl concepts.
- ``quantiphyse.data.QpData`` <-> ``fsl.data.image.Image``
Quantiphyse data objects can be transformed to and ... |
import traceback
import os
from todayLoginService import TodayLoginService
from actions.autoSign import AutoSign
from actions.collection import Collection
from actions.sleepCheck import sleepCheck
from actions.workLog import workLog
from actions.sendMessage import SendMessage
from actions.teacherSign import teacherSign... |
import copy
import inspect
import itertools
import types
import warnings
from typing import Any, Dict
import numpy as np
from axelrod import _module_random
from axelrod.action import Action
from axelrod.game import DefaultGame
from axelrod.history import History
from axelrod.random_ import RandomGenerator
C, D = Acti... |
import asyncio
import hashlib
import json
import re
import ssl
import websocket
import websockets
class OKCoinWSPublic:
Ticker = None
def __init__(self, pair, verbose):
self.pair = pair
self.verbose = verbose
@asyncio.coroutine
def initialize(self):
TickerFirstRun = True
while True:
i... |
# ._____. __
# ___________ |__\_ |__ _____/ |_
# \____ \__ \ | || __ \ / _ \ __\
# | |_> > __ \| || \_\ ( <_> ) |
# | __(____ /__||___ /\____/|__|
# |__| \/ \/
#This code is horrendous. Just saying.
import os, discord, random
from bo... |
# imports
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path
import numpy as np
from matplotlib.animation import FuncAnimation
import matplotlib.gridspec as gridspec
import os
import time
from manipulate_readinuvot import uvot
import scipy
from scipy.interpolate import interp1d
import matplot... |
# Copyright (c) 2013- The Spyder Development Team and Docrepr Contributors
#
# Distributed under the terms of the BSD BSD 3-Clause License
"""Simple tests of docrepr's output."""
# Standard library imports
import copy
import subprocess
import sys
import tempfile
from pathlib import Path
# Third party imports
import ... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import authenticate, login
from .forms import *
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.urls import reverse
# 自己写的用户登录的判断 ... |
# coding:utf-8
"""
Copyright 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 agree... |
from sys import exit
import argparse
import logging
_logger = logging.getLogger(__name__)
_LOGGING_FORMAT = '%(name)s.%(funcName)s[%(levelname)s]: %(message)s'
_DEBUG_LOGGING_FORMAT = '### %(asctime).19s.%(msecs).3s [%(levelname)s] %(name)s.%(funcName)s (%(filename)s:%(lineno)d) ###\n%(message)s'
def parse_args():
... |
import re
import pandas as pd
def update_simulation_date_time(lines, start_line, new_datetime):
"""
replace both the analysis and reporting start date and times
"""
new_date = new_datetime.strftime("%m/%d/%Y")
new_time = new_datetime.strftime("%H:%M:%S")
lines[start_line] = re.sub(r'\d{2}\\\d{... |
"""Dummy fill to keep density constant."""
import itertools
from typing import Optional, Union
import gdspy
import numpy as np
from numpy import sqrt
from phidl.device_layout import _parse_layer
from phidl.geometry import (
_expand_raster,
_loop_over,
_raster_index_to_coords,
_rasterize_polygons,
)
fr... |
import six
import collections
from chef.base import ChefObject
from chef.exceptions import ChefError
class NodeAttributes(collections.MutableMapping):
"""A collection of Chef :class:`~chef.Node` attributes.
Attributes can be accessed like a normal python :class:`dict`::
print node['fqdn']
no... |
import csv
import json
import os
import requests
import sys
from io import StringIO
from utils import CacheManager
from pathlib import PurePath
from configparser import ConfigParser, MissingSectionHeaderError, NoSectionError
from datetime import datetime, timedelta
requests.packages.urllib3.disable_warnings()... |
import torch.nn as nn
import torch
from ..builder import LOSSES
import numpy as np
from .utils import weighted_loss
import torch.nn.functional as F
from mmdet.core import bbox_overlaps
def _gaussian_dist_pdf(val, mean, var):
return torch.exp(- (val - mean) ** 2.0 / var / 2.0) / torch.sqrt(2.0 * np.pi * var)
# @we... |
# Copyright 2020 Canonical Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
import os
import sys
try:
base_directory = os.path.split(sys.executable)[0]
os.environ['PATH'] += ';' + base_directory
import cntk
os.environ['KERAS_BACKEND'] = 'cntk'
except ImportError:
print('CNTK not installed')
import keras
import keras.utils
import keras.datasets
import keras.models
import ... |
from __future__ import annotations
import pickle
import numpy as np
from lightgbm import LGBMRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import (
ElasticNet,
HuberRegressor,
Lasso,
LinearRegression,
MultiTaskElasticNet,
MultiTaskLasso,
)
from sklearn.... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#!/usr/bin/python
# A Change is an operation to a filesystem, such as writen file, or deleted one.
# A Changeset is a list of changes. Cumulative changes are a list of changes
# that are the result of applying a range of changesets (referred to as playback).
# In practice, it represents a complete filesystem and is us... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.0-a53ec6ee1b (http://hl7.org/fhir/StructureDefinition/Communication) on 2019-01-25.
# 2019, SMART Health IT.
##
from . import domainresource
class Communication(domainresource.DomainResource):
""" A record of information transmitted from... |
# Importing the required packages
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from catboost import CatBoostClassifier
import statistic... |
from qt import *
from qtcanvas import *
from lpathtree_qt import *
class Point:
def __init__(self, *args):
if len(args) == 2 and \
(isinstance(args[0],int) or isinstance(args[0],float)) and \
(isinstance(args[1],int) or isinstance(args[0],float)):
self.x = float(args[0])
... |
# coding=utf-8
# created by msgi on 2020/4/1 7:23 下午
import tensorflow as tf
# simple attention mechanism
class BahdanauAttention(tf.keras.layers.Layer):
def __init__(self, units):
super(BahdanauAttention, self).__init__()
self.W1 = tf.keras.layers.Dense(units)
self.W2 = tf.keras.layers.De... |
'''
Using resemble API based on https://app.resemble.ai/docs to do TTS (text-to-speech)
'''
import requests
import os
import copy
## Define variables
# User API token for access
pt_token = "<KEY>"
# Project to consider
project_uuid = 'e89aa5c3'
# User ID (uuid) for voice
pt_voice = '89423c90'
# text to convert to spee... |
import json
import re
import urllib.parse
from typing import Tuple, Dict, Union, List, Any, Optional
from lumigo_tracer.libs import xmltodict
import functools
import itertools
from collections.abc import Iterable
from lumigo_tracer.lumigo_utils import Configuration, get_logger
def safe_get(d: Union[dict, list], key... |
'''
@anchor pydoc:grizzly.testdata.variables.csv_row CSV Row
This variable reads a CSV file and provides a new row from the CSV file each time it is accessed.
The CSV files **must** have headers for each column, since these are used to reference the value.
## Format
Value is the path, relative to `requests/`, of an ... |
#!/usr/bin/env python2.7
# coding=utf8
import os
import sys
from youdao.config import __version__
from youdao.entry import Youdao
from youdao.sqlsaver import SQLSaver
reload(sys)
sys.setdefaultencoding("utf8")
db_path = SQLSaver().db_path
youdao = Youdao()
map_target = {
'--trans': '直接翻译',
'--web': '网络翻译',... |
"""Discover and load entry points from installed packages."""
# Copyright (c) <NAME> and contributors
# Distributed under the terms of the MIT license; see LICENSE file.
from contextlib import contextmanager
import glob
from importlib import import_module
import io
import itertools
import os.path as osp
import re
impo... |
import sys
import os
import re
import logging
import pkgutil
import importlib
import traceback
from collections import OrderedDict
from importlib import import_module
import optparse
from getpass import getpass
from substance import Shell
from substance.exceptions import InvalidCommandError
logger = logging.getLogg... |
#!/usr/bin/env python
# Copyright 2020 Johns Hopkins University (Author: <NAME>)
# Apache 2.0
# This script is based on the Bayesian HMM-based xvector clustering
# code released by BUTSpeech at: https://github.com/BUTSpeechFIT/VBx.
# Note that this assumes that the provided labels are for a single
# recording. So this... |
from breidablik.interpolate.spectra import Spectra
import numpy as np
import pytest
import warnings
try:
Spectra()
flag = False
except:
flag = True
# skip these tests if the trained models are not present
pytestmark = pytest.mark.skipif(flag, reason = 'No trained Spectra model')
class Test_find_abund:
... |
from scipy.signal import butter
from helper import ULogHelper
class DiagnoseFailure:
def __init__(self, ulog):
data_parser = ULogHelper(ulog)
data_parser.extractRequiredMessages(['estimator_status', 'vehicle_status'])
def change_diagnose(self, timestamps, flags, flag_type):
if fl... |
# Copyright 2018 The TensorFlow Constrained Optimization Authors. All Rights
# Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... |
# -*- coding utf-8-*-
"""
Created on Tue Nov 23 10:15:35 2018
@author: galad-loth
"""
import numpy as npy
import mxnet as mx
class SSDHLoss(mx.operator.CustomOp):
"""
Loss layer for supervised semantics-preserving deep hashing.
"""
def __init__(self, w_bin, w_balance):
self._w_b... |
#!/usr/bin/env python3
from __future__ import print_function
import argparse
import datetime
import os
import pickle
import re
import sys
import time
import googleapiclient
import icalendar
import ics
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth... |
import math
import torch
from torch import nn, Tensor
from torch.nn import functional as F
import torchvision
from typing import List, Tuple, Dict, Optional
@torch.jit.unused
def _resize_image_and_masks_onnx(image, self_min_size, self_max_size, target):
# type: (Tensor, float, float, Optional[Dict[str, Tensor]]) -> ... |
#
# Simulations: discharge of a lead-acid battery
#
import argparse
import matplotlib.pyplot as plt
import numpy as np
import pickle
import pybamm
import shared_plotting
from collections import defaultdict
from shared_solutions import model_comparison, convergence_study
try:
from config import OUTPUT_DIR
except Im... |
import numpy as np
from pommerman.constants import Item
from util.analytics import Stopwatch
def transform_observation(obs, p_obs=False, centralized=False):
"""
Transform a singular observation of the board into a stack of
binary planes.
:param obs: The observation containing the board
... |
# -*- encoding: utf-8 -*-
"""Record/Playback an api method's return values.
TODO: Make @api_automock decorator separate.
"""
import collections
import hashlib
import pprint
from slugify import slugify
from api_recorder.api_controller import ApiRecorderController
pp = pprint.PrettyPrinter(indent=2)
acr_remote = ApiRe... |
import os
import platform
import subprocess
import sys
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
__version__ = '0.4.1'
__capy_amqp_version__ = '0.5.4'
darwin_flags = ['-mmacosx-version-min=10.14', '-faligned-allocation']
cmake_darwin_flags = ['-DOPENSSL_ROOT_DIR=/usr/... |
#! /usr/bin/env python
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
import torchvision.models as models
import time
import sys
import os
import glob
... |
import torch
import torch.nn as nn
import torch.optim as optim
import os
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from data_loader import *
def get_iou(predict, label):
predict_f = torch.flatten(predict)
label_f = torch.flatten(label)
intersection = torch.sum(predict_f*lab... |
from enum import Enum
from supproperty import decimal, supproperty, boolean, integer, float_vector
from bac.simulate.coding import Encodable
from .group import Group
class CouplingType(Enum):
vdw_and_coulomb = 'vdw-q'
vdw = 'vdw'
coulomb = 'q'
none = 'none'
@classmethod
def _missing_(cls, v... |
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from rest_framework.parsers import JSONParser
from django.views.decorators.http import require_POST,require_GET
from django.views.decorators.csrf import csrf_exempt
import datetime
import pandas as pd
from transactions.models import... |
import numpy as np
from .base_likelihood import Likelihood
from scipy.special import logsumexp, softmax
from tramp.utils.linear_region import LinearRegionLikelihood
class PiecewiseLinearLikelihood(Likelihood):
def __init__(self, name, regions, y, y_name="y"):
self.y_name = y_name
self.size = self.... |
import os
import cv2
import pandas as pd
import numpy as np
import imgaug.augmenters as iaa
from sklearn.utils import shuffle
from tensorflow.keras.models import Sequential
from tensorflow.keras import layers
from tensorflow.keras.optimizers import Adam
import matplotlib.pyplot as plt
import matplotlib.image as mpimg... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import codecs
import getopt
import io
import os
import re
import shutil
import sys
import time
def main(argv):
# Defaults
dictionaryFile = "resources/cedict_ts.u8"
inputFile = ""
inputDir = ""
inputString = ""
process = "filename"
tones = False
... |
#!/usr/bin/env python
# -*- coding: utf-8
# Copyright 2017-2019 The FIAAS 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
#
# U... |
import Bio,gzip
from Bio import SeqIO
import pyteomics
from pyteomics import mass,fasta
import pyteomics.parser as pyt_parser
import pandas as pd
import numpy as np
import json,os
from tqdm import tqdm
from load_config import CONFIG
MAX_DATABASE_SIZE=100000000
DB_PEPTIDE_MINIMUM_LENGTH=CONFIG['DB_PEPTIDE_MINIMUM_LENG... |
from src.platsec.compliance.prowler import (ProwlerExecutionRun, ProwlerConfig)
from src.platsec.compliance.prowler_exceptions import (
PipelineValidationPhaseException,
AwsBucketPathCreateException,
AwsProwlerFileException)
from src.platsec.compliance.prowler import (
get_prowler_config,
check_reco... |
import numpy as np
import cv2
import keras
import utils
import glob
import os
from keras.models import load_model
import time
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.compat.v1.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.7
set_session(tf.comp... |
############
# Standard #
############
import logging
###############
# Third Party #
###############
import pytest
import numpy as np
from bluesky.preprocessors import run_wrapper
from ophyd.status import Status
##########
# Module #
##########
from pswalker.iterwalk import iterwalk
TOL = 5
logger = logging.getLogger... |
# /usr/bin/env python3.5
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2017-2018, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# mod... |
import asyncio
import random
from datetime import datetime, timedelta
import discord
from discord.ext import commands, tasks
from web3 import Web3
from joeBot import JoePic, JoeSubGraph, Constants, Utils
from joeBot.JoeMakerBot import JoeMaker
from joeBot.Utils import readable, Ticker
# web3
w3 = Web3(Web3.HTTPProvi... |
#! /usr/bin/env python3
'''
Author: <NAME>, ORCID 0000-0003-4248-4528
Copyleft: MIT License (https://en.wikipedia.org/wiki/MIT_License)
Construct labeled Gaifman graph of a transactional dataset.
Produce either DOT output on stdout for the Gaifman graph
or an AGraph from pygraphviz with separate singletons and
rep... |
# pylint: disable=W0614
import os
import click
from common.click_ext import MyGroup
from common.click_ext import MyCommand
from common import click_ext
from cmds import *
manage_cmds = {
"host": "Manage host networks",
"container": "Manage containers and networks"
}
host_cmds = {
"create": "Create a new c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.