text stringlengths 1 927k |
|---|
from flask import Flask, render_template, redirect, abort, send_file
from flaskext.markdown import Markdown
import os.path
from config import config
app = Flask(__name__)
Markdown(app)
site_title=config['site_title']
site_all_notification=config['site_all_notification']
footer='<small class="m-0 text-center text-whi... |
# -*- coding: utf-8 -*-
#
# tgs documentation build configuration file, created by
# sphinx-quickstart.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a def... |
import os
import io
import itertools
import gzip
import tarfile
import zipfile
import contextlib
import functools
from tqdm import tqdm
from pytools import memoize_method
import pandas as pd
import ir_datasets
import onir
from onir import util, datasets, indices
from onir.interfaces import trec, plaintext
def sanitiz... |
from django.apps import AppConfig
class UnidadeConfig(AppConfig):
name = 'unidade' |
# Copyright (c) 2018 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... |
# -*- coding: utf-8 -*-
'''
A module for shelling out.
Keep in mind that this module is insecure, in that it can give whomever has
access to the master root execution access to all salt minions.
'''
from __future__ import absolute_import, print_function, unicode_literals
# Import python libs
import functools
import g... |
DEFAULT_CONFIG = "Windows10SystemLog.txt"
class Windows10SystemLogger:
"""
Windows10SystemLogger writes error messages to the Windows10 System log
file for every rule in the Windows10 STIG that is violated.
"""
def __init__(self, filename=DEFAULT_CONFIG):
self.filename = filename
... |
import TestConstants
from generator.ExpressionParser import ExpressionParser
import unittest
class TestExpressionParser(unittest.TestCase):
# Test to verify the minute functionality & */multiple expression check.
def test_valid_minute_parsing(self):
expressionParser = ExpressionParser(TestConstants.V... |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.utils.timezone import now as timezone_now
from zerver.data_import.slack import (
get_slack_api_data,
get_admin,
get_guest,
get_user_timezone,
fetch_shared_channel_users,
users_to_zerver_userprofile,
get_subscription,
c... |
import pytest
import mfr
import mfr_rst
def test_detect(fakefile):
# set filename to have .rst extension
fakefile.name = 'mydoc.rst'
handler = mfr_rst.Handler()
assert handler.detect(fakefile) is True
@pytest.mark.parametrize('filename', [
'other.rs',
'otherrst',
'other',
'other.',
]... |
GET_INVERTER_REALTIME_DATA_SCOPE_DEVICE = {
"timestamp": {"value": "2020-09-18T14:14:24-07:00"},
"status": {"Code": 0, "Reason": "", "UserMessage": ""},
"energy_day": {"value": 6000, "unit": "Wh"},
"energy_total": {"value": 35611000, "unit": "Wh"},
"energy_year": {"value": 3310000, "unit": "Wh"},
... |
from __future__ import division
from bisect import bisect
from collections import namedtuple
from math import sqrt, hypot
# a planner computes a motion profile for a list of (x, y) points
class Planner(object):
def __init__(self, acceleration, max_velocity, corner_factor):
self.acceleration = acceleratio... |
"""Logic Blocks devices."""
from typing import Any, List
from mpf.core.delays import DelayManager
from mpf.core.device_monitor import DeviceMonitor
from mpf.core.events import event_handler
from mpf.core.machine import MachineController
from mpf.core.mode import Mode
from mpf.core.mode_device import ModeDevice
from mp... |
"""
OONI Probe Services API - URL prioritization
"""
from typing import List
import random
import time
from flask import Blueprint, current_app, request
from flask.json import jsonify
prio_bp = Blueprint("prio", "probe_services_prio")
# TODO add unit tests
test_items = {}
last_update_time = 0
def update_url_pri... |
import json
import logging
import ibmsecurity.utilities.tools
from ibmsecurity.utilities import tools
from io import open
logger = logging.getLogger(__name__)
uri = "/extensions"
requires_modules = None
requires_version = "9.0.5.0"
try:
basestring
except NameError:
basestring = (str, bytes)
def get_all(isa... |
""" CCOBRA benchmark functionality.
.. rubric:: Submodules
.. autosummary::
:toctree: _autosummary
ccobra.benchmark.comparators
.. rubric:: Functions
.. autofunction:: dir_context
.. autofunction:: entry_point
.. autofunction:: fix_model_path
.. autofunction:: fix_rel_path
.. autofunction:: main
.. autofunct... |
"""
Google web search.
Run queries on Google and return results.
"""
import requests
from kochira import config
from kochira.service import Service, background, Config, coroutine
from kochira.userdata import UserData
service = Service(__name__, __doc__)
@service.config
class Config(Config):
api_key = config.F... |
# Creating multiple topics
# Sam suddenly became a black sheep because she is responsible for
# an onslaught of text messages and notifications to department directors.
# No one will go to lunch with her anymore!
# To fix this, she decided to create a general topic per
# department for routine notifications, and a... |
from typing import Tuple, List
from flask import jsonify
from flask.wrappers import Response
def wrapped_response(data: dict = None, status: int = 200, message: str = "") -> Tuple[Response, int]:
"""
Create a wrapped response to have uniform json response objects
"""
if type(data) is not dict and da... |
# Copyright (c) 2014 Alexander Bredo
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above
# copyright notice, this list of conditions ... |
#!/usr/bin/env python3
# Test remapping of topic name for incoming message
from mosq_test_helper import *
def write_config(filename, port1, port2, port3):
with open(filename, 'w') as f:
f.write("per_listener_settings true\n")
f.write("port %d\n" % (port2))
f.write("listener %d 127.0.0.1\n... |
# qubit number=3
# total number=84
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from... |
def autonomia(carga):
if(carga <= 50000):
return 18000, 19800
elif(carga <= 200000):
return 9000, 9900
else:
return 3000, 3300
carga = int(input())
auto = autonomia(carga)
ax = float(input())
ay = float(input())
bx = float(input())
by = float(input())
dist = (((bx - ax) ** 2) + ((by... |
import hail as hl
from hail.typecheck import typecheck
@typecheck(mt=hl.MatrixTable, path=str, batch_size=int, bgzip=bool, header_json_in_file=bool, use_string_key_as_file_name=bool)
def export_entries_by_col(mt: hl.MatrixTable,
path: str,
batch_size: int = 256,
... |
__all__ = ["YahooFetcher", "QueryBuilder"]
from . import * |
import ila
from gb_arch import GBArch
from gb_nxt_wri import WRI
from gb_nxt_wr0 import WRU0
from gb_nxt_wr0b import WRU0b
from gb_nxt_wr1 import WRU1
from gb_rdi import defNext as rdDefNext
def defUSts (gb):
m = gb.abst
gb.pre_pix = m.reg ('pre_pix', gb.DATA_SIZE)
gb.pre_pix_nxt = gb.pre_pix
... |
import base64
import datetime
import decimal
import sys
import time
import unittest
from unittest import mock
import xmlrpc.client as xmlrpclib
import xmlrpc.server
import http.client
import http, http.server
import socket
import threading
import re
import io
import contextlib
from test import support
from test.support... |
import sys
import DefaultTable
import array
from fontTools import ttLib
from fontTools.misc.textTools import safeEval
class table_T_S_I__5(DefaultTable.DefaultTable):
def decompile(self, data, ttFont):
numGlyphs = ttFont['maxp'].numGlyphs
assert len(data) == 2 * numGlyphs
a = array.array("H")
a.fromstring(... |
__all__ = ['setup_targets']
from pathlib import Path
from typing import Final
from build_system.build_target import *
from build_system.compiler import *
from ..meson import *
def setup_targets(root_dir: Path,
targets: list[CompilerInstanceTargets],
cli_mode: bool) -> None:
f... |
# Copyright (C) 2019-2020, Therapixel SA.
# All rights reserved.
# This file is subject to the terms and conditions described in the
# LICENSE file distributed in this package.
"""The commands module exposes the different command lines methods
that can be used with pacsanini.
"""
from click import echo, group, option
... |
# adapted from https://github.com/nadavbh12/VQ-VAE
import numpy as np
import torch
from torch import nn
from torch.autograd import Function, Variable
import torch.nn.functional as F
from config import *
import pdb
class NearestEmbedFunc(Function):
"""
Input:
------
x - (batch_size, emb_dim, *)
... |
#!C:\Devel\Bankera\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==28.8.0','console_scripts','easy_install-3.6'
__requires__ = 'setuptools==28.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.a... |
from aiida.engine import calcfunction
from aiida.orm import Int
@calcfunction
def sum_and_difference(alpha, beta):
return {'sum': alpha + beta, 'difference': alpha - beta}
result = sum_and_difference(Int(1), Int(2)) |
# Lint as: python3
# Copyright 2019, The TensorFlow Federated Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required ... |
import glob
import subprocess
from setuptools import setup, find_packages, Extension
def build_libs():
subprocess.call(['cmake', '.'])
subprocess.call(['make'])
build_libs()
setup(
name='jetbot',
version='0.3.0',
description='An open-source robot based on NVIDIA Jetson Nano',
packages=... |
import cjb.uif
from cjb.uif.views import Label
from viz.layout import buttonSize
class BaseScene(cjb.uif.Scene):
def __init__(self, ui, key = None):
self.ui = ui
self.scroller = None
cjb.uif.Scene.__init__(self, ui.manager, key or self.__class__.__name__)
self.container.propertie... |
"""Unit tests for pydot drawing functions."""
try:
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
except ImportError:
from io import StringIO
import sys
import tempfile
from nose.tools import assert_equal, assert_is_instance, assert_true
import networkx... |
class Stack:
#initialize stack and top
def __init__(self,max_size=None):
self.__stack = []
self.__max_size = max_size
self.__top = 0
#current length of stack
def __len__(self):
return len(self.__stack)
#check if stack is empty
def is_empty(self):
return True if self.__top==0 else False
#check i... |
# Generated by Django 3.0.8 on 2021-01-15 13:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('Gallery', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='imageclient',
old_name='product',
... |
# Copyright 2019 The Android Open Source Project
#
# 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 ag... |
# -*- coding: utf-8 -*-
"""Canonical correlation analysis
author: Yichuan Liu
"""
import numpy as np
from numpy.linalg import svd
import scipy
import pandas as pd
from statsmodels.base.model import Model
from statsmodels.iolib import summary2
from .multivariate_ols import multivariate_stats
class CanCorr(Model):
... |
#
# Copyright (C) 2009 The Android Open Source Project
#
# 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 la... |
import numpy as np
def amaze_demosaic(src, raw):
cfarray = raw.raw_colors
cfarray[cfarray == 3] = 1
rgb = amaze_demosaic_libraw(src, cfarray, raw.daylight_whitebalance)
return rgb
def amaze_demosaic_libraw(src, cfarray, daylight_wb):
TS = 512
winx = winy = 0
width = src.shape[1]
... |
import copy
from datetime import datetime
from functools import wraps, update_wrapper
from hashlib import blake2b
import logging
from math import log
import os
from subprocess import Popen, PIPE
import uuid
from dateutil import parser
import elasticsearch
import pymysql
from rich import box
from rich.console import Co... |
# Copyright 2013 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
import unittest
from mollufy import mollufy
class MollufyTestSimple(unittest.TestCase):
def test_mollufy_word_2chars(self):
# TEST 1: Mollufy simple 2-characters noun word
self.assertEqual(mollufy.mollufy("블루"), "블?루")
self.assertEqual(mollufy.mollufy("하루"), "하?루")
self.assertEqual(mollufy.mollufy("감... |
import os
import stat
import sys
from stai.util.config import load_config, traverse_dict
from stai.util.permissions import octal_mode_string, verify_file_permissions
from logging import Logger
from pathlib import Path
from typing import Dict, List, Optional, Set, Tuple
DEFAULT_PERMISSIONS_CERT_FILE: int = 0o644
DEFAUL... |
"""webdev URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
import httplib2
import mock
import os
import pickle
import pytest
import socket
import sys
import tests
import time
from six.moves import urllib
@pytest.mark.skipif(
sys.version_info <= (3,),
reason=(
"TODO: httplib2._convert_byte_str was defined only in python3 code " "version"
),
)
def test_conv... |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: liaoxingyu2@jd.com
"""
import math
import random
class RandomErasing(object):
""" Randomly selects a rectangle region in an image and erases its pixels.
'Random Erasing Data Augmentation' by Zhong et al.
See https://arxiv.org/pdf/1708.04896.pdf... |
import platform
import sys
import mock
import pytest
from urllib3.util import ssl_
from urllib3.exceptions import SNIMissingWarning
@pytest.mark.parametrize(
"addr",
[
# IPv6
"::1",
"::",
"FE80::8939:7684:D84b:a5A4%251",
# IPv4
"127.0.0.1",
"8.8.8.8",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pipenv install twine --dev
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'mypackage'
DESCRIPTION = 'My sho... |
from setuptools import setup
setup(
name='proxy-pool',
version='1.0.0',
description='High performance proxy pool',
long_description='A proxy pool project modified from WiseDoge/ProxyPool',
author=['Germey', 'WiseDoge'],
author_email='cqc@cuiqingcai.com',
url='https://github.com/Germey/Proxy... |
import yaml
from enum import Enum
class SimulationType(Enum):
explosion = "EXPLOSION"
collision = "COLLISION"
class SatType(Enum):
rb = "RB"
sat = "SC"
soc = "SOC"
deb = "DEB"
class SimulationConfiguration:
# Takes a .yaml file with simulation configurations
def __init__(self, file... |
"""hellodjango URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class... |
# Copyright (c) Microsoft Corporation and contributors.
# Licensed under the MIT License.
import unittest
import numpy as np
from sklearn.mixture import GaussianMixture
from graspologic.plot.plot import (
_sort_inds,
gridplot,
heatmap,
pairplot,
pairplot_with_gmm,
)
from graspologic.simulations.s... |
from dbgscript import *
thd = Process.current_thread
print(thd)
frame = thd.current_frame
locals = frame.get_locals()
print(locals)
for l in locals: print(l.name)
for l in locals: print(l.name, l.type)
car1 = locals[0]
print(car1.name)
car1_f = car1['f']
print(car1_f)
print(car1_f.name, car1_f.type)
print(car1_f.name, ... |
"""Tests for pywemo.ouimeaux_device.api.service."""
import unittest.mock as mock
from xml.etree import ElementTree
from xml.etree import cElementTree as cet
import pytest
import requests
import pywemo.ouimeaux_device.api.service as svc
HEADERS_KWARG_KEY = "headers"
CONTENT_TYPE_KEY = "Content-Type"
SOAPACTION_KEY =... |
from pydantic import AnyHttpUrl
from typing import List
import os
ENV = os.environ.get("fast_env", "DEV") # 本次启动环境
class Settings:
APP_NAME = "fastapi-vue-admin"
# api前缀
API_PREFIX = "/api"
# jwt密钥,建议随机生成一个
SECRET_KEY = "ShsUP9qIP2Xui2GpXRY6y74v2JSVS0Q2YOXJ22VjwkI"
# token过期时间
ACCESS_TOK... |
# 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
# d... |
import icmplib
from pipecheck.api import CheckResult, Err, Ok, Probe, Warn
class PingProbe(Probe):
"""ICMP ping check"""
host: str = ""
ping_count: int = 1
def __call__(self) -> CheckResult:
h = icmplib.ping(self.host, privileged=False, count=self.ping_count)
if h.is_alive:
... |
"""A merge sort which accepts an array as input and recursively
splits an array in half and sorts and combines them.
"""
"""https://en.wikipedia.org/wiki/Merge_sort """
def merge(arr: list[int]) -> list[int]:
"""Return a sorted array.
>>> merge([10,9,8,7,6,5,4,3,2,1])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
... |
# -*- coding: utf-8 -*-
import hmac
import hashlib
import base64
"""
unit : utils
descritption: Collection of functions used in all projetcts
author : Alcindo Schleder
version : 1.0.0
package : i-City Identification Plataform
"""
def isnumber(value):
try:
float(valu... |
# -*- coding: utf-8 -*-
'''
:file: app.py
:author: -Farmer
:url: https://blog.farmer233.top
:date: 2021/09/21 12:44:37
'''
import os
import click
from apiflask import APIFlask, abort
from app.config import config
from app.models import TodoList
from app.extensions import db, cors
from app.api.todo impor... |
# Copyright 2017 The TensorFlow 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 applicable ... |
# coding: utf-8
from typing import List, Dict
from .items.data_items import DataItems
from .shared_data import BaseData
from .full_imports import FullImports
from .from_import import FromImport
class Data(BaseData):
from_imports: List[FromImport]
from_imports_typing: List[FromImport]
extends_map: Dict[str... |
from typing import List, Optional
from dagster_fivetran.resources import DEFAULT_POLL_INTERVAL
from dagster_fivetran.utils import generate_materializations
from dagster import AssetKey, AssetsDefinition, Out, Output
from dagster import _check as check
from dagster import multi_asset
from dagster.utils.backcompat impo... |
from __future__ import print_function
import os
import numpy as np
import random
import math
from skimage import io
import torch
import torch.utils.data as data
import torchfile
# from utils.utils import *
from utils.imutils import *
from utils.transforms import *
class W300(data.Dataset):
def __init__(self, ... |
"""
Stolen from https://github.com/django/django/blob/master/tests/utils_tests/test_dateparse.py at
9718fa2e8abe430c3526a9278dd976443d4ae3c6
Changed to:
* use standard pytest layout
* parametrize tests
"""
from datetime import date, datetime, time, timedelta, timezone
import pytest
from pydantic import BaseModel, Va... |
#!/usr/bin/env python
import time
import signal
from gfxhat import touch, lcd, backlight, fonts
from PIL import Image, ImageFont, ImageDraw
print("""hello-world.py
This basic example prints the text "Hello World" in the middle of the LCD
Press any button to see its corresponding LED toggle on/off.
Press Ctrl+C to... |
# Copyright 2018 VMware, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... |
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-2.4, 0.4, 20)
y = x * x + 2 * x + 1
plt.plot(x, y, 'c', linewidth=2.0)
plt.text(-1.5, 1.8, 'y=x^2 + 2*x + 1',
fontsize=14, style='italic')
plt.annotate('minima point', xy=(-1, 0),
xytext=(-1, 0.3), horizontalalignment='ce... |
def retorno():
resp=input('Deseja executar o programa novamente?[s/n] ')
if(resp=='S' or resp=='s'):
verificar()
else:
print('Processo finalizado com sucesso!')
pass
def cabecalho(titulo):
print('-'*30)
print(f'{titulo:^30}')
print('-'*30)
pass
def mensagem_er... |
from flask import Flask, redirect, render_template, url_for
import numpy as np
app = Flask( __name__ )
@app.route( '/home' )
def index():
# retrieve the agent
agent = app.config['AGENT']
print( 'Episode: {}/{}'.format( agent.get_episode(), agent.get_episodes() ) )
print( 'Trial: {}/{}'.format( agent.... |
"""
An RDFLib ConjunctiveGraph is an (unnamed) aggregation of all the named graphs
within a Store. The :meth:`~rdflib.graph.ConjunctiveGraph.get_context`
method can be used to get a particular named graph for use such as to add
triples to, or the default graph can be used
This example shows how to create named graphs ... |
"""
Shared methods for Index subclasses backed by ExtensionArray.
"""
from typing import (
Hashable,
List,
Type,
TypeVar,
Union,
)
import numpy as np
from pandas.compat.numpy import function as nv
from pandas.errors import AbstractMethodError
from pandas.util._decorators import (
cache_readonl... |
def find_single(arr, n):
res = arr[0]
for i in range(1,n):
res = res ^ arr[i]
return res |
# -*- coding: utf-8 -*-
"""Sample controller with all its actions protected."""
from tg import expose, flash, redirect, request
from tg.i18n import lazy_ugettext as l_
from molgears.model import DBSession, Tags, LCompound, LPurity, Names
from molgears.model import Compound, User, Projects
from molgears.model.auth impor... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
import setuptools
setuptools.setup(
name='qspreadsheet',
version='0.1.0',
author='TT-at-GitHub',
author_email='tt3d@start.bg',
license='MIT',
packages=setuptools.find_packages(),
install_requires=[
'numpy>=1.19.0',
'pandas>=1.0.5',
'PySide2>=5.13.0'
],
descri... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libgcrypt(AutotoolsPackage):
"""Libgcrypt is a general purpose cryptographic library based... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 07:52:25 2020
Generate, Plot, and write all data needed for ball drop example 1
@author: granthutchings
"""
#%% Imports
import numpy as np
#import pyDOE # Latin Hypercube
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
fro... |
# Copyright 2020 - 2021 MONAI Consortium
# 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 wri... |
from datetime import timedelta
from pathlib import Path
import click
from overhave.base_settings import LoggingSettings
from overhave.cli.group import overhave
from overhave.transport import OverhaveS3Bucket, OverhaveS3ManagerSettings, S3Manager
from overhave.utils import get_current_time
@overhave.group(short_help... |
from coffea.lookup_tools.lookup_base import lookup_base
import numpy
from copy import deepcopy
class dense_lookup(lookup_base):
def __init__(self, values, dims, feval_dim=None):
super(dense_lookup, self).__init__()
self._dimension = 0
whattype = type(dims)
if whattype == numpy.nda... |
import axp192
import kv
try:
# for m5stack-core2 only
axp = axp192.Axp192()
axp.powerAll()
axp.setLCDBrightness(80) # 设置背光亮度 0~100
except OSError:
print("make sure axp192.py is in libs folder")
def _on_get_url(url):
kv.set('_amp_pyapp_url', url)
execfile('/lib/appOta.py')
def _connect_... |
"""
sphinx.ext.duration
~~~~~~~~~~~~~~~~~~~
Measure durations of Sphinx processing.
:copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from datetime import datetime, timedelta
from itertools import islice
from operator import itemgetter
fr... |
# Generated by Django 3.1.7 on 2021-05-13 03:02
from django.db import migrations, models
import django.utils.timezone
import django_countries.fields
class Migration(migrations.Migration):
dependencies = [
('store', '0001_initial'),
]
operations = [
migrations.AddField(
model... |
import numpy as np
import pandas as pd
import pytest
from dku_timeseries.timeseries_helpers import generate_date_range, get_date_offset
from recipe_config_loading import get_resampling_params
@pytest.fixture
def config():
config = {u'clip_end': 0, u'constant_value': 0, u'extrapolation_method': u'none', u'shift':... |
import torch.nn as nn
class Generator(nn.Module):
def __init__(self, img_size=32):
super(Generator, self).__init__()
# TODO: update to proper image size
self.init_size = img_size // 4
self.l1 = nn.Sequential(nn.Linear(10, 128 * self.init_size ** 2))
self.conv_blocks = nn.... |
# voom_mode_org.py
# Last Modified: 2013-10-31
# VOoM -- Vim two-pane outliner, plugin for Python-enabled Vim 7.x
# Website: http://www.vim.org/scripts/script.php?script_id=2657
# Author: Vlad Irnov (vlad DOT irnov AT gmail DOT com)
# License: CC0, see http://creativecommons.org/publicdomain/zero/1.0/
"""
VOoM markup ... |
Experiment(description='SE extrapolation experiment',
data_dir='../data/tsdlr_9010/',
max_depth=1,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=2,
jitter_sd=0.1,
max_jobs=1000... |
from os import listdir, getcwd
from os.path import isfile, join
from math import sin, cos
from setting_utils import timeLimit, heightLimit, input_stream
files = [f for f in listdir(join(getcwd(), 'uploads')) if isfile(join(getcwd(), 'uploads', f))]
files = [f for f in files if f.endswith(".txt")]
czml =(
'var heigh... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A simple Python module for validating BagIt profiles. See
https://github.com/bagit-profiles/bagit-profiles
for more information.
This module is intended for use with https://github.com/edsu/bagit but does not extend it.
Usage:
import bagit
import bagit_profile
# I... |
# -*- coding: utf-8 -*-
from asyncy.Exceptions import StoryscriptError
from asyncy.Sentry import Sentry
from raven import Client
def test_init(patch):
# noinspection PyTypeChecker
Sentry.init(None, None) # No-op.
patch.init(Client)
Sentry.init('sentry_dsn', 'release_ver')
Client.__init__.assert_... |
from constants import *
from gateway_protocol import Gateway
from api import DiscordAPI
import bot_config as config
import logging as log
log.basicConfig(encoding='utf-8', level=log.DEBUG)
class Bot(object):
def __init__(self, token):
self.g = Gateway(token)
self.api = DiscordAPI(token)
de... |
# script to upload a file to zenodo sandbox via api
# seperate sandbox- and real-zenodo accounts and ACCESS_TOKENs each need to be created
# to adapt this script to real-zenodo (from sandbox implementation):
# update urls to zenodo.org from sandbox.zenodo.org
# update SANDBOX_TOKEN to a ACCESS_TOKEN from real-... |
# Copyright 1999-2018 Alibaba Group Holding 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 applicable law or a... |
"""TODO(wikitext): Add a description here."""
import os
import datasets
_CITATION = """\
@misc{merity2016pointer,
title={Pointer Sentinel Mixture Models},
author={Stephen Merity and Caiming Xiong and James Bradbury and Richard Socher},
year={2016},
eprint={1609.07843},
archivePrefix={... |
"""
PixelVAE: A Latent Variable Model for Natural Images
Ishaan Gulrajani, Kundan Kumar, Faruk Ahmed, Adrien Ali Taiga, Francesco Visin, David Vazquez, Aaron Courville
"""
import os, sys
sys.path.append(os.getcwd())
N_GPUS = 2
import random
import tflib as lib
import tflib.sampling_loop_cifar_filter_3
import tflib.o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.