text stringlengths 3.07k 22.1k |
|---|
"""Tests for krotov.Objective in isolation"""
import os
import copy
import numpy as np
import scipy
import qutip
import krotov
import pytest
@pytest.fixture
def transmon_ham_and_states(
Ec=0.386, EjEc=45, nstates=2, ng=0.0, T=10.0):
"""Transmon Hamiltonian"""
Ej = EjEc * Ec
n = np.arange(-nstat... |
from pykrx.website.comm import dataframe_empty_handler
from pykrx.website.krx.e3.core import (개별종목시세_ETF, 전종목시세_ETF,
PDF, 추적오차율추이, 괴리율추이)
from pykrx.website.krx.e3.ticker import EtfTicker
import numpy as np
import decimal
import pandas as pd
from pandas import DataFrame
@datafra... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Plugin for transfering objects and annotations between servers
"""
from pathlib import Path
import sys
import os
import copy
from ome_types.model import CommentAnnotation
from functools import wraps
import shutil
from collections import defaultdict
from hashlib i... |
import logging
from nltk.corpus import gutenberg
from src.common.constants import NGRAM_UPPER_THRESHOLD, NOUN_PHRASE_THRESHOLD, VERB_PHRASE_THRESHOLD
from src.common.model import Keyword, KnowledgeUnit
from src.common.handler import PosPatternHandler
from src.common.utils import *
class BasicGeneralTextParser(BaseLo... |
"""Tasmota status sensor."""
import asyncio
import json
import logging
from datetime import datetime, timedelta, timezone
import attr
from .const import (
CONF_DEVICENAME,
CONF_IP,
CONF_MAC,
PERCENTAGE,
SENSOR_STATUS_IP,
SENSOR_STATUS_LAST_RESTART_TIME,
SENSOR_STATUS_LINK_COUNT,
SENSOR... |
import psycopg2
import pandas as pd
from pandas_datareader import data as web
import numpy as np
import pickle
from sklearn.linear_model import LogisticRegression
from sklearn.multiclass import OneVsRestClassifier
import bs4
from bs4 import BeautifulSoup
import requests
import datetime
# Connecting to the databse
conn... |
__author__ = 'agiletekengineering'
__version__ = '0.1.16'
import datetime as dt
import dateutil.relativedelta as rdelta
from dateutil.rrule import DAILY, rrule
from dateutil.parser import parse
import requests as http
URL_START = "https://www.timecamp.com/third_party/api"
TC_ITEM_TYPES = ['users', 'tasks', 'entries',... |
"""
This module contains functions for creating tables in PostgreSQL database
"""
def create_table(rdb):
"""
Remove tables from database if exists and create new name_type and examination tables in the PostgreSQL database
"""
sql_drop = "DROP TABLE IF EXISTS header,name_type,examination,examinati... |
# ---------------------------------------------------------
# IOU Tracker
# Copyright (c) 2017 TU Berlin, Communication Systems Group
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>
# ---------------------------------------------------------
import numpy as np
import csv
import os
import... |
"""
Copyright (c) 2018-2021 Intel 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 wri... |
# Author: a101269
# Date : 2020/3/9
import torch
import torch.nn as nn
from utils.utils import logger, seed_everything
from model.criterion import criterion
from model.optimizer import get_optimizer
from torch.nn.utils import clip_grad_norm_
from modules.sdp_decoder import sdp_decoder, parse_semgraph
import mo... |
from collections import namedtuple
import unittest
# Named tuples assign meaning to each position in a tuple and allow for more readable,
# self-documenting code. They can be used wherever regular tuples are used, and they add
# the ability to access fields by name instead of position index.
# collections.namedtuple(t... |
# pylint: disable=redefined-outer-name, no-self-use
"""Test the linalg module."""
import numpy as np
import pytest
import xarray as xr
from xarray.testing import assert_allclose, assert_equal
from xarray_einstats import einsum, einsum_path, linalg, matmul, raw_einsum, tutorial
from xarray_einstats.linalg import (
... |
import logging
from difflib import SequenceMatcher
from pathlib import Path
from typing import Dict, List, Tuple, Union
from contributors_txt.create_content import (
Alias,
Person,
get_teams,
line_for_person,
person_should_be_shown,
persons_from_shortlog,
)
def similar(a_string: str, another_... |
from brownie import *
from .settings import *
from .contracts import *
from .contract_addresses import *
import time
import random
def main():
access_control = deploy_access_control(accounts[0])
bento_box = deploy_bento_box()
number_of_auction_1= 5
number_of_auction_2 = 5
deploy_n_number_fixed_t... |
import json
import os
import os.path as osp
import shutil
import numpy as np
import scipy.sparse as sp
from networkx.readwrite import json_graph
from spektral.data import Dataset, Graph
from spektral.data.dataset import DATASET_FOLDER
from spektral.datasets.utils import download_file
class GraphSage(Dataset):
"... |
from abc import ABC, abstractmethod
import os
import datetime
import re
import glob
import errno
import time
import shutil
import anidbcli.libed2k as libed2k
# ed2k,md5,sha1,crc32,resolution,aired,year,romanji,kanji,english,epno,epname,epromanji,epkanji,groupname,shortgroupname
API_ENDPOINT_FILE = "FILE size=%d&ed2k... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import json
import math
import os
from typing import List, Optional, Tuple, Union
import numpy as... |
# coding: utf-8
# # Accessing ERDDAP from Python
#
# ERDDAP rich responses and RESTful API is makes it **THE** most convenient way to serve data.
#
# One can build URLs manually or programmatically like:
#
# <small>`https://erddap-uncabled.oceanobservatories.org/uncabled/erddap/tabledap/CP05MOAS-GL336-02-... |
import os
from openbabel import openbabel as ob
from openbabel import pybel as pb
from rdkit import Chem
from fragresp.utils import logger
def make_g09(name,
conf,
nproc=4,
mem=1900,
queue='marc2'):
queue_choices = ['marc2', 'slurm', 'condor', 'none']
if qu... |
from os.path import basename as _basename
from Bio.Seq import Seq as _Bio_Seq
from molsysmt._private_tools.exceptions import *
from molsysmt.forms.common_gets import *
import numpy as np
form_name=_basename(__file__).split('.')[0].replace('api_','').replace('_','.')
is_form={
_Bio_Seq : form_name,
'biopython.... |
# -*- coding: utf-8 -*-
##########################################################################
# NSAp - Copyright (C) CEA, 2021
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
#... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 23 14:15:51 2018
@author: jacoblashner
"""
from serial import Serial
from serial.serialutil import SerialException
import time
import sys
import numpy as np
from collections import OrderedDict
import socket
from typing import List
BUFF_SIZE = 102... |
import html
from SaitamaRobot import (LOGGER, DRAGONS, TIGERS, WOLVES, dispatcher)
from SaitamaRobot.modules.helper_funcs.chat_status import (user_admin,
user_not_admin)
from SaitamaRobot.modules.log_channel import loggable
from SaitamaRobot.modules.sql import... |
from bson.objectid import ObjectId
import vacker.database
class MediaCollection(object):
_show_hidden = False
def __init__(self, id):
self._id = id
self._initialise()
def _initialise(self):
pass
def show_hidden(self):
self._show_hidden = True
def get_media_id... |
from orekit_utils import *
from plot_ephemeris import *
from spice_loader import *
class NoMapperError(ValueError):
pass
class WriteSpiceEphemerisHandler(PythonOrekitFixedStepHandler):
center_id = 399
ref_frame_name = 'J2000'
segment_id = 'transit'
degree = 15
write ... |
# By <NAME>
# https://github.com/DanyCaissy/Reddit/
import praw
import credentials # Contains my personal credentials, you don't need to include this
import karma_for_user # Calculates karma of a user within a specific subreddit
import logging # To log errors or otherwise
import collections # Ordered dictionary
impor... |
import tensorflow as tf
import numpy as np
def _point_scale2img(points, _H, _W):
""" map normalized [0,1]x[0,1] points to image [0,H]x[0,W]
args:
points -> [..., 2]
"""
# with tf.variable_scope("_point_scale2img", reuse=False):
points = points * tf.constant([_H - 1, _W - 1], "float32")
... |
from browser import document as doc
from browser import bind, window
from browser.html import TABLE, TR, TH, TD, INPUT, SELECT, OPTION, BUTTON, SPAN, LI, H2, H3, IMG, COLGROUP, COL, SECTION
from resource_vals import *
def load_page():
# add navigation buttons
pages = ['ascensions', 'modifiers', 'artifacts', 'notes'... |
import cv2
import torch
import random
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from pathlib import Path
from tqdm.notebook import tqdm
def read_frame_as_size(video_path, size=(128, 128)):
capture = cv2.VideoCapture(str(video_path))
ret, fram... |
import time
import torch
import torch.nn as nn
from tqdm import tqdm
from utils import train_utils
from torch.utils.data import DataLoader
from utils.types import Scores, Metrics
from dataset import MaskDataset
from models.separate_model import MaskModel, BBModel
from utils.train_utils import get_metrics, accuracy, cal... |
# Copyright 2011-2021 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 writ... |
import datetime
from kv import *
from genre import Genre
from gremlin_python.process.traversal import (Bytecode, P, Scope, Order, Column, T)
from gremlin_python.process.graph_traversal import (GraphTraversalSource, GraphTraversal)
from gremlin_python.process.graph_traversal import __ as AnonymousTraversal
from aenum im... |
import cv2
import math
import time
import numpy as np
from numpy import linalg as LA
def distance(p1, p2):
return math.sqrt((p1[0] - p2[0]) * (p1[0] - p2[0]) + \
(p1[1] - p2[1]) * (p1[1] - p2[1]))
def curve_interp(src, samples, index):
assert(src.shape[0] > 2)
assert(samples >= 2)
... |
import finplot as fplt
import json
from PyQt5.QtWidgets import QComboBox, QCheckBox, QWidget
from pyqtgraph import QtGui
import pyqtgraph as pg
from time import time as now, sleep
import sys
import asyncio
from binance import AsyncClient
from .. import binance_wrapper
import datetime
from itertools import chain
import... |
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import collections
import json
import os
from collections import OrderedDict
from functools import partial
import click
import requests
import xlwt
from xlwt import Workbook
class Json2Xls(object):
"""Json2Xls API 接口
:param string xls_filename: 指定需要生成的的excel的文件名... |
import bpy
from bpy.types import (Panel, Operator)
import os
os.system("cls") # Clear console
bl_info = {
"name": "Stretch Render",
"description": "Alternative rendering compression method.",
"author": "CrunchyDuck <<EMAIL>>",
"version": (0, 1, 1),
"blender": (2, 83, 0),
"category": "Render",
"location": "Ope... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""YOLOv4 for MS COCO.
# Reference:
- [tensorflow-yolov4-tflite](
https://github.com/hunglc007/tensorflow-yolov4-tflite)
"""
import tensorflow as tf
import numpy as np
import tensorlayer as tl
from tensorlayer.activation import mish
from tensorlayer.layers import Conv2d... |
#!/usr/bin/env python3
from configparser import RawConfigParser
from argparse import ArgumentParser
from requests import get
import sys
import os.path
import urllib.request, urllib.parse, urllib.error
import logging
__version__ = '0.2'
def set_log_level(args_level):
if args_level is None:
args_level = ... |
import os
import yaml
import time
import shutil
import torch
import random
import argparse
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data.dataloader import DataLoader
from torch.utils.data.sampler import RandomSampler
from tqdm import tqdm
from hyperseg.utils.utils import... |
from contextlib import contextmanager
from typing import Any, Callable, Type
import pytest
from antidote import Factory, Provide, Service, Wiring, factory, inject, world
from antidote._providers import (FactoryProvider, LazyProvider, ServiceProvider)
@contextmanager
def does_not_raise():
yield
@pytest.fixture... |
import networkx as nx
import EoN
import numpy as np
import random
def subsample(report_times, times, status1, status2=None,
status3 = None):
r'''
Given
S, I, and/or R as lists of numbers of nodes of the given status
at given times
returns them
subsampled at specific re... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 20 13:34:01 2018
@author: deborahkhider
This routine uses FLDAS climatology to
generate possible weather conditions
for an area given a percent level with
respect to observed conditions. The
routine prepares the CSV file for use with
the weather ge... |
'''
Description:
A technique for detecting anomalies in seasonal univariate time
series where the input is a series of <timestamp, count> pairs.
Usage:
anomaly_detect_ts(x, granularity="day", max_anoms=0.1, direction="pos", alpha=0.05, only_last=None,
threshold="None", e_value=F... |
from io import StringIO
import os
from os import path as op
import re
from shlex import quote, join as sjoin
import subprocess
import sys
import time
from .. import logger, get_config, CONFIG
COMMANDS = {
'install': 'Install app',
'start': 'Start app',
'stop': 'Stop app',
'restart': 'Restart app',
... |
from icv5.components.monday import boardItem, column_keys, manage, exceptions
class RefurbWrapper(boardItem.MondayWrapper):
def __init__(self, item_id, parent_obj, blank_item=False):
new_column_dictionary = column_keys.refurb_wrapper
super().__init__()
self.top_level = None
sel... |
class _DoublyLinkedBase:
''' maintains header and trailer nodes which will always be empty
This is important to make removing and adding new elements on respectively size of one element and zero size easier, without any if conditions
Any element that is added or removed will be having its previ... |
# Databricks notebook source
# MAGIC %md
# MAGIC ScaDaMaLe Course [site](https://lamastex.github.io/scalable-data-science/sds/3/x/) and [book](https://lamastex.github.io/ScaDaMaLe/index.html)
# COMMAND ----------
# MAGIC %md
# MAGIC
# MAGIC ## CNN for MNIST
# MAGIC
# MAGIC Let us move to a classic machine learning ... |
"""
S3 remote with automatic CloudFront invalidation.
Backend module for the remote family of commands.
"""
import boto3
import mimetypes
import re
import urllib.parse
from botocore.exceptions import ClientError, NoCredentialsError, PartialCredentialsError, WaiterError
from operator import methodcaller
from os.path i... |
import torch
import numpy as np
import matplotlib.pyplot as plt
import os, math, random
from PIL import Image, ImageDraw
import torch.utils.data as data
import torchvision.transforms as transforms
class Dataset_CSV(data.Dataset):
def __init__(self, root, list_file, name_file,
size=1025, tr... |
# Copyright 2011-2017 Free Software Foundation, Inc.
#
# This is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This prog... |
import numpy as np
import re
import json
import sys
baseWidth = 5
class Node:
def __init__(self, selfcalled, selftime, childtime, totalpct, name):
self.self_call = selfcalled
self.self_time = selftime
self.child_time = childtime
self.total_pct = totalpct
self.name = name
... |
# ----------------------------------------------------------------------------
# CLASSES: nightly
#
# Test Case: pickNamedArgs.py #
# Tests: queries - Pick using named-arguments
# Pick using query results as arguments
#
# Defect ID: 1781
#
# Programmer: <NAME>
# Date: ... |
# Importing standard Qiskit libraries
from math import pi,sin,cos,asin,acos,sqrt,ceil
from qiskit import QuantumCircuit, execute, Aer, IBMQ
from qiskit.compiler import transpile, assemble
from qiskit.tools.jupyter import *
from qiskit.visualization import *
from qiskit.transpiler import PassManager
from qiskit.transpi... |
import numpy as np
import random
import gym
import torch
from rl_games.common.segment_tree import SumSegmentTree, MinSegmentTree
from rl_games.algos_torch.torch_ext import numpy_to_torch_dtype_dict
class ReplayBuffer(object):
def __init__(self, size, ob_space):
"""Create Replay buffer.
Parameters
... |
# Copyright (c) 2020, Build-A-Cell. All rights reserved.
# See LICENSE file in the project root directory for details.
from biocrnpyler import MassAction, ProportionalHillNegative, ProportionalHillPositive, HillPositive, HillNegative, Hill
from biocrnpyler import GeneralPropensity
from biocrnpyler import ParameterEn... |
"""
Modified from matterport/Mask_RCNN/samples/shapes/
shapes.py
train_shapes.ipynb
"""
import os
import sys
import math
import random
import numpy as np
import cv2
import matplotlib
import matplotlib.pyplot as plt
import json
DATASET_PATH = r"dataset\coco2014"
CLASS_NAME = r"cat"
# Root directory... |
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
import abc
from pymatgen.core.periodic_table import get_el_sp
from monty.json import MSONable
from pymatgen.analysis.structure_matcher import StructureMatcher,\
ElementComparator
from pymatgen.symmetry.ana... |
import json
import pickle
import logging
import pandas as pd
from argparse import ArgumentParser
from tqdm import tqdm, trange
from pathlib import Path
from random import random, randrange, randint, shuffle, choice
from transformers import BertTokenizer
from pregenerate_training_data import DocumentDatabase, truncate_s... |
#!/usr/bin/env python3
#
# Copyright 2018 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 ... |
import math
import torch
from torch import nn
import torch.nn.functional as F
class AAEmbeddings(nn.Module):
def __init__(self, embed_dim):
super(AAEmbeddings, self).__init__()
self.embed_dim = embed_dim
self.onehot = nn.Embedding(21, 21)
self.onehot.weight.data = torch.eye(21)
... |
# Copyright 2014 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
import os, sys, argparse, shutil, hsd
# Global constants
RESTART_DIRNAME = "restart"
COLLECT_DIRNAME = "collect"
ITER_FILENAME = "iter_range.txt"
HSD_FILENAME = "dftb_in.hsd"
XYZ_FILENAME = "geo_end.xyz"
GEN_FILENAME = "geo_end.gen"
CHARGE_FILENAMES = ["charges.bin", "charges.dat"]
OUT_FILENAME = "md.out"
THIS_FILENAM... |
# Copyright 1999 by <NAME>. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
# Patched by <NAME>.
# <NAME> added modifications for work in myGrid
"""Code to invoke the NCBI BLAS... |
#!/usr/bin/env python
"""
Copyright (c) 2018 <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... |
import os, sys, time, pickle, re, py
class BenchmarkFailed(Exception):
pass
PYSTONE_CMD = 'from test import pystone;pystone.main(%s)'
PYSTONE_PATTERN = 'This machine benchmarks at'
PYSTONE_ASCENDING_GOOD = True
RICHARDS_CMD = 'from richards import *;main(iterations=%d)'
RICHARDS_PATTERN = 'Average time per itera... |
#!/usr/bin/env python
"""
ONS Address Index - Create Training Data for the Probabilistic Parser
=====================================================================
A simple script to use AddressBase information to create training and houldout
samples for probabilistic parser.
The script allows to reformat the deliv... |
# -*- coding: future_fstrings -*-
# Presents randomly generated auditory stimuli according to a
# simple switch rule, and asks participants to judge the
# beauty or patterned-ness of those stimuli using a slider.
# Stimuli can be either pure tones or guitar chords, with the
# order of stimulus presentation decided via... |
#Harmony Sample Bank (SBR) format is parsed here. Used by NewWaveAsset to store info about variations and segments.
#SBR files are machine endian.
from struct import unpack,pack
import io
import dbo
def unpackLE(typ,data): return unpack("<"+typ,data)
def unpackBE(typ,data): return unpack(">"+typ,data)
def packLE(typ,d... |
from collections import namedtuple
from sympy import Array, Pow, Rational, S, ones, tensorproduct, zeros
from sympy.tensor.tensor import TensorIndexType
from .partial import PartialDerivative
from .tensor import AbstractTensor, ReplacementManager, Tensor, expand_tensor, indices
class Metric(AbstractTensor, TensorIn... |
import urllib.request
import shutil
import os
import zipfile
import json
from typing import Dict
import requests
import warnings
# returns a path to the dataset file
def download(name: str, verbose: bool = True, data_dir: str = None, use_newest_version: bool = True,
use_local: bool = False) -> str:
""... |
from multiprocessing import Process, Pipe, Queue
import multiprocessing
import gym
from argparse import Namespace
from typing import List, Any
import numpy as np
def get_minigrid_envs(full_args: Namespace, env_wrapper: Any, no_envs: int,
env_seed_offset: int = 10000):
""" Minigrid action 6 i... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
## Made by Psycho - 2018 ##
import settings
import codecs
import json
import os
import paho.mqtt.client as mqtt
import paho.mqtt.publish as mqttPublish
if settings.USE_LEDS:
import pixels
import sys
from threading import Timer
import time
import logging
logging.basicConfi... |
import sys
import gym
import numpy as np
from collections import defaultdict
def initial_policy(observation):
"""A policy that sticks if the player score is >= 20 and his otherwise
Parameters:
-----------
observation:
Returns:
--------
action: 0 or 1
0: STICK
1: HIT
""... |
"""
pint.formatter
~~~~~~~~~~~~~~
Format units for pint.
:copyright: 2016 by Pint Authors, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
import re
from typing import Callable, Dict
from .babel_names import _babel_lengths, _babel_units
from .compat i... |
import logging
import tornado.ioloop
import tornado.web
import tornado.websocket
from message import MessageWriter
from game import CardGame, ScoreKeeper
from cards import Card, HandInfo, PlayerMove
from player import HumanPlayer, Player
class GameServer:
def __init__(self):
self.players = [... |
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache License Version 2.0.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019 Datadog, Inc.
import logging
import os
import json
from datadog_lambda.constants import (
Samp... |
from scipy.sparse import csr_matrix
import numpy as np
from sklearn.cluster import KMeans
import matplotlib
import matplotlib.pyplot as plt
#from matplotlib.path import Path
#import matplotlib.patches as patches
from scipy.spatial import distance
import networkx as nx
import time
#from scipy.interpolate import interp1d... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
import collections
import re
import os
import time
import random
import Pats
raw_sample_path = 'emoji_sample.txt'
def exeTime(func):
def newFunc(*args, **args2):
t0 = time.time()
print("@%s, {%s} start" % (time.strftime("%X", time.localtime()), func.__name__))
back = func(*args, **args2)
... |
from dataclasses import dataclass
import glob
import ntpath
import os
import shutil
import time
import traceback
from typing import Dict, Set, Union
import psutil
from ..utils.logger import get_logger
def filter_least_used_disks(disk_to_copy_processes_count: Dict[str, int]) -> Set[str]:
"""Filters for the least... |
"""
Created on Mon Nov 28 10:10:43 2016
@author: ahefny, zmarinho
"""
import numpy as np
import math
from IPython import embed
class Simulator(object):
def simulate(self, a, env):
return "NotImplementedError"
def reset(self,env):
return env.reset()
class PredictedSimulator(Simulator):
... |
#!/usr/bin/env python3
import os
import sys
import subprocess
import shutil
import hashlib
import argparse
import urllib.request
current_path = os.path.abspath(os.curdir)
# Git Repositories ---------------------------------------------------------------------------------
# Get SHA1: git rev-parse --short=7 HEAD
c... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from itertools import product
import torchvision
import torchvision.transforms as transforms
from torch import Tensor
import numpy as np
from SL2_classes import Vertex, Graph, SL2Element, CayleyGraph
from time import time
INIT_ADJUST = 0.1
class Lat... |
#!/usr/bin/env python
import argparse
import bz2
import gzip
import os.path
import sys
from csvkit import CSVKitReader
from csvkit.exceptions import ColumnIdentifierError
class CSVFileType(object):
"""
An argument factory like argparse.FileType with compression support.
"""
def __init__(self, mode =... |
import io
import textwrap
from collections import namedtuple
import numpy as np
import pandas as pd
import statsmodels.api as sm
from estimagic.config import EXAMPLE_DIR
from estimagic.visualization.estimation_table import _convert_model_to_series
from estimagic.visualization.estimation_table import _create_statistics... |
# Copyright 2013 <NAME>, Univ.Politecnica Valencia, Consejo Superior de
# Investigaciones Cientificas
#
# 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/LI... |
import copy
from typing import Callable, Dict, List, Optional, Tuple
from . import asciiart
class Action:
"""
Generic action class for updating the game state.
"""
def __init__(self, fn: Callable[["QuarantineStatus"], Optional[str]]):
self._fn: Callable[["QuarantineStatus"], Optional[str]] =... |
from typing import List, Optional
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.units import inch
from reportlab.lib.pagesizes import letter, portrait
from reportlab.lib import colors
from reportlab.platypus import Table, Paragraph, Spacer
from reportlab.lib... |
"""
Test koris.cloud.builder
"""
# pylint: disable=redefined-outer-name
import copy
from unittest import mock
from unittest.mock import MagicMock
import pytest
import unittest
from munch import Munch
import koris.cloud.openstack
from koris.cloud.openstack import OSClusterInfo, OSSubnet
from koris.cloud.builder impo... |
import torch
import torch.nn.functional as F
import argparse
import cv2
import numpy as np
from glob import glob
import matplotlib.pyplot as plt
num_classes = 10
img_height, img_width = 28, 28
channel = 1
GPU = False
torch.manual_seed(0)
# GPU
device = torch.device("cuda" if GPU else "cpu")
class Generator(... |
from argparse import ArgumentParser
import os
import copy
import gzip
import logging
from collections import OrderedDict, defaultdict, Counter
from singlecell.utils import file_transaction
logger = logging.getLogger()
class readsInWell:
def __init__(self, g, d):
self.gene = g
self.umi = d
def g... |
# -*- coding: utf-8 -*-
"""
Functions to measure the synchrony of several spike trains.
Synchrony Measures
------------------
.. autosummary::
:toctree: toctree/spike_train_synchrony/
spike_contrast
:copyright: Copyright 2015-2020 by the Elephant team, see `doc/authors.rst`.
:license: Modified BSD, see LI... |
from torch.nn.modules import batchnorm
from font2img import draw_single_char
from model import Zi2ZiModel
from PIL import Image, ImageDraw, ImageFont
import torchvision.transforms as transforms
import torch.nn as nn
import PIL
import os
import pandas as pd
import torch
from torch.utils.data import DataLoader, TensorDa... |
#!/usr/bin/python
from __future__ import print_function
#from subprocess import Popen, PIPE
from subprocess import check_output, CalledProcessError, STDOUT
from datetime import datetime
import json
import logging
import pdb
import os
import shlex
import sys
import argparse
def parseargs():
parser = argparse.Argume... |
"""
contain model handling functions:
evaluate, load, update
"""
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
import tensorflow as tf
import numpy as np
import time
def generate_session(graph = None):
"""
Generat session using the graph
"""
if graph is not None:
sess = tf.Session(graph = graph)
else:
s... |
# CUMMULATIVE PROFESSIONAL DEVELOPMENT ALLOWANCE
from .utils import *
def handle_cpda_admin(request):
app_id = request.POST.get('app_id')
status = request.POST.get('status')
reviewer = request.POST.get('reviewer_id')
designation = request.POST.get('reviewer_design')
remarks = request.POST.get('rem... |
# -*- coding:Utf-8 -*-
#------------------------------------------------------------------------------
# Author: <NAME>
# Name: main.py
# Purpose: Logiciel de traitement d'image au format PBM, PGM ou PPM
# Created: 12/12/2021
# Python: 3.10
# Modules: traitement, support
# Licence: Creative Commons BY NC SA
#-----... |
# high res ocean regions
import numpy as np
import xarray as xr
from xr_DataArrays import example_file, depth_lat_lon_names
from paths import path_samoc
from paths import file_ex_ocn_rect, file_RMASK_ocn, file_RMASK_ocn_rect, file_RMASK_ocn_low
ocn_file = example_file('ocn')
bll_AMO = (( 0, 60), (- 80, 0)) # (... |
import json
from urllib.request import Request, urlopen
test_json = """{"study_sessions": [{"timestamp": 5, "start": 400, "duration": 45, "rating": 1, "time_before:": 15},
{"timestamp": 3, "start": 500, "duration": 60, "rating": 2, "time_before:": 50}], "times_free": [[300, 500], [600, 800],
[900, 1000]]} """
"""
{... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.