content
stringlengths
5
1.05M
salario = float(input("informe o salario:")) aumento = float(salario*(15/100)) print("o aumento sera de R${:.2f}".format(salario+aumento))
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT # # 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...
# © 2019 KidsCanCode LLC / All rights reserved. # import setting varibles and pygame import pygame as pg from settings import * import time # player class class Player(pg.sprite.Sprite): def __init__(self, game, x, y): self.groups = game.all_sprites pg.sprite.Sprite.__init__(self, self.groups) ...
# -*- coding: utf-8 -*- """ Created on Apr 1, 2015 Service units to change the control flow. Copyright (c) 2013 Samsung Electronics Co., Ltd. """ from zope.interface import implementer from veles.distributable import IDistributable, TriviallyDistributable from veles.units import TrivialUnit, Unit, IUnit class Re...
"""Using CamelCase on these to match with DynamoDb""" from enum import Enum from typing import Optional, List from pydantic import BaseModel class Tag(BaseModel): Key: str Value: str class KeyType(str, Enum): hash = "HASH" range = "RANGE" class ProjectionType(str, Enum): all = "ALL" keys_o...
import matplotlib.mlab as mlab import matplotlib.pyplot as plt n = int(input()) infected = [] recovered = [] for i in range(n): s = input() count1 = 0 count2 = 0 for c in s: if c == '*': count1 += 1 else: count2 += 1 infected.append(count1) recovered.append(count2 + count1) plt.axis([0, n + 1, 0, 60]) pl...
import os from django import template from django.utils.html import format_html from django.conf import settings from template_addons.assets_helper import AssetsHelper register = template.Library() assets_uri = os.getenv('ASSETS_DEV_SERVER', None) public_asset = os.getenv('PUBLIC_ASSET', None) env = os.getenv('ENV...
# Generated by Django 2.1.3 on 2018-11-28 11:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('learning_logs', '0002_entry'), ] operations = [ migrations.CreateModel( name='Ghomeentry', fields=[ ...
# MIT LICENCE Taguar258 2020 # Please read the Licence to know your permissions. argvexit = False try: import socket import os import sys import time from threading import Thread import urllib2 import re import redis import pickle import wget import nmap try: imp...
import os import time from django.http import HttpResponse def index(request): return HttpResponse('<br>'.join('%s: %s' % (k, v) for k, v in os.environ.items())) def health(request): return HttpResponse('OK ' + os.environ.get('HOSTNAME', 'unknown')) def cpu_usage(request): start = time.time() whi...
# https://en.wikipedia.org/wiki/Caesar_cipher # int 0..25 KEY = 5 TEXT = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras nibh nisl, suscipit sed erat at, vulputate porttitor dolor. Etiam auctor augue id quam tempus placerat. Curabitur interdum ullamcorper dapibus. Fusce mattis condimentum mauris, ut co...
import os import time import datetime from scraping_manager.automate import Web_scraping import logging from logger import get_logger logger = get_logger(__name__) logger.setLevel(logging.INFO) class SportScraper (): def __init__ (self): """Contructor of class. Start browser""" # Class vars ...
""" This package contains modules to quickly set up a Panda environment for quick prototyping in the interactive Python shell. Merely importing one of these modules will create a :class:`.ShowBase` instance, opening a graphical window and setting up the scene graph. The most commonly used module from this package is ...
# Reference: http://python-packaging.readthedocs.io/en/latest/dependencies.html import distutils.command.install as orig from setuptools import setup, find_packages from setuptools.command.install import install import subprocess import os import io import sys import contextlib class InvokingShScript(install): ""...
import streamlit as st import requests # import pandas as pd API_URL = "http://127.0.0.1:80" st.title("Search for local Corona information") "Enter your location and we will show you local hotlines, websites, test sites, health departments, and restrictions." place_query = st.text_input("City, Neighborhood, State, ...
from django import forms from .models import SelectDateTime class SelectDateTimeForm(forms.Form): date = forms.DateField( input_formats=['%d.%m.%Y'], widget=forms.DateInput(attrs={ 'class': 'form-control datetimepicker-input', 'data-target': '#datetimepicker1' }) ...
from keras.models import Sequential from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate from keras.models import Model from keras.layers.normalization import BatchNormalization from keras.layers.pooling import MaxPooling2D, AveragePooling2D from keras.layers.merge import Concatenate from kera...
from importlib import import_module from dynaconf import FlaskDynaconf def load_libs(app): for lib in app.config.get("EXTENSIONS"): modulo = import_module(lib) modulo.init_app(app) def init_app(app): FlaskDynaconf(app)
from datetime import datetime import os from pathlib import Path from typing import Any, Dict try: import wandb except: pass import yaml def load_yaml(file_path: Path) -> Dict[str, Any]: with open(file_path, "r") as file: loaded_yaml = yaml.load(file, Loader=yaml.FullLoader) return loaded_ya...
from django.shortcuts import render_to_response, render from django.template import RequestContext from django.http import HttpResponse from ressources.models import Ressource # Create your views here. def que_faire(request): return render(request, 'que_faire.html') def que_faire_detail(request, sujet): if(sujet=...
""" remotes.py The client and web server needed to control a car remotely. """ import time from datetime import datetime import json import io import os import copy import math from threading import Thread import numpy as np import requests import tornado.ioloop import tornado.web import tornado.gen from PIL impor...
# -*- coding: utf-8 -*- import os from setuptools import setup, find_packages, Extension install_reqs = [ 'Pillow', 'matplotlib', 'importlib-resources', 'fabio@git+https://github.com/joelvbernier/fabio.git@master', 'pyyaml', 'hexrd' ] # This is a hack to get around the fact that pyside2 on con...
#Code adapated from https://github.com/andrewbeattycourseware/dataRepresenation2020 import mysql.connector from mysql.connector import cursor import config as config class StockDAO: db = "" #variable stores database connection,ok to leave blank def __init__(self): self.db = mysql.connector.connect( ...
################################################################################ # Copyright 2020 Advanced Micro Devices, Inc. All rights reserved. # # 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 So...
''' Based on https://github.com/diegoalejogm/gans ''' from torchvision import transforms, datasets def get_cifar_data(cfg): compose = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) out_dir = '{}/cifar'.format(cfg.data_dir) trai...
import asyncio import random MAX_INFLIGHT_REQUESTS = 2 api_lock = asyncio.BoundedSemaphore(MAX_INFLIGHT_REQUESTS) async def locked_my_call(url): async with api_lock: return await my_call(url) async def my_call(url): print("Entering call", url) await asyncio.sleep(random.randint(50, 1000) / 1000) print("E...
import abc from typing import Union from ..master.master import Master, _Shards from ..master.client import MasterClient from ..shard.client import ShardClient from ..core.client import ClientError from ..core.typing import Key, Doc, Hash class AbstractResult(abc.ABC): @abc.abstractmethod def result(self) ->...
""" Definition of urls for proearthengine. """ from django.conf.urls.static import static from datetime import datetime from django.conf.urls import url from django.contrib.staticfiles.urls import staticfiles_urlpatterns import django.contrib.auth.views from django.conf import settings import app.forms import app.view...
# to use this install package # pip install PyGithub from github import Github import requests # remove the minus sign from the key # you can add this to your code just don't commit it g = Github("eb593f066ef0b1d2c797b5fc0cd4b27afa139b8f") #for repo in g.get_user().get_repos(): # print(repo.name) #repo.edit(ha...
import requests import bs4 as bs url = "https://nhentai.net/" search_url = "https://nhentai.net/search/?q=" def get_codes(doujins): codes = [] for doujin in doujins: soup2 = bs.BeautifulSoup(str(doujin), 'lxml') code = soup2.find('a', href=True) code = code['href'] if code is N...
# Name: Ali Raza Zaidi # Date: Jan 8 2021 # Purpose: Use Models created by modeler.py which exist in JOBLIB format and use them to predict player contracts based # on given stats # Import Statements import joblib # Main Class - Wanted to incorporate OOP Principles to make program more elegant and easier to use clas...
# Copyright 2018 The Bazel 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 la...
""" PyPages ------- Do pagination in python like a charm. Links ````` * `documentation <https://github.com/fengsp/pypages>`_ * `development version <http://github.com/fengsp/pypages/zipball/master#egg=pypages-dev>`_ """ from setuptools import setup setup( name='PyPages', version='0.1', url='https://...
# Generated by Django 2.1.4 on 2019-02-28 18:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('restaurant', '0002_food_vat'), ] operations = [ migrations.AlterField( model_name='food', name='vat', ...
import pytest from tests.utils import compileScenic, sampleEgoFrom # Built-in functions def test_max_min(): ego = sampleEgoFrom(""" a = Range(0, 1) b = Range(0, 1) ego = Object with foo max(a, b), with bar min(a, b) """) assert ego.foo >= ego.bar ego = sampleEgoFrom('ego = Ob...
from io import BytesIO import aiohttp from aiogram import Bot, types async def upload_document( bot, doc: types.photo_size.PhotoSize or types.Document ) -> str: with await doc.download(BytesIO()) as file: form = aiohttp.FormData() form.add_field( name="file", value=fi...
from src.misdemeanor_recordmachine import State, StartState, ScreeningState, ZippingState, FinishedState, MisdemeanorRecordMachine from src.charge import Charge from src.defendant import Defendant import pytest from datetime import date, datetime, timedelta import typing @pytest.fixture def level1_record(): '''Thi...
"""Test fixes for CanESM5-CanOE.""" from esmvalcore.cmor._fixes.cmip6.canesm5 import Co2 as BaseCo2 from esmvalcore.cmor._fixes.cmip6.canesm5 import Gpp as BaseGpp from esmvalcore.cmor._fixes.cmip6.canesm5_canoe import Co2, Gpp from esmvalcore.cmor._fixes.fix import Fix def test_get_co2_fix(): """Test getting of ...
from modeltranslation.translator import translator, TranslationOptions from .models import Province, Region class ProvinceTranslationOptions(TranslationOptions): fields = ('name', ) class RegionTranslationOptions(TranslationOptions): fields = ('name', ) translator.register(Province, ProvinceTranslationOp...
from django.shortcuts import render from django.utils.safestring import mark_safe from portfolio.models import Chess_board import json def home(request): if 'alexcarter' in request.COOKIES: return render(request, 'home.html', {}) else: board = Chess_board() data = mark_safe(json.dumps(board.rep)) data2 = m...
import cv2 as cv img = cv.imread("testeOpenCV.jpg") b, g, r = cv.split(img) cv.imshow("Joelma Canal Azul", b) cv.waitKey(0) cv.imshow("Joelma Canal Verde", g) cv.waitKey(0) cv.imshow("Joelma Canal Vermelho", r) cv.waitKey(0) bgr = cv.merge((b, g, r)) cv.imshow("Joelma Todos os Canais", bgr) cv.waitKey(0) img[:, :, 2] =...
# This is a Python framework to compliment "Peek-a-Boo, I Still See You: Why Efficient Traffic Analysis Countermeasures Fail". # Copyright (C) 2012 Kevin P. Dyer (kpdyer.com) # See LICENSE for more details. import random from EventTrace import EventTrace class Webpage: def __init__( self, id ): self.__id ...
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from itemadapter import ItemAdapter import pymysql from MovieSpider.items import M...
from odp.job.publish import Publisher class SAEONPublisher(Publisher): pass
from tensor2_layer import Tensor2Layer
import torch from anndata import AnnData from scvi.core.trainers.inference import UnsupervisedTrainer from scvi.core.modules.vae import VAE use_cuda = torch.cuda.is_available() def unsupervised_training_one_epoch(adata: AnnData): stats = adata.uns["_scvi"]["summary_stats"] vae = VAE(stats["n_vars"], stats[...
# When macOS Photos.app exports an album, it follows the order of the pictures. # The first pictures of the album are also the first to be exported. # Thus they are the first and oldest files written on the disk. # The problem is Flowtos sorts pictures by the value of the last_modified attribute. # So eventually the f...
""" General settings """ import numpy as np # parameters N = 40 # number of grid point F = 8. # forcing term Tmax = 10. # time length of the experiment dT = 0.05 # forecast-analysis cycle length nT = int(Tmax / dT) # number of cycles
from sklearn import linear_model from scipy import stats import numpy import pandas as pd import logging import random import statistics from numpy.linalg import inv from matplotlib import pylab as plt import seaborn as sns
"""Load and stream data""" import json import boto3 import pandas as pd DATA = 'tweets.csv' def load_data(fn): return pd.read_csv(fn) def push_to_lambda(records): client = boto3.client('lambda', region_name='us-east-1') client.invoke( FunctionName='IngestStack-handler', InvocationType...
from discord.ext import commands from dotenv import load_dotenv from lib.mysqlwrapper import mysql from lib.logger import Logger from pathlib import Path import discord import logging import os # Load up the environment variables env_file_name = '.env' env_path = Path('.') / env_file_name load_dotenv(dotenv_path=env_p...
## Inorder Traversal of Binary Tree # 1. Iterative approach - Using stack # 2. Recursive approach # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def inord...
from socketserver import TCPServer, ThreadingMixIn, StreamRequestHandler class Server(ThreadingMixIn, TCPServer): pass class Handler(StreamRequestHandler): def handler(self): addr= self.request.getpeername() print('Got connection from ', addr) self.wfile.write('Thank you for connecting') server = Serv...
# Sample DIAMOND parameters. PARAMS = { 'application': 'DIAMOND', 'reference': ('Buchfink et al., Fast and Sensitive Protein Alignment ' 'using DIAMOND, Nature Methods, 12, 59-60 (2015)'), 'task': 'blastx', 'version': 'v0.8.23', } RECORD0 = { 'query': 'id0', 'alignments': [ ...
from numpy import array from numpy.random import RandomState from networkx import relabel_nodes, set_edge_attributes WALKING_SPEED = 3 # km per hour def relabel_source_sink(G, nodes_to_relabel={ "Source": "Ternatestraat", "Sink": "Delft...
import easygui as eg import os from Fase_1.sprint2_fase1_script import sprint2_fase1 from Fase_2.sprint2_fase2_script import sprint2_fase2 from Util.downloader_e_contador_locs_repositorios import runScriptDownloaderContadorLocsRepositoriosMain from Util.exportador_lista_loc_csv import runExportadorListaLocCsvScriptMain...
# Copyright 2021 Dynatrace LLC # # 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 t...
import zenduty from zenduty.exceptions import ApiException api_instance = zenduty.TeamsApi(zenduty.ApiClient('ENTER-YOUR-ACCESS-TOKEN-HERE')) try: # Get Incidents api_response = api_instance.get_teams() print(api_response.data) except ApiException as e: print("Exception when calling TeamsApi->api_acco...
import os import sys import json GENERATED = '${CMAKE_BINARY_DIR}/ncg_generated' ANALYSIS_FILE = './gyp_analysis.json' def get_OS(): if sys.platform == 'darwin': return 'mac' if sys.platform.startswith('linux'): return 'linux' if sys.platform == 'win32': return 'win32' generator...
"""Basic code to parse a file into html pages and a KB. Examples: >>> pages, kb = interpret.file('planets.txt') >>> pages['Neptune'] u'Neptune is great, blablabla' >>> kb['neptune'] {'isa': ['planet'], 'diameter': ['49500 km']} """ from abc import abstractmethod from abc import ABCMeta import codecs from parse impor...
import datetime, collections import GlobalConstants as GC import configuration as cf import ItemMethods, Image_Modification, Utility, Engine, Counters import StateMachine, InfoMenu, GUIObjects import CustomObjects import logging logger = logging.getLogger(__name__) def OutlineFont(FONTNAME, text, surf, inne...
from dagster import ( AssetStoreContext, DagsterInstance, InputDefinition, Int, ModeDefinition, OutputDefinition, PipelineRun, lambda_solid, pipeline, ) from dagster.core.events import DagsterEventType from dagster.core.execution.api import create_execution_plan, execute_plan from da...
from django.test import TestCase from hknweb.studentservices.models import ( CourseGuideParam, CourseGuideGroup, CourseGuideNode, CourseGuideAdjacencyList, ) class CourseGuideModelTests(TestCase): def test_course_guide_models(self): param = CourseGuideParam.objects.create( lin...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: artm/messages.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import descriptor_pb2 # @@protoc_insertion_point(impo...
import re class Solution: def myAtoi(self, str: str) -> int: if not re.findall('^\s*([-+]?[0-9]+)',str): return 0 else: intResult = int(re.findall('^\s*([-+]?[0-9]+)',str)[0]) if (intResult <= -2**31): return -2**31 elif (intResult >= 2**31-1): return 2**31-1 else: return intR...
#!/usr/bin/env python2 """ test script to provide gplog.feature (behave) test with logging samples. """ import logging from gppylib import gplog logger = gplog.get_default_logger() gplog.setup_tool_logging("test_logging", "localhost", "gpadmin") logger.warning("foobar to stdout and file") gplog.log_to_file_only("bla...
# Generated by Django 3.0.6 on 2020-10-08 15:57 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('meds', '0010_auto_20201005_0813'), ] operations = [ migrations.AlterModelOptions( name='comercialdrug', options={'ordering':...
import os from app import create_app from config.app_config import ProductionLevelConfig from config.db_config import RemoteDBConfig if "SECRET_KEY" not in os.environ: raise Warning("The secret key must be passed by the <SECRET_KEY> envvar.") application = create_app(ProductionLevelConfig, RemoteDBConfig)
# Generated by Django 2.2.1 on 2019-05-09 21:08 from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('matchapp', '0003_available_doctors'), ] operations = [ ...
''' implement the feature extractions for light CNN @author: Alfred Xiang Wu @date: 2017.07.04 ''' ### revised by Zhenggang Li 2018.12.10 from __future__ import print_function import argparse import os import shutil import time import matplotlib.pyplot as plt import torch import torch.nn as nn import torch...
from match import Match class Session(): ''' it collects the player name, boosts the game in each possible case ''' case_all = [1, 18, ] # TODO: move to a dictionary game_over = False def __init__(self, player_name, db_name): self.player_name = player_name self.db_name = db_name ...
""" Person class """ from ofb.constants import SEX import pprint class Person: """Class definition""" def __init__(self, data): assert data["sex"] is "male" or "female", "sex has value %s" % data["sex"] self.sex = data["sex"] self.age = data["age"] self.height = data["height"]...
# -*- coding: utf-8 from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from custom_auth_user.user.manager import UserManager class AbstractUser(AbstractBaseUser, PermissionsMixin): """ Abstract user model """ email...
from django.shortcuts import render def index(request): return render(request,'personal/home.html') def contact(request): return render(request,'personal/basic.html',{'content':['If you like my website,Please email me!','heng960509@gmail.com']})
#!/usr/bin/env python __copyright__ = "Copyright 2015, Moscow Exchange" __author__ = "Nikolay Viskov" __email__ = "help@moex.com" import socket import struct from serializer import Serializer class Client(object): def __init__(self): pass def connect(self, host, port): self.host = h...
n = int(input("[>] Enter N: ")) m = int(input("[>] Enter M: ")) if n % m: print(f"[+] Kilometers: {n // m + 1}") else: print(f"[+] Kilometers: {n // m}")
from flask import * from functionsGoHere import * from FileRetriever import * from ppt_creation import * from allWords import * app = Flask(__name__) @app.route('/', methods=["GET","POST"]) def hello_world(): t = request.method resp = "" if t == "GET": resp = render_template("index.html", quer='', val='') else: ...
import sqlite3 connection = sqlite3.connect("newnum.db") c = connection.cursor() # Create a user prompt asking for AVG, MAX, MIN, or SUM. Else exit choice = "" valid_choices = ["AVG","MAX","MIN","SUM","EXIT"] while True: choice = str.upper(raw_input("""Choose from the following: AVG, MAX, MIN, or SUM. EXI...
# pylint: disable=C0103 """ OpenTMI module for Test Job """ from opentmi_client.utils.Base import BaseApi from opentmi_client.utils.decorators import setter_rules class Job(BaseApi): """ Job Class """ def __init__(self, id_=None): """ Constructor for Job :param id_: String ...
""" This script is adopted from https://raw.githubusercontent.com/bcgsc/tasrkleat/0a6214bd6db60f947789ae3470b1bad5634db23c/hexamer_search/search_hexamer.py which search for PAS hexamer on reference genome. However, in this adopted version, it search for hexamer inside a given sequence (e.g contig) independent of a refe...
word_size = 16 num_words = 1024 words_per_row = 16 local_array_size = 40 output_extended_config = True output_datasheet_info = True netlist_only = True nominal_corner_only = True
def is_armstrong(n: int) -> bool: return sum([pow(int(x), len(str(n))) for x in str(n)]) == n
import optuna_core if __name__ == "__main__": study = optuna_core.study.create_study(direction="minimize") for _ in range(100): trial = study.ask() x = trial.suggest_float("x", -5.0, 5.0) y = (x - 2) ** 2 study.tell(trial, state=optuna_core.trial.TrialState.COMPLETE, value=y...
''' Tests for basic HTTP request handling ''' from unittest import TestCase from urllib import parse from tornado.web import Application from tornado.httputil import HTTPHeaders from tornado.httputil import HTTPConnection from tornado.httputil import HTTPServerRequest from f5.handlers import BaseRequestHandler cla...
from __feature__ import absolute_import from .Ahao import * name = 'Ahao'
#slicing word = 'happy' first = 3 last = 5 print( word[0:1] ) print( word[1:3] ) print( word[:3] ) print( word[3:] ) print( word[3:99]) print( word[:]) print( word[1:1]) print( word[4:2] ) print( word[first:last])
from . import configuration from . import env from . import event from . import recording from .py_version_check import check_py_version def initialize(): check_py_version() env.initialize() event.initialize() recording.initialize() configuration.initialize() # needs to be initialized after recor...
import pyramid import unicodedata import math from osgeo import osr, ogr def round(val): '''The builtin round function rounds even numbers down and odd numbers up. This avoids a round up bias and is conform to floating point manipulation defined by the IEEE. Since we want to round number in .5 up and the...
################################################################# # # Copyright 2013, Big Switch Networks, Inc. # # Licensed under the Eclipse Public License, Version 1.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:...
import xgboost as xgb import numpy as np import time import pickle import GPUtil n = 10000 m = 1000 X = np.random.random((n, m)) y = np.random.random(n) param = {'objective': 'binary:logistic', 'tree_method': 'gpu_hist' } iterations = 5 dtrain = xgb.DMatrix(X, label=y) # High memory usage # active ...
"""Support for De Lijn (Flemish public transport) information.""" import logging from pydelijn.api import Passages from pydelijn.common import HttpException import voluptuous as vol from homeassistant.components.sensor import ( PLATFORM_SCHEMA, SensorDeviceClass, SensorEntity, ) from homeassistant.const i...
from django import forms from ..forms import YesNoSwitch class YesNoForm(forms.Form): test_field = YesNoSwitch(label="Hello!") def test_input_returns_int_true_for_valid_true_input(): for value in ("1", "True", "true", 1, True): form = YesNoForm({"test_field": value}) form.full_clean() ...
# Copyright 2019 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
"""Module for request errors""" REQUEST_ERROR_DICT = { 'invalid_request': 'Invalid request object', 'not_found': '{} not found', 'invalid_credentials': 'Invalid username or password', 'already_exists': '{0} or {1} already exists', 'exists': '{0} already exists', 'invalid_provided_date': 'Invali...
import discord from discord.ext import commands class ErrHandler(commands.Cog): def __init__(self, bot): self.bot = bot @commands.Cog.listener() async def on_command_error(self, ctx, error): '''Error Handling''' if isinstance(error, commands.MissingRole): await ctx...
import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '../')) from synchrophasor.frame import * from synchrophasor.pmu import Pmu from synchrophasor.pmuGen import * from time import sleep import threading import numpy as np SLEEP_TIME = 1.0/70 SIGNAL_DURATION = 10 DT = 0.02 PI2 = np.pi * 2 def gen_...
# Generated by Django 2.0 on 2018-04-16 15:38 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('liba', '0001_initial'), ] operations = [ migrations.CreateModel( name='Author', field...
import asyncio import uuid from typing import List, Optional import pytest from fastapi_users import models from pydantic import UUID4 from sqlmodel import Field, Relationship from fastapi_users_db_sqlmodel import SQLModelBaseOAuthAccount, SQLModelBaseUserDB class User(models.BaseUser): first_name: Optional[str...
Given a string s, remove duplicate letters so that every letter appears once and only once. You must make sure your result is the smallest in lexicographical order among all possible results. Example 1: Input: s = "bcabc" Output: "abc" Example 2: Input: s = "cbacdcbc" Output: "acdb" Constraints: 1 <= s.length...
"""Entry point for the whole package.""" import sys from bitcoin_heist.src.analysis import binary, main from bitcoin_heist.src.constants import BINARY_PARAM if __name__ == "__main__": if BINARY_PARAM in sys.argv: binary() else: main()