content stringlengths 7 1.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 Lee McCuller <mcculler@mit.edu>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline ... |
class User:
def __init__(self, username, first, last):
self.username = username
self.password = None
self.first = first
self.last = last
self.bio = "Datau"
self.pic = "default.png" |
"""(Retorno de Investimento a 7%) Reimplemente o Exercício 2.12 para utilizar um laço que calcule e mostre a quantia de dinheiro que você terá ao fim dos anos 1 a 30."""
p = 1000 # montante inicial
r = 7 / 100 # taxa anual de juros
for n in range(1, 31):
a = p * (1 + r) ** n
print(f'Ao fim do {n}º ano, voc... |
cont = 0
cont2 = 0
stop = 0
maior = 0
menor = 0
while stop != 'n':
cont += 1
n = int(input('Digite um número: '))
cont2 += n
stop = str(input('Quer continuar? [s/n] ')).lower().strip()[0]
print('=-='*10)
if cont == 1:
maior = menor = n
else:
if n > maior:
maior = ... |
# appfat.cpp
MakeNameEx(LocByName("sub_401000"), "j_appfat_cpp_init", SN_NOWARN)
MakeNameEx(LocByName("sub_401005"), "appfat_cpp_init", SN_NOWARN)
MakeNameEx(LocByName("sub_401010"), "appfat_cpp_free", SN_NOWARN)
MakeNameEx(LocByName("sub_40102A"), "GetErr", SN_NOWARN)
MakeNameEx(LocByName("sub_4010CE"), "GetDDE... |
class reconnectionService():
def __init__(self, pebble, message):
self.targetPebble = pebble
def reconnect(self):
"""Reconnect Pebble"""
self.targetPebble.disconnect()
self.targetPebble.connect()
self.targetPebble.run_async()
self.targetPebble.startAppMessage... |
"""
Dictionary - key, value pairs
Sets - collection of distinct values
"""
# Enumerate
"""
A lot of times when dealing with iterators, we also get a need to keep a count of iterations.
Python eases the programmers’ task by providing a built-in function enumerate() for this task.
Enumerate() method adds a count... |
#revendo conceitos para trabalhar com listas
# Primeiro conceito a ser visto será p sort, aonde ele tem como objetivo
# a lista tando do menor para o maior, quanto o contrário do maior para
# o menor
# Criando uma lista para usar de exemplo,e adionando números randônicos, no caso os
# elementos da lista
lista_de_exe... |
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2018-12-29 14:41:46
# @Last Modified by: 何睿
# @Last Modified time: 2018-12-29 15:16:53
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
c... |
# -*- coding: utf-8 -*-
def xstr(s):
if s is None:
return ""
else:
return str(s)
|
"""Module initialization."""
__version__ = "0.0.1"
__name__ = "rxn_aa_mapper"
|
'''
Created: 2019-09-21 13:35:07
Author : YukiMuraRindon
Email : rinndonn@outlook.com
-----
Description: 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
'''
class Solution:
def isValid(self, s):
while '{}' in s or '()' in s or '[]' in s:
... |
fruits = ['grape', 'raspberry', 'apple', 'banana']
fruits_copy = fruits.copy()
print(f"fruits: {fruits}")
sorted_fruits = sorted(fruits)
assert fruits == fruits_copy
print(f"sorted(fruits): {sorted_fruits}")
sorted_fruits = sorted(fruits, reverse=True)
assert fruits == fruits_copy
print(f"sorted(fruits, reverse=True... |
""" blueprint for a sample human being """
class Human:
"""
blueprint for a sample human being.
expected structure:
human_attributes = {
"name" : "Bob",
"age" : 38,
"gender" : "male",
"profession": "coder"
}
"""
def __init__(self, human_attri... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""INTERNAL RUNS A COMMAND - Usage: run_command <arg 1> ... <arg n> [do_run_info=1]"""
INTERNAL = True
def func(root, display, *args, **kwargs):
# command name
command = args[0]
consoleout = []
try:
# Test For Index Air
args = args[1]
... |
# http://codeforces.com/problemset/problem/59/A
text = input()
upper_counter = 0
lower_counter = 0
for char in text:
if char.isupper():
upper_counter += 1
elif char.islower():
lower_counter += 1
if lower_counter > upper_counter:
text = text.lower()
elif upper_counter > lower_counter:
... |
class Base():
def __init__(self, agent, base_location):
self.base_location = base_location
self.agent = agent
self.mineral_fields = []
self.geysers = []
self.compute_mineral_fields()
self.compute_geysers()
def get_mineral_fields(self):
return se... |
# output: ok
assert str(None) == 'None'
assert str(1) == '1'
assert str(1.2) == '1.2'
assert str('a') == 'a'
assert str(()) == '()'
assert str((1,)) == '(1,)'
assert str(('a',)) == "('a',)"
assert str((1, 2, 3)) == '(1, 2, 3)'
assert str([]) == '[]'
assert str(['a']) == "['a']"
assert str([1, 2, 3]) == '[1, 2, 3]'
ass... |
# Represents a single node in the Trie
class TrieNode:
def __init__(self, end_of_word=False):
# Initialize this node in the Trie
# Indicates whether the string ends here is a valid word
self.end_of_word = end_of_word
# A dictionary to store the possible characters in this node
... |
host = "PASTE_YOUR_HOST_URL_HERE"
asrkey = 'PASTE_YOUR_ASR_API_KEY_HERE'
ttskey = 'PASTE_YOUR_TTS_API_KEY_HERE'
speaker = "nick"
|
# -*- coding: utf-8 -*-
#
# Copyright 2011, Toru Maesaka
# Copyright 2014, Carlos Rodrigues
#
# Redistribution and use of this source code is licensed under
# the BSD license. See COPYING file for license description.
#
class KyotoTycoonException(Exception):
pass
# EOF - kt_error.py
|
#
# Catching this Exception captures all known/planned error conditions
#
class OAuthSSHError(Exception):
"Base class for all custom exceptions in this module"
def __init__(self, msg):
super(OAuthSSHError, self).__init__(msg)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 30 11:34:12 2021
@author: Erlend Tøssebro
"""
def enkel_funksjon():
print("Skriver ut testetekst")
print("En linje til i blokken")
print("Test")
enkel_funksjon()
print("Prøver en gang til")
enkel_funksjon()
|
def factorial(n):
# test for a base case
if n == 0:
return 1
else:
return n*factorial(n-1) # make a calculation and a recursive call
print(factorial(4))
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, head: ListNode) -> int:
binaryString = ""
node = head
while(node != None):
binaryString... |
#
# PySNMP MIB module HH3C-IFQOS2-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-IFQOS2-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:27: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... |
# ANSI color codes
RED = "\x1b[31m"
GREEN = "\x1b[32m"
RESET = "\x1b[0m"
|
def dict_eq(d1, d2):
return (all(k in d2 and d1[k] == d2[k] for k in d1)
and all(k in d1 and d1[k] == d2[k] for k in d2))
assert dict_eq(dict(a=2, b=3), {'a': 2, 'b': 3})
assert dict_eq(dict({'a': 2, 'b': 3}, b=4), {'a': 2, 'b': 4})
assert dict_eq(dict([('a', 2), ('b', 3)]), {'a': 2, 'b': 3})
a = {'g... |
def square(number):
if number <= 0 or number > 64:
raise ValueError("square must be between 1 and 64")
return 2**(number - 1)
def total():
return 2**64 - 1
|
class BoaExitException(Exception):
pass
class BoaRunBuildException(Exception):
pass
|
class Solution:
def findLengthOfLCIS(self, nums: List[int]) -> int:
result = 0
anchor = 0
for ii, i in enumerate(nums):
if (ii > 0 and nums[ii-1] >= nums[ii]):
anchor = ii
result = max(result, ii - anchor + 1)
return result
|
class Solution:
def halvesAreAlike(self, s: str) -> bool:
n = len(s)
half_n = int(n/2)
# print(half_n)
first = s[:half_n]
second = s[half_n:]
count_first = 0
count_second = 0
s = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
for i... |
arr = [23, 34, 25, 12, 54, 11, 90]
def bubbleSort(arr):
"""
>>> bubbleSort(arr)
[11, 12, 23, 25, 34, 54, 90]
"""
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr... |
BOT_NAME = 'amazon2'
SPIDER_MODULES = ['amazon2.spiders']
NEWSPIDER_MODULE = 'amazon2.spiders'
ROBOTSTXT_OBEY = False
CONCURRENT_REQUESTS = 32
COOKIES_ENABLED = False
SPIDER_MIDDLEWARES = {
'amazon2.middlewares.AmazonSpiderMiddleware.AmazonSpiderMiddleware': 543,
}
DOWNLOADER_MIDDLEWARES = {
'scrapy.down... |
def good(num, name=None):
b = bad(num)
u = ugly(name)
return f"The GOOD({num}, name={name}), The BAD->{b}, and The UGLY->{u}"
def bad(num):
u = ugly(num)
return f"The BAD({num}) got UGLY->{u}"
def ugly(num):
return 42 / num
|
class AppControlInterface:
def __init__(self):
pass
def scroll_up(self, amount):
pass
def scroll_down(self, amount):
pass
|
"""I suck in the dust."""
class Vacuum(object):
def input(self):
"Dust."
def output(self):
print('Sucking in dust...')
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Created: 02/07/2022(m/d/y) 16:44:11 UTC from "Archnemesis" data
desc = "Challenge Autogen"
# Base type : settings pair
items = {
}
|
class FourCal:
def setdata(self, first, second):
self.first = first
self.second = second
def sum(self):
result = self.first + self.second
return result
def sub(self):
result = self.first - self.second
return result
def mul(self):
re... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
# {
# 'target_name': 'files_icon_button',
# 'includes': ['../../../compile_js2.gypi'],
# },
# {
# 'target_name': 'fil... |
"""
[issue2]
$ echo TEST1
. # doctest: +ELLIPSIS
T...ST1
$ echo TEST2
. # doctest: +ELLIPSIS
...EST2
"""
|
# sample function to get a prediction from the model
def getPrediction(text):
if type(text) is str:
return len(text)
else:
return -1
|
"""
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try cod... |
class Services:
ALL_SERVICES = set()
UNMUTED = set()
MUTED = set()
LATEST = ''
def add_latest(name):
Services.LATEST = name
def add(name):
Services.ALL_SERVICES.add(name)
Services.UNMUTED.add(name)
add_latest(name)
def remove(name):
try:
Services.ALL_SERVICES.remove(nam... |
valores = (int(input('Digite um número: ')),
int(input('Digite outro número: ')),
int(input('Digite mais um número: ')),
int(input('Digite o ultimo número: ')))
print(f'O valor 9 apareceu {valores.count(9)} vezes')
if 3 in valores:
print(f'O primeiro vaor 3 apareceu na {valores.inde... |
# -*- coding: utf-8 -*-
"""
559. Maximum Depth of N-ary Tree
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal,
each group of childr... |
notas = [[['A', 'E', 'I', 'O', 'U', 'L', 'N', 'R', 'S', 'T'], 1],
[['D', 'G'], 2],
[['B', 'C', 'M', 'P'], 3],
[['F', 'H', 'V', 'W', 'Y'], 4],
[['K'], 5],
[['J', 'X'], 8],
[['Q', 'Z'], 10]]
def score(word):
total = 0
word = word.upper()
for letra in wo... |
"""Commands for chooks.py."""
__all__ = [
'add',
'disable',
'execute',
'install',
'list',
'remove',
]
|
# [1052] 爱生气的书店老板
# https://leetcode-cn.com/problems/grumpy-bookstore-owner/description/
# * algorithms
# * Medium (50.70%)
# * Total Accepted: 29.5K
# * Total Submissions: 50.8K
# * Testcase Example: '[1,0,1,2,1,1,7,5]\n[0,1,0,1,0,1,0,1]\n3'
# 今天,书店老板有一家店打算试营业 customers.length 分钟。每分钟都有一些顾客(customers[i])会进入书店,所有... |
def splitDate(date):
splitup = date.split('.')
return splitup[1], splitup[0], splitup[2]
|
class StyleSelector(object):
"""
Provides a way to apply styles based on custom logic.
StyleSelector()
"""
def SelectStyle(self,item,container):
"""
SelectStyle(self: StyleSelector,item: object,container: DependencyObject) -> Style
When overridden in a derived class,returns a System.W... |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the... |
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
for x in range(len(nums)):
if nums[x] >= target:
return x
return (len(nums)) |
#!/usr/bin/python
class TOSSerialReceptionError:
def __init__(self, chaine = "Vide"):
self.ch = chaine;
def __str__(self):
return self.ch;
class TOSSerialPacket:
"""Data structure that defines the content of a serial packet"""
def __init__(self):
messageType = 0;
dest = 0;
src = 0;
len = 0;
group ... |
# A. Генератор скобок
# ID успешной посылки 66098296
COMBINATIONS = {'2': 'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
def gen_combination(d... |
# -*- coding: utf-8 -*-
__author__ = "venkat"
__author_email__ = "venkatram0273@gmail.com"
# def comments_and_doc_strings() -> None:
# """
# These are multi-line comments.
# Used to document specific information about the function.
# These are called docstrings as well and can be accessed through func... |
"""
List of 3rd party test dependencies. Generated by bazel-deps.
"""
def list_dependencies():
return [
{
"bind_args": {
"actual": "@com_typesafe_play_twirl_api_2_11",
"name": "jar/com/typesafe/play/twirl_api_2_11"
},
"import_args": {
... |
# -*- coding: utf-8 -*-
'''
File name: code\nontransitive_sets_of_dice\sol_376.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #376 :: Nontransitive sets of dice
#
# For more information see:
# https://projecteuler.net/problem=376
# Prob... |
def build_triangle(nlines):
triangle = []
if (nlines >= 1):
linha1 = [1]
triangle.append(linha1)
if (nlines >= 2):
linha2 = [1, 1]
triangle.append(linha2)
if (nlines >= 3):
previous_line = [1, 1]
for linha in range(3, nlines + 1):
... |
def analisa(num):
if num%2==0:
print(f"{num} é um numero par!")
else:
print(f"{num} é um numero impar!")
num = int(input("Digite um numero: "))
analisa(num) |
#ordem de precedencia () parênteses
# ** que é a potencia
# * mltiplicação / divisão // divisão inteira % resto
n1=int(input('Digite um número:'))
n2=int(input('Digite outro número:'))
soma=n1+n2
subt=n1-n2
multip=n1*n2
div=n1/n2
di=n1//n2
resto=n1%n2
pot=n1**n2
print('O resultado da soma é {},\n da subtração é {}, do... |
def gcd(m,n):
while n>0:
t=m%n
m=n
n=t
return m
input();A=list(map(int,input().split()))
input();B=list(map(int,input().split()))
AA=1; BB=1
for i in A: AA*=i
for i in B: BB*=i
result=gcd(AA,BB)
if result >= 10**9: print("%09d" % (result%(10**9)))
else: print(result) |
"""文字列基礎
大文字→小文字に変換する lowerメソッド
[説明ページ]
https://tech.nkhn37.net/python-upper-lower-translation/#_lower
"""
# 大文字→小文字の変換
data = 'Python PROJECT'
print(f'元の文字列: {data}')
print(f'lower: {data.lower()}')
|
class MessageBuilder:
DEFAULT_MESSAGE = """\
・+ボタンを押して位置情報を送ると、現在地に一番近い観測地点を登録します。再度位置情報を送るまで、観測地点は変わりません。
・毎日7時に、一日の暑さ指数(WBGT)の予測をお届けします。
・暑さ指数が31℃以上になったときにもお知らせします。
・「今」「明日」「明後日」(ひらがなでもOK)と話しかけると、その日の暑さ情報の予測をお知らせします。"""
MSG_FOOTER = """
※暑さ指数の単位は℃ですが、気温とは異なります。詳しくは環境省熱中症予防情報サイトへ(http://www.wbgt.env.go.jp/)"""... |
"""
Scenarios:
Parameters (some/all/None) -> reduce
Result (1, 2) -> reduce
Combinations of above -> reduce
Filter[parameter],Filter[result],Filter[parameter+result],None
= (3 + 2 + 6) * 4 = 44 tests
test: data recovered (shape,dtype, values), description recovered, tasks marked as complete, locations in index, subse... |
def title_card(code_name):
print('\n~~~~~~~~~~~~~~~~~~~~~~~')
print(code_name)
print('~~~~~~~~~~~~~~~~~~~~~~~ \n')
|
# 155. Min Stack
# ttungl@gmail.com
class MinStack(object):
# using list array
# runtime: 72 ms
def __init__(self):
self.stack = []
def push(self, x):
if not self.stack:
self.stack.append((x, x))
else:
self.stack.append((x, min(x, self.stack[-1][1]))) # keep track o... |
def check_similar_sequences(sequences):
"""
takes a dictionary of sequences, removes the gaps and checks which sequences are similar
return a dictionary of a group number as key and the similar sequence id as a list as vlaue
:param sequences: a dictionary of sequences
:return groups: a dictionary o... |
# -*- coding: utf-8 -*-
# Copyright 2013 Lyft
#
# 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... |
class Solution(object):
def pivotIndex(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return -1
N = len(nums)
sums = [0] * (N + 1)
for i in range(N):
sums[i + 1] = sums[i] + nums[i]
for i in range(N):
... |
# This file contains defaults that this module uses
# Max allowed for assumed safe request, any higher than this
# Will raise a RateLimitReached Exception
# If the rate limiter cant assume a safe request
# Due to the assumption being to risky at this point
max_safe_requests = 40
# quater of safe requests
max_ongoing... |
x = 10
def foo(x):
y = x * 2
return bar(y)
def bar(y):
y = x / 2
return y
z = foo(x)
|
# Copyright (c) 2020 Vishnu J. Seesahai
# Use of this source code is governed by an MIT
# license that can be found in the LICENSE file.
MIN_CONF = '6'
MAX_CONF = '9999999'
|
class Solution(object):
def generatePalindromes(self, s):
"""
:type s: str
:rtype: List[str]
"""
dic = {}
half = []
res = []
for c in s:
dic[c] = dic.get(c, 0) + 1
odd, even = 0, 0
for c in dic:
if dic[c] % 2 == ... |
class Node:
def __init__(self, item, next):
self.item = item
self.next = next
class Stack:
def __init__(self):
self.last = None
def push(self, item):
self.last = Node(item, self.last)
def pop(self):
item = self.last.item
self.last = self.last.next
... |
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
# dfs solution to solve this problem
nums = [-float('inf')] + nums + [-float('inf')]
lo, hi = 0, len(nums)-1
while lo < hi:
mid = (lo+hi)//2
if nums[mid] > nums[mid-1] and nums[mid] > ... |
"""
Unit Tests for lfs library
"""
__author__ = 'Stephen Brown (Little Fish Solutions LTD)'
|
# __init__.py
# Copyright 2011 Roger Marsh
# Licence: See LICENCE (BSD licence)
"""results berkelelydb interface.
"""
|
'''
凑零钱
'''
# 暴力
def coinChange(coins,amout):
def dp(n):
# base case
if n == 0: return 0
if n < 0: return -1
res = float('INF')
for coin in coins:
subproblem = dp(n - coin)
if subproblem == -1:continue
res = min(res,subproblem)
re... |
a = 2 < 3
b = 2 + 4
c = (1 <= 2 ) and (1 <= 3)
x = 1 + 2 * 3
y = 1 * 2 + 3
x = 2+3 < 2+1 or 2 < 3 and not not True
y = not True and False |
def test_view(app, client):
resp = client.options('/test/list/route')
assert resp.status_code == 200
assert resp.json == {
'facets': [{'code': 'category', 'facet': {'label': 'my.own.facet.label'}}],
'filters': []
}
# TODO: implement ?ln=
# resp = client.options('/test/list/route... |
'''THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE
DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OT... |
class deque:
def __init__(self):
self.items=[]
def isEmpty(self):
return self.item==[]
def addRear(self,item):
self.items.append(item)
def addFront(self,item):
self.items.insert(0,item)
def removeFront(self):
return self.pop()
def removeRear(self):
... |
# Creating a dictionary
crew_details = {
"Pilot": "Kumar",
"Co-Pilot": "Raghav",
"Head-Strewardess": "Malini",
"Stewardess": "Mala"
}
print(crew_details["Pilot"])
print("\nIterating the dictionary using items function")
for key, value in crew_details.items():
print(key, ":", value)
# Usually whil... |
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
x=[]
for i in nums:
x.append(sum([1 for y in nums if y<i]))
return x
|
def score_submission(submission):
# first remove existing leaderboard entries
# read in scores dictionary, ex:
# scoring_program_output = {
# "RESULTS": [
# ("Score", 1),
# ],
# "ALTERNATE_RESULTS": [
# ("Score", 2),
# (... |
'''
Write a function, gooseFilter / goose-filter / goose_filter / GooseFilter, that
takes an array of strings as an argument and returns a filtered array
containing the same elements but with the 'geese' removed.
The geese are any strings in the following array, which is pre-populated in
your solution:
geese = ["Afri... |
print('--------------处理异常--------------')
class MyError(Exception):
pass
try:
raise MyError()
except (NameError, ValueError) as ex:
print(f'This is a NameError:{ex}')
except MyError:
print('This is MyError')
raise
else:
print('Else clause')
finally:
print('This is finally clause')
|
l = float(input("Digite a medida do lado do quadrado: "))
a = l ** 2
dobro = a * 2
print ("O dobro da área do quadrado de lado %5.2f é %5.2f" % (l, dobro))
|
# -*- coding: utf-8 -*-
"""Top-level package for deploy_ova."""
__author__ = """Michael Palmer"""
__email__ = 'palmertime@gmail.com'
__version__ = '0.1.0'
|
# Copyright 2018 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... |
# Variables can be used to hold information.
# Integer-type
initial_amount = 100
# Float-type
interest_rate = 5.0
# Integer-type
num_of_years = 7
# The type of "final_amount" must be deduced from the number-types in the expression.
# The type of "final_amount" will be the least precise type that's involved in the c... |
#
# Author VinhLH <vinh.le@zalora.com>
# Copyright Mar 2016
#
# Configs
host = ''
port = 8888
workDir = '/Users/vinhlh/Works/test'
log = 'server.log' |
def register(mf):
mf.register_defaults({
"fuzzy": __file__,
"fuzzychild_nonunique": __file__
})
|
# === General ===
# Can be 'curl' or 'sftp'
uploader = 'curl'
# Enable or disable thumbnail previews in the notification (only for image uploads, broken on some distros)
enable_thumbnails = False
# === SFTP-related ===
# (S)FTP credentials, only if you want to use SFTP for uploads
# Set all to None that you don’t need... |
"""Integration tests for the pyWriter project.
Test helper module.
For further information see https://github.com/peter88213/PyWriter
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
def read_file(inputFile):
try:
with open(inputFile, 'r', encoding='utf-8'... |
# !/usr/bin/env python3
# Author: C.K
# Email: theck17@163.com
# DateTime:2021-09-14 21:20:08
# Description:
class Solution:
def fractionToDecimal(self, numerator: int, denominator: int) -> str:
if numerator % denominator == 0:
return str(numerator // denominator)
sign = '' if numerator ... |
valor = int(input())
print('{}'.format(valor))
numero100 = valor//100
print('{} nota(s) de R$ 100,00'.format(numero100))
valor -= numero100*100 #valor - valor (menos ele mesmo)
numero50 = valor//50
print('{} nota(s) de R$ 50,00'.format(numero50))
valor -= numero50*50
numero20 = valor//20
print('{} nota(s) de R$ 20,... |
def func_read_in_pattern_file(pattern_file_path):
pattern_dict = {}
with open(pattern_file_path, 'r') as file:
for line in file:
line_lst = line.strip().split(",")
pattern_dict[line_lst[0]] = [line_lst[1], line_lst[2], line_lst[3], line_lst[4]]
return pattern_dict |
# Copyright (c) 2015 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'test_default',
'type': 'executable',
'sources': ['hello.cc'],
},
{
'target_name'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.