text
stringlengths
3.07k
12.6k
# -*- coding: utf-8 -*- # Octowire Framework # Copyright (c) ImmunIT - <NAME> / <NAME> # License: Apache 2.0 # <NAME> / Eresse <<EMAIL>> # <NAME> / Ghecko <<EMAIL>> import ctypes import os import pkg_resources import platform import re import requests import subprocess import sys import tarfile import tempfile bit...
"""BNN MCMC Forward pass helper functions.""" import json import logging import os from pathlib import Path import numpy as np from psych_metric.distrib.bnn.bnn_mcmc import BNNMCMC def load_sample_weights(weights_dir, filename='.json', dtype=np.float): """Loads the sampled bnn weight sets from directory recursi...
import re from glob import glob from pathlib import Path from typing import AnyStr from typing import Tuple from typing import Union import click import requests import urllib3 class Linter: CONTENT_TAG = "content" DRY_RUN_TAG = "dry_run" STATUS_TAG = "status" ERROR_TAG = "errors" VALID_TAG = "va...
""" Simple connector between Dexcom's developer API and elasticsearch """ import json import logging import os import time from datetime import datetime, timedelta import elasticsearch import elasticsearch.helpers import requests import dexcom.settings as settings logging.basicConfig(level=logging.INFO) log = loggin...
from bs4 import BeautifulSoup from urllib.request import urlopen, Request import locale import number import pyodbc from datetime import datetime locale.setlocale(locale.LC_ALL, 'es_Cl.UTF8') 'SQL Server' conn = pyodbc.connect('Driver={SQL Server};' 'Server=;' 'Database=Yap...
#!/usr/bin/env python # coding: utf-8 # import package import tkinter as tk import pandas as pd import matplotlib.pyplot as plt from tkinter import filedialog from tkinter.filedialog import askopenfilename from tkinter import ttk from comut import comut from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg ...
""" Get generations from PPLM for the recipe rewrite task. """ import argparse import sys import re import time import csv import pandas as pd from run_pplm import run_pplm_example_recipe start = time.time() parser = argparse.ArgumentParser() parser.add_argument('--data_dir', type=str, default='sample_data') parser...
#!/usr/bin/env python """ This script builds the binary distribution for multiple IDA versions in one batch. The MIT License (MIT) Copyright (c) 2017 <NAME> <<EMAIL>> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentati...
# 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 use t...
from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException import urllib.parse import re import pandas as pd PROPERTY_TRENDING_URL = 'https://property.hk/property_search.php?bldg='+urllib...
from __future__ import absolute_import, unicode_literals import sys import typing from docutils import nodes from sphinx.environment import NoUri APPATTRS = { 'amqp': 'celery.app.amqp.AMQP', 'backend': 'celery.backends.base.BaseBackend', 'conf': 'celery.app.utils.Settings', 'control': 'celery.app.co...
#!/usr/bin/env python3 import logging import time from typing import Dict, List, Optional, Tuple import numpy as np import torch from sklearn.datasets import ( load_breast_cancer, load_digits, load_iris, load_boston, load_diabetes, ) from sklearn.ensemble import ( AdaBoostClassifier, Baggin...
from __future__ import annotations import numpy as np import pandas as pd from sklearn import datasets from IMLearn.metrics import mean_square_error from IMLearn.utils import split_train_test from IMLearn.model_selection import cross_validate from IMLearn.learners.regressors import PolynomialFitting, LinearRegression, ...
""" Base IO code for all datasets. """ import configparser import os from pathlib import Path import pandas as pd import requests def get_project_root(): return Path(__file__).parent.parent def get_root_data_dir(): """Return the path of the top level data dir.""" root_data_dir = os.environ.get( ...
import parmed from collections import OrderedDict import itertools import tempfile import os from copy import deepcopy from tools.amino_acids import standard_amino_acids from ampal.ampal_databases import element_data from ampal.protein import Polypeptide, Residue from ampal.assembly import Assembly, AmpalContainer fro...
import torch import numpy as np from math import sqrt from torch import nn class MultiHeadAttention(nn.Module): def __init__(self, hidden_dim:int, n_heads:int, dropout:float=0.) -> None: super(MultiHeadAttention, self).__init__() assert hidden_dim % n_heads == 0, "hidden_dim must be div by n_heads...
#Copyright (C) 2013 by <NAME> # #Released under the MIT license, see LICENSE.txt '''CDR3 length distribution: Reads and Clones % reads/% clones (yaxis) vs CDR3 aa_length (xaxis) ttests: 1/ for the median length of group1 vs group2 2/ for each length, compare the proportion (reads/clones) in group1 vs ...
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 """ The functions here interact with uw_gws """ import logging import re import traceback from uw_gws import GWS from uw_gws.models import Group, GroupEntity, GroupMember from uw_trumba.models import ( is_valid_campus_code, EDI...
# !/usr/bin/env python3 import re import os from datetime import datetime from flask import Blueprint, render_template, request, current_app, abort, \ flash, redirect from flask_mail import Mail, Message from werkzeug.utils import secure_filename from itsdangerous import TimestampSigner from cabrillo.parser import...
import logging import threading import time import wx from cellprofiler_core.setting import ValidationError import cellprofiler.gui.constants.module_view as mv_constants from cellprofiler.gui.module_view._validation_request_controller import ( ValidationRequestController, ) def text_control_name(v): """Retur...
import re from docutils import nodes from docutils.statemachine import ViewList from sphinx.directives.code import CodeBlock from sphinx.util.docutils import SphinxDirective from sphinx.util.nodes import nested_parse_with_titles from yamcs.api import annotations_pb2 class ProtoDirective(CodeBlock): required_arg...
import copy from datetime import datetime from pathlib import Path from typing import Optional, Dict import fire import pandas as pd from aim import Session from aim.tensorflow import AimCallback from tensorflow.keras.callbacks import CallbackList, ModelCheckpoint, EarlyStopping, TensorBoard, ReduceLROnPlateau from te...
# -*- coding: utf-8 -*- # Copyright (c) 2019 tecnovert # Distributed under the MIT software license, see the accompanying # file LICENSE.txt or http://www.opensource.org/licenses/mit-license.php. import struct import time import sqlalchemy as sa from sqlalchemy.ext.declarative import declarative_base CURRENT_DB_VERS...
#!/usr/bin/env python3 from flask import Flask from flask import jsonify from flask import request import camera import config app = Flask(__name__) def getFrame(input, output): cfg = config.getConfig() width = cfg['camera']['width'] height = cfg['camera']['height'] ros = cfg['worker_ros'] ros2 = cfg['upload_r...
#!/usr/bin/env python from __future__ import absolute_import, division, print_function, unicode_literals from io import StringIO NEGATIVE_PREFIX = "," BASE = 66 HHC_ALPHABET = "-.0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~" LEGACY_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopq...
## @file genetic.py # @author <NAME> # # @brief This file contains the genetic algorithm # @{ ## Import modules from database import Database from net import * import _pickle as pickle import random from collections import OrderedDict import numpy ## Genetic algorithm method # Reads the neural networks from dat...
import argparse import ast import inspect import sys import textwrap from collections import defaultdict from copy import deepcopy # gleaned from https://raw.githubusercontent.com/pypa/setuptools/main/docs/userguide/declarative_config.rst from typing import Dict, Any, List METADATA_KEYS = { "name": "str", "v...
""" Support for visonic partitions control when used with a connection to a Visonic Alarm Panel. Currently, there is only support for a single partition Initial setup by <NAME> """ import logging import custom_components.pyvisonic as visonicApi # Connection to python Library import homeassistant.components.alar...
import argparse import mxnet as mx import os import logging def get_fine_tune_model(sym, num_classes, layer_name): all_layers = sym.get_internals() net = all_layers[layer_name + '_output'] net = mx.symbol.FullyConnected(data=net, num_hidden=num_classes, name='new_fc') ...
# -*- coding: utf-8 -*- # Copyright (c) 2020, <NAME> and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import throw, _, _dict from frappe.model.document import Document from frappe.core.doctype.data_export.exporter import export_data ...
import json import os import time import subprocess import tempfile import itertools from collections import defaultdict import numpy as np from .reliability_checks import probability_recovery, runtime_complexity, memory_complexity class ImplementationProfiling: def __init__(self, implementation, config, scalin...
#!/usr/bin/env python3 # WebFaction Dynamic DNS Updater import os import sys import time import argparse import datetime import configparser import ipaddress import urllib.parse import urllib.request import xmlrpc.client VERSION = '0.1.2' class WFAPI: endpoint = 'https://api.webfaction.com/' # API session ...
'''https://practice.geeksforgeeks.org/problems/edit-distance3702/1 https://www.geeksforgeeks.org/edit-distance-dp-5/ Edit Distance Medium Accuracy: 49.98% Submissions: 44405 Points: 4 Given two strings s and t. Return the minimum number of operations required to convert s to t. The possible operations are permitted: ...
import numpy as np import types import scipy.signal import scipy.interpolate from slippy.core import _SurfaceABC __all__ = ['ACF'] class ACF(object): """ A helper class for auto correlation functions Produces ACFs that are independent ot the original grid spacing, these can be used to generate random su...
#!/usr/bin/python3.7 #Written by: <NAME> - D4Vinci ( QrlJacker-Framework ) import sys, os, time, random, importlib, readline, atexit from .color import * from terminaltables import AsciiTable as table from urllib.request import urlopen def banner(m): #Choose a random banner and prints it os.system("clear") ...
# Copyright 2019 The nn_inconsistency Authors. 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 a...
from direct.directtools.DirectGeometry import * from direct.showbase.DirectObject import DirectObject from direct.task import Task class PieMenu(NodePath, DirectObject): def __init__(self, visibleMenu, menuItems, action = None, fUpdateOnlyOnChange = 1, selectedSF = 1): NodePath.__init__(s...
""" Pipelining functions for graph data. Included prebatch preprocessing, batching and post-batch manipulations. These will be replaced by tf operations once we transition to eager mode first. """ from __future__ import annotations import abc import functools import itertools import warnings from typing import ( ...
#import modules from sympy import * import numpy as np import random as rd import pandas as pd #----------------------------------------------------------------------- #Define functions #---------------------------------------------------------------------- def get_partial_derivs(equation_list, state_variables): ...
#!/usr/bin/env python # # MIT License # # Copyright (c) 2017, <NAME> <<EMAIL>> # # 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 #...
""" Description: construct the NLP Transformer model here Author: <NAME>. @ AI - Camp Date: Spring 2022 """ from tabnanny import verbose from transformers import BertForSequenceClassification, AdamW, get_linear_schedule_with_warmup from text_preprocessing import clean_texts import config import torch import...
# This file is based on # https://github.com/jessevig/bertviz/blob/master/bertviz/attention_map.py. # # Original Author <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://w...
from collections import namedtuple import os import re import numpy as np import pandas as pd import spacy def flatten(it): """ Flatten an arbtirarily deeply nested iterable. :param it: iterable to flatten :return: generator that flattens the iterable. """ for i in it: ...
import py from pypy.rpython.lltypesystem import llmemory, lltype from pypy.annotation.model import SomeAddress, SomeChar from pypy.rlib.objectmodel import free_non_gc_object from pypy.translator.llvm.test.runtest import * def test_null(): def f(): return llmemory.NULL - llmemory.NULL fc = compile_fun...
""" 4 kyu: Breadcrumb Generator http://www.codewars.com/kata/breadcrumb-generator/train/python As breadcrumb menùs are quite popular today, I won't digress much on explaining them, leaving the wiki link to do all the dirty work in my place. What might not be so trivial is instead to get a decent breadcrumb from your...
""" This implementation is mostly copied from asyncio.tasks (Python 3.8) while making the necessary changes. :copyright: 2021 <NAME> :license: Apache2, see LICENSE for more details. """ import sys from asyncio import CancelledError, ensure_future, TimeoutError try: from asyncio import get_running_loop except Impo...
import torch from torch.utils.data import DataLoader from utils.dataset import VOCDataset from nets.nn import YOLOv1 from utils.loss import Loss import os import math import tqdm import argparse import numpy as np from collections import defaultdict parser = argparse.ArgumentParser(description='YOLOv1 implementation...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Project start date: Thurs 11/19/2020 @author: <NAME> A GUI-less mockup for PySimpleGUI/MySimpleGUI Version: 0.13.1 Check out project: https://github.com/gilbh/PySimpleNoGUI """ from sys import exit, argv from time import sleep from pathlib import Path from traceba...
"""The main runner for med ai models""" import traceback import uuid from typing import List from collections import defaultdict from celery import Celery import time import settings from services import logger_service, classifier_service, eval_service, experiment_service, messaging_service, model_service, orthanc_se...
import re import json import tempfile import logging import requests from mrjob.job import MRJob from datetime import datetime from urllib.parse import urlparse logger = logging.getLogger(__name__) def run_cdx_index_job_with_file(input_file, cdx_endpoint): # Read input file list in as items: # Run the given j...
"""General utility classes and functions. .. testsetup:: from sloth.utils.utils import * """ import os from os.path import isfile, isdir, join import sys import contextlib from .. import config class SlothException(Exception): """Root exception""" class IllegalSolverState(SlothException): """Unexpecte...
import logging import time import torch from loss.heatmaploss import HeatmapLoss from loss.offsetloss import OffsetLoss from loss.refineloss import RefineLoss class Trainer(object): def __init__(self, cfg, model, rank, output_dir): self.model = model self.output_dir = output_dir self.rank ...
import argparse import os import subprocess import moxing as mox _CACHE_DATA_URL = "./cache/data" _CACHE_TRAIN_URL = "./cache/train" def _parse_args(): parser = argparse.ArgumentParser('mindspore maskrcnn_mobilenetv1 training') parser.add_argument('--train_url', type=str, default='obs://neu-base/maskrcnn_1/m...
from flask import make_response, send_from_directory from .forms import PelengateProblem import matplotlib import json matplotlib.use('Agg') import matplotlib.pyplot as plt from io import StringIO, BytesIO import numpy as np class MatrixNewtonMethod: ALLOWED_FUNCTIONS = { 'max': np.fmax, 'mi...
import asyncio import json import typing from http import cookies as http_cookies from starlette.datastructures import URL, Address, Headers, QueryParams from starlette.formparsers import ( FormData, FormParser, MultiPartParser, parse_options_header, ) from starlette.requests import SERVER_PUSH_HEADERS...
"""This file contains the estimators: - ConstantImputedLR - ExpandedLR - EMLR - ConstantImputedMLPR - MICELR """ import numpy as np from sklearn.base import BaseEstimator, RegressorMixin from sklearn.linear_model import LinearRegression, RidgeCV from sklearn.neural_network import MLPRegressor from ...
import torch from torch.utils.data import DataLoader import logging from cormorant.cg_lib import rotations as rot from cormorant.data import collate_fn def _gen_rot(data, angles, maxl): alpha, beta, gamma = angles D = rot.WignerD_list(maxl, alpha, beta, gamma) R = rot.EulerRot(alpha, beta, gamma) return D, R ...
#!/usr/bin/env python import PySimpleGUI as sg import random import time """ Pong code supplied by <NAME> (Neonzz) Modified. Original code: https://www.pygame.org/project/3649/5739 """ class Ball: def __init__(self, canvas, bat, bat2, color): self.canvas = canvas self.bat = bat ...
import argparse, os, subprocess, concurrent.futures, multiprocessing, sys from Bio.Blast.Applications import NcbiblastpCommandline from Bio import SeqIO from dendropy import Tree work_dir = os.getcwd() + "/" parser = argparse.ArgumentParser(description='Tests orthologous group for potential orthology to closest pote...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import six import sys import csv import json import yaml import codecs import logging import archieml import validictory import frontmatter from django.apps import apps from datetime import datetime from django.core.serializers.base import DeserializationError fro...
from visualization_msgs.msg import Marker,MarkerArray from geometry_msgs.msg import PoseStamped, Pose, Point, Quaternion import rospy import numpy as np #colormap from matplotlib import cm color_rbg_usercmd = [0.1, 0.7, 0.1] color_rbg_assistcmd = [0.9, 0., 0.05] class VisualizationHandler: def __init__(self): ...
# # Pyserini: Reproducible IR research with sparse and dense representations # # 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...
from PySide2.QtCore import * from models.data_structure import List from models.constants import PropType, PyomoVarType, DatasetResolution, DisplayType class PropertyValue(QObject): """data stored for property value with unit information @param: name(str) @param: value(str) @param: unit(str) @sig...
import math import numpy as np import copy def solve_transform(p1, p2, p3, p4): block = np.matrix([ [p1[0][0], p1[0][1], p1[0][2], 1], [p2[0][0], p2[0][1], p2[0][2], 1], [p3[0][0], p3[0][1], p3[0][2], 1], [p4[0][0], p4[0][1], p4[0][2], 1] ]) M = np.kron(np.eye(3, dtype=int)...
import numpy as np import pandas as pd from PIL import Image PADDING_SIZE = 20 IMAGE_SIZE = 256 BATCH_SIZE = 4 ALL_WORD = ['<none>', '', 'statement', 'if', 'else', 'elseif', 'while', 'end', '<START>', '<END>'] N_ONEHOT_WORD = len(ALL_WORD) CHARS_MAP = {v: k for k, v in enumerate(ALL_WORD)} from keras.layers import ...
#!/usr/bin/env python3 import glob import gzip import os import subprocess import threading import time # Where logs and sampled data will wind up, and where the sequences are read. # Do note that the sequences variable is supposed to be a tuple, because you # could have multiple sets of sequences. logdir = "/tmp...
from skdecide.builders.discrete_optimization.generic_tools.do_problem import Problem, EncodingRegister, TypeAttribute, ObjectiveHandling from deap import creator, base, tools, algorithms import random from typing import Union, Optional, Any, Dict, List import numpy as np from enum import Enum from skdecide.builders.dis...
from mbi import LocalInference import numpy as np import argparse from hdmm import workload, templates, error from mbi import Dataset import itertools from autodp import privacy_calibrator import os import pandas as pd import pickle """ This is an implementation of HDMM+APPGM as described in the paper "Relaxed Margin...
#!/usr/bin/env python from collections import deque, namedtuple import os import shutil import string import sys import numpy as np from tqdm import tqdm import project CONTENT_DIR = os.path.join(project.UAF_DIR, 'content') TRAIN_FILE = os.path.join(project.UAF_DIR, 'train.csv') VALID_FILE = os.path.join(project.UA...
# File for handling imports, reimports, and registering/unregistering of all parts of the add-on. # Credit for the structure and explanation behind this __init__.py file goes to one very informative tutorial: # "Creating multifile add-on for Blender", by Nikita from Blender - Interplanetary # Link: https://b3d.interpla...
"""Provides methods and classes to translate various data types to and from the hex format. This module is heavily based off of other data format modules, like :mod:`json` and :mod:`pickle`. See Also: - `Hexadecimal on Wikipedia <https://en.wikipedia.org/wiki/Hexadecimal>`_ """ import binascii import typing as t...
import tensorflow as tf """ def drc_projection2(transformed_voxels): # swap batch and Z dimensions for the ease of processing input = tf.transpose(transformed_voxels, [1, 0, 2, 3, 4]) y = input x = 1.0 - y v_shape = tf.shape(input) size = v_shape[0] print("num z", size) # this part ...
# # Copyright (c) 2011-2014 The developers of Aqualid project - http://aqualid.googlecode.com # # 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 limitati...
from typing import TYPE_CHECKING from electroncash import cashaddr from modules.coins.network import CoinNetwork from modules.electrum_mods.functions import hash160_to_p2pkh, address_to_script, script_to_scripthash, hash_160 if TYPE_CHECKING: from modules.electrum_mods import PartialTransaction, BIP32Node clas...
import datetime import time import logging from django.core.cache import cache, caches from django.core.exceptions import ImproperlyConfigured from rest_framework.settings import api_settings from rest_framework.throttling import UserRateThrottle, SimpleRateThrottle __all__ = ( 'SearchUserRateThrottle', 'par...
import framebuf from micropython import const # register definitions SET_CONTRAST = const(0x81) SET_ENTIRE_ON = const(0xa4) SET_NORM_INV = const(0xa6) SET_DISP = const(0xae) SET_MEM_ADDR = const(0x20) SET_COL_ADDR = const(0x21) SET_PAGE_ADDR = const(0x22) SET_DISP_START_LINE = const(0x40) SET_SEG_REMAP = c...
""" SC101 Baby Names Project Adapted from <NAME>'s Baby Names assignment by <NAME>. YOUR DESCRIPTION HERE """ import tkinter import babynames import babygraphicsgui as gui FILENAMES = [ 'data/full/baby-1900.txt', 'data/full/baby-1910.txt', 'data/full/baby-1920.txt', 'data/full/baby-1930.txt', 'data/full/...
from .app import app, db from .models import Page, PageVersion, User from flask import jsonify, request import inspect class InvalidArgument(Exception): status_code = 400 def __init__(self, message, payload=None): super().__init__(self) self.message = message self.payload = dict(payloa...
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore import threading import datetime as dt import numpy as np cred = credentials.Certificate( "/Users/alex/Downloads/VS Code/project-argus/fir-py-c779c-firebase-adminsdk-gmpay-0f1a3c1852.json") firebase_admin.initialize_...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from collections import OrderedDict from .fields import BaseField from .errors import ArgumentError from .connection import Connection log = logging.getLogger('yamo') class EmbeddedDocumentType(type): """ This is a type that generates EmbeddedDoc...
import wandb import copy from core.run.event_dispatcher.register import EventRegister class WandbLogger: def __init__(self, wandb_instance: wandb.wandb_sdk.wandb_run.Run, logging_frequency: int, prefix=None, with_epoch=False): self.instance = wandb_instance self.logging_frequency ...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** 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 _utilities from...
import time from Jumpscale import j def info(message): j.tools.logger._log_info(message) def rand_string(): return j.data.idgenerator.generateXCharID(10) def rand_num(start=100, stop=1000): return j.data.idgenerator.generateRandomInt(start, stop) skip = j.baseclasses.testtools._skip client = "" CO...
#!/usr/bin/env python3 """Functional Python Programming Chapter 7, Example Set 4 """ # pylint: disable=wrong-import-position,reimported # Even more generic Rank-Order processing. # from collections import namedtuple # Rank_Data = namedtuple("Rank_Data", ("rank_seq", "raw")) from typing import NamedTuple, Tuple, Any...
import os import argparse from collections import Counter import torch from fvcore.nn import flop_count_table from detectron2.utils.analysis import ( FlopCountAnalysis, parameter_count_table, ) from detectron2.utils.logger import setup_logger from e2edet.utils.configuration import load_yaml from e2edet.model i...
import numpy as np import glob import os import sys def sample_data(data, num_sample): """ data is in N x ... we want to keep num_samplexC of them. if N > num_sample, we will randomly keep num_sample of them. if N < num_sample, we will randomly duplicate samples. """ N = data.shape[...
"""Overview of all modules and corresponding upload functions and insertion through forms""" import os from werkzeug.utils import secure_filename from flask import Blueprint, render_template, request, redirect, flash, url_for from ..db import PvModule, FlasherData, ManufacturerData, db from ..forms import PvModuleFor...
import argparse import csv import itertools from pathlib import Path from pyxtension.streams import stream import shutil from PIL import Image import imagehash import HeifImagePlugin import re import os def main(): # Initialize argument parser. parser = argparse.ArgumentParser(description='Merger...
import xml.etree.ElementTree as ET def parse_cadence(row: str) -> int: """Parses cadence value string 'Xrpm' and returns X as int""" keyword = 'rpm' if keyword not in row: return -1, row if ',' in row: keyword += ',' cadence, rest = row.split(keyword) if '/' in cadence: cadence = sum([int(...
import logging import os from collections import defaultdict from contextlib import contextmanager from dagster import check from dagster.config.source import StringSource from dagster.core.storage.pipeline_run import PipelineRunStatus from dagster.core.storage.sql import ( check_alembic_revision, create_engin...
# This pruning technique tries to prune weights that affects spectrum of layer weight import os import torch import torch.nn as nn import torch.nn.functional as F import types import snip import math ## Following code is for computing first and last singular values using Power iteration # def compute_sv(W, num_iters=...
################################################################## # Copyright 2018 Open Source Geospatial Foundation and others # # licensed under MIT, Please consult LICENSE.txt for details # ################################################################## """Unit tests for complex validator """ import uni...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** 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 from ... import _utilities, _tables from...
import click import geojson from shapely.geometry import box import tilematrix from tilematrix import TilePyramid @click.version_option(version=tilematrix.__version__, message='%(version)s') @click.group() @click.option( '--pixelbuffer', '-p', nargs=1, type=click.INT, default=0, help='Tile bounding box buffe...
################################################################ # import libraries ################################################################ import os import csv import json import uuid import time import datetime import discord # es imports from elasticsearch import Elasticsearch, helpers ###################...
import math import sys import pickle import time import numpy as np from typing import List, Tuple, Dict, Set, Union import sklearn from sklearn.metrics import precision_recall_fscore_support, accuracy_score from readerUtils import read_discussion_forum, torch_from_json, generate_indices, read_reddit_data, \ rea...
import numpy as np import pandas as pd import matplotlib.pyplot as plt class BaseRegressor(): def __init__(self, num_feats, learning_rate=0.1, tol=0.001, max_iter=100, batch_size=12, epsilon=1e-5): # initializing parameters self.W = np.random.randn(num_feats + 1).flatten() # assigning hyper...
# # Copyright 2014 OpenStack Foundation # 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 req...
from __future__ import absolute_import from __future__ import print_function # -*- coding: utf-8 -*- import numpy as np import random from keras.layers import Input, Flatten, Dense, Dropout, Lambda, merge,Activation,BatchNormalization from keras.callbacks import ModelCheckpoint, EarlyStopping,CSVLogger from ke...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import torch import numpy as np import skimage.io as io # from FaceSDK.face_sdk import FaceDetection # from face_sdk import FaceDetection import matplotlib.pyplot as plt from matplotlib.patches import Rectangle from skimage.transform import Simi...