content stringlengths 7 1.05M |
|---|
lstflavors = []
def updateflavors(op, flav):
if op == "add":
if flav in lstflavors:
print(f"{flav} already exists \n Choose a different flavor.")
else:
lstflavors.append(flav)
print(f"{flav} added to your {lstflavors} cone!")
... |
"""
X is a good number if after rotating each digit individually by 180 degrees, we get a valid number that is
different from X. Each digit must be rotated - we cannot choose to leave it alone. A number is valid if each
digit remains a digit after rotation. 0, 1, and 8 rotate to themselves; 2 and 5 rotate to each oth... |
"""
#1
a=int(input("a= "))
b=int(input("b= "))
c=int(input("c= "))
sum=a+b+c
pow=sum**2
print(sum)
print(pow)
"""
"""
#2
a=int(input("a= "))
b=int(input("b= "))
result=(a%5+b%3)**3
print(result)
"""
"""
#3
a=int(input("a= "))
b=int(input("b= "))
c=int(input("c= "))
d=int(input("d= "))
result=((a-1)+b+(c+1)*d)%2... |
# Operações aritméticas
# soma + subtração - multiplicação * e divisão /
# potencia ** divisão inteira // resto da divisão % raiz quadrada n**(1/2) raiz ao cubo n**(1/3)
# ordem de precedencia: 1o () , 2o **, 3o * ,/, //, % , 4o + e -
print('-=' * 40)
nome = str( input('Qual é o seu nome? '))
print('prazer em ... |
# Expand in both directions of `low` and `high` to find maximum length palindrome
def expand(s, low, high):
while low >= 0 and high < len(s) and s[low] == s[high]:
low = low - 1
high = high + 1
return s[low + 1:high]
def longest_palindromic(s):
# if there empty string
if not s ... |
"""Gunicorn config files."""
# for more directives see:
# http://gunicorn-docs.readthedocs.io/en/latest/settings.html#config-file
# The socket to bind.
bind = '0.0.0.0:8000'
# Numer of worker processes generally in the 2-4 x $(NUM_CORES) range.
workers = 5
# print access/error lines to stdout
accesslog = '-'
errorl... |
FreeSansOblique24pt7bBitmaps = [
0x01, 0xE0, 0x3C, 0x0F, 0x81, 0xE0, 0x3C, 0x07, 0x80, 0xF0, 0x3C, 0x07,
0x80, 0xF0, 0x1E, 0x03, 0xC0, 0xF0, 0x1E, 0x03, 0xC0, 0x78, 0x0F, 0x03,
0xC0, 0x78, 0x0F, 0x01, 0xE0, 0x38, 0x07, 0x00, 0xE0, 0x18, 0x03, 0x00,
0x00, 0x00, 0x00, 0x00, 0xF0, 0x1E, 0x07, 0x80, 0xF0, 0... |
#!/usr/bin/python
'''
FileName: convert_input_to_set.py
Author: John Delgado
Created Date: 8/7/2020
Version: 1.0 Initial Development
This will take the sys.stdin input and convert it into a set and then return the set
'''
def convert_input_to_set(inputVales,debug):
if(not inputVales):
raise Exception("In... |
def monthlyexp(m):
r=m
m=int(input("Hostel Rent"))
m1=int(input("Mobile"))
m2=int(input("Food"))
m3=int(input("Tea"))
m4=int(input("Fish"))
m5=int(input("Roti"))
#print("One Day Expenses Money Total:",m+m1+m2+m3+m4+m5)
a=(m*30+m1*30+m2*30+m3*30+m4*30+m5*30)
print("One Month Expenses Money Total",a)
def food(f):
... |
#!/usr/bin/python
with open('passwd.txt') as fh:
lines = fh.readlines()
for line in lines:
toks = line.split()
r = toks[0]
c = toks[1][:-1]
p = toks[2].strip()
toks2 = r.split('-')
min = toks2[0]
max = toks2[1]
i = p.count(c)
#if i < int(min) or i > int(max):
# print... |
# Crie um programa que leia dois números e mostre a soma entre eles.
n1 = float(input('Digite um primeiro número: '))
n2 = float(input('Digite um segundo número: '))
s = n1 + n2
print(f'A soma desses dois números é {s:.1f} !') |
# 동빈나 취업을 위한 코딩 테스트다.
# 숫자카드게임
# 2중 반복문 구조를 이용
n, m= map(int, input().split())
result= 0
for i in range(n):
data= list(map(input().split()))
min_value= 1001
for a in data:
min_value= min(min_value, a)
result= max(result, min_value)
print(result)
# min()
n,m= map(int, input().split())
result=... |
"""Exceptions for the confprint package.
Custom exceptions used by confprint for more helpful error messages.
"""
class confprintException(Exception):
"""Base class for all confprint exceptions."""
class PropertyError(confprintException):
"""Selection of properties failed."""
|
with open('input.txt') as f:
N, x, y = list(map(int, f.readline().split()))
def lbinsearch(N, x, y, checker):
left = 0
right = min(x, y) * N
while left < right:
middle = (left + right) // 2
if checker(N, x, y, middle):
right = middle
else:
left = middle +... |
class employeeList(viewsets.ModelViewSet):
def get(self,request):
employees = employee.objects.all()
serializer = employeeSerializer(employees,many=True)
return Response(serializer.data)
def post(self,request):
data = request.body
print(data)
emp = employee()
emp.firstname=data['firstname']
emp.last... |
class Person:
def __init__(self, first: str, last: str, age: int):
self.first = first
self.last = last
self.age = age
@property
def email(self):
return f"{self.first}.{self.last}@email.com"
def __str__(self):
return f"{self.first}, {self.last} is {self.age} old"... |
def register_user(r, user_id, display_name, points, rank, country):
"""
Stores the json fields of user data in a redis hash.
Stores the country iso code of a user in a redis set
Adds the user to the leaderboard using player:<guid>
as the key and the points as the value.
Parameters:
... |
'''
Write a program to receive the first and last name of user then print out the message "Hello,
name and surname" and the alias name which derived from the first 2 characters of the first and last
name.
Input: receive first and last name of user.
Output: display 2 lines as follows
The first line shows: "Hello", you... |
#!/usr/bin/env python
header = """ID XXX; XXX; linear; XXX; XXX; XXX; XXX.
XX
AC XXX;
XX
DE {species}, {partial} {gene} gene for {product_DE}, cell line {cell line}, allele {allele}
CC (file created with TypeLoader version {TL_version} based on {db_name} release {db_version})
XX
FH Key Location/Q... |
# Your bot's token -- Current inputted token is a dummy and is just an example
token = 'NTg5NDcyMDExNjI2MjE3NDkw.XQUKnA.2tGpcPM_0S6Y0mAbW5ZukFBQQr4'
# Your bot's prefix. This is what is used in front of every command.
prefix = '$'
# Your bot's description
description = "Bot that does great things"
# A list of people ... |
preco_compras = float(input('Preço das compras: '))
print('''----Forma de Pagamento----
[1] á vista dinheiro/pix
[2] á vista no cartão
[3] 2x no cartão
[4] 3x ou mais no cartão''')
opcao = int(input('Qual sua opção? '))
if opcao == 1:
s = preco_compras - (preco_compras * 0.10)
elif opcao == 2:
s = preco_c... |
__title__ = 'VSoup'
__description__ = 'A Python library for automating interaction with websites'
__url__ = 'https://vsoup.readthedocs.io/'
__github_url__ = 'https://github.com/vaderyang/VSoup'
__version__ = '1.0.0-dev'
__license__ = 'MIT'
|
# 定数
hw = 8
hw2 = 64
dy = [0, 1, 0, -1, 1, 1, -1, -1]
dx = [1, 0, -1, 0, 1, -1, 1, -1]
black = 0
white = 1
legal = 2
vacant = 3
# 座標(y, x)が盤面内にあるかを見る関数
def inside(y, x):
return 0 <= y < hw and 0 <= x < hw
# オセロのクラス
class othello:
# 初期化
def __init__(self):
# 盤面の状態 0: 黒 1: 白 2: 合法手 3: ... |
"""Custom exceptions."""
class FlaskError(Exception):
"""Basic exception for this application."""
class ExperimentTypeSearchParamsMissing(FlaskError):
"""Raised when search params for an experiment type are not defined."""
class SearchOptionNotCustomizeable(FlaskError):
"""Raised when an attempt to pa... |
# Haystack settings for running tests.
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'haystack_tests.db'
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'haystack',
'core',
]
ROOT_URLCONF = 'c... |
def numberOfBoomerangs(self, points):
return sum(
n * (n - 1)
for x1, y1 in points
for n in collections.Counter(
(x1 - x2) ** 2 + (y1 - y2) ** 2
for x2, y2 in points).values()) |
class Dog:
#class attributes are common for every instance of that class
species="Canis familiari"
def __init__(self,name,age):
#instance attributes are defined in a class and are diff for every instance of class
self.name=name
self.age=age
#instance methods
#... |
# COMMON
transformed_text_heading = ["transformedtokens"]
input_file_sheet_name = 0
input_file_columns = ['transformedtokens']
input_file_column = 'transformedtokens'
transformed_text_path_stage_4 = "../data/fluid/preprocessed-text-list-stage-4.xlsx"
symptom_state_output_path = "../data/fluid/output-symptom-state.xlsx... |
##############################################################################
# Parte do livro Introdução à Programação com Python
# Autor: Nilo Ney Coutinho Menezes
# Editora Novatec (c) 2010-2017
# Primeira edição - Novembro/2010 - ISBN 978-85-7522-250-8
# Primeira reimpressão - Outubro/2011
# Segunda reimpressão - ... |
action = 'action'
i = 'i'
id = 'id'
ip = 'ip'
query = 'query'
answer = 'answer'
keys = 'keys'
keys_replic = 'keys_replic'
url = 'url'
html = 'html'
depth = 'depth'
status = 'status'
client_ip = 'client_ip'
client_port = 'client_port'
client_query_id = 'client_query_id'
alive_req = 'alive_req'
alive_rep = 'alive_rep'... |
#DESAFIO 016: Crie um programa que leia um número Real qualquer pelo teclado e mostre na tela a sua porção inteira.
valor = float(input('Digite um valor: '))
inteiro = valor // 1
msg = f'O valor digitado foi {valor} e a sua porção inteira é {inteiro:.0f}'
print(msg) |
_base_ = ['faster_rcnn_r50_fpn_32x2_1x_openimages_challenge.py']
# Use ClassAwareSampler
data = dict(
train_dataloader=dict(class_aware_sampler=dict(num_sample_class=1)))
|
class Output(object):
def __init__(self, connection=None):
self.connection = connection
self.description = None
self.key = None
self.value = None
def __repr__(self):
return 'Output:"%s"="%s"' % (self.key, self.value)
|
"""
LeetCode Problem 528. Random Pick with Weight
Link: https://leetcode.com/problems/random-pick-with-weight/
Written by: Mostofa Adib Shakib
Language: Python
Example:
Array = [1, 9]
When we pick up a at random number out of it, the chance is that 9 times out of 10 we would pick the number 9.
In other words, the ... |
# Faça um programa que leia duas listas e que gere uma terceira com os elementos das duas primeiras
firstList = []
secondList = []
print()
while True:
n = int(input('Digite um número para a primeira lista (0 para terminar): '))
if n == 0:
break
firstList.append(n)
print()
while True:
n = int(... |
# Copyright 2020 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, sof... |
{
"name" : "Facturacion",
"version" : "1.0",
"depends" :[
"base",
"account",
"sale",
"account_voucher",
"fiscaloriginal",
],
"author" : "Odoo ERP",
"description" : """
Modulo de ventas
... |
class Funcionario:
def __init__(self, nome):
self.nome = nome
def registra_horas(self, horas):
print('Horas registradas...')
def mostrar_tarefas(self):
print('Fez muita coisa...')
class Caelum(Funcionario):
def mostrar_tarefas(self):
print('Fez muita coisa, Caelumer...... |
def main(request, response):
body = request.GET.first(b"body", None)
type = request.GET.first(b"type", None)
response.add_required_headers = False
response.writer.write_status(200)
response.writer.write_header(b"content-length", len(body))
response.writer.write_header(b"content-type", type)
... |
n = int(input())
def get_common(num):
if num == 1:
return sum([1])
return sum([i for i in range(1, int(num/2)+1) if num % i == 0] + [num])
cashe = {}
def cal(num):
for i in range(1, num+1):
temp = cashe.get(i, None)
if temp is None:
temp = get_common(i)
if not ... |
def two_sum(nums, target):
my_dict = {}
for i in range(len(nums)):
if target - nums[i] in my_dict:
return [ my_dict[ target - nums[i]], i]
else:
my_dict[nums[i]] = i
return target.values()
if __name__ == '__main__':
nums = [2, 7, 11, 15]
target = 9
prin... |
"""
What is to dream?
A dance of retracing and detracing the steps taken while awake (the life).
"""
class Dream:
def __init__(self, life_events):
self.life_events = life_events
self.day_events = life_events.current_day
pass
def retracing(self):
# retake the self.step
pa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
tweet1 = {
"created_at": "Tue Jun 02 13:22:55 +0000 2015",
"id": 605726286741434400,
"id_str": "605726286741434368",
"text": "At LC for @archemail today: Thinking about overlap between email archiving, web archiving, and social media archiving.",
"sour... |
#
# PySNMP MIB module UPS2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/UPS2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:44:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... |
# Copyright 2021 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... |
# https://leetcode.com/problems/binary-number-with-alternating-bits/description/
# 很多方法,包括往右移动一位再作XOR操作等等。这个方法最直观,变成二进制之后,保证没有连续两个00或者连续两个11就行了。
class Solution:
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
return '00' not in bin(n) and '11' not in bin(n... |
# Copyright (C) 2012 Victor Semionov
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and ... |
"""lpais - use libais to decode ais messages, replacing ais.stream"""
__version__ = '0.0.2'
__author__ = 'Loïc Peron <peronloic.us@gmail.com>'
__all__ = []
|
class HydroShareException(Exception):
def __init__(self, args):
super(HydroShareException, self).__init__(args)
class HydroShareArgumentException(HydroShareException):
def __init__(self, args):
super(HydroShareArgumentException, self).__init__(args)
class HydroShareBagNotReadyExcep... |
# Link : https://leetcode.com/problems/backspace-string-compare/
# Stack approach
# Iterate through the string and push elements in a stack after checking if the element is a "#"
# If the element is a "#" , pop the top ele of the stack
# If not , simply push the ele into the stack
# Convert the stack into a string
... |
'''s0 = 0
s1 = 'M'
s2 = 'F'
while s0 != s1 and s0 != s2:
s0 = str(input('Digite aqui seu sexo [M/F]: ')).upper().strip()
if s0 != s1 and s0 != s2:
print('Você digitou uma opção inválida. Tente novamente.')'''
#versão do Guanabara:
sexo = str(input('Informe seu sexo: [M/F] ')).strip().upper()[0]
whi... |
# https://leetcode.com/problems/trapping-rain-water/
# https://practice.geeksforgeeks.org/problems/trapping-rain-water-1587115621/1#
# For More solutions: https://www.geeksforgeeks.org/trapping-rain-water/
class Solution:
def trap(self, arr: List[int]) -> int:
n = len(arr)
if n==0... |
class Solution:
def shift(self, nums1, j, final_len):
for i in range(final_len, j, -1):
nums1[i] = nums1[i - 1]
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do no... |
'''
This code snippet is to explain how a binary tree is constructed, and one of its implementations in Python3.
We will discussing the basic structure and properties of the binary tree.
A Binary tree is made up of "Nodes". Each node is connected to atmost two other nodes.
We typically draw these two "child" nodes at ... |
# python3
n = int(input())
a = [int(i) for i in input().split()]
m = int(input())
b = [int(i) for i in input().split()]
dp = [[0 for j in range(m+1)] for i in range(n+1)]
for i in range(1, n+1):
for j in range(1, m+1):
if a[i-1] == b[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
... |
def __after_init_updatehub_atmel():
PLATFORM_ROOT_DIR = os.environ['PLATFORM_ROOT_DIR']
append_layers([ os.path.join(PLATFORM_ROOT_DIR, 'sources', p) for p in
[
'meta-atmel',
'meta-updatehub-atmel',
]])
run_after_init(__af... |
budget: float = float(input()) * .9
extras: int = int(input())
extras_costume_price: float = float(input())
extras_costume_expense = (extras * extras_costume_price) * .9 if extras > 150 else extras * extras_costume_price
leftover = round(budget - extras_costume_expense, 2)
if leftover < 0:
print('Not enough money... |
"""
Description: model-dependent wiring and behavior
"""
# copy and paste definitions for your model at the bottom of this file
# model 0000 (my prototype)
BTN_R = 6
BTN_L = 5
ACTIVE_HIGH = 0
LCD_RS = 24
LCD_EN = 25
LCD_D4 = 8
LCD_D5 = 7
LCD_D6 = 12
LCD_D7 = 16
# models 0001-0009 (v2 wiring)
# LCD pins on exterior e... |
class Validator:
@staticmethod
def raise_if_string_is_empty_or_whitespace(string, error_message):
if string.strip() == "":
raise ValueError(error_message)
@staticmethod
def raise_if_value_equal_or_less_than_zero(value, error_message):
if value <= 0:
raise ValueEr... |
# Write Python class to perform addition of two complex numbers using binary + operator overloading.
class Complex:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __add__(self, other):
return Complex(self.real + other.real, self.imaginary + other.i... |
class Charter:
TRACK_NAMES = [
'ExpertSingle',
'ExpertDoubleBass',
'ExpertDoubleRhythm',
'ExpertDoubleGuitar',
'ExpertKeyboard',
'HardSingle',
'HardDoubleBass',
'HardDoubleRhythm',
'HardDoubleGuitar',
'HardKeyboard',
'MediumSing... |
# Lexer that produces a sequence of tokens (keywords + ANY).
class Token:
def __init__(self, type, word_index=-1, extra=''):
self.type = type
self.extra = extra
self.word_index = word_index
self.done = False
def __eq__(self, o):
return self.type == o
def __repr__(s... |
# Use "e" to convert a number into scientific number format (with a lower-case e):
txt = "We have {:e} chickens."
print(txt.format(5))
|
class ReportBuilder:
def __init__(self, filename):
self.filename = filename
def buildReport(self, data):
print('Calling buildReport from ReportBuilder.')
print('Filename is: {}'.format(self.filename))
raise NotImplementedError()
|
# -*- coding: utf-8 -*-
x, y, z = 111, 222, 333 # 同时给多个变量赋值
x, y, z = z, y, x # 同时交换多个变量的值
print("x:{} --- y:{} --- x:{}".format(x, y, z))
values = 123, 456, 789 # 创建元组
a, b, c = values # 元组解包
print("values:{} --- a:{} --- b:{} --- c:{}".format(values, x, y, z))
values2 = {'AAA': 123, 'BBB': 456, 'CCC': 789}
k, ... |
def grep(pattern):
print("Searching for %s" % pattern)
n = 1
while True:
print("RUNNING num is %d" % n)
line = (yield) # 此时已经把yield变成一个协程了,它将不再包含任何初始值
print("have been seed value.")
if pattern in line: # 相反,要从外部传值给它,传值通过send()方法向它传值
print(line)
... |
def solution(ranks):
n = 0
m = 0
r = 0
s = sorted(ranks)
print(s)
for i in range(len(s)-1):
d = s[i+1] - s[i]
if d == 0:
if i != (len(s)-2):
n += 1
elif d == 1:
m += 1
else:
n = 0
r = n + m
print(r)
solut... |
token_query = '''
SELECT
T.token,
count(*) as C
FROM "TokenLinks" TL JOIN "Token" T
ON T.tokenid = TL.target
WHERE TL.source =
(SELECT tokenid FROM "Token" T WHERE T.token = :token)
AND TL.distance > -4 AND TL.distance < 28 and T.dateid=:id
GROUP BY T.token HAVING coun... |
def e_crescente(a, b, c, cond=True, condd=True, conddd=True):
if cond:
return c, b, a
elif condd:
return b, c, a
elif conddd:
return a, b, c
elif a == b > c:
return c, a, b
elif a == c > b:
return b, a, c
elif b == c > a:
return a, b, c
elif c ... |
###### FlightPort scripts #####
def BuildFlightPortPanel(UserPanel, FlightPortInfo, UnitInfo):
# UnitInfo.DisplayMessage('BuildFlightPortPanelCalled')
UserPanel.Clear()
UserPanel.SetTitle('Flight Deck Control')
# draw buttons for heading row
UserPanel.AddItem('Unit Type','',10,10,80,12)
UserPa... |
class LanguageDictionary:
"""Add padding to sentences, add <START> and <END> token to target sentence and convert each token to the index of the corresponding vocabulary.
Args:
source_sentences (array of array of str): Tokenized sentences in English.
target_sentences (array of array of str): T... |
# Leia um número n e determine os 50 primeiros termos da série n, (n - 1), (n - 2), (n - 3), ..., 1.
# Em seguida calcule e imprima o resultado da soma do primeiro termo + último termo, segundo termo + penúltimo termo, terceiro termo + antepenúltimo termo, ...
def soma(lista):
soma = lista[0] + lista[-1]
... |
#
# @lc app=leetcode id=34 lang=python3
#
# [34] Find First and Last Position of Element in Sorted Array
#
# @lc code=start
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
l, r = 0, len(nums) - 1
l_index = r_index = -1
while l <= r:
if nums[l... |
#Make a copy of this file, and enter your information into the dictionary fields. Name the file 'secret.json'.
#For the ID's in disocrd, make sure your values are ints, not strings.
jsonfo = {"TOKEN": "YOUR BOT TOKEN",
"red_id":"REDDIT CLIENT ID",
"red_secret": "REDDIT CLIENT SECRET",
"red_usr_agent": "REDDIT USER AGEN... |
class personaje():
def __init__(self, FechaDeCreacion, EpisodiosDondeAparece, NumeroEpisodiosDondeAparece, Genero, Id_Personaje, Imagen, Location_Name, Location_URL, Nombre, Origen_Name, Origen_URL, Especie, Status, Tipo, URL):
self._FechaDeCreacion = FechaDeCreacion
self._EpisodiosDondeAparece = E... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
Topic: list数据结构
Desc :
"""
def list_methods():
alist = [1, 2, 3, 4]
# 结论就是讲某个数组插入数组alist的位置i上,执行alist[i:i]=[...]
alist[4:4] = [9, 10, 11, 12]
# 删除某个或者某字段的list,请使用del
del alist[1:3]
# 情况list
del alist[:]
print(alist)
def transp... |
#!/usr/bin/env python3
def sum_exists(ls, target):
seen = set()
for n in ls:
if target - n in seen:
return True
seen.add(n)
return False
with open('input.txt', 'r') as infile:
numbers = [int(n) for n in infile]
for i in range(25, len(numbers)):
if not sum_exists(numbe... |
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://root: @127.0.0.1:3306/mbti"
SECRET_KEY = "iljxlijO*JCl:Idjlisjf8zj8*E"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30 |
nome = str(input('qual o seu nome completo?: ')).strip()
d = nome.split()
print('o seu primeiro nome é {}'.format(d[0]))
print('o seu ultimo nome é {}'.format(d[len(d)-1]))
|
def maiusculas(frase):
cont = len(frase) - 1
i = 0
frase_m = ""
while i <= cont:
if ord(frase[i]) < 91 and ord(frase[i]) > 64:
frase_m += frase[i]
i += 1
return frase_m
|
# Approach 1
def reverseString1(inpStr: str) -> str:
optStr = inpStr[::-1]
return optStr
# Approach 2
def reverseString2(inpStr: str) -> str:
optStr = ""
for ele in inpStr:
optStr = ele + optStr
return optStr
print(reverseString1("krupesh"))
print(reverseString2("krupesh"))
|
"""Version details for ovrlib"""
__title__ = "ovrlib"
__description__ = "Library to interface with per-state online voter registration APIs"
__url__ = "https://github.com/vote/state-registration-apis"
__version__ = "0.0.6"
__author__ = "Sage Weil"
__author_email__ = "sage@newdream.net"
__license__ = "Apache 2.0"
__mai... |
for i in range(int(input())):
n = int(input())
for j in range(n):
a = [int(k) for k in input().split()]
print(sum(a[1:len(a)//2+1]))
|
N = int(input())
p = list(map(int, input().split()))
dp = [[False] * (100 * 101) for _ in range(N + 1)]
dp[0][0] = True
for i in range(N):
for j, dpj in enumerate(dp[i - 1]):
if dpj:
dp[i][j] = True
dp[i][j + p[i]] = True
ans = 0
for dpi in dp[N - 1]:
if dpi is True:
ans ... |
def get_row(s):
s = s[:-3]
s = s.replace('F', '0')
s = s.replace('B', '1')
return int(s, 2)
def get_col(s):
s = s[-3:]
s = s.replace('L', '0')
s = s.replace('R', '1')
return int(s, 2)
def get_code(s):
return get_row(s) * 8 + get_col(s)
#nums = ["FBFBBFFRLR", "BFFFBBFRRR", "FF... |
# Aufgabe 1 - Prüfung Primzahl
def is_prime(n):
if n < 1:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
# Aufgabe 2 - Bruch Addierer
def add_frac(z1,n1,z2,n2):
gn=int(n1*n2) #gn = gemeinsamer Nenner
z1_neu=z1*n2
z2_n... |
"""
utils
~~~~~
Helper routines & 3rd party interfaces can be placed in this
module.
"""
|
config = {
'label2ind': {
'pos': 0,
'neg': 1
},
'model_type': 'bert-base-uncased',
'task2ner_rel': {
"mte": set([
('Target', 'Component', 'Contains'),
('Target', 'Property', 'HasProperty')
]),
"chemprot":set([('Chemical', 'Protein', 'CPR:3'),('Chemical', 'Protein', 'CPR:4'), ('Chemica... |
def print_corr(tica, feat, ic=0, num=20, save=False, outname=None):
''' helpful printing function for finding correlations between features and tICs
.. math::
\mathbf{Corr}(X_i - \mu_i, \mathbf{\theta}_j) = \frac{1}{\sigma_{X_i - \mu_i}}\sum_l \sigma_{(X_i - \mu_i)(X_l - \mu_l} \mathbf{U}_{li}
... |
x, y = 1, 1
mode = ['L', 'R', 'U', 'D']
move_x = [0, 0, -1, 1]
move_y = [-1, 1, 0, 0]
n = int(input())
plan = list(input().split())
for s in plan:
i = mode.index(s)
if s == mode[i]:
_x = x + move_x[i]
_y = y + move_y[i]
if _x < 1 or _x > n or _y < 1 or _y > n:
continue
x, y = _x, _y
print(x... |
countries = input().split(', ')
capitals = input().split(', ')
dd = zip(countries, capitals)
result = {x: y for (x, y) in dd}
[print(f'{key} -> {value}') for (key, value) in result.items()]
|
def __virtual__():
if __salt__["cmd.which"]("cpanm"):
return True
return (False, "cpanm is not installed")
def install(module, upgrade=True):
"""
Install or upgrade perl module with cpanm script
"""
ret = {}
# dont upgrade if upgrade = False
if is_installed(module) and not upg... |
class SingletonMetaClass(type):
def __init__(cls, name, bases, dict):
super(SingletonMetaClass, cls).__init__(name, bases, dict)
original_new = cls.__new__
def my_new(_cls, *args, **kwargs):
if _cls.instance is None:
_cls.instance = original_new(_cls, *args, **kw... |
"""Version details for simple-credentials
This file shamelessly taken from the requests library/simple-salesforce"""
__title__ = 'simple-credentials'
__description__ = 'A basic credentials parser.'
__url__ = 'https://github.com/mutenpo/simple-credentials'
__version__ = '0.0.4'
__author__ = 'Po'
__author_email__ = 'po... |
for t in range(int(input())):
N = int(input())
P = sorted(list(map(int,input().split())), reverse = True)
profit = 0
for i in range(N):
if P[i] - i > 0 :
profit += P[i] - i
else:
break
print(profit%1000000007)
|
""" Copyright (c) Microsoft Corporation. All Rights Reserved. """
""" Licensed under the MIT license. See LICENSE file on the project webpage for details. """
OEMBED_SERVICES = {
'youtube': {
'regex': '(https?:\/\/(www\.)?)(youtube\.com|youtu\.be|youtube\.googleapis.com)\/(?:embed\/|v\/|watch\?v=|watch\?.... |
"""
https://www.hackerrank.com/contests/projecteuler/challenges/euler016
Project Euler #16: Power digit sum
"""
#!/bin/python3
for _ in range(int(input())):
num = list(str(2**int(input())))
print(sum([int(x) for x in num]))
|
def computador_escolhe_jogada(n, m):
if n <= m:
pecas_comp = n
n = 0
else:
a = 1
while a < m:
resto = n - a
if resto % (m + 1) == 0:
n -= a
pecas_comp = a
a = m
else:
a += 1
r... |
class Node():
def __init__(self, val, next=None, prev=None):
self.item = val
self.next = next
self.prev = prev
class LinkedList():
def __init__(self):
self.first = None
self.last = None
def add_first(self, val):
if self.first == None:
self.first =... |
lovely_loveseat_description = """
Lovely Loveseat. Tufted polyester blend on wood. 32 inches high x 40 inches wide x 30 inches deep. Red or white.
"""
lovely_loveseat_price = 254.00
stylish_settee_description = """
Stylish Settee. Faux leather on birch. 29.50 inches high x 54.75 inches wide x 28 inches ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.