content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def HextoBin(n):
if isinstance(n,str) == False:
strnum = str(n)
hexnum = int(strnum,16)
binnum = bin(hexnum)
return binnum
else:
hexnum = int(n, 16)
binnum = bin(hexnum)
return binnum
| def hexto_bin(n):
if isinstance(n, str) == False:
strnum = str(n)
hexnum = int(strnum, 16)
binnum = bin(hexnum)
return binnum
else:
hexnum = int(n, 16)
binnum = bin(hexnum)
return binnum |
class Student:
passingMark = 60
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __str__(self):
return '%s received a %s.' %(self.name, self.marks)
def passOrFail(self):
if self.marks <= Student.passingMark:
self.mark... | class Student:
passing_mark = 60
def __init__(self, name, marks):
self.name = name
self.marks = marks
def __str__(self):
return '%s received a %s.' % (self.name, self.marks)
def pass_or_fail(self):
if self.marks <= Student.passingMark:
self.marks = 'fail'
... |
def grader(paths):
out=[]
penalty=0
for path in paths:
for i in range(1,len(path)-1):
hm1=terrain.height_from_coordinates(path[i-1])
h=terrain.height_from_coordinates(path[i])
hp1=terrain.height_from_coordinates(path[i+1])
d1=dist(pa... | def grader(paths):
out = []
penalty = 0
for path in paths:
for i in range(1, len(path) - 1):
hm1 = terrain.height_from_coordinates(path[i - 1])
h = terrain.height_from_coordinates(path[i])
hp1 = terrain.height_from_coordinates(path[i + 1])
d1 = dist(pa... |
# class LLNode:
# def __init__(self, val, next=None):
# self.val = val
# self.next = next
class Solution:
def solve(self, l0, l1):
num1 = ''
num2 = ''
while l0:
num1 += str(l0.val)
l0 = l0.next
while l1:
num2 ... | class Solution:
def solve(self, l0, l1):
num1 = ''
num2 = ''
while l0:
num1 += str(l0.val)
l0 = l0.next
while l1:
num2 += str(l1.val)
l1 = l1.next
ll_sum = str(int(num1[::-1]) + int(num2[::-1]))[::-1]
head = ll_node(int... |
print('Welcome to my first converter!!!!')
num = input('Whats your number???')
if '0000' == num:
print('The number is 0!!!')
if '0001' == num:
print('The number is 1!!!')
if '0010' == num:
print('The number is 2!!!')
if '0011' == num:
print('The number is 3!!!')
if '0100' == num:
print('The num... | print('Welcome to my first converter!!!!')
num = input('Whats your number???')
if '0000' == num:
print('The number is 0!!!')
if '0001' == num:
print('The number is 1!!!')
if '0010' == num:
print('The number is 2!!!')
if '0011' == num:
print('The number is 3!!!')
if '0100' == num:
print('The number i... |
class TelnetInfo(object):
def __init__(self, api_client):
self.api_client = api_client
def get_telnet_status(self):
jsondata = self.api_client.get('telnet/server')
if not self.api_client.error:
return jsondata['is_telnet_server_enabled']
elif self.api_client.error... | class Telnetinfo(object):
def __init__(self, api_client):
self.api_client = api_client
def get_telnet_status(self):
jsondata = self.api_client.get('telnet/server')
if not self.api_client.error:
return jsondata['is_telnet_server_enabled']
elif self.api_client.error:
... |
n,k=map(int,input().split())
arr=list(map(int,input().split()))
brr=[int(i) for i in arr]
brr.sort()
if brr[-1]-brr[0]>k:
print("NO")
exit()
print("YES")
for i in arr:
for j in range(1,i+1):
x=j%k if j%k!=0 else k
print(x,end=" ")
print() | (n, k) = map(int, input().split())
arr = list(map(int, input().split()))
brr = [int(i) for i in arr]
brr.sort()
if brr[-1] - brr[0] > k:
print('NO')
exit()
print('YES')
for i in arr:
for j in range(1, i + 1):
x = j % k if j % k != 0 else k
print(x, end=' ')
print() |
class Solution:
def findCelebrity(self, n: int) -> int:
celebrity = 0
for i in range(1,n):
if not knows(i,celebrity):
celebrity = i
for i in range(n):
if celebrity !=i and (knows(celebrity,i) or not knows(i, celebrity)):
... | class Solution:
def find_celebrity(self, n: int) -> int:
celebrity = 0
for i in range(1, n):
if not knows(i, celebrity):
celebrity = i
for i in range(n):
if celebrity != i and (knows(celebrity, i) or not knows(i, celebrity)):
return -1... |
'''
Author : MiKueen
Level : Easy
Problem Statement : Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
In... | """
Author : MiKueen
Level : Easy
Problem Statement : Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
In... |
_base_ = [
'./train.py',
'../_base_/models/segmentors/seg_semisl.py'
]
optimizer = dict(
type='SGD',
lr=1e-3,
momentum=0.9,
weight_decay=0.0005
)
optimizer_config = dict(
_delete_=True,
grad_clip=dict(
# method='adaptive',
# clip=0.2,
# method='default', # ?
... | _base_ = ['./train.py', '../_base_/models/segmentors/seg_semisl.py']
optimizer = dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0005)
optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=40, norm_type=2))
lr_config = dict(_delete_=True, policy='customstep', by_epoch=True, gamma=0.1, step=[200, 250], ... |
_base_ = ['./slowonly_r50_8x8x1_256e_kinetics400_rgb.py']
# model settings
model = dict(backbone=dict(depth=101, pretrained=None))
# optimizer
optimizer = dict(
type='SGD', lr=0.1, momentum=0.9,
weight_decay=0.0001) # this lr is used for 8 gpus
# learning policy
lr_config = dict(
policy='CosineAnnealing'... | _base_ = ['./slowonly_r50_8x8x1_256e_kinetics400_rgb.py']
model = dict(backbone=dict(depth=101, pretrained=None))
optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
lr_config = dict(policy='CosineAnnealing', min_lr=0, warmup='linear', warmup_ratio=0.1, warmup_by_epoch=True, warmup_iters=34)
total_e... |
'''https://leetcode.com/problems/palindrome-number/'''
class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
return x==x[::-1]
| """https://leetcode.com/problems/palindrome-number/"""
class Solution:
def is_palindrome(self, x: int) -> bool:
x = str(x)
return x == x[::-1] |
#
# PySNMP MIB module CISCO-SWITCH-NETFLOW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SWITCH-NETFLOW-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:13:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, constraints_union, single_value_constraint) ... |
# Base Parameters
assets = asset_list('FX')
# Trading Parameters
horizon = 'H1'
pair = 5
# Mass Imports
my_data = mass_import(pair, horizon)
# Indicator Parameters
lookback = 20
def ma(Data, lookback, close, where):
Data = adder(Data, 1)
for i in range(len(Data)):
... | assets = asset_list('FX')
horizon = 'H1'
pair = 5
my_data = mass_import(pair, horizon)
lookback = 20
def ma(Data, lookback, close, where):
data = adder(Data, 1)
for i in range(len(Data)):
try:
Data[i, where] = Data[i - lookback + 1:i + 1, close].mean()
except IndexError:
... |
class Product(object):
def __init__(self, price, id, quantity):
self.price = price
self.id = id.capitalize()
self.quantity = quantity
class Inventory(object):
def __init__(self, products=[], value=0):
self.products = products
self.value = value
def add_to_inv(self, product):
self.products.append(prod... | class Product(object):
def __init__(self, price, id, quantity):
self.price = price
self.id = id.capitalize()
self.quantity = quantity
class Inventory(object):
def __init__(self, products=[], value=0):
self.products = products
self.value = value
def add_to_inv(self... |
class WordParameterList(object):
def __init__(self, bytes_, offset):
self.ELEMENT_SIZE = 2 * 3
self.bytes = bytes_
bytes_.seek(offset)
self.size = int.from_bytes(bytes_.read(4), 'little')
self.offset = offset + 4
self.is_copied = False
def storage_size(self):
... | class Wordparameterlist(object):
def __init__(self, bytes_, offset):
self.ELEMENT_SIZE = 2 * 3
self.bytes = bytes_
bytes_.seek(offset)
self.size = int.from_bytes(bytes_.read(4), 'little')
self.offset = offset + 4
self.is_copied = False
def storage_size(self):
... |
def fake_bin(x:str):
my_str = []
for num in x:
if int(num) >= 5:
num = 1
my_str.append(num)
else:
num = 0
my_str.append(num)
return (''.join(map(str, my_str))) | def fake_bin(x: str):
my_str = []
for num in x:
if int(num) >= 5:
num = 1
my_str.append(num)
else:
num = 0
my_str.append(num)
return ''.join(map(str, my_str)) |
#print("Hello world through Jenkins")
print("2nd assignments question")
with open("file.txt","w") as f:
f.write('Rajaprasad')
with open("file.txt","r") as f1:
f1.read()
| print('2nd assignments question')
with open('file.txt', 'w') as f:
f.write('Rajaprasad')
with open('file.txt', 'r') as f1:
f1.read() |
# Black Heaven Inside: Core (350060160) | Stage 1 Lotus Boss | Used to show Lotus (stage1) HP as well as warp party into the next map upon Lotus' death
BLACK_HEAVEN_CORE = 8240103 # Stage 1
sm.showHP(BLACK_HEAVEN_CORE)
sm.waitForMobDeath(BLACK_HEAVEN_CORE)
sm.invokeAfterDelay(7000, "warp", 350060180, 0) # Warp ... | black_heaven_core = 8240103
sm.showHP(BLACK_HEAVEN_CORE)
sm.waitForMobDeath(BLACK_HEAVEN_CORE)
sm.invokeAfterDelay(7000, 'warp', 350060180, 0) |
def zap_started(zap, target):
zap.ascan.import_scan_policy("/zap/wrk/backend.policy")
zap.ascan.set_option_default_policy("Spring Boot Backend")
print("zap_started(target={})".format(target))
def zap_active_scan(zap, target, policy):
print("zap_active_scan(target={}, policy={})".format(target, policy))... | def zap_started(zap, target):
zap.ascan.import_scan_policy('/zap/wrk/backend.policy')
zap.ascan.set_option_default_policy('Spring Boot Backend')
print('zap_started(target={})'.format(target))
def zap_active_scan(zap, target, policy):
print('zap_active_scan(target={}, policy={})'.format(target, policy))... |
class InvalidImageUriException(Exception):
'''
Represents a failure due to unexpected s3_uri format.
'''
pass
class InvalidImageExtensionException(Exception):
'''
Represents a failure due to the file suffix being unsupported type.
'''
pass | class Invalidimageuriexception(Exception):
"""
Represents a failure due to unexpected s3_uri format.
"""
pass
class Invalidimageextensionexception(Exception):
"""
Represents a failure due to the file suffix being unsupported type.
"""
pass |
class PalProd():
def __init__(self):
self.maxProd = 0
self.maxNum = 9
def setDigits(self, dig):
self.maxNum = pow(10, dig)
def calcMaxProd(self):
for i in range(1, self.maxNum):
for j in range(1, self.maxNum):
if str(i*j) == str(i*j)[::... | class Palprod:
def __init__(self):
self.maxProd = 0
self.maxNum = 9
def set_digits(self, dig):
self.maxNum = pow(10, dig)
def calc_max_prod(self):
for i in range(1, self.maxNum):
for j in range(1, self.maxNum):
if str(i * j) == str(i * j)[::-1] ... |
def truncate(plot, comments, reviews, max_length):
reviews_token = [c.split(" ") for c in reviews]
reviews_token = [j for i in reviews_token for j in i]
len_R = len(reviews_token)
comments_token = [c.split(" ") for c in comments]
comments_token = [j for i in comments_token for j in i]
... | def truncate(plot, comments, reviews, max_length):
reviews_token = [c.split(' ') for c in reviews]
reviews_token = [j for i in reviews_token for j in i]
len_r = len(reviews_token)
comments_token = [c.split(' ') for c in comments]
comments_token = [j for i in comments_token for j in i]
len_c = le... |
# Vicfred
# https://atcoder.jp/contests/abc154/tasks/abc154_c
# sorting
n = int(input())
a = list(map(int, input().split()))
a.sort()
repeated = False
for i in range(len(a)-1):
if a[i] == a[i+1]:
repeated = True
break
if repeated:
print("NO")
else:
print("YES")
| n = int(input())
a = list(map(int, input().split()))
a.sort()
repeated = False
for i in range(len(a) - 1):
if a[i] == a[i + 1]:
repeated = True
break
if repeated:
print('NO')
else:
print('YES') |
while True:
coins = hero.findItems()
for coin in coins:
if coin.value == 3:
hero.moveXY(coin.pos.x, coin.pos.y)
| while True:
coins = hero.findItems()
for coin in coins:
if coin.value == 3:
hero.moveXY(coin.pos.x, coin.pos.y) |
#
# PySNMP MIB module PDN-CONFIG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PDN-CONFIG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:38:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) ... |
# -*- coding:utf-8 -*-
def add(a,b):
return a+b
sum=add(10,20)
print(sum) | def add(a, b):
return a + b
sum = add(10, 20)
print(sum) |
VERSION = (0, 6, 3, 'post1')
__version__ = VERSION # alias
def get_version():
version = f'{VERSION[0]}.{VERSION[1]}'
if VERSION[2]:
version = f'{version}.{VERSION[2]}'
if VERSION[3:] == ('alpha', 0):
version = f'{version} pre-alpha'
if 'post' in VERSION[3]:
version = f'{versio... | version = (0, 6, 3, 'post1')
__version__ = VERSION
def get_version():
version = f'{VERSION[0]}.{VERSION[1]}'
if VERSION[2]:
version = f'{version}.{VERSION[2]}'
if VERSION[3:] == ('alpha', 0):
version = f'{version} pre-alpha'
if 'post' in VERSION[3]:
version = f'{version}.{VERSIO... |
a = {'a': 2, 'b': 3}
arr = [a, 1]
arr2 = [2, a]
a['a'] = 1
# 1 1 1
print(a['a'])
print(arr[0]['a'])
print(arr2[1]['a'])
| a = {'a': 2, 'b': 3}
arr = [a, 1]
arr2 = [2, a]
a['a'] = 1
print(a['a'])
print(arr[0]['a'])
print(arr2[1]['a']) |
class Solution:
def kthGrammar(self, N, K):
flag = False
while K != 1:
i = 0
while 2 ** i < K:
i += 1
K -= 2 ** (i - 1)
flag = not flag
return 1 if flag else 0
| class Solution:
def kth_grammar(self, N, K):
flag = False
while K != 1:
i = 0
while 2 ** i < K:
i += 1
k -= 2 ** (i - 1)
flag = not flag
return 1 if flag else 0 |
class WingoCommands(object):
def __init__(self):
assert False, 'cannot create WingoCommands directly'
def AddWorkspace(self, Name):
'''
Adds a new workspace to Wingo with a name Name. Note that a workspace name
must be unique with respect to other workspaces and must have non-zero length.
The ... | class Wingocommands(object):
def __init__(self):
assert False, 'cannot create WingoCommands directly'
def add_workspace(self, Name):
"""
Adds a new workspace to Wingo with a name Name. Note that a workspace name
must be unique with respect to other workspaces and must have non-zero length.
Th... |
# A module inside the package
print("Module: ", __name__)
def do_stuff():
print("Doing stuff")
| print('Module: ', __name__)
def do_stuff():
print('Doing stuff') |
### General ###
# the port to which the API will bind
PORT = 1470
# whether or not to use debug mode
DEBUG = False
### Logging ###
# the path in which logs will be stored
LOGS_DIR = "logs"
# the time of day when logs will be rotated
LOGS_ROTATE_WHEN = "midnight"
# the number of logs to keep on disk
LOGS_BACKUP_COUNT =... | port = 1470
debug = False
logs_dir = 'logs'
logs_rotate_when = 'midnight'
logs_backup_count = 7
db_host = '127.0.0.1'
db_port = 27017
db_primary = 'AG'
db_logs = 'logs'
db_path = '/data/db'
heartbeat_interval = 10 |
class Nodo:
def __init__(self, id, label, tipo="ENT", tooltip="", fonte="RIF"):
self.id = id
self.tipo = tipo
self.label = label
self.cor = "Silver"
self.sexo = 0
self.m1 = 0
self.m2 = 0
self.situacao = ""
self.dataOperacao = ""
self.t... | class Nodo:
def __init__(self, id, label, tipo='ENT', tooltip='', fonte='RIF'):
self.id = id
self.tipo = tipo
self.label = label
self.cor = 'Silver'
self.sexo = 0
self.m1 = 0
self.m2 = 0
self.situacao = ''
self.dataOperacao = ''
self.t... |
# This script will plot the function f(x**2)
# Source code/software
# Math Adventures with Python by Peter Farrell, Chapter 4+
# Made with Processing 3.5.4 using Python Mode in Dec 2021
# https://py.processing.org
#range of x-values
xmin = -10
xmax = 10
#range of y-values
ymin = -10
ymax = 10
#calculat... | xmin = -10
xmax = 10
ymin = -10
ymax = 10
rangex = xmax - xmin
rangey = ymax - ymin
def setup():
global xscl, yscl
size(600, 600)
xscl = width / rangex
yscl = -height / rangey
def draw():
global xscl, yscl
background(255)
translate(width / 2, height / 2)
grid(xscl, yscl)
graph_func... |
num1, num2, num3 = 3, 2, 2
if num1 == num2 or num2 == num3 or num1 == num3:
add = 0
else:
add = num1 + num2 + num3
print(add)
| (num1, num2, num3) = (3, 2, 2)
if num1 == num2 or num2 == num3 or num1 == num3:
add = 0
else:
add = num1 + num2 + num3
print(add) |
while True:
try:
a, b = input().split()
a = int(a)
b = int(b)
def gcd(a, b):
x = a % b
while x > 0:
a = b
b = x
x = a % b
return b
c = gcd(a, b)
d = ""
for i in range(c):
... | while True:
try:
(a, b) = input().split()
a = int(a)
b = int(b)
def gcd(a, b):
x = a % b
while x > 0:
a = b
b = x
x = a % b
return b
c = gcd(a, b)
d = ''
for i in range(c):
... |
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 720
COLOR_BLACK = (0, 0, 0)
COLOR_WHITE = (255, 255, 255)
PLAYER_SPEED = 0.35
GRAVITY = 0.012
CLOUD_SPEED = 30
PLAYER_SCALE = 3
PLAYER_JUMP_VELOCITY = 2
PLAYER_HEIGHT_ADJUST = 54
PLAYER_SLIDING_DECAY = 0.0005
PLAYER_MIN_SLIDING_SPEED = 0.05
PLAYER_SLIDING_OFFSET = 4
PLAYER_SLIDING_RO... | screen_width = 1280
screen_height = 720
color_black = (0, 0, 0)
color_white = (255, 255, 255)
player_speed = 0.35
gravity = 0.012
cloud_speed = 30
player_scale = 3
player_jump_velocity = 2
player_height_adjust = 54
player_sliding_decay = 0.0005
player_min_sliding_speed = 0.05
player_sliding_offset = 4
player_sliding_ro... |
n = int(input())
total = 0
total += (n//100)
n -= 100*(n//100)
total += (n//20)
n -= 20*(n//20)
total += (n//10)
n -= 10*(n//10)
total += (n//5)
n -= 5*(n//5)
total += (n//1)
n -= 1*(n//1)
print(str(total))
| n = int(input())
total = 0
total += n // 100
n -= 100 * (n // 100)
total += n // 20
n -= 20 * (n // 20)
total += n // 10
n -= 10 * (n // 10)
total += n // 5
n -= 5 * (n // 5)
total += n // 1
n -= 1 * (n // 1)
print(str(total)) |
# File: proj1.py
# Author: Blake Lewis
# Date: 11/16/16
# Description: This program is a simple connect four game
EMPTY = "_"
PLAYER_1 = "x"
PLAYER_2 = "o"
# emptyBoard() creates a blank connect four board
# input: dimensions of board
# output: the board
def emptyBoard():
board = []
# asks for the rows of the... | empty = '_'
player_1 = 'x'
player_2 = 'o'
def empty_board():
board = []
rows = int(input('Please choose the number of rows: \nPlease enter a number greater than or equal to 5: '))
while rows < 5:
rows = int(input('Please choose the number of rows: \nPlease enter a number greater than or equal to 5:... |
class ParameterError(Exception):
pass
class InsertError(Exception):
pass
class UpdateError(Exception):
pass
class DeleteError(Exception):
pass
class GetError(Exception):
pass | class Parametererror(Exception):
pass
class Inserterror(Exception):
pass
class Updateerror(Exception):
pass
class Deleteerror(Exception):
pass
class Geterror(Exception):
pass |
sandwich_orders = ['pastrami', 'fish', 'pastrami', 'cabbage', 'pastrami', 'sala', 'pig', 'chicken']
finished_sandwich_orders = []
print(sandwich_orders)
print("'pastrami' soled out!")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_orders)
while sandwich_orders:
finished ... | sandwich_orders = ['pastrami', 'fish', 'pastrami', 'cabbage', 'pastrami', 'sala', 'pig', 'chicken']
finished_sandwich_orders = []
print(sandwich_orders)
print("'pastrami' soled out!")
while 'pastrami' in sandwich_orders:
sandwich_orders.remove('pastrami')
print(sandwich_orders)
while sandwich_orders:
finished =... |
instruments = ['EUR/USD', 'USD/JPY', 'AUD/USD', 'USD/CAD', 'GBP/USD', 'NZD/USD', 'GBP/JPY', 'EUR/JPY', 'AUD/JPY', 'EUR/GBP', 'USD/CHF']
current_prc = [ 0.8452, 108.66250, 0.70304, 1.29570, 1.5235, 1.2125, 144.25800, 125.43, 76.40250, 0.84592, 0.9547]
lot_size = 1
# https://www.xm.com/forex... | instruments = ['EUR/USD', 'USD/JPY', 'AUD/USD', 'USD/CAD', 'GBP/USD', 'NZD/USD', 'GBP/JPY', 'EUR/JPY', 'AUD/JPY', 'EUR/GBP', 'USD/CHF']
current_prc = [0.8452, 108.6625, 0.70304, 1.2957, 1.5235, 1.2125, 144.258, 125.43, 76.4025, 0.84592, 0.9547]
lot_size = 1
def calculate_pip_value_in_account_currency(currency, current... |
#littlepy
#it compresses some python commands into a letter or so
#dumb
inp=input("> ")
#registries
r=0
a=0
b=0
c=0
d=0
e=0
#commands:
#a-e: save r to a through e
#A-E: save a-e to r
#): r to int
#?: send input to r
#=: save the result of if a == b to c
#+: add a and b, save to c
#-: subtract a and b, save to c
#*: ... | inp = input('> ')
r = 0
a = 0
b = 0
c = 0
d = 0
e = 0
for i in inp:
if i == 'a':
a = r
if i == 'b':
b = r
if i == 'c':
c = r
if i == 'd':
d = r
if i == 'e':
e = r
if i == 'A':
r = a
if i == 'B':
r = b
if i == 'C':
r = c
... |
def arquivoexiste(nome):
try:
testar = open(nome, 'rt')
testar.close()
except FileNotFoundError:
return False
else:
return True
def criararquivo(nome):
criando = open(nome, 'wt+')
criando.close()
print(f'Arquivo {nome} criado com sucesso!')
def... | def arquivoexiste(nome):
try:
testar = open(nome, 'rt')
testar.close()
except FileNotFoundError:
return False
else:
return True
def criararquivo(nome):
criando = open(nome, 'wt+')
criando.close()
print(f'Arquivo {nome} criado com sucesso!')
def lerarquivo(nome):... |
def singleton(cls):
cls.__instance__ = None
cls.__firstinit__ = True
def init_decorator(func):
def wrapper(*args, **kwargs):
if not cls.__firstinit__:
return
func(*args, **kwargs)
cls.__firstinit__ = False
return wrapper
def new_decor... | def singleton(cls):
cls.__instance__ = None
cls.__firstinit__ = True
def init_decorator(func):
def wrapper(*args, **kwargs):
if not cls.__firstinit__:
return
func(*args, **kwargs)
cls.__firstinit__ = False
return wrapper
def new_deco... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/dongxiao/catkin_ws/src/LeGO-LOAM-zhushi/cloud_msgs/msg/cloud_info.msg"
services_str = ""
pkg_name = "cloud_msgs"
dependencies_str = "geometry_msgs;std_msgs;nav_msgs"
langs = "gencpp;geneus;genlisp;gennodejs;genpy"
dep_include_paths_str = "cloud_... | messages_str = '/home/dongxiao/catkin_ws/src/LeGO-LOAM-zhushi/cloud_msgs/msg/cloud_info.msg'
services_str = ''
pkg_name = 'cloud_msgs'
dependencies_str = 'geometry_msgs;std_msgs;nav_msgs'
langs = 'gencpp;geneus;genlisp;gennodejs;genpy'
dep_include_paths_str = 'cloud_msgs;/home/dongxiao/catkin_ws/src/LeGO-LOAM-zhushi/cl... |
loc = 'blazewebtestapp2.components.tests.tasks.init_db'
loctoo = 'blazewebtestapp2.components.tests.tasks.init_db'
def action_001():
return loctoo
| loc = 'blazewebtestapp2.components.tests.tasks.init_db'
loctoo = 'blazewebtestapp2.components.tests.tasks.init_db'
def action_001():
return loctoo |
USE_FP16 = "__use_fp16__"
SCHEDULER_STEP = "scheduler_step"
SCHEDULER_STEP_BATCH = "batch"
SCHEDULER_STEP_EPOCH = "epoch"
BATCH_LOGS_RATE_LIMIT = .2
VALID_SCHEDULER_STEP = {SCHEDULER_STEP_BATCH, SCHEDULER_STEP_EPOCH}
| use_fp16 = '__use_fp16__'
scheduler_step = 'scheduler_step'
scheduler_step_batch = 'batch'
scheduler_step_epoch = 'epoch'
batch_logs_rate_limit = 0.2
valid_scheduler_step = {SCHEDULER_STEP_BATCH, SCHEDULER_STEP_EPOCH} |
while(True):
if int(input("Digite um numero: ")) <= 10:
print("Ok, numero registrado")
break
else:
print("Numero invalido, digite outro numero menor que 10")
#https://pt.stackoverflow.com/q/332795/101
| while True:
if int(input('Digite um numero: ')) <= 10:
print('Ok, numero registrado')
break
else:
print('Numero invalido, digite outro numero menor que 10') |
# Determine if a string has all unique characters
# Solution implemented with a dictionary
def is_unique_with_dict(str):
frequency = {}
for char in str:
if frequency.get(char):
return False
frequency[char] = 1
return True
# Solution implemented with a list
def is_unique(str):
chars = [... | def is_unique_with_dict(str):
frequency = {}
for char in str:
if frequency.get(char):
return False
frequency[char] = 1
return True
def is_unique(str):
chars = []
for char in str:
if char in chars:
return False
else:
chars.append(ch... |
# Change this to your API keys
# Map API key -- only need 1 of the following
# Google Maps API key (if usemapbox is not set in Config)
googleapi = 'YOUR GOOGLE MAPS API KEY'
# Mapbox API key (access_token) [if usemapbox is set in Config]
mbapi = 'YOUR MAPBOX ACCESS TOKEN'
# Weather API key -- only need 1 of t... | googleapi = 'YOUR GOOGLE MAPS API KEY'
mbapi = 'YOUR MAPBOX ACCESS TOKEN'
owmapi = 'YOUR OPENWEATHERMAP API KEY' |
class Relationship:
id = -1
idObjectA = ""
idObjectB = ""
relation = ""
score = 0
def __init__(self, id=-1, idObjA="", idObjB="", relName="", score=0):
self.id = id
self.idObjectA = idObjA
self.idObjectB = idObjB
self.relation = relName
self.score = scor... | class Relationship:
id = -1
id_object_a = ''
id_object_b = ''
relation = ''
score = 0
def __init__(self, id=-1, idObjA='', idObjB='', relName='', score=0):
self.id = id
self.idObjectA = idObjA
self.idObjectB = idObjB
self.relation = relName
self.score = s... |
'''
Define the program name.
Particularly useful for error messages.
'''
PROGRAM_NAME = 'annokey'
| """
Define the program name.
Particularly useful for error messages.
"""
program_name = 'annokey' |
def uv_on_emitter(modifier):
pass
| def uv_on_emitter(modifier):
pass |
# Space: O(1)
# Time: O(n)
class Solution:
def shiftingLetters(self, s, shifts):
total = sum(shifts) % 26
res = []
for i, c in enumerate(s):
index = ord(c) - ord('a')
res.append(chr(ord('a') + (index + total) % 26))
total = (total - shifts[i]) % 26
... | class Solution:
def shifting_letters(self, s, shifts):
total = sum(shifts) % 26
res = []
for (i, c) in enumerate(s):
index = ord(c) - ord('a')
res.append(chr(ord('a') + (index + total) % 26))
total = (total - shifts[i]) % 26
return ''.join(res) |
def getNext(slow, waiting,locked):
if slow in waiting.keys():
resid = waiting[slow]
else:
return None
if resid in locked.keys():
thinf2 = locked[resid]
else:
return None
if thinf2 in waiting.keys():
slow = thinf2
else:
return None
return slow
def identifyDeadLock(locked,waiting):
deadlockList = []... | def get_next(slow, waiting, locked):
if slow in waiting.keys():
resid = waiting[slow]
else:
return None
if resid in locked.keys():
thinf2 = locked[resid]
else:
return None
if thinf2 in waiting.keys():
slow = thinf2
else:
return None
return slow... |
RUN_TEST = False
TEST_SOLUTION = 150
TEST_INPUT_FILE = "test_input_day_02.txt"
INPUT_FILE = "input_day_02.txt"
ARGS = []
def main_part1(
input_file,
):
with open(input_file) as file:
lines = list(map(lambda line: line.rstrip(), file.readlines()))
# Part 1
# Calculate the horizontal position ... | run_test = False
test_solution = 150
test_input_file = 'test_input_day_02.txt'
input_file = 'input_day_02.txt'
args = []
def main_part1(input_file):
with open(input_file) as file:
lines = list(map(lambda line: line.rstrip(), file.readlines()))
instructions = {}
for line in lines:
(instructi... |
def model_wh(resolution_str):
width, height = map(int, resolution_str.split('x'))
if width % 16 != 0 or height % 16 != 0:
raise Exception('Width and height should be multiples of 16. w=%d, h=%d' % (width, height))
return int(width), int(height)
| def model_wh(resolution_str):
(width, height) = map(int, resolution_str.split('x'))
if width % 16 != 0 or height % 16 != 0:
raise exception('Width and height should be multiples of 16. w=%d, h=%d' % (width, height))
return (int(width), int(height)) |
def stairs(n):
res=[]
s=["1"]
for i in range(n):
res.append(" "*((n-i-1)*4)+" ".join(s+s[::-1]))
s.append(str((i+2)%10))
return "\n".join(res)
| def stairs(n):
res = []
s = ['1']
for i in range(n):
res.append(' ' * ((n - i - 1) * 4) + ' '.join(s + s[::-1]))
s.append(str((i + 2) % 10))
return '\n'.join(res) |
__author__ = 'mstipanov'
class Configuration:
def __init__(self, username = None, password = None, api_key = None, token = None, base_url = None):
self.base_url = "https://api.infobip.com"
if base_url:
self.base_url = base_url
self.username = username
self.password = pa... | __author__ = 'mstipanov'
class Configuration:
def __init__(self, username=None, password=None, api_key=None, token=None, base_url=None):
self.base_url = 'https://api.infobip.com'
if base_url:
self.base_url = base_url
self.username = username
self.password = password
... |
class Solution:
def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
allowed = set(allowed)
count = 0
for word in words:
for c in word:
if c not in allowed:
break
else:
count += 1
return c... | class Solution:
def count_consistent_strings(self, allowed: str, words: List[str]) -> int:
allowed = set(allowed)
count = 0
for word in words:
for c in word:
if c not in allowed:
break
else:
count += 1
retur... |
class PriorityQueue:
def __init__(self, capacity):
self.__capacity = capacity
self.__values = []
self.__length = 0
def is_empty(self):
return self.__length == 0
def is_capacity_max(self):
return self.__length == self.__capacity
def length(self):
return ... | class Priorityqueue:
def __init__(self, capacity):
self.__capacity = capacity
self.__values = []
self.__length = 0
def is_empty(self):
return self.__length == 0
def is_capacity_max(self):
return self.__length == self.__capacity
def length(self):
return... |
class Pessoa:
def __init__(self,*filhos, nome, idade=42): #eh um metodo de inicializacao de contrucao de objeto
self.nome = nome #o atributo nome existe mas nao tem valor atribuido a ele
self.idade = idade
self.filhos = list(filhos) #lista conten... | class Pessoa:
def __init__(self, *filhos, nome, idade=42):
self.nome = nome
self.idade = idade
self.filhos = list(filhos)
def cumprimentar(self):
return 'Ola'
if __name__ == '__main__':
andre = pessoa(nome='Andre')
luciano = pessoa(andre, nome='Luciano')
print(Pesso... |
class SegBranch(nn.Module):
def __init__(self, net_enc, net_dec):
super(SegBranch, self).__init__()
self.encoder = net_enc
self.decoder = net_dec
def forward(self, data):
feats = self.encoder(data, return_feature_maps=True)
pred = self.decoder(feats)
if isinstance(pred,list):
for i in range(len(pred))... | class Segbranch(nn.Module):
def __init__(self, net_enc, net_dec):
super(SegBranch, self).__init__()
self.encoder = net_enc
self.decoder = net_dec
def forward(self, data):
feats = self.encoder(data, return_feature_maps=True)
pred = self.decoder(feats)
if isinstan... |
class CnmbDto():
physic = None
care_level_one = None
care_level_second = None
care_level_third = None
| class Cnmbdto:
physic = None
care_level_one = None
care_level_second = None
care_level_third = None |
{
"targets": [
{
"target_name": "blinkr",
"sources": [ "src/blinkr.cc" ]
}
]
}
| {'targets': [{'target_name': 'blinkr', 'sources': ['src/blinkr.cc']}]} |
n = input('digite seu nome: ')
print(n.lower())
print(n.upper())
k = n.replace(' ', '')
ik = len(k)
print(ik)
l = n.split(' ')
print(l)
il = len(l[0])
print(il)
| n = input('digite seu nome: ')
print(n.lower())
print(n.upper())
k = n.replace(' ', '')
ik = len(k)
print(ik)
l = n.split(' ')
print(l)
il = len(l[0])
print(il) |
class NeighborhoodFunctionNotFound(Exception):
pass
class LatticeTypeNotFound(Exception):
pass
class NormalizationFunctionNotFound(Exception):
pass
class ModelNotTrainedError(Exception):
pass
class InvalidValuesInDataSet(Exception):
pass
| class Neighborhoodfunctionnotfound(Exception):
pass
class Latticetypenotfound(Exception):
pass
class Normalizationfunctionnotfound(Exception):
pass
class Modelnottrainederror(Exception):
pass
class Invalidvaluesindataset(Exception):
pass |
# Create a function named same_name() that has two parameters named your_name and my_name.
# If our names are identical, return True. Otherwise, return False.
def same_name(your_name, my_name):
if your_name == my_name:
return True
else:
return False
| def same_name(your_name, my_name):
if your_name == my_name:
return True
else:
return False |
# -*- coding: utf-8 -*-
filename = 'MazeData.txt'
wall_char = '%'
space_char = ' '
start_char = 'S'
end_char = 'E'
| filename = 'MazeData.txt'
wall_char = '%'
space_char = ' '
start_char = 'S'
end_char = 'E' |
# Given an array of integers, return a new array such that each element at index
# i of the new array is the product of all the numbers in the original array
# except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be
# [120, 60, 40, 30, 24]. If our input was [3, 2, 1], th... | def product_except_self(nums):
n = len(nums)
p = 1
output = [1] * n
for i in range(n):
output[i] *= p
p *= nums[i]
p = 1
for i in range(n - 1, -1, -1):
output[i] *= p
p *= nums[i]
return output
if __name__ == '__main__':
for nums in [[1, 2, 3, 4, 5], [3, 2... |
# Scrapy settings for tutorial project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/topics/settings.html
#
BOT_NAME = 'livingsocial'
SPIDER_MODULES = ['living_social.spiders']
ITEM_PIPELINES = ['living_... | bot_name = 'livingsocial'
spider_modules = ['living_social.spiders']
item_pipelines = ['living_social.pipelines.LivingSocialPipeline']
database = {'drivername': 'postgres', 'host': 'localhost', 'port': '5432', 'username': 'lynnroot', 'password': '', 'database': 'scrape'} |
def escape_format_str(text):
return text.replace("{", "{{").replace("}", "}}")
def to_list(thing):
if not isinstance(thing, list):
if isinstance(thing, str) or not hasattr(thing, "__iter__"):
thing = [thing]
return thing
| def escape_format_str(text):
return text.replace('{', '{{').replace('}', '}}')
def to_list(thing):
if not isinstance(thing, list):
if isinstance(thing, str) or not hasattr(thing, '__iter__'):
thing = [thing]
return thing |
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
length = len(s)
s_dict = {}
t_dict = {}
for i in range(length):
s_char = s[i]
t_char = t[i]
if s_di... | class Solution:
def is_isomorphic(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
length = len(s)
s_dict = {}
t_dict = {}
for i in range(length):
s_char = s[i]
t_char = t[i]
if s_dict.get(s_char, -1) != t_dict.... |
def nested_property(func):
''' nested property documentation '''
names = func()
names['doc'] = func.__doc__
return property(**names)
class Square:
def __init__(self,value):
self.sides = value
@nested_property
def area():
def fget(self):
return self.sides**2
... | def nested_property(func):
""" nested property documentation """
names = func()
names['doc'] = func.__doc__
return property(**names)
class Square:
def __init__(self, value):
self.sides = value
@nested_property
def area():
def fget(self):
return self.sides ** 2... |
def latestYtVid(latest_vid, new_vid):
current = new_vid.execute()
if latest_vid == None:
return current
else:
if latest_vid['items'][0]['snippet']['resourceId']['videoId'] == current['items'][0]['snippet']['resourceId']['videoId']:
return latest_vid
else:
retu... | def latest_yt_vid(latest_vid, new_vid):
current = new_vid.execute()
if latest_vid == None:
return current
elif latest_vid['items'][0]['snippet']['resourceId']['videoId'] == current['items'][0]['snippet']['resourceId']['videoId']:
return latest_vid
else:
return current |
coo = 'coo'
lil = 'lil'
def nei_adj(typ: str, rc: float):
return f'nei_adj_{typ}_{rc}'
def nei_sft(typ: str, rc: float):
return f'nei_sft_{typ}_{rc}'
def nei_spc(typ: str, rc: float):
return f'nei_spc_{typ}_{rc}'
def vec(typ: str, rc: float):
return f'vec_{typ}_{rc}'
def sod(typ: str, rc: floa... | coo = 'coo'
lil = 'lil'
def nei_adj(typ: str, rc: float):
return f'nei_adj_{typ}_{rc}'
def nei_sft(typ: str, rc: float):
return f'nei_sft_{typ}_{rc}'
def nei_spc(typ: str, rc: float):
return f'nei_spc_{typ}_{rc}'
def vec(typ: str, rc: float):
return f'vec_{typ}_{rc}'
def sod(typ: str, rc: float):
... |
'''
Created on 5 juni 2017
@author: Wilma
'''
| """
Created on 5 juni 2017
@author: Wilma
""" |
string = str(input())
string = string.lower()
sum_of_vowels = 0
for char in string:
if char == 'a':
sum_of_vowels += 1
elif char == 'e':
sum_of_vowels += 2
elif char == 'i':
sum_of_vowels += 3
elif char == 'o':
sum_of_vowels += 4
elif char == 'u':
sum_of_vow... | string = str(input())
string = string.lower()
sum_of_vowels = 0
for char in string:
if char == 'a':
sum_of_vowels += 1
elif char == 'e':
sum_of_vowels += 2
elif char == 'i':
sum_of_vowels += 3
elif char == 'o':
sum_of_vowels += 4
elif char == 'u':
sum_of_vowel... |
def estimator(input):
res = {
"data": {},
"impact": {},
"severeImpact": {}
}
# challenge 1
res["data"] = input
res["impact"]["currentlyInfected"] = input["reportedCases"] * 10
res["severeImpact"]["currentlyInfected"] = input["reportedCases"] * 50
if input['periodTyp... | def estimator(input):
res = {'data': {}, 'impact': {}, 'severeImpact': {}}
res['data'] = input
res['impact']['currentlyInfected'] = input['reportedCases'] * 10
res['severeImpact']['currentlyInfected'] = input['reportedCases'] * 50
if input['periodType'] == 'weeks':
input['timeToElapse'] = in... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def calculate(factors, nth):
factors = sorted(factors)
for pos in iterate_positions(len(factors), nth):
nth_pos = list(pos)
return conposit_permutation(factors, nth_pos)
def iterate_positions(d, m):
for n in range(0,m):
ret = []
... | def calculate(factors, nth):
factors = sorted(factors)
for pos in iterate_positions(len(factors), nth):
nth_pos = list(pos)
return conposit_permutation(factors, nth_pos)
def iterate_positions(d, m):
for n in range(0, m):
ret = []
for i in range(0, d):
ret.append(n % ... |
def sum_n_natural_numbers(n: int) -> int:
return n * (n + 1) // 2
def number_special_strings(s: str) -> int:
special_strings = 0
i = 0
while i < len(s):
repeat = 1
while i + 1 < len(s) and (s[i] == s[i + 1]):
repeat += 1
i += 1
special_strings += sum_n_n... | def sum_n_natural_numbers(n: int) -> int:
return n * (n + 1) // 2
def number_special_strings(s: str) -> int:
special_strings = 0
i = 0
while i < len(s):
repeat = 1
while i + 1 < len(s) and s[i] == s[i + 1]:
repeat += 1
i += 1
special_strings += sum_n_natu... |
word_tree_pth = 'data/SpokenCOCO/Freda-formatting/test_word-level-ground-truth-83k-5k-5k.txt'
word_caps_pth = 'data/SpokenCOCO/Freda-formatting/test_caps-83k-5k-5k.txt'
with open(word_tree_pth, 'r') as f:
word_trees = f.readlines()
word_trees = [x.strip('\n') for x in word_trees]
with open(word_caps_pth, 'r') a... | word_tree_pth = 'data/SpokenCOCO/Freda-formatting/test_word-level-ground-truth-83k-5k-5k.txt'
word_caps_pth = 'data/SpokenCOCO/Freda-formatting/test_caps-83k-5k-5k.txt'
with open(word_tree_pth, 'r') as f:
word_trees = f.readlines()
word_trees = [x.strip('\n') for x in word_trees]
with open(word_caps_pth, 'r') as f:... |
hydrogen_test_cases = [
("[C]", 0),
("[CH]", 1),
("[CH2]", 2),
("[CH3]", 3),
("[CH4]", 4),
("[C][C]", 0),
("[C][CH]", 1),
("[CH][CH2]", 3),
("[H]", 1),
("[HH]", 2),
("[H][CH3]", 4),
("C", 4),
("[CH]([2H])([3H])[H]", 4),
("[H][CH3]", 4),
("[H][H]", 2),
]
... | hydrogen_test_cases = [('[C]', 0), ('[CH]', 1), ('[CH2]', 2), ('[CH3]', 3), ('[CH4]', 4), ('[C][C]', 0), ('[C][CH]', 1), ('[CH][CH2]', 3), ('[H]', 1), ('[HH]', 2), ('[H][CH3]', 4), ('C', 4), ('[CH]([2H])([3H])[H]', 4), ('[H][CH3]', 4), ('[H][H]', 2)]
aromatic_ring_cases = [('C1CCCCC1', 0), ('c1ccccc1', 1), ('c1ccccc1.c... |
def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n - 2)
def get_fibonacci_series(n):
fibonacci_series = []
for i in range(n):
term = fibonacci(i)
fibonacci_series.append(term)
return fibonacci_series
n = int(input())
result = g... | def fibonacci(n):
if n <= 1:
return n
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def get_fibonacci_series(n):
fibonacci_series = []
for i in range(n):
term = fibonacci(i)
fibonacci_series.append(term)
return fibonacci_series
n = int(input())
result = get_fibona... |
# This is a comment. Comments begin with a "#"
print("Hello,")
print(" world!")
| print('Hello,')
print(' world!') |
#!/usr/bin/env python3
avm_results = [
{"status": {"version": "1.0.0", "code": 0, "msg": "SuccessWithResult", "total": 1, "page": 1, "pagesize": 10, "responseDateTime": "2019-6-21T04:09:31", "transactionID": "7788506e-e039-49fa-84bc-28dc8312f372"}, "echoed_fields": {"jobID": "", "loanNumber": "", "preparedBy": "", "... | avm_results = [{'status': {'version': '1.0.0', 'code': 0, 'msg': 'SuccessWithResult', 'total': 1, 'page': 1, 'pagesize': 10, 'responseDateTime': '2019-6-21T04:09:31', 'transactionID': '7788506e-e039-49fa-84bc-28dc8312f372'}, 'echoed_fields': {'jobID': '', 'loanNumber': '', 'preparedBy': '', 'resellerID': '', 'preparedF... |
def _is_valid_line_start(ch):
return ch == '-' or ch == '"' or ch.isalpha() or ch.isdigit()
def _check_line_for_ident(line):
indent_ws = 0
for i in range( len(line) ):
ch = line[i]
if ch == ' ':
indent_ws += 1
elif ch == '#':
return None
elif _is_vali... | def _is_valid_line_start(ch):
return ch == '-' or ch == '"' or ch.isalpha() or ch.isdigit()
def _check_line_for_ident(line):
indent_ws = 0
for i in range(len(line)):
ch = line[i]
if ch == ' ':
indent_ws += 1
elif ch == '#':
return None
elif _is_valid_... |
class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
def display_details(self):
print(f'Name: {self.name} | Age: {self.age}')
# def __str__(self):
# return f'Name: {self.name}, Age: {self.age}'
class Programmer(Employee):
def __init__(sel... | class Employee:
def __init__(self, name, age):
self.name = name
self.age = age
def display_details(self):
print(f'Name: {self.name} | Age: {self.age}')
class Programmer(Employee):
def __init__(self, name, age):
super().__init__(name, age)
class Qa(Employee):
def __i... |
## Python Crash Course
# Exercise 6.1: Person:
# Use a dictionary to store information about a person you know.
# Store their first name, last name, age, and the city in which they live.
# You should have keys such as first_name, last_name, age, and city.
# ... | def exercise_6_1():
print('\n')
my_info = {'first_name': 'Akshay', 'last_name': 'Moharir', 'age': 29, 'city': 'Novi'}
print('Name:', myInfo['first_name'] + ' ' + myInfo['last_name'])
print('Age:', myInfo['age'])
print('City:', myInfo['city'])
print('\n')
if __name__ == '__main__':
exercise_6... |
a = 80000
b = 200000
ano = 0
while a <= b:
a += a * 0.03
b += b * 0.015
ano = ano + 1
print("A ultrapassa ou iguala a B em %d anos" % ano)
| a = 80000
b = 200000
ano = 0
while a <= b:
a += a * 0.03
b += b * 0.015
ano = ano + 1
print('A ultrapassa ou iguala a B em %d anos' % ano) |
#-----------------------------------------------------------------------------
# Runtime: 40ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def addBinary(self, a: str, b: str) -> str:
a_length = len(a) - 1
b_length = len(b)... | class Solution:
def add_binary(self, a: str, b: str) -> str:
a_length = len(a) - 1
b_length = len(b) - 1
carry = 0
result = ''
while a_length >= 0 or b_length >= 0:
a_value = int(a[a_length]) if a_length >= 0 else 0
b_value = int(b[b_length]) if b_len... |
#!/usr/bin/env python
#Modify once acccording to your setup
WORKSPACE = "/home/sharath/git-tree"
#Modify the below lines for each project
PROJECT_NAME = "GroupMessenger1"
#Modify if using DB
DB_NAME = "groupmsg"
TABLE_NAME = "group_msgs"
MAIN_ACTIVITY = "GroupMessengerActivity"
#DO NOT MODIFY
PREFIX = "edu.buffalo.c... | workspace = '/home/sharath/git-tree'
project_name = 'GroupMessenger1'
db_name = 'groupmsg'
table_name = 'group_msgs'
main_activity = 'GroupMessengerActivity'
prefix = 'edu.buffalo.cse.cse486586'
project_ext = PROJECT_NAME.lower() |
class Message():
def score(self, name, value):
return {
'type': 'score',
'name': name,
'value': value
}
def text(self, value):
return {
'type': 'text',
'value': value
}
def error(self, message):
return {
... | class Message:
def score(self, name, value):
return {'type': 'score', 'name': name, 'value': value}
def text(self, value):
return {'type': 'text', 'value': value}
def error(self, message):
return {'type': 'error', 'value': message} |
def select(session, bucket, file, sql, header):
req = session.select_object_content(
Bucket=bucket,
Key=file,
ExpressionType='SQL',
Expression=sql,
InputSerialization={'CSV': {'RecordDelimiter': '\r\n', 'FileHeaderInfo': header}},
OutputSerialization={'CSV': {}},
... | def select(session, bucket, file, sql, header):
req = session.select_object_content(Bucket=bucket, Key=file, ExpressionType='SQL', Expression=sql, InputSerialization={'CSV': {'RecordDelimiter': '\r\n', 'FileHeaderInfo': header}}, OutputSerialization={'CSV': {}})
records = []
for event in req['Payload']:
... |
#
# Copyright (c) 2019, Infosys Ltd.
#
# 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 ... | request_type = {'ATTACH_REQUEST': 'attach_request', 'ATTACH_REQUEST_GUTI': 'attach_request_guti', 'AUTHENTICATION_REQUEST': 'authentication_request', 'AUTHENTICATION_RESPONSE': 'authentication_response', 'AUTHENTICATION_REJECT': 'authentication_reject', 'AUTHENTICATION_FAILURE': 'authentication_failure', 'SECURITY_MODE... |
def factorial(n):
fact=1
for i in range(1,n+1):
fact=fact*i
return fact
num=int(input("Enter number to find its Factorial : "))
print(factorial(num))
| def factorial(n):
fact = 1
for i in range(1, n + 1):
fact = fact * i
return fact
num = int(input('Enter number to find its Factorial : '))
print(factorial(num)) |
#This file contains data settings for the main file.
gravityFlip = False
gravityValue = -1000
ballMass = 5E3
ballRadius = 5
displayText = ""
windowSizeX = 1920
windowSizeY = 1080
FrictionMultiplier = 0.2
ElasticityMultiplier = 0
SoundPath = 'sound.mp3'
MusicPath = 'music.mp3'
Music = True
psi = 0.5
Windo... | gravity_flip = False
gravity_value = -1000
ball_mass = 5000.0
ball_radius = 5
display_text = ''
window_size_x = 1920
window_size_y = 1080
friction_multiplier = 0.2
elasticity_multiplier = 0
sound_path = 'sound.mp3'
music_path = 'music.mp3'
music = True
psi = 0.5
windows_size_factor_x = windowSizeX / 640
windows_size_fa... |
#
# PySNMP MIB module DGS-3620-28SC-DC-L2MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DGS-3620-28SC-DC-L2MGMT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:29:17 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.