text
stringlengths
3.07k
12.6k
""" Created on Apr 4, 2014 @author: rgeorgi """ # Built-in imports ------------------------------------------------------------- import os, sys, re import subprocess as sub from io import StringIO # Set up logging import logging MAXENT_LOG = logging.getLogger('CLASSIFIER') # Internal Imports ------------------------...
#The following script is designed to read a CSV file with data in a correct format (this is important; more below), alter a PowerWorld simulation accordingly and run it and store the desired outputs (types and locations are hard-coded into the script) in another CSV file. The input files must be formatted in the follow...
"""More efficient implementation of infiniteroad_simulation which only partially simulates vehicles.""" import havsim.simulation as hs import havsim.plotting as hp import time import numpy as np #%% set up parameters IDM_parameters = [30, 1.5, 4, 1.3, 2] # in order: max speed, time headway, jam spacing, comfortable...
import torch.nn as nn import torch import numpy as np from collections import OrderedDict def dense_flops(in_neurons, out_neurons): """Compute the number of multiply-adds used by a Dense (Linear) layer""" return in_neurons * out_neurons def conv2d_flops(in_channels, out_channels, input_shape, kernel_shap...
#!/usr/bin/env python import numpy as np import pandas as pd from numpy.random import randint import tflearn import tensorflow as tf from evaluate_model import * from tf_model_component import * from sklearn.model_selection import train_test_split import math #import cPickle import pickle import sys from resnext_model...
#! python3 # PostRipProcess.py - script run by dBpoweramp CD Ripper after a CD has # been ripped. # # * Rename the .CUE file to use the album title # * Run the CheckFlacTags script to look for metadata problems. # This script needs to know where the album was ripped after the rip process # completes. Since this scri...
# This is a sample Python script. # Press Shift+F10 to execute it or replace it with your code. # Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings. import os.path import re import urllib.request import urllib.error import urllib.parse import time import logging ...
import datetime import numpy as np import pandas as pd import pathlib from sklearn.linear_model import LogisticRegression from sklearn.metrics import roc_auc_score import gust from utils import graph_util def evaluateLinkPrediction(AdjMat,embedding_method, round_id, train_ratio, train_epochs, eval_epochs,edge_emb_met...
import random from unidecode import unidecode from gensim.models import Word2Vec import torch from torch.autograd import Variable from torch import nn import torch.nn.functional as F from torch import optim f = open("grimms.txt") text = unidecode(f.read()).lower() sentences = text.split('.') for i in range(len(sentenc...
import os import torch import pickle import gensim import numpy as np import pandas as pd from config import model_config as config from gensim.scripts.glove2word2vec import glove2word2vec from sklearn.metrics import confusion_matrix, accuracy_score, f1_score, precision_score, recall_score import itertools import mat...
# # 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, software # distributed under...
from pycket.prims.expose import (unsafe, default, expose, expose_val, procedure, make_call_method, define_nyi) from pycket import values, values_string, values_regex from pycket.error import SchemeException from rpython.rlib import jit import sys @expose("regexp", [values_string.W_Str...
import os import time import sys import re import json import pandas as pd from selenium import webdriver import selenium.webdriver.chrome.service as service from selenium.webdriver.support.ui import Select from pandas_datareader.data import Options import requests_cache #############################################...
from typing import Mapping, List, Optional, Callable from baretypes import ( Scope, Info, RouteMatches, Content, HttpRequestCallback, HttpResponse ) import bareutils.header as header from bareutils.streaming import ( Compressor, compression_writer_adapter, make_deflate_compressobj, ...
import numpy as np import matplotlib import matplotlib.pyplot as plt import seaborn as sns """ Some notations: d = number of features including W_0 n = number of observations """ def prepare_X(X:np.ndarray, degree:int = 1)-> np.ndarray: ''' Expands X as per degrees and appends a column of ones in ...
import cv2 import numpy as np import tensorflow as tf INPUT_SIZE = 512 # input image size for Generator ATTENTION_SIZE = 32 # size of contextual attention def sort(str_lst): return [s for s in sorted(str_lst)] def reconstruct_residual_from_patches(residual, multiple): """reconstruct residual from patches...
import datetime import pickle import pytest from pyrsistent import CheckedPVector, InvariantException, optional, CheckedValueTypeError, PVector class Naturals(CheckedPVector): __type__ = int __invariant__ = lambda value: (value >= 0, 'Negative value') def test_instantiate(): x = Naturals([1, 2, 3]) ...
from math import ceil import numpy as np import tensorflow as tf from keras import backend as K from tensorflow.contrib import distributions from keras.utils.generic_utils import get_custom_objects from keras.models import Model, load_model from keras.layers import Layer, Input # Bayesian categorical cross entropy. #...
#!/usr/bin/python #birchcanoe.py ''' Generates novels and their accompanying audio based on phonetically-optimal English sentences. #NaNoGenMo2017 Uses the Harvard Sentences - see http://ieeexplore.ieee.org/document/1162058/ The overall goal is to use these sentences as seeds for each chapter. Next steps: * Build s...
""" """ import numpy as np from astropy.utils.misc import NumpyRNGContext from halotools.empirical_models import conditional_abunmatch from .probabilistic_binning import fuzzy_digitize from .sigmoid_g_minus_r import g_minus_r from .sigmoid_r_minus_i import r_minus_i from .sigmoid_g_minus_r import quiescent_fraction_g...
from core.arissploit import * from core import colors import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import socket import random from string import ascii_lowercase conf = { "name": "email_bomber", "version": "1.0", "shortdesc": "Spam email to target email.", "aut...
from datetime import datetime from django.contrib.auth.models import User from django.db import models from django.utils.translation import gettext_lazy as _ app_name = 'proj' PROJ = 'projects' EXPN = 'expenses' class Projects(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, verbose_na...
import pandas as pd import os import subprocess import tempfile from inference_results import InferenceResults from config import Config from dataset import get_synth_dataset from ranked_list import RankedList import re from typing import List, Tuple, Any import javalang from source_code_utils import get_source_code, ...
# -*- coding:utf-8 -*- import copy from typing import List, Tuple, Dict from tensorflow.lite.python.interpreter import Interpreter import cv2 import numpy as np import streamlit as st import tensorflow as tf TYPE_INT8 = "INT8" TYPE_FLOAT16 = "FLOAT16" MODEL_TYPE = (TYPE_INT8, TYPE_FLOAT16) MODEL_PATH = {TYPE_INT8: ...
# -*- coding: UTF-8 -*- import csv import math import operator import random import numpy as np import pandas as pd import os from math import exp import math import sklearn from sklearn import svm from sklearn.model_selection import train_test_split basedir = os.path.abspath(os.path.dirname(__file__)...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2021, Intel Corporation. All rights reserved. # SPDX-License-Identifier: BSD-2-Clause # """A helper script to simplify MAC address capsule """ import sys import os import argparse import glob import uuid sys.path.insert(0, os.path.dirname(os.path.dirna...
import tensorflow as tf # import tensorflow.compat.v1 as tf import numpy as np from . import gpt2parallelize from . import original_gpt2 import argparse import json class ReArrange(object): """ Map original model weights to our tf.keras model weights. """ @classmethod def Embedding(cls, weights): ...
# coding=utf-8 from django.db import models from django.contrib.auth.models import AbstractUser import base64 import random class BookHotestManager(models.Manager): def get_hotest_books(self): """ 获取当前最热门的书籍 :return: """ return super(BookHotestManager, self).get_queryset()[...
import numpy as np from scipy.ndimage import convolve, gaussian_filter def _funcGradientIndicator(x, alpha=2, sigma=1): ''' Return gradient indicator ''' # Apply gaussian kernel x = gaussian_filter(x, sigma) # Calc gradients pad = np.pad(x, pad_width=1, mode="edge") ...
print("\nArduboy flash cart writer v1.12 by Mr.Blinky May-Sep. 2018\n") #requires pyserial to be installed. Use "python -m pip install pyserial" on commandline import sys import time import os from serial.tools.list_ports import comports from serial import Serial compatibledevices = [ #Arduboy Leonardo ...
#!/usr/bin/env python # # <NAME>, <EMAIL> # 2019-02-25 # ref smoothGrad import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import grad,Variable import numpy as np class SmoothGrad(object): def __init__(self, model, device='cpu', only_seq=False, train=False, x_stddev=0...
import re from nltk.corpus import stopwords from nltk.stem.porter import PorterStemmer import pandas as pd import emoji import string from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS from sklearn.model_selection import train_test_split def preprocessing(dataset, column): """[This function prepr...
from typing import Any, Dict, List, Optional, TYPE_CHECKING import re import numpy as np from catalyst.core.logger import ILogger from catalyst.settings import SETTINGS if SETTINGS.mlflow_required: import mlflow from mlflow.tracking.fluent import ActiveRun if TYPE_CHECKING: from catalyst.core.runner impo...
# Project Repository : https://github.com/robertapplin/N-Body-Simulations # Authored by <NAME>, 2020 from n_body_simulations.xml_reader import get_simulation_setting, get_user_interface_property from PyQt5.QtCore import QRegExp, Qt from PyQt5.QtGui import QRegExpValidator from PyQt5.QtWidgets import (QDoubleSpinBox, Q...
#!/usr/bin/env python3 """ This script profiles each part of masked kyber using the st-link ITM + SWO It requires a bit of setup though. You need to install openocd (http://openocd.org/getting-openocd/), arm-none-eabi-gdb (https://developer.arm.com/tools-and-software/open-source-software/developer-...
import sys, os from os.path import abspath, join, commonprefix # replacement for os.path.relpath (2.6 and above) # extracted from https://github.com/python/cpython/blob/master/Lib/posixpath.py # several safety measures have been removed (os.fspath, better try-except statement, paths as bytes) def relpath_unsafe(path,...
import argparse import logging import os.path import shutil import sys import time import yaml from datetime import datetime from distutils import dir_util from config_xml_patch import patch_xml from config_json_patch import patch_json BUILD_HTML5_VIEWER_DIR_NAME = "html5viewer" BUILD_SITE_DIR_NAME = ...
import numpy as np import matplotlib.pyplot as plt def G_r(y_c, z_c, radius, integration_steps = 1000): """ Returns array of sensitivity of wire loop at position (0,y_c,z_c) of a given radius. Parameters ---------- y_c: list or array-like Multiple y coordinates can be input, this i used...
#! /usr/bin/env python import itertools from enum import Enum from time import time as ts from aoc.intcode import IntCodeCPU from aoc.utils import load_input class Direction(Enum): UP = "^" DOWN = "v" LEFT = "<" RIGHT = ">" def find_block(data, block, offset): if not block: return [] ...
import re from typing import List, Sequence import arviz as az from cmdstanpy import CmdStanMCMC import xarray as xr def full_fit_to_inference( fit: CmdStanMCMC, params: Sequence[str], coords: dict, dims: dict, alr_params: Sequence[str] = None, posterior_predictive: str = None, log_likeli...
import bs4 import time import pymysql import requests from dropbox import dropbox from selenium import webdriver from datetime import datetime, timedelta SOURCE_URL = 'https://blogtruyen.com/danhsach/tatca' data = [] client = dropbox.Dropbox("ut9MzqycHAAAAAAAAAAAM-HAvZ8JWgqcOSvr5e3VdjJnlPoTByUGs11BUsUzFl1T") # Kế...
''' ================================================ ## VOICEBOOK REPOSITORY ## ================================================ repository name: voicebook repository version: 1.0 repository link: https://github.com/jim-schwoebel/voicebook author: <NAME> author contact: <EMAIL> descr...
import sys from capstone import * from capstone.x86 import * from itertools import tee # from unittest import assertIn """List of basic blocks. They are denoted as their starting address (leaders). Example: BASIC_BLOCKS = [0x0, 0x12, 0x40] """ BASIC_BLOCKS = [] def getJumpTargets(disas): """Get...
"""Test the KPOINTS parser.""" # pylint: disable=unused-import,redefined-outer-name,unused-argument,unused-wildcard-import,wildcard-import import math import pytest import numpy as np from aiida_vasp.utils.fixtures import * from aiida_vasp.utils.fixtures.testdata import data_path from aiida_vasp.parsers.content_parse...
import logging import math from functools import partial from typing import Dict, Tuple import evalset.test_funcs import GPy import numpy as np import emukit from emukit.bayesian_optimization.loops import BayesianOptimizationLoop from emukit.core import ContinuousParameter, ParameterSpace from emukit.core.optimizatio...
__author__ = 'mirko' import sys, os, ctypes as ct, random from time import clock, sleep import OpenGL from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * from ctypes import * try: import gui.histograph as h except: import histograph as h def display(): glClear(GL_COLOR_BUFFER_BI...
import os import io import base64 from astropy.io import fits, votable import numpy import mlpy.wavelet as wave import matplotlib.pyplot as plt import warnings class SpectrumFileReader: """Abstract class for individual readers. Every reader can read its own type of spectrum format.""" def _scidata(self, ...
''' Warning: this module requires Python 3.2 or higher This is a set of classes to represent what I have most commonly needed when working on dozens (eukaryotic) or hundreds (prokaryotic) of annotation projects. If you have other attributes that you'd like to see supported, please add an 'issue' on the biocode GitHub...
import torch from .multi_head_attention import AttentionMask, MultiHeadAttentionBase, AttentionMergeMixin from typing import Optional from .geometric_attention import geometric_attention_activation import math from .multi_head_relative_pos_attention import FixedRelativeMultiheadAttentionBase, shift class DirectionSen...
import csv import os import re import spotipy # library for interacting with spotify api from spotipy.oauth2 import SpotifyClientCredentials # handles oath sign in with spotify api credentials import requests # make http requests from bs4 import BeautifulSoup # read page content from when opening genius urls impor...
"""Resynthesis of signals described as sinusoid tracks.""" import numpy as np def synthtrax(F, M, SR, SUBF=128, DUR=0): """ % X = synthtrax(F, M, SR, SUBF, DUR) Reconstruct a sound from track rep'n. % Each row of F and M contains a series of frequency and magnitude % samples for a particular track. The...
# Copyright (c) 2015 Cloudera, 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 o...
"""Helper module for generating channel config command and caching values.""" def get_channel_config_command( channel, power_down, gain, input_type, bias, srb2, srb1): """Get command string for the given parameters. See :func:`Cyton.configure_channel<openbci_interface.cyton.Cyton.configure_channe...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import json import warnings import pulumi import pulumi.runtime from .. import utilities, tables class GetImageResult: """ A c...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Copyright 2017 <NAME> <<EMAIL>> # # 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 r...
"""Flight category by hour""" import datetime import numpy as np import pytz from pandas.io.sql import read_sql import matplotlib.colors as mpcolors from matplotlib.patches import Rectangle from pyiem.plot.use_agg import plt from pyiem.util import get_autoplot_context, get_dbconn, utc from pyiem.exceptions import NoDa...
# Copyright (c) 2020, eQualit.ie inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. import datetime import json import os import time import traceback import pandas as pd from baskerville.util.helpers import ...
from __future__ import annotations from abc import abstractmethod, ABCMeta from typing import Optional, List, Iterable, Union, TypeVar import numpy as np from .. import tensor as ts T = TypeVar("T") IterT = Union[T, Iterable[T]] class Variable: def __init__(self, value: ts.Tensor, op: Optional[Op] = None): ...
''' * Copyright (c) 2022, salesforce.com, inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause * By <NAME> ''' import argparse import os import ruamel_yaml as yaml import numpy as np import...
""" pint.facets.formatting.objects ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: 2022 by Pint Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import annotations import re from typing import Any from ...compat import babel_parse, ndarray, np from ....
#!/usr/bin/env python """ MagPy - Basic Runtime tests including durations """ from __future__ import print_function from magpy.stream import * from magpy.database import * import magpy.transfer as tr import magpy.absolutes as di import magpy.mpplot as mp import magpy.opt.emd as emd import magpy.opt.cred as cre...
import os import pathlib import re from cached_property import cached_property from tracelog import TRACELOG from .bead import UnpackableBead from . import meta from . import tech from .ziparchive import ZipArchive from .exceptions import InvalidArchive persistence = tech.persistence __all__ = ('Archive', 'Invalid...
# ============================================================================== # # The following functions are designed to resize SPM nifti maps to align with # the given SPM template nifti using FSL and nilearn commands and output a # slice image of the two niftis overlaid. # # ======================================...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the Apache 2.0 License. import tempfile import http import subprocess import os import glob import infra.network import infra.path import infra.proc import infra.notification import infra.net import infra.e2e_args import suite.test_requirement...
###===### # Coder: <NAME> # Affiliation: The Australian National University #=== # Code purpose: # Supporting script, the MetaSGD-CL meta-learner nueral optimiser ###===### import numpy as np import math from functools import reduce from operator import mul #--...
#!/usr/bin/env python3 import argparse import os from camaptools.Dataset import RegressionDataset from camaptools.Regression import RegressionMetaManager from camaptools.EnhancedFutures import EnhancedProcessPoolExecutor, EnhancedMPIPoolExecutor OUTPUT_FOLDER = "./output" def add_blcl_peptide_lists(dataset): ...
""" Contains some misc utility functions """ import collections import multiprocessing from collections import OrderedDict, Callable from functools import reduce import numpy as np def as_list(obj): """ Makes sure `obj` is a list or otherwise converts it to a list with a single element. :param obj: ...
import websocket import threading from threading import Thread import time import json import random import copy import hashlib import datetime as date import sys from miner import BlockMiner sys.path.append("../CryptoWork") sys.path.append("../block") sys.path.append("../node") sys.path.append("../blockchain_lib...
import difflib import shelve from datetime import datetime import networkx as nx import base64 from io import BytesIO import matplotlib.pyplot as plt from collections import OrderedDict from collections import defaultdict VOCAB = ["undergrad", "postgrad", "faculty", "academic", "service", "software", "techno...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # imagecompare.py import numpy as np from concurrent import futures from functools import partial def gaussian2d(shape: tuple = (5,), sigma: tuple = (1.5,)) -> np.ndarray: """ create a gaussian 2d array shape and sigma tuples with diferent values can create ...
from __future__ import absolute_import import base64 import logging import os import re from google.appengine.ext import db from gae_bingo.config import config from gae_bingo import cookies from gae_bingo import request_cache from .models import GAEBingoIdentityModel IDENTITY_COOKIE_KEY = "gae_b_id" IDENTITY_COOKIE...
"""camera.py This code is a tiny and custom version of https://github.com/jkjung-avt/tensorrt_demos#yolov4 """ import cv2 import numpy as np import threading USB_GSTREAMER = True def add_camera_args(parser): """Add parser augment for camera options.""" parser.add_argument("--video_path", ...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from pointnet2 import SAModule, SAMSGModule, PointNet2FP class PointNet2SSGPartSeg(nn.Module): def __init__(self, output_classes, batch_size, input_dims=6): super(PointNet2SSGPartSeg, s...
import torch from torch import nn from .mobilenet_v2 import MobileNetV2 class Block(nn.Module): def __init__(self, num_residual_layers, in_channels, out_channels, kernel_size=3, stride=2, padding=1, remove_last_relu=False): super(Block, self).__init__() if remove_last_relu and num...
#!/usr/bin/env python3 # PYTHON_ARGCOMPLETE_OK from ays_general import __version__, __version_info__ import ays_model as aws import ays_general from pyviability import helper import numpy as np import scipy.integrate as integ import scipy.optimize as opt import matplotlib.pyplot as plt import mpl_toolkits.mplot3d as...
import copy import pytest from contk.dataloader import SingleTurnDialog, OpenSubtitles from contk.metric import MetricBase class TestSingleTurnDialog(): def base_test_init(self, dl): assert isinstance(dl, SingleTurnDialog) assert isinstance(dl.ext_vocab, list) assert dl.ext_vocab[:4] == ["<pad>", "<unk>", "<g...
import uno import unohelper from com.sun.star.beans import PropertyValue from com.sun.star.beans.PropertyState import DIRECT_VALUE from com.sun.star.container import XNameContainer, NoSuchElementException, ElementExistException from com.sun.star.lang import XServiceInfo, \ IllegalArgumentException from com.sun.st...
from django.http import HttpResponse from django.shortcuts import render, redirect from .forms import RoomCreateForm, RoomUpdateForm, UserUpdateForm, CustomUserCreationForm from django.shortcuts import get_object_or_404 from django.db.models import Q from django.contrib.auth import authenticate, login, logout from djan...
# 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, software # distributed under t...
# Copyright 2015-2017 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...
import numpy as np import os import torch import torch.nn as nn from torchvision import transforms from torch.utils.data import Dataset, DataLoader import math from PIL import Image from torchsummary import summary from numpy import asarray image_dir = "/content/Images" SAVE_DIR = "/content/Results" piece_dir = {} bat...
# -*- coding: utf-8 -*- from aloe import step from aloe import world import numpy import matplotlib.pyplot as plt from quantarhei import energy_units from quantarhei import Manager from quantarhei import CorrelationFunction from quantarhei import SpectralDensity from ...stepslib import read_n_columns @step(r'corre...
import json import unittest.mock as mock from datetime import datetime, date from freezegun import freeze_time from model_mommy import mommy from django.test import override_settings from django.utils import timezone from hourglass.tests.common import ProtectedViewTestCase from ..models import SubmittedPriceList from...
import numpy as np from read_models import read_models abstract_certain_feat_xgb, abstract_certain_vect_xgb, \ abstract_subject_feat_xgb, abstract_subject_vect_xgb, \ career_feat_xgb, career_vect_xgb, \ education_vect_xgb, specific_feat_xgb, specific_vect_xgb, \ time_boun...
#!/usr/bin/env python # coding: utf-8 # Copyright (C) PyZMQ Developers # Distributed under the terms of the Modified BSD License. # # Some original test code Copyright (c) 2007-2010 iMatix Corporation, # Used under LGPLv3 import argparse from multiprocessing import Process import time try: now = time.monotonic...
""" _StorageManagerAPI_ Contains all the code for interfacing with the StorageManager """ import logging import threading import time from WMCore.DAOFactory import DAOFactory knownStreamers = set() def injectNewData(dbInterfaceStorageManager, dbInterfaceHltConf, dbInterfaceSMNot...
# Train DCGAN model on CIFAR-10 data or other specified data # Originally written by <NAME> import tensorflow as tf import logging import importlib from data import utilities logger = logging.getLogger("gan.train") # Create CIFAR-10 input BATCH_SIZE = 32 def train(dataset, except_class_to_ignore, stop=300000): '''...
from django.test import TestCase from maps.models import Post from time import strftime from django.contrib.auth.models import User from .forms import * class PostModelTest(TestCase): TIMESTAMP_AUTHOR = strftime("U%d%m%y%H%M%S") TIMESTAMP_TITLE = strftime("T%d%m%y%H%M%S") CONTENT = """Lorem Ipsum is simpl...
# -*- coding: utf-8 -*- #################################################################################################### # File: dijkstra.py # Purpose: Implementation of the Dijkstra algorithm for path-finding. # # Author: <NAME> # # Location: NYC, 2021 #######################################################...
from jiwer import wer import nltk import distance import re, math from collections import Counter from nltk.corpus import stopwords from nltk import tokenize import argparse import os from pathlib import Path # Global variables WORD = re.compile(r'\w+') sws = stopwords.words('portuguese') # Stopwords removal def te...
import pytest from pytest_mock import MockerFixture from cgr_gwas_qc.testing import chdir from cgr_gwas_qc.testing.data import FakeData @pytest.mark.parametrize( "cgems,biowulf,cluster_profile", [(True, False, None), (False, True, None), (False, False, "./test")], ) def test_check_exclusive_options_no_error(...
import mxnet as mx import logging logger = logging.getLogger(__name__) __all__ = ['AddJitterOp', 'AddJitterOpProp'] INITIAL_JITTER_FACTOR = 1e-9 JITTER_GROWTH = 10. JITTER_UPPERBOUND_FACTOR = 1e3 class AddJitterOp(mx.operator.CustomOp): """ Finds smaller jitter to add to diagonal of square matrix to rende...
__author__ = 'Kalyan' from placeholders import * notes = """ This lesson explores some advanced features of functions. This will help you make sense of a lot of standard library functions when you use them. In particular, the following are covered - positional and keyword arguments - defining and passing va...
import os import sys import os.path import pcapy import xml.etree.ElementTree from ping import Ping from random import * from core.printf import * from lib.packetHandle import * from lib.socketHandle import * from urllib.parse import urlparse from os.path import dirname,abspath from core import Exceptions as exce sys...
import sys import cv2 import numpy as np import tensorboardX import torch from tqdm import trange from torch.optim.lr_scheduler import MultiStepLR from torch.utils.data import DataLoader from logger import Logger from modules.model import GeneratorFullModel, DiscriminatorFullModel from sync_batchnorm import DataParal...
import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as mpatches from numpy import array, mean, unique, vstack from os.path import join mpl.rcParams.update({'font.size': 18}) def my_plot(vector, xlabel_str=None, ylabel_str=None, title_str=None, output_file=Non...
# Copyright 2020 <NAME> # SPDX-License-Identifier: Apache-2.0 from .utils import * from ..op import CombinedOp, SequenceOp, ElementwiseAdd, Linear, ReLU class BasicBlock(CombinedOp): expansion = 1 def __init__(self, name, in_shape, out_channel, stride=1, downsample=None): in_shape = shape2d(in_shape)...
"""Tests for the implementation of SYS_MultiplyBytes_126""" import os.path import pathlib from importlib import reload from types import SimpleNamespace from hypothesis import given from hypothesis import strategies as st import asm from gtemu import RAM, Emulator MAX_CYCLES = 120 SYS_DIR = (pathlib.Path(__file__)...
import datetime class NoteUser: def __init__(self, _state, json: dict): self.id = json['id'] self.name = json['name'] self.username = json['username'] self.host = json['host'] self.avatar_url = json['avatarUrl'] self.avatar_blurhash = json['avatarBlurhash'] s...