content stringlengths 7 1.05M |
|---|
#
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2016, Ilya Etingof <ilya@glas.net>
# License: http://pysnmp.sf.net/license.html
#
# PySNMP MIB module SNMP-COMMUNITY-MIB (http://pysnmp.sf.net)
# ASN.1 source file:///usr/share/snmp/mibs/SNMP-COMMUNITY-MIB.txt
# Produced by pysmi-0.0.5 at Sat Sep 19 16:28... |
# hangman_lib.py
# A set of library functions for use with your Hangman game
def print_hangman_image(mistakes=6):
"""Prints out a gallows image for hangman. The image printed depends on
the number of mistakes (0-6)."""
if mistakes <= 0:
print(''' ____________________
| .__________________|
| | / / ... |
def apply(df, model, rel_ev, rel_act, parameters=None):
if parameters is None:
parameters = {}
ret = {}
for persp in rel_ev:
df = rel_ev[persp]
df = df[df["event_activity_merge"].isin(rel_act[persp])]
df = df.groupby([persp, persp+"_2", "event_activity_merge"]).first()
... |
class ListReader():
def __init__(self, aList: list):
self.list = aList
def __enter__(self) -> list:
print("will print a list:")
return self.list
def __exit__(self, expType, expVal, expTrace):
print("end")
aList = [1, 2, 3, 4, 5, 6]
with ListReader(aList) as lr:
print(... |
class RateLimit:
def __init__(self):
self.rateLimitType = ""
self.interval = ""
self.intervalNum = 0
self.limit = 0
class ExchangeFilter:
def __init__(self):
self.filterType = ""
self.maxOrders = 0
class Symbol:
def __init__(self):
self.symbol =... |
# Faça um programa que leia uma frase pelo teclado e mostre:
# Quantas vezes aparece a letra "A".
# Em que posição ela aparece a primira vez.
# Em que posiçao ela aparece a última vez.
frase = str(input("Digite uma Frase qualquer: "))
frase = frase.lower()
print('Letra A:',frase.count('a'))
print('Primeiro A pos:',... |
"""
redis client and lua script api
"""
VERSION = "0.0.1" |
"""-----------------------------------------------------------------------------
finalize.py (Last Updated: 10/16/2020)
The purpose of this script is to finalize the rt-cloud session. Specifically,
here we want to dowload any important files from the cloud back to the stimulus
computer and maybe even delete files fro... |
def remove_middle(a, b, c):
cross = (a[0] - b[0]) * (c[1] - b[1]) - (a[1] - b[1]) * (c[0] - b[0])
dot = (a[0] - b[0]) * (c[0] - b[0]) + (a[1] - b[1]) * (c[1] - b[1])
return cross < 0 or cross == 0 and dot <= 0
def convex_hull(points):
spoints = sorted(points)
hull = []
for p in spoint... |
# Copyright (c) 2012 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': 'api',
'type': 'static_library',
'sources': [
'<@(schema_files)',
],
# TODO(j... |
#!/usr/bin/env python
# encoding: utf-8
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
# adjacency matrix of the directed graph
self.graph = collections.defaultdict(list)
for to_node, from_node in prerequisites:
self.graph[from_node... |
def file_from_tar(context, tar, member):
return tar.extractfile(member).read()
def static_file(context, path):
with open(path, 'rb') as fobj:
return fobj.read()
|
#Find the BITWISE NOT of the given number
a = int(input())
b = ~a
print(b)
|
#!/usr/bin/env python3
def merge_chars(string, block):
for i in range(0, len(string), block):
s = ''
for c in string[i:i+block]:
if c not in s:
s += c
print(s)
if __name__ == '__main__':
merge_chars(input(), int(input()))
|
# Crie uma tupla preenchida com os 20 primeiros colocados da tabela do Campeonato Brasileiro de Futebol, na ordem de
# colocação. Depois mostre:
# Apenas os 5 primeiros colocados
# Os últimos 4 colocados da tabela
# Uma lista com os times em ordem alfabética
# Em que posição na tabela está o time da Chapecoense
colo... |
def solve():
direction = 0 # north = 0, east = 1, south = 2, west = 3
x = 0
y = 0
moves = [x for x in input().split(',')]
visited = []
for elem in moves:
elem = elem.strip()
turn = elem[0]
length = int(elem[1:])
if (turn == "R"):
direction = abs((direction + 1) % 4)
elif (turn == "L"):
direction ... |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
DEVELOPER_SIGN_ON_CLIENT_ID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"
AZURE_VSCODE_CLIENT_ID = "aebc6443-996d-45c2-90f0-388ff96faa56"
VSCODE_CREDENTIALS_SECTION = "VS C... |
"""
Conditioner
===========
Create simple 'if this then that' style rules in your Django application. Comes with a bunch of ready to use actions
and conditions, but is also easily extensible and allows model specific actions/conditions.
"""
default_app_config = 'conditioner.apps.ConditionerAppConfig'
__title__ = 'dja... |
def Glados(thoughts, eyes, eye, tongue):
return f"""
{thoughts}
{thoughts}
\#+ \@ \# \# M#\@
. .X X.%##\@;# \# +\@#######X. \@#%
,==. ,######M+ -#####%M####M- \#
:H##M%:=##+ .M##M,;#####/+#######% ,M#
.M########= =\@#\@.=#####M=M#######= X#
:\@\@MMM##M. -##M.,#####... |
live = 'yes'
def love():
live
|
class Solution(object):
def removeCoveredIntervals(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
# Sort by start point.
# If two intervals share the same start point
# put the longer one to be the first.
intervals.sort(key=lamb... |
# exercise-02 Length of Phrase
# Write the code that:
# 1. Prompts the user to enter a phrase:
# Please enter a word or phrase:
# 2. Print the following message:
# - What you entered is xx characters long
# 3. Return to step 1, unless the word 'quit' was entered.
while True:
input_word_phrase = input('P... |
KEY_PRESSES = {
'1ADGJMPTW* #': 1,
'BEHKNQUX0': 2,
'CFILORVY': 3,
'23456S8Z': 4,
'79': 5
}
def presses(phrase):
total = 0
for a in phrase.upper():
for k, v in KEY_PRESSES.iteritems():
if a in k:
total += v
break
return total
|
# 04 sKeyword Arguments
# def increment(number, by):
# return number + by
# result = increment(2, 1)
# print(result)
# It also works like this
def increment(number, by):
return number + by
print(increment(2, by=1))
# by=1 Its the keyword arguent, if a function as multiple arguments, the code can be more... |
with open("day16.txt") as f:
data = f.readline()
data = data.split(",")
programs = [chr(i) for i in range(97, 113)]
for instruction in data:
type_ = instruction[0]
if type_ == "s":
length = int(instruction[1:])
programs = programs[-length:] + programs[:len(programs)-length]
if type_ == ... |
#
# Simple class for dealing with Parameter.
# Parameter has a name, a value, an error and some bounds
# Names are also latex names.
class Parameter:
def __init__(self, name, value, err=0, bounds=None, Ltxname=None):
self.name = name
if Ltxname:
self.Ltxname = Ltxname
else:
... |
def enter_text(text):
print(text)
input("Press Enter key.")
return(0)
def nostop(text):
enter_text(text)
return(0)
def message(text):
enter_text(text)
exit(0)
def error(text):
enter_text(text)
exit(9001)
def fatal(text):
error(text)
#return true if yes, false if no
def yes_n... |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
"""
mayor = 0
suma = 0
for _ in range(10):
edad = int(input("Ingresar edad: "))
if edad >= 18:
mayor += 1
suma += edad
print(f"Promedio: {suma / 10}")
print(f"Mayores de edad: {mayor}") |
lista = [1, 13, 15, 7]
lista_animal = ['cachorro', 'gato', 'elefante', 'arara']
#Ordenando a lista
lista.sort()
lista_animal.sort()
print(lista)
print(lista_animal)
#Revertendo a ordem da lista
lista_animal.reverse()
print(lista_animal) |
class xcconfig_item_base(object):
def __init__(self, line):
line_end = line.find('//');
if line_end > 0:
line = line[:line_end];
self.contents = line;
self.type = 'EMPTY';
def __repr__(self):
if self.isValid():
return '(%s : %s : %s)' % (... |
# -*- coding: utf-8 -*-
"""
A module containing the Edge Validator functions which can be registered as callbacks to
:class:`~nodeeditor.node_edge.Edge` class.
Example of registering Edge Validator callbacks:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
You can register validation callbacks once for example on t... |
"""
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
"""
# pre-order, in-order, a... |
'''
Take name and two grades from many students
ONE LIST -> Nested list
Show a final grade from each student with the average grade
first show the final grade
Then ask if want to get the individual grade
'''
main_grade = list()
while True:
name = str(input('Name: '))
grade1 = float(input('First grade: '))
g... |
class Bag:
def __init__(self, bag_name):
self.name = bag_name
self.children_names = [bag_name]
self.children_counts = [1]
self.contained_bags = 0
def is_empty(self):
return len(self.children_names) == 0
def contains(self, bag_name):
return b... |
def schoolbook_operand_scanning(SRC1, SRC2, DEST, t, n):
"""
This generates a simple static schoolbook multiplication of n by n;
assumes SRC1 and SRC2 registers with pointers to where n elements live,
writes 2n-1 elements to the DEST pointer
"""
yield "mov r11, #0"
for i in range(2*n - 1):... |
# Networking settings
HOST = 'localhost'
PORT = 8000
TIMEOUT = 500
KEEP_ALIVE = False
# Validator settings
VALIDATOR_HOST = 'localhost'
VALIDATOR_PORT = 4004
# Database settings
DB_HOST = 'localhost'
DB_PORT = 28015
DB_NAME = 'marketplace'
# Runtime settings
DEBUG = True
# Secret keys
# WARNING! These defaults are ... |
"""
Counting Sort is kind of algorithm that works only to integers.
The idea is to pre-allocate array of arrays with the len of source list,
then traverse unsorted list putting each num at correct place (index) using some key function (`j % len(src)-1` in my case),
finally traverse that array of arrays items in order... |
"""
Exceptions for events app
To have so many exception types might be a little over the top, but ...
"""
class EventException(Exception):
"""Base exception type for events app"""
class UserRegistrationException(EventException):
"""Base class for exceptions that can be raised when a user trys to register f... |
#Faça um programa que leia tres numeros e mostre qual é o maior e qual é o menor.
numero = float(input('Digite um numero: '))
numeroII = float(input('Digite outro numero: '))
numeroIII = float(input('Digite outro numero: '))
if numero > numeroII:
maior = numero
else:
maior = numeroII
if maior > numeroIII:
... |
ROLES = ["administrator", "developer", "newswriter", "repositories"]
# Scenario: Try to add a role that 'admin' already has.
try:
output = instance.execute(
["sudo", "criticctl", "addrole",
"--name", "admin",
"--role", "administrator"])
expected_output = "admin: user already has role ... |
assert 1 + 1 == 2
try:
assert 1 + 1 == 3
except AssertionError as err:
print(err.__class__)
try:
assert 2 + 2 == 5, 'Only for very large values of 2'
except AssertionError as err:
print(err)
"""
<class 'AssertionError'>
Only for very large values of 2
"""
|
'''
Created on Aug 15, 2009
@author: santiago
'''
|
class KeyValueStorage:
def __init__(self, name, env, wtx, dupsort=False):
self.name = name.encode("utf-8")
self.env = env
self.main_db = self.env.open_db(self.name + b'_main_db', txn=wtx, dupsort=dupsort)
def put(self, key, value, wtx, dupdata=False):
return wtx.put( bytes(key), bytes(value), db=... |
a = input()
print(a)
name = input("Enter your name: ")
print(f'Welcome {name}!')
age = input("Enter your age:")
print(age)
print("Hello " + input("Enter your name ")+"!")
None
weapons = None
print(weapons)
name = input("Enter your name")
# print(name)
print(f'Welcome {name} !')
print("... |
def parse_bytes(value, default=0, suffixes='bkmgtp'):
# 将输入的内容(500K,2.5M)转化为字节的int
try:
last = value[-1].lower()
except(TypeError, KeyError, IndexError):
return default
if last in suffixes:
mul = 1024 ** suffixes.index(last)
value = value[:-1]
else:
mul = 1
... |
# edad = int(input("Escribe tu edad: "))
# if edad > 17:
# print('Eres mayor de edad')
# else:
# print('Eres menor de edad')
numero = int(input('Escribe un número: '))
if numero > 5:
print('Es mayor a 5')
elif numero == 5:
print('Es igual a 5')
else:
print('Es menor a 5')
#if True:
# pass
#else:... |
def scala_proto_register_toolchains():
native.register_toolchains("@io_bazel_rules_scala//scala_proto:default_toolchain")
def scala_proto_register_enable_all_options_toolchain():
native.register_toolchains("@io_bazel_rules_scala//scala_proto:enable_all_options_toolchain")
|
class Generator(nn.Module):
def __init__(self):
super().__init__()
self.noise_branch = nn.Sequential(
nn.ConvTranspose2d(noise_dim, d * 8, kernel_size=4, stride=1, padding=0, bias=False),
norm_layer(d * 8),
nn.ReLU(True)
)
self.label_branch = nn.S... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
t = int(input())
answer = []
for a in range(t):
val = int(input())
if(val == 2):
answer.append(2)
elif(val%2 == 1):
answer.append(1)
else:
answer.append(0)
for b in answer:
print(str(b))
|
# Module version
py_version_info = (1, 0, 8)
js_version_info = (0, 1, 13)
# Module version accessible using vitessce.__version__
__version__ = '%s.%s.%s' % (
py_version_info[0], py_version_info[1], py_version_info[2])
|
############### задача 11: номер последнего числа, равного х
def main():
err, num = find('in.txt')
if err==0:
print("answer", num)
elif err==1:
print("Can't open the file")
elif err==2:
print("Bad value")
elif err==3:
print("File is empty")
else:
print("Er... |
#isEqual(cad1: "abcd", cad2= "abcd") -> True
def isEqual(cad1,cad2):
diccCad = {}
for key in cad1:
if key in diccCad:
diccCad[key] += 1
else:
diccCad[key] = 1
for key in cad2:
if key in diccCad:
diccCad[key] -= 1
else:
return False
for (key) in diccCad:
if diccCad[key] !... |
# Copyright (C) 2019-2021 HERE Europe B.V.
# SPDX-License-Identifier: MIT
"""Project version information."""
# Module version
version_info = (1, 1, 1)
# Module version accessible using here_map_widget.__version__
__version__ = "%s.%s.%s" % (version_info[0], version_info[1], version_info[2],)
EXTENSION_VERSION = "^1... |
def run():
my_list = [1, 'Hello', True, 4.5]
my_dict = {'firstname': 'Hector', 'lastname': "Olvera"}
super_list = [
{"firstname": 'Facundo', 'lastname': 'García'},
{'firstname': 'Miguel', 'lastname': 'Torres'},
{'firstname': 'Pepe', 'lastname': 'Rodelo'},
]
super_dict = {
... |
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
SECRET_KEY = 1
INSTALLED_APPS = [
'django_counter_cache_field',
'tests',
]
DEBUG = False
SITE_ID = 1
|
description = 'setup for the status monitor'
group = 'special'
_reactorBlock = Block('Reactor', [
BlockRow(Field(name='Reactor power', dev='ReactorPower', width=6),
)
],
)
_shutterBlock = Block('Shutter', [
BlockRow(Field(name='Prim. shutter', dev='prim_shutt'),
Field(name='Sec.... |
size = int(input())
matrix = []
for c in range(size):
col = [int(n) for n in input().split(' ')]
matrix.append(col)
primary_diagonal_sum = 0
for i in range(size):
primary_diagonal_sum += matrix[i][i]
print(primary_diagonal_sum)
|
class DetectBaseNotImplementedError(NotImplementedError):
pass
class DetectBase:
def _notimplestr(self, param):
return (
"resource detect must have "
f"{param}\" property."
)
@property
def resource(self):
raise DetectBaseNotImplementedError(
... |
#
# PySNMP MIB module CISCO-LWAPP-DOT11-CCX-CLIENT-DIAG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-DOT11-CCX-CLIENT-DIAG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:05:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
#... |
b1 = True
b2 = True
tab_TT = (b1 == True and b2 == False) or (b1 == False and b2 == True)
## version courte
## tab_TT = (b1 and not b2) or (not b1 and b2)
b1 = True
b2 = False
tab_TF = (b1 == True and b2 == False) or (b1 == False and b2 == True)
b1 = False
b2 = True
tab_FT = (b1 == True and b2 == False) or (b1 == Fals... |
userInput = input("Enter your Sentence: ").upper()
translated = ""
i = len(userInput)-1
while i >= 0:
translated += userInput[i]
i-=1
print(translated) |
"""
Tipo string
Em Python, um dado é considerado do tipo string sempre que:
- Estiver entre àspas simples -> 'uma string', '234', 'a', 'True', '42,3'
- Estiver entre àspas simples -> "uma string", "234", "a", "True", "42,3"
- Estiver entre àspas simples -> '''uma string''', '''234''', '''a''', '''True''', '''42,3'''
... |
def part1(lines):
return 0
def part2(lines):
return 0
if __name__ == '__main__':
with open('input.txt', 'r') as f:
lines = f.read().splitlines()
print(part1(lines))
print(part2(lines))
|
class ValidatorLR0001:
value = None
def __get__(self, obj, objtype=None):
return self.value
def __set__(self, obj, value):
if value is not None:
if not isinstance(value, LR0001):
raise TypeError(f'Expected {value!r} to be LR0100 object')
self.value = va... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
load(":oss_shim.bzl", "target_utils")
def _wrap_bash_build_in_common_boilerplate(
self_dependency,
bash,
rule_type,
... |
def generate_config(context):
"""
Generates config
"""
project_id = context.properties['project']
billing = context.properties['billing']
concurrent_api_activation = context.properties['concurrent_api_activation']
resources = []
for index, api in enumerate(context.properties['apis']):
... |
class Singleton:
_instance = None
def __new__(cls):
if not isinstance(cls._instance, cls):
cls._instance = super(Singleton, cls).__new__(cls)
return cls._instance
|
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
d = {}
for letter in J:
d[letter] = 1
count = 0
for letter in S:
if letter in d:
count += 1
return count |
# -*- coding: utf-8 -*-
#
#
class ResultStr(object):
"""docstring for ResultStr"""
def __init__(self, arg=None):
super(ResultStr, self).__init__()
self.arg = arg
def TrainingResultStr(self, epoch, loss, acc, duration, training=True):
loss_str = self.Loss2Str(loss, decimal_places=... |
{
'conditions': [
['OS=="win"', {
'variables': {
'MAGICK_ROOT%': 'C:\\Program Files\\ImageMagick-6.9.12-Q16\\',
# download the dll binary and check off for libraries and includes
'OSX_VER%': "0",
}
}],
['OS=="mac"', {
'variables': {
# matches 10.9.X , 10.1... |
def main() -> None:
K = 10**4
def normalize(number: str) -> int:
parts = number.split(".")
if len(parts) == 1:
return int(parts[0]) * K
a, b = parts
return int(a) * K + int(b) * 10 ** (4 - len(b))
cx, cy, r = map(normalize, input().split())
def ... |
#
# PySNMP MIB module NBS-SFF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NBS-SFF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:17:37 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, 0... |
farmer = {
'kb': '''
Farmer(Mac)
Rabbit(Pete)
Mother(MrsMac, Mac)
Mother(MrsRabbit, Pete)
(Rabbit(r) & Farmer(f)) ==> Hates(f, r)
(Mother(m, c)) ==> Loves(m, c)
(Mother(m, r) & Rabbit(r)) ==> Rabbit(m)
(Farmer(f)) ==> Human(f)
(Mother(m, h) & Human(h)) ==> Human(m)
''',
# Note that this order of conjuncts
# would r... |
"""Configuration of OSP-core warnings."""
attributes_cannot_modify_in_place = True
"""Warns when a user fetches a mutable attribute of a CUDS object.
For example `fr = city.City(name='Freiburg', coordinates=[1, 2]);
fr.coordinates`.
"""
|
# Copyright 2010 Curtis McEnroe <programble@gmail.com>
# Licensed under the GNU GPLv3
class Scope:
def __init__(self, parent=None):
self.bindings = {}
self.parent = parent
def __getitem__(self, key):
# If bound in this scope, return that
if self.bindings.has_key(key):
... |
def soma(x: float, y: float) -> float:
return x + y
def main() -> None:
print(soma(10, 40))
print(soma(30, 30))
if __name__== '__main__':
main() |
l=float(input('Diga a largura da sua parede em metros: '))
a=float(input('Diga a altura da sua parede em metros: '))
print('A área de sua parede tem {:.2f} m² e para pintá-la '.format(l*a),end=
'você precisará de {:.2f} litros de tinta.'.format((l*a)/2))
|
rol_enviar_notificaiones_servidor = "Server"
time_resend_mail = 300
minimo_nivel_bateria = 30 #3.0V |
#!/usr/bin/env python
__author__ = "Christopher and Cody Reichert"
__copyright__ = "Copyright 2015, SimplyRETS Inc. <support@simplyrets.com>"
__credits__ = ["Christopher Reichert", "Cody Reichert"]
__license__ = "MIT"
__version__ = "0.1"
__maintainer__ = "Christopher Reichert"
__email__ = "christopher@simplyrets.com"
... |
STDIN_FILENO = 0
STDOUT_FILENO = 1
STDERR_FILENO = 2
DEFAULT_PORT = 0xdb9
DEFAULT_IP = '127.0.0.1'
DEFAULT_CONNECT_TIMEOUT = 10.
|
#14) Longest Collatz sequence
#The following iterative sequence is defined for the set of positive integers:
#n → n/2 (n is even)
#n → 3n + 1 (n is odd)
#Using the rule above and starting with 13, we generate the following sequence: 13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
#It can be seen that this sequence (starting... |
"""
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
"""
class BinaryTree(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = No... |
#Simay Hoşmeyve
#180401017
degerler = []
with open ("veriler.txt","r")as dosya:
for line in dosya.readlines():
degerler.append(int(line))
def textYazdir(katsayi,sonuc,ilk,son):
text = open("sonuc.txt", "a",encoding="utf-8")
text.write(str(len(katsayi)-1)+'. derece\n')
text.write('Kat... |
s=input().split()
n1=str(s[0].replace('7','0'))
op=s[1]
n2=str(s[2].replace('7','0'))
res=str(int(n1)+int(n2)) if op=='+' else str(int(n1)*int(n2))
res=int(res.replace('7','0'))
print(res)
|
class MyMsp430Constants:
ACT_PXY_ADC = 0x40
ACT_PXY_DACDMA = 0x41
ACT_PXY_NMI = 0x42
ACT_PXY_PORT1 = 0x43
ACT_PXY_PORT2 = 0x44
ACT_PXY_TIMERA0 = 0x45
ACT_PXY_TIMERA1 = 0x46
ACT_PXY_TIMERB0 = 0x47
ACT_PXY_TIMERB1 = 0x48
ACT_PXY_UART0RX = 0x49
ACT_PXY_UART0TX = 0x4... |
def prenom():
prenom = input("Bonjour ! Quel est votre prénom?\n")
if (prenom == 'Johnny'):
print("Je te déteste!")
elif(prenom =='Paul'):
print("Hello my love !")
elif(prenom =='Marc'):
print("Hello my love !")
elif(prenom =='Ismael'):
print ("salut, désolé p... |
# A Python program to demonstrate both packing and
# unpacking.
# A sample python function that takes three arguments
# and prints them
def fun1(a, b, c):
print(a, b, c)
# Another sample function.
# This is an example of PACKING. All arguments passed
# to fun2 are packed into tuple *args.
def fun2(*args):
... |
# Coding Challenge 2
### Chelsea Lizardo
### NRS 528
#
#
#3 Ask the user for an input of their current age, and tell them how many years until they reach retirement (65 years old).
name = input("What is your name: ")
age = int(input("How old are you: "))
year = str((2021 - age)+65)
#print name input + " will b... |
__name__ = "bootstrap-scoped"
__version__ = "0.1.0"
__url__ = "https://github.com/achillesrasquinha/bootstrap-scoped"
__author__ = "Achilles Rasquinha"
__email__ = "achillesrasquinha@gmail.com"
__description__ = "Scope your Bootstrap assets in a jiffy!"
__license__ = "MIT"
__keywords__... |
"""
Copy out of the top of sympy.core.compatibility as of
b8aa2de87d537eddde044c13f2eaaab99a5dcfe7
This can be deleted when we depend on sympy 0.7.0 or later
"""
"""
Reimplementations of constructs introduced in later versions of Python than we
support.
"""
# These are in here because telling if something is an itera... |
def process_image(img):
# 1) Define source and destination points for perspective transform
dst_size = 5
source = np.float32([[200, 95],[300, 140],[10, 140],[118, 95]])
destination = np.float32([[165, 135],[165, 145],[155, 145],[155, 135]])
# 2) Apply perspective transform
warped = perspect_tran... |
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
i, j = 0, (len(s) - 1)
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
i... |
# -*- encoding: utf-8 -*-
def spam():
pass
def grok():
pass
blah = 42
__all__ = {'spam', 'grok'} |
description = 'NOK5a using Beckhoff controllers'
group = 'lowlevel'
instrument_values = configdata('instrument.values')
showcase_values = configdata('cf_showcase.showcase_values')
optic_values = configdata('cf_optic.optic_values')
tango_base = instrument_values['tango_base']
code_base = instrument_values['code_base... |
# Crie um programa que leia um número inteiro e mostre na tela se ele é
# PAR ou ÍMPAR.#
#minha resolução do desafio
n = int(input('Digite um número qualquer: '))
if n % 2 == 0:
print('O número {} é Par'.format(n))
else:
print('O número {} é Ímpar'.format(n))
# resolução do Professor Guanabara
"""
número = i... |
# coding: utf-8
class StackUnderflow(ValueError):
pass
class SStack(object):
"""采用动态顺序表实现的栈"""
def __init__(self):
self._elems = []
def is_empty(self):
return len(self._elems) == 0
def top(self):
if self.is_empty():
raise StackUnderflow("in SStack.top")
... |
DATA_DIR = '/floyd/input'
PTB_DIR = '_ptb'
BROWN_DIR = '_brown'
GUTENBERG_DIR = '_gutenberg'
BIBLE_DIR = '_bible'
WIKITEXT2_DIR = '_wikitext2'
WIKITEXT103_DIR = '_wikitext103'
TRAIN = 'train'
TEST = 'test'
VAL = 'val'
MODEL_DIR = 'bin'
FLOYD = True
|
val = int(input('Digite o valor que você quer sacar: R$ '))
total = val
ced = 50
totced = 0
while True:
if total >= ced:
total -= ced
totced += 1
else:
print(f'Total de {totced} cédulas de {ced} reais')
if ced == 50:
ced == 20
elif ced == 20:
ced =... |
def textPreprocessing(text):
p_words = ['.','?','!',':',';','-','[',']','{','}','(',')','’',',','"',]
s_words = ['i', 'a', 'about', 'am', 'an', 'are', 'as', 'at', 'be', 'by', 'for', 'from', 'how', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'what', 'when', 'where', 'who', 'will', 'wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.