content stringlengths 7 1.05M |
|---|
def selection_sort(array):
"""Program for selection sort
Inplace sorting
Space Complexity O(1) only constant number of variables is used
Time complexity O(n^2)
>>> arr = [1, 5, 0, -3, 5, 7, 2, 0, 9, 1]
>>> print(arr)
[1, 5, 0, -3, 5, 7, 2, 0, 9, 1]
>>> selection_sort(arr)
>>> print(arr)
[-3, 0, 0, 1, 1, 2, 5, 5, 7, 9]
"""
n = len(array)
for i in range(n - 1):
minimum = array[i]
min_index = i
# find the minimum element in array[i+1..n-1]
for j in range(i + 1, n):
if array[j] < minimum:
minimum = array[j]
min_index = j
# swap array[i] with minimum element found after i
array[i], array[min_index] = array[min_index], array[i]
arr = [1, 5, 0, -3, 5, 7, 2, 0, 9, 1]
print(arr)
selection_sort(arr)
print(arr)
|
#NOTE: LIST - Secuence of mutable values
names = ["Harry", "Hik", "Linkin", "Park"]
#ADDS ANOTHER ITEM IN THE LIST
names.append("Paramore")
#SORT THE LIST IN APLHABETIC ORDER
names.sort()
#PRINTS THE LIST
print(names) |
subor = open("17_1input.txt", "r")
r = [x.strip() for x in subor.readlines()]
n=6
roz=(n+1)*2+len(r[0])
pole=[[["." for a in range(roz)] for a in range(roz)]for a in range((n+1)*2+1)]
#vypisanie pola
def vypis(x):
for a in x:
for b in a:
for c in b:
print(c,end=" ")
print()
print()
#dopisanie hodnot zo zadania
for i in range(len(r)):
for j in range(len(r[i])):
pole[n+1][n+1+i][n+1+j]=r[i][j]
"""
vypis(pole)
print("--------------")
"""
def susedia(p,x,y,z):
s=0
for a in (-1,0,1):
for b in (-1,0,1):
for c in (-1,0,1):
s+= p[x+a][y+b][z+c]=="#"
if p[x][y][z]=="#":
return s-1
else:
return s
def krok(p,i):
np=[[["." for a in range(roz)] for a in range(roz)]for a in range(roz)]
for a in range(n-i+1,(n+1)*2 -(n-i)):
for b in range(n-i+1,roz-(n-i)-1):
for c in range(n-i+1,roz-(n-i)-1):
#print(a,b,c,p[a][b][c],susedia(p,a,b,c) )
if p[a][b][c]=="." and susedia(p,a,b,c)==3:
np[a][b][c]="#"
#print("aha")
#vypis(np)
elif p[a][b][c]=="#" and susedia(p,a,b,c) in (2,3):
np[a][b][c]="#"
else:
np[a][b][c]="."
#print("np")
#vypis(np)
return(np)
for i in range(n):
pole=krok(pole,i+1)
#print(i)
#vypis(pole)
def zrataj(x):
suc=0
for a in x:
for b in a:
for c in b:
suc += c=="#"
return suc
print(zrataj(pole))
|
__author__ = "Ian Goodfellow"
class Agent(object):
pass
|
def pytest_report_header():
return """
------------------------
EXECUTING WEB UI TESTS
------------------------
"""
|
c = 41 # THE VARIABLE C equals 41
c == 40 # c eqauls 40 which is false becasue of the variable above
c != 40 and c <41 #c does not equal 40 is a true statement but the other statement is false, making it a false statement
c != 40 or c <41 #True statement in an or statement
not c == 40 #this is a true statement
not c > 40 #false statement
c <= 41 #true
not false #true
True and false #false
false or True #true
false or false or false #false
True and True and false #false
false == 0 #this is a true
True == 0 #false
True == 1 #this statement
|
dna = 'ACGTN'
rna = 'ACGUN'
# dictionary nucleotide acronym to full name
nuc2name = {
'A': 'Adenosine',
'C': 'Cysteine',
'T': 'Thymine',
'G': 'Guanine',
'U': 'Uracil',
'N': 'Unknown'
} |
print("Checking Imports")
import_list = ['signal', 'psutil', 'time', 'pypresence', 'random']
modules = {}
for package in import_list:
try:
modules[package] = __import__(package)
except ImportError:
print(f"Package: {package} is missing please install")
print("Loading CONFIG\n")
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# CONFIG
#
# Change the client_id to your own if you want to use your own assets and name.
#
client_id = '808908940993495040'
#
# The app can update every 15 seconds according to discord tos (https://discord.com/developers/docs/rich-presence/how-to#updating-presence)
# However, you can change it to whatever you want at the risk of being Rate-Limited (never have been actualy rate-limited so I dont know the limit. 1 Second works tho)
#
rpc_limit = 5 # int with 1 second being the min
#
# These are the default quotes or texts displayed. Change to your liking.
# Button is optional
#
def updateDynamicText():
cpu_per = round(modules["psutil"].cpu_percent(), 1)
mem_per = round(modules["psutil"].virtual_memory().percent, 1)
text = [
{
"name": "CPU / RAM",
"line1": f"CPU: {cpu_per}%",
"line2": f"RAM: {mem_per}%",
},
{
"name": "The Welcoming",
"line1": f"Yo we pimp",
"line2": f"chimping",
"button": [{"label": "Misfits", "url": "https://scuffed.store/"}, {"label": "Fitz", "url": "https://fitz.fanfiber.com/"}]
},
]
return {"text": text, "size": len(text)}
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Spawn Discord RPC connection
RPC = modules["pypresence"].Presence(client_id, pipe=0)
RPC.connect()
# https://stackoverflow.com/questions/18499497/how-to-process-sigterm-signal-gracefully
# Thanks to this thread for safe shutdown
class GracefulKiller:
kill_now = False
def __init__(self):
modules["signal"].signal(modules["signal"].SIGINT, self.exit_gracefully)
modules["signal"].signal(modules["signal"].SIGTERM, self.exit_gracefully)
def exit_gracefully(self):
self.kill_now = True
if __name__ == '__main__':
killer = GracefulKiller()
print(f"Client ID: {client_id}")
print(f"Updating every: {rpc_limit} seconds")
while not killer.kill_now:
# Presence
text = updateDynamicText()
x = modules["random"].randint(0,text["size"]-1)
try:
text["text"][x]["button"]
except KeyError:
print(RPC.update(details=text["text"][x]["line1"], state=text["text"][x]["line2"]))
else:
print(RPC.update(details=text["text"][x]["line1"], state=text["text"][x]["line2"], buttons=text["text"][x]["button"]))
# https://discord.com/developers/docs/rich-presence/how-to#updating-presence
# Should only update every 15 seconds, however, this is not a limit and it can go as fast as you want it too.
# However, you will probabaly get rate-limited and will have to serve a cooldown period if you go too fast.
modules["time"].sleep(rpc_limit)
print("I was killed")
RPC.close()
|
# A linked list node
class Node:
def __init__(self, value=None, next=None):
self.value = value
self.next = next
# Helper function to print given linked list
def printList(head):
ptr = head
while ptr:
print(ptr.value, end=" -> ")
ptr = ptr.next
print("None")
# Function to remove duplicates from a sorted list
def removeDuplicates(head):
previous = None
current = head
# take an empty set to store linked list nodes for future reference
s = set()
# do till linked list is not empty
while current:
# if current node is seen before, ignore it
if current.value in s:
previous.next = current.next
# insert current node into the set and proceed to next node
else:
s.add(current.value)
previous = current
current = previous.next
return head
if __name__ == '__main__':
# input keys
keys = [3,4,3,2,6,1,2,6]
# construct linked list
head = None
for i in reversed(range(len(keys))):
head = Node(keys[i], head)
removeDuplicates(head)
# print linked list
printList(head)
|
#!/usr/bin/env python3
# https://www.urionlinejudge.com.br/judge/en/problems/view/1014
def main():
X = int(input())
Y = float(input())
CONSUMPTION = X / Y
print(format(CONSUMPTION, '.3f'), "km/l")
# Start the execution if it's the main script
if __name__ == "__main__":
main()
|
'''
Data Columns - Exercise 1
The file reads the file with neuron lengths (neuron_data.txt)
and saves an identical copy of the file.
'''
Infile = open('neuron_data.txt')
Outfile = open('neuron_data-copy.txt', 'w')
for line in Infile:
Outfile.write(line)
Outfile.close()
|
"""In this bite you will work with a list of names.
First you will write a function to take out duplicates and title case them.
Then you will sort the list in alphabetical descending order by surname and lastly determine what the shortest first name is. For this exercise you can assume there is always one name and one surname.
With some handy Python builtins you can write this in a pretty concise way. Get it sorted :)"""
NAMES = ['arnold schwarzenegger', 'alec baldwin', 'bob belderbos',
'julian sequeira', 'sandra bullock', 'keanu reeves',
'julbob pybites', 'bob belderbos', 'julian sequeira',
'al pacino', 'brad pitt', 'matt damon', 'brad pitt']
def dedup_and_title_case_names(names):
"""Should return a list of names, each name appears only once"""
names = list(set(NAMES))
func_names = []
for i in names:
i = i.title()
func_names.append(i)
return func_names
def sort_by_surname_desc(names):
"""Returns names list sorted desc by surname"""
names = dedup_and_title_case_names(NAMES)
name_dict = []
for i in names:
i = i.split()
name_dict.append({'name':i[0], 'surname': i[1]})
sort_names = list(sorted(name_dict, key=lambda k: k['surname'], reverse=True))
names = []
for a in sort_names:
s = str(a['name']) + ' ' + str(a['surname'])
names.append(s)
return names
def shortest_first_name(names):
"""Returns the shortest first name (str)"""
names = dedup_and_title_case_names(names)
name_dict = []
for i in names:
i = i.split()
name_dict.append({'name':i[0], 'surname': i[1]})
short_name_sort = sorted(name_dict, key=lambda k: len(k['name']))
return short_name_sort[0]['name'] |
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*****************************************************************************"""
################################################################################
#### Business Logic ####
################################################################################
def genDriverHeaderRootFile(symbol, event):
symbol.setEnabled(event["value"])
def genDriverHeaderCommonFile(symbol, event):
symbol.setEnabled(event["value"])
############################################################################
#### Code Generation ####
############################################################################
genDriverCommonFiles = harmonyCoreComponent.createBooleanSymbol("ENABLE_DRV_COMMON", None)
genDriverCommonFiles.setLabel("Generate Harmony Driver Common Files")
genDriverCommonFiles.setVisible(False)
genDriverCommonFiles.setDefaultValue(False)
driverHeaderRootFile = harmonyCoreComponent.createFileSymbol("DRIVER_ROOT", None)
driverHeaderRootFile.setSourcePath("driver/driver.h")
driverHeaderRootFile.setOutputName("driver.h")
driverHeaderRootFile.setDestPath("driver/")
driverHeaderRootFile.setProjectPath("config/" + configName + "/driver/")
driverHeaderRootFile.setType("HEADER")
driverHeaderRootFile.setOverwrite(True)
driverHeaderRootFile.setEnabled(False)
driverHeaderRootFile.setDependencies(genDriverHeaderRootFile, ["ENABLE_DRV_COMMON"])
driverHeaderCommonFile = harmonyCoreComponent.createFileSymbol("DRIVER_COMMON", None)
driverHeaderCommonFile.setSourcePath("driver/driver_common.h")
driverHeaderCommonFile.setOutputName("driver_common.h")
driverHeaderCommonFile.setDestPath("driver/")
driverHeaderCommonFile.setProjectPath("config/" + configName + "/driver/")
driverHeaderCommonFile.setType("HEADER")
driverHeaderCommonFile.setOverwrite(True)
driverHeaderCommonFile.setEnabled(False)
driverHeaderCommonFile.setDependencies(genDriverHeaderCommonFile, ["ENABLE_DRV_COMMON"])
|
# 000404_02_04_step16_code04_formOutput.py
# Напишите программу, которая выводит частное целых переменных a/b и b/а
# с разделителем "***" в формате 9 знаковых позиций и 5 знаков после запятой
a=int(input())
b=int(input())
print('{:9.5f}'.format(a/b),'{:9.5f}'.format(b/a), sep=' ***')
# print('{:9.5f}'.format(b/a))
|
class Video:
def __init__(self, files):
self.files = files
def setFiles(self, files):
self.files = files
def getFiles(self):
return self.files |
class JsonUtil:
@staticmethod
def list_obj_dict(list):
new_list = []
for obj in list:
new_list.append(obj.__dict__)
return new_list
|
# pylint: disable=inconsistent-return-statements
def sanitize(value, output_type):
"""
Handy wrapper function for individual sanitize functions.
:param value: Input value to be sanitized
:param output_type: Class of required output
:type output_type: bool or int
"""
# pylint: disable=no-else-return
if output_type == bool:
return sanitize_bool(value)
elif output_type == int:
return sanitize_int(value)
# pylint: enable=no-else-return
# unrecognised/unsupported output_type. just return what we got..
return value
def sanitize_int(value):
"""
Sanitize an input value to an integer.
:param value: Input value to be sanitized to an integer
:return: Integer, or None of the value cannot be sanitized
:rtype: int or None
"""
if isinstance(value, str):
try:
return int(value)
except ValueError:
return None
elif isinstance(value, int):
return value
# pylint: enable=inconsistent-return-statements
def sanitize_bool(value, strict=False):
"""
Sanitize an input value to a boolean
:param value: Input value to be sanitized to a boolean
:param strict: if strict, if the value is not directly recognised as a
yes/no bool, we'll return None...if not strict, we'll
convert the unknown value to bool() and return True/False
:return: Boolean representation of input value.
:rtype: bool or NoneType
"""
if isinstance(value, str):
# pylint: disable=no-else-return
if value.lower().strip() in {'y', 'yes', 't', 'true', '1'}:
return True
elif value.lower().strip() in {'n', 'no', 'f', 'false', '0'}:
return False
else:
int_value = sanitize_int(value)
if int_value is not None:
return int_value > 0
return False
# pylint: enable=no-else-return
# Bool compare before int compare. This is because True isinstance() check
# will relate to 1 which means isinstance(value, int) will result as True,
# whilst being a bool. Testing a number against bool will result in False,
# therefore order is very important.
elif isinstance(value, bool):
return value
elif isinstance(value, int):
return value > 0
if isinstance(value, (list, tuple)) and len(value) == 1:
# recurse
return sanitize_bool(value[0], strict=strict)
if strict:
return None
return bool(value)
|
class Solution(object):
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
start = 0
end = len(arr) - 1
while start < end:
mid = (start + end) // 2
if arr[mid] == x:
start = mid
while arr[start] == x:
start = start - 1
end = start + 1
elif arr[mid] < x:
start = mid
else:
end = mid
return arr[start:start + k]
|
# 1
x = float(input("First number: "))
y = float(input("Second number: "))
if x > y:
print(f"{x} is greater than {y}")
elif x < y:
print(f"{x} is less than {y}")
else:
print(f"{x} is equal to {y}")
# bb
quiz = float(input("quiz: "))
mid_term = float(input("midterm: "))
final = float(input("final: "))
avg = (quiz + mid_term + final) / 3
if avg > 90:
print("Congrats! You got an A")
# if else
x = 6
if x >=3:
y = x-3
else:
y = x+3
print("y is",y)
# max
x = float(input("First number: "))
y = float(input("Second number: "))
print("The larger number is:", x if x > y else y) # max(x, y) can also be used
|
palavra = str(input('Digite uma frase: ')).strip().upper()
frase = palavra.split()
junto = ''.join(frase)
inverso = ''
for letra in range(len(junto) - 1, -1, -1):
inverso += junto[letra]
if inverso == palavra:
print('é um palindroma')
else:
print('não é um palindroma')
|
'''
um contador indo pela contagem regressiva e outro tendo incremento a cada passagem pelo loop
'''
contrario = 10
for var in range(0, 9):
print(var, contrario)
contrario -= 1
print('\nresolução do professor')
for i, r in enumerate(range(10, 1, -1)):
print(i, r)
|
x = {}
print(type(x))
file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
print(file_counts)
print(file_counts["txt"])
print("html" in file_counts) #true if found
#dictionaries are mutable
file_counts["cfg"] = 8 #add item
print(file_counts)
file_counts["csv"] = 17 #replaces value for already assigned csv
print(file_counts)
del file_counts["cfg"]
print(file_counts)
file_counts = {"jpg":10, "txt":14, "csv":2, "py":23}
for extension in file_counts:
print(extension)
for ext, amount in file_counts.items(): #value pairs
print("There are {} files with the .{} extension".format(amount, ext))
print(file_counts.keys(), file_counts.values())
cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"}
for keys, values in cool_beasts.items():
print("{} have {}".format(keys, values))
print("Test get: " + cool_beasts.get("octopuses"))
def count_letters(text):
result = {}
for letter in text:
if letter not in result:
result[letter] = 0
result[letter] += 1
return result
count_letters("aaaaa")
count_letters("tenant")
print(count_letters("lksdajfo;asijnfl;kdnv;oisrnfg;lzknv;oizdfo;hgj"))
wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]}
for clothes, color in wardrobe.items():
for n in color:
print("{} {}".format(n, clothes)) |
# Tweepy
# Copyright 2010-2021 Joshua Roesslein
# See LICENSE for details.
def list_to_csv(item_list):
if item_list:
return ','.join(map(str, item_list))
|
#Leia uma data de nascimento de uma pessoa fornecida
#através de três números inteiros:
#Dia, Mês e Ano. Teste a validade desta data para saber se
#esta é uma data válida. Teste se o dia fornecido é um dia
#válido: dia > O, dia < 28 para o mês de fevereiro (29 se o
#ano for bissexto), dia < 30 em abril, junho, setembro e
#novembro, dia < 31 nos outros nmeses. Teste a validade do
#mês: mês > O e mês < 13. Teste a validade do ano: ano <
#ano atual (use uma constante definida com o valor igual
#a 2008). Imprimir: “data válida” ou “data inválida” no
#final da execução do programa.
dia=int(input("Informe o dia do seu aniversario(Em numeros): "))
mes=int(input("Informe o mes do seu aniversario(Em numeros): "))
ano=int(input("Informe o ano do seu aniversario(Em numeros): "))
if(ano<2022):
if(1<=mes<=12):
if(1<=dia<=31):
if((mes==2) and ((ano%4==0 and ano%100!=0)or(ano%400==0))and(1<=dia<=28)):
print("Data Valida")
elif(mes==2 and (1<=dia<=28)):
print("Data Valida")
elif(mes!=2 and (1<=dia<=31)):
print("Data Valida")
else:
print("Data Invalidaalida")
else:
print("Data Invalida")
else:
print("Data Invalida")
else:
print("Data Invalida") |
'''
Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
You must write an algorithm with O(log n) runtime complexity
'''
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
if not nums:
return [-1, -1]
left, right = -1, len(nums) - 1
while left < right - 1:
mid = (left + right) // 2
if nums[mid] < target:
left = mid
elif nums[mid] >= target:
right = mid
if nums[right] == target:
ans_left = right
else:
return [-1, -1]
left, right = left + 1, len(nums)
while left < right - 1:
mid = (left + right) // 2
if nums[mid] > target:
right = mid
elif nums[mid] == target:
left = mid
ans_right = right - 1
return [ans_left, ans_right] |
def knapsack(limit, values, weights):
"""Returns the maximum value that can be reached using given weights"""
n = len(weights)
dp = [0]*(limit+1)
for i in range(n):
for j in range(limit, weights[i]-1, -1):
dp[j] = max(dp[j], values[i] + dp[j - weights[i]])
return dp[-1] |
_base_ = [
'../_base_/models/resnet50.py', '../_base_/datasets/imagenet_bs32.py',
'../_base_/schedules/imagenet_bs256.py', '../_base_/default_runtime.py'
]
load_from = "https://download.openmmlab.com/mmclassification/v0/resnet/resnet50_8xb32_in1k_20210831-ea4938fc.pth" |
x = int(input("Please enter a number: "))
if x % 2 == 0 :
print(x, "is even")
else :
print(x, "is odd")
|
class Memoization:
allow_attr_memoization = False
def _set_attr(obj, attr_name, value_func):
setattr(obj, attr_name, value_func())
return getattr(obj, attr_name)
def _memoize_attr(obj, attr_name, value_func):
if not Memoization.allow_attr_memoization:
return value_func()
try:
return getattr(obj, attr_name)
except AttributeError:
return _set_attr(obj, attr_name, value_func)
|
class BotConfiguration(object):
def __init__(self, auth_token, name, avatar):
self._auth_token = auth_token
self._name = name
self._avatar = avatar
@property
def name(self):
return self._name
@property
def avatar(self):
return self._avatar
@property
def auth_token(self):
return self._auth_token
|
gatitos = {'Padrão': [' ',
' ,_ _ ',
' |\\\\_,-// ',
' / _ _ | ,--.',
'( @ @ ) / ,-\'',
' \ _T_/-._( ( ',
' / `. \\ ',
'| _ \\ | ',
' \ \ , / | ',
' || |-_\__ / ',
' ((_/`(____,-\' ',
' ',
' '
]
}
|
#author SANKALP SAXENA
# Complete the has_cycle function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def has_cycle(head):
s = set()
temp = head
while True:
if temp.next == None:
return False
if temp.next not in s:
s.add(temp.next)
else:
return True
temp = temp.next
return False
|
'''
URL: https://leetcode.com/problems/hamming-distance/
Difficulty: Easy
Description: Hamming Distance
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
'''
class Solution:
def decimal_to_binary(self, n):
output = ""
while n > 0:
output += str(n % 2)
n = n // 2
return output[::-1]
def hammingDistance(self, x, y):
x_binary = self.decimal_to_binary(x)
y_binary = self.decimal_to_binary(y)
max_len = max(len(x_binary), len(y_binary))
x_binary = "0" * (max_len - len(x_binary)) + x_binary
y_binary = "0" * (max_len - len(y_binary)) + y_binary
count = 0
for i in range(max_len):
if x_binary[i] != y_binary[i]:
count += 1
return count
|
{
'targets': [
{
'target_name': 'test_new_target',
'defines': [ 'V8_DEPRECATION_WARNINGS=1' ],
'sources': [
'../entry_point.c',
'test_new_target.c'
]
}
]
}
|
# -*-coding:utf-8 -*-
#Reference:**********************************************
# @Time : 2019-10-11 00:00
# @Author : Fabrice LI
# @File : 578_lowest_common_ancestor_III.py
# @User : liyihao
# @Software : PyCharm
# @Description: Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the two nodes.
# The lowest common ancestor is the node with largest depth which is the ancestor of both nodes.
# Return null if LCA does not exist. node A or node B may not exist in tree.
# Each node has a different value
#Reference:**********************************************
'''
E.g
Input:
{4, 3, 7, #, #, 5, 6}
3 5
5 6
6 7
5 8
Output:
4
7
7
null
Explanation:
4
/ \
3 7
/ \
5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
LCA(5, 8) = null
Input:
{1}
1 1
Output:
1
Explanation:
The tree is just a node, whose value is 1.
'''
# Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
class Solution:
def __init__(self):
self.ans = None
"""
@param: root: The root of the binary tree.
@param: A: A TreeNode
@param: B: A TreeNode
@return: Return the LCA of the two nodes.
"""
def lowestCommonAncestor3(self, root, A, B):
def search(root):
if not root:
return False
left = search(root.left)
right = search(root.right)
mid = root == A or root == B
if mid + left + right >= 2:
self.ans = root
return mid or left or right
search(root)
return self.ans
# 创建二叉树
def build(data):
if len(data) == 0:
return TreeNode(0)
nodeQueue = []
# 创建一根节点,并将根节点进栈
root = TreeNode(data[0])
nodeQueue.append(root)
# 记录当前行节点的数量
lineNum = 2
# 记录当前行中数字在数组中的位置
startIndex = 1
# 记录数组中剩余元素的数量
restLength = len(data) - 1
while restLength > 0:
for index in range(startIndex, startIndex + lineNum, 2):
if index == len(data):
return root
cur_node = nodeQueue.pop()
if data[index] is not None:
cur_node.left = TreeNode(data[index])
nodeQueue.append(cur_node.left)
if index + 1 == len(data):
return root
if data[index + 1] is not None:
cur_node.right = TreeNode(data[index + 1])
nodeQueue.append(cur_node.right)
startIndex += lineNum
restLength -= lineNum
# 此处用来更新下一层树对应节点的最大值
lineNum = len(nodeQueue) * 2
return root
if __name__ == "__main__":
nums2 = [4,3,7,None,None,5,6]
root = build(nums2)
A = TreeNode(5)
B = TreeNode(6)
is_balanced = Solution().lowestCommonAncestor3(root, A, B)
print(is_balanced)
|
x = 10
print(x)
"""
tests here
""" |
usa = ['atlanta','new york','chicago','baltimore']
uk = ['london','bristol','cambridge']
india = ['mumbai','delhi','banglore']
'''
#(a)
i=input("Enter city name: ")
if i in usa:
print('city is in USA')
elif i in uk:
print('city is in UK')
elif i in india:
print('city is in INDIA')
else:
print('idk the country of the city entered!!')
'''
#(b)
i=input("Enter 1st city name: ")
j=input("Enter 2nd city name: ")
if (i in usa and j in usa) or (i in uk and j in uk) or (i in india and j in india):
print("Both are in same country!")
else:
print("Both are in different countries!") |
h = float(input('Altura [m]: '))
w = float(input('Largura [m]: '))
a = w * h
print('Área: {:.2f}m²'.format(a))
print('Tinta: {}L'.format(a/2))
|
#Base Class, Uses a descriptor to set a value
class Descriptor:
def __init__(self, name=None, **opts):
self.name = name
for key, value in opts.items():
setattr( self, key, value)
def __set__(self, instance, value):
instance.__dict__[self.name] = value
#Descriptor for enforcing types
class Typed( Descriptor ):
expected_type = type( None )
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError('expected '+str(self.expected_type ) )
super().__set__(instance, value)
#Descriptor for enforcing values
class Unsigned(Descriptor):
def __set__(self, instance, value):
if value < 0:
raise ValueError('Expected >=0 ')
super().__set__( instance, value )
#Descriptor for enforcing size
class MaxSized(Descriptor):
def __init__(self, name=None, **opts):
if 'size' not in opts:
raise TypeError('missing size option')
super().__init__(name, **opts )
def __set__(self, instance, value):
if len(value) >= self.size:
raise ValueError( 'size must be < ' + str( self.size ) )
super().__set__(instance, value)
class Integer(Typed):
expected_type = int
class UnsignedInteger( Integer, Unsigned):
pass
class Float(Typed):
expected_type = float
class UnsignedFloat( Float, Unsigned):
pass
class String(Typed):
expected_type = str
class SizedString( String, MaxSized):
pass
#Method 1
class Stock:
#Specify constraints
name = SizedString('name', size=8)
shares = UnsignedInteger('shares')
price = UnsignedFloat('price')
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
print('Method 1')
s = Stock('ACME', 50, 91.1)
print( s.name )
s.shares = 75
print( s.shares)
try:
s.shares = -1
except:
pass
print( s.shares )
try:
s.name = 'AAAABBBC'
except:
pass
print( s.name )
'''
There are some techniques that can be used to simplify the specification of constraints
in classes. One approach is to use a class decorator
'''
#Class decorator to apply constraints
def check_attributes(**kwargs ):
def decorate( cls ):
for key,value in kwargs.items():
if isinstance( value, Descriptor ):
value.name = key
setattr(cls, key , value)
else:
setattr(cls, key, value(key) )
return cls
return decorate
#Example
@check_attributes(
name=SizedString(size=8),
shares=UnsignedInteger,
price=UnsignedFloat
)
class Stock:
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
print('Method 2')
s = Stock('ACME', 50, 91.1)
print( s.name )
s.shares = 75
print( s.shares)
try:
s.shares = -1
except:
pass
print( s.shares )
try:
s.name = 'AAAABBBC'
except:
pass
print( s.name )
#A metaclass that applies checking Method3
class checkedmeta( type ):
def __new__(cls, clsname, bases, methods ):
#Attach attribute names to the descriptors
for key, value in methods.items():
if isinstance( value, Descriptor ):
value.name = key
return type.__new__(cls, clsname, bases, methods)
# Example
class Stock(metaclass=checkedmeta):
#default name eq name,better than method1
name = SizedString(size=8)
shares = UnsignedInteger()
price = UnsignedFloat()
def __init__(self, name, shares, price):
self.name = name
self.shares = shares
self.price = price
print('Method 3')
s = Stock('ACME', 50, 91.1)
print( s.name )
s.shares = 75
print( s.shares)
try:
s.shares = -1
except:
pass
print( s.shares )
try:
s.name = 'AAAABBBC'
except:
pass
print( s.name )
#Normal
class Point:
x = Integer('x')
y = Integer('y')
#MetaClass
class Point(metaclass=checkedmeta):
x = Integer()
y = Integer()
#use property functions~ TODO:: Change Typed,Unsigned,MaxSized as Method,
|
{
"targets": [
{
"target_name": "napi_test",
"sources": [ "napi.test.c" ]
},
{
"target_name": "napi_arguments",
"sources": [ "napi_arguments.c" ]
},
{
"target_name": "napi_async",
"sources": [ "napi_async.cc" ]
},
{
"target_name": "napi_construct",
"sources": [ "napi_construct.c" ]
},
{
"target_name": "napi_error",
"sources": [ "napi_error.c" ]
},
{
"target_name": "napi_fatal_error",
"sources": [ "napi_fatal_error.c" ]
},
{
"target_name": "napi_make_callback_recurse",
"sources": [ "napi_make_callback_recurse.cc" ]
},
{
"target_name": "napi_make_callback",
"sources": [ "napi_make_callback.c" ]
},
{
"target_name": "napi_object_wrap",
"sources": [ "napi_object_wrap.c" ]
},
{
"target_name": "napi_reference",
"sources": [ "napi_reference.c" ]
},
{
"target_name": "napi_new_target",
"sources": [ "napi_new_target.c" ]
},
{
"target_name": "napi_string",
"sources": [ "napi_string.c" ]
},
{
"target_name": "napi_thread_safe",
"sources": [ "napi_thread_safe.c" ]
},
{
"target_name": "napi_tsfn",
"sources": [ "napi_tsfn.c" ]
},
{
"target_name": "napi_typedarray",
"sources": [ "napi_typedarray.c" ]
}
]
}
|
__title__ = 'Django Platform Data Service'
__version__ = '0.0.4'
__author__ = 'Komol Nath Roy'
__license__ = 'MIT'
__copyright__ = 'Copyright 2020 Komol Nath Roy'
VERSION = __version__
default_app_config = 'django_pds.apps.DjangoPdsConfig'
|
#!C:\Python27
# For 500,000 mutables, this takes WAY to long. Look for better options
orgFile = open('InputList.txt', 'r')
newFile = open('SortedList.txt', 'w')
unsortedList = [line.strip() for line in orgFile]
def bubble_sort(list):
for i in reversed(range(len(list))):
finished = True
for j in range(i):
if list[j] > list[j + 1]:
list[j], list[j + 1] = list[j + 1], list[j]
finished = False
if finished:
break
return list
sortedList = bubble_sort(unsortedList)
for i in sortedList:
newFile.write("%s\n" % i)
orgFile.close()
newFile.clsoe()
|
students = []
def displayMenu():
print("What would you like to do?")
print("\t(a) Add new student: ")
print("\t(v) View students: ")
print("\t(q) Quit: ")
choice = input("Type one letter (a/v/q): ").strip()
return choice
#test the function
def doAdd():
currentstudent = {}
currentstudent["name"]=input("Enter Name: ")
currentstudent["modules"]= readmodules()
students.append(currentstudent)
def readmodules():
modules = []
modulesName = input("\tEnter the first module name (blank to quit): ").strip()
while modulesName != "":
module = {}
module["name"] = modulesName
module["grade"] = int(input("Enter Grade: "))
modules.append(module)
modulesName = input("\tEnter next module name (blank to quit: )").strip()
return modules
def displayModules(modules):
print("\tName \tGrade")
for module in modules:
print("\t{}\t{}".format(module["name"], module["grade"]))
def doView():
for currentstudent in students:
print(currentstudent["name"])
displayModules(currentstudent["modules"])
choice = displayMenu()
while (choice != 'q'):
if choice == 'a':
doAdd()
elif choice == 'v':
doView()
elif choice != 'q':
print("\n\nPlease select a, v or q")
choice = displayMenu()
print(students)
|
def collect(items, item):
if item in collecting_items:
return
collecting_items.append(item)
return
def drop(items, item):
if item in collecting_items:
collecting_items.remove(item)
return
return
def combine_items(old, new):
if old in collecting_items:
for el in collecting_items:
if el == old:
index_of_el = collecting_items.index(el)
collecting_items.insert(index_of_el + 1, new)
return
return
def renew(items, item):
if item in collecting_items:
collecting_items.remove(item)
collecting_items.append(item)
return
return
def split_items(items, item):
oldy, newy = item.split(":")
return oldy, newy
def is_item_in_list(items, item):
if item in items:
is_item_there = True
return is_item_there
return
collecting_items = input().split(", ")
command, item = input().split(" - ")
is_item_there = False
while command != "Craft!":
if command == "Collect":
is_item_in_list(collecting_items, command)
if not is_item_there:
collect(command)
if command == "Drop":
is_item_in_list(collecting_items, command)
if not is_item_there:
drop(command)
if command == "Combine Items":
if not is_item_there:
result3, result4 = split_items(item) # splitting the combining items by ":"
combine_items(result3, result4)
if command == "Renew":
is_item_in_list(collecting_items, command)
if not is_item_there:
renew(command)
print(collecting_items)
command = input().split(" - ")
print(", ".join(collecting_items))
print(*collecting_items, sep=", ")
# Iron, Sword, Stone
# Drop - Bronze
# Combine Items - Sword:Bow
# Renew - Iron
# Craft!
|
# Make this unique, and don't share it with anybody.
SECRET_KEY = ''
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
JOBS_NEW_THRESHOLD = 1
JOBS_NOTIFICATION_LIST = [] # list of email addresses
GATEKEEPER_ENABLE_AUTOMODERATION = True
GATEKEEPER_DEFAULT_STATUS = 0
GATEKEEPER_MODERATOR_LIST = JOBS_NOTIFICATION_LIST |
#* Asked by Facebook
#? Given a list of sorted numbers, build a list of strings displaying numbers,
#? Where each string is first and last number of linearly increasing numbers.
#! Example:
#? Input: [0,1,2,2,5,7,8,9,9,10,11,15]
#? Output: ['0 -> 2','5 -> 5','7 -> 11','15 -> 15']
#! Note that numbers will not be lower than 0, also numbers may repeat
def truncateList(lst):
if len(lst) == 0: return list()
num = lst[0]
next_num = num+1
start_num = num
final_lst = list()
i = 1
while i < len(lst):
if lst[i] == num or lst[i] == next_num:
pass
else:
final_lst.append(f"{start_num} -> {num}")
start_num = lst[i]
num = lst[i]
next_num = num + 1
i+=1
else:
final_lst.append(f"{start_num} -> {num}")
return final_lst
print(truncateList([0,1,2,2,5,7,8,9,9,10,11,15]))
# ['0 -> 2', '5 -> 5', '7 -> 11', '15 -> 15'] |
# Copyright (c) 2018-2019 Arizona Board of Regents
#
# 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.
class FigSize(object):
"""Helper to compute the size of matplotlib figures.
The idea is to perform conversion between absolute margin sizes (and spacing between rows and columns
in case of multiple subplots) and their corresponding relative that are needed for matplotlib.
Additionnally, there is the possibility to reserve room on a plot to add a color bar.
"""
SIZE_ALL = 1
SIZE_NO_CBAR = 2
SIZE_AXES = 3
SIZE_AX = 4
SIZE_RATIO_AX = 5
def __init__( self, size_h = None, size_v = None, nrows = 1, ncols = 1, margin_left = None, margin_bottom = None, margin_right = None, margin_top = None ):
self.size_h = size_h
self.type_h = self.SIZE_ALL
self.size_v = size_v
self.type_v = self.SIZE_ALL
self.nrows = nrows
self.ncols = ncols
self.margin_left = margin_left
self.margin_bottom = margin_bottom
self.margin_right = margin_right
self.margin_top = margin_top
self.spacing_h = None
self.spacing_v = None
self.cbar_loc = None
self.cbar_width = None
self.cbar_pad = None
def set_size_h( self, size_h, type_h = None ):
"""Set the horizontal size of the figure.
Parameters
----------
size_h : float
Horizontal size of the figure in inches, the meaning depends on the value of parameter `type_h`.
type_h : int
Mode for the horizontal size, one of the SIZE_* constants.
- SIZE_ALL: `size_h` is the total size of the figure, including margins and color bar (default)
- SIZE_NO_CBAR: `size_h` is the size of the figure, without the potential color bar
- SIZE_AXES: `size_h` is the size of the axis region of the figure, without the margins and the potential color bar.
- SIZE_AX: `size_h` is the size of one of the axis.
- SIZE_RATIO_AX: `size_h` is the ratio of the vertical size of the axis region.
"""
self.size_h = size_h
if not type_h is None:
self.type_h = type_h
def set_size_v( self, size_v, type_v = None ):
"""Set the vertical size of the figure.
Parameters
----------
size_v : float
Vertical size of the figure, the meaning depends on the value of parameter `type_v`.
type_v : int
Mode for the vertical size, one of the SIZE_* constants.
- SIZE_ALL: `size_v` is the total size of the figure, including margins and color bar (default)
- SIZE_NO_CBAR: `size_v` is the size of the figure, without the potential color bar
- SIZE_AXES: `size_v` is the size of the axis region of the figure, without the margins and the potential color bar.
- SIZE_AX: `size_v` is the size of one of the axis.
- SIZE_RATIO_AX: `size_v` is the ratio of the horizontal size of the axis region.
"""
self.size_v = size_v
if not type_v is None:
self.type_v = type_v
def set_nrows( self, nrows ):
"""Set the number of rows of subplots that will be inserted in the figure
This is used to compute the vertical spacing between the rows.
Parameters
----------
nrows : int
Number of rows of subplots that will be inserted in the figure
"""
self.nrows = nrows
def set_ncols( self, ncols ):
"""Set the number of columns of subplots that will be inserted in the figure
This is used to compute the horizontal spacing between the rows.
Parameters
----------
ncols : int
Number of columns of subplots that will be inserted in the figure
"""
self.ncols = ncols
def get_margin_left( self ):
"""Retrieve the left margin"""
return self.margin_left
def set_margin_left( self, margin_left ):
"""Set the left margin
Parameters
----------
margin_left : float
Left margin, in inches
"""
self.margin_left = margin_left
def get_margin_bottom( self ):
"""Retrieve the bottom margin"""
return self.margin_bottom
def set_margin_bottom( self, margin_bottom ):
"""Set the bottom margin
Parameters
----------
margin_bottom : float
Bottom margin, in inches
"""
self.margin_bottom = margin_bottom
def get_margin_right( self ):
"""Retrieve the right margin"""
return self.margin_right
def set_margin_right( self, margin_right ):
"""Set the right margin
Parameters
----------
margin_right : float
Right margin, in inches
"""
self.margin_right = margin_right
def get_margin_top( self ):
"""Retrieve the top margin"""
return self.margin_top
def set_margin_top( self, margin_top ):
"""Set the top margin
Parameters
----------
margin_top : float
Top margin, in inches
"""
self.margin_top = margin_top
def set_spacing_h( self, spacing_h ):
"""Set the horizontal spacing between panels.
By default it is equal to the sum of the left and right margins.
Parameters
----------
spacing_h : float or None
Horizontal spacing in inches, or None to reset to default.
"""
self.spacing_h = spacing_h
def set_spacing_v( self, spacing_v ):
"""Set the vertical spacing between panels.
By default it is equal to the sum of the top and bottom margins.
Parameters
----------
spacing_v : float or None
Vertical spacing in inches, or None to reset to default.
"""
self.spacing_v = spacing_v
def set_cbar_loc( self, cbar_loc ):
"""Set the location of the color bar
Parameters
----------
cbar_loc : "left", "bottom", "right" or "top"
Location of the color with respect to the plot area,
any other value will not reserve any room for the color bar on the figure.
"""
self.cbar_loc = cbar_loc
def set_cbar_width( self, cbar_width ):
"""Set the width of the color bar
Parameters
----------
cbar_width : float
Set the width of the color bar plot area, in inches
"""
self.cbar_width = cbar_width
def set_cbar_pad( self, cbar_pad ):
"""Set the padding between the color bar and the plot area.
Parameters
----------
cbar_loc : float
Set the width of the color bar axis area, in inches
"""
self.cbar_pad = cbar_pad
def get_figure_size( self ):
"""Determine the actual size of the figure.
This will determine the total size of the figure, including margins and color bar if needed.
Returns
-------
tuple
Horizontal and vertical size of the figure, in inches
"""
size_h = self.size_h
size_v = self.size_v
if self.spacing_h is None:
spacing_h = self.margin_left + self.margin_right
else:
spacing_h = self.spacing_h
if self.spacing_v is None:
spacing_v = self.margin_bottom + self.margin_top
else:
spacing_v = self.spacing_v
if self.type_h == self.SIZE_RATIO_AX:
if self.type_v == self.SIZE_RATIO_AX:
raise Exception( "type_h and type_v cannot be both SIZE_RATIO_AX at the same time." )
elif self.type_v == self.SIZE_AX:
size_h *= size_v
elif self.type_v == self.SIZE_AXES:
size_h *= ( size_v - spacing_v * ( self.nrows - 1 ) ) / self.nrows
elif self.type_v == self.SIZE_NO_CBAR:
size_h *= ( size_v - self.margin_bottom - self.margin_top - spacing_v * ( self.nrows - 1 ) ) / self.nrows
else:
size_h *= ( size_v - ( self.cbar_width + self.cbar_pad if self.cbar_loc == "bottom" or self.cbar_loc == "top" else 0. ) - self.margin_bottom - self.margin_top - spacing_v * ( self.nrows - 1 ) ) / self.nrows
if self.type_v == self.SIZE_RATIO_AX:
if self.type_h == self.SIZE_RATIO_AX:
# Should not happen, but just in case
raise Exception( "type_h and type_v cannot be both SIZE_RATIO_AX at the same time." )
elif self.type_h == self.SIZE_AX:
size_v *= size_h
elif self.type_h == self.SIZE_AXES:
size_v *= ( size_h - spacing_h * ( self.ncols - 1 ) ) / self.ncols
elif self.type_h == self.SIZE_NO_CBAR:
size_v *= ( size_h - self.margin_left - self.margin_right - spacing_h * ( self.ncols - 1 ) ) / self.ncols
else:
size_v *= ( size_h - ( self.cbar_width + self.cbar_pad if self.cbar_loc == "left" or self.cbar_loc == "right" else 0. ) - self.margin_left - self.margin_right - spacing_h * ( self.ncols - 1 ) ) / self.ncols
if self.type_h == self.SIZE_AX or self.type_h == self.SIZE_RATIO_AX:
size_h *= self.ncols
size_h += spacing_h * ( self.ncols - 1 )
if self.type_v == self.SIZE_AX or self.type_v == self.SIZE_RATIO_AX:
size_v *= self.nrows
size_v += spacing_v * ( self.nrows - 1 )
if self.type_h == self.SIZE_AXES or self.type_h == self.SIZE_AX or self.type_h == self.SIZE_RATIO_AX:
size_h += self.margin_left + self.margin_right
if self.type_v == self.SIZE_AXES or self.type_v == self.SIZE_AX or self.type_v == self.SIZE_RATIO_AX:
size_v += self.margin_bottom + self.margin_top
if ( self.type_h == self.SIZE_NO_CBAR or self.type_h == self.SIZE_AXES or self.type_h == self.SIZE_AX or self.type_h == self.SIZE_RATIO_AX ) and ( self.cbar_loc == "left" or self.cbar_loc == "right" ):
size_h += self.cbar_width + self.cbar_pad
if ( self.type_v == self.SIZE_NO_CBAR or self.type_v == self.SIZE_AXES or self.type_v == self.SIZE_AX or self.type_v == self.SIZE_RATIO_AX ) and ( self.cbar_loc == "bottom" or self.cbar_loc == "top" ):
size_v += self.cbar_width + self.cbar_pad
return ( size_h, size_v )
def get_figure_args( self ):
"""
Get the size arguments for when creating a figure.
Returns
-------
dict
Arguments for the matplotlib.pyplot.figure() function.
"""
return { "figsize": self.get_figure_size() }
def get_subplots_args( self ):
"""
Get the arguments for the location of the subplots.
Returns
-------
dict
Arguments for the Figure.subplots_adjust() function.
"""
size_h, size_v = self.get_figure_size()
left = self.margin_left
bottom = self.margin_bottom
right = self.margin_right
top = self.margin_top
if self.cbar_loc == "left":
left += self.cbar_width + self.cbar_pad
if self.cbar_loc == "right":
right += self.cbar_width + self.cbar_pad
if self.cbar_loc == "bottom":
bottom += self.cbar_width + self.cbar_pad
if self.cbar_loc == "top":
top += self.cbar_width + self.cbar_pad
if self.spacing_h is None:
spacing_h = self.margin_left + self.margin_right
else:
spacing_h = self.spacing_h
if self.spacing_v is None:
spacing_v = self.margin_bottom + self.margin_top
else:
spacing_v = self.spacing_v
if self.ncols > 1 and spacing_h > 0.:
wspace = self.ncols / ( ( size_h - right - left ) / spacing_h - ( self.ncols - 1 ) )
else:
wspace = 0.
if self.nrows > 1 and spacing_v > 0.:
hspace = self.nrows / ( ( size_v - top - bottom ) / spacing_v - ( self.nrows - 1 ) )
else:
hspace = 0.
return { "left": left / size_h, "bottom": bottom / size_v, "right": 1. - right / size_h, "top": 1. - top / size_v, "wspace": wspace, "hspace": hspace }
def has_cbar( self ):
"""Retrieve whether room has been reserved for the color bar.
Returns
-------
bool
Whether room is reserved for the color bar.
"""
return self.cbar_loc == "left" or self.cbar_loc == "right" or self.cbar_loc == "bottom" or self.cbar_loc == "top"
def get_cbar_ax_spec( self ):
"""Retrieve the location of the color bar in the figure.
Returns
-------
list
Location of the area for the color bar, which can be used as an argument to Figure.add_axes().
"""
size_h, size_v = self.get_figure_size()
if self.cbar_loc == "left":
return [ self.margin_left / size_h, self.margin_bottom / size_v, self.cbar_width / size_h, 1. - ( self.margin_bottom + self.margin_top ) / size_v ]
if self.cbar_loc == "right":
return [ 1. - ( self.cbar_width + self.cbar_pad ) / size_h, self.margin_bottom / size_v, self.cbar_width / size_h, 1. - ( self.margin_bottom + self.margin_top ) / size_v ]
if self.cbar_loc == "bottom":
return [ self.margin_left / size_h, self.margin_bottom / size_v, 1. - ( self.margin_left + self.margin_right ) / size_h, self.cbar_width / size_v ]
if self.cbar_loc == "top":
return [ self.margin_left / size_h, 1. - ( self.cbar_width + self.margin_top ) / size_v, 1. - ( self.margin_left + self.margin_right ) / size_h, self.cbar_width / size_v ]
return None
def get_cbar_orientation( self ):
"""Retrieve the orientation of the color bar.
Returns
-------
"vertical", "horizontal" or None
Orientation of the color bar, which can be provided as the value of the "orientation" parameter of Figure.colorbar(), or None if disabled.
"""
if self.cbar_loc == "left" or self.cbar_loc == "right":
return "vertical"
if self.cbar_loc == "bottom" or self.cbar_loc == "top":
return "horizontal"
return None
|
#!/usr/bin/env python3
"""
Advent of Code 2018
Puzzle #2 - 2018-12-02: Find two strings with hamming distance of one
# https://adventofcode.com/2018/day/2
Input (via stdin): A series of strings. e.g.:
abcdef
hijklm
uvwxyz
azcdef
Output: One of two strings that differ by exactly one character, with the matching character excluded. e.g.:
acdef
"""
def find_id_with_hamming_of_one(ids):
# We're going to be bad and assume that all IDs are the same length.
# It's true in our input, but not explicit in the problem statement.
# We're also just going to bruteforce it in a most horrendous manner:
for i in range(1, len(list(ids)[0])):
split_ids = set()
for id in ids:
s = id[0:i] + id[i+1:]
if s in split_ids:
return s
split_ids.add(s)
if __name__ == "__main__":
ids = set()
try:
while True:
ids.add(input())
except EOFError:
print(find_id_with_hamming_of_one(ids)) |
"""
Navigation provides the basic functionality of a page navigation
to navigate between sites
"""
class Navigation:
TEMPLATE = 'nav.j2'
def __init__(self, env, pages):
self._env = env
self._pages = pages
def render(self, name, current_page, tpl_file=None):
if tpl_file is None:
tpl_file = self.TEMPLATE
# prepare data
nodes = []
for page in self._pages:
node = {
'href': f"{page['file']}.html",
'name': page['name'],
'is_active': False
}
if page['name'] == current_page:
node['is_active'] = True
nodes.append(node)
# read template
tpl = self._env.get_template(tpl_file)
# render
return tpl.render(name=name, nodes=nodes) |
expected_output = {
"session_type": {
"AnyConnect": {
"username": {
"lee": {
"index": {
1: {
"assigned_ip": "192.168.246.1",
"bytes": {"rx": 4942, "tx": 11079},
"duration": "0h:00m:15s",
"encryption": "RC4 AES128",
"group_policy": "EngPolicy",
"hashing": "SHA1",
"inactivity": "0h:00m:00s",
"license": "AnyConnect Premium",
"login_time": "15:25:13 EST Fri Jan 28 2011",
"nac_result": "Unknown",
"protocol": "AnyConnect-Parent SSL-Tunnel DTLS-Tunnel",
"public_ip": "10.139.1.2",
"tunnel_group": "EngGroup",
"vlan": "none",
"vlan_mapping": "N/A",
}
}
},
"yumi": {
"index": {
2: {
"assigned_ip": "192.168.246.2",
"bytes": {"rx": 6942, "tx": 11055},
"duration": "0h:05m:15s",
"encryption": "RC4 AES128",
"group_policy": "EngPolicy",
"hashing": "SHA1",
"inactivity": "0h:00m:00s",
"license": "AnyConnect Premium",
"login_time": "15:25:13 EST Fri Jan 29 2011",
"nac_result": "Unknown",
"protocol": "AnyConnect-Parent SSL-Tunnel DTLS-Tunnel",
"public_ip": "10.139.1.3",
"tunnel_group": "EngGroup",
"vlan": "none",
"vlan_mapping": "N/A",
}
}
},
}
}
}
}
|
num = int(input('Digite um número: '))
n = num % 2
if n == 0:
print('O número {} é par.'.format(num))
else:
print('O número {} é ímpar.'.format(num))
|
"""
@name: Modules/House/Lighting/Lights/__init__.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2020-2020 by D. Brian Kimmel
@license: MIT License
@note: Created on Feb 5, 2020
"""
__updated__ = '2020-02-09'
__version_info__ = (20, 2, 9)
__version__ = '.'.join(map(str, __version_info__))
CONFIG_NAME = 'lights'
class LightInformation:
""" This is the information that the user needs to enter to uniquely define a light.
"""
yaml_tag = u'!light'
def __init__(self, Name=None) -> None:
self.Name: Union[str, None] = Name
self.Comment: Union[str, None] = None
self.DeviceType: str = 'Lighting'
self.DeviceSubType: str = 'Light'
self.Family = None
self.Room = None
def __repr__(self):
"""
"""
l_ret = ''
l_ret += '{}'.format(self.Name)
l_ret += '; {}/{}'.format(str(self.DeviceType), str(self.DeviceSubType))
l_ret += '; Family: {}'.format(self.Family.Name)
return l_ret
# ## END DBK
|
"""
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
Constraints
n = height.length
2 <= n <= 3 * 104
0 <= height[i] <= 3 * 104
https://leetcode.com/problems/container-with-most-water/
"""
class Solution:
def maxArea(self, height: List[int]) -> int:
largestVolume = 0
i = 0
j = len(height) - 1
while j != i:
curVolume = (height[i] if height[i] < height[j] else height[j]) * (j - i)
if curVolume > largestVolume:
largestVolume = curVolume
if height[i] >= height[j]:
j -= 1
else:
i += 1
return largestVolume |
"""
A pytest plugin for testing Tornado apps using plain (undecorated) coroutine tests.
"""
__version_info__ = (0, 6, 0, 'post2')
__version__ = '.'.join(map(str, __version_info__))
|
eventsA = [
{
"end_time": "2020-05-20T17:30:00+0200",
"start_time": "2020-05-20T17:00:00+0200",
"location": "Peaky Blinders - Barber Shop, Antoniego Józefa Madalińskiego 5, Kraków, małopolskie, PL, 33-332",
},
{
"end_time": "2020-05-20T16:30:00+0200",
"start_time": "2020-05-20T16:00:00+0200",
"location": "Łojasiewicza 11, Kraków",
},
{
"end_time": "2020-05-20T15:30:00+0200",
"start_time": "2020-05-20T15:00:00+0200",
"location": "Szewska 1, Kraków",
},
]
eventsB = [
{
"end_time": "2020-05-20T17:30:00+0200",
"start_time": "2020-05-20T17:00:00+0200",
"location": "Karmelicka 60, Kraków",
},
{
"end_time": "2020-05-20T14:30:00+0200",
"start_time": "2020-05-20T12:00:00+0200",
"location": "Czerwone Maki 49, Kraków",
},
{
"end_time": "2020-05-20T20:30:00+0200",
"start_time": "2020-05-20T20:00:00+0200",
"location": "Fabryczna 17, Kraków",
},
]
def window_intersect(window_a, window_b):
return window_a
def split(window_a, window_b):
return window_a
def previous_event(date, userEvents):
return {}
def center_of_gravity(vertices):
return "lat", "long"
def estimate_travel(point_a, point_b):
return 124352
def limit_window(time, window):
return window
date = "2020-05-20"
meeting_windows = [("2020-05-20T00:00:00Z", "2020-05-20T23:59:99Z")]
participantsEvents = [eventsA, eventsB]
for participantEvents in participantsEvents:
for event in participantEvents:
start = event["start_time"]
end = event["end_time"]
event_window = (start, end)
for index, window in enumerate(meeting_windows):
intersection = window_intersect(event_window, window)
if intersection:
windows = split(window, intersection)
meeting_windows[index] = windows
print(meeting_windows)
for index, window in enumerate(meeting_windows):
window_start = window[0]
vertices = []
for participantEvents in participantsEvents:
previous_event = previous_event(window_start, eventsA)
previous_event_location = previous_event["location"]
vertices.append(previous_event_location)
center_location = center_of_gravity(vertices)
max_travel_time = max([estimate_travel(vertex, center_location) for vertex in vertices])
meeting_windows[index] = limit_window(max_travel_time, window)
|
##!FAIL: HeterogenousElementError[str]@23:20
def renverse(L):
""" list[alpha] -> list[alpha]
renverse la liste (l'itérable) L.
"""
# LR : list[alpha] (liste résultat)
LR = []
# i : int (position)
i = len(L) - 1
while i >= 0:
LR.append(L[i])
i = i - 1
return LR
# Jeu de tests
assert renverse([1, 2, 3, 4, 5]) == [5, 4, 3, 2, 1]
assert renverse([]) == []
assert renverse([1, "two", 3, 4, 5]) == [5, 4, 3, "two", 1]
|
class XtbOutputParser:
"""Class for parsing xtb output"""
def __init__(self, output):
self.output = output
self.lines = output.split('\n')
def parse(self):
# output variable
xtb_output_data = {}
# go through lines to find targets
for i in range(len(self.lines)):
if 'HOMO-LUMO GAP' in self.lines[i]:
xtb_output_data['homo_lumo_gap'] = self._extract_homo_lumo_gap(i)
if '(HOMO)' in self.lines[i]:
xtb_output_data['homo_energy'] = self._extract_homo(i)
if '(LUMO)' in self.lines[i]:
xtb_output_data['lumo_energy'] = self._extract_lumo(i)
if 'TOTAL ENERGY' in self.lines[i]:
xtb_output_data['energy'] = self._extract_energy(i)
if 'TOTAL ENTHALPY' in self.lines[i]:
xtb_output_data['enthalpy'] = self._extract_enthalpy(i)
if 'TOTAL FREE ENERGY' in self.lines[i]:
xtb_output_data['free_energy'] = self._extract_free_energy(i)
if 'molecular dipole:' in self.lines[i]:
xtb_output_data['dipole_moment'] = self._extract_dipole_moment(i + 3)
if 'partition function' in self.lines[i]:
xtb_output_data['heat_capacity'] = self._extract_heat_capacity(i + 6)
if 'partition function' in self.lines[i]:
xtb_output_data['entropy'] = self._extract_entropy(i + 6)
if 'zero point energy' in self.lines[i]:
xtb_output_data['zpve'] = self._extract_zpve(i)
return xtb_output_data
def _extract_homo_lumo_gap(self, start_index: int):
line_split = self.lines[start_index].split()
return float(line_split[3])
def _extract_dipole_moment(self, start_index: int):
line_split = self.lines[start_index].split()
return float(line_split[4])
def _extract_enthalpy(self, start_index:int):
line_split = self.lines[start_index].split()
return float(line_split[3])
def _extract_energy(self, start_index:int):
line_split = self.lines[start_index].split()
return float(line_split[3])
def _extract_free_energy(self, start_index:int):
line_split = self.lines[start_index].split()
return float(line_split[4])
def _extract_heat_capacity(self, start_index:int):
line_split = self.lines[start_index].split()
return float(line_split[2])
def _extract_entropy(self, start_index:int):
line_split = self.lines[start_index].split()
return float(line_split[3])
def _extract_zpve(self, start_index:int):
line_split = self.lines[start_index].split()
return float(line_split[4])
def _extract_homo(self, start_index:int):
line_split = self.lines[start_index].split()
return float(line_split[3])
def _extract_lumo(self, start_index:int):
line_split = self.lines[start_index].split()
return float(line_split[2]) |
# Author: Jochen Gast <jochen.gast@visinf.tu-darmstadt.de>
class MovingAverage:
postfix = "avg"
def __init__(self):
self.sum = 0.0
self.count = 0
def add_value(self, sigma, addcount=1):
self.sum += sigma
self.count += addcount
def add_average(self, avg, addcount):
self.sum += avg * addcount
self.count += addcount
def mean(self):
return self.sum / self.count
class ExponentialMovingAverage:
postfix = "ema"
def __init__(self, alpha=0.7):
self.weighted_sum = 0.0
self.weighted_count = 0
self.alpha = alpha
def add_value(self, sigma):
self.weighted_sum = sigma + (1.0 - self.alpha) * self.weighted_sum
self.weighted_count = 1 + (1.0 - self.alpha) * self.weighted_count
def add_average(self, avg, addcount):
self.weighted_sum = avg * addcount + (1.0 - self.alpha) * self.weighted_sum
self.weighted_count = addcount + (1.0 - self.alpha) * self.weighted_count
def mean(self):
return self.weighted_sum / self.weighted_count
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2020/2/25 15:45
# @Author : Vodka0629
# @Email : 563511@qq.com, ZhangXiangming@gmail.com
# @FileName: mj_value.py
# @Software: Mahjong II
# @Blog :
class MjValue(object):
__slots__ = ("meld", "orphan",
"is_ready", "listening", "mahjong_chance",
"count_down", "waiting", "waiting_chance")
def __init__(self,
meld: int = 0,
orphan: int = 0,
is_ready: bool = False,
listening=None,
mahjong_chance=0,
count_down: int = 0,
waiting=None,
waiting_chance=0
):
self.meld = meld
self.orphan = orphan
self.is_ready = is_ready
self.listening = listening
self.mahjong_chance = mahjong_chance
self.count_down = count_down
self.waiting = waiting
self.waiting_chance = waiting_chance
def __str__(self):
waiting = "None"
if self.waiting:
waiting = "".join(["\n" + str(x) for x in self.waiting])
listening = "None"
if self.listening:
listening = "".join(["\n" + str(x) for x in self.listening])
text = f"""meld = {self.meld},
orphan = {self.orphan},
is_read = {self.is_ready},
listening = {listening},
mahjong_chance = {self.mahjong_chance},
count_down = {self.count_down},
waiting = {waiting}
waiting_chance = {self.waiting_chance}
"""
return text
|
"""
link: https://leetcode-cn.com/problems/minimum-unique-word-abbreviation
problem: 给定长为 m 的 target 字符串,与长为 n 的字符串数组,求 target 的最短缩写,且该缩写不为数组中任一子串的缩写。log2(n) + m ≤ 20。
solution: 搜索。搜索上限为 n * 2^m == 2^(log_2(n)) * 2^m == 2^(log_2(n) + m) <= 2^20。
枚举 target 的每个缩写(遍历 [0, 1 << m),用 0 代表该位压缩,1代表不压缩)并检查是否是有其他字符串在未缩写位置上均与其相同。
"""
class Solution:
def minAbbreviation(self, target: str, dictionary: List[str]) -> str:
m, l = len(target), []
for k in dictionary:
if len(k) == m:
l.append(k)
if not l:
return str(m)
res = target
def g_str(t: [int]):
c, x = 0, ""
for k in t:
if c != k:
x += str(k - c)
c = k + 1
x += target[k]
if c != m:
x += str(m - c)
return x
for i in range(0, 1 << m):
t = []
for j in range(m):
if i & (1 << j):
t.append(j)
cnt = 0
for k in l:
match = True
for j in t:
if k[j] != target[j]:
match = False
break
cnt += 1 if match else 0
if cnt > 1:
break
if cnt < 1:
cur_str = g_str(t)
if len(cur_str) < len(res):
res = cur_str
return res
|
ejem = "esto es un ejemplo"
print (ejem)
print (ejem[8:18], ejem[5:7], ejem[0:4])
subejem = ejem[8:18] + ejem[4:8] + ejem[0:4]
print (subejem)
#ejem = ejem.split(" ")
#print (ejem[2:4], ejem[1::-1]) |
"""Constants for the Almond integration."""
DOMAIN = "almond"
TYPE_OAUTH2 = "oauth2"
TYPE_LOCAL = "local"
|
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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 verify_capital(answers: dict) -> dict:
"""
Takes in a dictionary with states as keys and user's answers as values.
Attributes:
mark_scheme: dicitonary containing the correct answers of the quiz.
score: user's total score after quiz.
result: a dictionary containing the correct or wrong answers of the user on each question.
"""
score = 0
mark_scheme = {'CA': 'Sacramento', 'TX': 'Austin', 'WA': 'Olympia', 'DE': 'Dover', 'GA': 'Atlanta'}
result = {}
for state in answers:
if answers[state].lower().title() != mark_scheme[state]:
result[state] = False
else:
result[state] = True
score += 1
final_score = (score / 5) * 100
return result, final_score, mark_scheme
|
"""Top-level package for Proto Wind."""
__author__ = """Kais Sghari"""
__email__ = 'kais.sghari@gmail.com'
__version__ = '0.1.0'
|
"""
pytokio implements its command-line tools within this package. Each such CLI
tool either implements some useful analysis on top of pytokio connectors,
tools, or analysis or maps some of the internal python APIs to command-line
arguments.
Most of these tools implement a ``--help`` option to explain the command-line
options.
"""
|
max_char = 105
sample_rate = 22050
n_fft = 1024
hop_length = 256
win_length = 1024
preemphasis = 0.97
ref_db = 20
max_db = 100
mel_dim = 80
max_length = 780
reduction = 4
embedding_dim = 128
symbol_length = 70
d = 256
c = 512
f = n_fft // 2 + 1
batch_size = 16
checkpoint_step = 500
max_T = 160
learning_rate = 0.0002
beta1 = 0.5
beta2 = 0.9
|
"""Testes para as rotas de auth"""
def test_authentication(fake_user, client_auth_with_one):
"""Testando a rota authentication"""
url = "/api/auth/"
data = {"email": fake_user.email, "password": fake_user.password}
response = client_auth_with_one.post(url=url, json=data)
assert response.status_code == 200
assert isinstance(response.json(), dict)
assert response.json()["message"] is not None
assert isinstance(response.json()["data"], dict)
assert "Authorization" in response.json()["data"]
assert "exp" in response.json()["data"]
assert "user" in response.json()["data"]
|
#Crie um programa que leia a veloiade do carro
#Se ele assar de 80km/h mostre umamensagem dizendo que ele levou uma multa
#A multa va custar R$7,00 por ca da km acima do permitido
'''from random import randint#eu fiz como se um radar ou o propio corro lesse a velcidade sozinho
vc = randint(0,250)
print('Seu carro esta a {}km/h'.format(vc))
if vc >80:
print('VOCE ULTRAPASSOU O LIMTE DE 80KM/H o valor da multa é R${}'.format((vc-80)*7))
else:
print('Continue respeitando o limite de velocidade!')'''
#eu fiz como se o pc estivese lendo a velocidade do carro
#resolção da aula
vc = int(input('Digite uma velocidade:km'))
if vc > 80:
print('Voce esta além do limite de 80km')
print('Nessa velocidade voce ganhou uma multa de R${}'.format((vc-80)*7))
else:
print('VOCE ESTA DENTRO DO LIMITE, CONTINUE ASSIM!')
|
'''
Problem Description
The program takes two dictionaries and
concatenates them into one dictionary.
Problem Solution
1. Declare and initialize two dictionaries
with some key-value pairs
2. Use the update() function to add the
key-value pair from the second dictionary
to the first dictionary.
3. Print the final dictionary.
4. Exit.
'''
d1={'A': 1,'B': 2}
d2={'C': 3}
d1.update(d2)
print(f'First dictionary is: {d1}\nSecon dictionary is: {d2}\nConcatenated dictionary is: {d1}') |
LOC_RECENT = u'/AppData/Roaming/Microsoft/Windows/Recent/'
LOC_REG = u'/Windows/System32/config/'
LOC_WINEVT = LOC_REG
LOC_WINEVTX = u'/Windows/System32/winevt/logs/'
LOC_AMCACHE = u'/Windows/AppCompat/Programs/'
SYSTEM_FILE = [ # [artifact, src_path, dest_dir]
# registry hives
['regb', LOC_REG + u'RegBack/SAM', u'/Registry/RegBack/'],
['regb', LOC_REG + u'RegBack/SECURITY', u'/Registry/RegBack/'],
['regb', LOC_REG + u'RegBack/SOFTWARE', u'/Registry/RegBack/'],
['regb', LOC_REG + u'RegBack/SYSTEM', u'/Registry/RegBack/'],
['regb_xp', LOC_REG + u'Repair/SAM', u'/Registry/Repair/'],
['regb_xp', LOC_REG + u'Repair/SECURITY', u'/Registry/Repair/'],
['regb_xp', LOC_REG + u'Repair/software', u'/Registry/Repair/'],
['regb_xp', LOC_REG + u'Repair/system', u'/Registry/Repair/'],
# system logs
['evtl_xp', LOC_WINEVT + u'AppEvent.evt', u'/OSLogs/evtl/'],
['evtl_xp', LOC_WINEVT + u'SecEvent.evt', u'/OSLogs/evtl'],
['evtl_xp', LOC_WINEVT + u'SysEvent.evt', u'/OSLogs/evtl'],
['setupapi', u'/Windows/Inf/setupapi.dev.log', u'/Registry/'],
['setupapi_xp', u'/Windows/setupapi.log', u'/Registry/'],
# mru
['amcache', LOC_AMCACHE + u'RecentFileCache.bcf', u'/MRU/Prog/recentfilecache/'],
# persistence
['sch_xp', u'/Windows/SchedLgU.txt', u'/Autoruns/sch_tsks/'],
# etl
['etl', u'/ProgramData/Microsoft/Windows/Power Efficiency Diagnostics/energy-ntkl.etl', u'/Misc/etl/'],
['etl', u'/ProgramData/Microsoft/Windows/Power Efficiency Diagnostics/energy-trace.etl', u'/Misc/etl/'],
['etl', u'/Windows/System32/LogFiles/WMI/LwtNetLog.etl', u'/Misc/etl/'],
['etl', u'/Windows/System32/LogFiles/WMI/Wifi.etl', u'/Misc/etl/'],
# file system
['logfile', u'/$LogFile', u'/Filesystem/'],
['mft', u'/$MFT', u'/Filesystem/'],
# others
['bits', u'/ProgramData/Microsoft/Network/Downloader/qmgr.dat', u'/Misc/bits/'],
['pagefile', u'/pagefile.sys', u'/Memory/pagefile/']
]
SYSTEM_DIR = [ # [artifact, src_path, dest_dir, isRecursive, stringToMatch]
# registry hives
['reg', LOC_REG[:-1], u'/Registry/', False, u'SAM'],
['reg', LOC_REG[:-1], u'/Registry/', False, u'SECURITY'],
['reg', LOC_REG[:-1], u'/Registry/', False, u'SOFTWARE'],
['reg', LOC_REG[:-1], u'/Registry/', False, u'SYSTEM'],
# system logs
['etl', u'/Windows/System32/WDI/LogFiles', u'/OSLogs/etl/', False, u'.etl'],
['evtl', LOC_WINEVTX[:-1], u'/OSLogs/evtl/', False, None],
['ual', u'/Windows/System32/LogFiles/SUM', u'/OSLogs/ual/', False, u'.mdb'],
# mru
['amcache', LOC_AMCACHE[:-1], u'/MRU/Prog/amcache/', False, u'Amcache'],
['prefetch', u'/Windows/Prefetch', u'/MRU/Prog/prefetch/', False, u'.pf'],
['sccm', u'/Windows/System32/wbem/Repository', u'/MRU/Prog/sccm/', False, None],
['srum', u'/Windows/System32/sru', u'/MRU/Prog/srum/', False, None],
['sqm', u'/ProgramData/Microsoft/Windows/Sqm/Upload', u'/MRU/Prog/sqm/', False, u'.sqm'],
['syscache', u'/System Volume Information', u'/MRU/Prog/syscache/', False, u'Syscache'],
# persistence
['sch_job', u'/Windows/Tasks', u'/Autoruns/sch_tsks/', False, u'.job'],
['sch_xml', u'/Windows/System32/Tasks', u'/Autoruns/sch_tsks/', True, None],
['startupinfo', u'/Windows/System32/wdi/LogFiles/StartupInfo', u'/Autoruns/startupinfo/', False, u'StartupInfo'],
# others
['antimalware', u'/ProgramData/Microsoft/Microsoft Antimalware/Support', u'/VirusScans/', False, u'MPLog'],
['defender', u'/ProgramData/Microsoft/Windows Defender/Support', u'/VirusScans/', False, u'MPLog'],
['certutil', u'/Windows/System32/config/systemprofile/AppData/LocalLow/Microsoft/CryptnetUrlCache/MetaData',
u'/Misc/certutil/', False, None],
['recycle', u'/$Recycle.Bin', u'/Recycle/', True, None],
['recycle_xp', u'/RECYCLER', u'/Recycle/', True, None],
['sig_ctlg', u'/Windows/System32/CatRoot', u'/Misc/signatures/', True, None],
['wer', u'/ProgramData/Microsoft/Windows/WER', u'/Misc/wer/', True, None]
]
USER_FILE = [ # [artifact, src_path, dest_dir]
# system logs
['etl', u'/AppData/Local/Microsoft/Windows/Explorer/ExplorerStartupLog.etl', u'/OSLogs/etl/'],
['etl', u'/AppData/Local/Microsoft/Windows/Explorer/ExplorerStartupLog_RunOnce.etl', u'/OSLogs/etl/'],
['etl', u'/AppData/Local/Packages/Microsoft.Windows.Cortana_cw5n1h2txyewy/TempState/Traces/CortanaTrace1.etl',
u'/OSLogs/etl/'],
['pshist', u'/AppData/Roaming/Microsoft/Windows/PowerShell/PSReadline/ConsoleHost_history.txt', u'/OSLogs/pshist/']
]
USER_DIR = [ # [artifact, src_path, dest_dir, isRecursive, stringToMatch]
# registry hives
['ntuser', u'/', u'/Registry/', False, u'NTUSER'],
['usrclass', u'/AppData/Local/Microsoft/Windows/', u'/Registry/', False, u'UsrClass'],
['usrclass_xp', u'/Local Settings/Application Data/Microsoft/Windows/', u'/Registry/', False, u'UsrClass'],
# mru
['iehist', u'/AppData/Local/Microsoft/Windows/WebCache', u'/MRU/Files/iehist/', False, None],
['iehist_xp', u'/Local Settings/History/History.IE5', u'/MRU/Files/iehist/', True, None],
['jmp', LOC_RECENT + u'AutomaticDestinations', u'/MRU/Files/jmp/', False, None],
['jmp', LOC_RECENT + u'CustomDestinations', u'/MRU/Files/jmp/', False, None],
['lnk', LOC_RECENT, u'MRU/Files/lnk', False, None],
['lnk_xp', u'/Recent/', u'MRU/Files/lnk', False, None],
['thumbcache', u'/AppData/Local/Microsoft/Windows/Explorer', u'/MRU/thumbcache/', False, u'thumbcache_'],
['timeline', u'/AppData/Local/ConnectedDevicesPlatform', u'/MRU/timeline/', True, None],
# others
['certutil', u'/AppData/LocalLow/Microsoft/CryptnetUrlCache/MetaData', u'/Misc/certutil/', False, None],
['rdpcache', u'/AppData/Local/Microsoft/Terminal Server Client/Cache', u'/Misc/rdpcache/', False, None],
['rdpcache_xp', u'/Local Settings/Application Data/Microsoft/Terminal Server Client/Cache', u'/Misc/rdpcache/',
False, None]
]
FILE_ADS = [ # [artifact, src_path, dest_dir, ads_name]
# file system
['usnjrnl', u'/$Extend/$UsnJrnl', u'/Filesystem/', u'$J']
]
|
"""The code template to supply to the front end. This is what the user will
be asked to complete and submit for grading.
Do not include any imports.
This is not a REPL environment so include explicit 'print' statements
for any outputs you want to be displayed back to the user.
Use triple single quotes to enclose the formatted code block.
"""
challenge_code = '''dev = qml.device('default.qubit', wires=3)
@qml.qnode(dev)
def make_basis_state(basis_id):
"""Produce the 3-qubit basis state corresponding to |basis_id>.
Note that the system starts in |000>.
Args:
basis_id (int): An integer value identifying the basis state to construct.
Returns:
array[complex]: The computational basis state |basis_id>.
"""
##################
# YOUR CODE HERE #
##################
# CREATE THE BASIS STATE
return qml.state()
basis_id = 3
print(f"Output state = {make_basis_state(basis_id)}")
'''
|
"""escreva um programa que pergunte o salário de funcionário e calcule o valor do aumento
para salários superiores a R$ 1250,00, 10% de aumento
para salários menores ou iguais a R$ 1250,00, aumento de 15%"""
s = float(input('Informe o salário: '))
if s > 1250:
s = s * (10/100+1)
else:
s = s * (15/100+1)
print('Seu salário foi reajustado para {} '.format(s))
|
# trabajando con sobre carga de operadores para una clase
class Persona:
def __init__(self, nombre, edad):
self.nombre = nombre
self.edad = edad
def __str__(self):
return "{} tiene {} años".format(self.nombre, self.edad)
def __add__(self, other):
return "Al unir los nombres se tiene: {} {}".format(self.nombre, other.nombre)
def __sub__(self, other):
return "Al restar las edades se tiene: {}".format(self.edad - other.edad)
persona1 = Persona("Juan", 20)
persona2 = Persona("Pedro", 30)
print(persona1 + persona2)
print(persona1 - persona2) |
#coding=utf-8
#熟食店P113 2017.4.17
sandwichOrders = ['fruitSandwich','baconicSandwich','beefSandwich','pastrmiSandwich']
finishedSandwiches = []
print("Now we have")
print(sandwichOrders)
print("\nOpps!The pastramiSandwich is sold out!")
for sandwichOrder in sandwichOrders:
if sandwichOrder == 'pastrmiSandwich':
sandwichOrders.remove(sandwichOrder)
while sandwichOrders:
sandwich = sandwichOrders.pop()
print("I made your "+sandwich+'\n')
finishedSandwiches.append(sandwich)
print(finishedSandwiches)
|
class Config():
appId = None
apiKey = None
domain = None
def __init__(self, appId, apiKey, domain):
self.appId = appId
self.apiKey = apiKey
self.domain = domain |
"""
A utility for summing up two numbers.
"""
def add_two_numbers(first, second):
"""Adds up both numbers and return the sum.
Input values must be numbers."""
if not isinstance(first, (int, float)) or not (isinstance(second, (int, float))):
raise ValueError("Inputs must be numbers.")
return first + second
|
for i in range(int(input())):
array_length = int(input())
array = map(int, input().split())
s = sum(array)
if s < array_length:
print(1)
else:
print(s - array_length)
|
def _get_value(obj, key):
list_end = key.find("]")
is_list = list_end > 0
if is_list:
list_index = int(key[list_end - 1])
return obj[list_index]
return obj[key]
def find(obj, path):
try:
# Base case
if len(path) == 0:
return obj
key = str(path[0])
rest = path[1:]
nested = _get_value(obj, key)
return find(nested, rest)
except IndexError:
raise IndexError
except KeyError:
raise KeyError
except TypeError:
raise TypeError
|
GRAPH = {
"A":["B","D","E"],
"B":["A","C","D"],
"C":["B","G"],
"D":["A","B","E","F"],
"E":["A","D"],
"F":["D"],
"G":["C"]
}
visited_list = [] # an empty list of visited nodes
def dfs(graph, current_vertex, visited):
visited.append(current_vertex)
for vertex in graph[current_vertex]: # check neighbours
if vertex not in visited:
dfs(graph, vertex, visited) # recursive call
# stack will store return address, parameters
# and local variables
return visited
# main program
traversal = dfs(GRAPH, 'A', visited_list)
print('Nodes visited in this order:', traversal)
|
class Solution:
def minCostClimbingStairs(self, cost):
dp = [0] * (len(cost) + 1)
for i in range(2, len(dp)):
dp[i] = min(dp[i - 2] + cost[i - 2], dp[i - 1] + cost[i - 1])
return dp[-1]
s = Solution()
print(s.minCostClimbingStairs([10, 15, 20]))
print(s.minCostClimbingStairs([1, 100, 1, 1, 1, 100, 1, 1, 100, 1]))
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
# Version Number
# ------------------------------------------------------------------------------
major_version = "1"
minor_version = "2"
patch_version = "0"
# ------------------------------------------------------------------------------
# Help String
# ------------------------------------------------------------------------------
HELP = """====================================================
ufolint
Copyright 2019 Source Foundry Authors
MIT License
Source: https://github.com/source-foundry/ufolint
====================================================
ufolint is a UFO source file linter.
Usage:
$ ufolint [UFO path 1] ([UFO path2] [UFO path ...])
The application returns exit status code 0 if all tests are successful and
exit status code 1 if any failures are detected.
See documentation on the source repository (link above) for testing details.
"""
# ------------------------------------------------------------------------------
# Version String
# ------------------------------------------------------------------------------
VERSION = "ufolint v" + major_version + "." + minor_version + "." + patch_version
# ------------------------------------------------------------------------------
# Usage String
# ------------------------------------------------------------------------------
USAGE = "ufolint [UFO path 1] ([UFO path2] [UFO path ...])"
|
'''
@Author : Jin Yuhan
@Date : 2020-05-02 22:01:34
@LastEditors : Jin Yuhan
@LastEditTime : 2020-05-02 23:12:38
@Description : 字幕
'''
class Captions:
""" 用于保存字幕 """
def __init__(self, *captions):
self.captions = captions
self.index = -1
def get(self, count=1, move_index=True, single_value_if_possible=True):
""" 获取接下来的count个字幕 """
if count <= 0:
raise IndexError('count必须是正整数')
if self.index + count >= len(self.captions):
raise IndexError('字幕已经到达尽头o(╥﹏╥)o')
self.index += count
result = self.captions[self.index] if count ==1 and single_value_if_possible \
else self.captions[self.index - count + 1 : self.index + 1]
# 这里懒得改了,后加的
if not move_index:
self.index -= count
return result
def get_remaining_count(self) -> int:
return len(self.captions) - self.index - 1
def reset(self):
self.index = -1
def __len__(self):
return len(self.captions)
def __getitem__(self, index):
return self.captions[index]
def __setitem__(self, index, value):
self.captions[index] = value |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org)
# See "Python, Petit guide à l'usage du développeur agile", Tarek Ziadé, Ed. Dunod (2007)
class Observable(object):
"""The subject."""
def __init__(self):
raise NotImplementedError
def register(self, observer):
self.observers.add(observer)
def unregister(self, observer):
try:
self.observers.remove(observer)
except KeyError:
pass
def notify(self):
for observer in self.observers:
observer.update(self)
class ConcreteObservable(Observable):
"""The concrete subject."""
def __init__(self):
self.observers = set()
self.state = 0
def getState(self):
return self.state
def setState(self, state):
self.state = state
self.notify()
class Observer(object):
def update(self, observable):
raise NotImplementedError
class ConcreteObserver(Observer):
def update(self, observable):
print(id(self), observable.getState())
def main():
observable = ConcreteObservable()
observer1 = ConcreteObserver()
observer2 = ConcreteObserver()
observable.setState(0)
observable.register(observer1)
observable.setState(1)
observable.register(observer2)
observable.setState(2)
observable.unregister(observer1)
observable.setState(3)
observable.unregister(observer2)
observable.setState(4)
if __name__ == '__main__':
main()
|
def save_transcriptions(path, transcriptions):
with open(path, 'w') as f:
for key in transcriptions:
f.write('{} {}\n'.format(key, transcriptions[key]))
def load_transcriptions(path):
transcriptions = {}
with open(path, "r") as f:
for line_no, line in enumerate(f):
if len(line) == 0:
continue
try:
image_id, transcription = parse_transcription_line(line)
except ValueError:
raise ValueError('Failed to parse line {} of file {}'.format(line_no, path))
transcriptions[image_id] = transcription
return transcriptions
def parse_transcription_line(line):
image_id, transcription = line.split(" ", maxsplit=1)
if transcription[-1] == '\n':
transcription = transcription[:-1]
return image_id, transcription
|
class Halo_Status_Class():
def __init__(self):
# Halos information exist?
self.HalosDataExist = False
# AGNs information exist?
self.AGNsDataExist = False
# Solved for Lx, T, flux?
self.LxTxSolved = False
# Trasformed into XCat prefered coordinate?
self.XCatPreferedCoordinate = False
def update(self, Halo_data):
self.HalosDataExist = True
self.AGNsDataExist = False
self.LxTxSolved = False
self.XCatPreferedCoordinate = False
|
def load(info):
info['config']['/jquery'] = {
'tools.staticdir.on': 'True',
'tools.staticdir.dir': 'clients/jquery'
}
|
class Foo(object):
def __init__(self):
with open('b.py'):
self.scope = "a"
pass
def get_scope(self):
return self.scope |
def shell(arr):
gap = len(arr) // 2
while gap >= 1:
for i in xrange(len(arr)):
if i + gap > len(arr) - 1:
break
insertion_sort_gap(arr, i, gap)
gap //= 2
def insertion_sort_gap(arr, start, gap):
pos = start + gap
while pos - gap >= 0 and arr[pos] < arr[pos - gap]:
arr[pos], arr[pos - gap] = arr[pos - gap], arr[pos]
pos -= gap
if __name__ == '__main__':
arrs = [
[4, 3, 3, 7, 6, -1, 10, 3, 8, 4],
[10, 11, 9, 8, 13, 21],
[99, 87, 76, 65, 54, 43, 32, 21, 10, -1],
]
for arr in arrs:
print("unsorted: {}".format(arr))
shell(arr)
print("sorted: {}".format(arr))
|
# This program says hello and asks for my name and show my age.
print('Hello, World!')
print('What is your name?') #ask for name
myName = input()
print('It is good to meet you ' + myName)
print('The length of your name is :')
print(len(myName))
print('Please tell your age:') # ask for age
myAge = input()
print('You will be ' + str(int(myAge) + 1)+ ' in a year.') |
# -*- coding: utf-8 -*-
"""
_app_name_.manage.stores
~~~~~~~~~~~~~~~~~~~~~~
store management commands
"""
|
class Message:
snkrs_pass_message = "<!channel> 【SNKRS PASS Flying Get!!!】" + "\n"
snkrs_pass_message += "SNKRS PASSが発行されました!急げ!!:snkrspass:" + "\n"
snkrs_pass_message += "{}" + "\n"
@classmethod
def make_message(cls, url):
return cls.snkrs_pass_message.format(url)
|
load("//:third_party/org_sonatype_sisu.bzl", org_sonatype_sisu_deps = "dependencies")
load("//:third_party/org_eclipse_sisu.bzl", org_eclipse_sisu_deps = "dependencies")
load("//:third_party/org_eclipse_aether.bzl", org_eclipse_aether_deps = "dependencies")
load("//:third_party/org_checkerframework.bzl", org_checkerframework_deps = "dependencies")
load("//:third_party/javax_enterprise.bzl", javax_enterprise_deps = "dependencies")
load("//:third_party/com_google_j2objc.bzl", com_google_j2objc_deps = "dependencies")
load("//:third_party/com_google_errorprone.bzl", com_google_errorprone_deps = "dependencies")
load("//:third_party/aopalliance.bzl", aopalliance_deps = "dependencies")
load("//:third_party/javax_annotation.bzl", javax_annotation_deps = "dependencies")
load("//:third_party/org_xmlunit.bzl", org_xmlunit_deps = "dependencies")
load("//:third_party/org_eclipse_jetty.bzl", org_eclipse_jetty_deps = "dependencies")
load("//:third_party/org_eclipse_jetty_http2.bzl", org_eclipse_jetty_http2_deps = "dependencies")
load("//:third_party/org_apache_httpcomponents_core5.bzl", org_apache_httpcomponents_core5_deps = "dependencies")
load("//:third_party/org_apache_httpcomponents_client5.bzl", org_apache_httpcomponents_client5_deps = "dependencies")
load("//:third_party/net_sf_jopt_simple.bzl", net_sf_jopt_simple_deps = "dependencies")
load("//:third_party/net_minidev.bzl", net_minidev_deps = "dependencies")
load("//:third_party/net_javacrumbs_json_unit.bzl", net_javacrumbs_json_unit_deps = "dependencies")
load("//:third_party/jakarta_xml_bind.bzl", jakarta_xml_bind_deps = "dependencies")
load("//:third_party/jakarta_activation.bzl", jakarta_activation_deps = "dependencies")
load("//:third_party/commons_fileupload.bzl", commons_fileupload_deps = "dependencies")
load("//:third_party/com_jayway_jsonpath.bzl", com_jayway_jsonpath_deps = "dependencies")
load("//:third_party/com_github_jknack.bzl", com_github_jknack_deps = "dependencies")
load("//:third_party/javax_servlet.bzl", javax_servlet_deps = "dependencies")
load("//:third_party/xml_apis.bzl", xml_apis_deps = "dependencies")
load("//:third_party/oro.bzl", oro_deps = "dependencies")
load("//:third_party/org_typelevel.bzl", org_typelevel_deps = "dependencies")
load("//:third_party/org_tukaani.bzl", org_tukaani_deps = "dependencies")
load("//:third_party/org_specs2.bzl", org_specs2_deps = "dependencies")
load("//:third_party/org_sonatype_plexus.bzl", org_sonatype_plexus_deps = "dependencies")
load("//:third_party/org_slf4j.bzl", org_slf4j_deps = "dependencies")
load("//:third_party/org_scalaj.bzl", org_scalaj_deps = "dependencies")
load("//:third_party/org_scala_sbt.bzl", org_scala_sbt_deps = "dependencies")
load("//:third_party/org_scala_lang.bzl", org_scala_lang_deps = "dependencies")
load("//:third_party/org_scala_lang_modules.bzl", org_scala_lang_modules_deps = "dependencies")
load("//:third_party/org_reflections.bzl", org_reflections_deps = "dependencies")
load("//:third_party/org_reactivestreams.bzl", org_reactivestreams_deps = "dependencies")
load("//:third_party/org_portable_scala.bzl", org_portable_scala_deps = "dependencies")
load("//:third_party/org_ow2_asm.bzl", org_ow2_asm_deps = "dependencies")
load("//:third_party/org_objenesis.bzl", org_objenesis_deps = "dependencies")
load("//:third_party/org_mockito.bzl", org_mockito_deps = "dependencies")
load("//:third_party/org_joda.bzl", org_joda_deps = "dependencies")
load("//:third_party/org_javassist.bzl", org_javassist_deps = "dependencies")
load("//:third_party/org_iq80_snappy.bzl", org_iq80_snappy_deps = "dependencies")
load("//:third_party/org_hamcrest.bzl", org_hamcrest_deps = "dependencies")
load("//:third_party/org_fusesource_jansi.bzl", org_fusesource_jansi_deps = "dependencies")
load("//:third_party/org_eclipse_jgit.bzl", org_eclipse_jgit_deps = "dependencies")
load("//:third_party/org_codehaus_plexus.bzl", org_codehaus_plexus_deps = "dependencies")
load("//:third_party/org_codehaus_mojo.bzl", org_codehaus_mojo_deps = "dependencies")
load("//:third_party/org_apache_velocity.bzl", org_apache_velocity_deps = "dependencies")
load("//:third_party/org_apache_maven_wagon.bzl", org_apache_maven_wagon_deps = "dependencies")
load("//:third_party/org_apache_maven_shared.bzl", org_apache_maven_shared_deps = "dependencies")
load("//:third_party/org_apache_maven_resolver.bzl", org_apache_maven_resolver_deps = "dependencies")
load("//:third_party/org_apache_maven_reporting.bzl", org_apache_maven_reporting_deps = "dependencies")
load("//:third_party/org_apache_maven.bzl", org_apache_maven_deps = "dependencies")
load("//:third_party/org_apache_maven_doxia.bzl", org_apache_maven_doxia_deps = "dependencies")
load("//:third_party/org_apache_maven_archetype.bzl", org_apache_maven_archetype_deps = "dependencies")
load("//:third_party/org_apache_jackrabbit.bzl", org_apache_jackrabbit_deps = "dependencies")
load("//:third_party/org_apache_httpcomponents.bzl", org_apache_httpcomponents_deps = "dependencies")
load("//:third_party/org_apache_commons.bzl", org_apache_commons_deps = "dependencies")
load("//:third_party/net_sourceforge_jchardet.bzl", net_sourceforge_jchardet_deps = "dependencies")
load("//:third_party/net_bytebuddy.bzl", net_bytebuddy_deps = "dependencies")
load("//:third_party/nekohtml.bzl", nekohtml_deps = "dependencies")
load("//:third_party/junit.bzl", junit_deps = "dependencies")
load("//:third_party/joda_time.bzl", joda_time_deps = "dependencies")
load("//:third_party/jdom.bzl", jdom_deps = "dependencies")
load("//:third_party/javax_inject.bzl", javax_inject_deps = "dependencies")
load("//:third_party/io_github_alexarchambault_windows_ansi.bzl", io_github_alexarchambault_windows_ansi_deps = "dependencies")
load("//:third_party/io_github_alexarchambault.bzl", io_github_alexarchambault_deps = "dependencies")
load("//:third_party/io_get_coursier.bzl", io_get_coursier_deps = "dependencies")
load("//:third_party/io_argonaut.bzl", io_argonaut_deps = "dependencies")
load("//:third_party/dom4j.bzl", dom4j_deps = "dependencies")
load("//:third_party/commons_lang.bzl", commons_lang_deps = "dependencies")
load("//:third_party/commons_io.bzl", commons_io_deps = "dependencies")
load("//:third_party/commons_httpclient.bzl", commons_httpclient_deps = "dependencies")
load("//:third_party/commons_collections.bzl", commons_collections_deps = "dependencies")
load("//:third_party/commons_codec.bzl", commons_codec_deps = "dependencies")
load("//:third_party/commons_cli.bzl", commons_cli_deps = "dependencies")
load("//:third_party/com_wix.bzl", com_wix_deps = "dependencies")
load("//:third_party/com_typesafe.bzl", com_typesafe_deps = "dependencies")
load("//:third_party/com_typesafe_akka.bzl", com_typesafe_akka_deps = "dependencies")
load("//:third_party/com_thoughtworks_paranamer.bzl", com_thoughtworks_paranamer_deps = "dependencies")
load("//:third_party/com_jcraft.bzl", com_jcraft_deps = "dependencies")
load("//:third_party/com_googlecode_javaewah.bzl", com_googlecode_javaewah_deps = "dependencies")
load("//:third_party/com_google_guava.bzl", com_google_guava_deps = "dependencies")
load("//:third_party/com_google_code_findbugs.bzl", com_google_code_findbugs_deps = "dependencies")
load("//:third_party/com_github_tomakehurst.bzl", com_github_tomakehurst_deps = "dependencies")
load("//:third_party/com_github_scopt.bzl", com_github_scopt_deps = "dependencies")
load("//:third_party/com_github_alexarchambault.bzl", com_github_alexarchambault_deps = "dependencies")
load("//:third_party/com_fasterxml_jackson_module.bzl", com_fasterxml_jackson_module_deps = "dependencies")
load("//:third_party/com_fasterxml_jackson_datatype.bzl", com_fasterxml_jackson_datatype_deps = "dependencies")
load("//:third_party/com_fasterxml_jackson_core.bzl", com_fasterxml_jackson_core_deps = "dependencies")
load("//:third_party/com_chuusai.bzl", com_chuusai_deps = "dependencies")
load("//:third_party/classworlds.bzl", classworlds_deps = "dependencies")
load("//:third_party/ch_qos_logback.bzl", ch_qos_logback_deps = "dependencies")
load("//:third_party/backport_util_concurrent.bzl", backport_util_concurrent_deps = "dependencies")
def managed_third_party_dependencies():
backport_util_concurrent_deps()
ch_qos_logback_deps()
classworlds_deps()
com_chuusai_deps()
com_fasterxml_jackson_core_deps()
com_fasterxml_jackson_datatype_deps()
com_fasterxml_jackson_module_deps()
com_github_alexarchambault_deps()
com_github_scopt_deps()
com_github_tomakehurst_deps()
com_google_code_findbugs_deps()
com_google_guava_deps()
com_googlecode_javaewah_deps()
com_jcraft_deps()
com_thoughtworks_paranamer_deps()
com_typesafe_akka_deps()
com_typesafe_deps()
com_wix_deps()
commons_cli_deps()
commons_codec_deps()
commons_collections_deps()
commons_httpclient_deps()
commons_io_deps()
commons_lang_deps()
dom4j_deps()
io_argonaut_deps()
io_get_coursier_deps()
io_github_alexarchambault_deps()
io_github_alexarchambault_windows_ansi_deps()
javax_inject_deps()
jdom_deps()
joda_time_deps()
junit_deps()
nekohtml_deps()
net_bytebuddy_deps()
net_sourceforge_jchardet_deps()
org_apache_commons_deps()
org_apache_httpcomponents_deps()
org_apache_jackrabbit_deps()
org_apache_maven_archetype_deps()
org_apache_maven_doxia_deps()
org_apache_maven_deps()
org_apache_maven_reporting_deps()
org_apache_maven_resolver_deps()
org_apache_maven_shared_deps()
org_apache_maven_wagon_deps()
org_apache_velocity_deps()
org_codehaus_mojo_deps()
org_codehaus_plexus_deps()
org_eclipse_jgit_deps()
org_fusesource_jansi_deps()
org_hamcrest_deps()
org_iq80_snappy_deps()
org_javassist_deps()
org_joda_deps()
org_mockito_deps()
org_objenesis_deps()
org_ow2_asm_deps()
org_portable_scala_deps()
org_reactivestreams_deps()
org_reflections_deps()
org_scala_lang_modules_deps()
org_scala_lang_deps()
org_scala_sbt_deps()
org_scalaj_deps()
org_slf4j_deps()
org_sonatype_plexus_deps()
org_specs2_deps()
org_tukaani_deps()
org_typelevel_deps()
oro_deps()
xml_apis_deps()
javax_servlet_deps()
com_github_jknack_deps()
com_jayway_jsonpath_deps()
commons_fileupload_deps()
jakarta_activation_deps()
jakarta_xml_bind_deps()
net_javacrumbs_json_unit_deps()
net_minidev_deps()
net_sf_jopt_simple_deps()
org_apache_httpcomponents_client5_deps()
org_apache_httpcomponents_core5_deps()
org_eclipse_jetty_http2_deps()
org_eclipse_jetty_deps()
org_xmlunit_deps()
javax_annotation_deps()
aopalliance_deps()
com_google_errorprone_deps()
com_google_j2objc_deps()
javax_enterprise_deps()
org_checkerframework_deps()
org_eclipse_aether_deps()
org_eclipse_sisu_deps()
org_sonatype_sisu_deps()
|
#-*-coding:utf-8-*-
class Solution(object):
def myPow(self, x, n):
"""
:type x: float
:type n: int
:rtype: float
"""
if n == 0:
return 1
if n < 0:
n = -n
x = 1.0 / x
return self.myPow(x * x, n/2) if n % 2 == 0 else self.myPow(x * x, n/2) * x
|
"""
1. Clarification
2. Possible solutions
- Binary Search
3. Coding
4. Tests
"""
# T=O(nlg(sigma(w))), S=O(1)
class Solution:
def shipWithinDays(self, weights: List[int], D: int) -> int:
if not weights or D < 1: return 0
left, right = max(weights), sum(weights)
while left < right:
mid = (left + right) // 2
need, cur = 1, 0
for weight in weights:
if cur + weight > mid:
need += 1
cur = 0
cur += weight
if need <= D:
right = mid
else:
left = mid + 1
return left
|
def getFuel(mass):
return int(mass/3)-2
def getTotalFuel_1(values):
total = 0
for v in values:
total += getFuel(v)
return total
def getTotalFuel_2(values):
total = 0
for v in values:
while(True):
v = getFuel(v)
if v < 0:
break
total += v
return total
values = []
with open('2019/input1.txt') as f:
for l in f:
values.append(int(l))
print(getTotalFuel_1(values))
print(getTotalFuel_2(values))
|
# -*- coding: utf-8 -*-
{
'name': "Merced Report",
'summary': """Informe de Presupuesto""",
'description': """
Este informe imprime el nombre del usuario logueado, el cual crea el informe del presupuesto
""",
'author': "Soluciones4G",
'website': "http://www.soluciones4g.com",
# Categories can be used to filter modules in modules listing
# for the full list
'category': 'Sale',
'version': '1',
# any module necessary for this one to work correctly
'depends': ['sale'],
# always loaded
'data': [
'report/informe_view.xml',
],
'intallable': True,
'auto_install': False,
} |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftIGUALDADDESIGUALDADleftMAYORMENORMAYORIGUALMENORIGUALleftSUMARESTAleftMULTIPLICACIONDIVISIONleftPAR_ABREPAR_CIERRALLAVE_ABRELLAVE_CIERRACADENA DECIMAL DESIGUALDAD DIVISION ELSE ENTERO ID IF IGUALDAD IMPRIMIR LLAVE_ABRE LLAVE_CIERRA MAYOR MAYORIGUAL MENOR MENORIGUAL MULTIPLICACION PAR_ABRE PAR_CIERRA PUNTOCOMA RESTA SUMA WHILEinit : instruccionesinstrucciones : instrucciones instruccioninstrucciones : instruccion instruccion : imprimir_\n | if_statement\n | while_statementexpresion_ : expresion_ SUMA expresion_\n | expresion_ RESTA expresion_\n | expresion_ MULTIPLICACION expresion_\n | expresion_ DIVISION expresion_\n | expresion_ IGUALDAD expresion_\n | expresion_ DESIGUALDAD expresion_\n | expresion_ MAYOR expresion_\n | expresion_ MENOR expresion_\n | expresion_ MAYORIGUAL expresion_\n | expresion_ MENORIGUAL expresion_\n | expif_statement : IF PAR_ABRE expresion_ PAR_CIERRA statement else_statementelse_statement : ELSE statement\n | ELSE if_statement\n | while_statement : WHILE PAR_ABRE expresion_ PAR_CIERRA statementstatement : LLAVE_ABRE instrucciones LLAVE_CIERRA\n | LLAVE_ABRE LLAVE_CIERRAimprimir_ : IMPRIMIR PAR_ABRE expresion_ PAR_CIERRA PUNTOCOMAexp : primitivoprimitivo : ENTEROprimitivo : DECIMALprimitivo : CADENAprimitivo : varsvars : ID'
_lr_action_items = {'IMPRIMIR':([0,2,3,4,5,6,10,37,48,49,50,51,53,54,55,56,57,],[7,7,-3,-4,-5,-6,-2,-25,-21,7,-22,-18,7,-24,-19,-20,-23,]),'IF':([0,2,3,4,5,6,10,37,48,49,50,51,52,53,54,55,56,57,],[8,8,-3,-4,-5,-6,-2,-25,-21,8,-22,-18,8,8,-24,-19,-20,-23,]),'WHILE':([0,2,3,4,5,6,10,37,48,49,50,51,53,54,55,56,57,],[9,9,-3,-4,-5,-6,-2,-25,-21,9,-22,-18,9,-24,-19,-20,-23,]),'$end':([1,2,3,4,5,6,10,37,48,50,51,54,55,56,57,],[0,-1,-3,-4,-5,-6,-2,-25,-21,-22,-18,-24,-19,-20,-23,]),'LLAVE_CIERRA':([3,4,5,6,10,37,48,49,50,51,53,54,55,56,57,],[-3,-4,-5,-6,-2,-25,-21,54,-22,-18,57,-24,-19,-20,-23,]),'PAR_ABRE':([7,8,9,],[11,12,13,]),'ENTERO':([11,12,13,25,26,27,28,29,30,31,32,33,34,],[17,17,17,17,17,17,17,17,17,17,17,17,17,]),'DECIMAL':([11,12,13,25,26,27,28,29,30,31,32,33,34,],[18,18,18,18,18,18,18,18,18,18,18,18,18,]),'CADENA':([11,12,13,25,26,27,28,29,30,31,32,33,34,],[19,19,19,19,19,19,19,19,19,19,19,19,19,]),'ID':([11,12,13,25,26,27,28,29,30,31,32,33,34,],[21,21,21,21,21,21,21,21,21,21,21,21,21,]),'PAR_CIERRA':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[24,-17,-26,-27,-28,-29,-30,-31,35,36,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,]),'SUMA':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[25,-17,-26,-27,-28,-29,-30,-31,25,25,-7,-8,-9,-10,25,25,25,25,25,25,]),'RESTA':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[26,-17,-26,-27,-28,-29,-30,-31,26,26,-7,-8,-9,-10,26,26,26,26,26,26,]),'MULTIPLICACION':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[27,-17,-26,-27,-28,-29,-30,-31,27,27,27,27,-9,-10,27,27,27,27,27,27,]),'DIVISION':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[28,-17,-26,-27,-28,-29,-30,-31,28,28,28,28,-9,-10,28,28,28,28,28,28,]),'IGUALDAD':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[29,-17,-26,-27,-28,-29,-30,-31,29,29,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,]),'DESIGUALDAD':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[30,-17,-26,-27,-28,-29,-30,-31,30,30,-7,-8,-9,-10,-11,-12,-13,-14,-15,-16,]),'MAYOR':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[31,-17,-26,-27,-28,-29,-30,-31,31,31,-7,-8,-9,-10,31,31,-13,-14,-15,-16,]),'MENOR':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[32,-17,-26,-27,-28,-29,-30,-31,32,32,-7,-8,-9,-10,32,32,-13,-14,-15,-16,]),'MAYORIGUAL':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[33,-17,-26,-27,-28,-29,-30,-31,33,33,-7,-8,-9,-10,33,33,-13,-14,-15,-16,]),'MENORIGUAL':([14,15,16,17,18,19,20,21,22,23,38,39,40,41,42,43,44,45,46,47,],[34,-17,-26,-27,-28,-29,-30,-31,34,34,-7,-8,-9,-10,34,34,-13,-14,-15,-16,]),'PUNTOCOMA':([24,],[37,]),'LLAVE_ABRE':([35,36,52,],[49,49,49,]),'ELSE':([48,54,57,],[52,-24,-23,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'init':([0,],[1,]),'instrucciones':([0,49,],[2,53,]),'instruccion':([0,2,49,53,],[3,10,3,10,]),'imprimir_':([0,2,49,53,],[4,4,4,4,]),'if_statement':([0,2,49,52,53,],[5,5,5,56,5,]),'while_statement':([0,2,49,53,],[6,6,6,6,]),'expresion_':([11,12,13,25,26,27,28,29,30,31,32,33,34,],[14,22,23,38,39,40,41,42,43,44,45,46,47,]),'exp':([11,12,13,25,26,27,28,29,30,31,32,33,34,],[15,15,15,15,15,15,15,15,15,15,15,15,15,]),'primitivo':([11,12,13,25,26,27,28,29,30,31,32,33,34,],[16,16,16,16,16,16,16,16,16,16,16,16,16,]),'vars':([11,12,13,25,26,27,28,29,30,31,32,33,34,],[20,20,20,20,20,20,20,20,20,20,20,20,20,]),'statement':([35,36,52,],[48,50,55,]),'else_statement':([48,],[51,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> init","S'",1,None,None,None),
('init -> instrucciones','init',1,'p_init','execute.py',125),
('instrucciones -> instrucciones instruccion','instrucciones',2,'p_instrucciones_lista','execute.py',129),
('instrucciones -> instruccion','instrucciones',1,'p_instrucciones_instruccion','execute.py',134),
('instruccion -> imprimir_','instruccion',1,'p_instruccion','execute.py',138),
('instruccion -> if_statement','instruccion',1,'p_instruccion','execute.py',139),
('instruccion -> while_statement','instruccion',1,'p_instruccion','execute.py',140),
('expresion_ -> expresion_ SUMA expresion_','expresion_',3,'p_expresion_','execute.py',144),
('expresion_ -> expresion_ RESTA expresion_','expresion_',3,'p_expresion_','execute.py',145),
('expresion_ -> expresion_ MULTIPLICACION expresion_','expresion_',3,'p_expresion_','execute.py',146),
('expresion_ -> expresion_ DIVISION expresion_','expresion_',3,'p_expresion_','execute.py',147),
('expresion_ -> expresion_ IGUALDAD expresion_','expresion_',3,'p_expresion_','execute.py',148),
('expresion_ -> expresion_ DESIGUALDAD expresion_','expresion_',3,'p_expresion_','execute.py',149),
('expresion_ -> expresion_ MAYOR expresion_','expresion_',3,'p_expresion_','execute.py',150),
('expresion_ -> expresion_ MENOR expresion_','expresion_',3,'p_expresion_','execute.py',151),
('expresion_ -> expresion_ MAYORIGUAL expresion_','expresion_',3,'p_expresion_','execute.py',152),
('expresion_ -> expresion_ MENORIGUAL expresion_','expresion_',3,'p_expresion_','execute.py',153),
('expresion_ -> exp','expresion_',1,'p_expresion_','execute.py',154),
('if_statement -> IF PAR_ABRE expresion_ PAR_CIERRA statement else_statement','if_statement',6,'p_if_instr','execute.py',170),
('else_statement -> ELSE statement','else_statement',2,'p_else_instr','execute.py',174),
('else_statement -> ELSE if_statement','else_statement',2,'p_else_instr','execute.py',175),
('else_statement -> <empty>','else_statement',0,'p_else_instr','execute.py',176),
('while_statement -> WHILE PAR_ABRE expresion_ PAR_CIERRA statement','while_statement',5,'p_while_instr','execute.py',184),
('statement -> LLAVE_ABRE instrucciones LLAVE_CIERRA','statement',3,'p_statement','execute.py',188),
('statement -> LLAVE_ABRE LLAVE_CIERRA','statement',2,'p_statement','execute.py',189),
('imprimir_ -> IMPRIMIR PAR_ABRE expresion_ PAR_CIERRA PUNTOCOMA','imprimir_',5,'p_imprimir_instr','execute.py',194),
('exp -> primitivo','exp',1,'p_exp_primitivo','execute.py',198),
('primitivo -> ENTERO','primitivo',1,'p_exp_entero','execute.py',202),
('primitivo -> DECIMAL','primitivo',1,'p_exp_decimal','execute.py',207),
('primitivo -> CADENA','primitivo',1,'p_exp_cadena','execute.py',211),
('primitivo -> vars','primitivo',1,'p_exp_variables','execute.py',215),
('vars -> ID','vars',1,'p_exp_id','execute.py',219),
]
|
def calculate(expr: str) -> int:
"""Evaluate 'expr', which contains only non-negative integers,
{+,-,*,/} operators and empty spaces."""
plusOrMinus = {'+': lambda x, y: x + y ,
'-': lambda x, y: x - y}
mulOrDiv = {'*': lambda x, y: x * y ,
'/': lambda x, y: x // y}
stack = []
operators = []
number = 0
for char in expr:
if char.strip() == '':
# Skip whitespace.
continue
if char.isdigit():
# Add digit to current number.
number = number * 10 + int(char)
continue
stack.append(number)
number = 0
if operators and operators[-1] in mulOrDiv:
# Perform multiplication or division first.
snd = stack.pop()
fst = stack.pop()
operator = operators.pop()
stack.append(mulOrDiv[operator](fst, snd))
operators.append(char)
# The last operand must be a number, so add that to the stack.
# Also perform multiplication or division if it is the last operator.
stack.append(number)
if operators and operators[-1] in mulOrDiv:
snd = stack.pop()
fst = stack.pop()
operator = operators.pop()
stack.append(mulOrDiv[operator](fst, snd))
# The remaining computations are addition or subtraction. Perform these
# in order from left to right.
result = stack[0]
for snd, operator in zip(stack[1:], operators):
result = plusOrMinus[operator](result, snd)
return result |
# Python support inheritance from multiple classes. This part will show you:
# how multiple inheritance works
# how to use super() to call methods inherited from multiple parents
# what complexities derive from multiple inheritance
# how to write a mixin, which is a common use of multiple inheritance
class RightPyramid(Triangle, Square):
def __init__(self, base, slant_height):
self.base = base
self.slant_height = slant_height
def what_am_i(self):
return "Pyramid"
# The Method Resolution Order (MRO) dertermines where Python looks for a method when there is
# hierrachy of classes.
class A:
def __init__(self):
print("A")
super().__init__()
class B(A):
def __init__(self):
print("B")
super().__init__()
class X:
def __init__(self):
print("X")
super().__init__()
class Forward(B, X):
def __init__(self):
print("Forward")
super().__init__()
class Backward(X, B):
def __init__(self):
print("Backward")
super().__init__()
# If you combine the MRO and the **kwargs feature for specifying name-value pairs during
# construction, you can write code that passes parameters to parent classes even if they have
# different name
class Rectangle:
def __init__(self, length, width, **kwargs):
self.length = length
self.width = width
super().__init__(**kwargs)
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
class Square(Rectangle):
def __init__(self, length, **kwargs):
super().__init__(length=length, width=length, **kwargs)
class Triangle:
def __init__(self, base, height, **kwargs):
self.base = base
self.heigth = height
super().__init__(**kwargs)
def tri_area(self):
return 0.5 * self.base * self.length
class RightPyramid(Square, Triangle):
def __init__(self, base, slant_height, *kwargs):
self.base = base
self.slant_height
kwargs["height"] = slant_height
kwargs["length"] = base
super().__init__(base=base, **kwargs)
def area(self):
base_area = super().area()
perimeter = super().perimeter()
return 0.5 * perimeter * self.slant_height + base_area
def area_2(self):
base_area = super().area()
triangle_area = super().tri_area()
return triangle_area * 4 + base_area
# Multiple inheritance can get tricky quickly. A simple use case that is common in the field is to
# write a mixin. A mixin is a class that doesn't care about its position in the hierrachy, but just
# provides one or more convenience methods
class SurfaceMixin:
def surface_area(self):
surface_area = 0
for surface in self.surfaces:
surface_area += surface.area(self)
return surface_area
class Cube(Square, SurfaceMixin):
def __init__(self, length):
super().__init__()
self.surfaces = [Square, Square, Square, Square, Square, Square]
class RightPyramid(Square, Triangle, SurfaceMixin):
def __init__(self, base, slant_height):
self.base = base
self.slant_height = slant_height
self.height = base
self.width = base
self.surfaces = [Square, Triangle, Triangle, Triangle, Triangle]
|
# -*- coding: utf-8 -*-
E = int(input())
N = int(input())
P = float(input())
SALARY = N * P
print("NUMBER = %d" % (E))
print("SALARY = U$ %.2f" % (SALARY)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.