text
stringlengths
3.07k
12.6k
# Copyright 2016 United States Government as represented by the Administrator # of the National Aeronautics and Space Administration. All Rights Reserved. # # Portion of this code is Copyright Geoscience Australia, Licensed under the # Apache License, Version 2.0 (the "License"); you may not use this file # except in c...
import argparse import os import shutil import json import time from io import BytesIO import requests from bs4 import BeautifulSoup import lxml from PIL import Image from tqdm import tqdm GET_INTERVAL = 1 # sec TABLE_PAGE = 'https://gbf-wiki.com/index.php?%C1%B4%A5%AD%A5%E3%A5%E9%A5%AF%A5%BF%A1%BC%B0%EC%CD%F7' def...
import numpy as np import torch from lib.BaseAlg import BaseAlg # from backpack import backpack, extend # from backpack.extensions import BatchGrad def get_device(): if torch.cuda.is_available(): device = "cuda:{}".format(torch.cuda.current_device()) else: device = "cpu" # print("Use devi...
from pathlib import Path import json def getRootPath(subdir='data'): return Path(__file__).parent.absolute() / subdir KnowledgeBase = {} def jsondec(x): if isinstance(x, str): try: return json.loads(x) except: print('[JSON ERROR]', x) return {} retur...
# # Copyright <NAME>, 2012-2014 # # # This file contains definition of basic Generator interface # And all Exceptions # class GeneratorBase: def __init__(self): self.myParent = None def setParent(self, parent): self.myParent = parent def getVariableNames(self): raise NotImplemented...
import numpy as np def rasterize(V): """ Polygon rasterization (scanlines). Given an ordered set of vertices V describing a polygon, return all the (integer) points inside the polygon. See http://alienryderflex.com/polygon_fill/ Parameters: ----------- V : (n,2) shaped numpy array ...
import pandas as pd import math import numpy as np # from sklearn import metrics from sklearn import mixture from sklearn import cluster # import igraph import scipy as sp import scipy.linalg as linalg import networkx as nx import time from sklearn.cluster import KMeans def getNormLaplacian(W): """input matrix W=...
import os, random, json import numpy as np from scipy import stats import util SEQ_SIZE = 8 NUM_TO_GEN = 20 MODEL_DIR = 'trained_all/' PARSED_DIR = 'parsed_all/' MAKE_STATEFUL = False IS_REVERSE = True #Load titles title_words, title_word_to_ix = util.load_title_dict(PARSED_DIR) title_dict_size = len(title_words) tit...
# Split files for cross validation def cross_val_files(fpath): f = open(fpath, encoding='utf-8') lines = f.read().split('\n') lines = lines[1:-1] f.close() folds = [] fold1 = lines[:100] fold2 = lines[100:200] fold3 = lines[200:300] fold4 = lines[300:400] fold5 = lines[400:500] fold6 = lines[500:600] fold7...
import random import copy import asyncio from itertools import combinations, product, permutations from math import exp from prettytable import PrettyTable from matplotlib import pyplot as plt async def get_async_gen(sub): for i in sub: yield i def bool_function(x1: bool, x2: bool, x3: bool, x4: bool) ...
#!/usr/bin/env python # Copyright 2017 Informatics Matters Ltd. # # 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 applicab...
import torch as to from abc import ABC, abstractmethod from typing import Sequence from warnings import warn import pyrado from pyrado.exploration.normal_noise import DiagNormalNoise, FullNormalNoise from pyrado.utils.properties import Delegate from pyrado.sampling.hyper_sphere import sample_from_hyper_sphere_surface ...
# Act 3 # KEY FEATURES # weapons and equipment # more lore of game explored # combat and enemies # includes from TheCavesOfAntiquorum import items, const from TheCavesOfAntiquorum.helpers import clearScreen, inputError, printSlow, printVerySlow, loadPlayer from TheCavesOfAntiquorum.player import Player from TheCavesO...
import os import sys import general_utils import os from subprocess import PIPE, run def generate_function_c_file(func_num, functions, input_filename): f = open(input_filename, 'w') signature = "" function = functions[func_num] signature += "double function_" + str(func_num) + "(" for j in range(le...
import torch import torch.nn as nn import torch.nn.functional as F from ..utils import get_activation def make_att_3d(attention, channel, act_mode='relu'): if attention == 'strip_pool': return StripPoolingAttention3D(channel, act_mode) elif attention == 'plane_pool': return PlanePoolingAttent...
import pandas as pd from datetime import datetime, timedelta from embrace import get_date_from_garmin import os import collections def revise(): path = os.path.join(os.getcwd(), 'Selina Luo_26.11.20_12.21.44.md.pm.bp_datetime.csv') df = pd.read_csv(path) for i in range(len(df.Timestamp)): datetim...
import discord from discord.ext import commands from discord_slash import SlashCommand from dotenv import load_dotenv import os import requests import json import sentry_sdk import re # Basic setup description = "Official StopModReposts bot" bot = commands.Bot(command_prefix='/', description=description,...
from tkinter import * # -------massive coordinates of object------# # objectx=[0, 1, 0, -1] # objecty=[1, 0, -1, 0] # ---------------********------------------# # -------coordinates of circle object------# # objectx=[] # objecty=[] # # numpoint=100 # alpha0=2*3.14/numpoint # radius=0.3 # for pcr in range(numpoint)...
import operator from abc import ABCMeta, abstractmethod from functools import wraps from inspect import isclass from types import FunctionType from flask import request from .allows import _call_requirement from .overrides import current_overrides __all__ = ( "Requirement", "ConditionalRequirement", "wan...
#!/usr/bin/env python """ kmeans.py is a python 2.7 script implementing kmeans clustering, per the spec of Stanford class BMI 214, project 2 @author: <NAME> usage: python kmeans.py k expression.dat max.it centroids.txt INPUTS: k :: int; [1+]; the number of centroids / groupings to use data_file :: string...
from typing import Optional import discord from discord.ext import commands from discord.ext.commands import Context import numpy as np import lichess.api from LichessBot import LichessBot class Ratings(commands.Cog): def __init__(self, client: LichessBot): self.client = client @commands.command(na...
# 适配模式-实战电子书阅读器 from abc import ABCMeta, abstractmethod, ABC # 引入ABCMeta和abstractmethod来定义抽象类和抽象方法 import os # 导入os库,用于文件、路径相关的解析 class Page: """电子书一页的内容""" def __init__(self, pageNum): self.__pageNum = pageNum def getContent(self): return "第 " + str(self.__pageNum) + " 页的内容" class Ca...
# -*- coding: utf-8 -*- """Tests for imfusion.insertions.aligners.tophat module.""" # pylint: disable=wildcard-import,redefined-builtin,unused-wildcard-import from __future__ import absolute_import, division, print_function from builtins import * # pylint: enable=wildcard-import,redefined-builtin,unused-wildcard-impor...
#將股票交易資料放進MongoDB資料庫,就不用需要每次從證交所讀取資料 #Refers from https://github.com/jang0820/Stock/blob/master/FromTwseToMongo.py ###################################################### import numpy as np import requests import pandas as pd import datetime import json import matplotlib.pyplot as pp import time,os,sys from pymongo imp...
""" LinkedIn OAuth1 and OAuth2 backend, docs at: http://psa.matiasaguirre.net/docs/backends/linkedin.html """ from social.backends.oauth import BaseOAuth1, BaseOAuth2 class BaseLinkedinAuth(object): EXTRA_DATA = [('id', 'id'), ('first-name', 'first_name', True), ('last-name...
import numpy as np """ # This is basically a clean up of the implementations explained below # TODO: actually read through to understand the code # 1. https://medium.freecodecamp.org/improvements-in-deep-q-learning-dueling-double-dqn-prioritized-experience-replay-and-fixed-58b130cc5682 # 1b. https://gist.github.com/s...
''' --- Day 15: Rambunctious Recitation --- You catch the airport shuttle and try to book a new flight to your vacation island. Due to the storm, all direct flights have been cancelled, but a route is available to get around the storm. You take it. While you wait for your flight, you decide to check in with the El...
import gc import os from dask.diagnostics import ProgressBar from dask import compute from dask import delayed import matplotlib.patheffects as pe import matplotlib.pyplot as plt import networkx as nx from tqdm import tqdm def plot_gdf_vs_nx(G, gdf, boundaries): positions = {n: [n[0], n[1]] for n in list(G.nodes...
import os import random from time import time from PIL import Image import numpy as np import tensorflow as tf random.seed(0) slim = tf.contrib.slim work_dir = os.getcwd() tf.flags.DEFINE_string( 'input_dir', os.path.join(work_dir, 'development_set/images/'), 'Input directory with images.') tf.flags.DEFINE_strin...
from copy import deepcopy from django.utils.translation import ugettext_lazy as _ from django.utils.six import iteritems from api import serializers as s from api.validators import validate_alias from api.vm.utils import get_owners from api.vm.define.serializers import VmDefineSerializer, KVmDefineDiskSerializer, VmD...
import tarski from tarski.io import PDDLReader from tarski.io import fstrips as iofs from tarski.syntax import land, Atom from tarski.search import GroundForwardSearchModel from tarski.grounding.lp_grounding import ( ground_problem_schemas_into_plain_operators, LPGroundingStrategy, ) from tarski.grounding.na...
# -*- coding: utf-8 -*- """ LCBRU Downloads Tests """ import pytest import downloads from pprint import pprint from bs4 import BeautifulSoup from urllib.parse import urlparse from config import TestConfig, TestConfigCRSF from downloads.models import Download from downloads.database import db as _db class Tureen(...
# -*- coding: utf-8 -*- import pytest from unittest.mock import MagicMock from poke_env.environment.battle import Battle from poke_env.environment.field import Field from poke_env.environment.pokemon_type import PokemonType from poke_env.environment.side_condition import SideCondition from poke_env.environment.status...
import tensorflow as tf import tensorflow.contrib.slim as slim import numpy as np from tensorflow.python.framework import ops def test_scatter_update(): a = tf.Variable(initial_value=[2, 5, -4, 0]) b = tf.scatter_update(a, [2,2], [9,100]) return b def test_scatter_nd(): indices = tf.constant([[3]]) ...
# -*- coding: utf-8 -*- # MIT License # Copyright (c) 2018-2020 Renondedju # 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...
import matplotlib.pyplot as plt from matplotlib import rcParams import matplotlib as mpl mpl.use("Agg") import seaborn import time from pprint import pprint import json import numpy as np np.random.seed(42) import uproot from scipy.stats import rv_histogram, expon, poisson from veloGeom import buildTileXY, b...
#!/usr/bin/env python # coding=utf-8 from pandas import DataFrame, Series from time import time from concurrent.futures import ThreadPoolExecutor from functools import wraps from numpy import nan, unique, round from importlib import import_module from hielen2 import db from hielen2.utils import isot2ut, ut2isot, agood...
#!/usr/bin/env python from __future__ import print_function, absolute_import import rospy from dvs_msgs.msg import EventArray from std_msgs.msg import Int32, Float32MultiArray from rospy.numpy_msg import numpy_msg import numpy as np import cv2 import torch from utils.loading_utils import load_model, get_device import ...
''' Rod with 3 unknown mass. Define rotation center at make-world() Rod composite is loaded from fig/rot_center_rod.png, it's a 12 x 1 grid Regress mass with lcp-physics ''' import os import sys import pickle import time import cv2 import pygame import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes...
from django.db.models import Q from django.http import Http404 from django.shortcuts import render, HttpResponse import json from Players.models import Player from Teams.models import Team from Games.models import Game, PeriodScore, TeamBoxscore def game_index(request): return render(request, 'Games/game_index.h...
import requests import pandas as pd import numpy as np from dimod import BinaryQuadraticModel from dwave.system import LeapHybridSampler def getDataFrames(url): try: r = requests.get(url) except Exception as e: raise(e) _json = r.json() df_mid=df_gk=df_def=df_fwd = None if _json: ...
import matplotlib.pyplot as plt from scipy.fftpack import rfft, irfft, rfftfreq from scipy.signal import butter, filtfilt, freqz, lfilter import numpy as np import torch from torch.autograd import Variable #=============================================================================# # Functions #====================...
from dataset import * from load_model import settings from predict import prediction, recovery from utils import * from load_data import * from K_Sigma_transform import ksigmaTransform from tqdm import tqdm import torch as meg import torch.nn as M from torchvision.transforms import Compose from torch.autograd import Va...
from enum import Enum import math import random import pygame from pygame.locals import * BACKGROUND_GREY = 170 BACKGROUND_VARIANCE = 10 BACKGROUND_ALPHA = 45 CURRENT_RESOLUTION = (0, 0) TARGET_FRAMERATE = 30 JOY_DEADZONE = 0.2 JOY_SPEED_MULT = 2 JOY_X_AXIS_IDX = 0 JOY_Y_AXIS_IDX = 1 JOY_SHAKE_BUTTON_IDX = 3 MOUS...
# convertImageGrayscale.py # A program that converts a user supplied image to grayscale. """Write a program that converts a color image to grayscale. The user supplies the name of a file containing a GIF or PPM image, and the program loads the image and displays the file. At the click of a mouse, the program converts ...
import re import pandas as pd from datetime import date, datetime import configparser # Read local file `config.ini`. config = configparser.ConfigParser() config.read('config.ini') def mmyy_make_iterable_from_to(mmyy_from, mmyy_to=None): """ Create a collection of mmyy formatted dates lying between a from a...
from header_common import bignum ################################################### # header_troops.py # This file contains declarations for troops # DO NOT EDIT THIS FILE! ################################################### #Troop flags tf_male = 0 tf_female = 1 tf_undead = 2 t...
from __future__ import print_function import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import sys import os from sklearn.datasets import fetch_mldata import random import cntk as C import cntk.tests.test_utils from sklearn.preprocessing import OneHotEncoder import argparse ##########...
#!/usr/bin/env python3 """ @summary: how to send a signed transaction @version: v03 (6/March/2020) @since: 6/March/2020 @author: https://github.com/drandreaskrueger @see: https://github.com/drandreaskrueger/chainhammer-substrate for updates """ import time, sys from pprint import pformat from threading import ...
######## # Copyright (c) 2014 GigaSpaces Technologies Ltd. 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...
from enum import Enum import logging, random from django.contrib.auth.models import User from django.contrib.auth.signals import user_logged_in, user_logged_out from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django.conf import settings...
import codecs import hashlib from datetime import timedelta from io import BytesIO import pytest import requests from django.core.files.storage import FileSystemStorage from django.test import TestCase from django_s3_storage.storage import S3Storage from mock import MagicMock from .base import StudioTestCase from con...
from __future__ import print_function, division import os, sys import numpy as np import pickle, h5py, time, argparse, itertools, datetime import torch import torch.nn as nn import torch.utils.data # -- 0. utils -- def countVolume(data_sz, vol_sz, stride): return 1 + np.ceil((data_sz - vol_sz) / stride.astype(flo...
# Code generated by lark_sdk_gen. DO NOT EDIT. from pylark.lark_request import RawRequestReq, _new_method_option from pylark import lark_type, lark_type_sheet, lark_type_approval import attr import typing import io @attr.s class GetHelpdeskFAQListReq(object): category_id: str = attr.ib( default="", metad...
from __future__ import absolute_import from __future__ import print_function import numpy as np import os.path import sys import random import operator import cPickle as pkl from keras.preprocessing import sequence from keras.preprocessing.text import one_hot, Tokenizer_custom as Tokenizer from keras.optimizers import...
import os import sys import json from tkinter import * from tkinter.ttk import * from data import load_data, save_data from pypresence import * import time, datetime, struct, asyncio from time import time, sleep import asyncio #from encounter import encounters (Preventing Circular Imports) # -- #...
""" The admin App """ import os import web import settings import models from models import render web.config.debug = settings.DEBUG urls = ( "/userinfo",'userinfo', "/postsadmin","postsadmin", "/edit/(.+)","edit", "/new","new", "/view/(.+)","view", "/delete/(.+)","delete", "/upload","upload", "/newpwd","newp...
import numpy as np import json import tensorflow as tf from keras_htr.generators import CompiledDataset import scipy def get_zero_padded_array(image_path, target_height): img = tf.keras.preprocessing.image.load_img(image_path) a = pad_image_height(img, target_height) new_height, new_width = a.shape ...
import numpy import matplotlib.pylab as plt from scipy import interpolate import Shadow def read_file_cdf(file_cdf="xshwig.sha"): f = open(file_cdf,"r") firstline = f.readline() f.close() fl = firstline.split(" ")[0:-1] print(len(firstline),fl) np = int(fl[0]) step = fl...
from typing import Callable, Optional, Tuple, Callable, List, Union, cast import os import json import sys from pathlib import Path import lmdb import torch from torch import Tensor from torchvision.io import read_image from torchvision.io.image import ImageReadMode, decode_image from torchvision.datasets import Visio...
#====================== BEGIN GPL LICENSE BLOCK ====================== # # This program 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; either version 2 # of the License, or (at your option) any later vers...
import heapq import time import operator from collections import OrderedDict from .utils import OrderedSet, shared_prefix class KBucket(object): def __init__(self, range_lower, range_upper, ksize): self.range = (range_lower, range_upper) self.nodes = OrderedDict() self.replacement_nodes =...
from datetime import datetime, timedelta from flask import Blueprint, Response, abort, request from flask_restful import Api from flasgger import swag_from from app.docs.restaurant.restaurant import * from app.models.restaurant import RestaurantModel from app.views import BaseResource, json_required from utils.gps_o...
#!/usr/bin/env python """Handles loading multiple binary files, inspecting them and patching them. """ import struct from typing import IO, Optional, Tuple class InvalidAddressException(Exception): """Raised when an address cannot be mapped to a section""" pass class WriteException(Exception): """Raise...
import logging import numpy import os import pandas import pathlib import requests import scipy.stats import tarfile _log = logging.getLogger(__file__) _DP_DATA = pathlib.Path(pathlib.Path(__file__).parent.parent, "data") if not _DP_DATA.exists(): _log.warning("Data directory at %s does not exist yet. Creating......
# pylint: disable=no-name-in-module # pylint: disable=no-self-argument import urllib3 from SiemApiModule import * # noqa: E402 urllib3.disable_warnings() # ----------------------------------------- GLOBAL VARIABLES ----------------------------------------- DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%f' EVENT_FIELDS = [ ...
import dpm.monte_carlo as monte_carlo from dpm.distributions import ( Normal, Beta, Exponential, Gamma, Uniform, Laplace, Gumbel ) import pytest # from scipy.stats import ks_2samp from dpm.utils import to_hist, kl test_means = [ (Normal(0., 1.), 0), (Normal(-7., 1.), -7), (Exponential(4.), 0.25), (...
#Knapsack Problem from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure from matplotlib import style import numpy as np import random # Produto escalar de duas listas numéricas dotp = lambda v1, v2: sum([x*y for x,y in zip(v1, v2)]) # Iniciar população aleató...
# encoding: utf-8 # TODO Needs dtype dependent tests from __future__ import absolute_import, division, print_function import functools as ft import numpy as np import pytest as pt from _pytest.mark import matchmark from numpy.testing import assert_almost_equal from scipy.sparse.linalg import eigsh import mpnum as m...
import time import json from timethese import pprint_cmp, cmpthese from collections import namedtuple import json import six import cachetools import cachetools.keys import functools import pickle def pickled_lru_cache(cache): def pickled_lru_cache_decorator(func): def func_with_pickled_args(pickled_args,...
import unittest from ClassDefinition import ClassDefinition, ClassFlags from Parser.MethodParser import MethodParser from Variable import Variable from Types import Type import Types class ClassParser(object): def parse(self, parserContext): c = ClassDefinition() while True: token = p...
#!/usr/bin/env python3 import re import sys import os escapednewline = re.compile(r'\\\n') singlecomment = re.compile(r'\n?\s*\/{2}.*?\n') multicomment = re.compile(r'\/\*.*?\*\/', re.DOTALL) preprocess = re.compile(r'^\s*#') include = re.compile(r'^(\s*)include(\s)') cprimeinclude = re.compi...
''' A simple Python script to deploy contracts and then do a smoke test for them. ''' import click from populus import Project from populus.utils.wait import wait_for_transaction_receipt from web3 import Web3 from web3.utils.compat import ( Timeout, ) from ecdsa import SigningKey, SECP256k1 import sha3 import sign ...
from pyrh import Robinhood from dotenv import load_dotenv from tweepy import OAuthHandler from tweepy import API from tweepy import Cursor from datetime import datetime, timedelta import urllib.request import os # disable tensorflow debug information os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from imageai.Detection.Custo...
"""Extended image transformations to `mxnet.image`.""" from __future__ import division import random import numpy as np import mxnet as mx from mxnet import nd from mxnet.base import numeric_types __all__ = ['random_expand', 'random_color_distort'] def random_expand(src, max_ratio=4, fill=0, keep_ratio=True): ""...
import csv import itertools import logging import matplotlib.pyplot as plt import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix from horus.core.util import definitions from horus.core.feature_extraction import Core def confusion_matrix_analysis(horus_matrix): df = pd.DataFrame(horus...
''' 主程序 @author: PurePeace @time: 2020年2月10日 02:03:09 ''' import time, datetime, re, requests, random, json from bs4 import BeautifulSoup requests.adapters.DEFAULT_RETRIES = 999 # 增加重连次数 # get now timeString or timeStamp def getTime(needFormat=0, formatMS=True): if needFormat != 0: return datetime.date...
""" do pivot stuff $Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/pipeline/pub/pivot.py,v 1.2 2011/04/06 00:42:41 burnett Exp $ """ version='$Revision: 1.2 $'.split()[1] import os, sys, exceptions import numpy as np from skymaps import SkyDir from uw.utilities import collection class InvalidParameter(exce...
#!/usr/bin/env python # 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, software ...
# coding: utf-8 ''' ------------------------------------------------------------------------------ Copyright 2015 - 2017 Esri 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...
import sys; from datetime import datetime, timedelta; from mikecore.DfsFile import *; from mikecore.DfsFileFactory import *; def DfsShowInfo(dfsFileName, showAxis = False): '''Writes dfs info to console ''' dfs = DfsFileFactory.DfsGenericOpen(dfsFileName) txt = sys.stdout txt.write('FileName ...
# Scalers from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import MinMaxScaler #Classifiers from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.calibration import CalibratedClassifierCV from sklearn....
#!/usr/bin/env python # encoding: utf-8 # The MIT License (MIT) # Copyright (c) 2020 CNRS # 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 ...
"""Tests for schema and examples.""" import json from pathlib import Path, PurePath import datetime import pytest import yaml import jsonschema from copy import deepcopy TESTDIR = Path(__file__).parent.absolute() def test_schema_basic_json_syntax(): """Confirm that schemas are valid JSON""" # find and p...
# coding=utf-8 """ A module holding the cocepts invovled in the game: agent, orders' book, order """ from play import Play from endpoints import VenueList, Stocks __author__ = 'Lorenzo' class Agent: """ The agent for each account/venue pair. The player plays with a given account number for a given venue....
from enum import Enum import re import subprocess class CronScale(Enum): MIN = {"name": "minute", "min": 0, "max": 59} HOU = {"name": "hour", "min": 0, "max": 23} DAY = {"name": "day", "min": 1, "max": 31} MON = {"name": "month", "min": 1, "max": 12} WEE = {"name": "week", "min": 0, "max": 6} cl...
#!/usr/bin/env python # coding: utf-8 """ Check completeness of data. This is fumbling around so far... Sample select for missing days per year: select y.year, y.days, case when r.dwdts is not null then r.dwdts else 0 end / 1.0 / y.days as dwdts, case when r.temp_max is not null then r.temp_max else 0 ...
import math import random LINE_WIDTH = 256 DATA_WIDTH = 32 LINE_DEPTH = 8 BYTE_WIDTH = 8 DATA_HEX_WIDTH = math.ceil(DATA_WIDTH / 4) BYTE_HEX_WIDTH = math.ceil(BYTE_WIDTH / 4) WBE_WIDTH = LINE_WIDTH // BYTE_WIDTH WBE_HEX_WIDTH = math.ceil(WBE_WIDTH / 4) LINE_BYTE_OFFSET = int(math.log2(LINE_WIDTH // 8)) LINE_HEX_WIDTH ...
# Authors: <NAME> <<EMAIL>> # + All contributors to <https://github.com/smarie/python-pytest-cases> # # License: 3-clause BSD, <https://github.com/smarie/python-pytest-cases/blob/master/LICENSE> from copy import copy from decopatch import function_decorator, DECORATED # try: # python 3.2+ # from functoo...
import os import time import json import logging from tuner.solver.base_solver import BaseSolver import numpy as np try: import multibeep as mb except ImportError as e: raise ValueError("If you want to use Hyperband you have to install the following dependencies:\n" "multibeep (see https...
import struct import time from threading import Timer, Lock # for Error Codes from SmartMeshSDK.IpMgrConnectorMux import IpMgrConnectorMux import logging class NullHandler(logging.Handler): def emit(self, record): pass log = logging.getLogger('ReliableCmd') log.setLevel(logging.INFO) log.addHandler(Null...
#!/usr/bin/env python """This module is used to provide functionality to `python -m cronner` By default, it will print out the module name, version, and location. """ from __future__ import print_function import sys from os import path from .executor import execute def init_parser(): parser = argparse.ArgumentPa...
import numpy as np import cv2 import scipy.special as sc import numpy.linalg as linalg from scipy import fftpack def construct_g_D(pos_D, k, n): # pos_D : N X 2 vector containing position of each grid # n : size of each grid # k : wavevector a = (n**2/np.pi)**0.5 N = np.shape(pos_D)[0] L = np.int32(N**0.5) pos...
from PyQt5.QtCore import QRegExp from PyQt5.QtGui import QIntValidator, QRegExpValidator from PyQt5.QtWidgets import QMainWindow, QTableWidgetItem, QDialog, QTableWidget from PyQt5.uic import loadUi from src.Users.controllers.UserManager import UserManager from src.Users.models.User import User from src.Services.contro...
# Copyright (c) 2014, Facebook, Inc. All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. # """Module for common base classe...
# coding: utf-8 # 20190825 rewrite import sys import array import ctypes import struct from typing import Any from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * VS = ''' #version 120 in vec2 aPosition; void main () { gl_Position = vec4(aPosition, 0.5, 1); } ''' FS = ''' #version 120 out ve...
# -*- coding: utf-8 -*- import urllib from hashlib import md5 from datetime import datetime try: import json except ImportError: import simplejson as json class WithingsException(Exception): pass class WithingsAPIError(WithingsException): DESCRIPTIONS = { 100: 'The hash is missing, invalid...
# -*- coding: utf-8 -*- """ Training board ============== Credit: <NAME> A simple example on how to use a the lightweight online board tools. All developement are built upon Visdom. If you prefer tensorboard, use the dedicated `torch.utils.tensorboard.SummaryWriter` class. """ import os import copy import time impor...
from PIL import Image, ImageDraw, ImageFont, ImageColor import textwrap FONT = "Roboto-Regular.ttf" FONT_SIZE = 109 BACKGROUND_COLOR = (0, 0, 0) COLOR = (255, 255, 255) WRAP_WIDTH = 30 PADDING = 10 MARGIN = 15 def _resize(im1: Image, im2: Image, resample=Image.BICUBIC, resize_big_image=True): if im1.height == i...
import os import json from urllib.parse import urljoin import requests import settings from v2ray_api.client import Client from v2ray_api.errors import EmailExistsError, EmailNotFoundError from apscheduler.schedulers.blocking import BlockingScheduler import logging BASE_DIR = os.path.dirname(os.path.abspath(__file__))...