text
stringlengths
3.07k
12.6k
#!/usr/bin/env python # # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import ipaddress import json import logging from typing import Any, Dict, List, Optional from uuid import UUID from azure.cosmosdb.table.tableservice import TableService storage_client_logger = logging.getLogger("azure.c...
from ..utils.geom import Rect from .lazy import LazyPoint, LazyValue from .value import PosValue, SizeValue def _set_padding(a, b, c): if a is not None: return a if b is not None: return b return c or 0 class Layout: def __init__( self, x, y, width, ...
import requests import fire import shlex import platform import os import sys import subprocess import threading import yaml import config import __main__ # Load new API modules here APIS = ["store_api", "auth_api", "votes_api"] ENDPOINT_MAP = {} FUNCTION_MAP = {} # Shell Information PROMPT = "White Team >> " HIST_F...
#!/usr/local/bin/python import json import os import subprocess REPO_PATH = '/repo' PATHS_LIST_SEPARATOR = ',' def check_output(args, cwd=REPO_PATH, **kwargs): print('$', ' '.join(args), f'at "{cwd}"') output = subprocess.check_output(args, cwd=cwd, **kwargs, stderr=subprocess.STDOUT).decode('utf-8') p...
"""Unit tests for aws parameter store interactions with boto3""" from __future__ import annotations from typing import Any from typing import Generator from unittest.mock import patch import pytest from secretbox.awsparameterstore_loader import AWSParameterStore boto3_lib = pytest.importorskip("boto3", reason="boto3...
#!/usr/bin/env python3 import json import os import re import sys import subprocess from pathlib import Path import requests MAPPING_FILE_NAME = "gist-mapping.json" dry_run = bool(os.environ.get("DRY_RUN")) def add_header(src, year, day): link_to_file = f"https://github.com/fornwall/advent-of-code/tree/master...
import numpy as np import torch def get_active_kpts(kpt_sequence: torch.Tensor, intensity_threshold: float = 0.3) -> torch.Tensor: """ Filters key-points for the ones with a mean intensity above the given threshold. :param kpt_sequence: Torch tensor of key-point coordinates in (N, T, K, D...
import torch import torch.nn as nn # Define a function to partially zero inputs based on channel strength def percentile_zero(input, p=99.98, mode='norm'): if 'norm' in mode: px = input.norm(1) elif 'sum' in mode: px = input.sum(1) elif 'mean' in mode: px = input.sum(1) if 'abs...
from flask import render_template, Flask from flask_bootstrap import Bootstrap from PIL import Image import pickle import pandas as pd import numpy as np import os from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing import image from flask import Flask, redirect, url_for, request, render_...
# Crichton, Admirable Source Configuration Management # Copyright 2012 British Broadcasting 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/licens...
#test.py import sys import maya.cmds as cmds import numpy as np import scipy as sp import math N = 100 x = -5 + 5* np.random.rand(N) y = 0.5 + 5 * np.random.rand(N) z = -5 + 5*np.random.rand(N) #make a list of spheres/points cmds.polySphere(r=0.01) result = cmds.ls(orderedSelection = True) transformName = result[0] ...
import torch, os, h5py, datetime, sys, time, random import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import SharedArray as sa import numpy as np import torch.nn.init as init from torch.utils.data import Dataset from torch.autograd import Variable from skimage.measure import bloc...
import asyncio import datetime import discord from discord.ext import commands from .utils import human_time class Timer: __slots__ = ("bot", "id", "event", "data", "expires_at", "created_at") def __init__(self, bot, **kwargs): self.bot = bot self.id = kwargs.get("id") self.event = k...
''' AVL Tree named after the initials of its inventors Adel'son-Vel'skii and Landis. AVL tree is just like BST(Binary Search Tree) with one difference that they are more balanced than BST(Binary Search Tree) and they guaranteed Big-O(log-N) complexity. ''' class Node(object): def __init__(self,data): ...
import torch import torch.nn as nn class TrainerWeightWiseFC(torch.nn.Module): def __init__(self, input_features, output_features, hidden = [], device = "cpu"): super(TrainerWeightWiseFC, self).__init__() self.input_features = input_features self.output_features = output_features ...
# https://www.wescottdesign.com/articles/pid/pidWithoutAPhd.pdf from math import * import cmath import numpy as np import matplotlib.pyplot as plt """ The motor response is represented by the differential equation y''(t) = 1/tau(kV - y'(t)) y(t) represents the angle position at time t We can classify this differen...
import os import requests from dotenv import load_dotenv import statistics import terminaltables SUPERJOB_CATALOGUE = 48 class TownNotFound(BaseException): pass def get_predict_salary(salary_from, salary_to): if salary_from in (None, 0) and salary_to in (None, 0): return None if salary_from i...
import logging import sys import numpy as np import matplotlib import tkinter as tk import os from tkinter import filedialog # import tkinter.ttk as TTK #use for Combobox # from tkinter import scrolledtext # use for logger import matplotlib.pyplot as plt from matplotlib.backends.backend_tkagg import ( FigureCanv...
import logging import os import unittest import uuid from functools import wraps from typing import List import numpy as np from casadi import MX, Function import lumos.numpy as lnp logger = logging.getLogger(__name__) def use_backends(backends: List[str]): """Decortator to run tests with different backends. ...
#!/usr/bin/env python from LLC_Membranes.llclib import fitting_functions import numpy as np from scipy.stats import levy_stable class TruncatedLevyDistribution: """ This class is meant to help approximate draws from a truncated levy distribution repeatedly with speed. The only way (that I know how) to draw f...
from .projectboard import PROJECT_BOARD from .database import PROJECT_CARDS from .gidgethub import GHArgs def get_create_card_ghargs(issue_or_pr_event, column='to_do'): column_id = PROJECT_BOARD['column_ids'][column] event_type = get_event_type(issue_or_pr_event) html_url = issue_or_pr_event.data[event_ty...
import fenics as fn from ElectrospraySimulator.Main_scripts.MAIN import MainWrapper # Copyright (C) 2020- by <NAME> # # This file is part of the End of Degree Thesis. # # This is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Fr...
# -*- coding: utf-8 -*- """ *************************************************************************** HelpEditionDialog.py --------------------- Date : August 2012 Copyright : (C) 2012 by <NAME> Email : <EMAIL>ayaf at gmail dot com ***********************...
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import functools def rsetattr(obj, attr, val): pre, _, post = attr.rpartition('.') return setattr(rgetattr(obj, pre) if pre else obj, post, val) def rgetattr(obj, attr, *args): def _getattr(obj, attr): return getattr(obj, ...
import sys import time import json import requests from PyQt5 import QtGui from PyQt5 import QtWidgets from PyQt5 import QtCore from PyQt5.QtCore import QThread, pyqtSignal, pyqtSlot import design class getPostsThread(QThread): add_post_signal = pyqtSignal(str) def __init__(self, subreddits): "...
import torch import torch.nn as nn import numpy as np from highway_env.utils import lmap import gym from MPC.casadi_opti import get_first_action import time def v_lmap(s, road_r, max_v): s = s.reshape(4, -1) x = s[0, :] y = s[1, :] theta = s[2, :] v = s[3, :] for i in range(50): x[i] =...
# -- Imports -- # exec("""\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nimport random\n""") # -- Used for the bomb image -- # bomb_image = QImage("bitcoin.png") # -- Define the board size -- # board = [(10, 10)] expandable = pyqtSignal(int, int) clicked = pyqtSignal() failed...
""" A CRNN model implementation. The earlier experiments, 07-uaf-lstm and 10-crnn-uaf-noisy use their own copy; They have not been refactored to use this implementation because that would trigger a lengthy rerun of the experiments. """ import collections import logging import sys import keras # type: ignore import num...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: victor # @Date: 2014-06-04 # @Last Modified by: victor # @Last Modified time: 2014-06-05 # @Copyright: # # This file is part of the AppVulnMS project. # # # Copyright (c) 2014 <NAME> <info AAET dornea DOT nu> # # Permission is hereby granted, free of...
""" from __future__ import absolute_import from __future__ import division from __future__ import print_function """ import torch import pdb from torch import nn import numpy as np from . import geom_utils from ..utils import cub_parse def triangle_direction_intersection(tri, trg): ''' Finds where an origin-...
import logging import time from sqlalchemy import create_engine from structlog import wrap_logger from config import Config logger = wrap_logger(logging.getLogger(__name__)) def execute_sql(sql_script_file_path=None, sql_string=None, database_uri=Config.DATABASE_URI): logger.debug('Executing SQL script', sql_s...
import os from enum import Enum from os.path import join, exists import argparse import pathlib import click import numpy as np import pandas as pd import download_data import dataframe import plotter from model_types import ModelTypes, model_types_map class HypModelTypes(Enum): STANDARD = ('Standard ResNet50',...
import argparse import copy import os import torch import torch.nn as nn import torch.optim as optim import context from embracenet_pytorch import EmbraceNet class BimodalMNISTModel(): def parse_args(self, args): parser = argparse.ArgumentParser() parser.add_argument('--model_learning_rate', type=float,...
from Database import Database import datetime from player import Player from board import Board, FullBoardError, PlayerAlreadyInBoard, WrongTurn, InsuficientPlayers, EmptyBoard import json import sys, traceback import time import asyncio import websockets, websockets.exceptions from _thread import start_new_thread cla...
#!/Users/kylemoore/miniconda3/bin/python #TODO clean up this code a bit """This file contains tree classes""" #imports from treelib import Node, Tree import pandas as pd import numpy as np from math import log import pdb """ DecisionTreeClassifier() * decide based on maximum gain what to split each node on *...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: alvin """ import os import glob import shutil prefix = ['sftp://alvin@172.16.31.10', 'sftp://robotarium.hw.ac.uk', 'sftp://172.16.31.10'] def list2string(lsof_strings, sort = True, linebreak = False, delimiter = ' '): if lsof_strings is None or lsof_s...
# 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 warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import...
from typing import Union from openpyxl.cell.cell import Cell from .exceptions import ( InvalidTemplateResource, InvalidTemplateResources, ) from .properties import Properties from .utils import get_and_validate_cell, sorted_data, Graph class Resource: PROPERTIES_ = ( TYPE, PROPERTIES, ...
import numpy import warnings from spt3g.maps import G3SkyMapWeights, G3SkyMap, FlatSkyMap # This file adds extra functionality to the python interface to G3SkyMap and # G3SkyMapWeights. This is done in ways that exploit a large fraction of # the evil things you can do in Python (Nick referred to it as "devil magic"), ...
"""This module includes the classes for JWTs and their validation. """ import pkgutil try: import jwt JWT_INSTALLED = True except ImportError: JWT_INSTALLED = False from ..base import Credential, CredentialValidator from ...misc.errors import AuthenticationError PYCRYPTO_SUPPORTED_ALGS = ["RS256", "RS3...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
# server def test_disk_free_space(Command): command = Command("df -P / | awk '/%/ {print $5}' | sed -e 's/%//'") assert int(command.stdout.strip()) <= 95 # elasticsearch def test_elasticsearch_running_and_enabled(Service): elasticsearch = Service("elasticsearch") assert elasticsearch.is_running as...
# included from snippets/main.py # included from libs/unionfind.py """ Union-Find Tree / Disjoint Set Union (DSU) """ def init_unionfind(N): global parent, rank, NUM_VERTEX NUM_VERTEX = N parent = [-1] * N rank = [0] * N def find_root(x): p = parent[x] if p == -1: return x p2 = ...
from tkinter import * from tkinter import filedialog from PIL import Image, ImageTk from tkinter.ttk import Frame, Style import os, time, cv2 import numpy as np from scipy.ndimage.morphology import distance_transform_edt import tkinter.messagebox as mbox from our_func_cvpr18 import cly_our_func, our_func, build...
import sys from projections import * from bayes import * import numpy as np import csv import random import sklearn import math import operator #import matplotlib.pyplot as plt import timeit from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.neighbors...
from __future__ import absolute_import, division, print_function, unicode_literals import pytest import math import numpy as np from rsbeams.rsstats.stats6d import specify_significant_figures as rs_sigfig import scipy from rsfbpic.rswake import lbn_wake # Specify values of relevant physical quantities... # number d...
import sublime import sublime_plugin import os _st_version = int(sublime.version()) if _st_version < 3000: from modules import conflict_re from modules import drawing_flags as draw from modules import git_mixin from modules import icons from modules import messages as msgs from modules import s...
import os from seguard.common import default_config import re import argparse import networkx as nx import numpy as np import matplotlib.pyplot as plt import pygraphviz import copy from sklearn.feature_extraction import DictVectorizer import pickle import subprocess from tqdm import tqdm from seguard.graph import Gra...
""" #---------------------------------------------------------------------- # This file is part of "Soft Cluster EX" # and covered by a BSD-style license, check # LICENSE for detail. # # Author: <NAME> # Contact: <EMAIL> # Homepage: http://riggingtd.com #-----------------------------------...
"""Script to analyze output of MC simulations of nucleosome chains.""" import re from pathlib import Path import pickle import matplotlib.cm as cm import numpy as np import seaborn as sns import pandas as pd from matplotlib import pyplot as plt import scipy from scipy import stats from scipy.optimize import curve_fit ...
from django.db.backends.base.base import BaseDatabaseWrapper from django.db.backends.base.creation import BaseDatabaseCreation from django.db.backends.base.features import BaseDatabaseFeatures from django.db.backends.base.validation import BaseDatabaseValidation import jaydebeapi as Database import sys from django.db ...
from ..types import ( Command, dataclass, field, Action, Distribution, StateDescription, DistributionDescription, MarkovDecisionProcess as MDP, imdict, defaultdict, ) from ..utils import ( itertools, operator, np, partition, flatten, Counter, reduce, ...
import datetime import minishogilib from optparse import OptionParser import queue import simplejson as json import subprocess import threading import time class Engine(): def __init__(self, name=None, command=None, cwd=None, verbose=False, usi_option={}, timelimit={}): self.name = name self.verbo...
# -*- coding: utf-8 -*- """ bromelia.etsi_3gpp_s6b.messages ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This module contains the Diameter protocol messages for 3GPP S6b Application Id. :copyright: (c) 2020-present <NAME>. :license: MIT, see LICENSE for more details. """ import platform import socket fro...
from copy import copy from operator import itemgetter from migen.fhdl.structure import * from migen.fhdl.structure import (_Operator, _Slice, _Part, _Assign, _ArrayProxy, _Fragment) class NodeVisitor: def visit(self, node): if isinstance(node, Constant): self...
import torch.nn as nn from collections import OrderedDict from .layers import ConvLayer, Noop, Flatten __all__ = ['act_fn', 'Stem', 'DownsampleBlock', 'BasicBlock', 'Bottleneck', 'BasicLayer', 'Body', 'Head', 'init_model', 'Net'] act_fn = nn.ReLU(inplace=True) class Stem(nn.Sequential): """Base ste...
#!/usr/bin/env python # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import argparse import builtins import math import os import random import warnings import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import ...
# -*- coding:UTF-8 -*- import urllib.request import time from bs4 import BeautifulSoup import re import os import tempfile class Properties: def __init__(self, file_name): self.file_name = file_name self.properties = {} try: fopen = open(self.file_name, 'r') for li...
"""Feeder for songs.""" import logging from dakara_base.exceptions import DakaraError from dakara_base.progress_bar import null_bar, progress_bar from path import Path from dakara_feeder.customization import get_custom_song from dakara_feeder.difference import generate_diff, match_similar from dakara_feeder.director...
import pandas as pd import numpy as np import matplotlib import matplotlib.pyplot as plt from timeit import default_timer as timer from pathlib import Path def calculate_measures(df, num_true_homographs): ''' Calculates and adds columns precision, recall and f1_score in the dataframe for each node. ...
import os from io import BytesIO from typing import BinaryIO from zipfile import BadZipFile import pytest from cidc_schemas.prism.extra_metadata import parse_elisa, parse_npx, parse_clinical from ..constants import TEST_DATA_DIR # Single NPX file and metadata npx_file_path = os.path.join(TEST_DATA_DIR, "olink", "ol...
# -*- coding: utf-8 -*- # @Author: <NAME> # @Email: <EMAIL> # @Date: 2021-05-14 19:42:00 # @Last Modified by: <NAME> # @Last Modified time: 2021-05-20 10:09:19 import numpy as np import matplotlib.pyplot as plt from ..core import NeuronalBilayerSonophore, PulsedProtocol, Batch from ..utils import si_format from ....
# coding: utf8 import sys import Queue as queue # in Python 3: import queue from traits.api import (HasTraits, Instance, DelegatesTo, Button, Str, List, Range) from traitsui.api import (View, HSplit, Tabbed, VGroup, Item, MenuBar, ToolBar, Action, Menu, EnumEditor, ListEditor, Group) from pyface.api import er...
#!/usr/bin/env python # Author: <NAME> # Disclaimer: # This ROS node is created as part of the Capstone Project where AEB and # collision avoidance by lane change for a vehicle based on camera #detection is the targeted outcome. # This code is an extension of the codes provided by the barc project ROS code-base develo...
# # PySNMP MIB module IANATn3270eTC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IANATn3270eTC-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:38:55 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
#!/usr/bin/env python # # Copyright 2007 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 o...
""" Loss 5 assumes symmetry and planarity, and optimizes over a single parameter, slant angle of the symmetry plane. """ import torch import torch.nn as nn import torch.nn.functional as F import numpy as np from optimize import loss5_torch from preprocess import get_edge_matrix, get_M_xcol2, get_adj import datetime f...
import pandas as pd import numpy as np import logging import os import math import logging import sys import os import random SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR)) from global_variables import config as g # ROOT_DIR = os.path.dirname(os.path.abspath("top_...
# # # # # # # # # # # # # # # # # # # # Created by <NAME> (<EMAIL>) # An open form solution to the string # pattern matching problem. # Example: # word = 'pricepricetag' # pattern = 'aab' # ----------------------- # yields--> Pattern match! # 'a'--> 'price' # 'a'--> 'price' ...
# Hitori Helper - Auxiliary Module def input_board (): print ('Enter row number: ', end = '') row_count = int (input ().strip ()) print ('Enter col number: ', end = '') col_count = int (input ().strip ()) board = [] for _ in range (row_count): board.append ([]) print ('Enter puzzle ...
import torch import torch.nn as nn import torch.nn.functional as F """ LAYERS: GCNConv and ChebNetConv """ class GCNConv(nn.Module): def __init__(self, in_features, out_features): super(GCNConv, self).__init__() self.linear = nn.Linear(in_features, out_features, bias=False) def forward(...
# -*- coding: utf-8 -*- import re import time from typing import Dict, List, Optional, Set, Tuple from urllib.error import URLError from urllib.request import urlopen from cx_Oracle import Cursor from .utils import load_exceptions, load_global_exceptions, load_terms DoS = Dict[str, Set[str]] LoS = List[str] Err = ...
from sklearn.model_selection._split import KFold as _KFold from sklearn.model_selection._split import ShuffleSplit as _ShuffleSplit from sklearn.model_selection._split import (_BaseKFold, BaseCrossValidator,_validate_shuffle_split,BaseShuffleSplit) from sklearn.utils.validation import _num_samples from sklearn....
import sys import os import re import argparse import shlex from PIL import Image, ImageDraw, ImageColor from pyocr.tesseract import image_to_string from masecret import __version__ from masecret.builders import ModifiedCharBoxBuilder from masecret.position_utils import offset_rect, padding_box, bounding_boxes_by_lin...
import torch import warnings from torch.utils.checkpoint import get_device_states, set_device_states, check_backward_validity def detach_variable(inputs): if isinstance(inputs, tuple): out = [] for inp in inputs: x = inp.detach() x.requires_grad = inp.requires_grad ...
# -*- coding: utf-8 -*- # Architecture module : manage working architecture and interface with BARF from barf.arch import ARCH_X86_MODE_32 from barf.arch import ARCH_X86_MODE_64 from barf.arch.x86.x86translator import X86Translator from barf.arch.x86.x86disassembler import X86Disassembler from barf.arch.x86.x86base ...
# ariadneplugin.py -- Contains classes and functoins necessary to implement a plugin architecture for # ariadne. import os import sys import tools import nose PLUGIN_TYPE_ARCHIVE="ArchivePlugin" PLUGIN_TYPE_GENERIC="Plugin" PLUGIN_TYPE_DATASET="DatasetPlugin" PLUGIN_TYPE_VALIDATION="ValidationPlugin" PLUGIN_TYPE_EXEC...
import numpy as np from utils import c_conj, c_distance, create_error, make_CDP_operator from tls_utils import tls_update_a def norm_estimate(y): # Estimate norm of signal from measurements return np.sqrt(0.5*np.sum(y)/y.shape[0]) def spectral_initialization(y, A, N, iterations): S = np.array(c...
#!/usr/bin/python3 import io import sys from concurrent.futures import ThreadPoolExecutor import collections import itertools import multiprocessing as mp import multiprocessing.connection from multiprocessing.context import ForkProcess from typing import Iterable, List, Optional, Any, Dict import dill from queue im...
from func.operations1d import * from func.sinc import SincConv_fast, Conv_0 from func.p2sgrad import P2SActivationLayer def drop_path(x, drop_prob): if drop_prob > 0.: keep_prob = 1.-drop_prob mask = torch.cuda.FloatTensor(x.size(0), 1, 1).bernoulli_(keep_prob) x.div_(keep_prob) x.mul_(mas...
import os import sys import datetime import logging from base64 import decodestring, b64decode from flask import Flask, render_template, g, session, request, redirect, make_response from flask_sqlalchemy import SQLAlchemy from flask.ext.babel import Babel, gettext, ngettext from smtplib import SMTP, SMTP_SSL from emai...
#!/usr/bin/python3 # -*- coding: utf-8 -*- from gtts import gTTS import pygame import time from os import remove from argparse import ArgumentParser import re, requests, warnings from six.moves import urllib from requests.packages.urllib3.exceptions import InsecureRequestWarning _args = ArgumentParser() _args.add_ar...
""" Module defining a base pipeline schema and custom fields For each pipeline a separate schema has to be defined which inherits from PipelineSchema. Such schema should be placed as an internal class of the implemented pipeline class """ from inspect import isclass from typing import Dict, List, Literal, Optional, Ty...
# MIT License. # Copyright (c) 2020 by BioicDL. All rights reserved. # Created by LiuXb on 2020/11/24 # -*- coding:utf-8 -*- """ @Modified: @Description: """ import threading import time import queue from deepclaw.driver.arms import URController_rtde as URctl from deepclaw.driver.arms.ArmController import ArmControl...
""" Serializers for Course Blocks related return objects. """ from django.conf import settings from rest_framework import serializers from rest_framework.reverse import reverse from lms.djangoapps.course_blocks.transformers.visibility import VisibilityTransformer from .transformers.block_completion import BlockComp...
"""Functions to execute MCMC training for BNN.""" import time import tqdm import numpy as np import tensorflow as tf import tensorflow_probability.python.edward2 as ed import util.bnn as model_util import tensorflow_probability as tfp def sample_parameter(sample_op, is_accepted_op, rv_names, mcmc_graph): """P...
from typing import Text, Any, Dict, List, Set, Union, Optional from dataclasses import dataclass from sagas.nlu.inspector_common import Inspector, Context from sagas.nlu.inspectors import NamedArgInspector from sagas.nlu.registries import registry_sinkers, named_exprs from sagas.conf.conf import cf import logging impor...
""" Procedure: First run: ./inference_networks.py before running this analysis file. """ import math import pickle import sys from scipy.stats import describe # --- DATA PARAMETERS --- from experiments.inference_networks import net_template_paths, nb_iterations, \ results_dir, conversion_sample_counts, infer...
import time from copy import deepcopy import sys import os sys.path.append(os.getcwd() + '/src') import math import numpy as np import PyExpUtils.runner.Slurm as Slurm import PyExpUtils.runner.parallel as Parallel from PyExpUtils.results.backends.h5 import detectMissingIndices from PyExpUtils.utils.generator import gro...
""" Utility to save go positions as psgo tex files. """ from time import sleep, strftime import os import sys from asciimatics.screen import Screen from asciimatics.event import KeyboardEvent import win32clipboard from renderer import Renderer from state import State from board import Board def _cursor_move_hand...
from typing import List, Optional, Any, Iterable, Tuple def test(given: Any, expected: Any) -> bool: ret = given == expected if not ret: print(f"{given} != {expected}") return ret def using_mode(mode: int, memory: List[int], address: int) -> int: if mode == 0: return memory[address...
from minerva.gimmebio.kmers import MinSparseKmerSet from minerva.gimmebio.readclouds import iterReadClouds from itertools import combinations import numpy as np import sys ################################################################################ def parseBarcodesAndRemoveStopKmers(filelike, K, W, dropout, ...
import numpy as np from numpy.fft import fft2, ifft2, ifftshift from scipy.stats import multivariate_normal from menpo.shape import PointDirectedGraph def pad(pixels, ext_shape, boundary='constant'): _, h, w = pixels.shape h_margin = (ext_shape[0] - h) // 2 w_margin = (ext_shape[1] - w) // 2 h_mar...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from typing import Callable, Optional import torch import torch.nn as nn from pytorchvideo.models.resnet import ResBlock class SqueezeAndExcitationLayer2D(nn.Module): """2D Squeeze and excitation layer, as per https://arxiv.org/pdf/1709.015...
import abc import enum import operator import pickle from functools import reduce from typing import Callable, Generator, List, Optional, Tuple import numpy as np import pydantic import torch from torch.utils.data import Dataset, random_split from tqdm.auto import tqdm from src.helpers import constants class ModelT...
import numpy as np import math from scipy.stats import truncnorm, norm from scipy.special import erfc from collections import defaultdict from operator import mul, truediv, eq, ne, add, ge, le, itemgetter mapDirn = {'True' : "+", 'False' : "-"} complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N' : 'N'} # TN ...
from utils import * import torch.nn.functional as F from torch.autograd import Variable from torch.autograd.gradcheck import zero_gradients from torch.utils.data.sampler import SubsetRandomSampler import time CE_loss = nn.CrossEntropyLoss() def max_margin_loss(x, y, num_cla=10): B = y.size(0) corr = x[range(B...
# Copyright (c) 2015 Cisco Systems # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, ...
import csv import random import colorama class Color: """Class containing some common methods used for colorama.""" def __init__(self): colorama.init() def reset(self): print(colorama.Style.RESET_ALL) def setRedText(self): print(colorama.Fore.RED) def setGreenText(self):...
import numpy as np import tensorflow as tf from vis import grid_vis class GAN: def __init__(self, z_dim=50, img_h=28, img_w=28, img_c=1, dataset_name='', gan_type=''): self.z_dim = z_dim self.img_hwc = (img_h, img_w, img_c) self.img_dim = img_h * img_w * img_c self.dataset_name = da...