text
stringlengths
3.07k
12.6k
from future import standard_library standard_library.install_aliases() from builtins import str from bson import ObjectId import urllib.request, urllib.error, urllib.parse import json import time def test_general_simple_task_one(worker): result = worker.send_task( "tests.tasks.general.Add", {"a": 41, "b"...
#!/usr/bin/python2 """ Raspberry Pi fan control script Author: <NAME> (<EMAIL>) """ import argparse from getpass import getuser import logging import os import signal import sys from threading import Event gpio_import_error = None try: from RPi import GPIO except (ImportError, RuntimeError) as e: GPIO = None...
#!/usr/bin/python ''' Calculate exposure settings and generate a script. Parameters are for Jan 21 2019 eclipse. ''' import sys, os, json import time, calendar from collections import OrderedDict import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d from camerasettings imp...
# Copyright (c) 2021 NVIDIA Corporation. All rights reserved. import numpy as np import math import cupy.cuda.nvtx as nvtx from MDAnalysis.lib.formats.libdcd import DCDFile from timeit import default_timer as timer from numba import njit import os from pathlib import Path def dcdreadhead(infile): nconf = infil...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################# # _____ __________ ___ __ # # / ___// ____/ __ \/ | / / # # \__ \/ / / /_/ / /| | / / ...
import typing as tp class ReX: """ Abstract class that contains regular expression. """ def __str__(self) -> str: pass def accepts(self, string: str) -> bool: pass class Epsilon(ReX): """ Empty regular expression. """ def __str__(self) -> str: return "" ...
# DCGAN-like generator and discriminator from torch import nn import torch.nn.functional as F from spectral_normalization import SpectralNorm channels = 3 leak = 0.1 w_g = 4 class Generator(nn.Module): def __init__(self, z_dim, a1, a2, a3): super(Generator, self).__init__() self.z_dim = z_dim ...
""" hiku.query ~~~~~~~~~~ `Hiku` doesn't rely on any specific query language, internally it uses generic query representation to describe result and it could be constructed by parsing different suitable query languages. However, `Hiku` provides one built-in way to describe result -- `edn`_ dat...
import cv2 import glob import numpy as np import scipy as sp from matplotlib import * from pylab import * import time from keras.models import Model, model_from_json import numpy as np from keras import backend as K import tensorflow as tf import os from sklearn.utils import shuffle from keras.models import model_from_...
import glob from astropy.io import fits import numpy as np import matplotlib.pyplot as plt from astropy.nddata import CCDData import astropy.units as u import ccdproc as ccdp import os import pathlib from ccdproc import ImageFileCollection from astropy.visualization import hist import itertools from astropy.stats impor...
#!/usr/bin/env python3 # Convert (c) Baltasar 2019 MIT License <<EMAIL>> # ConveRT Converts training from Garmin CSV format to a readable text format. import csv import argparse class Split: COL_SUMMARY = ["summary", "resumen"] """Holds the info about a given split time.""" def __init__(self, n, s...
#!/usr/bin/env python # -*- coding: utf-8 -*- import re import os import logging from imp import load_source from flask import Flask, Blueprint, g, session, redirect, url_for, request app = Flask(__name__) app.config.from_object('config') secret = load_source('secret', app.config['SECRET_FILE']) app.config.update(sec...
# ref: https://qiita.com/ttsubo/items/c4af71ceba15b5b213f8 import argparse import curses import os import sys import json from flatten_dict import flatten from typing import Union # local try: # need when 「python3 gfzs/runtime/config.py」 if __name__ == "__main__": # https://codechacha.com/ja/how-to-im...
#!/usr/bin/env python # # Copyright (C) 2019 # <NAME> # Centre of Excellence Cognitive Interaction Technology (CITEC) # Bielefeld University # # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # 1. Redistributions of so...
from gluonts.model.estimator import Estimator from gluonts.model.forecast import SampleForecast from gluonts.model.predictor import RepresentablePredictor from gluonts.support.pandas import frequency_add from gluonts.core.component import validated from gluonts_forecasts.custom_models.utils import cast_kwargs, get_mode...
#!/usr/bin/env python """ usage: bcl2fq-local -i <seq_dir> -o <ou_dir> optional arguments: --sample-sheet Path Using custom sample sheet file --mismatch N Mismatch for barcode, default: 1 --process N Process number for demultiplexing and processing --io-process N Process number...
""" Developed by : <NAME> Email : <EMAIL> """ import numpy as np import cv2 import pickle import os import time import serial import json import deep_learning_object_detection as objectdetection import color_classification_image import datetime import notification os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_t...
# Copyright (c) 2021 Qualcomm Technologies, Inc. # All Rights Reserved. import fire import numpy as np import torch import torch.nn as nn from dataset.dataset import get_dataloader from model.adaptive_models import ConditionalFrameExitInferenceModel from utils.config import Config from utils.metrics import A...
import numpy as np import tensorflow as tf import tensorflow_probability as tfp from gpflow.models import VGP, VGPOpperArchambeau, SVGP from gpflow.kernels import Stationary, SquaredExponential from gpflow.likelihoods import Bernoulli from tensorflow.keras import optimizers from tqdm import trange # shortcuts tfd =...
import os import os.path import cv2 import numpy as np from torch.utils.data import Dataset IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm'] def is_image_file(filename): filename_lower = filename.lower() return any(filename_lower.endswith(extension) for extension in IMG_EXTENSIONS) def ...
"""Config flow for Discovergy integration.""" from __future__ import annotations import logging from typing import Any import pydiscovergy import pydiscovergy.error as discovergyError import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from home...
#!/usr/bin/python # -*- coding: utf-8 -*- # # netcheck.py - simple module to check local network for (ar)pingable devices # # Copyright (c) 2017 <NAME> # # GNU GENERAL PUBLIC LICENSE # Version 3, 29 June 2007 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Gen...
#!/usr/bin/env python3 import subprocess as SP import argparse as AP import shlex as SHL import signal as SIG import sys as SYS import time as T import threading import queue class AsyncReader(threading.Thread): def __init__(self, fil, q): threading.Thread.__init__(self) self.q = q; self.fi...
# -*- coding: utf-8 -*- from django.utils import timezone from django.shortcuts import render, redirect from django.contrib.sites.shortcuts import get_current_site from django.core.mail import get_connection, EmailMultiAlternatives from django.conf import settings from django.template.loader import render_to_string fro...
# Standard Library from functools import partial from math import atanh # Third Party import numpy as np from scipy import stats from scipy.interpolate import NearestNDInterpolator from nilearn.image import get_data, load_img, new_img_like, mean_img, concat_imgs from nilearn.masking import compute_epi_mask from tqdm i...
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import os import math import itertools import pandas as pd import datetime from fclib.dataset.retail.benchmark_paths import DATA_DIR import fclib.dataset.retail.benchmark_settings as bs # Utility functions def week_of_month(dt): """Get the ...
import logging import asyncio import pathlib import uuid from asyncio.events import AbstractEventLoop from functools import wraps from typing import Callable, Any, Union, List from bleak.backends.device import BLEDevice from bleak.exc import BleakError, BleakDotNetTaskError from bleak.backends.scanner import BaseBleak...
#!/usr/bin/env python3 import argparse import botocore import boto3 import json import os import sys import time severities = [ 'INFORMATIONAL', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL', ] def log_output(level, message): colours = { "Info": "\033[1;34m", "Error": "\033[0;31m", ...
import json import logging import os import re from datetime import datetime, timedelta from threading import Timer import discord from dotenv import load_dotenv from dateutil import parser import paypal_api from pathlib import Path regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' def isValid(email): ...
import discord from discord.ext import commands import yaml from PIL import Image, ImageDraw, ImageFont import io, time, asyncio from discord import File a = open("config.yaml", 'r') x = yaml.load(a) prefix = x['PREFIX'] bot=commands.Bot(command_prefix=prefix, case_insensitive=True) bot.remove_command('help') @bot.ev...
import turtle import math from time import time from random import randint score = 0 pen = turtle.Turtle() wn = turtle.Screen() wn.setup(width=1645, height=1000, startx=None, starty=None) wn.listen() turtle.register_shape("images/spaceship2.gif") turtle.register_shape("images/meteor.gif") turtle.register...
''' Feature engineering ''' import numpy as np import os import json import pandas as pd from utils import logger DATA_HOUSE_PATH = '/media/leo/working/SoftwarePackage/datahouse/user-interest/datahouse' CLEAN_DATA_PATH = DATA_HOUSE_PATH + '/clean-data' RAW_DATA_PATH = DATA_HOUSE_PATH + '/raw-data' # DATASET_TEST_FAC...
# # Blackboard Mobile API Library # # Developed by github.com/adammw, released under MIT License # import sys from urllib.parse import urlparse import xml.etree.ElementTree as etree try: import requests except ImportError: sys.stderr.write("ERROR: requests module not available\nTo install requests:\n pip instal...
from flask import render_template, jsonify from .app import app, rq, mail from rq import get_current_job from rq.exceptions import NoSuchJobError from integrations import base_crm, briteverify import flanker.addresslib.address from flask_mail import Message import logging from datetime import datetime log = logging.g...
"""Implements nest_ops deploy subcommand.""" import argparse from nest_py.ops.ops_logger import log import nest_py.nest_envs as nest_envs import nest_py.ops.nest_sites as nest_sites from nest_py.nest_envs import ProjectEnv from nest_py.ops.nest_sites import NestSite from nest_py.ops.command_runner import CommandRunne...
# -*- coding: utf-8 -*- import os, sys from urllib.request import urlopen from urllib.error import HTTPError import re import sys from io import StringIO, BytesIO import contextlib import pathlib import tempfile from zipfile import ZipFile import shutil from subprocess import check_output from qtpy import QtWidgets, Qt...
import warnings from collections import OrderedDict from enum import Enum from typing import List, Dict, Type, OrderedDict as OrderedDictType, Set from typing import TYPE_CHECKING from .config_function import ConfigFunction from .config_item import ConfigItem if TYPE_CHECKING: from . import Configs RESERVED = {'...
# Identificador de codigo Braille # Script para reconocer codigos generadores Braille utilizando OpenCV # y TensorFlow # # El script consiste en dibujar un codigo Braille dentro de un area de trabajo # predefinida. Mediante la posicion y los eventos del mouse se generan # distintas formas que permitan el trazo o dibu...
import multiprocessing import os import sys import traceback from bs4 import BeautifulSoup from quantlaw.de_extract.statutes_areas import StatutesExtractor from quantlaw.de_extract.statutes_parse import StatutesParser from quantlaw.utils.beautiful_soup import save_soup from quantlaw.utils.files import ensure_exists, l...
import tensorflow as tf import numpy as np import math import sys import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) sys.path.append(os.path.join(BASE_DIR, '../utils')) sys.path.append(os.path.join(BASE_DIR, '../../utils')) import tf_util_reconstruct from transform_nets_reconstruc...
#! /usr/bin/env python3 import os import sys import paf import argparse import requests config = { 'base': '/opt/gdelt-diff', 'user_config': '/etc/gdelt-diff/config', 'english': 'http://data.gdeltproject.org/gdeltv2/masterfilelist.txt', 'translation': 'http://data.gdeltproject.org/gdeltv2/masterfileli...
"""button_array.py""" from ..devices import Sensor class ButtonArray(Sensor): """An array of buttons, extends :class:`Sensor`. Args: pin_nums (list): List with the gpio numbers for buttons. direction (list|str): Could be a list with different values per pin_num or single valu...
''' This is the ServiceNow Retire Workflow Action It updates the existing CMDB record, createts a Change Request, and then Closes the Change Record once done Tested on vRA 8.0 and vRA Cloud. Tested on SNOW's London release Assumptions: - A vRA deployment is the trackable unit, and is recorded in the CMDB, regardless ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. and Epidemico Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You ma...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import cv2 import numpy as np from progress.bar import Bar import torch import pickle from opts import opts from datasets.init_dataset import switch_dataset from detector.stream_moc_det import MOCDet...
from django.contrib import admin import zsolozsma.models from django.utils import timezone from django.db.models.functions import Concat from django.urls import reverse from django.utils.html import format_html class LiturgiaTvAdmin(admin.ModelAdmin): save_on_top = True class EventInline(admin.Tabul...
"""Tests for the `planeo.galaxy.test` module.""" import os import shutil from planemo.galaxy.test import structures from planemo.galaxy.test.actions import passed from planemo.galaxy.test.actions import run_in_config from .test_utils import ( TempDirectoryTestCase, test_context, TEST_DATA_DIR, ) nose_1_3...
""" contains code from https://github.com/uber-research/safemutations and https://towardsdatascience.com/paper-repro-deep-neuroevolution-756871e00a66 """ import logging from enum import Enum from abc import ABC import numpy as np import torch from torch import nn from algorithm.safe_mutations import Sensitivity cla...
""" Script that investigates frames where global predictions are better than single branch predictions with KL measures. """ from __future__ import print_function import os import cv2 import numpy as np from os.path import join from tqdm import tqdm from computer_vision_utils.stitching import stitch_together from comp...
from __future__ import annotations import math from collections import namedtuple from typing import Optional def main(): serial_number = 9445 grid: list[list[int]] = [[0] * 300 for _ in range(300)] for y in range(1, 301): for x in range(1, 301): grid[y - 1][x - 1] = compute_power_lev...
""" Base class for all wrapper modules """ import logging import os import re import shutil import sys import tempfile from e_uae_wrapper import utils from e_uae_wrapper import path from e_uae_wrapper import WRAPPER_KEY class Base(object): """ Base class for wrapper modules """ CONF_RE = re.compile(...
from __future__ import division from __future__ import print_function import os import glob import time import random import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import scipy.sparse as sp from sklearn.manifold im...
import os import requests import xmltodict import csv import json # # # # # # # # # # # FRED DATA BELOW # # # # # # # # # # # FRED_BASE_URL = 'https://api.stlouisfed.org/fred/' GEOFRED_BASE_URL = 'https://api.stlouisfed.org/geofred/' def append_fred_token(url, external=None): if external: token = externa...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 4 08:24:48 2021 inverse_gan_optim.py """ import torch import torchvision import torch.optim as optim import torch.nn as nn import torchvision.datasets as dset import torchvision.transforms as transforms import math import sys sys.path.append('.')...
import logging from decimal import Decimal import stripe from config import CIRCLE_FAILURE_RECIPIENT, STRIPE_KEYS from npsp import Task, User from util import send_slack_message stripe.api_key = STRIPE_KEYS["secret_key"] TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01') class ChargeException(Exception): ...
import enum import queue from typing import Callable from . import autoresp from pySerialDebugger.autosend import autosend_result from pySerialDebugger.send_node import send_data_node class ThreadNotify(enum.Enum): """ スレッド間通信メッセージ """ # GUIへの通知 RECV_ANALYZE = enum.auto() # 受信解析結果通知 COMMIT_RX = enum.auto() ...
try: from urllib import quote_plus #python 2 except: pass try: from urllib.parse import quote_plus #python 3 except: pass from django.contrib.auth import get_user_model from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib.auth.mixins import LoginRequiredMixin from django.u...
#! /usr/bin/env python # -*- coding: utf-8 -*- # # # MIT License # # Copyright (c) 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim...
from abc import abstractmethod from dataclasses import dataclass import os from typing import Optional, Tuple import inspect import pytest from _pytest.monkeypatch import MonkeyPatch import shortuuid from pywharf_core.backend import ( BackendInstanceManager, PkgRepoConfig, PkgRepoSecret, ) from pywharf_co...
from flask_wtf import FlaskForm from wtforms import StringField, SelectField, TextAreaField, validators, ValidationError from wtforms.fields import DecimalField from wtforms.fields.html5 import EmailField from wtforms.validators import DataRequired, Email from flask_wtf.file import FileField, FileRequired, FileAllowed ...
def evaluate_model(self, model_name, model, df, df_features, output_folder=None, le_map=None, show_extra=True, find_nearest_on_cols=False, zscore_low...
# Copyright 2020 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
#!/usr/bin/env python # 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 # "Li...
import base64 import functools import json import os import sys from datetime import datetime, timedelta from http.cookies import SimpleCookie from urllib.parse import urlencode import boto3 import jwt import logging from botocore.vendored import requests from cryptography.hazmat.backends import default_backend from c...
import pickle from torch.utils.data import DataLoader, Dataset import pandas as pd import numpy as np import torch class PM25_Dataset(Dataset): def __init__(self, eval_length=36, target_dim=36, mode="train", validindex=0): self.eval_length = eval_length self.target_dim = target_dim path =...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. import torch from torch import nn from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou from ..attribute_head.roi_attribute_feature_extractors import make_roi_attribute_feature_extractor from ..box_head.roi_box_feature_extractors impor...
from mcpy import auth, connector, dns, login, play, state, status import time import traceback from Crypto import Random from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 import rx _authapi = auth.AuthAPI() _resolver = dns.MCDNSResolver() _handshake_client_state = state.HandshakeState() _status...
import graphene from django.db import IntegrityError, transaction from graphql_jwt.decorators import login_required from backend.graphql.exceptions import ValidationError from backend.trip.graphql.types import TripType, ExpenseType from backend.trip.graphql.inputs import CreateTripInput, UpdateTripInput, CreateOrUpdat...
#!/usr/bin/python # -*- coding: utf-8 -*- """WebSocket Server. autobahn version: 0.9.3-3 A mid-2010 draft(version hixie-76) broke compatibility with reverse-proxies and gateways by including 8 bytes of key data after the headers, but not advertising that data in a Content-Length: 8 header. This data...
from .toplevel import * from .constants import * from .implementation import Implementation from .experiment import ExperimentalData from .collection import Collection class Design(TopLevel): """This class represents a biological Design. A Design is a conceptual representation of a biological system that ...
#!/usr/bin/env python3 ''' ''' import tkinter as tk import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.patches import Polygon import matplotlib.dates as mdates import matplotlib.pyplot as plt from datetime import datetime, timedelta import json, ...
import time import numpy as np from copy import deepcopy from typing import List from acrolib.dynamic_programming import shortest_path, shortest_path_with_state_cost from acrolib.cost_functions import ( # pylint: disable=no-name-in-module norm_l1, norm_l2, sum_squared, weighted_sum_squared, ) from acr...
# Copyright (c) 2020 PaddlePaddle 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 appli...
#!/usr/bin/env python3 """Get some dices and filter them """ # ======================================================================== # # Imports # # ======================================================================== import os import argparse import numpy as np import yt from yt.units import m, s import time f...
from datetime import datetime from logging import getLogger from typing import Final, Optional, Tuple, Union from urllib.parse import quote import iso8601 import pytz from fastapi import APIRouter, HTTPException from fastapi.param_functions import Depends from fastapi.params import Query from fastapi.requests import R...
""" delta extraction for primitive objects and tree indices and consistent ordering in sequences was a nightmare for a long time, but I think I have a good solution to it each atomic delta stores a "sticky" direction (0 or 1) when a conflicting index is found in master, stick index dictates which direction inserted de...
""" @author: <NAME> @email : <EMAIL> @desc : Examples using the algorithms provided by the framework. """ import numpy as np from sklearn import datasets from sklearn.metrics import accuracy_score from sklearn.model_selection import train_test_split from fuzzytrees.fdt_base import FuzzificationOptions, FuzzyDecisionT...
# Copyright (C) 2020 GreenWaves Technologies, SAS # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This progr...
from collections import OrderedDict import os import sys import random import gym import hiive.mdptoolbox.mdp as MDP import hiive.mdptoolbox.example as example import hiive.mdptoolbox.util as mdp_util import numpy as np import pandas as pd import seaborn as sns import pickle from matplotlib import pypl...
import sys import json from flask import Flask from flask import request from flask import g from flask_httpauth import HTTPBasicAuth from aldap import Aldap from cache import Cache from os import environ from logs import Logs # --- Logging ----------------------------------------------------------------- logs = Logs(...
from flask import Flask from flask import render_template from flask import request from model import search,pyhtml from flask import redirect,url_for from model import User,db,Company,SPO,Person import datetime from flask_admin import Admin from flask_admin.contrib.pymongo import ModelView, filters from flask_admin.co...
#!/usr/bin/env python3 """ Initialise a GenomeHubs instance. Usage: genomehubs init [--hub-name STRING] [--hub-path PATH] [--hub-version PATH] [--config-file PATH...] [--config-save PATH] [--es-host URL...] [--es-url URL] [--insdc-metadata] [--insdc-root...
import numpy as np from pyomo import dae as pod from pyomo import environ as po from pydex.core.designer import Designer def simulate(model, simulator, ti_controls, sampling_times, model_parameters): """ fixing the control variables """ # time-invariant model.theta_0.fix(model_parameters[0]) model.th...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 25 11:23:24 2018 @author: ekrem """ import numpy as np import pandas as pd from time import time import taste_fn as fn start_time = time() print('Loading..') triplets, users, songs = fn.load_files() userIDs, songIDs = fn.ids(users, songs) #only i...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Oct 1 13:56:13 2017 @author: ernestmordret """ import pandas as pd from scipy.interpolate import interp1d import re import numpy as np from params import * import os path_to_subs = os.path.join(output_dir,'subs') def create_modified_seq(modified_seq...
######################################################### # Implementation of Social Navigation # # Based on pedestrian model on Helbing & Molnar (1995) # # <NAME>, Sept 2017 # # Human Robot Interaction, Cornell University # ######################################################...
import numpy as np from scp import SCP import robots import yaml import multiprocessing as mp import tqdm import itertools import argparse import re import gen_motion_primitive import sys, os sys.path.append(os.getcwd()) # normalize angle between -pi and pi def norm_angle(angle): # eps = 0.01 # if angle < np.pi + e...
# /psqtraviscontainer/container.py # # Abstract base class for an operating system container. # # See /LICENCE.md for Copyright information """Abstract base class for an operating system container.""" import abc import os # suppress(PYC50) import re import shutil import subprocess import sys import textwrap fr...
import os import random import numpy as np import cv2 import time import h5py #pathh=['/media/yp/My Passport/n01440764/'] #vpath=['/media/yp/新增磁碟區/validation/'] #traindir=os.listdir(path) #pathh=[path + k +'/' for k in traindir] #camerapath=[w+'camera.h5' for w in pathh] #vcamerapath=[w+'camera.h5' for w in vpath] #tra...
# -*- coding: utf-8 -*- """Wrapper to run MAD-X from the command line. :copyright: Copyright (c) 2020 RadiaSoft LLC. All Rights Reserved. :license: http://www.apache.org/licenses/LICENSE-2.0.html """ from __future__ import absolute_import, division, print_function from pykern import pkio from pykern import pksubproce...
import argparse import os import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf sns.set_palette("colorblind") @tf.function def fp_to_resized_image(filepath: str): parts = tf.strings.split(filepath, sep=os.sep) # Only keep filename, remove AE fro...
"""A CRFSuite-based mention annotator.""" import os import pickle import tempfile import time from os import PathLike from pathlib import Path from typing import IO, Dict, Iterable, List, Mapping, Optional, Sequence, Union from attr import attrib, attrs from attr.validators import instance_of, optional from pycrfsuite...
""" ===================== gprof_nn.bin.retrieve ===================== This sub-module implements the command line interface to apply the GPROF-NN to input data. """ import argparse import logging from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor import multiprocessing as mp from pathlib import Pat...
import pandas as pd import numpy as np import matplotlib.pyplot as plt def get_bounds_iqr(data): """ Returns outlier bounds of a given numpy array """ temperatures = data[:, 1] q25 = np.percentile(temperatures, 25) q75 = np.percentile(temperatures, 75) iqr = q75 - q25 lower = q25 - (1.5...
#****************************************************************************** # (C) 2018, <NAME>, Austria * # * # The Space Python Library is free software; you can redistribute it and/or * # modif...
import os import pandas as pd def aggregatePlayerStats(data, player_list): team_data = data[data['player'].isin(player_list)] #subset data in the player list sum_data = team_data[['fga', '3pa', '2pa', 'fta', 'orb', 'drb', 'trb', 'ast', 'stl', 'blk', 'tov', 'pf', 'pts']].sum() avg_da...
# %matplotlib inline import numpy as np from scipy.stats import beta import matplotlib.pylab as plt from collections import namedtuple class BetaBandit(object): """ Thompson Sampling Parameters ---------- K : int total number of arms prior_params : list of float length 2 tuple, default None, (optional) ...
""" helper um mit checkpoints umzugehn """ import tensorflow as tf import glom from tensorflow.keras.layers import Conv2D def load(file): """ diese funktion von außen benutzen. gibt den root node zurück """ return Node.fromFilename(file) def set_path(obj,path,value): path = path.replace("/",".")+".value" glom.a...
#!/usr/bin/python """Functions to help working with FASTQ files.""" import os import gzip import uuid import logging import subprocess from Bio.SeqIO.QualityIO import FastqGeneralIterator from Bio.SeqIO.FastaIO import SimpleFastaParser from lib.exec_helpers import run_cmds def get_reads_from_url( input_str, ...
from gevent import monkey monkey.patch_all() import gevent import gevent.pool import os import sys import glob import time import uuid import ujson import falcon import base64 import shutil import datetime import logging import epyk from functools import partial from . import _utils while "META.time_per_example" not...