text
stringlengths
3.07k
12.6k
from datetime import datetime from enum import IntFlag, IntEnum from bleak import BleakClient, BleakScanner from typing import Optional, List BLEDOM_CHARACTERISTIC = "0000fff3-0000-1000-8000-00805f9b34fb" class Days(IntFlag): MONDAY = 1 << 1 TUESDAY = 1 << 2 WEDNESDAY = 1 << 3 THURSDAY = 1 << 4 F...
# -*- coding: utf-8 -*- """ Created on Sat Dec 18 19:47:42 2021 @author: Connor """ from itertools import product, permutations from copy import deepcopy def parse_input(filename): with open(filename, "r") as fh: lines = fh.readlines() out = [] global ll ll = None for line in lines: ...
import torchvision import ast import torch from PIL import Image import torchvision.transforms as transforms from torch.autograd import Variable import torchvision.models as models from torchvision import datasets from torch import __version__ from collections import OrderedDict import matplotlib.pyplot as pl...
import ast import glob import sys from typing import Dict, List import numpy as np class SpecData: def __init__(self, repo, classname, testname, original_time, optimizer_time, best_param, best_score, filename, trials, passed, failed, best_prob): self.repo=repo self.classname=cla...
#!/bin/python from cv2 import cv2 import numpy as np import matplotlib.pyplot as plt import sys import re from math import ceil, sqrt #============================================ #Extract color mapping from VGA color plate #============================================ #Read image and convert into hsv color space pl...
from enum import Enum class JtagState(Enum): """ Set of JTAG states. """ RESET = 0 RUN_IDLE = 1 DRSELECT = 2 DRCAPTURE = 3 DRSHIFT = 4 DREXIT1 = 5 DRPAUSE = 6 DREXIT2 = 7 DRUPDATE = 9 IRSELECT = 10 IRCAPTURE = 11 IRSHIFT = 12 IREXIT1 = 13 IRPAUSE = 14 IREXIT2 = 15 IRUPDATE = 16 # JT...
# -*- coding: utf-8 -*- import os, csv, re, sys from shutil import copyfile from newspaperaccess import NewspaperArchive, NoSuchNewspaper, NoSuchDocumentFound from Levenshtein import distance as L_distance L_THRESHOLD = 1.9 # length of title / L distance. Bigger = better. REFLIST = "positives.csv" if len(sys.arg...
import string import random from kmeldb import MediaFile from pprint import pprint def single_cd( album_name, number_of_tracks, disc_number, offset=0, performer='performer', genre='genre', reversed=False): ''' Creates a single CD worth of tracks and retu...
import bpy import os import numpy as np from photogrammetry_importer.point import Point from photogrammetry_importer.camera import Camera from photogrammetry_importer.file_handler.nvm_file_handler import NVMFileHandler from photogrammetry_importer.file_handler.colmap_file_handler import ColmapFileHandler from bpy.pro...
import numpy as np import matplotlib import matplotlib.pyplot as plt def plot_dates(zircon_means, zircon_2sigmas, include, sample_means, sample_2sigmas, colors, labels, legend=True, figsize=None, ylim=None, lineweight=None, bbox_to_anchor=None, plot_zircons=True): """...
import boto3 import torch import torchvision import torchvision.transforms as transforms from torch.utils.data import DataLoader, Dataset from tensorboardX import SummaryWriter from PIL import Image from tqdm.notebook import tqdm import numpy as np import os import sys from Utils import networks manualSeed = 999 torch...
import SonarDataset import tensorflow as tf import numpy as np def sigmoid(phi): return 1.0/(1.0 + tf.exp(-phi)) def train_boundary_hunter(points, out, iterations): in_size = len(data[0]) out_size = 1 num_centroids = 1 inputs = tf.placeholder('float64', [in_size]) targets = tf.placeholder('fl...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """PocketMod Creator This script should be called from the command line with a valid input file argument. It takes the input PDF and converts it into a pocketmod format PDF. This pocketmod PDF is output into the directory the script was called from. This tool accepts a P...
import tkinter as tk import schedule import time import queue import threading from slack_app.slack_message import * class CheckBar(tk.Frame): def __init__(self, options_list, parent=None, side=tk.TOP, anchor=tk.W): tk.Frame.__init__(self, parent) self.vars = list() for opt in options_list...
from .fgir import * from .error import * # Optimization pass interfaces class Optimization(object): def visit(self, obj): pass class FlowgraphOptimization(Optimization): '''Called on each flowgraph in a FGIR. May modify the flowgraph by adding or removing nodes (return a new Flowgraph). If you modify nodes, ...
# MIT License # # Copyright (c) 2019 enigmatos # # 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, pu...
""" Use of this source code is governed by the MIT license found in the LICENSE file. All (known) response messages to be received from plugwise plugs """ from datetime import datetime import struct from plugwise.constants import ( MESSAGE_FOOTER, MESSAGE_HEADER, ) from plugwise.message import PlugwiseMessage ...
from collections import defaultdict import argparse import numpy as np import chainer from chainer import iterators from chainer.dataset import concat_examples from chainer import functions as F from chainercv.datasets import ade20k_semantic_segmentation_label_names from chainercv.datasets import ADE20KSemanticSegmen...
'''ResNet in PyTorch. For Pre-activation ResNet, see 'preact_resnet.py'. Reference: [1] <NAME>, <NAME>, <NAME>, <NAME> Deep Residual Learning for Image Recognition. arXiv:1512.03385 ''' import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter class BasicBlock(nn.Module):...
#!/usr/bin/env python3 """Compute the expected segment length distribution of compressed winnowing windows for a given hash function codomain size C and winnowing windows size w for segments up to length k. This code was developed in cooperation with Dr. <NAME> (https://ls11-www.cs.tu-dortmund.de/staff/kurz). """ impo...
import functools import itertools import operator as op from abc import ABC from typing import List, Tuple, TypeVar from gen_factor_sat.circuit.interface.circuit import GateStrategy, SimpleCircuitStrategy, NBitCircuitStrategy from gen_factor_sat.formula.symbol import Constant, constant T = TypeVar('T') W = TypeVar('W...
from __future__ import unicode_literals, division, absolute_import from datetime import datetime, timedelta from string import capwords from flexget.manager import Session from flexget.plugin import register_plugin, register_parser_option, DependencyError from flexget.utils.tools import console try: from flexget.p...
import re from datetime import datetime, timedelta from dateparser import parse as d_parse from dateutil.parser import parse class EumeOrigin(object): producers = "producers" Consumers = "Consumers" middlemen = "middlemen" class JudgeField: NUMTYPE = ["count"] STRTYPE = ["content"] NONETYPE ...
""" Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ #!/usr/bin/python # -*- coding: utf-8 -*- import re import subprocess import sys def findTokenToInt(output, ex...
import asyncio import json import logging import os import smtplib import sys import time from datetime import datetime, timedelta from email.header import Header from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import base64 import requests from pyppeteer import launch # 不能删,隔壁 dyna...
# jupyter-require # Copyright 2019 <NAME> <<EMAIL>> # # MIT License # # 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, co...
from keras.models import Sequential from keras.layers import Dense, Activation, LSTM from keras.callbacks import LambdaCallback from keras.optimizers import RMSprop import numpy as np import random import datetime import sys from LSTM import mecab from LSTM import format def sample(preds, temperature=1.0): preds ...
from scipy.optimize import curve_fit from numpy import inf class convergenceError(Exception): def __init__(self,curr,best): Exception.__init__(self) self.best = best self.curr = curr def __str__(self): return (Exception.__str__(self)+"Current: " + ":".join((str(x) for x in self.c...
""" define class Gene """ # from random import randint from autoprover.evaluation import evaluation # import logging def random_chromosome(tactics): """generate a random chromosome with length of 15. Args: tactics (Tactic): a Tactic class instance. Returns: list: chromosome, a list of str...
from datetime import datetime, timedelta from django.db import models from django.utils.translation import ugettext as _ from django.contrib.localflavor.us.models import PhoneNumberField from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.contrib.contenttypes.models imp...
# Simple Python implementation of node and directed graph class Node(object): def __init__(self, name): self.name = name self.inlinks = [] self.outlinks = [] self.rank = 0.0 self.new_rank = 0.0 def add_outlink(self, node): # Add directed edge from this node to a...
""" Gaussian Mixtures implementations from ngmix ported to tensorflow Author: es<NAME>. (original), andrevitorelli (port) ver: 0.0.0 """ import tensorflow as tf pi = 3.141592653589793 #############utilites conversions def fwhm_to_sigma(fwhm): """ convert fwhm to sigma for a gaussian """ return fwhm / 2.35...
""" Used for analysis of public companies filing with the United States SEC. """ from dataclasses import dataclass from typing import Iterable, Tuple, Union import pandas as pd from ..dataframes import Form10K, Form10Q, HistoricalStockPrices from ..utils import NestedDepthError, nested_depth, ticker_or_ci...
# -*- coding:utf-8 -*- ''' @Author: LiamTTT @Project: TCTPreprocess @File: utils.py.py @Date: 2021/9/10 @Time: 上午10:46 @Desc: Tools for processing annotations. ''' import numpy as np from .VOCAnnotation import BndBox, Size, Source, Object, Annotation def create_voc_annotation( folder, filename, imag...
import mysqlwrite import copy #从共享文档下载解压 import uniform import main_rate import tkinter as tk op0=['CELC','E1','E2','E3','E4','E5','EW2','SDE1','SDE2','SDE3','EA','E2A','E1A','E3A','E4A',\ 'EW1','TLAB','UCC','YSTCM','LT1','LT2','LT3','LT4','LT5','LT6','LT7','LT7A'] op1=['CL','KR11','CCELIB','KR12A','S2S'] op2=...
from .. import errors, updateset, utils from . import base_field import uuid class ListWrapper(list): def __init__(self, *args, list_field=None, **kwargs): self.list_field = list_field super().__init__(*args, **kwargs) def __eq__(self, other): return self.as_value() == other def ...
# -*- coding: utf-8 -*- """ Various functions to help with IO. Not intended for 3rd party clients. """ import os import glob # pylint: disable=missing-function-docstring, invalid-name def get_calib_prefix(file_prefix: str): prefix = 'calib' if file_prefix: prefix = file_prefix return prefix d...
import collections from django.apps import apps from django.contrib.admin.utils import NestedObjects from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, transaction from terminaltables import AsciiTable from review import models RELATED_OBJECTS_TO_MERGE = { ...
#!/usr/bin/env python # coding: utf-8 # In[7]: import os import matplotlib.pyplot as plt import numpy as np ## read data: import pandas as pd import copy import os folder_names = sorted(os.listdir("../Data/ILSVRC/Data/CLS-LOC/train/")) folder_names =sorted([i for i in folder_names if "n" in i]) # print(len(folde...
from datetime import datetime, timezone, timedelta from google.cloud import storage from pytz import timezone from utils import now_with_timezone import __main__ import dashboard import gzip import json import requests __taipei_tz__ = timezone('Asia/Taipei') __api_time_format__ = '%Y-%m-%dT%H:%M:%S' def get_daily_o...
import time import ctypes from multiprocessing import Process, Manager from multiprocessing.sharedctypes import Array ARQUIVO = "BASEPROJETO.txt" PESOS_CPF_PRIMEIRO_DIGITO = [10, 9, 8, 7, 6, 5, 4, 3, 2] PESOS_CPF_SEGUNDO_DIGITO = [11, 10, 9, 8, 7, 6, 5, 4, 3, 2] PESOS_CNPJ_PRIMEIRO_DIGITO = [5, 4, 3, 2, 9, 8, 7, 6, ...
import numpy as np import numba as nb import pandas as pd import qnt.ta.ndadapter as nda import typing as tp import time import sys from qnt.log import log_info, log_err @nb.jit(nb.float64[:](nb.float64[:], nb.int64), nopython=True) def lwma_np_1d(series: np.ndarray, periods: int) -> np.ndarray: tail = np.empty((...
from src.PFA_AES import * from multiprocessing import Pool def RandomMatrix(): matrix = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] for i in range(0,4): for j in range(0,4): matrix[i][j]=random.randint(0, 255) return matrix def GenerateCiphertext(key,numofciphertext, *Table): Ciphert...
from __future__ import absolute_import, division, print_function, unicode_literals from utils.DataLoader import DataLoader as dl import tensorflow as tf class DatasetGenerator: def __init__(self, dataset='taxi', batch_size=64, n_w=0, n_d=7, n_wd_times=3, n_p=1, n_before=1, l_half=3, pre_shuffle=...
#GUI con TKinter - Procesador de Texto #Autor: <NAME> #Fecha: 23/Sep/2017 #Descripcion: Curso Python FES Acatlán from tkinter import * from tkinter import messagebox as mb from tkinter import filedialog as fd from io import open #Variables de control ruta = "" #Variable para verificar archivo g = "" #Vari...
""" This file defines actions, i.e. functions the URLs are mapped into The @action(path) decorator exposed the function at URL: http://127.0.0.1:8000/{app_name}/{path} If app_name == '_default' then simply http://127.0.0.1:8000/{path} If path == 'index' it can be omitted: http://127.0.0.1:8000/ The pa...
from tkinter import * import numpy as np import math from geometry import * from graph import * from functions import * import time graph_noderadius = 70 graph_nodewidth = 50 graph_nodeoffset = 3*graph_noderadius graph_arrowheadradius = 5 graph_folddepth = 2 graph_maxstep = 5 graph_stepratio = 0.2 width = 1000 height...
import requests import json import timeit import time import io import os import itertools from pymongo import MongoClient from multiprocessing.dummy import Pool as ThreadPool from functools import partial class Static: headers = {'Host': 'data.stats.gov.cn', 'Proxy-Connection': 'keep-alive', 'Cache-Control': ...
from __future__ import unicode_literals import frappe, erpnext from frappe.utils import flt, cint, nowdate from frappe import throw, _ import frappe.defaults from frappe.utils import getdate from erpnext.stock.get_item_details import get_conversion_factor from erpnext.buying.utils import validate_for_items from erpnex...
import pygame, sys, random, time screen_width, screen_height = (600, 700) screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption("Brick Out") player = pygame.Rect(((screen_width//2)-50, screen_height-30),(100, 10)) ball = pygame.Rect(((screen_width/2)-(20/2),(screen_height-60)),(20...
#!/usr/bin/env python3 """ Usage example of Targetran with TFDS for image classification model training. On a Kaggle Notebook, select the "Accelerator": TPUv3-8 """ import os from typing import Tuple # Needed for the Kaggle Notebook. os.system("pip install -U targetran") import matplotlib.pylab as plt import numpy ...
import os from app import app from flask import request, jsonify,make_response import uuid import json import time from app.models import * def wrap(arg): response = make_response(arg) response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'GET, POST' r...
#!/usr/local/bin/python3 from os.path import join, dirname, abspath import argparse import xlrd from sheet_helper import connect_GSheets, spreadsheet_id from sheet_helper import section1_sheet_id, section2_sheet_id from sheet_helper import color_default, color_wrong from other.student_info import section1_grade, sec...
# App necessities from flask import Flask, render_template, request import requests from hikepnw import app # Data manipulation import pandas as pd import numpy as np # Database connections from sqlalchemy import create_engine from sqlalchemy_utils import database_exists, create_database import psycopg2 # lightfm hybri...
"""Update all the get-pip.py scripts.""" import itertools import operator import re from base64 import b85encode from functools import lru_cache from io import BytesIO from pathlib import Path, PosixPath from typing import Dict, Iterable, List, Tuple from zipfile import ZipFile import requests from cachecontrol impor...
#!/usr/bin/env python import sys from datetime import date import requests from html.parser import HTMLParser import json class HTMLParserWBGTEnvGoJp(HTMLParser): """ html pserver class for the html text taken from WBGT daily in env.go.jp such as http://www.wbgt.env.go.jp/day_list.php?region=04&prefecture...
#!/usr/bin/env python """ - Set of functions for converting between different speech quality estimation metrics such as PESQ MOS, MOS LQO, R-factor. - Python wrapper for ITU-T pesq utlity. - Helper class to define Speex codec parameters based on other options: - mapping between speex "quality" and "mode" opti...
from copy import deepcopy flag = [ [0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 2, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 3, 4, 2, 3, 0, -1, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 2, 2, 1, 3, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, 0, 0, 0...
import threading import zmq import logging import time import socket __all__ = ['EventPublisher', 'EventSubscriber', 'EventMessage', 'EventCodes'] class EventPublisher(object): """ Event broadcast class for Labtronyx :param port: Port to bind for event notifications :type port: int ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.test import TestCase from rest_framework.test import APIClient from django.core.urlresolvers import reverse from rest_framework import status from django.contrib.auth.models import User # Create your tests here. from .models import Blog, Cate...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from datetime import timedelta from django.shortcuts import render from django.utils.timezone import now from datetime import datetime import time from aggregator.models import Dataset, Organization, Variable, Dimension from bdo_main_app.models import Ser...
__version__ = 1.02 try: import tkinter as tk BOTTOM_TK = tk.BOTTOM TOP_TK = tk.TOP LEFT_TK = tk.LEFT RIGHT_TK = tk.RIGHT except ImportError: pass class PyToolsError(Exception): pass """ ############################################################# PyTools...
"""Handle requests to display the trackbacks for arXiv articles.""" import re from typing import Any, Dict, List, Tuple from werkzeug.exceptions import InternalServerError, BadRequest from werkzeug.datastructures import MultiDict from arxiv import status from arxiv.base import logging from arxiv.base.globals import g...
import random import string from typing import Optional, Union from django.contrib.auth.models import Group from django.db.models import QuerySet, Q from django.http import Http404 from django.shortcuts import get_object_or_404 from rest_framework.request import Request from content_app.models import Post, Comment fr...
""" <NAME> and <NAME>, Reinforcement Learning, <NAME>ion University of the Negev, 2020 """ from datetime import datetime import gym import matplotlib.pyplot as plt import numpy as np from numpy.linalg import inv from tqdm import tqdm """ Assumes installation of tqdm: pip install tqdm If this is an issue, remove the...
#!/usr/bin/python # -*- coding: utf-8 -*- # A DynaFed that contacts an LDAP server and uses a JSON file # to determine whether a user with certain attributes can # access a resource # usage: # ldap_auth.py <clientname> <remoteaddr> <fqan1> .. <fqanN> # # Return value means: # 0 --> access is GRANTED # nonzero --> acce...
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.11.3 # kernelspec: # display_name: Python 3 # name: python3 # --- # + [markdown] id="gn_7TYq4nJ1y" # # Parallel simulation of a bubble raft # *...
from abc import ABC, abstractmethod import numpy as np import sympy from scipy import stats from roughml.plot import as_grayscale_image class SurfaceGenerator(ABC): def __init__( self, n_points, rms, skewness, kurtosis, corlength_x, corlength_y, alpha ): self.n_points = n_points self...
from collections import defaultdict from datetime import datetime import math from operator import itemgetter import os import random import re import numpy as np import pandas as pd import little_mallet_wrapper as lmw import pdb import seaborn as sns import matplotlib.pyplot as plt import constants root = "/home/c...
from pathlib import Path from typing import Iterable, List, Union from pyregions.dataio import datasets from infotools import numbertools from pony.orm import db_session, BindingError import importlib from pyregions import standard_definition as sd from pyregions.database.ponydatabase import sql_entities cl...
import os from typing import Mapping import numpy as np import pytest import tensorflow as tf from emulation._monitor.monitor import ( StorageHook, _bool_from_str, _convert_to_quantities, _convert_to_xr_dataset, _create_nc_path, _get_attrs, _get_timestep, _load_nml, _remove_io_suffi...
from flask import Flask, render_template, request, flash, redirect, url_for, session, logging #from data import Blogs from flask_mysqldb import MySQL from flask_wtf import Form from wtforms import Form, StringField, TextAreaField, PasswordField, validators from wtforms.validators import Required from passlib.hash impo...
from lenet5 import * import numpy as np import matplotlib.pyplot as plt def get_data(dim=100, load=True): """ :param dim: images per worker :param load: :return: data_workers, y, lenet5, right_pred_data, labels, test_x, test_y. Where right_pred_data is the variable of lenet5 correctly...
#!/usr/bin/env python3 import django import sys # 在crontab环境下可能会无法找到PYTHONPATH,PYTHONPATH决定python查找lib的路径 sys.path.append('/home/ljtc/dev') import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'devnet.settings') django.setup() from devnet2019.models import Devicedb, DeviceInterface, DeviceInterfaceState, DeviceI...
import boto3 import json import time import botocore import glob import cleanup import detection initial_directory = "./S3-Files" #directory containing mp4 files to be processed shortened_files_directory = "./Wav-Clips" #directory containing files to be uploaded to azure wav_files_directory = "./Wav-Encoded" reprocess...
from enum import IntEnum, unique from typing import Tuple, List from ijim.types.vector import * @unique class KeyFlag(IntEnum): Loop = 0x0 PauseOnFirstFrame = 0x1 NoLoop = 0x2 PauseOnLastFrame = 0x4 RestartIfPlaying = 0x8 FinishInGivenTime = 0x10 EndSmo...
import re import os from tqdm import tqdm import logging import pandas as pd from preprocess.preprocess import load_stopwords, seg_sentence from gensim import corpora, models, similarities from w2v_wmd.dataProcess import seg_sentence, load_stopwords from utils import read_pkl_file, save_pkl_file, eval_MPP lo...
# -*- coding: utf-8 -*- """ gui defines using PyQt5 @author: <NAME> and <NAME> """ import cv2 import numpy as np import face_functions as face from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QWidget, QInputDialog, QLineEdit, QGridLayout, QLabel) from PyQt5.QtGui impor...
import cPickle as pickle import copy import gevent import logging import os import os.path import socket import shutil import subprocess import string import time import gzip from whoiscache import parsers, settings, state STATE_INITIALIZING = 'initializing' STATE_UPDATING = 'updating' STATE_READY = 'ready' STATE_ERR...
#!/usr/bin/python from __future__ import absolute_import, division, print_function, unicode_literals import os import cv2 import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow import keras from tensorflow.keras.preprocessing import image from tensorflow.keras.models import model_fro...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2019-12-04 15:13 qiang.zhou <<EMAIL>> # # Distributed under terms of the MIT license. """ """ import cv2 from PIL import Image import random import numpy as np import torch import torchvision.transforms.functional as TF def Train_Collat...
""" Functions for creating, formatting and serialising representaitons of molecules. """ import re import pandas as pd import numpy as np import periodictable as pt from pyrolite.mineral.transform import merge_formulae from ..util.sorting import get_relative_electronegativity from ..util.meta import interferen...
#%% Imports from datetime import datetime import requests import requests_cache from bs4 import BeautifulSoup as bs import re #%% Invariants requests_cache.install_cache() BASE_URL = "https://aleemstudio.com/SalatTimings/SalatTimings4MonthExternal/" current_month = datetime.now().month current_day = datetime.now().d...
import asyncio import logging from centimani.headers import Headers _LOGGER = logging.getLogger(__name__) REQUEST_METHODS = frozenset( {"GET", "HEAD", "POST", "OPTIONS", "PUT", "PATCH", "DELETE"} ) #======================================# # HTTP Response and Request Structures # #=============================...
from PyQt5.QtWidgets import (QTableView, QHeaderView, QAbstractItemView, QStyledItemDelegate) from PyQt5.QtCore import (Qt, QMimeData, QModelIndex, ...
import struct from . import resources from .anim import AnimatedValue, ConstantValue, autoschedule, Wait from .text import get_font from .palette import Palette def pack_f1(f): return int(f * 255) SKIPS = { (-1, -1): 0, ( 0, -1): 1, (+1, -1): 2, (-1, 0): 3, ( 0, 0): 4, (+1, 0): 5, ...
""" Validate CAL MevPerDac calibration data in XML format. The command line is: mevPerDacVal [-V] [-r] [-R <root_file>] [-L <log_file>] <xml_file> where: -r - generate ROOT output with default name -R <root_file> - output validation diagnostics in ROOT file -L <log_file> - save console outpu...
# © 2019 University of Illinois Board of Trustees. All rights reserved import torch class PositionalEncoding(torch.nn.Module): """ This is based on the "Attention is all you need" paper, and the Transformer-XL paper Code reference: https://github.com/kimiyoung/transformer-xl """ def __init__(...
''' File: groupLasso.py Author: <NAME> (<EMAIL>) ''' # Standard library imports import math # Third party imports import numpy as np import tensorflow as tf @tf.function def groupLasso(y, p, alpha, beta): ''' input: y = labels. (batch_size, num_of_classes) p = predictions. (b...
#!/usr/bin/env python # <NAME> (<EMAIL>) from collections import defaultdict import pystache import re import subprocess # Top level --version is a pain to deal with so ignoring for now # This one extracts single commands and the help txt commandRegex = r"^\s+(?P<command>\w+)\s+(?P<helptxt>[a-zA-Z ]*)$" # Why the he...
# This file is part of MaixUI # Copyright (c) sipeed.com # # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license.php # import image def draw_quadrangle(img, topL, topR, downL, downR, radius, fill=True, color=(255, 0, 0)): #print(topL, topR, downL, downR, radius) tmp = [ (to...
### Voxel-Based VAE Layers # <NAME> 2016 # Originally adopted from Voxnet import numpy as np import lasagne from lasagne.layers import Layer import theano import theano.tensor as T from theano.sandbox.cuda import dnn from theano.sandbox.cuda.basic_ops import gpu_contiguous, gpu_alloc_empty from theano.sandbox.cu...
# -*- coding: utf-8 -*- # Copyright 2017-2019 ControlScan, Inc. # # This file is part of Cyphon Engine. # # Cyphon Engine is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # Cyphon En...
#!/usr/bin/env python import numpy as np import traceback import glob from scipy.stats.mstats import gmean from CGIAR.slim.eval_image_classifier import eval_images # Note : List of train-classes CLASSES = ['leaf_rust', 'stem_rust', 'healthy_wheat'] def prepare_test_data(): file_paths = [] file_names = []...
# ___________________________________________________________________________ # # Prescient # Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. # This software is ...
""" Extra utility functions for interfacing within a dragodis disassembly """ from typing import Union, List, Iterable, Tuple, Optional import logging from dragodis import Disassembler, ReferenceType, NotExistError, OperandType from dragodis.interface import Function logger = logging.getLogger(__name__) def iter_...
""" Parse data for TAT-vol2 directly goes to training data """ import sys import os import pandas as pd import numpy as np import json import argparse from collections import defaultdict def append_files(df, directory, args): if args.pseudo_label: text_column_name = "pseudo_cmn" else: text_colu...
# !/usr/bin/env python3 # Author: <EMAIL> # Function:获取https证书的过期时间 # 需要先执行 pip3 install pyopenssl, pip3 install zmail, pip3 install netifaces from OpenSSL import SSL import idna from socket import socket from datetime import datetime import zmail import netifaces def get_ip(interface_name): loc...
# import the necessary packages from imutils.video import VideoStream from imutils.video import FPS import numpy as np import argparse import imutils import time import cv2 import RPi.GPIO as GPIO # Motor Control Functions: def MotorInit(F,B,R,L,EN,_EN): GPIO.setmode(GPIO.BOARD) GPIO.setup(F, GPIO.OUT) GPIO...
""" Model data for optimal binning 2D formulations. """ # <NAME> <<EMAIL>> # Copyright (C) 2020 import numpy as np from ..metrics import jeffrey from ..metrics import jensen_shannon from ..metrics import hellinger from ..metrics import triangular def _connected_rectangles(m, n, n_rectangles, monotonicity_x, monoto...