text
stringlengths
3.07k
12.6k
# Copyright 2011-2013 <NAME> # Copyright 2011-2013 <NAME> # # 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...
import unittest import torch from torchvision import datasets, transforms import utility import model_helper import os import json data_dir = 'flowers' testing_dir = 'testing' gpu_epochs = 9 cpu_epochs = 5 category_names = 'cat_to_name.json' hidden_units = 600 learning_rate = 0.001 test_image = 'flowers/test/28/image_...
#!/usr/bin/env python ############################################################################ # # # Copyright (c) 2019-2020 <NAME> # # Modifications copyright (c) 2020 <NAME> # # ...
#This program takes a raster image and produces its raster halftone using patterning algorithm. """ For each possible value in the image, we create and display a pattern of pixels that approximates that value. Remembering the concept of spatial integration, if we choose the appropriate patterns we can simulate the ap...
import numpy as np import cv2 as cv import os W = 1800 # width of range image H = 40 # height of range image LABEL_DICT = { 0: "unlabeled", 4: "person", 5: "2+ person", 6: "rider", 7: "car", 8: "trunk", 9: "plants", 10: "traffic sign 1", # standing sign 11: "traffic sign 2", # han...
#!/usr/bin/env python3 ''' @author <NAME> - http://www.ce.unipr.it/people/tomamic @license This software is free - http://www.gnu.org/licenses/gpl.html ''' from tkinter import Tk, messagebox, simpledialog import subprocess, sys try: import pygame except: subprocess.call([sys.executable, "-m", "pip"...
# Copyright (c) 2017-present, Facebook, Inc. # # 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...
from .models import PhotoEntry, MedicationAmount, Medication, DrinkType, DrinkAmount, DayEntry, FoodTag, HeadacheTag from .serializers import UserSerializer, DetailDayEntrySerializer, TextEntrySerializer, DrinkEntrySerializer, SimpleDayEntrySerializer, MedicationEntrySerializer, PhotoEntrySerializer, FoodEntrySerialize...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: terraformlintingcli.py # # Copyright 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 witho...
"""Authentication module.""" import sys from typing import Optional import requests as req from click import group, option, echo from requests.models import Response from userconf import Userconf # Settings app_id = "notelist_cli" api_url = "api_url" user_id = "user_id" acc_tok = "<PASSWORD>" ref_tok = "<PASSWORD>"...
import random def welcome(): for i in range(1,9): print("*\t",end="") print() print("*",end="") for i in range(1,8): print("\t",end="") print("*") print("*",end="") for i in range(1,4): print("\t",end="") print("welcome",end="") for i in range(1,5): print("\t",end="") print("*") print...
from torch.utils.data import Dataset from tok import Tokenizer import copy import json import os import numpy as np import torch DATA_ROOT = "data/" class NADataset: def __init__(self, split='train'): self.split = split if split == 'train': self.data = json.load(open(os.path.join(DAT...
import xml.etree.ElementTree as ET import statistics as stat import csv import os import re import sys from multiprocessing.dummy import Pool as ThreadPool def fuSaveProtInfo(strLine1, strLine2, strBaseDir): if not strLine1 or not strLine2: return strProtName = strLine1[1:-1].split(' ')[0] strFil...
from functools import cached_property from typing import Any, Tuple, Dict, Union import intake import numpy as np import pandas as pd from intake.catalog import Catalog from .util import * from .. import io class IntakeDataset: def __init__(self, catalog: Union[str, Catalog], loader=None): self._loader...
import numpy as np import pandas as pd import pytest from gspread_pandas import util @pytest.fixture def df(): data = [[1, 2], [3, 4]] cols = ["col1", "col2"] df = pd.DataFrame(data, columns=cols) df.index.name = "test_index" return df @pytest.fixture def df_empty(): return pd.DataFrame() ...
#!/usr/bin/env python3 import sys import os import argparse import json from google.cloud import storage def cleanup_empty_states(args): storage_client = storage.Client() blobs = storage_client.list_blobs(args.bucket) for blob in blobs: blob_name = "gs://%s/%s" % (args.bucket, blob.name) if args....
#!/usr/bin/env python import dateutil.parser import logging import os import requests import time as _time from datetime import date, datetime, time, timedelta from tzlocal import get_localzone logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__package__) today = date.today() START_DATE = datetime....
import numpy as np import pandas as pd import json import os import pyapprox as pya import SALib.sample.latin as latin from SALib.util import read_param_file from basic.boots_pya import fun from basic.utils import to_df, adjust_sampling from basic.group_fix import group_fix, uncond_cal from basic.read_data import file...
"""Cloudmesh 4 :: Usage: cm4 admin mongo install [--brew] [--download=PATH] cm4 admin mongo status cm4 admin mongo start cm4 admin mongo stop cm4 admin mongo backup FILENAME cm4 admin mongo load FILENAME cm4 admin rest status cm4 admin rest start cm4 admin res...
import logging as _logging import sys __all__ = ( 'get_class_module_root', 'get_class_namespace', 'create_class_instance', 'export_dict', 'import_dict' ) logging = _logging.getLogger() logging.setLevel(_logging.WARNING) # constants TYPE_BASIC, TYPE_LIST, TYPE_DAGNODE, TYPE_COMPLEX, TYPE_NONE = ra...
#!/usr/bin/env python3 import sys sys.path.append("../neurgoo/") import numpy as np import tensorflow as tf from loguru import logger from sklearn.model_selection import train_test_split from neurgoo.api import ( SGD, CrossEntropyLoss, DefaultModelTrainer, DefaultNNModel, Linear, MeanSquared...
# coding=utf-8 # Copyright 2020 The Google AI Perception Team 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 b...
from novmpy.bridge import * from capstone import * from capstone.x86 import * from novmpy.x86_deobf import * from novmpy.match_helper import * class VMConfig: def __init__(self): self.reg_key = X86_REG_INVALID self.reg_ip = X86_REG_INVALID self.reg_sp = X86_REG_INVALID self.reg_reg...
"""import models""" from django.db import models class Substances(models.Model): """ getting data from the substances DB table""" id = models.SmallAutoField(primary_key=True) name = models.CharField(max_length=256, default='') formula = models.CharField(max_length=256, default='') monomass = model...
import argparse import subprocess from subprocess import STDOUT, check_output import sys import string import os import tarfile import yaml from datetime import date #-----------------------------------------------------------------------------# # CONFIGURATION YAML # Fonction pour récupérer la configur...
import torchvision import pathlib import torch import numpy as np import math import logging import collections try: import wandb except ImportError: logging.warning("Could not import wandb") from PIL import Image from fba import utils class DefaultLogger: def __init__(self) -> None: pass de...
import cv2 import torch import numpy as np import time from itertools import count from torchvision.utils import make_grid def env_from_args(args): if 'umanoid' in args.env_id: from gesture.environments.social import SocialHumanoid Env = SocialHumanoid args.env_id = 'SocialHumanoid' ...
""" Copyright 2021 InfAI (CC SES) 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...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. """ Maintains a collection of status codes received by each sequence """ import time import collections class RequestExecutionStatus(object): """ RequestExecutionStatus class. """ def __init__(self, timestamp, request_hex, status_code, i...
#! /usr/bin/python import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import pysam,os import pandas as pd import numpy as np import seaborn as sns from resources.utils import readBED DWINDOW = 2500 FIGHEIGHT= 4 FIGWIDTH = 16 XLABEL = 'Chromosome' YLABEL = 'Reads' PALETTE = 'husl' DPI ...
# ActivitySim # See full license in LICENSE.txt. import logging from activitysim.core import simulate from activitysim.core import tracing from activitysim.core import config from activitysim.core import los from activitysim.core import expressions from activitysim.core.pathbuilder import TransitVirtualPathBuilder l...
""" Provides functions for syncing entities and their relationships to the Entity and EntityRelationship tables. """ from collections import defaultdict from itertools import chain from django.contrib.contenttypes.models import ContentType import manager_utils from entity.config import entity_registry from entity.mod...
""" Classes for .param and .cell files """ import os import tempfile import re from collections import OrderedDict import numpy as np from .parser import Parser, PlainParser from .common import Block, cell_abcs_to_vec class CastepInput(OrderedDict): """ Class for storing key - values pairs of CASTEP inputs ...
""" Module, providing a DAO api for accessing metadata on warehoused python_types. Python object types are associated with warehoused Variables (measured values & dimensional attributes), as a convenience - for binding values into SQLAlchemy querys, without first having to connect/query the table to determine the col...
from copy import deepcopy import pytest from pystachio.basic import * from pystachio.composite import * from pystachio.container import * from pystachio.naming import Ref def ref(address): return Ref.from_address(address) def test_ref_parsing(): for input in ['', None, type, 1, 3.0, 'hork bork']: with pyt...
import os import time from collections import OrderedDict import torch from torch.autograd import Variable from pix2pixHD.options.test_options import TestOptions from pix2pixHD.data.data_loader import CreateDataLoader from pix2pixHD.models.models import create_model import pix2pixHD.util.util as util from pix2pixHD.uti...
"""``otf.pack.tree``: In memory trees ================================== Convert to and from :class:`Node`. :mod:`otf.pack` convert directly between different types and doesn't have any intermediate representation of values. Having access to a simple representation makes it easier to write tests and debug application...
import numpy as np import chainer import chainer.functions as F import chainer.links as L from chainercv.transforms import resize from chainercv.utils import download_model def _pool_without_cudnn(p, x): with chainer.using_config("use_cudnn", "never"): return p.apply((x,))[0] class SegNetBasic(chainer...
import pandas as pd from .aux import existingYearDirectories def readMergeClean(country, year): route ='./data/'+ country + '/' + str(year) try: productsRoute = route + '/products.csv' partnersRoute = route + '/partners.csv' exportValuesRoute = route + '/exportValues.csv' prod...
from onelang_core import * from onelang_file import * from onelang_yaml import * from onelang_json import * import OneLang.Generator.IGenerator as iGen import OneLang.Generator.JavaGenerator as javaGen import OneLang.Generator.CsharpGenerator as cshGen import OneLang.Generator.PythonGenerator as pythGen import OneLang....
import io import datetime as dt from threading import Thread, Lock from collections import namedtuple from math import sin, cos, pi from time import sleep from picamerax import mmal, mmalobj as mo, PiCameraPortDisabled from PIL import Image, ImageDraw class Coord(namedtuple('Coord', ('x', 'y'))): @classmethod ...
def lbs_to_kg(weight): """convert a weight in pounds to a weight in kg :params: weight(lbs) - Float :returns: weight(kg) - Float Examples: >>> lbs_to_kg(10) 4.535923700000001 >>> lbs_to_kg(100) 45.359237 """ return weight * 0.45359237 def get_amount_in_mg(weight, ...
# pylint: disable=C0111,R0903 """Shows a widget for each connected screen and allows the user to enable/disable screens. Parameters: * xrandr.overwrite_i3config: If set to 'true', this module assembles a new i3 config every time a screen is enabled or disabled by taking the file '~/.config/i3/config.templat...
from .paddle import Paddle from .ball import Ball import pygame import random pygame.init() class GameInformation: def __init__(self, left_hits, right_hits, left_score, right_score): self.left_hits = left_hits self.right_hits = right_hits self.left_score = left_score self.right_sco...
import numpy as np import bokeh import bokeh.plotting as bk import bokeh.palettes as bp from bokeh.transform import linear_cmap from bokeh.models import ColumnDataSource from bokeh.models import NumeralTickFormatter import math def get_colors(x, palette=bp.all_palettes['RdYlBu'][11], xmin=None, xmax=None): ''...
import logging from flask import jsonify, request import flask_login import mediacloud.error from server import app, TOOL_API_KEY from server.util.request import api_error_handler, json_error_response, form_fields_required from server.views.topics.apicache import topic_story_count from server.auth import user_mediaclo...
from optparse import OptionParser import os import sys from intervaltree import Interval, IntervalTree ################################################################################ # preprocess_flanks.py # # Produce a set of true negatives flanks for Basset analysis, potentially adding # them to an existing databas...
import inspect from copy import deepcopy from functools import wraps from botocore.paginate import TokenDecoder, TokenEncoder from moto.core.exceptions import InvalidToken def paginate(pagination_model, original_function=None): def pagination_decorator(func): @wraps(func) def pagination_wrapper...
import itertools import inspect from statistics import mean import numpy as np from sklearn.base import BaseEstimator, ClassifierMixin from sklearn.metrics import balanced_accuracy_score from scipy.ndimage.morphology import distance_transform_cdt from pynger.types import Field, Image, List, Mask, Union, Tuple from py...
import datetime import io import requests import tempfile import time import unicodecsv import xml.etree.ElementTree as ET from contextlib import contextmanager from sqlalchemy import types from sqlalchemy import event from sqlalchemy import Column from sqlalchemy import Integer from sqlalchemy import Table from sqlal...
import numpy as np from util import Saver from agents.util import (get_next_theta, gmm_rand, gauss_pdf, gmm_pdf, DebugAnimation, Projection) class MDS(Saver): saved_names = ('theta', ) def __init__(self, n_updates, n_reps, n_dims, n_bfs, n_times, r_gain, r_normalize)...
import re from datetime import datetime, timedelta import cv2 as cv from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense, Flatten, Conv2D from tensorflow.keras.callbacks import EarlyStopping from tensorflow.keras.initializers import Zeros from tensorflow.keras.models import load_model from...
from datapackage_pipelines.wrapper import ingest, spew from datapackage_pipelines.utilities.resources import PROP_STREAMING from pyquery import PyQuery as pq import datetime, logging, requests, json, time, os from pipeline_params import get_pipeline_param_rows from bs4 import BeautifulSoup source_parameters, datapack...
# -*- coding: utf-8 -*- """ This module downloads lyrics from AZLyrics by scraping them off its HTML pages. The url structure used is: http://www.azlyrics.com/lyrics/<artist>/<title>.html AZLyrics only allows lowercase alphanumeric(no '_') URLs. This source is least accurate since BeautifulSoup is not able t...
""" Este script integra la ec. de movimiento de un pendulo real usando el algoritmo de Runge-Kutta de orden 2. """ import numpy as np import matplotlib.pyplot as plt g = 9.8 # en m/s^2, aceleracion de gravedad R = 5.704 # en m, largo del péndulo gamma=2.704 # en 1/s, coeficiente de fricción # Implementando soluc...
from src.substitute_dynamic_symbols import lambdify,run from inspect import signature from src.symbols import * from pandas.api.types import is_numeric_dtype ## Prime System df_prime = pd.DataFrame() df_prime.loc['denominator','length'] = L df_prime.loc['denominator','volume'] = L**3 df_prime.loc['denominator','mass']...
import itertools VERBOSE = False def sortkey(s): s = s.strip() if s.startswith('#'): s = s[1:].strip() return s class Thing: def __init__(self, lib, srcs, node): self.name = lib self.srcs = srcs self.indirect = dict() self.node = node @classmethod de...
import re from property_caching import cached_property from webob import Request from woma.endpoints import Endpoint, not_found from woma.exceptions import NotFound class Router(object): """Map URL paths to handlers. Supports being used as WSGI callable. High-level API --------------- from wom...
# Copyright 2018 Google Inc. # # 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, ...
#! /usr/bin/env python3 # yts import requests import argparse import bs4 import sys import os import subprocess # YTS CLASS class YTS: """ provides an API for downloading yts yifi movies. """ # Initialize with the current yts url def __init__(self, yts_url): self.url = yts_url # Gets the po...
import os import bokeh.plotting import bokeh.models import pandas as pd import seaborn as sns from sklearn.preprocessing import LabelEncoder def colors_from_column(hue_column): """Apply a color palette based on the values in a column. Parameters ---------- hue_column : pandas.Series The col...
from typing import Union, Optional, Callable, Any, Iterator, Dict, List from pathlib import Path import urllib.parse import enum from functools import partial import gzip import pickle import json import numpy as np from fs import open_fs from fs.base import FS from fs.osfs import OSFS from ndstructs import Point5D, ...
from os.path import join import numpy as np import matplotlib.pyplot as plt from scipy.spatial.distance import squareform from brainiak.isc import isc, isfc # Load helper function(s) for interacting with CTF dataset from ctf_dataset.load import create_wrapped_dataset base_dir = '/mnt/bucket/labs/hasson/snastase/soci...
""" Author: <NAME> Email: <EMAIL> Docs: https://giangtranml.github.io/ml/conv-net.html """ import sys, os sys.path.append("..") import numpy as np from neural_network.neural_network import NeuralNetwork from nn_components.layers import ConvLayer, ActivationLayer, PoolingLayer, FlattenLayer, FCLayer, BatchNormLayer from...
import argparse import logging import subprocess import os from os import path from pathlib import Path import glob from typing import List import re import sys from pydantic import BaseModel import colorama class Plugin(BaseModel): path: str name: str url: str = None description: str = None def do...
""" Created Apr 09, 2019 @author montreal91 """ from typing import List from typing import Optional from typing import Tuple from configuration.config_game import DdGameplayConstants from core.attendance import DdCourt from core.financial import DdFinancialAccount from core.player import DdPlayer from core.player i...
# 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. # hack to make sure -m transformer/generator works as expected from .modules import TransformerEncoder from .modules import get_n_positions_from...
import asynctest import pytest from aiotelegrambot import Content, Handler, Handlers from aiotelegrambot.errors import HandlerError from aiotelegrambot.rules import Text class TestHandler: def test___init__(self, mocker): async def handler(): pass chat_type = mocker.MagicMock() ...
import os import guessit import shutil import sys import re import uinput from pathlib_revised import Path2 import argparse # Moves file from A to B. If the folder # does not exist, we create it def move_me(abp, fon, fn): if not os.path.exists(fon): os.makedirs(fon) shutil.move(abp, fon + '/' + fn) ...
__author__ = '<NAME>' from oriented_packing import oriented_packer from operator import itemgetter from itertools import ifilter def get_non_blocking_boxes(current_box, all_boxes, packed_boxes): """ Get boxes that are not allowed to block with the current box. """ result = [] curren...
from goalnet.helpers.log_init import log import numpy as np class Metrics: def __init__(self, data_type, providers=[], **kw): self.data_type = data_type self.providers_names = providers def get_providers_names(self): return self.providers_names def get(self, params, providers=[]):...
# University of Illinois/NCSA Open Source License # Copyright (c) 2015 Information Trust Institute # All rights reserved. # # Developed by: # # Information Trust Institute # University of Illinois # http://www.iti.illinois.edu # # Permission is hereby granted, free of charge, to any person obtaining a copy of # this so...
import random import sys from TicTacIA import HumanPlayer, RandomPlayer, NotSoDumbPlayer, LethalPlayer, DarwinPlayer, \ SemiLethalPlayer, DefensivePlayer, AIPlayer def play(player, grid): while True: try: position = player.generate_play(grid.copy()) # print(position) ...
import discord from discord.ext import commands from discord.ext.commands import cooldown,BucketType class SupportCog(commands.Cog): def __init__(self, bot): self.bot = bot # Bug reporting @commands.command(name='bugs', aliases=['bug']) @cooldown(1, 10, BucketType.guild) async def bug_report(self, ctx, *, m...
import serial import eventlet from datetime import datetime from app import db, socketio import time workers = []; serials = []; def do_work(id): """ do work and emit message """ tc = TempControl.query.get(int(id)); if not tc.sleeptime: sleeptime = 3; else: sleeptime = tc.slee...
import random from sqlalchemy.sql import text from coffeebot import config, session from coffeebot.models import User, Pair def get_channel(driver, team_name, channel_name): """ Retrieve a channel given a team and channel name. Returns the JSON response from the Mattermost API. """ response = dr...
# Copyright (c) 2017, The Linux Foundation. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # * Redistributions of source code must retain the above copyright # notice, this list of cond...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pickle import math from multiprocessing import Pool from .utils import word_tokenize from .parameters import parse_args from nltk.corpus import stopwords import os import logging class BM25(object): ''' The implementation of BM25 ...
import logging import argparse import robin_stocks.robinhood as rh import pandas import numpy import ta import folio def golden_cross(sym: str, n1: int, n2: int, days: int, direction: str) -> bool: """Determine if a golden/death cross has occured for a specified stock in the last X trading days Args: ...
from __future__ import print_function, division from coffea import processor import multiprocessing import warnings import numpy as np import sys import pytest def test_parsl_start_stop(): parsl = pytest.importorskip("parsl", minversion="0.7.2") from coffea.processor.parsl.detail import (_parsl_initi...
import os import pytest from flask import url_for from burpui.app import create_app @pytest.fixture def app(): conf = os.path.join( os.path.dirname(os.path.realpath(__file__)), "../configs/test2.cfg" ) bui = create_app(logfile="/dev/null", gunicorn=False, unittest=True) bui.setup(conf, True)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os, sys import argparse from core import config from core import utils from modules import fofa from modules import shodan from modules import censys from modules import zoomeye from modules import sploitus from modules import vulners from modules import writeups...
#!/usr/bin/env python3 """ Sierpinski Triangle Program (Fractals) A turtle graphics program that generates Sierpinski triangles at various levels of repetition.This program utilizes recursive functions NOTE: The Sierpinski triangle is an example of a fractal. A fractal is a shape that contains parts that ar...
__source__ = 'https://leetcode.com/problems/swap-adjacent-in-lr-string/' # Time: O(N) # Space: O(1) # # Description: Leetcode # 777. Swap Adjacent in LR String # # In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", # a move consists of either replacing one occurrence of "XL" with "LX", # or replac...
# Built-in import unittest import sys import os # Internal from nxt import nxt_path from nxt.nxt_node import INTERNAL_ATTRS from nxt.session import Session class TestExpansion(unittest.TestCase): def test_vars_only(self): platform_tests = { 'linux': "$zoom/$all/$around", 'win32': ...
import json from django.contrib import messages from django.http import HttpResponseForbidden, HttpResponseRedirect from django.urls import reverse from django.utils.translation import ugettext as _ from django.views.decorators.http import require_POST from django_prbac.utils import has_privilege from corehq.apps.use...
""" NumPy ===== Provides 1. An array object of arbitrary homogeneous items 2. Fast mathematical operations over arrays 3. Linear Algebra, Fourier Transforms, Random Number Generation How to use the documentation ---------------------------- Documentation is available in two forms: docstrings provided...
""" $Id: testEsmfParallelGridField.py 2394 2012-07-26 17:23:11Z dkindig $ Test the order of grid and field creation relative to GridAddCoord such that all grids and fields are decomposed. """ import ESMF import numpy try: from mpi4py import MPI has_mpi = True except BaseException: has_mpi = False rootP...
import warnings from numpy import abs, arctan, argmax, linspace, min, sign, sin def magic_formula(p, num=1000000, b=10, c=1.9, d=1, e=0.97): """ The magic formula [1] computes the longitudinal force between wheel and tarmac in function of the longitudinal tire slip. [1] Pacejka, <NAME>. Tire and Ve...
"""Test for get_grade.py""" import pytest import random from get_grade import get_grade GRADE_PARAMS_TABLE = [ [95, 90, 93, "A"], [100, 85, 96, "A"], [92, 93, 94, "A"], [100, 100, 100, "A"], [70, 70, 100, "B"], [82, 85, 87, "B"], [84, 79, 85, "B"], [70, 70, 70, "C"], [75, 70, 79, ...
import torch.nn as nn import torch import numpy as np import os def get_norm_3d(norm, out_channels): """ Get a normalization module for 3D tensors Args: norm: (str or callable) out_channels Returns: nn.Module or None: the normalization layer """ if isinstance(norm, str):...
#!/usr/bin/env python # Copyright (c) 2012 <NAME> <<EMAIL>> # Adapted for use with SLURM by <NAME> <<EMAIL>> # Published under the BSD 3-clause licence. """usage: %prog [options] -- [qsub-options] FILE Submit a string of dependent jobs through the PBS/TORQUE, Gridengine, (GE), or SLURM queuing system. Either set --...
import argparse from fileinput import filename from locale import locale_encoding_alias import torch import torch.nn as nn from network.Math_Module import P, Q from network.decom import Decom import os import torchvision import torchvision.transforms as transforms from PIL import Image import time from util...
import tensorflow as tf import numpy as np import pickle import skimage.transform import skimage.filters import datetime import os import shutil import math from scipy import misc import scipy.ndimage import glob def process_individual_image(filename_queue, img_size, random_crop=False): """Individual loading & proce...
import torch import torch.nn as nn from torch.nn.utils.rnn import PackedSequence, pack_padded_sequence, pad_packed_sequence # class GRU(nn.Module): # def __init__(self, input_size, # hidden_size, # num_layers=1, # dropout=0.2, # batch_first=True,...
# Copyright (c) Istituto Nazionale di Fisica Nucleare (INFN). 2020-2021 # # 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 ...
# Copyright 2021 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 or agreed to in writing, ...
# Object Oriented GPIO manipulation for Raspberry Pi from threading import Timer, Lock, RLock import time import functools import RPi.GPIO as GPIO def synchronized(wrapped): """ Synchronization decorator. """ meta_lock = Lock() @functools.wraps(wrapped) def _wrapper(self, *args, **kwargs): ...
""" Copyright (c) Facebook, Inc. and its affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ import os from argparse import ArgumentParser from typing import Callable, List, Optional, Union import covidprognosis as cp import numpy as ...
''' Created on 2012-10-31 @author: hzzhoushaoyu ''' import httplib import hmac import urllib import hashlib import json import time from umbrella.common import cfg import umbrella.common.log as logging from umbrella.db.sqlalchemy import models CONF = cfg.CONF opts = [ cfg.StrOpt("monitor_service_host"), ...