content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import json
import requests
import base64
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Hash import SHA
#from Crypto import Random
public_key = RSA.importKey(open('/tmp/duetpublickey.pem').read())
message = "1,27"
# default hash Algorithm is SHA1, mask generation func... | python |
#!/bin/python
import sys
import math
def _pal2(n):
h = n / 1000 + 1
while True:
p = str(h)
p += p[2::-1]
yield int(p)
h -= 1
def ifact(i):
f1 = int(math.sqrt(float(i))) + 1
while f1 > 99:
f2,r = divmod(i,f1)
if f2 > 999:
return None
... | python |
#
# -*- coding: utf-8 -*-
#
# @Author: Arrack
# @Date: 2020-05-25 17:25:12
# @Last modified by: Arrack
# @Last Modified time: 2020-06-08 15:27:48
#
from wtforms import BooleanField
from wtforms import Form
from wtforms import PasswordField
from wtforms import StringField
from wtforms import SubmitField
from wtform... | python |
numero1 = float(input("primeiro numero: "))
numero2 = float(input("segundo numero: "))
numero3 = float(input("terceiro numero: "))
numero4 = float(input("quarto numero: "))
numero5 = float(input("quinto numero: "))
lista = [numero1,numero2,numero3,numero4,numero5]
soma = sum(lista)
print (soma)
| python |
"""
Python definitions used to help with plotting routines.
*Methods Overview*
-> geo_scatter(): Geographical scatter plot.
"""
import matplotlib.pyplot as plt
from warnings import warn
from .logging_util import warn
import numpy as np
def r2_lin(x, y, fit):
"""For calculating r-squared of a linear fit. Fit... | python |
from direct.directnotify import DirectNotifyGlobal
from src.connection.protocol import *
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.PyDatagramIterator import PyDatagramIterator
from src.messagedirector.ChannelWatcher import ChannelWatcher
class MDParticipant(ChannelWatcher):
notif... | python |
# NOTE THAT 'data' IN THIS CODE IS TRANSPOSE, COMPARED WITH THE MANIFOLDER CODE
# data is shaped [13848,8] here ... ogm ...
# loads in data, dimlist, n_channels, npts, x
# file_location_in_data
# file_location_out_data
import numpy as np
# Coweb, if not installed, can 'pip install -U concept_formation'
# https://git... | python |
from django.conf import settings
from django.core.mail import send_mail
from chatbot.models import Notification
class NotificationProcessor:
def __init__(self, notification: Notification):
self.notification = notification
self.notification_map = {
'welcome': {
'subje... | python |
from django.shortcuts import render
from django.views.generic import (
ListView,
)
from .models import (
Event,
EventPhoto,
)
class AllEventsView(ListView):
model = Event
queryset = Event.objects.all().filter(status = True)
template_name = "event/all_events.html"
context_object_name = "cont... | python |
from tests.utils.owtftest import OWTFCliTestCase
class OWTFCliExceptTest(OWTFCliTestCase):
categories = ['cli']
def test_except(self):
"""Run OWTF web plugins except one."""
self.run_owtf('-s', '-g', 'web', '-e', 'OWTF-WVS-006', "%s://%s:%s" % (self.PROTOCOL, self.IP, self.PORT))
sel... | python |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size': 14})
mpl.rc('text', usetex=True)
#V1 = np.genfromtxt('Heat.txt')[::-1]
V2 = np.genfromtxt('Heat_b25.txt')[::-1]
'''
N = len(V1)
plt.figure(figsize=(7,7))
plt.title(r'... | python |
import time
import json
from random import choice, randrange, shuffle
class Citation:
"""
Notre objet Citation est composé de :
- Le contenu (un texte càd str)
- Un auteur (le nom de l'auteur càd str)
- Une origine (titre de l'oeuvre dont elle est extraitre càd str)
- Année de publication càd ... | python |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe, json
no_cache = True
def get_context(context):
token = frappe.local.form_dict.token
if token:
paypal_express_payment = frappe.get_doc("Paypal Express Payment", token)
... | python |
from tensorflow.keras import layers
from tensorflow.keras.layers import TimeDistributed, LayerNormalization
from tensorflow.keras.models import Model
from tensorflow.keras.regularizers import l2
import kapre
from kapre.composed import get_melspectrogram_layer
import tensorflow as tf
import os
def Conv1D(N_CLASSES=10,... | python |
"""Stack Analysis Load test."""
import os
import datetime
import time
from requests_futures.sessions import FuturesSession
start_time = datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S %Z %Y")
print("TEST START TIME: {}".format(start_time))
three_scale_token = os.getenv('THREE_SCALE_PREVIEW_USER_KEY', '')
api... | python |
from flask import render_template, flash
from flask_login import login_required
from mcadmin.config import CONFIG, _F_USE_JAR
from mcadmin.forms.config.version_form import SetVersionForm
from mcadmin.io.files.server_list import SERVER_LIST
from mcadmin.io.server.server import SERVER
from mcadmin.main import app
@app... | python |
import os
import math
import torch
import pickle
import argparse
# Data
from data.data import add_data_args
# Model
from model.model import get_model, get_model_id
from model.baseline import get_baseline
from survae.distributions import DataParallelDistribution
# Optim
from optim import get_optim, get_optim_id, add_... | python |
"""
Copyright 2020 Hype3808
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, softw... | python |
import os
from setuptools import setup
this_dir = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(this_dir, "README.rst"), "r") as f:
long_description = f.read()
setup(
name="flake8parser",
description=(
"A public python API for flake8 created by parsing the command line output.... | python |
import typing
import unittest
from m3c import mwb
from m3c import prefill
List = typing.List
class TestPrefill(unittest.TestCase):
def setUp(self):
self.olddb = [
prefill.db.add_organization,
prefill.db.find_organizations,
prefill.db.get_organization,
pre... | python |
from abc import ABC, abstractmethod
from stateful_simulator.datatypes.DataTypes import FeatureVector
from typing import List
class StatelessModel(ABC):
@abstractmethod
def predict(self, fv: FeatureVector) -> float:
pass
@abstractmethod
def train(self, fvs: List[FeatureVector]):
pass | python |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from turtle import *
import os
import shutil
class Recorder(object):
def __init__(self, func, fps=30):
self.func = func
self.fps = fps
def __enter__(self):
self.record()
... | python |
import unittest
from unittest import mock
from flumine.events import events
class BaseEventTest(unittest.TestCase):
def setUp(self) -> None:
self.mock_event = mock.Mock()
self.base_event = events.BaseEvent(self.mock_event)
def test_init(self):
mock_event = mock.Mock()
base_ev... | python |
import json
import requests
class Gen3FileError(Exception):
pass
class Gen3File:
"""For interacting with Gen3 file management features.
A class for interacting with the Gen3 file download services.
Supports getting presigned urls right now.
Args:
endpoint (str): The URL of the data com... | python |
"""
setup.py: Install IsCAn
"""
import os
import sys
import re
import subprocess
from os.path import join as pjoin
from glob import glob
import setuptools
from distutils.extension import Extension
from distutils.core import setup
from Cython.Distutils import build_ext
import numpy
# --------------------------------... | python |
from setuptools import find_packages, setup
setup(
name="typer", packages=find_packages(),
)
| python |
from textwrap import dedent
endc = "\033[0m"
bcolors = dict(
blue="\033[94m",
green="\033[92m",
orange="\033[93m",
red="\033[91m",
bold="\033[1m",
underline="\033[4m",
)
def _color_message(msg, style):
return bcolors[style] + msg + endc
def _message_box(msg, color="green", border="=" * ... | python |
import sys
import subprocess
import gzip
from tqdm import tqdm
def get_lines_count(file_path):
if file_path[-3:] == ".gz":
ps = subprocess.Popen(
f"gzip -cd {file_path} | wc -l", shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return int(ps.communicate()[0])
else:
... | python |
# convert ERAiterim data from (Claudia Wekerle's) netcdf files to ieee-be
# compute specific humidity from dew point temperature
# unfortunately precipitation and downward radiation are only available
# as daily averages, I don't know why
import numpy as np
import matplotlib.pyplot as plt
from netCDF4 import Dataset
i... | python |
"""
Conversion functions between corresponding data structures.
"""
import json
import logging
from collections import Hashable, OrderedDict # pylint: disable=E0611,no-name-in-module # moved to .abc in Python 3
from copy import deepcopy
from tempfile import TemporaryDirectory
from typing import TYPE_CHECKING
from ur... | python |
# This source code is part of the Biotite package and is distributed
# under the 3-Clause BSD License. Please see 'LICENSE.rst' for further
# information.
__name__ = "biotite.sequence.graphics"
__author__ = "Patrick Kunzmann"
__all__ = ["plot_dendrogram"]
import numpy as np
def plot_dendrogram(axes, tree, orientatio... | python |
import boto3
from trp import Document
# Document
s3BucketName = "ki-textract-demo-docs"
documentName = "expense.png"
# Amazon Textract client
textract = boto3.client('textract')
# Call Amazon Textract
response = textract.analyze_document(
Document={
'S3Object': {
'Bucket': s3BucketName,
... | python |
from itertools import chain
import attr
@attr.s(slots=True, cmp=False)
class KmerDataCollection(object):
_kmers_data = attr.ib()
num_colors = attr.ib(init=False)
_coverage = attr.ib(None)
_edges = attr.ib(None)
raw_kmer = attr.ib(None)
def __attrs_post_init__(self):
assert len(self._... | python |
__author__ = "Frédéric BISSON"
__copyright__ = "Copyright 2022, Frédéric BISSON"
__credits__ = ["Frédéric BISSON"]
__license__ = "mit"
__maintainer__ = "Frédéric BISSON"
__email__ = "zigazou@protonmail.com"
from dietpdf.info.decode_objstm import decode_objstm
def create_stream():
return b"""11 0 12 54 13 107
<</... | python |
import json
import os
from unittest.mock import patch
from django.conf import settings
from django.utils import timezone as djangotime
from model_bakery import baker
from autotasks.models import AutomatedTask
from tacticalrmm.test import TacticalTestCase
class TestAPIv3(TacticalTestCase):
def setUp(self):
... | python |
"""
Copyright 2020 Vitaliy Zarubin
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, softwar... | 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 "License"); you may not use ... | python |
class dtype:
def __eq__(self, other):
return self.__name__ == other.__name__
class complex128(dtype):
precedence = 10
class complex64(dtype):
precedence = 9
class float64(dtype):
precedence = 8
class float32(dtype):
precedence = 7
class float16(dtype):
precedence = 6
# class ... | python |
"""
Global mail object used to send notification emails.
"""
from flask_mail import Mail, Message
from flask import current_app
mail = Mail()
def send_mail(email, output):
"""sends email"""
header = "Your analysis is ready"
content = '''<div style='font-size:14px;'>\
Your requested analysis is r... | python |
import argparse
import sys
from typing import Callable
from typing import List
from typing import Optional
from . import audit
from . import baseline
from . import filters
from . import plugins
from . import scan
from ...settings import get_settings
from .common import initialize_plugin_settings
from detect_secrets.__... | python |
# Copyright 2020 Huawei Technologies Co., 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 agreed to... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 9 02:35:02 2018
@author: elvex
"""
"""Boite à outils de manipulation des base de données de tweets. """
#import json
import pandas as pd
import txt_analysis as TA
from math import log10
from glob import glob
from os.path import abspath
from re im... | python |
from jmetal.algorithm.singleobjective.simulated_annealing import SimulatedAnnealing
from jmetal.operator import PolynomialMutation
from jmetal.problem.bbob import bbob
from jmetal.util.observer import ProgressBarObserver
from jmetal.util.termination_criterion import StoppingByEvaluations
if __name__ == '__main__':
... | python |
"""
Packaging setup for ledcontroller
"""
# pylint: disable=line-too-long
import os.path
from codecs import open as codecs_open
from setuptools import setup
with codecs_open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.rst'), encoding='utf-8') as f:
LONG_DESCRIPTION = f.read()
setup(
na... | python |
'''
实验名称:RTC实时时钟
版本:v1.0
日期:2020.12
作者:01Studio
说明:在LCD上显示时间
社区:www.01studio.org
'''
#导入相关模块
import pyb
from tftlcd import LCD43M
#定义常用颜色
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
WHITE = (255,255,255)
########################
# 构建4.3寸LCD对象并初始化
########################
d = LCD43M(portrait=1)... | python |
from __future__ import division, absolute_import, print_function
from .jdx import jdx_reader, jdx_file_reader, JdxFile
__all__ = ["jdx"]
| python |
# -*- coding: utf-8 -*-
# Copyright (c) 2015, shakeel vaim and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('Add New Properties')
class TestAddNewProperties(unittest.TestCase):
pass
| python |
from datetime import datetime
from city_scrapers_core.spiders import CityScrapersSpider
from dateutil.parser import parse as dateparse
from city_scrapers.mixins.wayne_commission import WayneCommissionMixin
class WayneBuildingAuthoritySpider(WayneCommissionMixin, CityScrapersSpider):
name = "wayne_building_autho... | python |
"""Base segment definitions.
Here we define:
- BaseSegment. This is the root class for all segments, and is
designed to hold other subsegments.
- RawSegment. This is designed to be the root segment, without
any children, and the output of the lexer.
- UnparsableSegment. A special wrapper to indicate that th... | python |
"""客户端查询排行榜"""
from upload import uploading
def rank():
pass | python |
#!/usr/bin/env python
#pylint: disable=C0103
"""
This module provides business object class to interact with
DATASET_ACCESS_TYPES table.
"""
from WMCore.DAOFactory import DAOFactory
from dbs.utils.dbsExceptionHandler import dbsExceptionHandler
class DBSDatasetAccessType:
"""
DatasetAccessType business object ... | python |
# Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
# examples/python/ReconstructionSystem/sensors/realsense_recorder.py
# pyrealsense2 is required.
# Please see instructions in https://github.com/IntelRealSense/librealsense/tree/master/wrappers/python
import pyreal... | python |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^job-meta/',views.job_meta, name='job_meta'),
url(r'^job-success-failure',views.job_success_failure_ratio, name='job_success_failure_ratio'),
url(r'^$',views.dashboard, name='dashboard'),
] | python |
# Copyright 2008-2018 Univa Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | python |
import tweepy # To consume Twitter's API
import pandas as pd # To handle data
import numpy as np # For number computing
from textblob import TextBlob # for sentimental
import re
# For plotting and visualization:
from IPython.display import display
# for display use only import matplotlib.pyplot as... | python |
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Table
from sqlalchemy.orm import relationship, backref
from models import db_base as base
import os
import json
__author__ = "zadjii"
class Issue(base):
__tablename__ = "issue"
"""
Represents a single issue
"""
... | python |
port = 8888
logging = 'info'
log_file_prefix = "tivid-error.log"
redis_host = 'localhost'
redis_port = 6379
redis_db = 0
java_source = "http://www.importnew.com/all-posts"
python_source = "http://python.jobbole.com/all-posts/"
| python |
from threading import Thread
def async_func(f):
def wrapper(*args, **kwargs):
thr = Thread(target = f, args = args, kwargs = kwargs)
thr.start()
return wrapper | python |
from __future__ import unicode_literals
from django.apps import AppConfig
class SequencerConfig(AppConfig):
name = 'sequencer'
| python |
import os
import sys
import datetime
from glob import iglob
from skimage import io
import cv2
import tensorflow as tf
import numpy as np
import utils as ut
import training as tr
class VAE2predict:
def __init__(self, use_sampling=False):
self.use_sampling = use_sampling
self._build_model()
def... | python |
from django import template
register = template.Library()
from urlparse import urlparse
def domain_only(full_url):
parsed = urlparse(full_url)
return parsed.netloc.lstrip("www.")
register.filter('domain_only', domain_only) | python |
print('spam = 40')
spam = 40
print('eggs = 2')
eggs = 2
print('spam + eggs')
a = spam + eggs
print(a)
# Variable naming convention
# small then capital or sparated by _
# varA
| python |
#
# This file is part of m.css.
#
# Copyright © 2017, 2018, 2019 Vladimír Vondruš <mosra@centrum.cz>
#
# 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... | python |
from django.apps import AppConfig
class MagiclinkConfig(AppConfig):
name = 'magiclink'
| python |
from flask import Flask
import os
app = Flask(__name__)
healthy = True
@app.route('/')
def hello():
global healthy
if healthy:
return f"Hello from {os.environ['HOST']}!\n"
else:
return "Unhealthy", 503
@app.route('/healthy')
def healthy():
global healthy
healthy = True
retur... | python |
'''
Integration tests for states.
'''
import unittest as ut
import numpy as np
import dynamite_test_runner as dtr
from dynamite.states import State
class RandomSeed(dtr.DynamiteTestCase):
def test_generation(self):
'''
Make sure that different processors get the same random seed.
'''
... | python |
import requests
import os
from dotenv import load_dotenv
from datetime import datetime
load_dotenv()
def send_to_slack(msg: str) -> None:
URL = os.getenv("SLACK_WEBHOOK")
headers = {"content-type": "application/json"}
payload = {
"attachments": [
{
"fallback": "Plain-t... | python |
from flask import abort, request
from . import app
from .helpers import render_error_template
import logging
# Catch all route for everything not matched elsewhere
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path): # pragma: no cover
abort(404, "Not Found")
@app.errorhandler... | python |
'''
Created on Jun 21, 2016
@author: MarcoXZh
'''
import sys, re
import xml.etree.ElementTree as ET
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
from PIL import Image
from ImageComparison import calcSSIM
... | python |
#!/usr/bin/env python3
# Xilinx CoolRunner II XC2C64A characteristics
bits_of_address = 7
bits_of_data = 274
bytes_of_data = (bits_of_data + 7) // 8
bits_in_program_row = bits_of_address + bits_of_data
address_sequence = (0x00, 0x40, 0x60, 0x20, 0x30, 0x70, 0x50, 0x10, 0x18, 0x58, 0x78, 0x38, 0x28, 0x68, 0x48, 0x08, ... | python |
# Copyright 2020 reinforced_scinet (https://github.com/hendrikpn/reinforced_scinet)
#
# 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.... | python |
#!/usr/bin/env python
import os
import sys
from chromedriver_py import binary_path
print(
"""This command will fail if you have not run the setup.py script AND "source environment/env.sh" first.\n\n\nIt is installing a headless chrome web browser driver to allow making an image out of the big demo script session... | python |
import unittest
from users import User
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the contact class behaviours.
Args:
unittest.TestUser: TestUser class that helps in creating test cases
'''
# Items up here .......
def setUp(self):
'''
... | python |
import random
import time
import os
import discord
import triggers
import data
import cmd
import tools
################################################################################
lurker_data = dict()
lurker_data['emoji'] = '👀'
lurker_data['min_chance'] = 1
lurker_data['max_chance'] = 10
data.NewGuildEnvAdd('l... | python |
from enum import auto
from mstrio.utils.enum_helper import AutoName
class RefreshPolicy(AutoName):
ADD = auto()
DELETE = auto()
UPDATE = auto()
UPSERT = auto()
REPLACE = auto()
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
from __future__ import unicode_literals, division, absolute_import, print_function
# to work around tk_chooseDirectory not properly returning unicode paths on Windows
# need to use a dialog that can be hacked up to actually... | python |
from django.apps import AppConfig
class EsgConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'esg'
| python |
from .base import * # noqa: F403,F401
DEBUG = True
INSTALLED_APPS += [ # noqa ignore=F405
'debug_toolbar',
]
MIDDLEWARE += [ # noqa ignore=F405
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ALLOWED_HOSTS = [
'0.0.0.0',
'127.0.0.1',
'art-backend.herokuapp.com'
]
INTERNAL_IPS = [
'0... | python |
# Version 3.1; Erik Husby; Polar Geospatial Center, University of Minnesota; 2019
from __future__ import division
import math
import os
import sys
import traceback
from warnings import warn
import numpy as np
from osgeo import gdal_array, gdalconst
from osgeo import gdal, ogr, osr
gdal.UseExceptions()
class Rast... | python |
import random
print('====================== \033[35mBEM-VINDO AO JOGO DA ADIVINHAÇÃO\033[m ======================')
print('Tente adivinhar o número entre 0 e 10 que eu estou pensando')
computador = random.randint(0, 10)
palpites = 0
acertou = False
while not acertou:
jogador = int(input('Qual é a sua tentativa? '))... | python |
# -*- coding: utf-8 -*-
# Imports
import json
import discord
import random
import datetime
import asyncio
client = discord.Client()
# Readiness Indicator
@client.event
async def on_ready():
print("The bot is ready!")
await client.change_presence(game=discord.Game(name="roulette with your money"))
# Remind... | python |
import re
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from markdown import markdown
register = template.Library()
@register.filter("markdown")
@stringfilter
def markdown_filter(value):
return mark_safe(markdown(value))
@regi... | python |
"""
This file is part of Advent of Code 2019.
Coded by: Samuel Michaels (samuel.michaels@protonmail.com)
11 December 2019
NO COPYRIGHT
This work is dedicated to the public domain. All rights have been
waived worldwide under copyright law, including all related and
neighboring rights, to the extent allowed by law.
Y... | python |
# -*- coding: utf-8 -*-
from flask import Flask
from flask_restful import Resource, Api
from controller.TestSuit import TestSuit
from model.TestSuit import db as TestSuitDB
app = Flask(__name__)
api = Api(app)
api.add_resource(TestSuit, '/testsuit')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.sqlit... | python |
# Compact version
# ---------------
rule = (('0'*8 + bin(30)[2:])[-8:])[::-1]
cells = list('0'*40 + '1' + '0'*40)
for epoch in range(40):
print(''.join(cells).replace("0"," ").replace("1","█"))
cells = [cells[0]] + [rule[eval('0b' + cells[i-1]+cells[i]+cells[i+1])]
for i in range(1,len... | python |
import io
import os
from google.cloud import vision
from google.cloud.vision import types
from google.protobuf.json_format import MessageToJson
class GoogleVisionApi:
def __init__(self):
# Instantiates a client
self.client = vision.ImageAnnotatorClient()
self.requestsCache = {}
def request(self, imagePath):... | python |
from os import getenv, \
path
class Config(object):
API_KEY = getenv('API_KEY')
DEBUG = getenv('DEBUG', False)
SQLALCHEMY_DATABASE_URI = getenv('DATABASE_URL', 'sqlite:///' + path.dirname(__file__) + '/app/app.db').replace('mysql2:', 'mysql:')
SQLALCHEMY_ECHO = getenv('SQLALCHEMY_ECHO', ... | python |
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='main', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--dataset', default='mag', choices=['mag', 'amazon'])
parser.add_argument('--num_motif', default=50, type=int)
parser.add_argument('--eta', default=2.0, t... | python |
from infi.pyutils.lazy import cached_method
from ..inquiry import InquiryException
from logging import getLogger
logger = getLogger(__name__)
class InfiniBoxVolumeMixin(object):
@cached_method
def _is_volume_mapped(self):
"""In race condition between a rescan and volume unmap operation, the device may... | python |
import discord
from discord.ext import commands
import random, string
from asyncio import sleep
class Fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def ascii(self, ctx, amount: int=1):
await ctx.message.delete()
for i in range(amount):
text=''
for i in... | python |
import requests
import lib.RModule as rmodule
import lib.RAudiostream as raudiostream
import lib.RAtmosphere as ratmosphere
import lib.RMonitoring as rmonitoring
class Project:
project_id = None
switchboards = []
neopixels = []
audiostream = None
monitoring = None
def __init__(self, projec... | python |
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
from sklearn import ensemble, svm,datasets
import brica1
# Randomforest Component Definition
class RandomForestClassifierComponent(brica1.Component):
def __init__(self, n_in):
super(RandomForestClassifierComponent, self).__init__()
... | python |
""" Parent class to inception models """
import tensorflow as tf
from . import TFModel
from .layers import conv_block
class Inception(TFModel):
""" The base class for all inception models
**Configuration**
body : dict
layout : str
a sequence of blocks in the network:
- ... | python |
# Generated by Django 3.0.4 on 2020-03-20 04:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('places', '0024_submittedplace'),
]
operations = [
migrations.RemoveField(
model_name='submittedplace',
name='website... | python |
"""Tests for claim_line model and the associated functions."""
from claims_to_quality.analyzer.models import claim_line
def test_str_method():
"""Test that claim lines are represented in a readable format."""
line = claim_line.ClaimLine(
{'clm_line_hcpcs_cd': 'code', 'mdfr_cds': ['GQ'], 'clm_pos_code'... | python |
#!/usr/bin/env python3
"""
Script to preprocess OCR output for Tesseract
Usage:
python3 preprocess.py /path/to/input/dir \
/path/to/output/dir
"""
from glob import glob
import os
import shutil
import sys
import cv2
import numpy as np
def preprocess(img):
"""Takes a given image and retu... | python |
from .davis import vis
| python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CERN.
# Copyright (C) 2019 Northwestern University.
#
# Invenio App RDM is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Invenio Records Permissions API."""
from elasticsearch_dsl.query... | python |
#! python3
# aoc_13.py
# Advent of code:
# https://adventofcode.com/2021/day/13
# https://adventofcode.com/2021/day/13#part2
#
def part_one(input) -> int:
nmap =[]
ymap = []
coords = []
with open(input, 'r') as inp:
lines = inp.readlines()
for line in lines:
line.strip()
... | python |
# Copyright (C) 2018 Shriram Bhat
#
# 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,... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.