text
stringlengths
3.07k
12.6k
import discord import random import datetime class MemoButton(discord.ui.Button["Memo"]): # Button Logic def __init__(self, x: int, y: int, cell_value): if cell_value == None: super().__init__(style=discord.ButtonStyle.secondary, label="❓", disabled=True, row=x) ...
import cv2 as cv import numpy as np import random import xml.etree.ElementTree as ET NUMBER = 7 #画像1枚当たりの牌の枚数 size_x = 512 size_y = 512 mode = 10 #ロバストする確率 dict={"0":"1m","1":"2m","2":"3m","3":"4m","4":"5m","5":"6m","6":"7m","7":"8m","8":"9m","9":"1p","10":"2p","11":"3p","12":"4p","13":"5p","14":"6p","15":"7p",...
""" Plugin for basic commands Commands: roll feature """ import random from re import match import discord import bot import plugins from pcbot import utils, Config, Annotate client = plugins.client # type: bot.Client feature_reqs = Config(filename="feature_requests", data={}) @plugins.command() async ...
""" Implementation of https://eprint.iacr.org/2020/152 ``Compressed Σ-Protocol Theory and Practical Application to Plug & Play Secure Algorithmics'' Protocols: * Protocol 2, page 13: Pi_s ("pivot") """ import os import sys import hashlib from random import SystemRandom project_root = sys.path.append(o...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import re import argparse from logging import getLogger, DEBUG, StreamHandler logger = getLogger(__name__) logger.addHandler(StreamHandler()) ids = { '千代田': { 'autonomy': '区', 'id': 'chiyoda' }, '中央': { 'autonomy': '区', 'id': 'chuo' }, '港': { 'autonomy'...
# # Created on March 2022 # # Copyright (c) 2022 <NAME> # import os import torch import argparse import pytorch_lightning as pl from pytorch_lightning.loggers import NeptuneLogger import numpy as np from src.AE_ClusterPipeline import AE_ClusterPipeline from src.datasets import MNIST, REUTERS from src.embbeded_dataset...
import logging from config import Config as cfg import util.db as db from util.Constants import Constants as cs import pickle as pkl import os import matplotlib.pyplot as plt import re import numpy as np import pandas as pd import shutil logging.basicConfig(format='%(levelname)s:%(message)s', level=cfg.logging_level) ...
""" This module contains code for data retrieval and sampling. Preprocess of data took place in advance of this file. """ from solardataretrieval import utilities import boto3 from solardatatools.clear_day_detection import filter_for_sparsity from solardatatools import find_clear_days from io import BytesIO import pan...
from io import BytesIO import argparse import random import cv2 import numpy as np from matplotlib import pyplot as plt from albumentations import ( Compose, ToFloat, FromFloat, RandomRotate90, Flip, HorizontalFlip, OneOf, MotionBlur, MedianBlur, Blur, ShiftScaleRotate, OpticalDistortion, GridDistort...
# Copyright (c) 2018 Commissariat à l'énergie atomique et aux énergies alternatives (CEA) # Copyright (c) 2018 Centre national de la recherche scientifique (CNRS) # Copyright (c) 2018-2020 Simons Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in complia...
import sys sys.path.insert(1, '../') import sveCacheSim as sim import numpy as np from elftools.elf.elffile import ELFFile #conda install pyelftools # HOW TO USE: # An example is at the bottom of this file, in __main__. # Basically, you just need to create a DWARFMap object by giving it # the executable with dwarf inf...
from utils import * def attention(query, key, value, mask=None, dropout=None): "Compute 'Scaled Dot Product Attention'" d_k = query.size(-1) scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(d_k) if mask is not None: scores = scores.masked_fill(mask == 0, -1e9)...
"""Main entry point for the API service.""" from typing import List, Optional import uuid import datetime from fastapi import FastAPI, Query, status, HTTPException from fastapi.middleware.cors import CORSMiddleware import uvicorn from models import User, Item, ItemResponse, Status import data_access app = FastAPI( ...
from io import BufferedWriter from queue import LifoQueue from struct import pack def scanner(octree): def process(data): nonlocal lastlevel for i in range(lastlevel - data["level"]): counter.put(0) lastlevel -= 1 yield Command.create_node() ...
#!/usr/bin/env python3 """ Script to test the time complexity """ # Imports # Standard lib import pathlib import time # 3rd party import numpy as np import matplotlib.pyplot as plt # Our own imports from hw1 import algs # Range of sizes to test ARRAY_SIZES = np.arange(100, 1100, 100) # Number of random vectors ...
import os import ipdb import torch import pickle import numpy as np import collections from tqdm import tqdm import pandas as pd from captum.attr import IntegratedGradients from captum.attr import visualization def load_save_json(json_path, mode, verbose=1, encoding='utf-8', data=None): if mode == 'save': ...
import os import string import numpy as np from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from sklearn.metrics.pairwise import cosine_similarity from nltk.translate.bleu_score import corpus_bleu from stanfordcorenlp import StanfordCoreNLP import argparse from tqdm import tqdm import collectio...
import os import matplotlib.pyplot as plt import matplotlib.image as mpimg import math import time import random coef1 = 1.48 coef2 = 1.43 coef3 = 1.39 coef = coef1 def get_point_with_diff_color(img, start_x, start_y, end_x, end_y, allow_range=0.1, ignore_x=(), ignore_y=()): for y in range(start_y, end_y): ...
import argparse import logging import os import json import collections from agents.bert_agent.methods.baseline.dataset.dialog import flatten_variables logging.basicConfig(format='%(asctime)s: %(levelname)s: %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger =...
from pdchaosazure.vmss.constants import RES_TYPE_VMSS_VM, RES_TYPE_VMSS def provide_instance(os_type: str = 'Linux'): return { 'name': 'chaos-pool_0', 'instance_id': '0', 'type': RES_TYPE_VMSS_VM, 'storage_profile': { 'os_disk': { 'os_type': os_type ...
#!/usr/bin/env python3 # Copyright 2020 Efabless Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# coding: utf-8 __author__ = '<NAME> : https://www.kaggle.com/svpons' '''Partially based on grid_plus_classifier script: https://www.kaggle.com/svpons/facebook-v-predicting-check-ins/grid-plus-classifier ''' import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.neighbors i...
AL = 'AL' NL = 'NL' MLB = 'MLB' LEAGUES = [AL, NL, MLB] def mlb_teams(year): """ For given year return teams active in the majors. Caveat, list is not complete; those included are only those with a current team still active. """ year = int(year) return sorted(al_teams(year) + nl_teams(y...
from django.db import models, transaction from blame.models import ImmutableBlame, Blame from article.models import ArticleType from money.models import CostField, Cost from crm.models import User from tools.util import raiseif, raiseifnot from stock.models import Stock, StockChangeSet, StockLock, LockError from stock...
"""Dashboard management class""" from __future__ import annotations import argparse import json import os from typing import Any from .api import DuneAPI from .constants import FIND_DASHBOARD_POST, FIND_QUERY_POST from .logger import set_log from .types import DuneQuery, DashboardTile, Post, Network, QueryParameter f...
import base64 import boto3 import os import json def get_encoded_img_data(image_name): # print("Encoding image : ",image_name," ...") image = open(image_name, 'rb') image_read = image.read() image_64_encode = base64.b64encode(image_read) # print("---------------") # print(image_64_encode) # p...
import logging import asyncio from urllib import parse logger = logging.getLogger("handle") SEP_LINE = b"\r\n" SPACE = b" " RECV_REQUEST_INIT = 0 RECV_REQUEST_LINE = 5 RECV_REQUEST_HEADER = 10 RECV_REQUEST_HEADER_COMPLETE = 15 RECV_REQUEST_DATA = 20 RECV_REQUEST_COMPLETE = 25 proxy_response = SEP_LINE.join([ ...
from ..instruments import keithley6221 as k6221 from ..instruments import srs830 as srs from ..instruments import tektronix3252 as tek from .. import core import time import numpy as np import pandas as pd __all__ = ('ready_for_pulse', 'pulse', 'EGMR', 'collect_lockin_data') def ready_for_pulse(pulse_gen, voltage_p...
""" Option A: - resample all spectra to a common wavelength grid - add them together - fit to that Pros: - easier to normalize - radial velocity shift between observations is small (if from the same transit) Cons: - Loose some precision due to resampling Option B: - calculate SME spectra without sampling...
import itertools import os from os import path import re from typing import Iterable, List, NamedTuple, Optional, Tuple, TypedDict, cast import numpy as np from tqdm import tqdm import PIL from PIL import Image, ImageFile from rclip import db, model, utils ImageFile.LOAD_TRUNCATED_IMAGES = True class ImageMeta(Ty...
# Copyright 2021 The Kraken Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
#Modified from https://github.com/pytorch/vision/pull/467/files from __future__ import print_function import torch.utils.data as data from torchvision.datasets.folder import pil_loader, accimage_loader, default_loader from PIL import Image import os import numpy as np from .utils import download_url, mkdir def make...
# -*- coding: utf-8 -*- """ Created on Tue Jul 25 16:58:09 2017 @author: dconly PURPOSE: Take in multiple CSV files of collision data and combine them For coordinates, use POINT_X and POINT_Y as defaults; otherwise use the CHP coordinates (less reliable, but something) df to numpy array https://pandas.pydata....
import os import numpy as np from PIL import Image from PIL import ImageFile ImageFile.LOAD_TRUNCATED_IMAGES = True import torch import torch.nn as nn from torch.autograd import Variable import math import torch.nn.functional as F import torchvision import pretrainedmodels OUTPUT_DIM = { 'alexnet' : 25...
"""Tests for input validation functions""" import numpy as np import scipy.sparse as sp from nose.tools import assert_raises, assert_true, assert_false, assert_equal from itertools import product # from sklearn.utils.estimator_checks import NotAnArray from sklearn.neighbors import KNeighborsClassifier from sklearn...
from itertools import groupby def split_form_table(cldf_wordlist): """ Create a list of list of ordered dictionaries, grouped by Language_ID, where each CLDF row is mapped to an individual entry. Example: OrderedDict([('ID', 'amar1273-1-1'), ('Parameter_ID', '1'), ...]) """ return [ ...
import argparse import json import os import numpy as np import torch from torch.autograd import Variable from tqdm import tqdm from misc.utils import AverageMeter from models.adacrowd.blocks import assign_adaptive_params from models.cc_adacrowd import CrowdCounterAdaCrowd device = 'cuda' if torch.cuda.is_available(...
# See file COPYING distributed with dpf for copyright and license. import os import subprocess import socket import time import httplib import json from . import start_process_server, start_data_server, stop_server test_vars = {} def setup(): # (po, fo_out, fo_err) = start_data_server() # test_vars['data_po'] ...
#!/usr/bin/python # -*- coding: utf-8 -*- import argparse import os import logging import datetime import h5py import matplotlib.pyplot as plt from causal_inference.config import LV_PARAMS, RESULTS_DIR from causal_inference.utils.log_config import log_LV_params class LotkaVolterra(): ''' Class simulates pre...
import glob import html import os import configparser import re import boto3 import botocore import io from types import SimpleNamespace import sys def cli_pypi(args): prepared_files = list(prepare(args.file_mask)) if not prepared_files: raise RuntimeError('No files to upload') target = args.tar...
""" Testing of the matmul operator '@' for distributions. For py27 reasons, the dunder-methods '__matmul__' and '__rmatmul__' are used instead of the literal '@' operator. """ from pytest import raises import numpy import chaospy UNIVARIATE = chaospy.Uniform(2, 3) MULTIVARIATE = chaospy.J(chaospy.Uniform(1, 2), chao...
import os from glob import glob from future.utils import iteritems import sys if sys.version_info > (3, 2): def bCheckIfStr(v): return type(v) ==str def cStr(v): if type(v)==bytes: return v.decode("utf-8") else: return v else: def bCheckIfStr(v): retu...
from itertools import chain import sys from os import listdir from os.path import basename, isfile, join EDU_MARKER = "<edu_split>" def get_files(_dir): return [join(_dir, f) for f in listdir(_dir) if isfile(join(_dir, f)) and f.endswith("edus")] def get_counts(gold_dict): num_edus = 0 num_tokens = 0 ...
from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.templatetags.static import static from django.views.generic import ListView, TemplateView from django.views.generic.edit import CreateView, DeleteView, UpdateView from django.views.decorators.csrf import csrf_protect f...
from copy import copy import mdparser.topology as mdtop def get_subsections(top: mdtop.GromacsTop, section_node): section_nvtype = mdtop.GromacsTop.select_nvtype("section") subsection_nvtype = mdtop.GromacsTop.select_nvtype("subsection") subsections = [] start = section_node while True: ...
#!/usr/bin/python3 import I2C_LCD_driver import cv2 import pyzbar.pyzbar as qr import time import requests import sys import RPi.GPIO as GPIO from player import Player import json import requests from requests.structures import CaseInsensitiveDict URL = "http://127.0.0.1:8000/api/data" HEADER = CaseInsensitiveDict() ...
# Copyright 2017 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, softwa...
# ------------------------------------------------------------------------ # Modified by <NAME> & <NAME> # Modified from Deformable-DETR (https://github.com/fundamentalvision/Deformable-DETR) # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) 2020 SenseTime. All Rights Reserved. # Copyright...
import math import rouletteModel import dataPreprocessing def getSPC(p1, p2, dis, pheList, neighborMatrix): """ 获得即点p为中心,与近邻点p1’的从路径信度Subordinate Path Credibility :param p1: 第一个点 :param p2: 第二个点 :param dis: 距离矩阵 :param neighborMatrix: 近邻矩阵 :return: S_pc_<p,p1'> 即以点p为中心,与近邻点p1’的从路径信度Subordi...
import json import logging from decimal import Decimal from enum import Enum import aio_pika from aiohttp import web from asyncpg import Pool, UniqueViolationError from marshmallow import ValidationError from billing_service.schema import AccountSchema, AddFundsSchema LOG = logging.getLogger(__name__) RENT_PRICE ...
from ppadb.client import Client as AdbClient from pathlib import Path from pick import pick import os, shutil MIN_NO_FOR_FILE_TRANSFER = 10 #the criteria used to determine if a folder should be transfered #absolute path seemed to keep getting a permission denied error from ppadb when transfering hence the reas...
""" Shape implementations """ import numpy as np from numpy import random import color import constants as c from shapely import affinity from shapely.geometry import Point, box, Polygon def rand_size(): return random.randint(c.SIZE_MIN, c.SIZE_MAX) def rand_size_2(): """Slightly bigger.""" return ra...
from catty.words import ( dupN, dup, dup2, dup3, swap, over, under, nip, tuck, slide, snip, drop, drop2, drop3, dropN, hide, reveal, depth, copy_stack, set_stack, save, restore ) from . import check_reduce, check_error def test_du...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2020 <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 ...
#!/usr/bin/env python import sys import regex import requests import time import json import yaml from bs4 import BeautifulSoup from html2text import html2text from urllib.parse import urlencode def local2utc(secs): if time.daylight: return secs - time.timezone - time.altzone else: return secs...
# -*- coding: UTF-8 -*- # Copyright 2017 <NAME> # # License: BSD (see file COPYING for details) from __future__ import unicode_literals from __future__ import print_function from django.db import models from etgen.html import E from lino.utils import join_elems from lino.core.diff import ChangeWatcher from lino.mod...
import unittest from numpy import hstack, max, abs, ones, zeros, sum, sqrt from cantera import Solution, one_atm, gas_constant import numpy as np from spitfire import ChemicalMechanismSpec from os.path import join, abspath from subprocess import getoutput test_mech_directory = abspath(join('tests', 'test_mechanisms', ...
"""Contains code that did not make it into an own module. """ import contextlib with contextlib.redirect_stdout(None): import pygame import pygame.ftfont from . import surface_composition as sc import os import time from functools import lru_cache from threading import Thread class _PumpThread(Thread): ...
import collections import re class DataTypeRecognition: def __init__(self, query, lemmas, position): query = query.split() self.query = query self.query_lemmas = lemmas self.position = position def recognize_type(self): data_type = "all" if((self.position > 0) ...
import os import re import subprocess from time import sleep from typing import Any, Dict, List, Optional from semantic_version import Version import src.cli.console as console from src import settings from src.local.providers.abstract_provider import AbstractK8sProvider from src.local.providers.k3d.storage import K3...
import subprocess import os import cv2 import infinitechallenge.model.skull_detection as sd from infinitechallenge.utils.labelling import label_image from tempfile import NamedTemporaryFile from infinitechallenge.logging import logger # Description: Skull Recognition with video stream input # Developed Date: 25 June ...
"""Dump all the utility functions into this one file and load it for nipype loop This branch is the software release for the 2019 paper: https://www.nature.com/articles/s41598-019-47795-0 See LICENSE.txt Copyright 2019 Massachusetts Institute of Technology """ __author__ = "<NAME>" __date__ = "October 12, 2018" ...
from itertools import product import math import torch import torch.nn.functional as F def im2toepidx(c, i, j, h, w): return c*h*w + i*w + j def get_toeplitz_idxs(fshape, dshape, f_stride=(1,1), s_pad=(0,0)): assert fshape[1] == dshape[0], "data channels must match filters channels" fh, fw = fshape[-2:] ...
import os import time import jsonpath import allure from common.logger import logger class ActionBase: def __init__(self, db, request, context, utils): self.db = db self.service = getattr(context, "ENV").get("service") self.request = request self.context = context self.log...
import json import logging import os from concurrent.futures import ThreadPoolExecutor from plastron import version from plastron.commands import get_command_class from plastron.exceptions import FailureException from plastron.http import Repository from plastron.stomp import Destination from plastron.stomp.handlers i...
from itertools import cycle import subprocess from reticular import say from fast.files import Input, Output, Executable from fast.utils import gnuplot, normalize_camel_case class Stats(object): POINTS = [1, 12, 2, 3, 4, 5] COLORS = [3, 2, 4, 5] def __init__(self, name, files, xlabel="Input"): se...
""" A factory that creates concrete Figmentator instances and also acts as a registry for getting the registered Figmentators. """ import os from asyncio import get_event_loop, Lock from typing import Any, Dict, Type, List, Optional from pkg_resources import ( working_set, find_distributions, parse_requirem...
# Load Libraries from timeit import default_timer as timer from collections import defaultdict from collections import deque from typing import Dict from typing import List import pandas as pd import numpy as np # Plotting from matplotlib.lines import Line2D import matplotlib.pyplot as plt import matplotlib as mpl m...
from sklearn.metrics import confusion_matrix, roc_auc_score, auc import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits import mplot3d import numpy as np """ Return Precision, Recall, F1-Score and Accuracy """ def metrics(TP, FP, TN, FN, y_test, array_params=None): precision_lis...
import sys import os import subprocess from shutil import copyfile, rmtree def find_and_split_inputs(input_env_data, output_dir, number_of_inputs): ## Generate the environment file (by splitting inputs) ## Find the input file name input_env_lines = input_env_data.split('\n') input_vars = [line.split('...
import numpy as np import torch import time import torch.nn as nn import torch.nn.functional as F from torch.optim import Adam import matplotlib.pyplot as plt import config.HyperConfig as Config import Attention_LSTM as Model import loss_function as LossFunc import data # from sklearn.model_selection import train_test_...
import pandas as pd # type: ignore from copy import copy from collections import defaultdict import csv import sys csv.field_size_limit(sys.maxsize) def combine_dicts(dicts): new_dict=defaultdict(set) for d in dicts: for k in d.keys(): new_dict[k] = new_dict[k] | set(d[k]) for k, v in n...
""" Tests for `kolibri` module. """ from __future__ import absolute_import, print_function, unicode_literals import copy import logging import os import pytest from kolibri.utils import cli logger = logging.getLogger(__name__) LOG_LOGGER = [] def log_logger(logger_instance, LEVEL, msg, args, **kwargs): """ ...
#!/usr/bin/env python3 import json import logging import pathlib import random import string import time from typing import Tuple import requests.auth import checklib import checklib.http import checklib.random from proof_of_work import challenge_responses class SandboxChecker(checklib.http.HttpJsonChecker): p...
from google.cloud import speech,storage import io import wave, struct, matplotlib.pyplot as plt import syllables from fuzzywuzzy import fuzz import parselmouth from parselmouth.praat import call, run_file import pandas as pd import numpy as np import cloudstorage as gcs import os import subprocess # params: # bucket_n...
import numpy as np from scipy import ndimage as nd import tensorflow as tf from prdepth import sampler import prdepth.utils as ut import cv2 H, W = sampler.H, sampler.W IH, IW = sampler.IH, sampler.IW PSZ = sampler.PSZ STRIDE = sampler.STRIDE HNPS, WNPS = sampler.HNPS, sampler.WNPS class S2DOptimizer: ''' Opti...
import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.linear_model import LassoLars from sklearn import datasets from safe_enet_path import compute_path def set_style(): # This sets reasonable defaults for font size for # a figure that will go in a paper sns.set_context("pa...
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright 2016-2017 by I3py Authors, see AUTHORS for more details. # # Distributed under the terms of the BSD license. # # The full license is in the file LICENCE, distributed with this software. # ----------------...
"""Command Line Interface of Clocker""" import logging from datetime import date, datetime, timedelta from typing import Optional import click from clocker import converter from clocker.core import SettingsError, Tracker from clocker.database import Database from clocker.model import AbsenceType from clo...
# Third Party Library # Standard Library import importlib.util import sys # Third Party Library import pytest # First Party Library from data_extractor.core import AbstractSimpleExtractor from data_extractor.item import Field, Item from data_extractor.json import ( JSONPathExtractor, JSONPathRWExtExtractor, ...
from ctypes import * from .tools import iterate_array, is_iterable class BerElement(Structure): _fields_ = [] class LDAP(Structure): _fields_ = [] class LDAPMessage(Structure): _fields_ = [] class Timeval(Structure): _fields_ = [] class BerVal(Structure): _fields_ = [('bv_len', c_ulong), ...
import torch import torch.nn as nn from torch.utils.data import TensorDataset, DataLoader, random_split from torch.optim.lr_scheduler import LambdaLR import pytorch_lightning as pl import numpy as np import math from argparse import ArgumentParser from gpt2 import GPT2 from utils import quantize def _to_sequence(x):...
import os import json import boto3 import click import string import random import logging import pandas as pd from variable_type_config import RECIPE random_str = ''.join(random.choices(string.ascii_lowercase, k=6)) ## Fixed variables. No need to change them # MODEL_TYPE fixed as the code is only written for extern...
# http://github.com/timestocome # Attempt to use velocity, acceleration, momentum, energy, force, hooke's law # to predict prices 1 week, month, quarter into the future # score seems insanely too good to be true. import pandas as pd import numpy as np import matplotlib.pyplot as plt import tensorflow as tf # ...
import pandas as pd import time from tqsdk import TqApi, TqAuth import datetime import os import threading from vnpy.app.option_master.pricing import black_76_cython as black76 from AlarmTools.SMS import SMSAlarm from AccountTracker.database.database_influxdb import init from AccountTracker.settings import database_set...
#!/bin/python import sys, numpy, os.path, re import argparse from Bio import SeqIO loc = os.path.abspath(__file__[:__file__.rfind("/")]) def select_champion(fastq, favourite): parse_dict = {} for i in open(fastq): chunk = i.split() if chunk[5] == "2": continue else: parse_dict[chunk[0]] = chunk[1:] champi...
from os import makedirs from os.path import exists from traceback import print_exc from gi.repository.GLib import get_user_config_dir, get_user_cache_dir, \ log_default_handler, LogLevelFlags from gi.repository.Gtk import Orientation try: from configparser import ConfigParser, NoSectionError, NoOptionErro...
# vim: sw=4:ts=4:et import os import os.path import logging import re import sys import json import saq from saq.error import report_exception from saq.analysis import Analysis, Observable from saq.modules import AnalysisModule, LDAPAnalysisModule from saq.constants import * class UserTagAnalysis(Analysis): def ...
""" Copyright © 2021, SAS Institute Inc., Cary, NC, USA. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 """ import os import json import urllib3 import boto3 from botocore.exceptions import ClientError print("Initializing function") # Get the service resource dynamodb = boto3.resource('dynamodb') # Initi...
import os import numpy as np def leitura_arquivo(): linhas = [] arquivos = os.listdir(".") for f in arquivos: if f.endswith(".txt"): f = open(f) for linha in f: linhas.append(linha.replace("\n", "").split(" ")) variaveis = len(linhas[0]) restricoes =...
bl_info = { "name": "Export Model to Java (.java)", "author": "<NAME>", "version": (1, 0), "blender": (2, 7, 9), "location": "File -> Export", "description": "Exports selected models to Java source files", "warning": "", "wiki_url": "", "tracker_url": "", "category": "Import-Export"} import os import array ...
from __future__ import print_function import argparse import functools import importlib import os import struct import sys import traceback import keypipe class InvalidMagicError(Exception): pass class UnrecognizedVersionError(Exception): def __init__(self, version): self.version = version # the...
#!python # -*- coding: utf-8 -*- # # Author : <NAME>; Physics Graduate Student, Ohio University # Date : Aug 24, 2016 # Last update : Jan 18, 2018 # # Runtime: 30 secs for redshift 1.0 and 216 files. """ .. note:: 1. This program creates fitted P gamma values (i.e. galshear_fpg.cat) from galshe...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jan 18 14:44:27 2021 @author: xujianchen """ import os import cv2 import threading import time import email, smtplib, ssl from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email....
import os import time import tensorflow as tf import qaData from qaLSTMNet import QaLSTMNet def restore(): try: print("正在加载模型,大约需要一分钟...") saver.restore(sess, trainedModel) except Exception as e: print(e) print("加载模型失败,重新开始训练") train() def train(): print("重新训练,请...
"""Extract features from static moments of IMU data.""" from typing import Optional, Tuple, Union import numpy as np import pandas as pd from scipy.stats import skew from biopsykit.utils.array_handling import sanitize_input_nd from biopsykit.utils.time import tz def compute_features( data: pd.DataFrame, sta...
""" MIT License Copyright (c) 2019-2021 Scuwr 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, di...
import os import torch import torch.nn as nn import torch.utils.data as Data import torchvision #torchvision是torch安装时自带的一些数据集。MNIST是其中手写数字的数据集。 import matplotlib.pyplot as plt # 超级参数 EPOCH = 1 BATCH_SIZE = 50 LR = 0.001 DOWNLOAD_MNIST = True #为True会下载torchvision里的训练集,为False就不会下载。但为False我会报错不知道为啥。 # 定义训...
import math import torch import torch.nn as nn import numpy as np import torchvision.models as models from torch.autograd import Variable import torch.nn.functional as F import itertools import operator from multiprocessing.dummy import Pool as ThreadPool from multiprocessing import Pool from collections import Counter...
import sys import os import numpy as np import time import lasagne as nn import theano import theano.tensor as T from lasagne.layers import InputLayer, Conv2DLayer, MaxPool2DLayer, DenseLayer from lasagne.layers import Upscale2DLayer, ReshapeLayer sys.path.append("..") import utils as u import config as c from batch_...