content stringlengths 7 1.05M |
|---|
def multiplicationTable(size):
return [[j*i for j in range(1, size+1)] for i in range(1, size+1)]
x = multiplicationTable(5)
print(x)
print()
for i in x:
print(i)
|
def getFrequencyDictForText(sentence):
fullTermsDict = multidict.MultiDict()
tmpDict = {}
# making dictionary for counting word frequencies
for text in sentence.split(" "):
# remove irrelevant words
if re.match("a|the|an|the|to|in|for|of|or|by|with|is|on|that|but|from|than|be", text):
continue
val = tmpDict.get(text, 0)
tmpDict[text.lower()] = val + 1
for key in tmpDict:
fullTermsDict.add(key, tmpDict[key])
return fullTermsDict
def makeImage(text):
wc = WordCloud(width = 3000, height = 1080, background_color="white", colormap = 'Dark2', max_words=200)
# generate word cloud
wc.generate_from_frequencies(text)
# save
plt.imshow(wc)
plt.axis("off")
datestring = date.today().strftime("%b-%d-%Y")
plt.text(860, -50, 'Date Generated: ' + datestring)
filename = datestring + '.png'
plt.savefig(os.path.join(os.getcwd(), '..', './static', filename), dpi = 400, bbox_inches='tight')
# get text from existing word file
tifile = open(os.path.join(os.getcwd(), '..','words.txt'), 'r')
text = tifile.read()
makeImage(getFrequencyDictForText(text))
tifile.close()
|
class BoxaugError(Exception):
pass
|
""" Desenvolva um programa que leia o comprimento de três retas
e diga ao usuário se elas podem ou não formar um triângulo."""
a = float(input('Reta A:'))
b = float(input('Reta B:'))
c = float(input('Reta C:'))
if a < b + c and b < a + c and c < a + b:
print('Forma um triangulo')
else:
print('Não forma um triangulo') |
# short hand if
a=23
b=4
if a > b: print("a is greater than b")
# short hand if
print("a is greater ") if a > b else print("b is greater ")
#pass statements
b=300
if b > a:
pass
|
if args.algo in ['a2c', 'acktr']:
values, action_log_probs, dist_entropy, conv_list = actor_critic.evaluate_actions(Variable(rollouts.states[:-1].view(-1, *obs_shape)), Variable(rollouts.actions.view(-1, action_shape)))
# pre-process
values = values.view(args.num_steps, num_processes_total, 1)
action_log_probs = action_log_probs.view(args.num_steps, num_processes_total, 1)
# compute afs loss
afs_per_m_temp, afs_loss = actor_critic.get_afs_per_m(
action_log_probs=action_log_probs,
conv_list=conv_list,
)
if len(afs_per_m_temp)>0:
afs_per_m += [afs_per_m_temp]
if (afs_loss is not None) and (afs_loss.data.cpu().numpy()[0]!=0.0):
afs_loss.backward(mone, retain_graph=True)
afs_loss_list += [afs_loss.data.cpu().numpy()[0]]
advantages = Variable(rollouts.returns[:-1]) - values
value_loss = advantages.pow(2).mean()
action_loss = -(Variable(advantages.data) * action_log_probs).mean()
final_loss_basic = value_loss * args.value_loss_coef + action_loss - dist_entropy * args.entropy_coef
ewc_loss = None
if j != 0:
if ewc == 1:
ewc_loss = actor_critic.get_ewc_loss(lam=ewc_lambda)
if ewc_loss is None:
final_loss = final_loss_basic
else:
final_loss = final_loss_basic + ewc_loss
basic_loss_list += [final_loss_basic.data.cpu().numpy()[0]]
final_loss.backward()
if args.algo == 'a2c':
nn.utils.clip_grad_norm(actor_critic.parameters(), args.max_grad_norm)
optimizer.step()
elif args.algo == 'ppo':
advantages = rollouts.returns[:-1] - rollouts.value_preds[:-1]
advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-5)
old_model.load_state_dict(actor_critic.state_dict())
if hasattr(actor_critic, 'obs_filter'):
old_model.obs_filter = actor_critic.obs_filter
for _ in range(args.ppo_epoch):
sampler = BatchSampler(SubsetRandomSampler(range(num_processes_total * args.num_steps)), args.batch_size * num_processes_total, drop_last=False)
for indices in sampler:
indices = torch.LongTensor(indices)
if args.cuda:
indices = indices.cuda()
states_batch = rollouts.states[:-1].view(-1, *obs_shape)[indices]
actions_batch = rollouts.actions.view(-1, action_shape)[indices]
return_batch = rollouts.returns[:-1].view(-1, 1)[indices]
# Reshape to do in a single forward pass for all steps
values, action_log_probs, dist_entropy, conv_list = actor_critic.evaluate_actions(Variable(states_batch), Variable(actions_batch))
_, old_action_log_probs, _, old_conv_list= old_model.evaluate_actions(Variable(states_batch, volatile=True), Variable(actions_batch, volatile=True))
ratio = torch.exp(action_log_probs - Variable(old_action_log_probs.data))
adv_targ = Variable(advantages.view(-1, 1)[indices])
surr1 = ratio * adv_targ
surr2 = torch.clamp(ratio, 1.0 - args.clip_param, 1.0 + args.clip_param) * adv_targ
action_loss = -torch.min(surr1, surr2).mean() # PPO's pessimistic surrogate (L^CLIP)
value_loss = (Variable(return_batch) - values).pow(2).mean()
optimizer.zero_grad()
(value_loss + action_loss - dist_entropy * args.entropy_coef).backward()
optimizer.step()
|
'''
Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle.
Example 1:
Input: [2,2,3,4]
Output: 3
Explanation:
Valid combinations are:
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
Note:
The length of the given array won't exceed 1000.
The integers in the given array are in the range of [0, 1000].
'''
class Solution:
def triangleNumber(self, nums: List[int]) -> int:
nums.sort()
res = 0
for i in reversed(range(len(nums))):
j = 0
k = i - 1
while j < k:
if nums[j] + nums[k] > nums[i]:
res += k - j
k -= 1
else:
j += 1
return res
|
print("\tWelcome to the Factor Generator App")
#Creamos la variable c = True para utilizar en un bucle sin fin
c = True
#Creamos el bucle
while c :
num = int(input("\nEnter a number to determine all factors of that number: "))
fact = []
#Añadimos los factores del número
for i in range(1,num+1):
if num%i == 0:
fact.append(i)
print("\nFactors of ",num ," are:")
#Mostramos los factores y la multiplicacion
for i in fact:
print(i)
print("\nIn summary:")
for i in fact:
for j in fact:
if i*j==num and i<=j:
print(i,"*",j," = ",num)
s = input("Run again (y/n): ").lower()
if s == 'yes':
continue
if s == 'no':
print("\nThank you for using the program. Have a great day.")
break
|
a = [0x77, 0x60, 0x76, 0x66, 0x72, 0x77, 0x7D, 0x73, 0x60, 0x3D, 0x64, 0x60, 0x39, 0x52, 0x66, 0x3B, 0x73, 0x7A, 0x23, 0x7D, 0x73, 0x4A, 0x70, 0x78, 0x6A, 0x46, 0x69, 0x2B, 0x76, 0x68, 0x41, 0x77, 0x41, 0x42, 0x49, 0x4A, 0x4A, 0x42, 0x40, 0x48, 0x5A, 0x5A, 0x45, 0x41, 0x59, 0x03, 0x5A, 0x4A, 0x51, 0x5C, 0x4F]
flag = ''
for i in range(len(a)):
flag += chr(a[i]^i)
print(flag) # watevr{th4nk5_h4ck1ng_for_s0ju_hackingforsoju.team} |
"""
Datos de entrada:
Nombre --> str --> A
Compra --> float --> B
Datos de salida:
Total --> float --> C
Nombre --> str --> A
Compra --> float --> B
Descuento --> float --> D
"""
# Entrada
A = str(input("\nDigite tu nombre "))
B = float(input("Digite el valor de tu compra "))
# Caja negra
if B < 50000:
D = 0
elif 50000 <= B < 100000:
D = .05
elif 100000 <= B < 700000:
D = .11
elif 700000 <= B < 1500000:
D = .18
else:
D = .25
C = B - B * D
# Salida
print(f"\nHola {A}\nPara la compra: {B}\nEl valor a pagar es: {C}\nCon un descuento de: {B*D}\n") |
# This code is provoded by MDS DSCI 531/532
def mds_special():
font = "Arial"
axisColor = "#000000"
gridColor = "#DEDDDD"
return {
"config": {
"title": {
"fontSize": 24,
"font": font,
"anchor": "start", # equivalent of left-aligned.
"fontColor": "#000000"
},
'view': {
"height": 300,
"width": 400
},
"axisX": {
"domain": True,
#"domainColor": axisColor,
"gridColor": gridColor,
"domainWidth": 1,
"grid": False,
"labelFont": font,
"labelFontSize": 12,
"labelAngle": 0,
"tickColor": axisColor,
"tickSize": 5, # default, including it just to show you can change it
"titleFont": font,
"titleFontSize": 16,
"titlePadding": 10, # guessing, not specified in styleguide
"title": "X Axis Title (units)",
},
"axisY": {
"domain": False,
"grid": True,
"gridColor": gridColor,
"gridWidth": 1,
"labelFont": font,
"labelFontSize": 14,
"labelAngle": 0,
#"ticks": False, # even if you don't have a "domain" you need to turn these off.
"titleFont": font,
"titleFontSize": 16,
"titlePadding": 10, # guessing, not specified in styleguide
"title": "Y Axis Title (units)",
# titles are by default vertical left of axis so we need to hack this
#"titleAngle": 0, # horizontal
#"titleY": -10, # move it up
#"titleX": 18, # move it to the right so it aligns with the labels
},
}
} |
# Writing a method
class Shape:
def __init__(self, name, sides, colour=None):
self.name = name
self.sides = sides
self.colour = colour
def get_info(self):
return '{} {} with {} sides'.format(self.colour,
self.name,
self.sides)
s = Shape('square', 4, 'green')
print(s.get_info())
# example of classmethod and staticmethod
class Shape:
def __init__(self, name, sides, colour=None):
self.name = name
self.sides = sides
self.colour = colour
@classmethod
def green_shape(cls, name, sides):
print(cls)
return cls(name, sides, 'green')
@staticmethod
def trapezium_area(a, b, height):
# area of trapezium = 0.5(a + b)h
return 0.5 * (a + b) * height
green = Shape.green_shape('rectangle', 4)
print('{} {} with {} sides'.format(green.colour,
green.name,
green.sides))
print(Shape.trapezium_area(5, 7, 4))
# demonstrating differences when calling regular methods, classmethods
# and staticmethods
class Shape:
def dummy_method(self, *args):
print('self:', self)
print('args:', *args)
@classmethod
def dummy_classmethod(cls, *args):
print('cls :', cls)
print('args:', *args)
@staticmethod
def dummy_staticmethod(*args):
print('args:', *args)
square = Shape()
# calling regular method from instance
square.dummy_method('arg')
print(repr(square.dummy_method) + '\n')
# calling regular method from class
Shape.dummy_method('arg')
print(repr(Shape.dummy_method) + '\n')
# calling classmethod from instance
square.dummy_classmethod('arg')
print(repr(square.dummy_classmethod) + '\n')
# calling classmethod from class
Shape.dummy_classmethod('arg')
print(repr(Shape.dummy_classmethod) + '\n')
# calling staticmethod from instance
square.dummy_staticmethod('arg')
print(repr(square.dummy_staticmethod) + '\n')
# calling staticmethod from class
Shape.dummy_staticmethod('arg')
print(repr(Shape.dummy_staticmethod) + '\n')
|
def soma(a, b):
print(f'A = {a} e B = {b}.')
s = a + b
print(f'A soma de A + B = {s}.')
# Programa Principal
soma(a=4, b=5)
soma(b=8, a=9)
soma(2, 1)
# Empacotamento
def contador(* num):
for valor in num:
print(f'{valor} ', end=' ')
print('FIM!')
tam = len(num)
print(f'O total de números é {tam}!')
contador(2, 1, 7)
contador(8, 0)
contador(4, 4, 7, 6, 2)
# Trabalhando com listas
def dobra(lst):
pos = 0
while pos < len(lst):
lst[pos] *= 2
pos += 1
valores = [6, 3, 9, 1, 0, 2]
dobra(valores)
print(valores)
# Desempacotamento
def soma(* valores):
s = 0
for num in valores:
s += num
print(f'Somando os valores {valores} temos {s}')
soma(5, 2)
soma(2, 9, 4) |
"""
A very simple class to make running tests a bit simpler.
There are much stronger frameworks possible; this is a KISS framework.
Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder,
and their colleagues.
"""
class SimpleTestCase(object):
"""
A SimpleTestCase is a test to run. It has:
-- The function to test,
-- its argument(s), and
-- its correct returned value.
"""
def __init__(self, function, arguments, correct_returned_value):
"""
The arguments are:
-- The function to test
-- The arguments to use in the test, as a sequence
-- The correct returned value.
For example, if the intended test is:
foo(blah1, blah2, blah3)
with correct returned value True,
then its SimpleTestCase would be construced by:
SimpleTestCase(foo, [blah1, blah2, blah3], True)
Note that the arguments must be a SEQUENCE even if there is
only a single argument and an EMPTY sequence if there are no
arguments. For example:
foo(blah) with correct returned value 88
would be constructed by:
SimpleTestCase(foo, [blah], 88)
"""
self.function_to_test = function
self.arguments_to_use = arguments
self.correct_returned_value = correct_returned_value
def run_test(self):
"""
Runs this test, printing appropriate messages.
Returns True if your code passed the test, else False.
Does not attempt to catch Exceptions.
"""
your_answer = self.function_to_test(*(self.arguments_to_use))
if your_answer == self.correct_returned_value:
result = 'PASSED'
else:
result = 'FAILED'
print()
print('Your code {:6} this test'.format(result))
if len(self.arguments_to_use) == 0:
format_string = ' ( )'
else:
f_beginning = ' {}( {} '
f_args = ', {}' * (len(self.arguments_to_use) - 1)
format_string = f_beginning + f_args + ' )'
print(format_string.format(self.function_to_test.__name__,
*(self.arguments_to_use)))
print(' The correct returned value is:',
self.correct_returned_value)
print(' Your code returned ..........:', your_answer)
return (your_answer == self.correct_returned_value)
@staticmethod
def run_tests(function_name, tests):
print()
print('--------------------------------------------------')
print('Testing the {} function:'.format(function_name))
print('--------------------------------------------------')
failures = 0
for k in range(len(tests)):
result = tests[k].run_test()
if result is False:
failures = failures + 1
if failures > 0:
print()
print('************************************')
print('*** YOUR CODE FAILED SOME TESTS. ***')
print('************************************')
|
class Solution:
def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:
degree = [0] * n
for u, v in edges:
degree[v] = 1
return [i for i, d in enumerate(degree) if d == 0]
|
#!/usr/bin/env python
DEBUG = True
SECRET_KEY = 'super-ultra-secret-key'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:',
}
}
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.staticfiles',
'django_tables2',
'django_tables2_column_shifter',
'django_tables2_column_shifter.tests',
]
ROOT_URLCONF = 'django_tables2_column_shifter.tests.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
LANGUAGE_CODE = 'en-us'
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
MIDDLEWARE = []
|
def recursion_test(depth):
print("recursion depth:", depth)
if depth < 996:
recursion_test(depth + 1)
else:
print("exit recursion")
return
# 下面是 代码16-5,重复出现,不要出现在代码示例里:
recursion_test(1) |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 2 07:54:50 2022
@author: HP
"""
A = [85, 86 ,32 ,12 ,82 ,43]
# i, j
# [12,32,43,55,82,86]
# obtener el tamaño de la lista
num = len (A)
i=0
while i < num :
j=i
while j < num :
if (A[i]> A[j]):
aux= A[i]
A[i]=A[j]
A[i]=aux
j=j+1
i=i+1
print ("lista ordenada")
print (A)
listDeNumeros = [34, 12, 4, 10]
print ("lista original")
print (listDeNumeros)
listDeNumeros.sort()
print ("lista ordenada")
print (listDeNumeros)
|
# classical (x, y) position vectors
class Pos:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return(Pos(self.x + other.x, self.y + other.y))
def __eq__(self, other):
return(
(self.x == other.x) and
(self.y == other.y))
def __mul__(self, factor):
return(Pos(factor * self.x, factor * self.y))
def __ne__(self, other):
return(not(self == other))
def __str__(self):
return("(" + str(self.x) + ", " + str(self.y) + ")")
def __sub__(self, subtrahend):
return(self + (subtrahend * -1))
|
# model settings
model = dict(
type='Recognizer3D',
backbone=dict(
type='C3D',
# pretrained= # noqa: E251
# 'https://download.openmmlab.com/mmaction/recognition/c3d/c3d_sports1m_pretrain_20201016-dcc47ddc.pth', # noqa: E501
pretrained= # noqa: E251
'./work_dirs/fatigue_c3d/c3d_sports1m_pretrain_20201016-dcc47ddc.pth',
# noqa: E501
style='pytorch',
conv_cfg=dict(type='Conv3d'),
norm_cfg=None,
act_cfg=dict(type='ReLU'),
dropout_ratio=0.5,
init_std=0.005),
cls_head=dict(
type='I3DHead',
num_classes=2,
in_channels=4096,
spatial_type=None,
dropout_ratio=0.5,
init_std=0.01),
# model training and testing settings
train_cfg=None,
test_cfg=dict(average_clips='score'))
# dataset settings
dataset_type = 'FatigueCleanDataset'
data_root = '/zhourui/workspace/pro/fatigue/data/rawframes/new_clean/fatigue_clips'
data_root_val = '/zhourui/workspace/pro/fatigue/data/rawframes/new_clean/fatigue_clips'
facerect_data_prefix = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_info_from_yolov5'
ann_file_train = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
ann_file_val = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
ann_file_test = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
test_save_results_path = 'work_dirs/fatigue_c3d/valid_results_testone.npy'
test_save_label_path = 'work_dirs/fatigue_c3d/valid_label_testone.npy'
img_norm_cfg = dict(mean=[104, 117, 128], std=[1, 1, 1], to_bgr=False)
# support clip len 16 only!!!
clip_len = 16
train_pipeline = [
dict(type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, out_of_bound_opt='repeat_last'),
dict(type='FatigueRawFrameDecode'),
dict(type='Resize', scale=(112, 112), keep_ratio=False),
#dict(type='RandomCrop', size=112),
dict(type='Flip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs', 'label'])
]
val_pipeline = [
dict(
type='SampleFrames',
clip_len=clip_len,
frame_interval=1,
num_clips=1,
test_mode=True,
out_of_bound_opt='repeat_last'),
dict(type='FatigueRawFrameDecode'),
dict(type='Resize', scale=(112, 112), keep_ratio=False),
#dict(type='CenterCrop', crop_size=112),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
test_pipeline = [
dict(
type='SampleFrames',
clip_len=clip_len,
frame_interval=1,
num_clips=1,
test_mode=True,
out_of_bound_opt='repeat_last'),
dict(type='FatigueRawFrameDecode'),
dict(type='Resize', scale=(112, 112), keep_ratio=False),
#dict(type='CenterCrop', crop_size=112),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
data = dict(
videos_per_gpu=40,
workers_per_gpu=4,
pin_memory=False,
train=dict(
type=dataset_type,
ann_file=ann_file_train,
video_data_prefix=data_root,
facerect_data_prefix=facerect_data_prefix,
data_phase='train',
test_mode=False,
pipeline=train_pipeline,
min_frames_before_fatigue=clip_len),
val=dict(
type=dataset_type,
ann_file=ann_file_val,
video_data_prefix=data_root_val,
facerect_data_prefix=facerect_data_prefix,
data_phase='valid',
test_mode=True,
test_all=False,
pipeline=val_pipeline,
min_frames_before_fatigue=clip_len),
test=dict(
type=dataset_type,
ann_file=ann_file_test,
video_data_prefix=data_root_val,
facerect_data_prefix=facerect_data_prefix,
data_phase='valid',
test_mode=True,
test_all=False,
test_save_label_path=test_save_label_path,
test_save_results_path=test_save_results_path,
pipeline=test_pipeline,
min_frames_before_fatigue=clip_len))
evaluation = dict(
interval=5, metrics=['top_k_classes'])
# optimizer
optimizer = dict(
type='SGD', lr=0.001, momentum=0.9,
weight_decay=0.0005) # this lr is used for 8 gpus
optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2))
# learning policy
lr_config = dict(policy='step', step=[20, 40])
total_epochs = 45
checkpoint_config = dict(interval=1)
log_config = dict(
interval=20,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook'),
])
# runtime settings
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = f'./work_dirs/fatigue_c3d/'
load_from = None
resume_from = None
workflow = [('train', 1)]
|
#
# @lc app=leetcode id=55 lang=python
#
# [55] Jump Game
#
# https://leetcode.com/problems/jump-game/description/
#
# algorithms
# Medium (31.35%)
# Total Accepted: 241.1K
# Total Submissions: 767.2K
# Testcase Example: '[2,3,1,1,4]'
#
# Given an array of non-negative integers, you are initially positioned at the
# first index of the array.
#
# Each element in the array represents your maximum jump length at that
# position.
#
# Determine if you are able to reach the last index.
#
# Example 1:
#
#
# Input: [2,3,1,1,4]
# Output: true
# Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
#
#
# Example 2:
#
#
# Input: [3,2,1,0,4]
# Output: false
# Explanation: You will always arrive at index 3 no matter what. Its
# maximum
# jump length is 0, which makes it impossible to reach the last index.
#
#
#
'''
class Solution(object):
def solver(self, nums, start_pos, stop_pos):
if start_pos == len(nums)-1:
return True
for i in range(start_pos, stop_pos+1):
res = self.solver(nums, i, min(len(nums)-1, start_pos+nums[start_pos]))
if res:
return res
return False
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
return self.solver(nums, 0, len(nums)-1)
def canJump(self, nums):
m = 0
for i, n in enumerate(nums):
if i > m:
return False
m = max(m, i+n)
return True
'''
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
goal = len(nums)-1
for i in range(len(nums))[::-1]:
if i + nums[i] >= goal:
goal = i
return not goal
|
class HelperProcessRequest:
"""
This class allows agents to express their need for a helper process that may be shared with other agents.
"""
def __init__(self, python_file_path: str, key: str, executable: str = None):
"""
:param python_file_path: The file that should be loaded and inspected for a subclass of BotHelperProcess.
:param key: A key used to control the mapping of helper processes to bots. For example, you could set
:param executable: A path to an executable that should be run as a separate process
something like 'myBotType-team1' in order to get one shared helper process per team.
"""
self.python_file_path = python_file_path
self.key = key
self.executable = executable
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
if root is None:
return None
stack = deque([root,])
parent = {root: None}
while stack:
node = stack.pop()
if node.left:
parent[node.left] = node
stack.append(node.left)
if node.right:
parent[node.right] = node
stack.append(node.right)
ancestors = set()
while p:
ancestors.add(p)
p = parent[p]
while q not in ancestors:
q = parent[q]
return q |
def variance_of_sample_proportion(a,b,c,d,e,f,g,h,j,k):
try:
a = int(a)
b = int(b)
c = int(c)
d = int(d)
e = int(e)
f = int(f)
g = int(g)
h = int(h)
j = int(j)
k = int(k)
sample = [a,b,c,d,e,f,g,h,j,k]
# Count how many people are over the age 80
i = 0
occurrence = 0
while i < len(sample):
if (sample[i])> 80:
occurrence = occurrence + 1
else:
i = i + 1
i = i + 1
# n is population size
n = len(sample)
# p is probability
p = float(occurrence/n)
var_samp_propor = float((p * (1-p))/n)
print("variance_of_sample_proportion:",var_samp_propor )
return var_samp_propor
except ZeroDivisionError:
print("Error: Dividing by Zero is not valid!!")
except ValueError:
print ("Error: Only Numeric Values are valid!!") |
class FlatList(list):
"""
This class inherits from list and has the same interface as a list-type.
However, there is a 'data'-attribute introduced, that is required for the encoding of the list!
The fields of the encoding-Schema must match the fields of the Object to be encoded!
"""
@property
def data(self):
return list(self)
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, list(self))
class ChannelList(FlatList):
pass
class TokensList(FlatList):
pass
class AddressList(FlatList):
pass
class PartnersPerTokenList(FlatList):
pass
class EventsList(FlatList):
pass
class Address(object):
def __init__(self, token_address):
self.address = token_address
class PartnersPerToken(object):
def __init__(self, partner_address, channel):
self.partner_address = partner_address
self.channel = channel
class Channel(object):
def __init__(
self,
channel_address,
token_address,
partner_address,
settle_timeout,
reveal_timeout,
balance,
state):
self.channel_address = channel_address
self.token_address = token_address
self.partner_address = partner_address
self.settle_timeout = settle_timeout
self.reveal_timeout = reveal_timeout
self.balance = balance
self.state = state
class ChannelNew(object):
def __init__(self, netting_channel_address, participant1, participant2, settle_timeout):
self.netting_channel_address = netting_channel_address
self.participant1 = participant1
self.participant2 = participant2
self.settle_timeout = settle_timeout
class ChannelNewBalance(object):
def __init__(
self,
netting_channel_address,
token_address,
participant_address,
new_balance,
block_number):
self.netting_channel_address = netting_channel_address
self.token_address = token_address
self.participant_address = participant_address
self.new_balance = new_balance
self.block_number = block_number
class ChannelClosed(object):
def __init__(self, netting_channel_address, closing_address, block_number):
self.netting_channel_address = netting_channel_address
self.closing_address = closing_address
self.block_number = block_number
class ChannelSettled(object):
def __init__(self, netting_channel_address, block_number):
self.netting_channel_address = netting_channel_address
self.block_number = block_number
class ChannelSecretRevealed(object):
def __init__(self, netting_channel_address, secret):
self.netting_channel_address = netting_channel_address
self.secret = secret
|
class ITypeHintingFactory(object):
def make_param_provider(self):
"""
:rtype: rope.base.oi.type_hinting.providers.interfaces.IParamProvider
"""
raise NotImplementedError
def make_return_provider(self):
"""
:rtype: rope.base.oi.type_hinting.providers.interfaces.IReturnProvider
"""
raise NotImplementedError
def make_assignment_provider(self):
"""
:rtype: rope.base.oi.type_hinting.providers.interfaces.IAssignmentProvider
"""
raise NotImplementedError
def make_resolver(self):
"""
:rtype: rope.base.oi.type_hinting.resolvers.interfaces.IResolver
"""
raise NotImplementedError
|
class Stack:
def __init__(self):
self.stack = []
self.current_minimum = float('inf')
def push(self, item):
if not self.stack:
self.stack.append(item)
self.current_minimum = item
else:
if item >= self.current_minimum:
self.stack.append(item)
else:
self.stack.append(2 * item - self.current_minimum)
self.current_minimum = item
def pop(self):
if not self.stack:
raise IndexError
else:
item = self.stack.pop()
if item >= self.current_minimum:
return item
else:
answer = self.current_minimum
self.current_minimum = 2 * self.current_minimum - item
return answer
def peek(self):
if not self.stack:
raise IndexError
else:
item = self.stack[-1]
if item >= self.current_minimum:
return item
else:
return self.current_minimum
def find_min(self):
if not self.stack:
return IndexError
return self.current_minimum
def __len__(self):
return len(self.stack) |
# -*- coding: utf-8 -*-
# Return the contents of a file
def load_file(filename):
with open(filename, "r") as f:
return f.read()
# Write contents to a file
def write_file(filename, content):
with open(filename, "w+") as f:
f.write(content)
# Append contents to a file
def append_file(filename, content):
with open(filename, "a+") as f:
f.write(content)
|
def main():
t: tuple[i32, str]
t = (1, 2)
main() |
# Config
SIZES = {
'basic': 299
}
NUM_CHANNELS = 3
NUM_CLASSES = 2
GENERATOR_BATCH_SIZE = 32
TOTAL_EPOCHS = 50
STEPS_PER_EPOCH = 100
VALIDATION_STEPS = 50
BASE_DIR = 'C:\\Users\\guilo\\mba-tcc\\data\\' |
def test_split():
assert split(10) == 2
def test_string():
city = "String"
assert type(city) == str
def test_float():
price = 3.45
assert type(price) == float
def test_int():
high_score = 1
assert type(high_score) == int
def test_boolean():
is_having_fun = True
assert type(is_having_fun) == bool
def split(cash):
bounty = cash / 5
print(bounty)
return bounty
|
"""
ID: tony_hu1
PROG: milk2
LANG: PYTHON3
"""
def read_in(infile):
a = []
with open(infile) as filename:
for line in filename:
a.append(line.rstrip())
return a
def milk_cows_main(flines):
total = []
num_cows = int(flines[0])
for i in range(num_cows):
b = flines[i+1].split(' ')
total.append([int(b[0]),int(b[1])])
arrange(total)
def arrange(total):
total.sort()
time= [[0,0]]
for i in range(len(total)):
a = total[i][0]
b =time[len(time)-1][0]
c =time[len(time)-1][1]
judgement = (a >= b )and (a <= c)
if judgement:
period = [time[len(time)-1][0],max(total[i][1],time[len(time)-1][1])]
time[len(time)-1] = period
else:
time.append(total[i])
if time[0]==[0,0]:
del time[0]
result(time)
def result(total):
no_cows = 0
for i in range(len(total)-1):
x = total[i+1][0] - total[i][1]
no_cows = max(no_cows,x)
cows = 0
for i in range(len(total)):
x = total[i][1] - total[i][0]
cows = max(cows,x)
fout = open ('milk2.out', 'w')
a = str(cows) + ' ' + str(no_cows)+'\n'
fout.write(a)
flines = read_in("milk2.in")
milk_cows_main(flines) |
A = 'A'
B = 'B'
RULE_ACTION = {
1: 'Suck',
2: 'Right',
3: 'Left',
4: 'NoOp'
}
rules = {
(A, 'Dirty'): 1,
(B, 'Dirty'): 1,
(A, 'Clean'): 2,
(B, 'Clean'): 3,
(A, B, 'Clean'): 4
}
# Ex. rule (if location == A && Dirty then 1)
Environment = {
A: 'Dirty',
B: 'Dirty',
'Current': A
}
def INTERPRET_INPUT(input): # No interpretation
return input
def RULE_MATCH(state, rules): # Match rule for a given state
rule = rules.get(tuple(state))
return rule
def SIMPLE_REFLEX_AGENT(percept): # Determine action
state = INTERPRET_INPUT(percept)
rule = RULE_MATCH(state, rules)
action = RULE_ACTION[rule]
return action
def Sensors(): # Sense Environment
location = Environment['Current']
return (location, Environment[location])
def Actuators(action): # Modify Environment
location = Environment['Current']
if action == 'Suck':
Environment[location] = 'Clean'
elif action == 'Right' and location == A:
Environment['Current'] = B
elif action == 'Left' and location == B:
Environment['Current'] = A
def run(n): # run the agent through n steps
print(' Current New')
print('location status action location status')
for i in range(1, n):
(location, status) = Sensors() # Sense Environment before action
print("{:12s}{:8s}".format(location, status), end='')
action = SIMPLE_REFLEX_AGENT(Sensors())
Actuators(action)
(location, status) = Sensors() # Sense Environment after action
print("{:8s}{:12s}{:8s}".format(action, location, status))
if __name__ == '__main__':
run(10)
|
numero = int(input('\033[33mDigite um número inteiro:\033[m '))
print("""Escolha uma das bases para conversão:
[ \033[1;31m1\033[m ] converter para \033[1;31mBINÁRIO\033[m
[ \033[1;35m2\033[m ] converter para \033[1;35mOCTAL\033[m
[ \033[1;36m3\033[m ] converter para \033[1;36mHEXADECIMAL\033[m""")
opcao = int(input('Sua opção: '))
if opcao == 1:
print('O número {} equivale a \033[1;31m{:0b}\033[m na base \033[1;31mBINÁRIA\033[m.'.format(numero, numero))
print('O número {} equivale a \033[1;31m{}\033[m na base \033[1;31mBINÁRIA\033[m.'.format(numero, bin(numero)[2:] ))
elif opcao == 2:
print('O número {} equivale a \033[1;35m{:0o}\033[m na base \033[1;35mOCTAL\033[m.'.format(numero, numero))
print('O número {} equivale a \033[1;35m{}\033[m na base \033[1;35mOCTAL\033[m.'.format(numero, oct(numero)[2:]))
elif opcao == 3:
print('O número {} equivale a \033[1;36m{:0x}\033[m na base \033[1;36mHEXADECIMAL\033[m.'.format(numero, numero))
print('O número {} equivale a \033[1;36m{}\033[m na base \033[1;36mHEXADECIMAL\033[m.'.format(numero, hex(numero)[2:]))
else:
print('Opção inválida! Tente novamente.') |
def convert(s):
s_split = s.split(' ')
return s_split
def niceprint(s):
for i, elm in enumerate(s):
print('Element #', i + 1, ' = ', elm, sep='')
return None
c1 = 10
c2 = 's'
|
# Source : https://leetcode.com/problems/reverse-string-ii/#/description
# Author : Han Zichi
# Date : 2017-04-23
class Solution(object):
def reverseStr(self, s, k):
"""
:type s: str
:type k: int
:rtype: str
"""
l = len(s)
tmp = []
for i in range(0, l, k * 2):
tmp.append(s[i:i+k*2])
ans = ''
for item in tmp:
if k <= len(item) <= k * 2:
ans += item[0:k][::-1] + item[k:min(k*2, len(item))]
else:
ans += item[::-1]
return ans |
# 1.
def print_greeting(name, age_in_years, address):
age_in_days = age_in_years * 365
age_in_years_1000_days_ago = (age_in_days - 1000) / 365
print("My name is "
+ name + " and I am " + str(age_in_years) + " years old (that's "
+ str(age_in_days) + " days). 1000 days ago, I was "
+ str(age_in_years_1000_days_ago) + " years old. My address is: "
+ address)
address = """WeWork,
38 Chancery Lane,
London,
WC2A 1EN"""
print_greeting("Tim Rogers", 25, address)
# 2.
def square(number=2):
return number * number
print("Two squared is " + str(square()))
print("Four squared is " + str(square(4)))
# 3.
def powers(number=2):
squared = number * number
cubed = number * number * number
return squared, cubed
five_squared, five_cubed = powers(5)
print(
"Five squared is " +
str(five_squared) +
" and five cubed is " +
str(five_cubed))
|
#
# PySNMP MIB module ASCEND-MIBIPSECSPD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBIPSECSPD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:11:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
configuration, = mibBuilder.importSymbols("ASCEND-MIB", "configuration")
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Gauge32, Bits, Counter32, iso, IpAddress, Integer32, ModuleIdentity, Unsigned32, Counter64, ObjectIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Bits", "Counter32", "iso", "IpAddress", "Integer32", "ModuleIdentity", "Unsigned32", "Counter64", "ObjectIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
class DisplayString(OctetString):
pass
mibmibProfIpsecSpd = MibIdentifier((1, 3, 6, 1, 4, 1, 529, 23, 168))
mibmibProfIpsecSpdTable = MibTable((1, 3, 6, 1, 4, 1, 529, 23, 168, 1), )
if mibBuilder.loadTexts: mibmibProfIpsecSpdTable.setStatus('mandatory')
mibmibProfIpsecSpdEntry = MibTableRow((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1), ).setIndexNames((0, "ASCEND-MIBIPSECSPD-MIB", "mibProfIpsecSpd-SpdName"))
if mibBuilder.loadTexts: mibmibProfIpsecSpdEntry.setStatus('mandatory')
mibProfIpsecSpd_SpdName = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1, 1), DisplayString()).setLabel("mibProfIpsecSpd-SpdName").setMaxAccess("readonly")
if mibBuilder.loadTexts: mibProfIpsecSpd_SpdName.setStatus('mandatory')
mibProfIpsecSpd_DefaultFilter = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1, 2), DisplayString()).setLabel("mibProfIpsecSpd-DefaultFilter").setMaxAccess("readwrite")
if mibBuilder.loadTexts: mibProfIpsecSpd_DefaultFilter.setStatus('mandatory')
mibProfIpsecSpd_Action_o = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("noAction", 1), ("createProfile", 2), ("deleteProfile", 3)))).setLabel("mibProfIpsecSpd-Action-o").setMaxAccess("readwrite")
if mibBuilder.loadTexts: mibProfIpsecSpd_Action_o.setStatus('mandatory')
mibmibProfIpsecSpd_PolicyTable = MibTable((1, 3, 6, 1, 4, 1, 529, 23, 168, 2), ).setLabel("mibmibProfIpsecSpd-PolicyTable")
if mibBuilder.loadTexts: mibmibProfIpsecSpd_PolicyTable.setStatus('mandatory')
mibmibProfIpsecSpd_PolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1), ).setLabel("mibmibProfIpsecSpd-PolicyEntry").setIndexNames((0, "ASCEND-MIBIPSECSPD-MIB", "mibProfIpsecSpd-Policy-SpdName"), (0, "ASCEND-MIBIPSECSPD-MIB", "mibProfIpsecSpd-Policy-Index-o"))
if mibBuilder.loadTexts: mibmibProfIpsecSpd_PolicyEntry.setStatus('mandatory')
mibProfIpsecSpd_Policy_SpdName = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1, 1), DisplayString()).setLabel("mibProfIpsecSpd-Policy-SpdName").setMaxAccess("readonly")
if mibBuilder.loadTexts: mibProfIpsecSpd_Policy_SpdName.setStatus('mandatory')
mibProfIpsecSpd_Policy_Index_o = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1, 2), Integer32()).setLabel("mibProfIpsecSpd-Policy-Index-o").setMaxAccess("readonly")
if mibBuilder.loadTexts: mibProfIpsecSpd_Policy_Index_o.setStatus('mandatory')
mibProfIpsecSpd_Policy = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1, 3), DisplayString()).setLabel("mibProfIpsecSpd-Policy").setMaxAccess("readwrite")
if mibBuilder.loadTexts: mibProfIpsecSpd_Policy.setStatus('mandatory')
mibBuilder.exportSymbols("ASCEND-MIBIPSECSPD-MIB", mibmibProfIpsecSpdTable=mibmibProfIpsecSpdTable, mibProfIpsecSpd_SpdName=mibProfIpsecSpd_SpdName, mibmibProfIpsecSpd=mibmibProfIpsecSpd, mibProfIpsecSpd_Policy=mibProfIpsecSpd_Policy, mibmibProfIpsecSpd_PolicyEntry=mibmibProfIpsecSpd_PolicyEntry, mibProfIpsecSpd_Policy_Index_o=mibProfIpsecSpd_Policy_Index_o, mibmibProfIpsecSpdEntry=mibmibProfIpsecSpdEntry, mibProfIpsecSpd_Policy_SpdName=mibProfIpsecSpd_Policy_SpdName, mibmibProfIpsecSpd_PolicyTable=mibmibProfIpsecSpd_PolicyTable, mibProfIpsecSpd_Action_o=mibProfIpsecSpd_Action_o, DisplayString=DisplayString, mibProfIpsecSpd_DefaultFilter=mibProfIpsecSpd_DefaultFilter)
|
#!/usr/bin/env python
# coding: utf-8
# In[2]:
def utopianTree(cycles):
h=1
for cyc_no in range(cycles):
if (cyc_no%2==0):
h=h*2
elif (cyc_no):
h+=1
return h
if __name__=='__main__':
n=int(input())
for itr in range(n):
cycles=int(input())
print(utopianTree(cycles))
# In[ ]:
|
# Copyright 2020 InterDigital Communications, Inc.
#
# 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 License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
def rename_key(key):
"""Rename state_dict key."""
# ResidualBlockWithStride: 'downsample' -> 'skip'
if ".downsample.bias" in key or ".downsample.weight" in key:
return key.replace("downsample", "skip")
return key
def load_pretrained(state_dict):
"""Convert state_dict keys."""
state_dict = {rename_key(k): v for k, v in state_dict.items()}
return state_dict
|
def divisors(integer):
aux = [i for i in range(2, integer) if integer % i == 0]
if len(aux) == 0:
return "{} is prime".format(integer)
else:
return aux |
# coding: utf-8
pyslim_version = '0.700'
slim_file_version = '0.7'
# other file versions that require no modification
compatible_slim_file_versions = ['0.7']
|
"""
Created on Sat Aug 27 12:52:52 2021
AI and deep learnin with Python
Data types and operators
Quiz Zip and Enumerate
"""
# Problem 1:
"""Use zip to write a for loop that creates a string specifying the label
and coordinates of each point and appends it to the list points.
Each string should be formatted as label: x, y, z. For example, the string
for the first coordinate should be F: 23, 677, 4. """
x_coord = [23, 53, 2, -12, 95, 103, 14, -5]
y_coord = [677, 233, 405, 433, 905, 376, 432, 445]
z_coord = [4, 16, -6, -42, 3, -6, 23, -1]
labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"]
points = []
for point in zip (labels, x_coord, y_coord, z_coord):
points.append("{}: {}, {}, {}".format(*point))
for point in points:
print(point)
# Problem 2
"""
Use zip to create a dictionary cast that uses names as keys and
heights as values.
"""
cast_names = ["Barney", "Robin", "Ted", "Lily", "Marshall"]
cast_heights = [72, 68, 72, 66, 76]
cast = dict(zip(cast_names, cast_heights))
print(cast)
# Problem 3
"""
Unzip the cast tuple into two names and heights tuples.
"""
cast_details = {'Barney': 72, 'Robin': 68, 'Ted': 72, 'Lily': 66,
'Marshall': 76}
cast_name, cast_height = zip(*cast_details.items())
print(cast_name, cast_height, end='\n')
# Problem 4
"""
Quiz: Transpose with Zip
Use zip to transpose data from a 4-by-3 matrix to a 3-by-4 matrix.
"""
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data_transpose = tuple(zip(*data))# replace with your code
print(data_transpose)
# Problem 5
"""
Quiz: Enumerate
Use enumerate to modify the cast list so that each element contains the name
followed by the character's corresponding height. For example, the first
element of cast should change from "Barney Stinson" to "Barney Stinson 72".
"""
cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin",
"Marshall Eriksen"]
heights = [72, 68, 72, 66, 76]
for i, character in enumerate(cast):
cast[i] = character + " " + str(heights[i])
print(cast)
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# 有效的字母异位词
# v1
def isAnagram(s, t):
return sorted(s) == sorted(t)
v1 = 'cat'
v2 = 'tca'
# print(isAnagram(v1, v2))
# v2
def isAnagram1(s, t):
dic1, dic2 = {},{} # dict -> hashmap
for item in s:
dic1[item] = dic1.get(item, 0) + 1
for item in t:
dic2[item] = dic2.get(item, 0) + 1
return dic1 == dic2
print(isAnagram1(v1, v2))
|
def format_as_vsys(amount):
abs_amount = abs(amount)
whole = int(abs_amount / 100000000)
fraction = abs_amount % 100000000
if amount < 0:
whole *= -1
return f'{whole}.{str(fraction).rjust(8, "0")}'
|
class Solution:
def canVisitAllRooms(self, rooms):
stack = [0]
visited = set(stack)
while stack:
curr = stack.pop()
for room in rooms[curr]:
if room not in visited:
stack.append(room)
visited.add(room)
if len(visited) == len(rooms): return True
return len(visited) == len(rooms) |
__author__ = 'spersinger'
class Configuration:
@staticmethod
def run():
Configuration.enforce_ttl = True
Configuration.ttl = 60
Configuration.run()
|
"""
link: https://leetcode-cn.com/problems/relative-ranks
problem: 求数组每个元素排序后的次序
solution: 排序后记录
"""
class Solution:
def findRelativeRanks(self, nums: List[int]) -> List[str]:
if not nums:
return []
res = [_ for _ in nums]
for i, v in enumerate(nums):
nums[i] = (-v, i)
nums.sort()
for i, k in enumerate(nums):
if i == 0:
res[k[1]] = "Gold Medal"
elif i == 1:
res[k[1]] = "Silver Medal"
elif i == 2:
res[k[1]] = "Bronze Medal"
else:
res[k[1]] = str(i+1)
return res
|
#####
# https://github.com/sushiswap/sushiswap-subgraph
# https://dev.sushi.com/api/overview
# https://github.com/sushiswap/sushiswap-analytics/blob/c6919d56523b4418d174224a6b8964982f2a7948/src/core/api/index.js
# CP_API_TOKEN = os.environ.get("cp_api_token")
#"https://gateway.thegraph.com/api/c8eae2e5ac9d2e9d5d5459c33fe7b1eb/subgraphs/id/0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0"
# "https://thegraph.com/legacy-explorer/subgraph/sushiswap/exchange"
#####
url = {
"sushiexchange" : "https://api.thegraph.com/subgraphs/name/sushiswap/exchange",
"sushibar" : "https://api.thegraph.com/subgraphs/name/matthewlilley/bar",
"aave" : "https://api.thegraph.com/subgraphs/name/aave/protocol-v2"
}
|
"""
Telemac-Mascaret exceptions
"""
class TelemacException(Exception):
""" Generic exception class for all of Telemac-Mascaret Exceptions """
pass
class MascaretException(TelemacException):
""" Generic exception class for all of Telemac-Mascaret Exceptions """
pass
|
# -*- coding: utf-8 -*-
commands = {
'start_AfterAuthorized':
u'Welcome to remoteSsh_bot\n\n'
u'If you known password - use /on\n'
u'else - connect to admin',
'start_BeforeAuthorized':
u'Hello!\n'
u'If you want information about this bot - use /information\n'
u'If you want command list - use /help',
'help_AfterAuthorized':
u'If you known password - use /on\n'
u'else - connect to admin',
'help_BeforeAuthorized':
u'Command:\n'
u'/off - disconnect from bot\n'
u'/setsshUser - Set ssh user and ssh password\n'
u'/setsshHost - Set host(IP) for ssh connection\n'
u'/information - Show information, about ssh-connection\n'
u'/aboutBot - Information about bot and author\n',
'aboutBot': 'Author GitHub - https://github.com/vzemtsov\n'
u'Please write wishes to improve this bot',
} |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 5 14:31:36 2018
@author: User
"""
# part 1-e
def multlist(m1, m2):
lenof = len(m1)
newl = []
for i in range(lenof):
newl.append( m1[i]* m2[i])
print(None)
m1=[1, 2, 23, 104]
m2=[-3, 2, 0, 6]
multlist(m1, m2)
# part 1-a
#def createodds(n):
# lofodds = []
# for i in range(1,n, 2):
# lofodds.append(i)
# print(lofodds)
#createodds(0)
# part 1-b
#def spllist(n):
# newlist = []
# for i in range(1,n):
# smallist = list(range(1,i))
# newlist += [smallist]
# print(newlist[1:])
#spllist(6)
# part 1-c
#def divisibles(n):
# lol = []
# for i in range(1, int(n/2)+1):
## print(i)
# if n%i == 0:
# lol.append(i)
# print(lol)
#
#divisibles(19)
# part 1-d
#def update(l, a, b):
# count = 0
# newl = l
# for i in range(len(l )):
## print(l[i])
# if l[i] == a:
# newl[i] = b
# count += 1
# s = ('newlist is {0}, and {1} was replaced {2} times')
# print(s.format(newl, a, count))
#
#nl = [3, 10, 5, 10, -4]
#update(nl, 10, 7)
#def afn(los): # join various elements of a list recursively
# news = los[0:]
# if los == []:
# return
# else:
## print(los[1:])
# news = news + [afn(los[1:])]
# print(news)
#
#s = ['abc', 12, True, '',-12.4]
#print(afn(s))
|
'''
'''
def main():
info('Pump Microbone')
close(description="Jan Inlet")
if is_closed('F'):
open(description= 'Microbone to CO2 Laser')
else:
close(name="T", description="Microbone to CO2 Laser")
sleep(1)
close(description= 'CO2 Laser to Roughing')
#close(description= 'Microbone to Minibone')
open(description= 'Microbone to Turbo')
open(description= 'Microbone to Getter NP-10H')
open(description= 'Microbone to Getter NP-10C')
#open(description= 'Microbone to CO2 Laser')
open(description= 'Microbone to Inlet Pipette')
sleep(1)
set_resource(name='CO2PumpTimeFlag', value=30)
release('JanCO2Flag') |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
def split_text_by_fragments(text: str, fragment_length=50) -> list:
"""
Функция для разбития текста (<text>) на куски указанной длины (<fragment_length>).
"""
# Если длина фрагмента больше или равна длине текста, то сразу возвращаем список из одного элемента
if fragment_length >= len(text):
return [text]
fragments = list()
# Количество фрагментов
number = len(text) // fragment_length + 1
for i in range(number):
start = fragment_length * i
end = fragment_length * (i + 1)
fragments.append(text[start:end])
return fragments
if __name__ == '__main__':
text = """\
Брату в пору башмаки:
Не малы, не велики.
Их надели на Андрюшку,
Но ни с места он пока -
Он их принял за игрушку,
Глаз не сводит с башмака.
Мальчик с толком, с расстановкой
Занимается обновкой:
То погладит башмаки,
То потянет за шнурки.
Сел Андрей и поднял ногу,
Языком лизнул башмак...
Ну, теперь пора в дорогу,
Можно сделать первый шаг!
"""
fragments = split_text_by_fragments(text)
print(len(fragments), fragments)
assert ''.join(fragments) == text
assert len(fragments) == 7
fragments = split_text_by_fragments(text, fragment_length=len(text))
print(len(fragments), fragments)
assert ''.join(fragments) == text
assert len(fragments) == 1
fragments = split_text_by_fragments(text, fragment_length=9999)
print(len(fragments), fragments)
assert ''.join(fragments) == text
assert len(fragments) == 1
|
def findDecision(obj): #obj[0]: Driving_to, obj[1]: Passanger, obj[2]: Weather, obj[3]: Temperature, obj[4]: Time, obj[5]: Coupon, obj[6]: Coupon_validity, obj[7]: Gender, obj[8]: Age, obj[9]: Maritalstatus, obj[10]: Children, obj[11]: Education, obj[12]: Occupation, obj[13]: Income, obj[14]: Bar, obj[15]: Coffeehouse, obj[16]: Carryaway, obj[17]: Restaurantlessthan20, obj[18]: Restaurant20to50, obj[19]: Direction_same, obj[20]: Distance
# {"feature": "Education", "instances": 41, "metric_value": 0.9892, "depth": 1}
if obj[11]>1:
# {"feature": "Occupation", "instances": 26, "metric_value": 0.9612, "depth": 2}
if obj[12]>3:
# {"feature": "Income", "instances": 20, "metric_value": 1.0, "depth": 3}
if obj[13]>1:
# {"feature": "Maritalstatus", "instances": 17, "metric_value": 0.9774, "depth": 4}
if obj[9]<=1:
# {"feature": "Carryaway", "instances": 15, "metric_value": 0.9183, "depth": 5}
if obj[16]>1.0:
# {"feature": "Children", "instances": 13, "metric_value": 0.7793, "depth": 6}
if obj[10]<=0:
return 'True'
elif obj[10]>0:
# {"feature": "Gender", "instances": 6, "metric_value": 1.0, "depth": 7}
if obj[7]<=0:
return 'False'
elif obj[7]>0:
return 'True'
else: return 'True'
else: return 'False'
elif obj[16]<=1.0:
return 'False'
else: return 'False'
elif obj[9]>1:
return 'False'
else: return 'False'
elif obj[13]<=1:
return 'False'
else: return 'False'
elif obj[12]<=3:
return 'False'
else: return 'False'
elif obj[11]<=1:
# {"feature": "Income", "instances": 15, "metric_value": 0.5665, "depth": 2}
if obj[13]>2:
return 'True'
elif obj[13]<=2:
# {"feature": "Coffeehouse", "instances": 4, "metric_value": 1.0, "depth": 3}
if obj[15]<=0.0:
return 'False'
elif obj[15]>0.0:
return 'True'
else: return 'True'
else: return 'False'
else: return 'True'
|
bil = 0
count = 0
hasil = 0
while(bil <= 100):
if(bil % 2 == 1):
count += 1
hasil += bil
print(bil)
bil += 1
print('Banyaknya bilangan ganjil :', count)
print('Jumlah seluruh bilangan :', hasil)
|
def mapping_Luo(t=1):
names = [ 'Yao_6_2', 'AB_TMA_2', 'ABA_TMA_2',
'ABAB_TMA_2', 'ABABA_TMA_2', 'ABABA_IPrMeP_2']
xlocs = [ 21400, 5500, -7200,
-11700, -17200, -30700]
ylocs = [ 0, 0, 0,
0, 0, 0]
zlocs = [ 2700, 2700, 2700,
2700, 2700, 2700]
x_range=[[0, 500, 21], [0, 500, 21], [0, 500, 21],
[0, 500, 21], [0, 500, 21], [0, 500, 21]]
y_range=[[0, 500, 101],[0, 500, 101],[0, 500, 101],
[0, 500, 101],[0, 500, 101],[0, 500, 101]]
wa_range=[ [0, 13, 3], [0, 13, 3], [0, 13, 3],
[0, 13, 3], [0, 13, 3], [0, 13, 3]]
# names = ['CRP_2_275', 'CRP_1_131', 'Yao_6', 'CRP_2_275F', 'CRP_1_275A', 'AB_TMA', 'iPrMeP_stat', 'ABA_TMA', 'ABAB_TMA', 'ABABA_TMA',
# 'TMA_stat', 'ABABA_IPrMeP' ]
# xlocs = [30400, 26100, 21400, 16200, 9600, 5500, -500, -7200,
# -11700, -17200, -23700, -30700]
# ylocs = [0, 0, 0, 0, 0, 0, 0, 0,
# 0, 0, 0, 0]
# zlocs = [2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700,
# 2700, 2700, 2700, 2700]
# x_range=[[0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11],
# [0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11]]
# y_range=[[0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101],
# [0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101]]
# wa_range=[[0, 26, 5], [0, 13, 3], [0, 26, 5], [0, 26, 5], [0, 26, 5], [0, 13, 3], [0, 13, 3], [0, 13, 3],
# [0, 13, 3], [0, 13, 3], [0, 13, 3], [0, 13, 3]]
user = 'AL'
det_exposure_time(t,t)
assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(names)})'
assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(ylocs)})'
assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(zlocs)})'
assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(x_range)})'
assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(y_range)})'
assert len(xlocs) == len(wa_range), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(wa_range)})'
# Detectors, motors:
dets = [pil300KW, pil1M]
for num, (x, y, sample, x_r, y_r, wax_ra) in enumerate(zip(xlocs, ylocs, names, x_range, y_range, wa_range)):
if num == 0:
proposal_id('2121_1', '307948_Luo')
else:
proposal_id('2121_1', '307948_Luo2')
pil1M.cam.file_path.put('/nsls2/xf12id2/data/images/users/2021_1/307948_Luo2/1M/%s'%sample)
pil300KW.cam.file_path.put('/nsls2/xf12id2/data/images/users/2021_1/307948_Luo2/300KW/%s'%sample)
for wa in np.linspace(wax_ra[0], wax_ra[1], wax_ra[2]):
yield from bps.mv(waxs, wa)
yield from bps.mv(piezo.x, x)
yield from bps.mv(piezo.y, y+500)
name_fmt = '{sam}_4m_16.1keV_wa{waxs}'
sample_name = name_fmt.format(sam=sample, waxs='%2.1f'%wa)
sample_id(user_name=user, sample_name=sample_name)
print(f'\n\t=== Sample: {sample_name} ===\n')
yield from bp.rel_grid_scan(dets, piezo.y, *y_r, piezo.x, *x_r, 0) #1 = snake, 0 = not-snake
sample_id(user_name='test', sample_name='test')
det_exposure_time(0.3,0.3)
|
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 21:55:16 2018
@author: User
"""
def by_courses(file):
lol = []
name_dict = {}
f = open(file, 'r')
all_details = f.read()
lol.append([all_details])
f.close()
all_details = [line for line in all_details.split('\n') if line.strip() != ''] # strip the lines of newline and blank line
for each in all_details:
each = ((each.split(' ')))
name = each[0] + ' ' + each[1]
courses = (each[2::])
courses = un_camel(courses)
courses = [item for item in courses.split(' ')] # split into courses
courses = [x for x in courses if x!= ''] # remove empty
name_dict[name] = (courses)
for k, v in name_dict.items():
print(k,'-->', v)
all_courses = (list(name_dict.values()))
courses_set = []
for each in all_courses:
for item in each:
if item in courses_set:
pass
else:
courses_set.append(item)
revDict(name_dict, courses_set)
def revDict(name_dict, alist):
d1 = {k: [] for k in alist} # initialize an empty dictionary for all the courses
for k, v in name_dict.items():
for i in v:
if i in alist: # if the course name in alist
d1[i].append(k) # append the name
for k,v in d1.items():
print([k, sorted(v)])
def un_camel(courses): # convert from camelcase to uppercase
uc_text = ''
for x in courses:
for item in x:
if item.islower():
uc_text += item.upper()
else:
uc_text += item
uc_text += ' ' # to add blank spaces between courses
return uc_text
by_courses('Names.txt')
# b = {y:x for x,y in name_dict.items()} # just an experiment to see dictionary reversal - doesn't help in this case tho
# print(b.items())
|
def alpha_numeric(m):
return re.sub('[^A-Za-z0-9]+', ' ', m)
def uri_from_fields(fields):
string = '_'.join(alpha_numeric(f.strip().lower()) for f in fields)
if len(string) == len(fields)-1:
return ''
return string
def splitLocation(location):
return re.search('[NS]',location).start()
def getLatitude(s,l):
second = float(s[-2:])
minute = float(s[-4:-2])
degree = float(s[:-4])
if l == "N":
return str(degree+minute/60+second/3600)
else:
return str(-degree-minute/60-second/3600)
def getLongitude(s,l):
second = float(s[-2:])
minute = float(s[-4:-2])
degree = float(s[:-4])
if l == "E":
return str(degree+minute/60+second/3600)
else:
return str(-degree-minute/60-second/3600)
def ISOtime(s):
MM_dict = {"JAN":"01","FEB":"02","MAR":"03","APR":"04","MAY":"05","JUN":"06","JUL":"07","AUG":"08","SEP":"09","OCT":"10","NOV":"11","DEC":"12"}
return s[:4]+MM_dict[s[4:7]]+s[7:9]+"T"+s[9:11]+":"+s[11:]
def parseFstatOutput(s):
if s[-3:] == "NOP":
return "baseClosed"
if s[-3:] == "OPR":
return "baseOpen"
def parseEstatAction(action):
if action == "ABORT":
return "missionAbort"
elif action == "LANDED":
return "missionLanded"
elif action == "REFUEL":
return "aircraftRefuel"
elif action == "RTB":
return "missionReturnToBase"
elif action == "TAKEOFF":
return "aircraftTakeoff"
elif action == "ON STATION":
return "missionOnStation" |
def solve(input, days):
# Lanternfish with internal timer t are the number of lanternfish with timer t+1 after a day
for day in range(days):
aux = input[0]
input[0] = input[1]
input[1] = input[2]
input[2] = input[3]
input[3] = input[4]
input[4] = input[5]
input[5] = input[6]
# Lantern fish with interal timer 0 replicate, but they have to be added to those lanternfish that have
# a timer equal to 7
input[6] = input[7] + aux
input[7] = input[8]
input[8] = aux
return sum([input[key] for key in input])
# Get input and transform to my chosen data structure
with open('Day6_input.txt','r') as inputfile:
input = inputfile.read().split(",")
input = [int(element) for element in input]
# Lanterfish dictionary where the key represents their internal timer, and the value how many lanternfish
# with that internal timer are alive right now
input = {
0: input.count(0),
1: input.count(1),
2: input.count(2),
3: input.count(3),
4: input.count(4),
5: input.count(5),
6: input.count(6),
7: input.count(7),
8: input.count(8)
}
part1_sol = solve(input,80)
print("Part 1 solution: ",part1_sol)
# 80 days have already been calculated, we take advantage of it
part2_sol = solve(input,256 - 80)
print("Part 2 solution: ",part2_sol) |
def funcao1(funcao, *args, **kwargs):
return funcao(*args, **kwargs)
def funcao2(nome):
return f'Oi {nome}'
def funcao3(nome, saudacao):
return f'{saudacao} {nome}'
executando = funcao1(funcao2, 'Luiz')
print(executando)
executando = funcao1(funcao3, 'Luiz', saudacao='Bom dia')
print(executando)
|
true = True;
false = False;
true1 = "True";
false1 = "False";
true2 = true; ''' I was trying to check if keyword is case sensitive which it is not but here the above defined variable value is taken which is bool
This technique can be used to define case insensitive keywords at start to py program.'''
false2 = false;
print(true,type(true));
print(false,type(false));
print(true1,type(true1));
print(false1,type(false1));
print(true2,type(true2));
print(false2,type(false2));
|
## input = 1,2,3,4
## output = ['1','2','3','4'], ('1','2','3','4')
def abc():
values = input()
print("----")
print(values)
print("----")
x = values.split(",")
print(x)
y = tuple(x)
print("===")
print(y)
if __name__ == "__main__":
abc()
|
#!/usr/bin/env python3
FILENAME = "/tmp/passed"
bmks = []
with open(FILENAME, "r") as f:
for l in f:
[m, a] = l.split(" ")
t = (m, a.strip())
bmks.append(t)
def quote(s):
return '"{}"'.format(s)
indent = " "
output = '{}[ {}\n{}]'.format(indent, f'\n{indent}, '.join(f'("{m}", "{a}")' for m, a in bmks), indent)
print("passedTests :: [(String, String)]")
print("passedTests =")
print(output)
|
class Solution:
def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
"""BFS.
"""
words = set(wordList)
if endWord not in words:
return 0
layer = set([beginWord])
res = 1
while layer:
nlayer = set()
for word in layer:
if word == endWord:
return res
for i in range(len(word)):
for c in string.ascii_lowercase:
nword = word[:i] + c + word[i+1:]
if nword in words:
nlayer.add(nword)
words -= nlayer
layer = nlayer
res += 1
return 0
|
{
"includes": [
"../common.gypi"
],
"targets": [
{
"target_name": "libgdal_ogr_vrt_frmt",
"type": "static_library",
"sources": [
"../gdal/ogr/ogrsf_frmts/vrt/ogrvrtlayer.cpp",
"../gdal/ogr/ogrsf_frmts/vrt/ogrvrtdriver.cpp",
"../gdal/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp"
],
"include_dirs": [
"../gdal/ogr/ogrsf_frmts/vrt"
]
}
]
}
|
class Compose(object):
"""Composes several transforms together for object detection.
Args:
transforms (list of ``Transform`` objects): list of transforms to compose.
"""
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, image, target):
for t in self.transforms:
image, target = t(image, target)
return image, target
|
def subarraysCountBySum(a, k, s):
ans=0
n=len(a)
t=0
ii=1
while(k+t<=n):
tmp=[]
for i in range(t,ii+t):
tmp.append(a[i])
print(tmp)
ii+=1
if len(tmp)<=k and sum(tmp)==s:
ans+=1
t+=1
else:
break
return ans
a=list(map(int,input().split()))
k,s=map(int,input().split())
print(subarraysCountBySum(a, k, s))
|
def main(request, response):
response.headers.set(b"Content-Type", b"text/plain")
response.status = 200
response.content = request.headers.get(b"Content-Type")
response.close_connection = True
|
fruits = ['banana', 'orange', 'mango', 'lemon']
fruit = str(input('Enter a fruit: ')).strip().lower()
if fruit not in fruits:
fruits.append(fruit)
print(fruits)
else:
print(f'{fruit} already in the list')
|
amount = 20
num=1
def setup():
size(640, 640)
stroke(0, 150, 255, 100)
def draw():
global num, amount
fill(0, 40)
rect(-1, -1, width+1, height+1)
maxX = map(mouseX, 0, width, 1, 250)
translate(width/2, height/2)
for i in range(0,360,amount):
x = sin(radians(i+num)) * maxX
y = cos(radians(i+num)) * maxX
x2 = sin(radians(i+amount-num)) * maxX
y2 = cos(radians(i+amount-num)) * maxX
noFill()
bezier(x, y, x-x2, y-y2, x2-x, y2-y, x2, y2)
bezier(x, y, x+x2, y+y2, x2+x, y2+y, x2, y2)
fill(0, 150, 255)
ellipse(x, y, 5, 5)
ellipse(x2, y2, 5, 5)
num += 0.5;
|
class EmailValidator(object):
"""Abstract email validator to subclass from.
You should not instantiate an EmailValidator, as it merely provides the
interface for is_email, not an implementation.
"""
def is_email(self, address, diagnose=False):
"""Interface for is_email method.
Keyword arguments:
address -- address to check.
diagnose -- flag to report a diagnose or just True/False
"""
raise NotImplementedError()
is_valid = is_email
|
# Copyright (c) Microsoft Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
async def test_listeners(page, server):
log = []
def print_response(response):
log.append(response)
page.on("response", print_response)
await page.goto(f"{server.PREFIX}/input/textarea.html")
assert len(log) > 0
page.remove_listener("response", print_response)
log = []
await page.goto(f"{server.PREFIX}/input/textarea.html")
assert len(log) == 0
|
class Backend(object):
# should be implemented all methods
def set(self, name, value):
raise NotImplementedError()
def get(self, name):
raise NotImplementedError()
def delete(self, name):
raise NotImplementedError()
def set_fields(self):
raise NotImplementedError()
def fields(self):
raise NotImplementedError()
def values(self):
raise NotImplementedError()
class AbstractBackend(Backend):
bucket_prefix = 'ONTHEFLY'
def __init__(self, options, original=None):
self.options = options
self.original = original
self.field_registry = None
self.value_registry = {}
def get_value_from_original_settings(self, name):
return getattr(self.original, name)
def get_fields(self):
if self.field_registry is None:
self.field_registry = self.fields()
return self.field_registry
def add_field(self, name):
if name not in self.get_fields():
self.field_registry.append(name)
self.set_fields()
def delete_field(self, name):
if name in self.field_registry:
self.field_registry.remove(name)
self.set_fields()
def set_value(self, name, value):
if name in self.value_registry:
del self.value_registry[name]
return self.set(name, value)
def get_value(self, name):
if name in self.value_registry:
value = self.value_registry[name]
else:
value = self.get(name)
self.value_registry[name] = value
return value
def delete_value(self, name):
if name in self.value_registry:
del self.value_registry[name]
return self.delete(name)
|
number_of_days = int(input())
type_of_room = str(input())
rating = str(input())
room_for_one_person = 18.00
apartment = 25.00
president_apartment = 35.00
apartment_discount = 0
president_apartment_discount = 0
total_price_for_a_room = 0
total_price_for_apartment = 0
total_price_for_presidential_apartment = 0
additional_discount = 0
additional_pay = 0
room_with_discounts = 0
apartment_with_discounts = 0
president_apartment_with_discounts = 0
apartment1 = 0
president_apartment1 = 0
if type_of_room == 'room for one person' or type_of_room == 'apartment' or \
type_of_room == 'president apartment':
nights = number_of_days - 1
if type_of_room == 'room for one person':
total_price_for_a_room = room_for_one_person * nights
if rating == 'positive':
additional_pay = total_price_for_a_room * 0.25
room_with_discounts = total_price_for_a_room + additional_pay
elif rating == 'negative':
additional_discount = total_price_for_a_room * 0.10
room_with_discounts = total_price_for_a_room - additional_discount
print(f'{room_with_discounts:.2f}')
elif type_of_room == 'apartment':
total_price_for_apartment = apartment * nights
if number_of_days < 10:
apartment_discount = total_price_for_apartment * 0.30
elif 10 <= number_of_days <= 15:
apartment_discount = total_price_for_apartment * 0.35
elif number_of_days > 15:
apartment_discount = total_price_for_apartment * 0.50
apartment1 = total_price_for_apartment - apartment_discount
if rating == 'positive':
additional_pay = apartment1 * 0.25
apartment_with_discounts = apartment1 + additional_pay
elif rating == 'negative':
additional_discount = apartment1 * 0.10
apartment_with_discounts = apartment1 - additional_discount
print(f'{apartment_with_discounts:.2f}')
elif type_of_room == 'president apartment':
total_price_for_presidential_apartment = president_apartment * nights
if number_of_days < 10:
president_apartment_discount = total_price_for_presidential_apartment * 0.10
elif 10 <= number_of_days <= 15:
president_apartment_discount = total_price_for_presidential_apartment * 0.15
elif number_of_days > 15:
president_apartment_discount = total_price_for_presidential_apartment * 0.20
president_apartment1 = total_price_for_presidential_apartment - president_apartment_discount
if rating == 'positive':
additional_pay = president_apartment1 * 0.25
president_apartment_with_discounts = president_apartment1 + additional_pay
elif rating == 'negative':
additional_discount = president_apartment1 * 0.10
president_apartment_with_discounts = president_apartment1 - additional_discount
print(f'{president_apartment_with_discounts:.2f}')
|
LIST_WORKFLOWS_GQL = '''
query workflowList {
workflowList {
edges{
node {
id
name
objectType
initialPrefetch
initialState {
id
name
}
initialTransition {
id
name
}
}
}
}
}
'''
LIST_STATES_GQL = '''
query stateList {
stateList {
edges{
node {
id
name
active
initial
workflow {
id
name
}
}
}
}
}
'''
MUTATE_WORKFLOW_GRAPH_GQL = '''
mutation workflowMutation($param: WorkflowMutationInput!) {
workflowMutation(input:$param) {
id
name
initialPrefetch
objectType
errors {
messages
}
}
}
'''
MUTATE_STATE_GRAPH_GQL = '''
mutation stateMutation($param: StateMutationInput!) {
stateMutation(input:$param) {
id
name
initial
active
workflow
errors {
messages
}
}
}
'''
LIST_TRANSITIONS_GQL = '''
query transitionList($param: ID) {
transitionList(workflow_Id:$param) {
edges{
node {
id
name
initialState {
id
name
active
initial
variableDefinitions {
edges {
node {
id
name
}
}
}
}
finalState {
id
name
active
initial
variableDefinitions {
edges {
node {
id
name
}
}
}
}
conditionSet {
edges {
node {
id
conditionType
functionSet {
edges {
node {
id
functionModule
functionName
parameters{
edges {
node {
id
name
value
}
}
}
}
}
}
}
}
}
}
}
}
}
'''
LIST_WORKFLOW_STATES_GQL = '''
query stateList($param: ID) {
stateList(workflow_Id:$param) {
edges{
node {
id
name
active
initial
workflow {
id
name
}
}
}
}
}
'''
LIST_WORKFLOW_GRAPH_GQL = '''
query workflowList($param: String) {
workflowList(name:$param) {
edges{
node {
id
name
graph
}
}
}
}
''' |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
x = ['0', '1', '8']
t = int(int(input()))
for _ in range(t):
n = int(input())
if str(n) == str(n)[::-1] and set(str(n)).issubset(x):
print('YES')
else:
print('NO')
|
"""
if __name__ == '__main__':
for _ in range(int(input())):
name = input()
score = float(input())
"""
# pythonNestedLists.py
#!/usr/bin/env python
N = int(input())
students = list()
for i in range(N):
students.append([input(), float(input())])
scores = set([students[x][1] for x in range(N)])
scores = list(scores)
scores.sort()
students = [x[0] for x in students if x[1] == scores[1]]
students.sort()
for s in students:
print (s)
|
with open("text.txt", "w") as my_file:
my_file.write("Tretas dos Bronzetas")
if my_file.closed == False:
my_file.close()
print(my_file.closed)
|
test = {
'name': 'Mutability',
'points': 0,
'suites': [
{
'type': 'wwpp',
'cases': [
{
'code': """
>>> lst = [5, 6, 7, 8]
>>> lst.append(6)
Nothing
>>> lst
[5, 6, 7, 8, 6]
>>> lst.insert(0, 9)
>>> lst
[9, 5, 6, 7, 8, 6]
>>> x = lst.pop(2)
>>> lst
[9, 5, 7, 8, 6]
>>> lst.remove(x)
>>> lst
[9, 5, 7, 8]
>>> a, b = lst, lst[:]
>>> a is lst
True
>>> b == lst
True
>>> b is lst
False
"""
},
]
},
{
'type': 'wwpp',
'cases': [
{
'code': """
>>> pokemon = {'pikachu': 25, 'dragonair': 148, 'mew': 151}
>>> pokemon['pikachu']
25
>>> len(pokemon)
3
>>> pokemon['jolteon'] = 135
>>> pokemon['mew'] = 25
>>> len(pokemon)
4
>>> 'mewtwo' in pokemon
False
>>> 'pikachu' in pokemon
True
>>> 25 in pokemon
False
>>> 148 in pokemon.values()
True
>>> 151 in pokemon.keys()
False
>>> 'mew' in pokemon.keys()
True
>>> pokemon['ditto'] = pokemon['jolteon']
>>> pokemon['ditto']
135
"""
},
]
}
]
}
|
DESCRIBE_VMS = [
{
"id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM",
"type": "Microsoft.Compute/virtualMachines",
"location": "West US",
"resource_group": "TestRG",
"name": "TestVM",
"plan": {
"product": "Standard",
},
"handware_profile": {
"vm_size": "Standard_D2s_v3",
},
"license_type": "Windows_Client ",
"os_profile": {
"computer_name": "TestVM",
},
"identity": {
"type": "SystemAssigned",
},
"zones": [
"West US 2",
],
"additional_capabilities": {
"ultra_ssd_enabled": True,
},
"priority": "Low",
"eviction_policy": "Deallocate",
},
{
"id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM1",
"type": "Microsoft.Compute/virtualMachines",
"location": "West US",
"resource_group": "TestRG",
"name": "TestVM1",
"plan": {
"product": "Standard",
},
"handware_profile": {
"vm_size": "Standard_D2s_v3",
},
"license_type": "Windows_Client ",
"os_profile": {
"computer_name": "TestVM1",
},
"identity": {
"type": "SystemAssigned",
},
"zones": [
"West US 2",
],
"additional_capabilities": {
"ultra_ssd_enabled": True,
},
"priority": "Low",
"eviction_policy": "Deallocate",
},
]
DESCRIBE_VM_DATA_DISKS = [
{
"lun": 0,
"name": "dd0",
"create_option": "Empty",
"caching": "ReadWrite",
"managed_disk": {
"storage_account_type": "Premium_LRS",
"id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd0",
},
"disk_size_gb": 30,
},
{
"lun": 0,
"name": "dd1",
"create_option": "Empty",
"caching": "ReadWrite",
"managed_disk": {
"storage_account_type": "Premium_LRS",
"id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd1",
},
"disk_size_gb": 30,
},
]
DESCRIBE_DISKS = [
{
"id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd0",
"type": "Microsoft.Compute/disks",
"location": "West US",
"resource_group": "TestRG",
"name": "dd0",
"creation_data": {
"create_option": "Attach",
},
"disk_size_gb": 100,
"encryption_settings_collection": {
"enabled": True,
},
"max_shares": 10,
"network_access_policy": "AllowAll",
"os_type": "Windows",
"tier": "P4",
"sku": {
"name": "Standard_LRS",
},
"zones": [
"West US 2",
],
},
{
"id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd1",
"type": "Microsoft.Compute/disks",
"location": "West US",
"resource_group": "TestRG",
"name": "dd1",
"creation_data": {
"create_option": "Attach",
},
"disk_size_gb": 100,
"encryption_settings_collection": {
"enabled": True,
},
"max_shares": 10,
"network_access_policy": "AllowAll",
"os_type": "Windows",
"tier": "P4",
"sku": {
"name": "Standard_LRS",
},
"zones": [
"West US 2",
],
},
]
DESCRIBE_SNAPSHOTS = [
{
"id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/snapshots/ss0",
"type": "Microsoft.Compute/snapshots",
"location": "West US",
"resource_group": "TestRG",
"name": "ss0",
"creation_data": {
"create_option": "Attach",
},
"disk_size_gb": 100,
"encryption_settings_collection": {
"enabled": True,
},
"incremental": True,
"network_access_policy": "AllowAll",
"os_type": "Windows",
"tier": "P4",
"sku": {
"name": "Standard_LRS",
},
},
{
"id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/snapshots/ss1",
"type": "Microsoft.Compute/snapshots",
"location": "West US",
"resource_group": "TestRG",
"name": "ss1",
"creation_data": {
"create_option": "Attach",
},
"disk_size_gb": 100,
"encryption_settings_collection": {
"enabled": True,
},
"incremental": True,
"network_access_policy": "AllowAll",
"os_type": "Windows",
"tier": "P4",
"sku": {
"name": "Standard_LRS",
},
},
]
DESCRIBE_VMEXTENSIONS = [
{
"id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\
virtualMachines/TestVM/extensions/extensions1",
"type":
"Microsoft.Compute/virtualMachines/extensions",
"resource_group":
"TestRG",
"name":
"extensions1",
"location": "West US",
"vm_id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM",
},
{
"id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\
virtualMachines/TestVM1/extensions/extensions2",
"type":
"Microsoft.Compute/virtualMachines/extensions",
"resource_group":
"TestRG",
"name":
"extensions2",
"location": "West US",
"vm_id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM1",
},
]
DESCRIBE_VMAVAILABLESIZES = [
{
"numberOfCores":
2,
"type":
"Microsoft.Compute/virtualMachines/availablesizes",
"osDiskSizeInMB":
1234,
"name":
"size1",
"resourceDiskSizeInMB":
2312,
"memoryInMB":
4352,
"maxDataDiskCount":
3214,
"vm_id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM",
},
{
"numberOfCores":
2,
"type":
"Microsoft.Compute/virtualMachines/availablesizes",
"osDiskSizeInMB":
1234,
"name":
"size2",
"resourceDiskSizeInMB":
2312,
"memoryInMB":
4352,
"maxDataDiskCount":
3214,
"vm_id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM1",
},
]
DESCRIBE_VMSCALESETS = [
{
"id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\
virtualMachineScaleSets/set1",
"type":
"Microsoft.Compute/virtualMachineScaleSets",
"resource_group":
"TestRG",
"name":
"set1",
"location": "West US",
},
{
"id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\
virtualMachineScaleSets/set2",
"type":
"Microsoft.Compute/virtualMachineScaleSets",
"resource_group":
"TestRG",
"name":
"set2",
"location": "West US",
},
]
DESCRIBE_VMSCALESETEXTENSIONS = [
{
"id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\
virtualMachineScaleSets/set1/extensions/extension1",
"type":
"Microsoft.Compute/virtualMachineScaleSets/extensions",
"resource_group":
"TestRG",
"name":
"extension1",
"set_id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\
virtualMachineScaleSets/set1",
},
{
"id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\
virtualMachineScaleSets/set2/extensions/extension2",
"type":
"Microsoft.Compute/virtualMachineScaleSets/extensions",
"resource_group":
"TestRG",
"name":
"extension2",
"set_id":
"/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\
virtualMachineScaleSets/set2",
},
]
|
n = int(input('Informe um número: '))
print('Analisando o número: {}'.format(n))
u = n // 1 % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // 1000 % 10
print('Unidade: {}\nDezena: {}\nCentena: {}\nMilhar: {}'.format(u, d, c, m))
|
'''
Pattern
Enter number of rows: 5
1
21
321
4321
54321
'''
print('Number Pattern:')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(row,0,-1):
if column < 10:
print(f'0{column}',end=' ')
else:
print(column,end=' ')
print() |
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
dic = {'1': '1', '6': '9', '8': '8', '9': '6', '0': '0'}
l, r = 0, len(num)-1
while l <= r:
if num[l] not in dic or dic[num[l]] != num[r]:
return False
l += 1
r -= 1
return True
|
# Runtime: 128 ms
# Beats 99.53% of Python submissions
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def insertIntoBST(self, root, val):
"""
:type root: TreeNode
:type val: int
:rtype: TreeNode
"""
curr_root = root
if not curr_root:
root = TreeNode(val)
return root
while curr_root:
if curr_root.val > val:
if curr_root.left:
curr_root = curr_root.left
else:
curr_root.left = TreeNode(val)
return root
else:
if curr_root.right:
curr_root = curr_root.right
else:
curr_root.right = TreeNode(val)
return root
return root
# Or, 4 ms slower recursive solution:
# def insertIntoBST(self, root, val):
# """
# :type root: TreeNode
# :type val: int
# :rtype: TreeNode
# """
# if not root:
# return TreeNode(val)
# else:
# if root.val > val:
# if not root.left:
# root.left = TreeNode(val)
# else:
# self.insertIntoBST(root.left, val)
# else:
# if not root.right:
# root.right = TreeNode(val)
# else:
# self.insertIntoBST(root.right, val)
# return root
|
"""
Iterate List of list vertically
tags : Twitter, array
"""
class Solution():
def vertical_iterator(self, arr):
ans = []
arr_len = len(arr)
col = 0
while True:
is_empty = True
for x in range(arr_len):
if col < len(arr[x]):
is_empty = False
ans.append(arr[x][col])
if is_empty:
break
col += 1
print (ans)
abc = Solution()
abc.vertical_iterator([
[5,6],
[7],
[1,2,3,4],
])
|
# -*- coding: utf-8 -*-
name = 'usd'
version = '20.02'
requires = [
'alembic-1.5',
'boost-1.55',
'tbb-4.4.6',
'opensubdiv-3.2',
'ilmbase-2.2',
'jinja-2',
'jemalloc-4',
'openexr-2.2',
'pyilmbase-2.2',
'materialx',
'oiio-1.8',
'ptex-2.0',
'PyOpenGL',
'embree_lib',
'glew',
'renderman-22.6',
'ocio-1.0.9'
]
build_requires = [
'pyside-1.2'
]
private_build_requires = [
'cmake-3.2'
]
variants = [['platform-linux', 'arch-x86_64']]
def commands():
env.PYTHONPATH.append('{root}/lib/python')
env.LD_LIBRARY_PATH.append('{root}/lib/')
appendenv('PATH', '{root}/bin/')
|
contador = 1
while contador <= 9:
for contador2 in range(7, 4, -1):
print(f'I={contador} J={contador2}')
contador += 2 |
hora = int(input('quantas horas trabalha por mes: '))
money = float(input('quanto ganha por hora: '))
salario = hora * money
ir = salario * 0.11
inss = salario * 0.08
sindicato = salario * 0.05
salario2 = (((salario - ir)-inss)-sindicato)
print('''
+ Salário Bruto : R${}
- IR (11%) : R${}
- INSS (8%) : R${}
- Sindicato ( 5%) : R${}
= Salário Liquido : R${}'''.format(salario,ir,inss,sindicato,salario2)) |
# Advent of Code - Day 4
valid_passport_data = {
'ecl', 'pid', 'eyr', 'hcl',
'byr', 'iyr', 'hgt',
}
count_required_data = len(valid_passport_data)
def ecl_rule(value):
return value in {'amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'}
def pid_rule(value):
try:
int(value)
isnumber = True
except:
isnumber = False
return (len(value) == 9) and isnumber
def eyr_rule(value):
try:
year = int(value)
except:
return False
return year >= 2020 and year <= 2030
def hcl_rule(value):
try:
int(value[1:], 16)
except:
return False
return value[0] == '#' and len(value) == 7
def byr_rule(value):
try:
year = int(value)
except:
return False
return year >= 1920 and year <= 2002
def iyr_rule(value):
try:
year = int(value)
except:
return False
return year >= 2010 and year <= 2020
def hgt_rule(value):
units = value[-2:]
try:
height = float(value[:-2])
except:
return False
if units == 'cm':
return height >= 150.00 and height <= 193.00
if units == 'in':
return height >= 59.00 and height <= 76.00
return False
validation_rules = {
'ecl': ecl_rule,
'pid': pid_rule,
'eyr': eyr_rule,
'hcl': hcl_rule,
'byr': byr_rule,
'hgt': hgt_rule,
'iyr': iyr_rule
}
def load_passports(path):
with open(path, 'r') as file:
lines = file.readlines()
passports = []
passport_data = {}
for line in lines:
if ':' in line:
key_value_list = line.split()
for key_value in key_value_list:
key, value = key_value.split(':')
passport_data[key] = value
else:
passports.append(passport_data)
passport_data = {}
passports.append(passport_data)
return passports
def validate_passport(passport):
keys = set(passport)
common_data = valid_passport_data.intersection(keys)
if len(common_data) == count_required_data:
is_valid = True
for key in keys:
if key == 'cid':
continue
try:
value = passport[key]
is_valid = (is_valid and validation_rules[key](value))
except Exception as e:
print(f'ValidationError: {e}')
return int(is_valid)
return 0
# === MAIN ===
valid_passports_count = 0
passports = load_passports('day4.txt')
for p in passports:
valid_passports_count += validate_passport(p)
print(valid_passports_count)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-----------------------------------
# AutoNaptPython
#
# Copyright (c) 2018 RainForest
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
#-----------------------------------
class Event2(object):
def __init__(self, doc = None):
self.handlers = []
self.__doc__ = doc
def __str__(self):
return 'Event<%s>' % str(self.__doc__)
def add(self, handler):
self.handlers.append(handler)
return self
def remove(self, handler):
self.handlers.remove(handler)
return self
def __call__(self, sender, e):
for handler in self.handlers:
handler(sender, e)
__iadd__ = add
__isub__ = remove
|
class Parser:
def __init__(self, directory, rel_path):
pass
def parse(self):
return {}, []
def get_parser(): return 5
|
load("@bazel_tools//tools/jdk:toolchain_utils.bzl", "find_java_runtime_toolchain", "find_java_toolchain")
def _proto_path(proto):
"""
The proto path is not really a file path
It's the path to the proto that was seen when the descriptor file was generated.
"""
path = proto.path
root = proto.root.path
ws = proto.owner.workspace_root
if path.startswith(root):
path = path[len(root):]
if path.startswith("/"):
path = path[1:]
if path.startswith(ws):
path = path[len(ws):]
if path.startswith("/"):
path = path[1:]
return path
def _protoc_cc_output_files(proto_file_sources):
cc_hdrs = []
cc_srcs = []
for p in proto_file_sources:
basename = p.basename[:-len(".proto")]
cc_hdrs.append(basename + ".pb.h")
cc_hdrs.append(basename + ".pb.validate.h")
cc_srcs.append(basename + ".pb.cc")
cc_srcs.append(basename + ".pb.validate.cc")
return cc_hdrs + cc_srcs
def _proto_sources(ctx):
protos = []
for dep in ctx.attr.deps:
protos += [f for f in dep[ProtoInfo].direct_sources]
return protos
def _output_dir(ctx):
dir_out = ctx.genfiles_dir.path
if ctx.label.workspace_root:
dir_out += "/" + ctx.label.workspace_root
return dir_out
def _protoc_gen_validate_cc_impl(ctx):
"""Generate C++ protos using protoc-gen-validate plugin"""
protos = _proto_sources(ctx)
cc_files = _protoc_cc_output_files(protos)
out_files = [ctx.actions.declare_file(out) for out in cc_files]
dir_out = _output_dir(ctx)
args = [
"--cpp_out=" + dir_out,
"--validate_out=lang=cc:" + dir_out,
]
return _protoc_gen_validate_impl(
ctx = ctx,
lang = "cc",
protos = protos,
out_files = out_files,
protoc_args = args,
package_command = "true",
)
def _protoc_python_output_files(proto_file_sources):
python_srcs = []
for p in proto_file_sources:
basename = p.basename[:-len(".proto")]
python_srcs.append(basename.replace("-", "_", maxsplit = None) + "_pb2.py")
return python_srcs
def _protoc_gen_validate_python_impl(ctx):
"""Generate Python protos using protoc-gen-validate plugin"""
protos = _proto_sources(ctx)
python_files = _protoc_python_output_files(protos)
out_files = [ctx.actions.declare_file(out) for out in python_files]
dir_out = _output_dir(ctx)
args = [
"--python_out=" + dir_out,
]
return _protoc_gen_validate_impl(
ctx = ctx,
lang = "python",
protos = protos,
out_files = out_files,
protoc_args = args,
package_command = "true",
)
def _protoc_gen_validate_impl(ctx, lang, protos, out_files, protoc_args, package_command):
protoc_args.append("--plugin=protoc-gen-validate=" + ctx.executable._plugin.path)
dir_out = ctx.genfiles_dir.path
if ctx.label.workspace_root:
dir_out += "/" + ctx.label.workspace_root
tds = depset([], transitive = [dep[ProtoInfo].transitive_descriptor_sets for dep in ctx.attr.deps])
descriptor_args = [ds.path for ds in tds.to_list()]
if len(descriptor_args) != 0:
protoc_args += ["--descriptor_set_in=%s" % ctx.configuration.host_path_separator.join(descriptor_args)]
package_command = package_command.format(dir_out = dir_out)
ctx.actions.run_shell(
outputs = out_files,
inputs = protos + tds.to_list(),
tools = [ctx.executable._plugin, ctx.executable._protoc],
command = " && ".join([
ctx.executable._protoc.path + " $@",
package_command,
]),
arguments = protoc_args + [_proto_path(proto) for proto in protos],
mnemonic = "ProtoGenValidate" + lang.capitalize() + "Generate",
use_default_shell_env = True,
)
return struct(
files = depset(out_files),
)
cc_proto_gen_validate = rule(
attrs = {
"deps": attr.label_list(
mandatory = True,
providers = [ProtoInfo],
),
"_protoc": attr.label(
cfg = "host",
default = Label("@com_google_protobuf//:protoc"),
executable = True,
allow_single_file = True,
),
"_plugin": attr.label(
cfg = "host",
default = Label("@com_envoyproxy_protoc_gen_validate//:protoc-gen-validate"),
allow_files = True,
executable = True,
),
},
output_to_genfiles = True,
implementation = _protoc_gen_validate_cc_impl,
)
_ProtoValidateSourceInfo = provider(
fields = {
"sources": "Depset of sources created by protoc with protoc-gen-validate plugin",
},
)
def _create_include_path(include):
return "--proto_path={0}={1}".format(_proto_path(include), include.path)
def _java_proto_gen_validate_aspect_impl(target, ctx):
proto_info = target[ProtoInfo]
includes = proto_info.transitive_imports
srcs = proto_info.direct_sources
options = ",".join(["lang=java"])
srcjar = ctx.actions.declare_file("%s-validate-gensrc.jar" % ctx.label.name)
args = ctx.actions.args()
args.add(ctx.executable._plugin.path, format = "--plugin=protoc-gen-validate=%s")
args.add("--validate_out={0}:{1}".format(options, srcjar.path))
args.add_all(includes, map_each = _create_include_path)
args.add_all(srcs, map_each = _proto_path)
ctx.actions.run(
inputs = depset(transitive = [proto_info.transitive_imports]),
outputs = [srcjar],
executable = ctx.executable._protoc,
arguments = [args],
tools = [ctx.executable._plugin],
progress_message = "Generating %s" % srcjar.path,
)
return [_ProtoValidateSourceInfo(
sources = depset(
[srcjar],
transitive = [dep[_ProtoValidateSourceInfo].sources for dep in ctx.rule.attr.deps],
),
)]
_java_proto_gen_validate_aspect = aspect(
_java_proto_gen_validate_aspect_impl,
provides = [_ProtoValidateSourceInfo],
attr_aspects = ["deps"],
attrs = {
"_protoc": attr.label(
cfg = "host",
default = Label("@com_google_protobuf//:protoc"),
executable = True,
allow_single_file = True,
),
"_plugin": attr.label(
cfg = "host",
default = Label("@com_envoyproxy_protoc_gen_validate//:protoc-gen-validate"),
allow_files = True,
executable = True,
),
},
)
def _java_proto_gen_validate_impl(ctx):
source_jars = [source_jar for dep in ctx.attr.deps for source_jar in dep[_ProtoValidateSourceInfo].sources.to_list()]
deps = [java_common.make_non_strict(dep[JavaInfo]) for dep in ctx.attr.java_deps]
deps += [dep[JavaInfo] for dep in ctx.attr._validate_deps]
java_info = java_common.compile(
ctx,
source_jars = source_jars,
deps = deps,
output_source_jar = ctx.outputs.srcjar,
output = ctx.outputs.jar,
java_toolchain = find_java_toolchain(ctx, ctx.attr._java_toolchain),
host_javabase = find_java_runtime_toolchain(ctx, ctx.attr._host_javabase),
)
return [java_info]
"""Bazel rule to create a Java protobuf validation library from proto sources files.
Args:
deps: proto_library rules that contain the necessary .proto files
java_deps: the java_proto_library of the protos being compiled.
"""
java_proto_gen_validate = rule(
attrs = {
"deps": attr.label_list(
providers = [ProtoInfo],
aspects = [_java_proto_gen_validate_aspect],
mandatory = True,
),
"java_deps": attr.label_list(
providers = [JavaInfo],
mandatory = True,
),
"_validate_deps": attr.label_list(
default = [
Label("@com_envoyproxy_protoc_gen_validate//validate:validate_java"),
Label("@com_google_re2j//jar"),
Label("@com_google_protobuf//:protobuf_java"),
Label("@com_google_protobuf//:protobuf_java_util"),
Label("@com_envoyproxy_protoc_gen_validate//java/pgv-java-stub/src/main/java/io/envoyproxy/pgv"),
Label("@com_envoyproxy_protoc_gen_validate//java/pgv-java-validation/src/main/java/io/envoyproxy/pgv"),
],
),
"_java_toolchain": attr.label(default = Label("@bazel_tools//tools/jdk:current_java_toolchain")),
"_host_javabase": attr.label(
cfg = "host",
default = Label("@bazel_tools//tools/jdk:current_host_java_runtime"),
),
},
fragments = ["java"],
provides = [JavaInfo],
outputs = {
"jar": "lib%{name}.jar",
"srcjar": "lib%{name}-src.jar",
},
implementation = _java_proto_gen_validate_impl,
)
python_proto_gen_validate = rule(
attrs = {
"deps": attr.label_list(
mandatory = True,
providers = ["proto"],
),
"_protoc": attr.label(
cfg = "host",
default = Label("@com_google_protobuf//:protoc"),
executable = True,
allow_single_file = True,
),
"_plugin": attr.label(
cfg = "host",
default = Label("@com_envoyproxy_protoc_gen_validate//:protoc-gen-validate"),
allow_files = True,
executable = True,
),
},
output_to_genfiles = True,
implementation = _protoc_gen_validate_python_impl,
)
|
# Set up constants
WIDTH = 25
HEIGHT = 6
LAYER_SIZE = WIDTH * HEIGHT
# Read in the input file and convert to a list
pixel_string = ""
with open("./input.txt") as f:
pixel_string = f.readline()
unlayered_pixel_values = list(pixel_string.strip())
# Make into a list of layers
idx = 0
layers = []
while idx < len(unlayered_pixel_values):
layers.append(unlayered_pixel_values[idx:(idx + LAYER_SIZE)])
idx += LAYER_SIZE
# Find the layer with the fewest zeroes
fewest_zeroes = LAYER_SIZE + 1
layer_with_fewest_zeroes = None
for i, layer in enumerate(layers):
zeroes = 0
for pixel in layer:
if pixel == "0":
zeroes += 1
if zeroes < fewest_zeroes:
fewest_zeroes = zeroes
layer_with_fewest_zeroes = i
# For the layer with the fewest zeroes, count the ones and twos
# and then print the product of the ones and the twos
layer_of_interest = layers[layer_with_fewest_zeroes]
ones = 0
twos = 0
for pixel in layer_of_interest:
if pixel == "1":
ones += 1
if pixel == "2":
twos += 1
product = ones * twos
print(product)
|
def pg_version(conn):
"""
Returns the PostgreSQL server version as numeric and full version.
"""
num_version = conn.get_pg_version()
conn.execute("SELECT version()")
full_version = list(conn.get_rows())[0]['version']
return dict(numeric=num_version, full=full_version)
|
class BaseExceptions(Exception):
pass
class DeleteException(BaseException):
"""Raised when delete failed"""
def __init__(self, resp_data):
if isinstance(resp_data, dict):
self.err = ''.join('Failed with reason {}'.format(val) for key, val in resp_data.items())
else:
self.err = 'Delete failed with an unknown reason'
def __str__(self):
return '{}'.format(self.err)
class NotFoundException(BaseException):
"""Raised when item is not found"""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return 'Unable to found {}'.format(self.msg)
class CreateException(BaseException):
"""Raised when creation failed"""
def __init__(self, resp_data):
if isinstance(resp_data, dict):
self.err = ''.join('{} '.format(val[0]) for key, val in resp_data.items())
else:
self.err = 'Creation failed with unknown reason'
def __str__(self):
return '{}'.format(self.err)
class UpdateException(BaseException):
"""Raised when an object update fails"""
def __init__(self, resp_data):
if isinstance(resp_data, dict):
self.err = ''.join('{} '.format(val[0]) for key, val in resp_data.items())
else:
self.err = 'Update failed with unknown reason'
def __str__(self):
return '{}'.format(self.err)
class AuthException(BaseException):
"""Raised when an API call method is not allowed"""
pass
|
def transition(state, char, stack_char):
new_state = -1
new_stack_chars = ""
if state == 0:
new_state = 1
new_stack_chars = "S#"
elif state == 1:
if stack_char in "0123456789+-*:().":
new_state = 1
new_stack_chars = ""
elif stack_char == "S":
if char in "123456789":
new_state = 1
new_stack_chars = "A"
elif char == "0":
new_state = 1
new_stack_chars = "B"
elif char == "(":
new_state = 1
new_stack_chars = "E)R"
elif stack_char == "A":
if char in "0123456789":
new_state = 1
new_stack_chars = "A"
elif char == ".":
new_state = 1
new_stack_chars = "C"
elif char in "+-:*":
new_state = 1
new_stack_chars = "E"
elif stack_char == "B":
if char == ".":
new_state = 1
new_stack_chars = "C"
elif char in "+-:*":
new_state = 1
new_stack_chars = "E"
elif stack_char == "C":
if char in "0123456789":
new_state = 1
new_stack_chars = "D"
elif stack_char == "D":
if char in "0123456789":
new_state = 1
new_stack_chars = "D"
elif char in "+-:*":
new_state = 1
new_stack_chars = "E"
elif stack_char == "E":
if char in "123456789":
new_state = 1
new_stack_chars = "A"
elif char == "0":
new_state = 1
new_stack_chars = "B"
elif char == "(":
new_state = 1
new_stack_chars = "E)R"
elif stack_char == "R":
if char in "+-:*":
new_state = 1
new_stack_chars = "E"
elif char == "":
new_state = 2
elif stack_char == "#":
new_state = 2
return new_state, new_stack_chars
def scan_word(word):
state = 0
stack = ["#"]
for char in word:
stack_char = stack.pop(0)
state, stack_chars = transition(state, char, stack_char)
for sc in reversed(stack_chars):
stack.insert(0, sc)
if len(stack) > 0:
transition(state, "", stack[0])
return word == "" and state == 2
if __name__ == "__main__":
word = input("Bitte ein Wort eingeben: ")
accepted = scan_word(word)
if accepted:
print("Wort gehört zur Sprache")
else:
print("Wort gehört nicht zur Sprache")
|
###### Gui Reis - guisreis25@gmail.com ###### COPYRIGHT © 2020 KINGS
# -*- coding: utf-8 -*-
## Classe responsável pelo dos dias entre duas datas.
class Dif_emDias:
## Construtor: define os atributos separando cada índice da data
def __init__(self) -> None:
# jan,fev,mar,abr,mai,jun,jul,ago,set,out,nov,dez
self.mes = (0,31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) # O zero no início é para igualar a posição com o número do mês
## Destruidor: Deleta os atributos
def __del__(self) -> None:
del self.mes
del self.dia_Ini, self.mes_Ini, self.ano_Ini
del self.dia_Fin, self.mes_Fin, self.ano_Fin
## Método especial: define as datas
def setDatas(self, dt_Ini_:str, dt_Fin_:str) -> None:
# Data Inicial:
self.dia_Ini, self.mes_Ini, self.ano_Ini = map(int, dt_Ini_.split("/")) # Cria os atributos
# Data Final:
self.dia_Fin, self.mes_Fin, self.ano_Fin = map(int, dt_Fin_.split("/"))
## Método: calcula os dias restantes.
def dif_dias(self, mes_maior_, dia_maior_, mes_menor_, dia_menor_) -> int:
d = 0 # Variável para retorno
for m in range(mes_menor_+1, mes_maior_): # Pega o intervalo de meses entre as datas
d += self.mes[m] # Soma eles
d += (self.mes[mes_menor_]-dia_menor_) + dia_maior_ # Soma os dias restantes (dos próprios meses)
return d
## Método: calcula os anos bissextos.
def bissexto(self) -> int:
anos_bi = 0
for inter_anos in range(self.ano_Ini, self.ano_Fin + 1): # Pega o intervalo de anos
if (inter_anos%400 == 0 and inter_anos%4 == 0) or (inter_anos%100 != 0 and inter_anos%4 == 0): # Se for um ano bissexto
anos_bi += 1 # Soma
if (self.mes_Ini >= 2 and self.ano_Ini == inter_anos): # Se o primeiro ano for bissexto e a data for maior que fevereiro
anos_bi -= 1 # Não conta o ano bissexto
return anos_bi
## Método: verifica se é possível fazer a conta.
def is_possible(self) -> bool:
if (self.ano_Ini > self.ano_Fin):
return False
elif (self.ano_Ini == self.ano_Fin) and (self.mes_Ini > self.mes_Fin):
return False
elif (self.ano_Ini == self.ano_Fin) and (self.mes_Ini == self.mes_Fin) and (self.dia_Ini > self.dia_Fin):
return False
return True # Eh válido
## Método: calcula os dias restantes.
def result(self) -> int:
dias_meses = 0
if (self.mes_Fin == self.mes_Ini): # No mesmo mês
dias_meses += abs(self.dia_Ini - self.dia_Fin) # Adiciona a diferença dos dias
elif (self.mes_Fin > self.mes_Ini): # Se passou da data incial
dias_meses += self.dif_dias(self.mes_Fin, self.dia_Fin, self.mes_Ini, self.dia_Ini) # Soma os dias que passaram
else: # Se não passou
dias_meses -= self.dif_dias(self.mes_Ini, self.dia_Ini, self.mes_Fin, self.dia_Fin) # Tira quanto que falta
return (self.ano_Fin-self.ano_Ini)*365 + dias_meses + self.bissexto() # Conta final |
class CommandBuilder():
def __init__(self, cindex):
self.cindex = cindex
class CodeBuilder(CommandBuilder):
def __init__(self, cindex, cmd):
super().__init__(cindex)
self.cmd = cmd
def __str__(self):
return self.cmd
class SlugBuilder(CommandBuilder):
def __init__(self, cindex, time, location, transition):
super().__init__(cindex)
self.time = time
self.location = location
self.transition = transition
def __str__(self):
return F" scene bg {self.location}" + (F"\n with {self.transition}" if self.transition else "")
class ActorBuilder(CommandBuilder):
def __init__(self, cindex, alias, actor):
super().__init__(cindex)
self.alias = alias
self.actor = actor
def __str__(self):
return F"define {self.alias} = Character(\"{self.actor.upper()}\", color=\"#fff\")"
class LineBuilder(CommandBuilder):
def __init__(self, cindex, actor, blocking, line):
super().__init__(cindex)
self.actor = actor
self.blocking = blocking
self.line = line
def __str__(self):
return F" {self.actor} \"{self.line}\"" |
n1=int(input('Digite o primeiro valor: '))
n2=int(input('Digite o segundo valor: '))
o=(input('Digite o operador para conta: '))
if o=='+':
r=n1+n2
print(f'O resultado da conta é {r:,}')
elif o=='-':
r=n1-n2
print(f'O resultado da conta é {r:,}')
elif o=='*':
r==n1*n2
print(f'O resultado da conta é {r:,}')
elif o=='/':
r==n1/n2
print(f'O resultado da conta é {r:,}')
else:
print('Operador não reconhecido ERRO!!!')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.