content stringlengths 7 1.05M |
|---|
"""
𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻:
Implement the design of the Pasta class so that the following output is
produced:
print("Pasta Plate Count:", Pasta.pasta_plate_count)
print("=======================")
s1 = Pasta("Chicken")
s1.set_ingredients("Farfalle",250, 11, 40, 10)
s1.display_all_info()
print("------------------------------------")
s2 = Pasta("Beef")
s2.set_ingredients("Pipe Rigate",150, 10.5, 10, 10)
s2.display_all_info()
print("------------------------------------")
s3 = Pasta("Mushrooms")
s3.set_ingredients("Spaghetti",500, 50, 20, 10)
s3.display_all_info()
print("=======================")
print("Pasta Plate Count:", Pasta.pasta_plate_count)
Output:
Pasta Plate Count: 0
=======================
Pasta Type: Chicken
Shape: Farfalle
Cal: 250 g
Fat: 11 g
Protein: 40 g
Carbohydrate: 10 g
------------------------------------
Pasta Type: Beef
Shape: Pipe Rigate
Cal: 150 g
Fat: 10.5 g
Protein: 10 g
Carbohydrate: 10 g
------------------------------------
Pasta Type: Mushrooms
Shape: Spaghetti
Cal: 500 g
Fat: 50 g
Protein: 20 g
Carbohydrate: 10 g
=======================
Pasta Plate Count: 3
"""
class Pasta:
pasta_plate_count = 0
def __init__(self, name):
self.name = name
Pasta.pasta_plate_count += 1
def set_ingredients(self, type, cal, fat, prot, carb):
self.type = type
self.cal = cal
self.fat = fat
self.prot = prot
self.carb = carb
def display_all_info(self):
s1 = f"Pasta Type: {self.name}\n"
s2 = f"Shape: {self.type}\n"
s3 = f"Cal: {self.cal} g\n"
s4 = f"Fat: {self.fat} g\n"
s5 = f"Protein: {self.prot} g\n"
s6 = f"Carbohydrate: {self.carb} g"
s = s1 + s2 + s3 + s4 + s5 + s6
print(s)
print("Pasta Plate Count:", Pasta.pasta_plate_count)
print("=======================")
s1 = Pasta("Chicken")
s1.set_ingredients("Farfalle", 250, 11, 40, 10)
s1.display_all_info()
print("------------------------------------")
s2 = Pasta("Beef")
s2.set_ingredients("Pipe Rigate", 150, 10.5, 10, 10)
s2.display_all_info()
print("------------------------------------")
s3 = Pasta("Mushrooms")
s3.set_ingredients("Spaghetti", 500, 50, 20, 10)
s3.display_all_info()
print("=======================")
print("Pasta Plate Count:", Pasta.pasta_plate_count)
|
"""
Simply pretty print the adf
"""
class pprint:
"""
class to pretty print the data structure behind adf
>>> pp = pprint()
>>> pp.head()
+------------------+------------------+------------------+
| c1 | c2 | c3 |
+------------------+------------------+------------------+
| 1 | 11 | 11 |
+------------------+------------------+------------------+
| 2 | dsfa | 22 |
+------------------+------------------+------------------+
| 3 | 33 | afsd |
+------------------+------------------+------------------+
| 4 | 44 | sadgsaafgfdhhf...|
+------------------+------------------+------------------+
| 5 | 5 | 5 |
+------------------+------------------+------------------+
>>> pp.tail()
Showing last 5 rows -
+------------------+------------------+------------------+
| c1 | c2 | c3 |
+------------------+------------------+------------------+
| 6 | 6 | 6 |
+------------------+------------------+------------------+
| 7 | 7 | 7 |
| 9 | 9 | sdfa |
+------------------+------------------+------------------+
| 8 | 8 | 8 |
+------------------+------------------+------------------+
+------------------+------------------+------------------+
>>>
"""
def __init__(self):
"""
"""
self.data = {"c1": [1,2,3,4,5,6,7,8,9],
"c2": [11,"dsfa",33,44,5,6,7,8,9],
"c3": [11, 22, "afsd", "sadgsaafgfdhhfdshfdhkdghjlkdfjhdkl", 5, 6, 7, 8, "sdfa"]}
self.n = len(self.data.keys())
def show(self, d):
"""
:param d:
:return:
"""
for row in zip(*([key] + value for key, value in sorted(d.items()))):
print('+'+('-'*18+'+')*self.n)
print("|", *[str(i).strip() + " "*(18-len(str(i))-1) + "|" if len(str(i)) < 18 else str(i)[0:14] + "...|" for i in row])
print('+' + ('-' * 18 + '+')*self.n)
def head(self, n=5):
"""
:param n:
:return:
"""
print("Showing first " + str(n) + " rows - ")
self.show({k: self.data[k][0:5] for k in self.data})
def tail(self, n=5):
"""
:param n:
:return:
"""
print("Showing last "+str(n)+" rows - ")
self.show({k: self.data[k][len(self.data[k])-n+1:] for k in self.data})
|
description = 'NE1002 syringe pump'
pv_root = 'E04-SEE-FLUCO:NE1002x-001:'
devices = dict(
inside_diameter_1002=device(
'nicos_ess.devices.epics.pva.EpicsAnalogMoveable',
description='The Inside diameter of the syringe',
readpv='{}DIAMETER'.format(pv_root),
writepv='{}SET_DIAMETER'.format(pv_root),
epicstimeout=3.0,
abslimits=(0.1, 50),
),
pump_volume_1002=device(
'nicos_ess.devices.epics.pva.EpicsAnalogMoveable',
description='The volume to be pumped',
readpv='{}VOLUME'.format(pv_root),
writepv='{}SET_VOLUME'.format(pv_root),
epicstimeout=3.0,
abslimits=(0.1, 50),
),
pump_volume_units_1002=device(
'nicos_ess.devices.epics.pva.EpicsMappedMoveable',
description='The volume units',
readpv='{}VOLUME_UNITS'.format(pv_root),
writepv='{}SET_VOLUME_UNITS'.format(pv_root),
mapping={'μL': 0, 'mL': 1},
),
pump_rate_1002=device(
'nicos_ess.devices.epics.pva.EpicsAnalogMoveable',
description='The pump rate',
readpv='{}RATE'.format(pv_root),
writepv='{}SET_RATE'.format(pv_root),
epicstimeout=3.0,
abslimits=(0.1, 50),
),
pump_rate_units_1002=device(
'nicos_ess.devices.epics.pva.EpicsMappedMoveable',
description='The rate units',
readpv='{}RATE_UNITS'.format(pv_root),
writepv='{}SET_RATE_UNITS'.format(pv_root),
mapping={'μL / min': 0, 'mL / min': 1, 'μL / hr': 2, 'mL / hr': 3},
),
pump_direction_1002=device(
'nicos_ess.devices.epics.pva.EpicsMappedMoveable',
description='The pump direction',
readpv='{}DIRECTION'.format(pv_root),
writepv='{}SET_DIRECTION'.format(pv_root),
),
volume_withdrawn_1002=device(
'nicos_ess.devices.epics.pva.EpicsReadable',
description='The volume withdrawn',
readpv='{}VOLUME_WITHDRAWN'.format(pv_root),
epicstimeout=3.0,
),
volume_infused_1002=device(
'nicos_ess.devices.epics.pva.EpicsReadable',
description='The volume infused',
readpv='{}VOLUME_INFUSED'.format(pv_root),
epicstimeout=3.0,
),
pump_status_1002=device(
'nicos.devices.epics.EpicsReadable',
description='The pump status',
readpv='{}STATUS'.format(pv_root),
lowlevel=True,
epicstimeout=3.0,
),
pump_message_1002=device(
'nicos_ess.devices.epics.pva.EpicsStringReadable',
description='The pump message',
readpv='{}MESSAGE'.format(pv_root),
lowlevel=True,
epicstimeout=3.0,
),
start_purge_1002=device(
'nicos_ess.devices.epics.extensions.EpicsMappedMoveable',
description='Start purging',
readpv='{}PURGE'.format(pv_root),
writepv='{}PURGE'.format(pv_root),
mapping={'OFF': 0, 'ON': 1},
),
start_pumping_1002=device(
'nicos_ess.devices.epics.extensions.EpicsMappedMoveable',
description='Start pumping',
readpv='{}RUN'.format(pv_root),
writepv='{}RUN'.format(pv_root),
mapping={'OFF': 0, 'ON': 1},
),
pause_pumping_1002=device(
'nicos_ess.devices.epics.extensions.EpicsMappedMoveable',
description='Pause pumping',
readpv='{}PAUSE'.format(pv_root),
writepv='{}PAUSE'.format(pv_root),
mapping={'OFF': 0, 'ON': 1},
),
stop_pumping_1002=device(
'nicos_ess.devices.epics.extensions.EpicsMappedMoveable',
description='Stop pumping',
readpv='{}STOP'.format(pv_root),
writepv='{}STOP'.format(pv_root),
mapping={'OFF': 0, 'ON': 1},
),
seconds_to_pause_1002=device(
'nicos.devices.epics.EpicsAnalogMoveable',
description='How long to pause for (seconds)',
readpv='{}SET_PAUSE'.format(pv_root),
writepv='{}SET_PAUSE'.format(pv_root),
epicstimeout=3.0,
abslimits=(0.1, 50),
),
zero_volume_withdrawn_1002=device(
'nicos.devices.epics.EpicsReadable',
description='Zero volume withdrawn and infused',
readpv='{}CLEAR_V_DISPENSED'.format(pv_root),
epicstimeout=3.0,
),
)
|
'''Faça um programa que leia o sexo de uma pessoa, mas só aceite os valores 'M' ou 'F'.
Caso esteja errado peça a digitação novamente até ter um valor correto, '''
sexo = str(input(''
'\nInforme "M" para Masculino ou "F" para Feminino : ')).upper().strip()[0]
while sexo not in ['M', 'F']:
print(''
'\nSomente são aceito as letras M para masculino e F para Feminino.')
sexo = str(input('Informe "M" para Masculino ou "F" para Feminino : ')).strip()
if sexo in ['m', 'M']:
print(''
'\nO sexo informado foi o sexo Masculino representado pela letra {}.'.format(sexo.upper()))
elif sexo in ['f', 'F']:
print(''
'\nO sexo informado foi o sexo Feminino representado pela letra {}.'.format(sexo.upper()))
print(''
'\nObrigado.!')
# Desafio Concluído |
# Delete Middle Node: Implement an algorithm to delete a node in the middle (i.e., any node but
# the first and last node, not necessarily the exact middle) of a singly linked list, given only access to
# that node.
def delete_mid_node(node):
if node is None or node.get_next_mode() is None:
return False
node.value = node.get_next_mode().get_value()
node.set_next_mode(node.get_next_mode().get_next_mode())
return True
|
'''
Given an array of positive integers.
Find the length of the longest sub-sequence such that elements in the subsequence are consecutive integers,
the consecutive numbers can be in any order.
'''
## function work...!!!!
'''
findLCS() function--> which takes the array arr[]
and the size of the array as inputs and
returns the length of the longest subsequence of consecutive integers.
'''
## Here we use the hashmap to store element..
def findlcs(arr,n):
pass
## Driver code...!!!!
if __name__ == "__main__":
n = int(input())
arr = list(map(int,input().split()))
'''
sample input..
7
2 6 1 9 4 5 3
'''
|
def make_song(verses = 99, beverage = "soda"):
for num in range(verses, -1, -1):
if num == 0:
yield f"No more {beverage}!"
elif num == 1:
yield f"Only {num} bottle of {beverage} left!"
else:
yield f"{num} bottles of {beverage} on the wall."
song = make_song(4, "michelada")
print(next(song))
print(next(song))
print(next(song))
print(next(song))
print(next(song))
print(next(song)) |
# par ou impar com funcoes
def par_impar(x):
if x % 2 == 0:
return 'par'
else:
return 'impar'
# Programa principal
print(par_impar(int(input('Digite um valor inteiro: '))))
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head):
if not head:
return head
count = 1
temp = head
while temp.next:
count += 1
temp = temp.next
curr_count = 0
stack = list()
temp = head
while curr_count != count // 2:
stack.append(temp.val)
temp = temp.next
curr_count += 1
if count % 2 != 0:
temp = temp.next
while temp:
if temp.val != stack.pop():
return False
temp = temp.next
return True
|
def foo():
f = 0.0
while f < 10000000.0:
f = f + 1.0
foo()
|
speed = 108
time = 12
dist = speed * time
print(dist)
# + Сложение 11 6 17
# - Вычитание 11 6 5
# * Умножение 11 6 66
# // Целочисленное деление 11 6 1
# % Остаток от деления 11 6 5
# ** Возведение в степень 2 3 8
goodByePhrase = 'Hasta la vista'
person = 'baby'
print(goodByePhrase + ', ' + person + '!')
answer = '2 + 3 = ' + str(2 + 3)
print(answer)
word = 'Bye'
phrase = word * 3 + '!'
print(phrase) |
#5. Un vendedor recibe mensualmente un sueldo base más un 10%
# extra por comisión de sus ventas. El vendedor desea saber cuánto
# dinero obtendrá por concepto de comisiones por las tres ventas que realiza en el mes y
# el total que recibirá en el mes tomando en cuenta su sueldo base y comisiones.
sueldo=float(input("Ingresa el Sueldo: "))
venta01=float(input("Ingrese venta N° 01: "))
venta02=float(input("Ingrese venta N° 02: "))
venta03=float(input("Ingrese venta N° 03: "))
incremento=0.10
sumaventa=venta01+venta02+venta03
opincremento=sumaventa*incremento
final=sueldo+opincremento
print("el Incremento de 10% es igual= ", opincremento)
print("Total sueldo a recibir + incremento es = ", final)
|
def helper(arr, left_pos, mid_pos, right_pos):
sum1 = sum2 = 0
left_sum = right_sum = -9999
for i in range(mid_pos, left_pos - 1, -1):
sum1 += arr[i]
if sum1 > left_sum:
left_sum = sum1
for i in range(mid_pos + 1, right_pos + 1):
sum2 += arr[i]
if sum2 > right_sum:
right_sum = sum2
maximum = max(left_sum, right_sum, left_sum + right_sum)
return maximum
def max_subarray_sum(arr, left_pos, right_pos):
if left_pos == right_pos:
return arr[0]
else:
mid_pos = (left_pos + right_pos) // 2
left_arr = max_subarray_sum(arr, left_pos, mid_pos)
right_arr = max_subarray_sum(arr, mid_pos + 1, right_pos)
helper_arr = helper(arr, left_pos, mid_pos, right_pos)
maximum = max(left_arr, right_arr, helper_arr)
return maximum
arr = [2, 3, 4, -100, 5, 7, -4]
print(f'Maximum subarray sum is {max_subarray_sum(arr, 0, len(arr) - 1)}')
|
CH_FONTS={
u'\u4e2d':bytearray([
0x01,0x00,0x01,0x00,0x01,0x00,0x3f,0xfc,
0x21,0x04,0x21,0x04,0x21,0x04,0x21,0x04,
0x3f,0xfc,0x21,0x04,0x01,0x00,0x01,0x00,
0x01,0x00,0x01,0x00,0x00,0x00,0x00,0x00
]),
u'\u6587':bytearray([
0x01,0x00,0x01,0x00,0x01,0x80,0x7f,0xfc,
0x18,0x10,0x08,0x20,0x0c,0x20,0x04,0x40,
0x02,0xc0,0x03,0x80,0x03,0x80,0x06,0x60,
0x38,0x38,0x60,0x0c,0x00,0x00,0x00,0x00
]),
} |
class ConfirmationTypes:
"""Self explanatory :("""
"""Received by server if the client's connection is refused.
id:CLIENT_ID, type:CONNECTION_REFUSED"""
CONNECTION_REFUSED = "CONNECTION_REFUSED"
"""Sent by either server or client to reject previous request
id:CLIENT_ID, type:REJECTED, request:PREVIOUS_REQUEST"""
REJECTED = "REJECTED"
class InfoTypes:
"""Information Types"""
"""Received by server, storing client id, rsa public key and connection timeout.
id:CLIENT_ID, rsa-public-key:KEY, timeout:TIMEOUT(SEC) type:CONNECTION_INFO"""
CONNECTION_INFO = "CONNECTION_INFO"
"""Sent by server, containing all active clients' id's.
clients:string_array_of_client_id, type:SERVER_INFO"""
SERVER_INFO = "SERVER_INFO"
"""Stores information of current connection, content:True/False
id:CLIENT_ID, content:True/False, type:CONNECTION_STATUS"""
CONNECTION_STATUS = "CONNECTION_STATUS"
class RequestTypes:
"""Request Types to create requests"""
"""Sent by client to establish a connection.
id:CLIENT_ID, type:CONNECTION_REQUEST"""
CONNECTION_REQUEST = "CONNECTION_REQUEST"
"""Sent by client to terminate connection.
id:CLIENT_ID, type:DISCONNECTION_REQUEST"""
DISCONNECTION_REQUEST = "DISCONNECTION_REQUEST"
"""Sent by client to gather information about the active connections.
id:CLIENT_ID, type:SERVER_INFO_REQUEST"""
SERVER_INFO_REQUEST = "SERVER_INFO_REQUEST"
class MessageTypes:
"""Text Message Types. Usage:
Client sends CARRY_MESSAGE to the server, and server fowards the message as TEXT_MESSAGE."""
"""Sent by client to foward the message to another client
id:CLIENT_ID, to:string_array_of_client_id, content:MESSAGE, type:CARRY_MESSAGE"""
CARRY_MESSAGE = "CARRY_MESSAGE"
"""Sent by server, to a client.
id/from:CLIENT_ID/SENDER_ID, to:string_array_of_client_id, content:MESSAGE, type:TEXT_MESSAGE"""
TEXT_MESSAGE = "TEXT_MESSAGE"
class TcpTypes:
"""TCP Communication Message Types"""
"""Sent by client to maintain connection and prevent timeout.
id:CLIENT_ID, type:KEEP_ALIVE"""
KEEP_ALIVE = "KEEP_ALIVE"
|
"""
This script includes all the functions for generic interviews
"""
def binary_to_decimal(decimal_num: str):
"""
Converts binary number to decimal number.
@return: <int> int of the decimal number
"""
decimal_string = str(decimal_num)
if len(decimal_string) > 0:
first = decimal_string[0]
current = 2**(len(decimal_string) - 1) if first == '1' else 0
decimal_string = decimal_string[1:]
return current + binary_to_decimal(decimal_string)
return 0
|
#encoding:utf-8
subreddit = 'im14andthisisdeep'
t_channel = '@wokesouls'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
#utilities.py
foodsize = 30
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 1024
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BACKGROUND_COLOR = (0, 0, 0)
AREA = 30
def compreso(num, low, high):
"""
checks whether or not a number is between low and high
"""
return num>=low and num<=high
if __name__ == '__main__':
startx = 20
starty = 40
finishx = finishy = 60
slope = (startx-finishx)/(starty-finishy)
print(slope)
|
bot_token = '<your_bot_token>'
fd_token = '<your_football_api_token>'
fd_hostname = 'api.football-data.org'
fd_protocol = 'https'
loglevel = 'DEBUG'
|
"""
Task Score: 100%
Complexity: O(N*log(N))
"""
def solution(A):
"""
Not even going to comment on this one...
"""
return len(set(A))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Contains reference and master data used elsewhere in the program
'''
# LED GPIO pin mappings
# Used to provide user information on when the photos are being taken
# and for the user to trigger the script by pressing the button controller
# Need to use BOARD numbering convention (not BCM)
PIN_LED_PHOTO_RED = int(4)
PIN_LED_PHOTO_YEL = int(25)
PIN_LED_PHOTO_GRE = int(24)
PIN_SWITCH_IN = int(18)
# Folders on the Pi where the files are saved down
FOLDER_PHOTOS_ORIGINAL = "/home/pi/Photos/"
FOLDER_PHOTOS_CONVERTED = "/home/pi/PhotoBooth/Converted/"
FOLDER_PHOTOS_MONTAGE = "/home/pi/PhotoBooth/Montages/"
# Configuration of each image
# UK passport is 35mm width x 45mm height
PASSPORT_IMAGE_WIDTH = 35
PASSPORT_IMAGE_HEIGHT = 45
# Amount to rotate each image taken
# Handles different orientations of the camera
IMAGE_ROTATE_AMOUNT = 90
# Configuration of the photo montages
MONTAGE_NUMBER_OF_PHOTOS = 4
MONTAGE_PHOTO_WIDTH = PASSPORT_IMAGE_WIDTH * 20
MONTAGE_PHOTO_HEIGHT = PASSPORT_IMAGE_HEIGHT * 20
MONTAGE_MARGINS = [25,25,25,25] # [w, t, r, b]
MONTAGE_PADDING = 25
|
class Stack(object):
def __init__(self):
self.items =[]
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
def peek(self):
if not self.is_empty():
return self.items[-1]
def size(self):
return len(self.items)
def __len__(self):
return self.size()
class Queue(object):
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
if not self.is_empty():
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
def peek(self):
if not self.is_empty():
return self.items[-1].value
def __len__(self):
return self.size()
def size(self):
return len(self.items)
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree(object):
def __init__(self, root):
self.root = Node(root)
def print_tree(self, traversal_type):
if traversal_type == "preorder":
return self.preorder_print(tree.root, "")
elif traversal_type == "inorder":
return self.inorder_print(tree.root, "")
elif traversal_type == "postorder":
return self.postorder_print(tree.root, "")
elif traversal_type == "levelorder":
return self.levelorder_print(tree.root)
elif traversal_type == "reverse_levelorder":
return self.reverse_levelorder_print(tree.root)
else:
print("traversal type" + str(traversal_type) + "is not supported")
#Root -> Left -> Right
#1-2-4-5-3-6-7-
def preorder_print(self, start, traversal):
if start:
traversal += (str(start.value) + "-")
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
#Root -> Left -> Right
#4-2-5-1-6-3-7
def inorder_print(self, start, traversal):
if start:
traversal = self.inorder_print(start.left, traversal)
traversal += (str(start.value) + "-")
traversal = self.inorder_print(start.right, traversal)
return traversal
#Left->right->Root
#4-2-5-6-3-7-1
def postorder_print(self, start, traversal):
if start:
traversal = self.inorder_print(start.left, traversal)
traversal = self.inorder_print(start.right, traversal)
traversal += (str(start.value) + "-")
return traversal
#prints out (from top to bottom) level by level (in order of height)
#1-2-3-4-5-6
def levelorder_print(self, start):
if start is None:
return
queue = Queue()
queue.enqueue(start)
traversal = ""
while len(queue) > 0:
traversal += str(queue.peek()) + "-"
node = queue.dequeue()
if node.left:
queue.enqueue(node.left)
if node.right:
queue.enqueue(node.right)
return traversal
#prints out (from top to bottom) level by level (in order of height)
#
def reverse_levelorder_print(self, start):
if start is None:
return
queue = Queue()
stack = Stack()
queue.enqueue(start)
traversal = ""
while len(queue) > 0:
node = queue.dequeue()
stack.push(node)
if node.right:
queue.enqueue(node.right)
if node.left:
queue.enqueue(node.left)
while len(stack) > 0:
node = stack.pop()
traversal += str(node.value) + "-"
return traversal
#gives the height og the tree
def height(self, node):
if node is None:
return -1
left_height = self.height(node.left)
right_height = self.height(node.right)
return 1 + max(left_height, right_height)
#gives the size of tree i.e number of nodes
#using recursive approaach
def size_(self, node):
if node is None:
return 0
return 1 + self.size_(node.left) + self.size_(node.right)
#gives the size of tree i.e number of nodes
#using iterative approaach
def size(self):
if self.root is None:
return 0
stack = Stack()
stack.push(self.root)
size = 1
while stack:
node = stack.pop()
if node.left:
size += 1
stack.push(node.left)
if node.right:
size += 1
stack.push(node.right)
return size
|
def match(value, pattern, exact=False):
if exact:
return value == pattern
pattern = pattern.split('*')
if len(pattern) == 2:
return value.startswith(pattern[0])
elif len(pattern) == 1:
return value == pattern[0]
else:
raise ValueError(pattern)
def match_any(value, patterns, exact=False):
return any([
match(value, pattern, exact=exact)
for pattern in patterns
])
|
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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.
mailto_edge = {
'color': {'color': 'lightblue'},
'title': 'Mailto Parsing Functions',
'label': '📧',
}
def run(unfurl, node):
if node.data_type == 'url' and node.value.startswith('mailto:'):
raw = node.value.split(':', 1)
if len(raw[1]) == 0:
return
nodes = []
if '?' in raw[1]:
split_qs = raw[1].split('?', 1)
if len(split_qs[0]) > 0:
nodes.append({'k': 'to', 'v': split_qs[0]})
# rest of the string for node value, parse as 'url.query;'
for pair in split_qs[1].replace('&', '&').split('&'):
r = pair.split('=', 1)
nodes.append({'k': r[0], 'v': r[1]})
else:
nodes.append({'k': 'to', 'v': raw[1]})
for n in nodes:
k = n['k']
v = n['v']
if k in ['to', 'cc', 'bcc']:
if ',' in v:
data_type = 'mailto.email.multiple'
else:
data_type = 'email'
unfurl_val = v
else:
data_type = 'url.query'
unfurl_val = f'{k}={v}'
unfurl.add_to_queue(
data_type=data_type, key=k, value=unfurl_val, label=f'{k}: {v}',
hover='Mailto link is a type of URL that opens the default mail client for sending an email, per '
'<a href="https://tools.ietf.org/html/rfc2368" target="_blank">RFC2368</a>',
parent_id=node.node_id, incoming_edge_config=mailto_edge)
if node.data_type == 'mailto.email.multiple':
for raw_email in node.value.split(','):
email = raw_email.replace('%20', ' ').strip()
unfurl.add_to_queue(
data_type='email', key=None, value=email, label=f'{node.key}: {email}',
hover='Mailto link is a type of URL that opens the default mail client for sending an email, '
'per <a href="https://tools.ietf.org/html/rfc2368" target="_blank">RFC2368</a>',
parent_id=node.node_id, incoming_edge_config=mailto_edge)
|
# encoding: UTF-8
LOADING_ERROR = u'Error occurred when loading the config file, please check.'
CONFIG_KEY_MISSING = u'Key missing in the config file, please check.'
DATA_SERVER_CONNECTED = u'Data server connected.'
DATA_SERVER_DISCONNECTED = u'Data server disconnected'
DATA_SERVER_LOGIN = u'Data server login completed.'
DATA_SERVER_LOGOUT = u'Data server logout completed.'
TRADING_SERVER_CONNECTED = u'Trading server connected.'
TRADING_SERVER_DISCONNECTED = u'Trading server disconnected.'
TRADING_SERVER_AUTHENTICATED = u'Trading server authenticated.'
TRADING_SERVER_LOGIN = u'Trading server login completed.'
TRADING_SERVER_LOGOUT = u'Trading server logout completed.'
SETTLEMENT_INFO_CONFIRMED = u'Settlement info confirmed.'
CONTRACT_DATA_RECEIVED = u'Contract data received.' |
def countSpace():
count = 0
with open('test.txt') as file:
for line in file:
if ' ' in line:
count += line.count(' ')
print(count)
return count
def replaceSpace():
with open('test.txt') as file:
content = file.read()
content = content.replace(' ', '#')
with open('test.txt', 'w') as file:
file.write(content)
count = countSpace()
replaceSpace()
print("Space ' '- occurence: ", count) |
# ======================================================================
# Copyright CERFACS (November 2018)
# Contributor: Adrien Suau (adrien.suau@cerfacs.fr)
#
# This software is governed by the CeCILL-B license under French law and
# abiding by the rules of distribution of free software. You can use,
# modify and/or redistribute the software under the terms of the
# CeCILL-B license as circulated by CEA, CNRS and INRIA at the following
# URL "http://www.cecill.info".
#
# As a counterpart to the access to the source code and rights to copy,
# modify and redistribute granted by the license, users are provided
# only with a limited warranty and the software's author, the holder of
# the economic rights, and the successive licensors have only limited
# liability.
#
# In this respect, the user's attention is drawn to the risks associated
# with loading, using, modifying and/or developing or reproducing the
# software by the user in light of its specific status of free software,
# that may mean that it is complicated to manipulate, and that also
# therefore means that it is reserved for developers and experienced
# professionals having in-depth computer knowledge. Users are therefore
# encouraged to load and test the software's suitability as regards
# their requirements in conditions enabling the security of their
# systems and/or data to be ensured and, more generally, to use and
# operate it in the same conditions as regards security.
#
# The fact that you are presently reading this means that you have had
# knowledge of the CeCILL-B license and that you accept its terms.
# ======================================================================
"""Simplification detection and modification for :py:class:`~.QuantumCircuit`.
This package aims at implementing reusable classes/methods to detect and
"correct" simplifications in a :py:class:`~.QuantumCircuit`.
Definitions:
# In the whole package, a :py:class:`~.QuantumCircuit` is said to be
"simplifiable" if it admits at least one sub-sequence :math:`S` checking at
least one of the following points:
* The :py:class:`~.QuantumCircuit` represented by :math:`S` acts on a quantum
state as the identity matrix.
* The matrix :math:`M` representing :math:`S` represents also a shorter (in
terms of quantum gate number) sequence of quantum gates :math:`S'`.
"""
|
def nthprime(n: int) -> int:
'''
Returns nth prime number.
Reference:
https://stackoverflow.com/a/48040385/13977061
'''
start = 2
count = 0
while True:
if all([start % i for i in range(2, int(start**0.5 + 1))]):
count += 1
if count == n:
return start
start += 1
print(nthprime(1) == 2)
print(nthprime(2) == 3)
print(nthprime(3) == 5)
print(nthprime(4) == 7)
print(nthprime(5) == 11)
print(nthprime(6) == 13)
print(nthprime(7) == 17)
print(nthprime(8) == 19)
print(nthprime(9) == 23)
print(nthprime(10) == 29)
print(nthprime(100) == 541)
|
# Реализуйте функцию sum_of_intervals, которая принимает на вход список интервалов и возвращает сумму
# всех длин интервалов. В данной задаче используются только интервалы целых чисел от 1 до ∞ , которые представлены
# в виде списков. Первое значение интервала всегда будет меньше, чем второе значение. Например, длина интервала [1, 5]
# равна 4, а длина интервала [5, 5] равна 0. Пересекающиеся интервалы должны учитываться только один раз.
# def sum_of_intervals(intervals):
# values = []
# for interval in intervals:
# for i in range(interval[0], interval[1]):
# if i not in values:
# values.append(i)
# return len(values)
def sum_of_intervals(source):
range_list = []
for i in source:
if i[0] != i[1]:
range_list.extend([item for item in range(i[0], i[1])])
return len(set(range_list))
def test_sum_of_intervals():
assert sum_of_intervals([[5, 5]]) == 0
assert sum_of_intervals([[3, 10]]) == 7
assert sum_of_intervals([
[1, 2],
[11, 12],
]) == 2
assert sum_of_intervals([
[2, 7],
[6, 6],
]) == 5
assert sum_of_intervals([
[1, 5],
[1, 10],
]) == 9
assert sum_of_intervals([
[1, 9],
[7, 12],
[3, 4],
]) == 11
assert sum_of_intervals([
[7, 10],
[1, 4],
[2, 5],
]) == 7
assert sum_of_intervals([
[1, 5],
[9, 19],
[1, 7],
[16, 19],
[5, 11],
]) == 18
assert sum_of_intervals([
[1, 3],
[20, 25]
]) == 7
test_sum_of_intervals()
|
x=int(input('enter value '))
for i in range(x):
for j in range(x):
if((i+j==4) or (i+j==5) or(i+j==6)or(i+j==7)or(i+j==8)):
print((i+j)-(x-2) ,end=' ')
else:
print('*',end=' ')
print()
|
def buildsquare(width=0,height=0):
spaces = " " * (height // 6)
lineshor = "|" + ("_" * (width // 5)) + "|"
linesver = "|\n" * (height // 6)
print(linesver + lineshor)
#NO SNEAKING TO MY CODE, THIS NOT DONE
|
'''
Escribir un programa que determine si un año es bisiesto. Un año es bisiesto si es múltiplo de 4 (por ejemplo 1984).
Los años múltiplos de 100 no son bisiestos, salvo si ellos son también múltiplos de 400 (2000 es bisiesto, pero; 1800 no lo es).
'''
def is_leap(year):
if (year % 100 != 0 or year % 400 == 0) and year % 4 == 0:
print('{year} is a leap year.'.format(year=year))
else:
print('{year} is not a leap year.'.format(year=year))
is_leap(1997)
|
# Підрахувати, скільки разів серед символів заданого рядка зустрічається буква "а".
# Рядок : "It is a long established fact that a reader."
# Потрібно створити змінну count = 0 - де буде зберігатися кількість букви "а" .
# Використати цикл for і умовний оператор if .
# Надрукувати через print("Кількість букв а : ", count)
string1 = "It is a long established fact that a reader."
count = 0
for i in range(len(string1)):
if string1[i] =='a':
count = count +1
print("Number of letter a in 'It is a long established fact that a reader.' is: ", count)
|
num_list = list()
size = 0
try:
for filename in ['5a.txt', '5b.txt']:
with open(filename, 'r') as f:
splited = f.read().split()
size = len(splited) if len(splited) > size else size
num_list.append(splited)
for num in range(size):
num_sum = 0
for index in [0, 1]:
if num < len(num_list[index]):
num_sum += int(num_list[index][num])
print(num_sum, end=' ')
print()
except FileNotFoundError:
print('Um dos arquivos não foi encontrado!')
|
grid = [[0,0,0,0,0,0,0,2,0],
[9,7,0,0,0,0,4,0,0],
[0,4,0,1,0,8,0,0,0],
[0,0,0,6,0,3,0,7,0],
[0,0,0,4,0,0,0,8,5],
[0,0,8,0,0,5,0,3,0],
[0,5,0,0,0,0,2,0,0],
[0,0,0,0,0,1,0,6,3],
[3,0,0,7,4,0,0,9,0]]
def print_grid (grid) :
for i in grid :
for j in i :
print(j,"\t", end = '')
print ("\n", end = '')
def possible (x,y,n) :
for i in range(9) :
if grid[i][y] == n or grid[x][i] == n :
return False
tmp = x%3
x0 = x - tmp
tmp = y%3
y0 = y - tmp
for i in range (3) :
for j in range (3) :
if grid[x0+i][y0+j] == n :
return False
return True
def solve() :
global grid
for i in range(9) :
for j in range(9) :
if grid[i][j] == 0 :
for x in range(1,10) :
if possible (i,j,x) :
grid[i][j] = x
solve()
grid[i][j] = 0
return grid
print ("Sudoku Solved !")
print_grid (grid)
print("Grid :")
print_grid (grid)
solve()
|
#Reading input n,k
n,k = map(int, input().split())
count = 0 #count denotes number of integers divisible by 3
for _ in range(0, n):
t = int(input())
#check for divisibility by 3
if t%k==0:
#If t is divisible by 3 increment count by 1
count+=1
#print answer
print(count)
|
def make_data(data='created some data here'):
return data
def concat_data(left, right):
return left + right
def divide_by_zero():
return 1 / 0
def _make_generator():
yield "beep"
_GENERATOR = _make_generator()
def returns_generator():
return _GENERATOR
def returns_fresh_generator():
return _make_generator()
def executes_generator(gen):
return next(gen) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def leafSimilar(self, root1: TreeNode, root2: TreeNode) -> bool:
return self.getLeaves(root1) == self.getLeaves(root2)
def getLeaves(self, root: TreeNode) -> List[TreeNode]:
res = []
def dfs(node: TreeNode):
if not node:
return
if not node.left and not node.right:
res.append(node.val)
else:
dfs(node.left)
dfs(node.right)
dfs(root)
return res
|
"""Bazel rule for loading external repository deps for J2CL."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
_IO_BAZEL_RULES_CLOSURE_VERSION = "master"
_BAZEL_SKYLIB_VERSION = "0.7.0"
def load_j2cl_repo_deps():
http_archive(
name = "io_bazel_rules_closure",
strip_prefix = "rules_closure-%s" % _IO_BAZEL_RULES_CLOSURE_VERSION,
url = "https://github.com/bazelbuild/rules_closure/archive/%s.zip"% _IO_BAZEL_RULES_CLOSURE_VERSION,
)
http_archive(
name = "bazel_skylib",
strip_prefix = "bazel-skylib-%s" % _BAZEL_SKYLIB_VERSION,
url = "https://github.com/bazelbuild/bazel-skylib/archive/%s.zip"% _BAZEL_SKYLIB_VERSION,
)
|
# dictionaries method II
# dictionaries dont follow input ordering
eng2sp={'one':'uno','two':'dos','three':'tres'}
print(eng2sp)
# dictionaries are mutable
# changing elements in a dictionary
eng2sp['three']='changed'
# to delete dictionaries
del eng2sp['two']
print(eng2sp)
print(len(eng2sp))
|
class Solution:
def XXX(self, x: int) -> int:
y=0
while x!=0:
if ((y<-214748364)or (y>214748364)) :
return 0
y=10*y+x%10
x=x/10
return y
|
"""Level3 configuration information
"""
#: Filename used to record frames that error out during decoding.
ERROR_FILENAME = 'LEVEL3.ERR'
#: Expire messages that have not been seen in this many minutes
#: The longest interval time between sending is 15 minutes for some
#: image products, so time should be greater than this.
EXPIRE_MSG_TIME_MINS = 45
#: Run the process to clean out the hash table every this number
#: of minutes.
EXPUNGE_HASHTABLE_MINS = 10
#: For the standard, PIREPs should expire >= 75 minutes after the time of last reception.
#: To be standard compliant, set this to ``False```.
#: Setting this to ``True`` decreases processor
#: time and doesn't really affect desired behavior. This is especially
#: true if using PIREP augmentation to add location information. It
#: will greatly decrease database lookups.
PIREP_STORE_LEVEL3 = True
#: Set to ``True`` if the message should be printed to standard output.
#: If you use pretty printing (``--pp``) this will be forced to True.
PRINT_TO_STDOUT = False
#: Set to ``True`` to write the message to the ``OUTPUT_DIRECTORY``.
#: Both ``PRINT_TO_STDOUT`` and ``WRITE_TO_FILE`` can be ``True``.
#: This should be set to ``True`` if feeding Harvest with data.
#: If you use pretty printing (``--pp``) this will be forced to False.
WRITE_TO_FILE = True
#: Directory to store processed files to when ``WRITE_TO_FILE`` is
#: ``True``. This is mostly for processing by Harvest.
OUTPUT_DIRECTORY = "../runtime/harvest"
|
g = [
list("-A----"),
list("-ADDDD"),
list("-A----"),
list("-A---S"),
list("-A---S"),
list("PP---S")
]
a, d, p, s = 0, 0, 0, 0
uh, ha, hs = 0, 0, 0
for i in range(int(input())):
x, y = map(int, input().split())
x, y = x-1, y-1
c = g[y][x]
if c == "A":
a += 1
elif c == "D":
d += 1
elif c == "S":
s += 1
elif c == "P":
p += 1
g[y][x] = "-"
if a == 0:
uh += 1
elif a == 5:
hs += 1
else:
ha += 1
if d == 0:
uh += 1
elif d == 4:
hs += 1
else:
ha += 1
if s == 0:
uh += 1
elif s == 3:
hs += 1
else:
ha += 1
if p == 0:
uh += 1
elif p == 2:
hs += 1
else:
ha += 1
print(f"UNHARMED:{uh}")
print(f"HIT BUT AFLOAT:{ha}")
print(f"HIT AND SUNK:{hs}") |
class DictUtil(object):
# def __init__(self):
# pass
# 将dto转dict
def dto2dict(object):
dict = {}
for key in dir(object):
value = getattr(object, key)
if not key.startswith('__') and not callable(value):
dict[key] = value
return dict |
#!/usr/bin/env python3
example = """35
20
15
25
47
40
62
55
65
95
102
117
150
182
127
219
299
277
309
576"""
def execute():
with open('2020/input/9.txt') as inp:
lines = inp.readlines()
xmas = [l.strip() for l in lines if len(l.strip()) > 0]
xmas = [int(e) for e in xmas]
return first_invalid(xmas, 25), find_weakness(xmas, 25)
tests_failed = 0
tests_executed = 0
def verify(a, b):
global tests_executed
global tests_failed
tests_executed += 1
if (a == b):
print("✓")
return
tests_failed += 1
print (locals())
def is_valid(preamble, next):
for i in range(len(preamble)):
for j in range(i+1,len(preamble)):
if preamble[i] + preamble[j] == next:
return True # i,j,preamble[i],preamble[j],next
return False
def first_invalid(xmas, length):
for i in range(len(xmas)-length):
if not is_valid(xmas[i:i+length], xmas[i+length]):
return xmas[i+length]
return None
def find_weakness(xmas, length):
target = first_invalid(xmas, length)
for i in range(len(xmas)):
total = xmas[i]
if total >= target:
continue
for j in range(i+1, len(xmas)):
total += xmas[j]
if total > target:
break
if total == target:
return min(xmas[i:j+1]) + max(xmas[i:j+1])
return None
def test_cases():
preamble = range(1,26)
verify(is_valid(preamble, 26), True)
verify(is_valid(preamble, 49), True)
verify(is_valid(preamble, 100), False)
verify(is_valid(preamble, 50), False)
preamble = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,21,22,23,24,25,45]
verify(is_valid(preamble, 26), True)
verify(is_valid(preamble, 65), False)
verify(is_valid(preamble, 64), True)
verify(is_valid(preamble, 66), True)
xmas = [int(e) for e in example.splitlines()]
verify(first_invalid(xmas, 5), 127)
verify(find_weakness(xmas, 5), 62)
print("Failed {} out of {} tests. ".format(tests_failed, tests_executed))
if __name__ == "__main__":
test_cases()
print(execute()) |
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SingleLinkedList:
def __init__(self):
self.headval = None
def traverse(self):
printval = self.headval
list_string = ""
while printval is not None:
list_string += str(printval.dataval) + "->"
printval = printval.nextval
list_string += "(Next Node)"
print(list_string)
def valueExists(self, value):
current_value = self.headval
while current_value is not None:
if (current_value.dataval == value) and (type(current_value.dataval) == type(value)):
return True
current_value = current_value.nextval
return False
def insertAtBegin(self, newdata):
newNode = Node(newdata)
newNode.nextval = self.headval
self.headval = newNode
def insertAtEnd(self, newdata):
newNode = Node(newdata)
if self.headval is None:
self.headval = newNode
return
last = self.headval
while(last.nextval):
last = last.nextval
last.nextval = newNode
def insertInbetween(self, middle_node, newdata):
if middle_node is None:
print("The mentioned node is absent")
return
newNode = Node(newdata)
newNode.nextval = middle_node.nextval
middle_node.nextval = newNode
def removeNode(self, remove_key):
headVal = self.headval
if (headVal is not None):
if (headVal.dataval == remove_key):
self.headval = headVal.nextval
headVal = None
return
while headVal is not None:
if headVal.dataval == remove_key:
break
prev = headVal
headVal = headVal.nextval
if headVal == None:
return
prev.nextval = headVal.nextval
headVal = None
list1 = SingleLinkedList()
list1.headval = Node("Mon")
e2, e3, e4 = Node("Tue"), Node("Wed"), Node("Thur")
list1.headval.nextval = e2
e2.nextval = e3
e3.nextval = e4
list1.insertAtBegin("Sun")
list1.insertAtEnd("Fri")
list1.insertInbetween(e3.nextval, "WhatDay")
list1.insertAtEnd(1)
list1.insertAtBegin(0)
list1.insertAtEnd(False)
list1.removeNode("WhatDay")
list1.traverse()
if list1.valueExists(False):
print("Value Exists")
else:
print("Value Does not Exist")
|
# model
model = Model()
i1 = Input("op1", "TENSOR_FLOAT32", "{2, 2, 2, 2}")
i2 = Input("op2", "TENSOR_FLOAT32", "{2, 2, 2, 2}")
act = Int32Scalar("act", 0) # an int32_t scalar fuse_activation
i3 = Output("op3", "TENSOR_FLOAT32", "{2, 2, 2, 2}")
model = model.Operation("MUL", i1, i2, act).To(i3)
# Example 1. Input in operand 0,
input0 = {i1: # input 0
[1, 2, -3, -4, -15, 6, 23, 8, -1, -2, 3, 4, 10, -6, 7, -2],
i2: # input 1
[-1, -2, 3, 4, -5, -6, 7, -8, 1, -2, -3, -4, -5, 6, 7, 8]}
output0 = {i3: # output 0
[-1, -4, -9, -16, 75, -36, 161, -64, -1, 4, -9, -16, -50, -36, 49, -16]}
# Instantiate an example
Example((input0, output0))
|
### Author: HIROSE Masaaki <hirose31 _at_ gmail.com>
global mysql_options
mysql_options = os.getenv('DSTAT_MYSQL') or ''
global target_status
global _basic_status
global _extra_status
_basic_status = (
('Queries' , 'qps'),
('Com_select' , 'sel/s'),
('Com_insert' , 'ins/s'),
('Com_update' , 'upd/s'),
('Com_delete' , 'del/s'),
('Connections' , 'con/s'),
('Threads_connected' , 'thcon'),
('Threads_running' , 'thrun'),
('Slow_queries' , 'slow'),
)
_extra_status = (
('Innodb_rows_read' , 'r#read'),
('Innodb_rows_inserted' , 'r#ins'),
('Innodb_rows_updated' , 'r#upd'),
('Innodb_rows_deleted' , 'r#del'),
('Innodb_data_reads' , 'rdphy'),
('Innodb_buffer_pool_read_requests', 'rdlgc'),
('Innodb_data_writes' , 'wrdat'),
('Innodb_log_writes' , 'wrlog'),
('innodb_buffer_pool_pages_dirty_pct', '%dirty'),
)
global calculating_status
calculating_status = (
'Innodb_buffer_pool_pages_total',
'Innodb_buffer_pool_pages_dirty',
)
global gauge
gauge = {
'Slow_queries' : 1,
'Threads_connected' : 1,
'Threads_running' : 1,
}
class dstat_plugin(dstat):
"""
mysql5-innodb, mysql5-innodb-basic, mysql5-innodb-extra
display various metircs on MySQL5 and InnoDB.
"""
def __init__(self):
self.name = 'MySQL5 InnoDB '
self.type = 'd'
self.width = 5
self.scale = 1000
def check(self):
if self.filename.find("basic") >= 0:
target_status = _basic_status
self.name += 'basic'
elif self.filename.find("extra") >= 0:
target_status = _extra_status
self.name += 'extra'
elif self.filename.find("full") >= 0:
target_status = _basic_status + _extra_status
self.name += 'full'
else:
target_status = _basic_status + _extra_status
self.name += 'full'
self.vars = tuple( map((lambda e: e[0]), target_status) )
self.nick = tuple( map((lambda e: e[1]), target_status) )
mysql_candidate = ('/usr/bin/mysql', '/usr/local/bin/mysql')
mysql_cmd = ''
for mc in mysql_candidate:
if os.access(mc, os.X_OK):
mysql_cmd = mc
break
if mysql_cmd:
try:
self.stdin, self.stdout, self.stderr = dpopen('%s -n %s' % (mysql_cmd, mysql_options))
except IOError:
raise Exception('Cannot interface with MySQL binary')
return True
raise Exception('Needs MySQL binary')
def extract(self):
try:
self.stdin.write('show global status;\n')
for line in readpipe(self.stdout):
if line == '':
break
s = line.split()
if s[0] in self.vars:
self.set2[s[0]] = float(s[1])
elif s[0] in calculating_status:
self.set2[s[0]] = float(s[1])
for k in self.vars:
if k in gauge:
self.val[k] = self.set2[k]
elif k == 'innodb_buffer_pool_pages_dirty_pct':
self.val[k] = self.set2['Innodb_buffer_pool_pages_dirty'] / self.set2['Innodb_buffer_pool_pages_total'] * 100
else:
self.val[k] = (self.set2[k] - self.set1[k]) * 1.0 / elapsed
if step == op.delay:
self.set1.update(self.set2)
except IOError as e:
if op.debug > 1: print('%s: lost pipe to mysql, %s' % (self.filename, e))
for name in self.vars: self.val[name] = -1
except Exception as e:
if op.debug > 1: print('%s: exception' % (self.filename, e))
for name in self.vars: self.val[name] = -1
|
findNumber = 40
guessNumber = 0
while guessNumber != findNumber:
guessNumber = int(input('Guess a number : '))
if findNumber == guessNumber:
print('You guess ! That number is :', guessNumber)
elif findNumber > guessNumber:
print('Find number is greater than', guessNumber)
else:
print('Find number is smaller than', guessNumber)
|
'''def é_hipotenusa(a):
cateto1 = 0
cateto2 = 0
for i in range(1, a):
for j in range(1, a):
if i ** 2 + j ** 2 == a ** 2:
cateto1 = i
cateto2 = j
break
if cateto1 != 0 and cateto2 != 0:
return True
else:
return False
def soma_hipotenusas(n):
lista = []
soma = 0
for i in range(2, n+1):
if é_hipotenusa(i) == True:
lista.append(i)
soma += i
print(lista)
print(soma)
flores = ["margarida", "rosa", "tulipa", "cravo"]
tam = len(flores) - 1
while tam >= 0:
print(flores[tam], end=", ")
tam = tam-1
'''
aluno = ["Fulano de Tal", 25, "Rua xyz, 123", "São Paulo", 3, "Matemática", 7.5, "Português", 6.6, "Artes", 10]
|
def contador(inicio, fim, passo):
for num in range(inicio, fim, passo):
print(num, end=' ')
print("Segue a contagem de 1 até 10, de 1 em 1:")
contador(1,11, 1)
print()
print('-'*30)
print("Segue a contagem de 10 até 0, de 2 em 2:")
contador(10,-1,-2)
print()
print('-'*30)
ini = int(input("Digite o início da contagem:"))
fim = int(input("Digite o fim da contagem:"))
pas = int(input("Digite os passos entre um número e outro: "))
if pas>0:
contador(ini, fim+1, pas)
else:
contador(ini, fim-1, pas) |
"""
Write a method to determine the number of ways to decode a string.
A msg string consists of letters from A-Z,
which represent numbers in the following mapping:
'A' -> 1
'B' -> 2
...
'Z' -> 26
Examples:
decodeString("521") => 2
Possible ways of decoding:
EBA, EU
decodeString("113021") => 0
Take 0 or 30, neither represent any alphabet and hence the entire string can't be decoded!
"""
#Approach 1, dfs, 2^n
def decode_string(msg):
if msg is None:
return 0
counter = 0
stack = list()
addNext(-1, msg, stack)
while stack:
current = stack.pop()
if current[1] == len(msg) - 1:
counter += 1
continue
addNext(current[1], msg[current[1] + 1:], stack)
return counter
def addNext(i_so_far, msg, stack):
i = 1
while i <= 2:
if len(msg) < i:
break
next_s = msg[:i]
if isValid(next_s):
stack.append((next_s, i_so_far + i))
i += 1
def isValid(s):
if s[0] == "0":
return False
return 1 <= int(s) <= 26
#Approach 2, O(n)
def decode_string(msg):
if len(msg) == 0:
return 0
previousWays = 0
possibleWays = 1
for i in range(0,len(msg)):
if not msg[i].isdigit():
return 0
temp = 0
if msg[i]!='0':
temp = possibleWays
if i>0 and int(msg[i-1:i+1])<27 and msg[i-1]!= '0':
temp += previousWays
previousWays = possibleWays
possibleWays = temp
return possibleWays |
class Solution:
# @param A : list of integers
# @param B : list of integers
# @return an integer
def coverPoints(self, A, B):
moves = 0
for i in range(len(A) - 1):
if abs(A[i] - A[i + 1]) <= abs(B[i] - B[i + 1]):
moves += abs(B[i] - B[i + 1])
else:
moves += abs(A[i] - A[i + 1])
return moves
|
class Volume():
def __init__(self, name, total, maxiops, maxbw):
self.name = name
self.total = total
self.maxiops = maxiops
self.maxbw = maxbw |
def _gradle_build_impl(ctx):
args = []
outputs = [ctx.outputs.output_log]
args += ["--log_file", ctx.outputs.output_log.path]
args += ["--gradle_file", ctx.file.build_file.path]
if (ctx.attr.output_file_destinations):
for source, dest in zip(ctx.attr.output_file_sources, ctx.outputs.output_file_destinations):
outputs += [dest]
args += ["--output", source, dest.path]
distribution = ctx.attr._distribution.files.to_list()[0]
args += ["--distribution", distribution.path]
for repo in ctx.files.repos:
args += ["--repo", repo.path]
for task in ctx.attr.tasks:
args += ["--task", task]
ctx.actions.run(
inputs = ctx.files.data + ctx.files.repos + [ctx.file.build_file, distribution],
outputs = outputs,
mnemonic = "gradlew",
arguments = args,
executable = ctx.executable._gradlew,
)
# This rule is wrapped to allow the output Label to location map to be expressed as a map in the
# build files.
_gradle_build_rule = rule(
attrs = {
"data": attr.label_list(allow_files = True),
"output_file_sources": attr.string_list(),
"output_file_destinations": attr.output_list(),
"tasks": attr.string_list(),
"build_file": attr.label(
allow_single_file = True,
),
"repos": attr.label_list(allow_files = True),
"output_log": attr.output(),
"_distribution": attr.label(
default = Label("//tools/base/build-system:gradle-distrib"),
allow_files = True,
),
"_gradlew": attr.label(
executable = True,
cfg = "host",
default = Label("//tools/base/bazel:gradlew"),
allow_files = True,
),
},
implementation = _gradle_build_impl,
)
def gradle_build(
name = None,
build_file = None,
data = [],
output_file = None,
output_file_source = None,
output_files = {},
repos = [],
tasks = [],
tags = []):
output_file_destinations = []
output_file_sources = []
if (output_file):
output_file_destinations += [output_file]
if (output_file_source):
output_file_sources += ["build/" + output_file_source]
else:
output_file_sources += ["build/" + output_file]
for output_file_destination, output_file_source_name in output_files.items():
output_file_destinations += [output_file_destination]
output_file_sources += [output_file_source_name]
_gradle_build_rule(
name = name,
build_file = build_file,
data = data,
output_file_sources = output_file_sources,
output_file_destinations = output_file_destinations,
output_log = name + ".log",
repos = repos,
tags = tags,
tasks = tasks,
)
|
########################################
# QUESTION
########################################
# A square of squares
# You like building blocks. You especially like building blocks that are squares. And what you even like more, is to arrange them into a square of square building blocks!
# However, sometimes, you can't arrange them into a square. Instead, you end up with an ordinary rectangle! Those blasted things! If you just had a way to know, whether you're currently working in vain… Wait! That's it! You just have to check if your number of building blocks is a perfect square.
# Task
# Given an integral number, determine if it's a square number:
# In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.
# The tests will always use some integral number, so don't worry about that in dynamic typed languages.
# Examples
# -1 => false
# 0 => true
# 3 => false
# 4 => true
# 25 => true
# 26 => false
###################################
# SOLUTION
###################################
def is_square(n):
x = (n)**0.5
if type(x) is complex:
return False
else:
if x.is_integer() == True and x.is_integer() >= 0:
return True
else:
return False
print(is_square(1))
|
print('\033[36m='*12, '\033[32mLendo notas', '\033[36m='*12)
n1 = float(input('\033[35mDigite sua primeira nota: '))
n2 = float(input('Digite sua segunda nota: '))
media = (n1+n2)/2
print(f'\033[36mA sua média é {media:.1f} e vc está:')
if media < 5:
print('\033[31mReprovado!')
elif media >= 7:
print('\033[32mAprovado!')
else:
print('\033[33mEm Recuparaçao!')
|
# Introduction to Python
# Non homogeneous collection of elements
list1 = [12,12.8,'This is a string']
# Printing the list
print(list1)
print(list1[0])
print(list1[1])
print(list1[2])
# Adding elements to the list
list1.append(50)
list1.insert(0,'Another string')
print(list1[3])
# Updating List
list1[1] = 20
# Deleting elements of the list
list1.pop()
del list1[2]
# Length of the list
print(len(list1))
# Looping through List
# Method 1 : Using Indexes (Mainly for updating)
for i in range(0,len(list1)):
print(list1[i])
list1[i] = 12 # Something else
# Method 2 : For each technique (Mainly for accessing)
for item in list1:
print(item) |
# -*- coding: utf-8 -*-
__author__ = """Josh Yudaken"""
__email__ = 'josh@smyte.com'
__version__ = '0.1.0'
|
class Solution(object):
@staticmethod
def isPalindrome(x):
if x < 0:
return False
temp = str(x)
return temp == temp[::-1]
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print(Solution.isPalindrome(121))
print(Solution.isPalindrome(-121))
print(Solution.isPalindrome(10))
|
n1 = float(input("digite a nota 1 do aluno: "))
n2 = float(input("digite a nota 2 do aluno: "))
m = (n1 + n2) / 2
print("\n")
print("a media do aluno entre {} e {} é igual a {}" .format (n1, n2, m))
print("\n")
print("A média entre {:.1f} e {:.1f} é igual a {:.1f}" . format (n1, n2, m)) |
# http://codingbat.com/prob/p129981
def make_out_word(out, word):
return out[0:2] + word + out[2:4]
|
# *************************************************************************
#
# Copyright (c) 2021 Andrei Gramakov. All rights reserved.
#
# This file is licensed under the terms of the MIT license.
# For a copy, see: https://opensource.org/licenses/MIT
#
# site: https://agramakov.me
# e-mail: mail@agramakov.me
#
# *************************************************************************
def get_round(in_list, num):
new_l = []
for i in in_list:
new_l.append(round(i, num))
return new_l
def get_max_deviation(in_list):
lmax = float(max(in_list))
lmin = float(min(in_list))
delta = lmax - lmin
if not delta:
return 0
return delta / lmax
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
TOPO_COMMIT = "8866b0a658247683bd4b852839ce91c6ba60f6ac"
TOPO_SHA = "dc63356c3d34de18b0afdf04cce01f6de83e2b7264de177e55c0595b05dbcd07"
def generate_topo_device():
http_archive(
name = "com_github_onosproject_onos_topo",
urls = ["https://github.com/onosproject/onos-topo/archive/%s.zip" % TOPO_COMMIT],
sha256 = TOPO_SHA,
strip_prefix = "onos-topo-%s/api" % TOPO_COMMIT,
build_file = "//tools/build/bazel:topo_BUILD",
)
|
# OutputHTML.py
#
# This class outputs an HTML page as title headings and tables.
#
class OutputHTML:
def __init__(self):
styles = [ "<style>",
"<!--",
"caption {",
"font-size: 16pt;",
"padding-top: 1em;",
"padding-bottom: 0.5em;",
"}",
"table {",
"border: 1px solid black;",
"border-collapse: collapse;",
"}",
"th {",
"border: 1px solid black;",
"background-color: #00CCFF;",
"padding-left: 1em;",
"padding-right: 1em;",
"padding-top: 0.5em;",
"padding-bottom: 0.5em;",
"}",
"td {",
"border: 1px solid black;",
"padding-top: 0.5em;",
"padding-bottom: 0.5em;",
"text-align: center",
"}",
"-->",
"</style>" ]
form = [ '<form action="sample.html">',
'<p><input type="radio" name="ident" value="bibleid" checked>BibleId</input>',
'<input type="radio" name="ident" value="filesetid">FilesetId</input>',
'<input type="text" name="type" /></p>',
'<p><br/><label>Detail:</label>',
'<input type="radio" name="detail" value="no" checked>No</input>',
'<input type="radio" name="detail" value="yes">Yes</input></p>',
'<p><br/><label>Output:</label>',
'<input type="radio" name="output" value="html" checked>HTML</input>',
'<input type="radio" name="output" value="json">JSON</input></p>',
'<p><br/><input type="submit"></p>',
'</form>' ]
self.output = []
self.output.append("<html>\n")
self.output.append("<head>\n")
self.output.append("\n".join(styles))
self.output.append("</head>\n")
self.output.append("<body>\n")
self.output.append("\n".join(form))
def title(self, level, text):
if level == 1:
self.output.append("<h1>%s</h1>\n" % (text))
elif level == 2:
self.output.append("<h2>%s</h2>\n" % (text))
elif level == 3:
self.output.append("<h3>%s</h3>\n" % (text))
else:
self.output.append("<p>%s</p>\n" % (text))
def table(self, name, columns, rows):
self.output.append("<table>\n")
if name != None:
self.output.append("<caption>%s</caption>\n" % (name))
self.output.append("<thead>\n")
self.output.append("<tr>")
for col in columns:
self.output.append("<th>%s</th>" % (col))
self.output.append("</tr>\n")
self.output.append("</thead>\n")
self.output.append("<tbody>\n")
for row in rows:
self.output.append("<tr>")
for value in row:
self.output.append("<td>%s</td>" % (value))
self.output.append("</tr>\n")
self.output.append("</tbody>\n")
self.output.append("</table>\n")
def json(self, name, columns, rows):
self.output.append('table: "%s", rows: [ ' % (name))
for row in rows:
self.output.append(' { ')
for index in range(len(columns)):
if index > 0:
self.output.append(', ')
self.output.append('"%s": "%s"' % (columns[index]), row[index])
self.output.append(' } ')
self.append(' ] ')
def close(self):
self.output.append("</body>\n")
self.output.append("</html>\n")
def stdout(self):
for line in self.output:
print(line)
def file(self, filename):
fp = open(filename, "w")
for line in self.output:
fp.write(line)
fp.close()
if __name__ == "__main__":
html = OutputHTML()
#html.title(1, "What?")
html.table("caption", ["col1", "col2", "col3"], [[1, 2, 3], ["a", "b", "c"]])
html.table("caption2", ["col4", "col5", "col6"], [[1, 2, 3], ["a", "b", "c"]])
html.close()
html.file("sample.html")
|
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
listS = list(s)
listS.sort()
listT = list(t)
listT.sort()
return listS == listT |
myDict = { "hello": 13,
"world": 31,
"!" : 71 }
# iterating over key-value pairs:
for key, value in myDict.items():
print ("key = %s, value = %s" % (key, value))
# iterating over keys:
for key in myDict:
print ("key = %s" % key)
# (is a shortcut for:)
for key in myDict.keys():
print ("key = %s" % key)
# iterating over values:
for value in myDict.values():
print ("value = %s" % value)
|
input()
e = str(input()).split()
j = 1
for i in e:
if len(i) == 3:
if i[0] == 'O' and i[1] == 'B': print('OBI', end='')
elif i[0] == 'U' and i[1] == 'R': print('URI', end='')
else: print(i, end='')
else: print(i, end='')
if j < len(e): print(end=' ')
j += 1
print()
|
DURACLOUD_USERNAME = "duracloud_user"
DURACLOUD_PASSWORD = "duracloud_password"
DURACLOUD_SPACE_ID = "my_streaming_space"
DURACLOUD_PROTOCOL = "http"
DURACLOUD_HOST = "localhost"
DURACLOUD_PORT = "8080"
|
{
'variables': {
'target_arch%': 'ia32',
'library%': 'static_library', # build chakracore as static library or dll
'component%': 'static_library', # link crt statically or dynamically
'chakra_dir%': 'core',
'icu_args%': '',
'icu_include_path%': '',
'linker_start_group%': '',
'linker_end_group%': '',
'chakra_libs_absolute%': '',
'chakra_disable_jit%':'false',
# xplat (non-win32) only
'chakra_config': '<(chakracore_build_config)', # Debug, Release, Test
'chakra_build_flags': ['-v'],
'conditions': [
['target_arch=="ia32"', { 'Platform': 'x86' }],
['target_arch=="x64"', {
'Platform': 'x64',
'chakra_build_flags+': [ '--arch=amd64' ],
}],
['target_arch=="arm"', {
'Platform': 'arm',
}],
['target_arch=="arm64"', {
'Platform': 'arm64',
'chakra_build_flags+': [ '--arch=arm64' ],
}],
['OS!="win" and v8_enable_i18n_support', {
'icu_include_path': '../<(icu_path)/source/common'
}],
['OS=="ios"', {
'chakra_build_flags+': [ '--target=ios' ],
}],
# xplat (non-win32) only
['chakracore_build_config=="Debug"', {
'chakra_build_flags': [ '-d' ],
}, 'chakracore_build_config=="Test"', {
'chakra_build_flags': [ '-t' ],
}, {
'chakra_build_flags': [],
}],
['chakra_disable_jit=="true"', {
'chakra_build_flags+': [ '--no-jit' ],
}],
],
},
'targets': [
{
'target_name': 'chakracore',
'toolsets': ['host'],
'type': 'none',
'conditions': [
['OS!="win" and v8_enable_i18n_support', {
'dependencies': [
'<(icu_gyp_path):icui18n',
'<(icu_gyp_path):icuuc',
],
}]
],
'variables': {
'chakracore_header': [
'<(chakra_dir)/lib/Common/ChakraCoreVersion.h',
'<(chakra_dir)/lib/Jsrt/ChakraCore.h',
'<(chakra_dir)/lib/Jsrt/ChakraCommon.h',
'<(chakra_dir)/lib/Jsrt/ChakraCommonWindows.h',
'<(chakra_dir)/lib/Jsrt/ChakraDebug.h',
],
'chakracore_win_bin_dir':
'<(chakra_dir)/build/vcbuild/bin/<(Platform)_<(chakracore_build_config)',
'xplat_dir': '<(chakra_dir)/out/<(chakra_config)',
'chakra_libs_absolute': '<(PRODUCT_DIR)/../../deps/chakrashim/<(xplat_dir)',
'conditions': [
['OS=="win"', {
'chakracore_input': '<(chakra_dir)/build/Chakra.Core.sln',
'chakracore_binaries': [
'<(chakracore_win_bin_dir)/chakracore.dll',
'<(chakracore_win_bin_dir)/chakracore.pdb',
'<(chakracore_win_bin_dir)/chakracore.lib',
]
}],
['OS in "linux android"', {
'chakracore_input': '<(chakra_dir)/build.sh',
'chakracore_binaries': [
'<(chakra_libs_absolute)/lib/libChakraCoreStatic.a',
],
'icu_args': [
'--icu=<(icu_include_path)'
],
'linker_start_group': '-Wl,--start-group',
'linker_end_group': [
'-Wl,--end-group',
'-lgcc_s',
]
}],
['OS=="mac" or OS=="ios"', {
'chakracore_input': '<(chakra_dir)/build.sh',
'chakracore_binaries': [
'<(chakra_libs_absolute)/lib/libChakraCoreStatic.a',
],
'conditions': [
['v8_enable_i18n_support', {
'icu_args': [
'--icu=<(icu_include_path)'
],
},{
'icu_args': '--no-icu',
}],
],
'linker_start_group': '-Wl,-force_load',
}]
],
},
'actions': [
{
'action_name': 'build_chakracore',
'inputs': [
'<(chakracore_input)',
],
'outputs': [
'<@(chakracore_binaries)',
],
'conditions': [
['OS=="win"', {
'action': [
'msbuild',
'/p:Platform=<(Platform)',
'/p:Configuration=<(chakracore_build_config)',
'/p:RuntimeLib=<(component)',
'/p:AdditionalPreprocessorDefinitions=COMPILE_DISABLE_Simdjs=1',
'/m',
'<@(_inputs)',
],
}, {
'action': [
'bash',
'<(chakra_dir)/build.sh',
'--without=Simdjs',
'--static',
'<@(chakracore_parallel_build_flags)',
'<@(chakracore_lto_build_flags)',
'<@(chakra_build_flags)',
'<@(icu_args)',
'--libs-only'
],
}],
],
},
],
'copies': [
{
'destination': 'include',
'files': [ '<@(chakracore_header)' ],
},
{
'destination': '<(PRODUCT_DIR)',
'files': [ '<@(chakracore_binaries)' ],
},
],
'direct_dependent_settings': {
'library_dirs': [ '<(PRODUCT_DIR)' ],
'conditions': [
['OS=="win"', {
}, {
'conditions': [
['OS=="mac" or OS=="ios"', {
'libraries': [
'-framework CoreFoundation',
'-framework Security',
]
}]
],
'libraries': [
'-Wl,-undefined,error',
'<@(linker_start_group)',
'<(chakra_libs_absolute)/lib/libChakraCoreStatic.a ' # keep this single space.
'<@(linker_end_group)', # gpy fails to patch with list
],
}],
],
},
}, # end chakracore
],
}
|
def som_div_propres(n):
sum = 0
for div in range(1, n):
if n % div == 0: sum += div
return sum
def est_presque_parfait(n):
return som_div_propres(n) == n - 1
def affiche_presque_parfait(k):
for i in range(2**k):
if est_presque_parfait(i): print(i)
affiche_presque_parfait(10)
|
summary_features = ['ts',
'event_type',
'SID',
'ECID',
'session',
'game_type',
'game_number',
'episode_number',
'score',
'lines_cleared',
'level',
'criterion',
'crit_game',
'study',
'tetrises_game',
'tetrises_level']
game_state_features = ['curr_zoid',
'next_zoid',
'danger_mode',
'zoid_row',
'zoid_col',
'zoid_rot']
motor_features = ['rots',
'trans',
'path_length',
'min_rots',
'min_trans',
'min_path',
'min_rots_diff',
'min_trans_diff',
'min_path_diff',
'u_drops',
's_drops',
'prop_u_drops',
'initial_lat',
'drop_lat',
'avg_lat']
pile_structure_features = ['all_diffs',
'all_ht',
'all_trans',
'max_diffs',
'max_ht',
'max_ht_diff',
'max_well',
'mean_ht',
'mean_pit_depth',
'min_ht',
'min_ht_diff',
'pits',
'pit_depth',
'pit_rows',
'lumped_pits',
'wells',
'cuml_wells',
'deep_wells',
'full_cells',
'weighted_cells',
'cd_1',
'cd_2',
'cd_3',
'cd_4',
'cd_5',
'cd_6',
'cd_7',
'cd_8',
'cd_9',
'column_9',
'jaggedness',
'pattern_div',
'nine_filled',
'tetris_progress']
zoid_placement_features = ['move_score',
'cleared',
'cuml_cleared',
'eroded_cells',
'cuml_eroded',
'matches',
'd_all_ht',
'd_max_ht',
'd_mean_ht',
'd_pits',
'landing_height',
'col_trans',
'row_trans',
'tetris']
# features analysed in 2019 cog. psy. paper by LIndstedt and Gray)
lindstedt_2019_features = ['rots',
'trans',
'min_rots_diff',
'min_trans_diff',
'prop_u_drops',
'initial_lat',
'drop_lat',
'avg_lat',
'cd_1',
'cd_2',
'cd_3',
'cd_4',
'cd_5',
'cd_6',
'cd_7',
'cd_8',
'cd_9',
'col_trans',
'cuml_wells',
'd_max_ht',
'd_pits',
'deep_wells',
'jaggedness',
'landing_height',
'lumped_pits',
'matches',
'max_diffs',
'max_ht',
'max_well',
'mean_ht',
'min_ht',
'pattern_div',
'pit_depth',
'pit_rows',
'pits',
'row_trans',
'weighted_cells',
'wells'] |
# Module: Utility
# Author: Ajay Arunachalam <ajay.arunachalam08@gmail.com>
# License: MIT
version_ = "1.10.0"
def version():
return version_
def __version__():
return version_
|
# OpenWeatherMap API Key
weather_api_key = "Insert API Key"
# Google API Key
g_key = "Insert API Key"
|
# This script generates a create table statement
# for all of the feature columns of a TSV.
#
# This table is useful for creating select statements.
#
# usage
# cat mywellformedtsv.tsv | python create_feature_table.py > create_feature_table.sql
create_string = """
CREATE TABLE IF NOT EXISTS features (
index INT,
feature TEXT ENCODING DICT,
name TEXT ENCODING DICT)"""
print(create_string)
|
"""
Helper functions for the url_breadcrumbs template tag.
Configure the template tag to call these helper functions, or functions of
your own, by defining URL_BREADCRUMBS_FUNCTIONS in your Django settings and
setting the value to a list of one or more callables.
Each callable in the URL_BREADCRUMBS_FUNCTIONS setting must accemt three
arguments:
- context : the template context
- request : the current request
- path_fragment : the URL path component being converted into a crumb name
- is_current_page : True if the path fragment is for the current page,
False if it is for any ancestor pages.
The callables must return one of the following:
- None if they do not wish to set the crumb name
- Empty string if the path fragment should not appear in the breadcrumb
- String name for the crumb representing the path fragment
"""
def feincms_page_title(context, request, path_fragment, is_current_page):
"""
Set the crumb name of the current page to the title of the FeinCMS page
in the current context, if any.
"""
# We only want to set the crumb title for the current page
if not is_current_page:
return None
# If a FeinCMS page with a title is set in the context, use as crumb name
if 'feincms_page' in context and hasattr(context['feincms_page'], 'title'):
return context['feincms_page'].title
# If no titled FeinCMS page is available leave template tag to figure out
# an appropriate crumb name
return None
|
# 입력받은 리스트 a를 오름차순으로 정렬할 것
# a[i] < value < a[j]를 범위를 가진 새 리스트 b로 슬라이싱할 것
# 리스트 b의 b[k]를 리턴시킬 것
def Q(i, j, k):
length_of_list, number_of_call = input().split(' ')
input_list = [int(param) for param in input().split(' ')].sort()
new_list = input_list[i - 1:] + input_list[:j - 1]
for _ in range(number_of_call):
i, j, k = input().split(' ')
new_list[i]
return new_list[k]
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
'''
给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
'''
def levelOrderBottom(self, root: TreeNode):
if not root:
return []
# q: 队列存储每层的节点
ans, q = [], [root]
while q:
level, qt = [], []
for n in q:
level.append(n.val)
# qt: 下一层节点的缓存, 要保持层内节点的顺序, 需要先添加左侧子节点
if n.left:
qt.append(n.left)
if n.right:
qt.append(n.right)
q = qt
ans.append(level)
ans.reverse()
return ans
|
'''
Desenvolva um programa que faça a tabuada de um número qualquer inteiro que
será digitado pelo usuário, mas a tabuada não deve necessariamente iniciar em 1 e terminar em 10, o valor inicial e final devem ser informados também pelo usuário, conforme exemplo abaixo:
Montar a tabuada de: 5
Começar por: 4
Terminar em: 7
Vou montar a tabuada de 5 começando em 4 e terminando em 7:
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
Obs: Você deve verificar se o usuário não digitou o final menor que o inicial.
'''
### ALGORÍTMO ###
num = int(input('Montar a tabuada de: '))
inicio = int(input('Começar por: '))
fim = int(input('Terminar em: '))
print('')
print('Vou montar a tabuada de %i começando em %i e termanando em %i: '%(num,inicio,fim))
print('')
for i in range(inicio, fim+1):
print('%i x %i = %i'%(num, i, num * i))
print('\n')
### FUNÇÃO ###
def tabInicioFim(num,inicio,fim):
print('')
print('Vou montar a tabuada de %i começando em %i e termanando em %i: '%(num,inicio,fim))
print('')
for i in range(inicio, fim+1):
print('%i x %i = %i'%(num, i, num * i))
print('\n')
|
"""
link: https://leetcode.com/problems/construct-quad-tree
problem: 矩阵生成四叉树
solution: 递归分治
"""
class Solution:
def construct(self, grid: List[List[int]]) -> 'Node':
def f(x: int, y: int, l: int) -> Node:
if l == 1:
return Node(grid[x][y], True, None, None, None, None)
a, b, c, d = f(x, y, l // 2), f(x, y + l // 2, l // 2), f(x + l // 2, y, l // 2), f(x + l // 2, y + l // 2,
l // 2)
if a.val == b.val == c.val == d.val == 1:
return Node(1, True, None, None, None, None)
if a.val == b.val == c.val == d.val == 0:
return Node(0, True, None, None, None, None)
return Node(2, False, a, b, c, d)
return f(0, 0, len(grid))
|
a = '9' * 127
while ('333' in a) or ('999' in a):
if ('333' in a):
a = a.replace('333','9',1)
else:
a = a.replace('999','3',1)
print(a)
|
def encode_message(enigma, message):
print("Message:", message)
message = enigma.encode(message)
print("Encoded message:", message)
|
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
for i in range(len(letters)-1):
if(i%2!=0):
continue;
print(letters[i]) |
"""2017 - Day 13 Part 1: Packet Scanners.
You need to cross a vast firewall. The firewall consists of several layers,
each with a security scanner that moves back and forth across the layer. To
succeed, you must not be detected by a scanner.
By studying the firewall briefly, you are able to record (in your puzzle
input) the depth of each layer and the range of the scanning area for the
scanner within it, written as depth: range. Each layer has a thickness of
exactly 1. A layer at depth 0 begins immediately inside the firewall; a layer
at depth 1 would start immediately after that.
For example, suppose you've recorded the following:
0: 3
1: 2
4: 4
6: 4
This means that there is a layer immediately inside the firewall (with range
3), a second layer immediately after that (with range 2), a third layer which
begins at depth 4 (with range 4), and a fourth layer which begins at depth 6
(also with range 4). Visually, it might look like this:
0 1 2 3 4 5 6
[ ] [ ] ... ... [ ] ... [ ]
[ ] [ ] [ ] [ ]
[ ] [ ] [ ]
[ ] [ ]
Within each layer, a security scanner moves back and forth within its range.
Each security scanner starts at the top and moves down until it reaches the
bottom, then moves up until it reaches the top, and repeats. A security
scanner takes one picosecond to move one step. Drawing scanners as S, the
first few picoseconds look like this:
Picosecond 0:
0 1 2 3 4 5 6
[S] [S] ... ... [S] ... [S]
[ ] [ ] [ ] [ ]
[ ] [ ] [ ]
[ ] [ ]
Picosecond 1:
0 1 2 3 4 5 6
[ ] [ ] ... ... [ ] ... [ ]
[S] [S] [S] [S]
[ ] [ ] [ ]
[ ] [ ]
Picosecond 2:
0 1 2 3 4 5 6
[ ] [S] ... ... [ ] ... [ ]
[ ] [ ] [ ] [ ]
[S] [S] [S]
[ ] [ ]
Picosecond 3:
0 1 2 3 4 5 6
[ ] [ ] ... ... [ ] ... [ ]
[S] [S] [ ] [ ]
[ ] [ ] [ ]
[S] [S]
Your plan is to hitch a ride on a packet about to move through the firewall.
The packet will travel along the top of each layer, and it moves at one layer
per picosecond. Each picosecond, the packet moves one layer forward (its
first move takes it into layer 0), and then the scanners move one step. If
there is a scanner at the top of the layer as your packet enters it, you are
caught. (If a scanner moves into the top of its layer while you are there, you
are not caught: it doesn't have time to notice you before you leave.) If you
were to do this in the configuration above, marking your current position with
parentheses, your passage through the firewall would look like this:
Initial state:
0 1 2 3 4 5 6
[S] [S] ... ... [S] ... [S]
[ ] [ ] [ ] [ ]
[ ] [ ] [ ]
[ ] [ ]
Picosecond 0:
0 1 2 3 4 5 6
(S) [S] ... ... [S] ... [S]
[ ] [ ] [ ] [ ]
[ ] [ ] [ ]
[ ] [ ]
0 1 2 3 4 5 6
( ) [ ] ... ... [ ] ... [ ]
[S] [S] [S] [S]
[ ] [ ] [ ]
[ ] [ ]
Picosecond 1:
0 1 2 3 4 5 6
[ ] ( ) ... ... [ ] ... [ ]
[S] [S] [S] [S]
[ ] [ ] [ ]
[ ] [ ]
0 1 2 3 4 5 6
[ ] (S) ... ... [ ] ... [ ]
[ ] [ ] [ ] [ ]
[S] [S] [S]
[ ] [ ]
Picosecond 2:
0 1 2 3 4 5 6
[ ] [S] (.) ... [ ] ... [ ]
[ ] [ ] [ ] [ ]
[S] [S] [S]
[ ] [ ]
0 1 2 3 4 5 6
[ ] [ ] (.) ... [ ] ... [ ]
[S] [S] [ ] [ ]
[ ] [ ] [ ]
[S] [S]
Picosecond 3:
0 1 2 3 4 5 6
[ ] [ ] ... (.) [ ] ... [ ]
[S] [S] [ ] [ ]
[ ] [ ] [ ]
[S] [S]
0 1 2 3 4 5 6
[S] [S] ... (.) [ ] ... [ ]
[ ] [ ] [ ] [ ]
[ ] [S] [S]
[ ] [ ]
Picosecond 4:
0 1 2 3 4 5 6
[S] [S] ... ... ( ) ... [ ]
[ ] [ ] [ ] [ ]
[ ] [S] [S]
[ ] [ ]
0 1 2 3 4 5 6
[ ] [ ] ... ... ( ) ... [ ]
[S] [S] [S] [S]
[ ] [ ] [ ]
[ ] [ ]
Picosecond 5:
0 1 2 3 4 5 6
[ ] [ ] ... ... [ ] (.) [ ]
[S] [S] [S] [S]
[ ] [ ] [ ]
[ ] [ ]
0 1 2 3 4 5 6
[ ] [S] ... ... [S] (.) [S]
[ ] [ ] [ ] [ ]
[S] [ ] [ ]
[ ] [ ]
Picosecond 6:
0 1 2 3 4 5 6
[ ] [S] ... ... [S] ... (S)
[ ] [ ] [ ] [ ]
[S] [ ] [ ]
[ ] [ ]
0 1 2 3 4 5 6
[ ] [ ] ... ... [ ] ... ( )
[S] [S] [S] [S]
[ ] [ ] [ ]
[ ] [ ]
In this situation, you are caught in layers 0 and 6, because your packet
entered the layer when its scanner was at the top when you entered it. You are
not caught in layer 1, since the scanner moved into the top of the layer once
you were already there.
The severity of getting caught on a layer is equal to its depth multiplied by
its range. (Ignore layers in which you do not get caught.) The severity of the
whole trip is the sum of these values. In the example above, the trip severity
is 0*3 + 6*4 = 24.
Given the details of the firewall you've recorded, if you leave immediately,
what is the severity of your whole trip?
"""
def solve() -> int:
"""Solve the puzzle."""
|
def test_stickers(app):
app.wd.get("http://localhost/litecart")
goods = app.wd.find_elements_by_css_selector(".product")
for g in goods:
stickers = g.find_elements_by_xpath(".//div[contains(@class, 'sticker')]")
assert len(stickers) == 1
|
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 10 17:04:30 2015
@author: Wasit
"""
def inc(x=1):
yield x+1 |
print("*** Dimensions")
print(ds.dims)
print("\n\n*** Coordinates")
print(ds.coords)
print("\n\n*** Attributes")
print(ds.attrs)
|
"""
Desafio 049
Problema: Refaça o desafio 009, mostrando tabuada de um
número que o usuário escolher, só que agora
utilizando um laço FOR.
Resolução do problema:
"""
tabuada = int(input('Informe a tabuada que deseja ver: '))
for c in range(0, 11):
print('{} X {:2} = {}'.format(tabuada, c, tabuada * c))
|
CODE_EXP_TIME = 600 # Expiration time from Codes
TOKEN_EXP_TIME = 1000 # Expiration time from Token.
CODE_MIN_CHAR = 26 # Miximun number of characteres from Authentication Code
CODE_MAX_CHAR = 26 # Maximun number of characteres from Authentication Code
CODE_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890' # Charset to create the Authentication Code
TOKEN_MIN_CHAR = 30 # Miximun number of characteres from Access Token
TOKEN_MAX_CHAR = 30 # Miximun number of characteres from Access Token
TOKEN_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890i.-_' # Charset to create the Access Token
REFRESH_MIN_CHAR = 40 # Miximun number of characteres from Refresh Token
REFRESH_MAX_CHAR = 40 # Miximun number of characteres from Refresh Token
REFRESH_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890i.-_' # Charset to create the Refresh Token
NONCE_MIN_CHAR = 25 # Miximun number of characteres from Nonce
NONCE_MAX_CHAR = 25 # Miximun number of characteres from Nonce
NONCE_CHARSET = '1234567890.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-' # Charset to create the Nonce
|
class PodcastError(Exception):
"""Base class for all podcast exceptions."""
pass
class NoResults(PodcastError):
"""Raised when no results are found."""
pass |
class Solution:
def numberOfPatterns(self, m: int, n: int) -> int:
skip = [[0] * 10 for _ in range(10)]
skip[1][3] = skip[3][1] = 2
skip[1][7] = skip[7][1] = 4
skip[3][9] = skip[9][3] = 6
skip[7][9] = skip[9][7] = 8
skip[1][9] = skip[9][1] = skip[2][8] = skip[8][2] = skip[3][7] = skip[7][3] = skip[4][6] = skip[6][4] = 5
visited = [False] * 10
def dfs(curr, remain):
if remain == 0:
return 1
remain -= 1
count = 0
visited[curr] = True
for i in range(1, 10):
if not visited[i] and (skip[curr][i] == 0 or visited[skip[curr][i]]):
count += dfs(i, remain)
visited[curr] = False
return count
count = 0
for i in range(m, n + 1):
count += dfs(1, i - 1) * 4
count += dfs(2, i - 1) * 4
count += dfs(5, i - 1)
return count
|
class load_api_1:
name="hash1"
def __init__(self, data=b''):
self.data = data
def update(self, data=b''):
self.data += data
def digest(self):
return 1516152524156352132515252551426
def hexdigest(self):
return hex(self.digest())
class load_api_2:
name="hash2"
def __init__(self, data=b''):
self.data = data
def update(self, data=b''):
self.data += data
def digest(self):
return 1234567876543234567897654324562
def hexdigest(self):
return hex(self.digest())
class load_api_3:
name="hash3"
def __init__(self, data=b''):
self.data = data
def update(self, data=b''):
self.data += data
def digest(self):
return 5232348239489234823948203294829
def hexdigest(self):
return hex(self.digest())
|
# -*- coding: utf-8 -*-
"""
@Author: Lyzhang
@Date:
@Description:
""" |
#!/usr/bin/env python
# Copyright (c) 2015:
# Istituto Nazionale di Fisica Nucleare (INFN), Italy
#
# 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.
#
# fgapiserver_queries - Provide queries for fgapiserver tests
#
__author__ = 'Riccardo Bruno'
__copyright__ = '2019'
__license__ = 'Apache'
__version__ = 'v0.0.0'
__maintainer__ = 'Riccardo Bruno'
__email__ = 'riccardo.bruno@ct.infn.it'
__status__ = 'devel'
__update__ = '2019-05-03 17:04:36'
fgapiservergui_queries_queries = [
{'id': 0,
'query': 'SELECT VERSION();',
'result': [['test_version', ], ]},
{'id': 1,
'query': ('select uuid, creation, last_access, enabled, cfg_hash '
'from srv_registry;'),
'result': [['test_uuid1', '1/1/1970', '1/1/1970', 'true', 'test_hash1'],
['test_uuid2', '1/1/1970', '1/1/1970', 'true', 'test_hash2'], ]},
{'id': 2,
'query': ('select id, name, first_name, last_name, institute, mail '
'from fg_user where name=\'%s\';'),
'result': [[1, 'futuregateway', 'futuregateway', 'futuregateway',
'infn', 'futuregateway@futuregateway'], ]},
]
# fgapiserver tests queries
queries = [
{'category': 'fgapiservergui_queries',
'statements': fgapiservergui_queries_queries}]
|
"""
An evaluator for problems from the toy-socket suite to demonstrate external evaluation of
objectives and constraints in Python
"""
def evaluate_toy_socket_objectives(suite_name, func, instance, x):
y0 = instance * 1e-5
if suite_name == 'toy-socket':
if func == 1:
# Function 1 is the sum of the absolute x-values
return [y0 + sum([abs(xi) for xi in x])]
elif func == 2:
# Function 2 is the sum of squares of all x-values
return [y0 + sum([xi * xi for xi in x])]
else:
raise ValueError('Suite {} has no function {}'.format(suite_name, func))
elif suite_name == 'toy-socket-biobj':
if func == 1 or func == 2:
# Objective 1 is the sum of the absolute x-values
y1 = y0 + sum([abs(xi) for xi in x])
# Objective 2 is the sum of squares of all x-values
y2 = y0 + sum([xi * xi for xi in x])
return [y1, y2]
else:
raise ValueError('Suite {} has no function {}'.format(suite_name, func))
else:
raise ValueError('Suite {} not supported'.format(suite_name))
def evaluate_toy_socket_constraints(suite_name, func, instance, x):
y0 = instance * 1e-5
average = y0 + sum([abs(xi) for xi in x])
average = average / len(x)
if suite_name == 'toy-socket' and func == 1:
# Function 1 of the single-objective suite has two constraints
# Violation 1 is the difference between the 0.2 and the average of absolute x-values
y1 = (0.2 - average) if average < 0.2 else 0
# Violation 2 is the difference between the average and 0.5
y2 = (average - 0.5) if average > 0.5 else 0
return [y1, y2]
elif suite_name == 'toy-socket-biobj' and func == 2:
# Function 3 of the bi-objective suite has one constraint
# Violation 1 is the difference between the average and 0.5
y1 = (average - 0.5) if average > 0.5 else 0
return [y1]
else:
raise ValueError('Suite {} function {} does not have constraints'.format(suite_name, func))
|
# Example variable assignment and comparison
x = 12
y = 1
print(x == y)
# Test dict
label_map = {"anxiety": 0, "depression": 1, "positive_mood": 2, "negative_mood": 3}
# Example SQL queries
selection_query = (
"SELECT JID, Journal FROM `journal` " "WHERE status = %(unique_timestamp)s "
)
# Example SQL queries
insertion_query = "INSERT IGNORE INTO `journal_analysis` (JID, AnalysisValue, Flag, Indicators) VALUES (%(JID)s, %(AnalysisValue)s, %(Flag)s, %(Indicators)s) "
# Test format
a = 1
b = 2
print(a == b)
|
def crevasse_water_depth(x,y,t,thck,topg,*etc):
depth = 0.0
if (t >= 10.0):
depth = 20.0
if (t >= 20.0):
depth = 0.0
return depth
|
#-----------------------------------------------------------------------------
# Runtime: 44ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution:
def permute(self, nums: [int]) -> [[int]]:
if len(nums) == 1:
return [ nums ]
result = []
sub_permutations = self.permute(nums[1:])
for sub_permutation in sub_permutations:
for i in range(len(sub_permutation) + 1):
result.append(sub_permutation[:i] + [ nums[0] ] + sub_permutation[i:])
return result
|
# Write a method to replace all spaces in a string with '%20'.
# You may assume that the string has sufficient space at the end to hold the additional characters,
# and that you are given the "true" length of the string.
# (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)
# Example:
# Input: "Mr John Smith ", 13
# Output: "Mr%20John%20Smith"
def replace_spaces(str, true_length):
return str.replace(' ', '%20')
# Testing the function
str_1 = 'Mr John Smith '
str1_replaced = replace_spaces(str_1, 13)
print(str1_replaced)
#Output: Mr%20John%20Smith%20%20%20%20
# The above output is half correct. The correct output should be Mr%20John%20Smith.
# The spaces at the end of the string are merely for holding any additional characters.
# These additional spaces should not replaced with %20.
def replace_string_2(str, true_length):
"""
Given a string and a true length of the string, replace all spaces with %20.
Be careful with the spaces that comes after the last character.
Solution: Count the spaces in the string[:true_length] and add 2*count to the true_length...
...when returning the string.
"""
space_count = 0
for char in str[:true_length]:
if char == ' ':
space_count += 1
str_2 = str.replace(' ', '%20')
return str_2[:true_length + space_count * 2]
str_2 = 'Mr John Smith '
str2_replaced = replace_string_2(str_2, 13)
print(str2_replaced)
#Output: Mr%20John%20Smith
str_3 = 'Mr John '
str3_replaced = replace_string_2(str_3, 7)
print(str3_replaced)
str_4 = 'Mr Set '
str4_replaced = replace_string_2(str_4, 6)
print(str4_replaced)
#Output: Mr%20John
# Great, but can I do better? Perhaps without using the replace method?
|
class GetChannelError(Exception):
"""Raises when fetch channel is failed."""
pass
class SendMessageToChannelFailed(Exception):
"""Raises when send message to channel is failed."""
pass
class EditChannelFailed(Exception):
"""Raises when editing the channel is failed."""
pass
class DeleteChannelFailed(Exception):
"""Raises when deleting the channel is failed."""
pass
class FetchChannelHistoryFailed(Exception):
"""Raises when fetching the channel history is failed."""
pass
class FetchChannelMessageFailed(Exception):
"""Raises when fetching the channel message is failed."""
pass
class FetchChannelInvitesFailed(Exception):
"""Raises when fetching the channel invites is failed."""
pass
class CreateInviteFailed(Exception):
"""Raises when creating new invite is failed."""
pass
class FetchPinnedMessagesFailed(Exception):
"""Raises when fetching the pinned messages is failed."""
pass
class PinMessageFailed(Exception):
"""Raises when pinning a message is failed."""
pass
class UnpinMessageFailed(Exception):
"""Raises when unpinning a message is failed."""
pass
class EditChannelPermissionsFailed(Exception):
"""Raises when editing the channel permissions is failed."""
pass
class DeleteChannelPermissionsFailed(Exception):
"""Raises when deleting the channel permissions is failed."""
pass
class TriggerTypingFailed(Exception):
"""Raises when trigger the typing is failed."""
pass
class DeleteChannelMessageFailed(Exception):
"""Raises when deleting a channel message is failed."""
pass
class CreateWebhookFailed(Exception):
"""Raises when creating a webhook is failed."""
pass
class FetchWebhooksFailed(Exception):
"""Raises when fetching the webhooks is failed."""
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.