text
stringlengths
3.07k
22.1k
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : <NAME> # @Contact : <EMAIL> from copy import deepcopy from fractions import Fraction from typing import Dict, Optional, Union, List import numpy as np from ConfigSpace import ConfigurationSpace, Constant, CategoricalHyperparameter, Configuration from Config...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import numpy as np import scipy def _handle_negative_axis(axis, tensor_rank): return axis + tensor_rank if axis < 0 else axis def _size_helper(shape, start, end): size = shape[start] for i in range(start + 1, end): size *=...
# -*- coding: utf-8 -*- # Copyright (c) 2020, <NAME> and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import cstr from frappe.model.document import Document import json from frappe.core.doctype.version.versio...
import collections import gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim USE_WANDB = False # if enabled, logs data on wandb server class ReplayBuffer: def __init__(self, buffer_limit): self.buffer = collections.deque(maxlen=buffer_li...
import logging import re import torch as th from torch import nn from pgc_torch.conf import CONV_DIM, CONV_BACTH_NOR from pgc_torch.errors import ConfigError, ObjectTypeError logger = logging.getLogger('django') def set_conv_dim(): mapping = { 1: (nn.Conv1d, nn.BatchNorm1d, nn.MaxPool1d, nn.AvgPool1d),...
""" Test CBlocks functionality. """ # pylint: disable=missing-docstring, no-self-use, protected-access # pylint: disable=invalid-name, redefined-outer-name, unused-argument, unused-variable # pylint: disable=wildcard-import, unused-wildcard-import import pytest import edzed from .utils import * def test_connect_o...
import requests import json from bs4 import BeautifulSoup import csv BASEURL = 'https://www.transfermarkt.com/' def loadJson(name): CACHE_FNAME = str(name) + '.json' try: cache_file = open(CACHE_FNAME, 'r') cache_contents = cache_file.read() CACHE_DICTION = json.loads(cache_contents) ...
from __future__ import annotations from dataclasses import * from typing import * from .moves import Move import re import socket from . import gripper prelude = ''' # Set TCP so that RPY makes sense set_tcp(p[0, 0, 0, -1.2092, 1.2092, 1.2092]) set_gravity([0.0, 0.0, 9.82]) set_payload(0.1) gl...
import math import os import warnings from collections import OrderedDict from os.path import abspath from shutil import copyfile import torch import yaml from jinja2 import Environment import aggregator as module_constructor from base.container import Container from base.properties import Tensor from utils import pr...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ gaetk2.tools.caching - based on huTools.decorators and gaetk1/tools.py Created by <NAME> on 2007-05-10. Copyright (c) 2007, 2015, 2018 HUDORA GmbH. All rights reserved. """ from __future__ import absolute_import from __future__ import unicode_literals import threading...
# -*- coding: utf-8 -*- # ########################## Copyrights and license ########################## # # # # Copyright 2020 <NAME> <<EMAIL>> # # ...
from __future__ import print_function import logging from unittest import SkipTest from couchbase_core.analytics import AnalyticsRequest from couchbase_tests.base import RealServerTestCase, version_to_tuple from parameterized import parameterized import json import time import copy from couchbase_core import JSON fro...
from __future__ import division, print_function from hscom import __common__ (print, print_, print_on, print_off, rrr, profile, printDBG) = __common__.init(__name__, '[mc3]', DEBUG=False) # Science import numpy as np # HotSpotter from hscom import params from hscom import helpers as util import DataStructures as ds im...
import tempfile import os from PIL import Image from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Product, Category from category.serializers import Prod...
from django.contrib.auth.models import User from django.db import DatabaseError, transaction from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from usermanagement.views import get_random_alphanumeric_string, check_if_user_is_logged, get_respon...
from typing import List, Tuple, Optional from enum import Enum import subprocess import re import time from colorama import Fore from test_base import TestData from tests import TestSet import os.path class TestResult(Enum): PASSED = 1 FAILED = 2 IGNORED = 3 TestColors = { TestResult.PASSED: Fore.G...
import json, collections, os, glob, sys import local_utilities as lu BASE_DIR = '/badc/cmip6/data/' ##`CMIP/E3SM-Project/E3SM-1-1-ECA/piControl/r1i1p1f1/Lmon/mrsos/gr/v20191218/mrsos_Lmon_E3SM-1-1-ECA_piControl_r1i1p1f1_gr_195001-195912.nc TEMPLATE = '%(base)s/%(era)s/%(mip)s/%(inst)s/%(model)s/%(expt)s/%(variant)s/...
""" server.py Implementation of the deep learning server. """ import time import dataclasses import logging import grpc import uuid import asyncio import multiprocessing import numpy as np import configparser from scipy.io import wavfile from pathlib import Path from collections.abc import Sequence from dlserver.label...
import torch from torch import nn import numpy as np import math from matplotlib import pyplot as plt import os seed = 0 torch.manual_seed(seed) def HO_loss(x1, y1, x2, y2): loss = nn.MSELoss() return 2.*loss(x1, y1) - loss(x2, y2) def test_LOSS(x1, y1, x2, y2): loss = nn.MSELoss() return torch.sqrt(...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: DQN.py # Author: <NAME> <<EMAIL>> import numpy as np import tensorflow as tf import os import sys import re import time import random import argparse import subprocess import multiprocessing import threading from collections import deque from tensorpack import * ...
import tensorflow.compat.v1 as tf import tensorflow_addons as tfa import numpy as np import gym import logging import copy from tensorflow.compat.v1 import layers class Policy(object): def reset(self, **kwargs): pass def act(self, observation): # should return act, info raise NotImpl...
import logging from abc import ABC from os import path from jmeter_api.basics.element.elements import BasicElement from jmeter_api.basics.utils import Renderable, tree_to_str class BasicListener(BasicElement, ABC): def __init__(self, name: str = 'BasicElement', comments: str =...
""" build layer Programmer: <NAME> Date: 2021.3 """ import inspect import platform import torch.nn as nn import torch.nn.functional as F if platform.system() == 'Windows': import regex as re else: import re from dl_toolbox_cwm.model.utils import xavier_init from dl_toolbox_cwm.model.utils.core.misc import is_tu...
''' Written by <NAME> (<EMAIL>) Github repository: https://github.com/tmunzer/Mist_library/ ''' import mlib as mist_lib from mlib import cli import requests import time from geopy import Nominatim from tzwhere import tzwhere try: from config import log_level except: log_level = 6 finally: from mlib.__debu...
from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.core.urlresolvers import reverse_lazy, reverse from django.core import serializers from cStringIO import StringIO from reportlab.platypus.flowables import Image from reportlab.pdfgen import canvas from reportlab.l...
#!/usr/bin/python3 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # ##### #### #### #### # This file is managed by juju. Do not make local changes. # Copyright (C) 2009, 20...
# coding: utf-8 # https://docs.google.com/spreadsheets/d/1aCIRyol3UncEtstWhT_Yw3I8mCbvpGQU5_HUKB_0JFA/edit#gid=0 属性 # https://docs.google.com/spreadsheets/d/1aCIRyol3UncEtstWhT_Yw3I8mCbvpGQU5_HUKB_0JFA/edit#gid=2013091340 検査 # https://docs.google.com/spreadsheets/d/1aCIRyol3UncEtstWhT_Yw3I8mCbvpGQU5_HUKB_0JFA/edit#gid=...
""" track.py tester code. Part of glbase Tests that track is performing accurately. TODO: ----- . some of the tests are not very extensive yet. . There is a bug, whereby the order of the retrieved reads is random. Making the test erroneously fail. . The /tmp/ stuff is platform specific """ import unittest # get g...
import socket import time import sys name_list = [] name_map = {} name_database = {} dns_quest_id = 0 default_RTT = 0.5 local_ip = "192.168.1.1" local_port = 10000 dhcp_ip = "192.168.2.1" dhcp_port = 10000 # read dns table file def read_dns_table(filename="dns_table.txt"): global name_list global name_map ...
''' Created on Sep 25, 2014 @author: <NAME> (Acsone S. A.) (c) Copyright 2014 Acsone S. A., All rights reserved. ''' from arelle.RenderingResolver import resolveAxesStructure from arelle.ModelFormulaObject import Aspect, aspectModels, aspectModelAspect from arelle.FormulaEvaluator import aspectMatches from arelle.Mod...
""" Utility classes for C++ name mangling (Itanium C++ ABI) https://mentorembedded.github.io/cxx-abi/abi.html """ __author__ = "<NAME>" __copyright__ = "Copyright 2016, <NAME>" __credits__ = ["<NAME>"] __license__ = "MIT" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" class Name(object)...
#!/usr/bin/python # -- Content-Encoding: UTF-8 -- """ Tests remote services discovery using the JSON-RPC transport :author: <NAME> :copyright: Copyright 2020, <NAME> :license: Apache License 2.0 .. Copyright 2020 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this...
""" new importer to use with MultiChannelEEGDataset """ __author__ = 'sstober' import os import glob import csv import math import logging log = logging.getLogger(__name__) import numpy as np import theano from pylearn2.utils.timing import log_timing from deepthought.util.fs_util import save, load from deepthought....
"""Defines vanilla CNNs with torch backbones, mainly for patch classification.""" import numpy as np import torch import torch.nn as nn import torchvision.models as torch_models from tiatoolbox.models.abc import ModelABC from tiatoolbox.utils import misc def _get_architecture(arch_name, pretrained=True, **kwargs): ...
"""Validation functions for scenario config files. Provides: * :cls:`ConfigValidationError` * :func:`validate_scan_scenario_config` * :func:`validate_webscraped_scenario_config` Both functions return an error message that can be used to raise an exception. The intention is that the messages from all scenario configs...
# Steps here: # # - Find all good cascades: # 1. Synthesis time is greater than 1 hour. # 2. Synthesis temperature is greater than 500 degC. # 3. Target composition is not interpolated. # - Compute features import pickle from argparse import ArgumentParser from collections import Counter, defaultdict from ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2014 uralbash <<EMAIL>> # # Distributed under terms of the MIT license. """ Functional tests for views """ from .conftest import User, Group, Tree def is_table_exist(table_name, engine): return engine.dialect.has_table(engine.connect...
import threading import json import logging import os import random import threading from typing import Optional, List, Dict, Tuple from mutagen.mp3 import HeaderNotFoundError from prometheus_client import Gauge from utils import get_mp3_info, remove_links from .models import Song def get_files_in_dir(directory): ...
""" Functions to train the neural networks """ from collections import deque import re import logging import h5py import pandas as pd import numpy as np from sklearn.metrics import confusion_matrix from Bio import SeqIO import torch.optim as optim import torch from coconet.core.torch_models import CompositionModel,...
import csv import decimal import json import os import statistics from pathlib import Path import numpy as np import sys from FeatureGeneration.CalPeaks import cal_peaks from FeatureGeneration.GetTimeStampsPeaks import get_timestamps_peaks ED = 10000 def generate_binned_distribution(data): ''' method to ge...
# Python Standard Libraries import argparse from pprint import pprint import re from math import * # Third Party Libraries import pynmea2 import simplekml from haversine import haversine PATH_LINESTYLE_COLOR = 'Af00ffff' PATH_LINESTYLE_WIDTH = 6 PATH_POLYSTYLE_COLOR = '7f00ff00' STOP_ICONSTYLE_COLOR = simplekml.Colo...
# Author: <NAME>, <<EMAIL>>, Institute of Physics, Chinese Academy of Sciences # Adapted from the kdotp-symmetry package by: <NAME> <<EMAIL>> © 2017-2018, ETH Zurich, Institut für Theoretische Physik """ Utilities for handling symmetry representations, such as converting them to matrix form. """ import numpy as np im...
import math import os from copy import deepcopy import numpy as np from Animator.clustering_methods import c_dbscan, c_optics from Animator.cluster_logic import CharacterConsolidator from Animator.cluster_logic import ConsolidationEvaluator def my_simple_clustering(ids, features, frame_ids): """ Binary sear...
import unittest,subprocess,os,wsgikit,signal,time,json,urllib from urllib.request import urlopen from urllib.request import Request import mimetypes def encode_multipart_formdata( fields = None, files = None): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (...
# coding: utf-8 from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( clean_html, determine_ext, ExtractorError, extract_attributes, get_element_by_class, get_element_html_by_id, HEADRequest, parse_qs, unescapeHTML, unified_ti...
#!/usr/bin/env python3 """ This file is part of pynadc https://github.com/rmvanhees/pynadc Defines class ArchiveGosat2L2 to add new entries to GOSAT-2 SQLite database Copyright (c) 2021 SRON - Netherlands Institute for Space Research All Rights Reserved License: BSD-3-Clause """ import argparse import sqlite3 ...
# ! /usr/bin/env python """ __author__ = <NAME> __email__ = <EMAIL> __date__ = 08/02/2018 """ import pysam import time from src.handlefiles import save_objects from src.snps import load_VCF ############################# # Human Imprinted Regions # ############################# class ImprintedRegion: def __init_...
import pickledb import sqlite3,json,os def genunit(): global unitdb unitdb=pickledb.load(unitfn,False) dat=json.loads('{"usd":["$",["dollar","dollars"],"¢",[100,"cent","cents"]],"eur":["€",["euro","euros"],"¢",[100,"cent","cents"]],"gbp":["£",["pound","pounds"],"p",[100,"pence",null]],"jpy":["¥",["yen",nul...
''' Attempt at a tree recursive neural network ''' import argparse import tensorflow as tf import numpy as np class SimpleTreeLayer(tf.keras.layers.Layer): def __init__(self, dim, just_root_output=True, *args, **kwargs): super(SimpleTreeLayer, self).__init__(*args, **kwargs) self.dim = dim ...
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ------------------------------------------...
# -*- coding: utf-8 -*- import re import sys import traceback import requests from sqlalchemy import Column, Integer, String, ForeignKey, MetaData, Table from monitorrent.db import row2dict from monitorrent.plugin_managers import register_plugin from monitorrent.plugins import Topic, Status from monitorrent.plugins.t...
""" Created on Mon Jan 28 23:08:26 2019 @author: NickT """ from pymatgen import MPRester import pandas as pd import matplotlib.pyplot as plt import csv import multiprocessing as mp import pickle import tqdm import time mat_api_key = '<KEY>' mpr = MPRester(mat_api_key) print("Loading Compounds....") all_compounds =...
import re from argparse import Namespace import os import torch from models import SurnameClassifier from text_preparation import SurnameDataset import torch.nn as nn import torch.optim as optim from models import generate_batches, make_train_state, set_seed_everywhere, handle_dirs, \ update_train_state, compute_a...
from graphics import * import time A=0x001 B=0x002 C=0x003 D=0x004 E=0x005 F=0x006 G=0x007 DP=0x008 dictionary={ 0:[A,B,C,D,E,F], 1:[B,C], 2:[A,B,G,E,D], 3:[A,B,G,C,D], 4:[F,G,B,C], 5:[A,F,G,C,D], 6:[A,F,G,C,D,E], 7:[A,B,C], 8:[A,B,C,D,E,F,G], 9:[G,F,A,B,C,D] } switchMan={ #basic format preDig:{0:[energize],[...
import dash_bootstrap_components as dbc import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, State, MATCH, ALL import dash_apps.shared_components as dsc from dash_apps.shared_styles import * from dash_apps.apps.myapp import app import dash from engine impor...
""" This script demonstrates the following: - How to scan a target host for known ports and other port ranges from 0 - 65536 My primary focus while coding this script is LEARN how to program in Python. It is NOT my intention to cause any harm to 3rd parties (people and/or organizations) Example: python po...
"""Map objects, the parts of a map that aren't part of a tile grid """ from __future__ import division from tmxlib import helpers, tile, draw NOT_GIVEN = object() class MapObject(helpers.LayerElementMixin): """A map object: something that's not placed on the fixed grid Has several subclasses. Can b...
import json import os, sys, backoff, math from datetime import datetime from random import randint from gremlin_python import statics from gremlin_python.process.traversal import Pop from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection from gremlin_python.structure.graph import Graph from g...
import logging import os import shutil import signal import sys import atexit import time import json from pathlib import Path import click import psutil from flask import Config from ..config import DEFAULT_CONFIG logger = logging.getLogger(__name__) class Echo: def __init__(self, quiet): self.quiet =...
# %% [markdown] # # Imports import os import pickle import warnings from operator import itemgetter from pathlib import Path from timeit import default_timer as timer import colorcet as cc import matplotlib.colors as mplc import matplotlib.pyplot as plt import networkx as nx import numpy as np import pandas as pd impo...
"""Utilities for constructing a metric """ import functools import itertools from typing import Tuple, Union, List import sympy from sympy import Function, sin, Expr, Array, Derivative as D, MatrixBase, Matrix, Symbol from sympy.diffgeom import twoform_to_matrix from sympy.printing.latex import latex from pystein i...
from typing import List, Optional, Tuple from docutils import nodes from docutils.parsers.rst import directives from sphinx import addnodes from sphinx.application import Sphinx from sphinx.util.docutils import ReferenceRole, SphinxDirective, SphinxRole from sphinx_design.shared import SEMANTIC_COLORS, make_choice, t...
#!/usr/bin/python # qlearn.py : simple discrete, deterministic Q-learning # # Requires: numpy, pandas, matplotlib # # <NAME> # <EMAIL> # # 2021. 02. 17. (wed) 09:00:58 KST # 2021. 02. 18. (thu) 00:09:00 KST # # Getting started: # # - pick between "console" mode (for command line) or "notebook" mode (for colab, etc)....
import datetime import math import mpyq import binascii import requests import struct from pathlib import Path from io import BytesIO from importlib import import_module from typing import Dict from zephyrus_sc2_parser.events import ( ObjectEvent, AbilityEvent, SelectionEvent, ControlGroupEvent, Upg...
import urllib3 import io import gzip import csv import logging import pprint import collections from pyramid.view import view_config from sqlalchemy.sql import text from elasticsearch.exceptions import ( NotFoundError ) from snovault import DBSESSION, COLLECTIONS from snovault.storage import ( TransactionRecord...
import warnings from complexity_considerations_package.binary_layer import BinaryConv2D import config if config.tf: from tensorflow.keras.layers import (GlobalAveragePooling2D, GlobalMaxPooling2D, Dense, multiply, add, Permute, Conv2D, ...
# -*- coding: utf-8 -*- from collections import OrderedDict from decimal import Decimal import textwrap from django.conf import settings from django.core import signing from django.db import transaction, models from django.db.models import Count from django.http import HttpResponseRedirect from django.http.response im...
#!/usr/bin/env python3 """ Generate El Null Range product from L0B (DM2) + Antenna HDF5 + [DEM raster] data which will be used for pointing analyses by D&C team """ import os import time import argparse as argp import numpy as np from datetime import datetime from nisar.products.readers.Raw import Raw from nisar.produ...
#!/usr/bin/env python3 import unittest, os from util.securechannel import SecureChannel, SecureError from util import secp256k1 AID = "B00B5111CE01" APPLET = "toys.BlindOracleApplet" CLASSDIR = "BlindOracle" mode = os.environ.get('TEST_MODE', "simulator") if mode=="simulator": from util.simulator import Simulator...
import os from enum import Enum from copy import deepcopy from random import shuffle, seed, randint import h5py import numpy as np from scipy.io import loadmat from mne.filter import resample from matplotlib import pyplot as plt from math import sqrt EEG_SAMPLE_RATE = 500 # Hz class Formats(str, Enum): ttc = "tt...
import pytest from unittest import TestCase from mock import Mock, call, ANY from samtranslator.model.exceptions import InvalidResourceException from samtranslator.model import PropertyType, Resource, SamResourceMacro, ResourceTypeResolver from samtranslator.intrinsics.resource_refs import SupportedResourceReferences ...
from rpython.rlib import jit from topaz.coerce import Coerce from topaz.closure import LocalCell from topaz.objects.arrayobject import W_ArrayObject from topaz.objects.hashobject import W_HashObject from topaz.objects.functionobject import W_FunctionObject class BaseFrame(object): _attrs_ = ["backref", "escaped"...
# Copyright 2019 The Glow Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
# REQUIREMENTS = ['wideq'] # DEPENDENCIES = ['smartthinq'] import json import logging import voluptuous as vol from datetime import timedelta import time from .wideq.device import ( OPTIONITEMMODES, STATE_OPTIONITEM_ON, STATE_OPTIONITEM_OFF, DeviceType, ) from .wideq.washer import WasherDevice from ...
# coding: utf-8 # Generate random groupings of 3-5 members for each group, irrespective # of technology and category preferences # Created by <NAME> (2021) import slack import ast import settings import config import math import secrets from slackers.hooks import commands from typing import Generator, Callable, List ...
# -*- coding: UTF-8 -*- """ .. --------------------------------------------------------------------- ___ __ __ __ ___ / | \ | \ | \ / the automatic \__ |__/ |__/ |___| \__ annotation and \ | | | | \ ...
import pytest import typing import numpy as np import pandas as pd import psm def test_import(): assert hasattr(psm, 'models') assert hasattr(psm, 'utils') def test_invalid_model_name(): """Should get ValueError when calling different name than '1_region' or '6_region.""" with pytest.raises(ValueErr...
################################################################################ # # MIT No Attribution # # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the...
import os def static(): path = './train2id.txt' head_dic = {} tail_dic = {} cnt = 0 with open(path, 'r') as f: for raw in f.readlines(): raw = raw.strip().split(' ') try: head, tail, r = raw if head not in head_dic.keys(): ...
from typing import Optional, Dict, Tuple, List from time import time import pandas as pd import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer from sklearn.model_selection import cross_validate, GridSearchCV from sklearn.preprocessing import LabelEncoder, FunctionTransfor...
# Run detection in real-time setting on a COCO-format dataset # profiling version import argparse, json, pickle from os.path import join, isfile, basename from glob import glob from time import perf_counter from tqdm import tqdm import numpy as np import torch from pycocotools.coco import COCO imp...
# Copyright 2021 The Bellman Contributors # # 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...
import datetime import gc import os import random import time import warnings import cv2 import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter from torch.utils.data import DataLoader, Dataset, WeightedRandomSampler from torch....
from base64 import (b16decode, b16encode, b32decode, b32encode, b64decode, b64encode, urlsafe_b64decode, urlsafe_b64encode) from binascii import hexlify, unhexlify from bz2 import decompress as bz2decompress from concurrent.futures import ThreadPoolExecutor from functools import wraps from hashlib ...
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% from dataclasses import dataclass from typing import List, Tuple, Dict, Optional from datetime import date from datetime import timedelta from pathlib import Path import click import pandas as pd import numpy as np from scipy.st...
import os import requests import json from django.core.management.base import BaseCommand, CommandError from django.utils import timezone from django.db.models import Q from scanner.models import Contact, Attendance, ParticipantStatusType from scanner.conf import settings CIVICRM_API_DRYRUN_ENVVAR = 'CIVICRM_API_DRY...
import obd from obd import OBDStatus import math import time import sys import colorama import re import os from tabulate import tabulate import tkinter from tkinter import * from tkinter import messagebox colorama.init() #initialize colorama print("\x1b[2J", end="\r") #ASCII escape sequen...
import cv2 import numpy as np def resize_image(img, new_width, new_height): """Resize image to a ``new_width`` and ``new_height``. Args: img (np.array): An image. new_width (int): New width. new_height (int): New height. Returns: np.array: A resized image. ...
""" Script to run validation using qcsubmit on dataset_fragments.json files """ import copy import json import os import glob from argparse import ArgumentParser import pandas as pd from github import Github from openff.qcsubmit.datasets import (BasicDataset, OptimizationDataset, ...
''' generates input data for pipeline producing four files attributes, samples, values and coexistences see ./docs/documentation.md for details This version: Creates coexistances.csv directly avoiding doing this via a json file. This is better because the converter was build with regex and was less robust. Does not ...
""" A Mixture Density Layer for Keras cpmpercussion: <NAME> (University of Oslo) 2018 https://github.com/cpmpercussion/keras-mdn-layer Hat tip to [Omimo's Keras MDN layer](https://github.com/omimo/Keras-MDN) for a starting point for this code. ---------------------------------------------------------------------- Mo...
import subprocess import time, sys import json from collections import defaultdict import copy import os import importlib import argparse import re ### helpers def flatten(d, prefix="", target={}, sep=";"): for k,v in d.items(): if isinstance(v, dict): flatten(v, prefix+sep, target); else: target[prefix+k]...
import numpy as np from scipy import stats import scipy.io as sio import os import torch from torch import nn from dataloader import Data_Loader import util import torch.utils.data from torchfoldext import FoldExt import sys import json import partnet as partnet_model with open('./part_color_mapping.json', 'r') as f: ...
# -*- coding: utf-8 -*- import os import sys import random import numpy as np from skimage import io import chainer from skimage import io from skimage import transform as tr def read_img(path, arr_type='npz'): """ read image array from path Args: path (str) : path to directory which images a...
import os from collections import OrderedDict, namedtuple from itertools import chain from gooey.gui.lang.i18n import _ from gooey.gui.util.quoting import quote import wx ArgumentGroup = namedtuple('ArgumentGroup', 'name command required_args optional_args') class MyWidget(object): # TODO: Undumbify d...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Dict, List, Optional, Callable import torch.optim from . import ClassyOptimizer, register_opt...
import asyncio import functools import io import json from time import strftime import aiohttp import discord import prettytable from discord import member from PIL import Image, ImageDraw, ImageFont from sqlalchemy.orm import sessionmaker from src.model.chapter import Chapter async def get_roles(member: discord.Me...
# pylint: disable=redefined-outer-name # pylint: disable=too-many-arguments # pylint: disable=unused-argument # pylint: disable=unused-variable from copy import deepcopy from pathlib import Path from typing import ( Any, AsyncIterable, AsyncIterator, Callable, Dict, List, Optional, Type...
import requests import re from Crypto.Cipher import AES from queue import Queue import threading import time import datetime import os import sys class MediaPart: def __init__(self, url, time_len, cryptor): self.url = url self.filename = url.split('/')[-1].replace('+', '_') if len(self.fil...
import pygame import constants import os, sys import utils # from environment import Walkables, Obstacles from environment import Environment # ------------------------------------------------------ # class Player # ------------------------------------------------------ class Player(pygame.sprite...