content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from django.core.validators import MinLengthValidator
from django.db import models
class Design(models.Model):
TYPE_CHOICE_INTERIOR = 'interior'
TYPE_CHOICE_PRODUCT = 'product'
TYPE_CHOICE_3D = '3d'
TYPE_CHOICE_OTHER = 'other'
TYPE_CHOICES = (
(TYPE_CHOICE_INTERIOR, 'Interior design'),
... | nilq/baby-python | python |
from abc import ABC, abstractmethod
from typing import List
import numpy as np
from scipy.stats import t, spearmanr
from scipy.special import erfinv
from chemprop.uncertainty.uncertainty_calibrator import UncertaintyCalibrator
from chemprop.train import evaluate_predictions
class UncertaintyEvaluator(ABC):
"""
... | nilq/baby-python | python |
import json
import glob
import luigi
import os
from dlib.task_helpers import parse_yaml, extract_task_config
from dlib.task_helpers import read_data, generate_output_filename, run_init
from dlib.identifier import Identify
from dlib.parser import Parser
from dlib.process_router import Processor
from dlib.btriples import... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# @version : ??
# @Time : 2017/3/29 17:31
# @Author : Aries
# @Site :
# @File : shutil_0329.py
# @Software: PyCharm
import zipfile
"""
压缩 解压 .zip包
"""
# 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('test.txt')
z.write('test2.xml')
z.close()
# 解压
z = zipfile.ZipFile('laxi.zip', 'r... | nilq/baby-python | python |
# Time: O(r * c)
# Space: O(1)
# Given a matrix A, return the transpose of A.
#
# The transpose of a matrix is the matrix flipped over it's main diagonal,
# switching the row and column indices of the matrix.
#
# Example 1:
#
# Input: [[1,2,3],[4,5,6],[7,8,9]]
# Output: [[1,4,7],[2,5,8],[3,6,9]]
# Example 2:
#
# Inpu... | nilq/baby-python | python |
import logging
from typing import List
from api.token.service import Token
from api.calendar.service import CalendarService, Calendar
LOG = logging.getLogger(__name__)
class GoogleCalendarService(CalendarService):
IGNORED_CALENDARS = {'addressbook#contacts@group.v.calendar.google.com',
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from setuptools import setup
import codecs
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()
def get_version(rel_path):
for line in read(rel_pa... | nilq/baby-python | python |
import os
import re
from string import letters
import random
import hashlib
import hmac
import webapp2
import jinja2
from jinja2 import Environment
from google.appengine.ext import db
from Handler import Handler
class Logout(Handler):
""" handles user logout safely """
def get(self):
self.logout()
... | nilq/baby-python | python |
import numpy as np
import inspect # Used for storing the input
from .element import Element
from .equation import PotentialEquation
__all__ = ['Constant', 'ConstantStar']
class ConstantBase(Element, PotentialEquation):
def __init__(self, model, xr=0, yr=0, hr=0.0, layer=0, \
name='ConstantBase',... | nilq/baby-python | python |
from mangofmt import MangoFile, EncryptionType, CompressionType, Language
def test_title():
mango = MangoFile()
meta = mango.meta_data
assert meta.title == None
meta.title = "test"
assert meta.title == "test"
def test_author():
mango = MangoFile()
meta = mango.meta_data
assert meta.a... | nilq/baby-python | python |
import simplejson as json
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt, ensure_csrf_cookie
import directory.models as directory
from appcon... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""Tests of deployment."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import base64
import mock
from asyncat.client import GithubError
from hindsight.finder import N... | nilq/baby-python | python |
def mdc(m, n):
while m % n != 0:
oldm = m
oldn = n
m = oldn
n = oldm % oldn
return n
def separadorFrac(frac):
novoNum = frac.getNum()
inteiro = 0
while novoNum > frac.getDen():
novoNum -= frac.getDen()
inteiro += 1
return inteiro, novoNum
def ... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
# 数据库定义
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_cache import Cache
import memcache
import os
curdir = os.getcwd()
static_dir = curdir+'/static'
template_dir = curdir+'/templates'
app = Flask(__name__,static_folder=static_dir,template_folder=template_dir)
cac... | nilq/baby-python | python |
SYMBOLS = \
[
# 1
'?', '!', '¿', '¡', ',', '.', '@', '#', '%', '&', '-',
'(', ')', '[', ']', ';', ':', '′', '‘', '’', '‚', '‛',
'\\', '/', '{', '}', '•', '…', '″', '“', '”', '„', '_',
'<', '>', '«', '»', '←', '→', '↑', '↓', '⇒', '⇔', '˜',
'$', '¢', '€', '£', '¥', '₽',... | nilq/baby-python | python |
"""
DriverFactory class
Note: Change this class as you add support for:
1. SauceLabs/BrowserStack
2. More browsers like Opera
"""
import dotenv,os,sys,requests,json
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabil... | nilq/baby-python | python |
from django.test import TestCase
from django.urls import reverse, resolve
from media_server.views import (
VideoListCreateView,
VideoRetrieveUpdateDestroyView,
GenreListCreateView,
GenreRetrieveUpdateDestroyView
)
class VideoListCreateViewUrlsTests(TestCase):
def test_urls(self):
url = re... | nilq/baby-python | python |
# Copyright (C) 2018 Intel 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 wri... | nilq/baby-python | python |
# Copyright 2020 Toyota Research Institute. All rights reserved.
import os
import torch
import numpy as np
from dgp.datasets.synchronized_dataset import SynchronizedSceneDataset
from dgp.utils.camera import Camera, generate_depth_map
from dgp.utils.geometry import Pose
from packnet_sfm.geometry.pose_utils import inv... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request
from scrapy.selector import Selector
from scrapy_doubanmovie.scrapy_doubanmovie.items import ScrapyDoubanmovieItem
from urllib.parse import urljoin
# 通过scrapy genspider douban_spider movie.douban.com生成的
class DoubanSpiderSpider(scrapy.Spider):
#... | nilq/baby-python | python |
from base64 import b64encode, b64decode
from random import randint
class UtilityService:
@staticmethod
def decode_bytes(s):
return b64decode(s).decode('utf-8')
@staticmethod
def encode_string(s):
return str(b64encode(s.encode()), 'utf-8')
@staticmethod
def jitter(fraction):
... | nilq/baby-python | python |
"""Compare two HTML documents."""
from html.parser import HTMLParser
from django.utils.regex_helper import _lazy_re_compile
# ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020
# SPACE.
# https://infra.spec.whatwg.org/#ascii-whitespace
ASCII_WHITESPACE = _lazy_re_compile(r'[\t\n\f\r ]+')
de... | nilq/baby-python | python |
# coding:utf-8
import MeCab
import codecs
from model import Seq2Seq
import chainer
import json
import sys
import io
class Chatbot:
def __init__(self, dirname):
self.dir = 'model/' + dirname + '/'
self.dict_i2w = self.dir + 'dictionary_i2w.json'
self.dict_w2i = self.dir + 'dictionary_w2i.jso... | nilq/baby-python | python |
#!/usr/bin/python
#coding: utf-8 -*-
#
# (c) 2014, Craig Tracey <craigtracey@gmail.com>
#
# This module 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 3 of the License, or
# (at your option) an... | nilq/baby-python | python |
# Obfuscated by Py Compile
# Created by Wh!73 D3v!1 (https://github.com/WHI73-D3VI1)
# Facebook : (https://www.facebook.com/WHI73.D3VI1)
# Don't try to edit or modify this tool
import marshal,zlib,base64
exec(marshal.loads(zlib.decompress(base64.b64decode("eJzNVd1PG0cQn7vDGBscvsJHoE2XUiduUr4bSFHUBoWGoDaUAirSIYQMt9hnfD... | nilq/baby-python | python |
import datetime
import hashlib
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
from tldr import app
from urllib.parse import urlparse
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
db = SQLAlchemy(app)
def baseN(num, b, numerals='0123456789abcdefghijklmnopqrstuvwxyz... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
Change directory to provide relative paths for doctests
>>> import os
>>> filepath = os.path.dirname( os.path.realpath( __file__ ) )
>>> datadir = os.path.realpat... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright 2019, GeoSolutions Sas.
# All rights reserved.
#
# This source code is licensed under the MIT license found in the
# LICENSE.txt file in the root directory of this source tree.
#
#############################... | nilq/baby-python | python |
# Generated by Django 2.2.13 on 2020-11-10 08:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('studygroups', '0139_team_subtitle'),
]
operations = [
migrations.AlterField(
model_name='team',
name='subtitle',
... | nilq/baby-python | python |
import time
from locust import HttpUser, between, task
class QuickstartUser(HttpUser):
wait_time = between(1, 2)
@task
def get_users(self):
self.client.get("/api/users/") | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# BCDI: tools for pre(post)-processing Bragg coherent X-ray diffraction imaging data
# (c) 07/2017-06/2019 : CNRS UMR 7344 IM2NP
# (c) 07/2019-present : DESY PHOTON SCIENCE
# authors:
# Jerome Carnis, carnis_jerome@yahoo.fr
import numpy as np
from numpy... | nilq/baby-python | python |
from django.shortcuts import render
from django.views.generic import View
class IndexView(View):
""" An index view"""
template_name = "base.html"
def get(self, request):
""" GET to return a simple template """
return render(
request, self.template_name
)
| nilq/baby-python | python |
"""
Tests for ESMTP extension parsing.
"""
from aiosmtplib.esmtp import parse_esmtp_extensions
def test_basic_extension_parsing():
response = """size.does.matter.af.MIL offers FIFTEEN extensions:
8BITMIME
PIPELINING
DSN
ENHANCEDSTATUSCODES
EXPN
HELP
SAML
SEND
SOML
TURN
XADR
XSTA
ETRN
XGEN
SIZE 51200000
"""
... | nilq/baby-python | python |
import pytest
from liquid import *
def test_register_filter():
@filter_manager.register(mode='python')
def incr(base, inc=1):
return base + inc
liq = Liquid('{{ 2 | incr}}', dict(mode='python'))
assert liq.render() == '3'
liq = Liquid('{{ 2 | incr:2}}', dict(mode='python'))
assert liq.... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import json
with open(os.path.join(os.environ['BOOST_CI_SRC_FOLDER'], 'meta', 'libraries.json')) as jsonFile:
lib_data = json.load(jsonFile)
print(lib_data['key'])
| nilq/baby-python | python |
#!/usr/bin/env python2.7
import sys
import argparse
import gzip
import clsnaputil
#assumes you already have the AUCs
#pulled out using:
#wiggletools print non_unique_base_coverage.bw.auc AUC non_unique_base_coverage.bw
RECOUNT_TARGET = 40 * 1000000
SNAPTRON_FORMAT_CHR_COL = 1
SNAPTRON_FORMAT_COUNT_COL = 11
def load_... | nilq/baby-python | python |
from optparse import make_option
import os
import shutil
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
import MySQLdb
from blog.models import Blog, Post, Asset
class Command(BaseCommand):
help = 'Import blog posts from Movable Type'
option_list = BaseCommand... | nilq/baby-python | python |
"""Programa 8_5.py
Descrição: Reescrever a função da listagem 8.5 de forma a utilizar os métodos de pesquisa em lista vistos no cap 7.
Autor:Cláudio Schefer
Data:
Versão: 001
"""
# Declaração de variáveis
L = []
valor = int (0)
# Entrada de dados
L = [10, 20, 25, 30]
# Processamento
def pesquise (lista, valor)... | nilq/baby-python | python |
import asyncio
import logging
from timeit import default_timer as timer
from podping_hivewriter.async_context import AsyncContext
from podping_hivewriter.models.podping_settings import PodpingSettings
from podping_hivewriter.podping_settings import get_podping_settings
from pydantic import ValidationError
class Podp... | nilq/baby-python | python |
from rest_framework import permissions
from API.models import *
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
... | nilq/baby-python | python |
WORD_EMBEDDING_FILE = './data/GoogleNews-vectors-negative300.txt'
WORD_EMBEDDING_BIN_FILE = './bin/unigram_embedding.pkl'
LOW_FREQ_TOKEN_FILE = './bin/unigram_low_freq_voc.pkl'
EMBEDDING_SIZE = 300
if __name__ == "__main__":
from preprocess.data import GigawordRaw, ParaphraseWikiAnswer
from gensim.models impo... | nilq/baby-python | python |
print('Vamos somar alguns números: ')
for c in range(1, 501):
if c % 3 == 0:
print(c)
| nilq/baby-python | python |
#!/usr/bin/python
"""
Check current Husky battery status (via ROS)
usage:
./battery.py [<node IP> <master IP> | -m <metalog> [F]]
"""
import sys
import os
from huskyros import HuskyROS
# apyros should be common lib - now in katarina code
from apyros.sourcelogger import SourceLogger
from apyros.metalog import... | nilq/baby-python | python |
import os
import tkinter.filedialog as tk
import natsort
pot = '/media/vid/DLS DATA/seq4Amod35/2112'
seznam = os.listdir(pot)
seznam = natsort.natsorted(seznam)
key = 'OHL'
temp = []
for i in seznam:
if key in i:
print(i)
if '.txt' in i:
continue
with open(pot ... | nilq/baby-python | python |
#Will take a directory full of covariance models and feed them to Infernal's cmcalibrate one at a time.
#The resulting covariance models are put in sys.argv[3].
#This script may take several days to complete. Calibrating models of large alignments is slow.
#Necessary modules: biopython, infernal
#Usage: python Infer... | nilq/baby-python | python |
outputText = """Yesterday I went to see {0}.
To be honest, I thought it was pretty good.
It's a good effort by {1}.
I hadn't seen a plot move quite as fluidly as it did in {0},
but {1} does have a good hand for it."""
print('What movie are we reviewing')
movie = input().title()
print('And who directs it?')
director ... | nilq/baby-python | python |
class ControllerSettings:
def __init__(self, powerslide, air_roll, air_roll_left, air_roll_right, boost, jump, ball_cam, brake, throttle):
self.powerslide = powerslide
self.air_roll = air_roll
self.air_roll_left = air_roll_left
self.air_roll_right = air_roll_right
self.boost ... | nilq/baby-python | python |
import os
import nbformat
def get_cur_dir():
return os.path.abspath(os.path.dirname(__file__))
def get_par_dir():
return os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
def gen_items(path):
for item in os.listdir(path):
path_item = os.path.abspath(os.path.join(path, item))... | nilq/baby-python | python |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# File name: test.py
# First Edit: 2020-03-19
# Last Change: 19-Mar-2020.
"""
This scrip is for test
"""
amount_dict = {"high": 1.2, "normal": 1.0, "low": 0.8}
def main():
factorya = AbstractPizzaFactory(PizzaFactoryA())
pizza1 = factorya.make... | nilq/baby-python | python |
'''
最长公共子序列
描述
给定两个字符串,返回两个字符串的最长公共子序列(不是最长公共子字符串),可能是多个。
输入
输入为两行,一行一个字符串
输出
输出如果有多个则分为多行,先后顺序不影响判断。
输入样例
1A2BD3G4H56JK
23EFG4I5J6K7
输出样例
23G456K
23G45JK
'''
'''
d为方向矩阵
1:上
2:左上
3:左
4:左or上
'''
def LCS (a, b):
C = [[0 for i in range(len(b) + 1)] for i in range(len(a) + 1)] # 定义矩阵C保存最长公共子序列长度
d = [[0 for i in ra... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to convert YOLO keras model to an integer quantized tflite model
using latest Post-Training Integer Quantization Toolkit released in
tensorflow 2.0.0 build
"""
import os, sys, argparse
import numpy as np
import tensorflow as tf
from tensorflow.keras.mo... | nilq/baby-python | python |
from taskcontrol.lib import EPubSubBase
def run(data):
print("Running Pubsub ", data)
def publisher(data):
print("Running publisher ", data)
def subscriber(data):
print("Running subscriber ", data)
config = {"name": "new", "handler": run, "queue": None, "maxsize": 10,
"queu... | nilq/baby-python | python |
import numpy as np
import os
import sys
from astropy.io import fits
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
plt.style.use('araa')
from matplotlib import rc
rc('text.latex', preamble=r'\usepackage{amsmath}')
rc("font", **{"family": "serif", "serif": ["Palatino"]})
rc("text", usetex = True... | nilq/baby-python | python |
from collections import OrderedDict
from functools import partial
from unittest import TestCase
import os
import os.path as osp
import numpy as np
from datumaro.components.annotation import (
AnnotationType, LabelCategories, Mask, MaskCategories,
)
from datumaro.components.dataset import Dataset
from datumaro.com... | nilq/baby-python | python |
"""
Django 1.10.5 doesn't support migrations/updates for fulltext fields, django-pg-fts isn't
actively maintained and current codebase is broken between various versions of Django.
Because of that I decided to implement our migrations with intent to drop it when django develops
its own solution.
"""
import copy
from ... | nilq/baby-python | python |
import os
import argparse
import shutil
from datetime import datetime,timedelta
def main():
'''
the driver
'''
args = parse()
files = get_files(args)
if confirm(files):
copy_files(files,args)
def parse():
'''
sets the args needed to run and returns them
'''
#default... | nilq/baby-python | python |
import yaml
from pathlib import Path
from .repo import serialize_repo, deserialize_repo
from .validation import validate_manifest
from ..exception import AppException
from ..env import MANIFEST_PATH_DEFAULT
from ..logger import get_logger
from ..utils import to_absolute_path, validate_writable_directory
def seriali... | nilq/baby-python | python |
import logging
import sqlite3
from phizz.database import get_cursor
from . import GENE_DB
logger = logging.getLogger(__name__)
def query_hpo(hpo_terms, database=None, connection=None):
"""Query with hpo terms
If no databse is given use the one that follows with package
Args:
... | nilq/baby-python | python |
import numpy as np
def gaussian_KL(mu0, Sig0, mu1, Sig1inv):
t1 = np.dot(Sig1inv, Sig0).trace()
t2 = np.dot((mu1-mu0),np.dot(Sig1inv, mu1-mu0))
t3 = -np.linalg.slogdet(Sig1inv)[1] - np.linalg.slogdet(Sig0)[1]
return 0.5*(t1+t2+t3-mu0.shape[0])
def weighted_post_KL(th0, Sig0inv, sigsq, X, Y, w, reverse=True):... | nilq/baby-python | python |
# <editor-fold desc="Description">
x = 'foo' + 'bar'
# </editor-fold> | nilq/baby-python | python |
import numpy as np
from matplotlib import pyplot as plt
import seaborn as sb
from utils.data_handling import load_config
def get_colors():
cfg = load_config()
sb.set_style(cfg['plotting']['seaborn']['style'])
sb.set_context(cfg['plotting']['seaborn']['context']['context'],
font_scale=c... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on 2021/1/12 16:51
@author: Irvinfaith
@email: Irvinfaith@hotmail.com
""" | nilq/baby-python | python |
# Generated by Django 3.1.4 on 2020-12-12 22:01
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("peeringdb", "0014_auto_20201208_1856"),
("peering", "0065_auto_20201025_2137"),
]
operations = [
mi... | nilq/baby-python | python |
r"""
Hypergraphs
This module consists in a very basic implementation of :class:`Hypergraph`,
whose only current purpose is to provide method to visualize them. This is
done at the moment through `\LaTeX` and TikZ, and can be obtained from Sage
through the ``view`` command::
sage: H = Hypergraph([{1,2,3},{2,3,4},{... | nilq/baby-python | python |
# coding: utf-8
# **In this simple kernel, I will attempt to predict whether customers will be "Charged Off" on a loan using Random Forests Classifier.**
# In[ ]:
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/... | nilq/baby-python | python |
from rater import generate_pokemon_list_summary
from common import pokemon_base_stats
from pokedex import pokedex
excluded_pokemon_name_list = []
def find_bad_pokemons(pokemon_list):
pokemon_summary = generate_pokemon_list_summary(pokemon_list)
bad_pokemons_ids = []
for pokemon_name in sorted(pokemon_summary.k... | nilq/baby-python | python |
app = """
library(dash)
app <- Dash$new()
app$layout(
html$div(
list(
dccInput(id='input-1-state', type='text', value='Montreal'),
dccInput(id='input-2-state', type='text', value='Canada'),
html$button(id='submit-button', n_clicks=0, 'Submit'),
html$div(id='output-state'),
dccGraph... | nilq/baby-python | python |
class Solution:
def wordPattern(self, pattern, str):
map_letter_to_word = dict()
map_word_to_letter = dict()
words = str.split()
if len(words) != len(pattern):
return False
for letter, word in zip(pattern, words):
if l... | nilq/baby-python | python |
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
# Mostly taken from PasteDeploy and stripped down for Galaxy
import inspect
import os
import re
import sys
import pkg_resources
from six import ite... | nilq/baby-python | python |
from numpy import sin, cos, pi, fabs, sign, roll, arctan2, diff, cumsum, hypot, logical_and, where, linspace
from scipy import interpolate
import matplotlib.pyplot as plt
# Cross-section class that stores x, y points for the cross-section
# and calculates various geometry data
d = 1000
class CrossSection:
"""
Cla... | nilq/baby-python | python |
#! python2.7
## -*- coding: utf-8 -*-
## kun for Apk View Tracking
## ParseElement.py
from DeviceManagement.Device import Device
from TreeType import CRect
from Utility import str2int
class ParseElement():
def __init__(self, element_data):
self.class_name = ""
self.hash_code = ""
... | nilq/baby-python | python |
#Crie um progama que tenha uma tupla totalmente preenchida com uma contagem por extensão de Zero até Vinte.
#Seu programa deverá ler um número pelo teclado (entre 0 e 20) e mostra-lo por extenso.
numeros = ('zero','um', 'dois','três','quatro','cinco','seis','sete','oito','nove','dez','onze','doze','treze','quatorze',
... | nilq/baby-python | python |
import sys
import logging
import logging.handlers
from command_tree import CommandTree, Config
from voidpp_tools.colors import ColoredLoggerFormatter
from .core import Evolution, Chain
from .revision import REVISION_NUMBER_LENGTH
tree = CommandTree(Config(
prepend_double_hyphen_prefix_if_arg_has_default = True,
... | nilq/baby-python | python |
import os
import pandapower as pp
import pandapower.networks as pn
from pandapower.plotting.plotly import pf_res_plotly
from preparation import NetworkBuilder
import_rules = dict()
aemo_data = r"data/aemo_data_sources.json"
tnsp_buses = r"data/electranet_buses.json"
if __name__ == "__main__":
builder = NetworkBui... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
import ssl
from base64 import b64decode, b64encode
from hashlib import sha256
from time import time
from urllib import parse
from hmac import HMAC
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
from paho.mqtt import client as mqtt
def... | nilq/baby-python | python |
objConstructors = {'flow_emap.get_key' : {'constructor' : 'FlowIdc',
'type' : 'FlowIdi',
'fields' : ['sp', 'dp', 'sip',
'dip', 'prot']}}
typeConstructors = {'FlowIdc' : 'FlowIdi',
... | nilq/baby-python | python |
from django.conf.urls import patterns, include, url
from django.utils.translation import ugettext_lazy as _
from django.views.generic import TemplateView, RedirectView
from django.core.urlresolvers import reverse_lazy as reverse
from .views import reroute
home = TemplateView.as_view(template_name='home.html')
#: IHM... | nilq/baby-python | python |
from math import ceil
from utils import hrsize
from json import dumps
from . import Sample
class SampleSet:
round = 5
def __init__(self, samples) -> None:
if not (isinstance(samples, list) and all(isinstance(sample, Sample) for sample in samples)):
raise Exception("samples parameter inval... | nilq/baby-python | python |
import pytest
from django.core.exceptions import PermissionDenied
from datahub.admin_report.report import get_report_by_id, get_reports_by_model
from datahub.core.test_utils import create_test_user
pytestmark = pytest.mark.django_db
@pytest.mark.parametrize(
'permission_codenames,expected_result',
(
... | nilq/baby-python | python |
def factorial(n):
if n < 1:
return 1
else:
return n * factorial(n-1)
end
end
print factorial(5) # should output 120
| nilq/baby-python | python |
"""
@author: acfromspace
"""
# Make a function aardvark that, given a string, returns 'aardvark'
# if the string starts with an a. Otherwise, return 'zebra'.
#
# >>>> aardvark("arg")
# aardvark
# >>>> aardvark("Trinket")
# zebra
def aardvark(string):
# Add code here that returns the answer.
if string[0] == ... | nilq/baby-python | python |
import datetime
from django.test import TestCase
from trojsten.contests.models import Competition, Round, Semester, Task
from trojsten.people.models import User, UserProperty, UserPropertyKey
from .model_sanitizers import (
GeneratorFieldSanitizer,
TaskSanitizer,
UserPropertySanitizer,
UserSanitizer,... | nilq/baby-python | python |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
# Copyright 2019-2021 Fortinet, Inc.
#
# 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 3 of the ... | nilq/baby-python | python |
import torch.nn
from gatelfpytorchjson.CustomModule import CustomModule
import sys
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
streamhandler = logging.StreamHandler(stream=sys.stderr)
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(messag... | nilq/baby-python | python |
class TimeFrame(object):
_string_repr = [[" day", " hour", " min", " sec"],[" d", " h", " m", " s"]]
def __init__(self, seconds = 0.0):
self._seconds = 0.0
self._minutes = 0
self._hours = 0
self._days = 0
self._use_short = int(False)
self._total_seconds = seconds
self.set_with_seconds(seconds)
de... | nilq/baby-python | python |
import subprocess
import sys
from optparse import OptionParser
from django.core.management import LaxOptionParser
from django.core.management.base import BaseCommand, CommandError
from cas_dev_server.management import subprocess_environment
class Command(BaseCommand):
option_list = BaseCommand.option_list[1:]
... | nilq/baby-python | python |
#!/usr/bin/env python3
from dotenv import load_dotenv
load_dotenv()
import os
import logging
import argparse
import pugsql
import json
import pandas as pd
from uuid import UUID
from articleparser.drive import GoogleDrive
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
logger = logging.getLogger(__name__)
... | nilq/baby-python | python |
import warnings
from collections import namedtuple, defaultdict
from functools import partial
from typing import Optional, Tuple, List, Callable, Any
import torch
from torch import Tensor
from torch import distributions
from torch import nn
class TemporalDifference(nn.Module):
def __init__(
self,
... | nilq/baby-python | python |
import unittest
from httpretty import HTTPretty
from notification_log import NotificationLog
import requests
import json
class NotificationLogTests(unittest.TestCase):
def setUp(self):
HTTPretty.enable()
self.client = NotificationLog(hostname='test.example.com', protocol='http')
def tearDown... | nilq/baby-python | python |
from unittest.mock import patch
from main import main_handler
import sys
@patch("main.hello_world")
def test_mock_external_incorrect(mock_hello_world):
mock_hello_world.return_value = "Hello Dolly!"
assert main_handler() == "Hello Dolly!"
for path in sys.path:
print(path) | nilq/baby-python | python |
# Character field ID when accessed: 925070100
# ObjectID: 0
# ParentID: 925070100
| nilq/baby-python | python |
y,z,n=[int(input()) for _ in range(3)]
print("The 1-3-sum is",str( y+z*3+n+91))
| nilq/baby-python | python |
import xarray as xr
import numpy as np
import pytest
import pathlib
from xarrayutils.file_handling import (
temp_write_split,
maybe_create_folder,
total_nested_size,
write,
)
@pytest.fixture
def ds():
data = np.random.rand()
time = xr.cftime_range("1850", freq="1AS", periods=12)
ds = xr.Da... | nilq/baby-python | python |
from snovault.elasticsearch.searches.interfaces import SEARCH_CONFIG
from snovault.elasticsearch.searches.configs import search_config
def includeme(config):
config.scan(__name__)
config.registry[SEARCH_CONFIG].add_aliases(ALIASES)
config.registry[SEARCH_CONFIG].add_defaults(DEFAULTS)
@search_config(
... | nilq/baby-python | python |
from bs4 import BeautifulSoup as bs
import requests
import pandas as pd
import random
url = 'https://www.oschina.net/widgets/index_tweet_list'
headers = {
'Accept':
'*/*',
'Accept-Encoding':
'gzip, deflate, br',
'Accept-Language':
'zh-CN,zh;q=0.9',
'Cache-Control':
'no-cache',
'Con... | nilq/baby-python | python |
from datetime import datetime
from testil import Config, eq
from .. import rebuildcase as mod
def test_should_sort_sql_transactions():
def test(sql_form_ids, couch_form_ids, expect):
sql_case = Config(
transactions=[Config(form_id=x, details={}) for x in sql_form_ids]
)
couch... | nilq/baby-python | python |
#!/usr/bin/env python3
import socket, time, sys
from multiprocessing import Process
HOST = ""
PORT = 8001
BUFFER_SIZE = 1024
#TO-DO: get_remote_ip() method
def get_remote_ip(host):
print(f'Getting IP for {host}')
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
prin... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 26 19:56:37 2017
@author: Simon Stiebellehner
https://github.com/stiebels
This file implements three classifiers:
- XGBoost (Gradient Boosted Trees)
- Random Forest
- AdaBoost (Decision Trees)
These three base classifiers are then ensembled in two ways:
(1) Weighti... | nilq/baby-python | python |
from django.shortcuts import render
from .models import Entry
from rest_framework import generics
from .serializers import EntrySerializer
# Create your views here.
class EntryCreate(generics.ListCreateAPIView):
# Allows creation of a new entry
queryset = Entry.objects.all()
serializer_class = EntrySerial... | nilq/baby-python | python |
#!/usr/bin/python
#import sys
import boto3
import datetime
from Crypto import Random
from Crypto.Cipher import AES
import argparse
import base64
from argparse import Namespace
from keypot_exceptions.KeypotError import KeypotError
#VERSION
keypot_version='Keypot-0.3'
ddb_hash_key_name='env-variable-name'
#Pads the dat... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.