content stringlengths 7 1.05M |
|---|
class Color:
def __init__(self, r, g, b, alpha=255):
self.r = r
self.g = g
self.b = b
self.alpha = alpha
if self.r < 0 or self.g < 0 or self.b < 0 or self.alpha < 0:
raise ValueError("color values can't be below 0")
if self.r > 255 or self.g > 255 or self.b > 255 or self.alpha > 255:
raise ValueError("color values can't be above 255")
# Get the floating point representation between 0 and 1
def scale_down(self):
return Color(self.r / 255, self.g / 255, self.b / 255, self.alpha / 255) |
def ConverterTempo(tempo, unidade):
if unidade == "m":
return tempo*60
if unidade == "s":
return tempo
def ConverteMetros(quantidade, unidade):
if unidade == "M":
return quantidade*100
if unidade == "m":
return quantidade |
class TokenType(object):
END = ""
ILLEGAL = "ILLEGAL"
# Operators
PLUS = "+"
MINUS = "-"
SLASH = "/"
AT = "@"
# Identifiers
NUMBER = "NUMBER"
MODIFIER = "MODIFIER"
# keywords
NOW = "NOW"
class Token(object):
def __init__(self, tok_type, tok_literal):
self.token_type = tok_type
self.token_literal = tok_literal
|
'''
* (210927) 최소직사각형
* https://programmers.co.kr/learn/courses/30/lessons/86491
'''
def solution(sizes):
width = []
height = []
for item in sizes:
if item[1] > item[0]:
item[0], item[1] = item[1], item[0]
width.append(item[0])
height.append(item[1])
max_width = max(width)
max_height = max(height)
return max_width * max_height |
n = (int(input('Dgite um numero: ')),
int(input('Dgite outro numero: ')),
int(input('Dgite outro numero: ')),
int(input('Dgite outro numero: ')))
print(f'O valor 9 apareu {n.count(9)} vezes' if 9 in n else 'O numero 9 não foi digitado')
print(f'O valor 3 foi digitado na posição {n.index(3) + 1}' if 3 in n else 'O numero 3 não foi digitado')
print('Os valores pares digitados foram', end=' ')
for num in n:
if num % 2 == 0:
print(num, end=' ')
|
def sort(L):
n = len(L)
# Build Heap
for i in range(n-1, -1, -1):
L = heapify(L, i, n)
for i in range(n-1, 0, -1):
L[i], L[0] = L[0], L[i]
n -= 1
heapify(L, 0, n)
return L
def heapify(L, _v, n): # v is index to be passed
v = _v + 1
largest = v
if 2*v <= n:
if L[2*v - 1] > L[v - 1]:
largest = 2*v
if 2*v + 1 <= n:
if L[2*v] > L[largest - 1]:
largest = 2*v + 1
if not largest == v:
L[_v], L[largest - 1] = L[largest - 1], L[_v]
return heapify(L, largest - 1, n)
return L
|
print('DESCUBRA O MAIOR NÚMERO')
num1 = float(input('Digite o primeiro número: '))
num2 = float(input('Digite o segundo número: '))
if num1 > num2 :
print('O primeiro número {} é maior que o segundo número {}'.format(num1, num2))
elif num2 > num1 :
print('O segundo número {} é maior que o primeiro número {}'.format(num2, num1))
else:
print('Os dois números são iguais.') |
####################################################
#
# Components applicable to all types of items
#
####################################################
# what type of item is this entity
# this is primarily used in iterable statements as a filter
class TypeOfItem:
def __init__(self, label=''):
self.label = label
# defines the available actions based on the type of item
class Actionlist:
def __init__(self, action_list=''):
self.actions = action_list
class Name:
def __init__(self, label=''):
self.label = label
class Description:
def __init__(self, label=''):
self.label = label
class ItemGlyph:
def __init__(self, glyph=''):
self.glyph = glyph
class ItemForeColour:
def __init__(self, fg=0):
self.fg = fg
class ItemBackColour:
def __init__(self, bg=0):
self.bg = bg
class ItemDisplayName:
def __init__(self, label=''):
self.label = label
# physical location on the game map
# obviously no location means the item is not on the game map
class Location:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
# what is the item made of
# this might not be used as a game mechanic, but it will at least add some flavour
class Material:
def __init__(self, texture='cloth', component1='', component2='', component3=''):
self.texture = texture
self.component1 = component1
self.component2 = component2
self.component3 = component3
# is this item visible on the game map
# YES means it can be seen by the player and any mobiles (unless they're blind)
# NO means: (1) it's invisible or (2) it's inside a container
class RenderItem:
def __init__(self, istrue=True):
self.is_true = istrue
# what is the quality of this item
# this may be a game mechanic or not but it will at least be flavour
class Quality:
def __init__(self, level='basic'):
self.level = level
####################################################
#
# BAGS
#
####################################################
# how many slots does this bag have
# populated indicates how many different slots contain at least one item
class SlotSize:
def __init__(self, maxsize=26, populated=0):
self.maxsize = maxsize
self.populated = populated
####################################################
#
# WEAPONS
#
####################################################
class Experience:
def __init__(self, current_level=10):
self.current_level = current_level
self.max_level = 10
class WeaponType:
def __init__(self, label=''):
self.label = label
# hallmarks are a way to add a different bonus to an existing weapon
class Hallmarks:
def __init__(self, hallmark_slot_one=0, hallmark_slot_two=0):
self.hallmark_slot_one = hallmark_slot_one
self.hallmark_slot_two = hallmark_slot_two
# can this item be held in the hands
# the true_or_false parameter drives this
class Wielded:
def __init__(self, hands='both', true_or_false=True):
self.hands = hands
self.true_or_false = true_or_false
# which spells are loaded into the weapon
class Spells:
def __init__(self, slot_one=0, slot_two=0, slot_three=0, slot_four=0, slot_five=0):
self.slot_one = slot_one
self.slot_two = slot_two
self.slot_three = slot_three
self.slot_four = slot_four
self.slot_five = slot_five
self.slot_one_disabled = False
self.slot_two_disabled = False
self.slot_three_disabled = False
self.slot_four_disabled = False
self.slot_five_disabled = False
# weapon damage range
class DamageRange:
def __init__(self, ranges=''):
self.ranges = ranges
####################################################
#
# ARMOUR
#
####################################################
# how heavy is this piece of armour
class Weight:
def __init__(self, label=''):
self.label = label
# what is the calculated defense value for this piece of armour
class Defense:
def __init__(self, value=0):
self.value = value
# where on the body can this piece of armour be placed
class ArmourBodyLocation:
def __init__(self, chest=False, head=False, hands=False, feet=False, legs=False):
self.chest = chest
self.head = head
self.hands = hands
self.feet = feet
self.legs = legs
# what bonus does this piece of armour add and to which attribute
class AttributeBonus:
def __init__(self, majorname='', majorbonus=0, minoronename='', minoronebonus=0):
self.major_name = majorname
self.major_bonus = majorbonus
self.minor_one_name = minoronename
self.minor_one_bonus = minoronebonus
# If this piece of armour belongs to an armour set it, the set name will
# be found here
class ArmourSet:
def __init__(self, label='', prefix='', level=0):
self.name = label
self.prefix = prefix
self.level = level
# Is the armour being worn
class ArmourBeingWorn:
def __init__(self, status=False):
self.status = status
# armour spell information
class ArmourSpell:
def __init__(self, entity=0, on_cool_down=False):
self.entity = entity
self.on_cool_down = on_cool_down
####################################################
#
# JEWELLERY
#
####################################################
# this defines the stat(s) the piece of jewellery improves
# the dictionary is in the format:{stat_name, bonus_value}
class JewelleryStatBonus:
def __init__(self, statname='', statbonus=0):
self.stat_name = statname
self.stat_bonus = statbonus
# defines the gemstone embedded in the piece of jewllery
class JewelleryGemstone:
def __init__(self, name=''):
self.name = name
# where on the body can this piece of jewellery be worn
# neck = Amulets, fingers = Rings, ears=Earrings
class JewelleryBodyLocation:
def __init__(self, fingers=False, neck=False, ears=False):
self.fingers = fingers
self.neck = neck
self.ears = ears
# Is the piece of jewellery already equipped
class JewelleryEquipped:
def __init__(self, istrue=False):
self.istrue = istrue
class JewelleryComponents:
def __init__(self, setting='', hook='', activator=''):
self.setting = setting
self.hook = hook
self.activator = activator
class JewellerySpell:
def __init__(self, entity=0, on_cool_down=False):
self.entity = entity
self.on_cool_down = on_cool_down |
def get_ages() -> list[int]:
with open('input.txt') as f:
line, = f.readlines()
return list(map(int, line.split(',')))
def step_day(ages: list[int]):
for i, age in enumerate(ages[:]):
age, *newborn = tick(age)
ages[i] = age
ages.extend(newborn)
def tick(age: int) -> list[int]:
if not age:
return [6, 8]
return [age - 1]
if __name__ == '__main__':
ages: list[int] = get_ages()
for day in range(18):
step_day(ages)
answer = len(ages)
print(f'Answer: {answer}')
|
'''
Given an array of integers A sorted in non-decreasing order,
return an array of the squares of each number, also in sorted non-decreasing order.
Example 1:
Input: [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Example 2:
Input: [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Note:
1 <= A.length <= 10000
-10000 <= A[i] <= 10000
A is sorted in non-decreasing order.
'''
def sortedSquares(A):
for i in range(len(A)):
A[i] = A[i]*A[i]
A.sort()
return A
def sortedSquares2(A):
N = len(A)
# i, j: negative, positive parts
j = 0
while j < N and A[j] < 0:
j += 1
i = j - 1
ans = []
while 0 <= i and j < N:
if A[i]**2 < A[j]**2:
ans.append(A[i]**2)
i -= 1
else:
ans.append(A[j]**2)
j += 1
while i >= 0:
ans.append(A[i]**2)
i -= 1
while j < N:
ans.append(A[j]**2)
j += 1
return ans
|
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
print(tuple1)
print(tuple2)
print(tuple3)
|
class Node:
def __init__(self,data):
self.data = data
self.previous = None
self.next = None
class removeDuplicates:
def __init__(self):
self.head = None
self.tail = None
def remove_duplicates(self):
if (self.head == None):
return
else:
current = self.head
while (current!= None):
index = current.next
while (index != None):
if (current.data == index.data):
temp = index
index.previous.next = index.next
if (index.next != None):
index.next.previous = index.previous
temp = None
index = index.next
current = current.next
|
class Parameter:
def __init__(self, name: str, klass: str, data_member, required=True, array=False):
self._name = name
self._klass = klass
self._data_member = data_member
self._required = required
self._array = array
def __eq__(self, other):
return True if \
self.name == other.name and \
self.json == other.json \
else False
@property
def name(self):
return self._name
@property
def klass(self):
return self._klass
@property
def required(self):
return self._required
@property
def data_member(self):
return self._data_member
@property
def array(self):
return self._array
@required.setter
def required(self, value):
self._required = value
@property
def json(self):
return {
'name': self.name,
'class': self.klass,
'array': self.array,
'data_member': self.data_member.name if self.data_member else None
}
|
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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.
#
# Const Class
# this is a auto generated file generated by Cheetah
# Libre Office Version: 7.3
# Namespace: com.sun.star.view
class DuplexMode(object):
"""
Const Class
These constants specify available duplex modes.
See Also:
`API DuplexMode <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1view_1_1DuplexMode.html>`_
"""
__ooo_ns__: str = 'com.sun.star.view'
__ooo_full_ns__: str = 'com.sun.star.view.DuplexMode'
__ooo_type_name__: str = 'const'
UNKNOWN = 0
"""
specifies an unknown duplex mode.
"""
OFF = 1
"""
specifies that there is no duplex mode enabled
"""
LONGEDGE = 2
"""
specifies a long edge duplex mode
"""
SHORTEDGE = 3
"""
specifies a short edge duplex mode
"""
__all__ = ['DuplexMode']
|
"""Calculation history Class"""
class Calculations:
"""Calculation history Class"""
history = []
@staticmethod
def clear_history():
""" clear the history items"""
Calculations.history.clear()
return True
@staticmethod
def count_history():
""" get the length of history items"""
return len(Calculations.history)
@staticmethod
def get_last_calculation_object():
""" get the last calculation from history"""
return Calculations.history[-1]
@staticmethod
def get_last_calculation_result():
""" get the last calculation from history"""
return Calculations.get_last_calculation_object().get_result()
@staticmethod
def get_first_calculation():
""" get the first calculation from history"""
return Calculations.history[0]
@staticmethod
def get_calculation_from_history(num):
""" get a specific calculation from history"""
return Calculations.history[num]
@staticmethod
def add_calculation_to_history(calculation):
""" get a specific calculation from history"""
Calculations.history.append(calculation)
return Calculations.history
|
fname = input('Enter the name of the file: ')
if(len(fname) < 1) : fname = 'clown.txt'
hand = open(fname)
di = dict()
for line in hand:
line = line.rstrip()
wds = line.split()
for w in wds:
##if not there, the count is zero
##if it is there, just add + 1
di[w] = di.get(w, 0) + 1
##All the code below in a single line in the code above
'''
if w in di:
di[w] = di[w] + 1
print('***EXISTING***')
else:
di[w] = 1
print('***NEW***')
'''
print(di)
#Finding the most common word:
bigCount = None
bigWord = None
for k, v in di.items():
if(bigCount == None or v > bigCount):
bigCount = v
bigWord = k
print('bigCount: ', bigCount)
print('bigWord: ', bigWord)
|
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
rows_to_zero = set()
cols_to_zero = set()
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if matrix[row][col] == 0:
rows_to_zero.add(row)
cols_to_zero.add(col)
for row in range(len(matrix)):
for col in range(len(matrix[0])):
if row in rows_to_zero or col in cols_to_zero:
matrix[row][col] = 0
|
def distinct(iterable, keyfunc=None):
seen = set()
for item in iterable:
key = item if keyfunc is None else keyfunc(item)
if key not in seen:
seen.add(key)
yield item |
'''
URL: https://leetcode.com/problems/binary-tree-level-order-traversal/
Difficulty: Medium
Description: Binary Tree Level Order Traversal
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def levelOrder(self, root):
result = []
# Empty tree
if root == None:
return result
# queue for tracking next node to process
queue = [root]
# last node in current level
lastInCurrLevel = root
# all the nodes in current level we have visited
nodesInCurrLevel = []
while len(queue):
node = queue.pop(0)
nodesInCurrLevel.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# if we reach last node in current level
if node == lastInCurrLevel:
# add the level (list of nodes) to result
result.append(nodesInCurrLevel)
# reset the list
nodesInCurrLevel = []
if len(queue):
# last node in the queue will be the last node in next level
lastInCurrLevel = queue[-1]
return result
|
def read_file():
content = open("C:/Users/DIPANSH KHANDELWAL/Desktop/Python Codes/PythonFiles/read_file/read_file.txt")
text = content.read()
print (text)
content.close()
read_file()
|
NAME='syslog'
CFLAGS = []
LDFLAGS = []
LIBS = []
GCC_LIST = ['syslog_plugin']
|
class DisjointSets(object):
"""A simple implementation of the Disjoint Sets data structure.
Implements path compression but not union-by-rank.
"""
def __init__(self, elements):
self.num_elements = len(elements)
self.num_sets = len(elements)
self.parents = {element: element for element in elements}
def is_connected(self):
return self.num_sets == 1
def get_num_elements(self):
return self.num_elements
def contains(self, element):
return element in self.parents
def add_singleton(self, element):
assert not self.contains(element)
self.num_elements += 1
self.num_sets += 1
self.parents[element] = element
def find(self, element):
parent = self.parents[element]
if element == parent:
return parent
result = self.find(parent)
self.parents[element] = result
return result
def union(self, e1, e2):
p1, p2 = map(self.find, (e1, e2))
if p1 != p2:
self.num_sets -= 1
self.parents[p1] = p2
|
"""This module provides the client to make the connection with the given database."""
class DatabaseClient:
"""Initializes the connector with the DatabaseFactory object and provides a connector."""
def __init__(self, factory_obj) -> None:
"""
Initializes the factory object.
:factory_obj : object of type DatabaseFactory.
"""
self.__connector = factory_obj
def connect(self, database_value, app_config):
"""Selectes the database system and returns its connection object."""
try:
database = self.__connector.get_database(database_value)
return database.connect(app_config)
except Exception as err:
raise err
def get_row_query( # pylint: disable=too-many-arguments
self,
database_value: int,
cols_to_query: str,
table_name: str,
output_col: str,
limit: int = 100,
) -> str:
"""
Selects the database and returns its row query.
: database_value: database representation value.
: cols_to_query: comma seperated column names to select from the table.
example: "id, input_text"
: table_name: name of the database table.
: output_col: name of the output column.
: limit: number of rows to return, default is 100
"""
if (
cols_to_query is None or
table_name is None or
output_col is None or
database_value is None
):
raise Exception("Missing parameters")
database = self.__connector.get_database(database_value)
return database.get_row_query(cols_to_query, table_name, output_col, limit)
|
#lambda is used to create an anonymous function (function with no name)
# It is an inline function that does not contain a return statement
a = lambda x: x*2
for i in range(1,6):
print(a(i)) |
def solve(a, b):
return a + b
def driver():
a, b = list(map(int, input().split(' ')))
result = solve(a, b)
print(solve(a, b))
return result
def main():
return driver()
if __name__ == '__main__':
main()
|
# Program to convert Miles to Kilometers
# Taking miles input from the user
miles = float(input("Enter value in miles: "))
# conversion factor
convFac = 0.621371
# calculate kilometers
kilometers = miles / convFac
print("%0.2f miles is equal to %0.2f kilometers" % (miles, kilometers))
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright © 2014-2016 NetApp, Inc. All Rights Reserved.
#
# CONFIDENTIALITY NOTICE: THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION OF
# NETAPP, INC. USE, DISCLOSURE OR REPRODUCTION IS PROHIBITED WITHOUT THE PRIOR
# EXPRESS WRITTEN PERMISSION OF NETAPP, INC.
"""API Utilities"""
def ascii_art(version):
"""
Used to build SolidFire ASCII art.
:return: a string with the SolidFire ASCII art.
"""
art = "\n"
art += "\n"
art += " 77 \n"
art += " 7777 \n"
art += " 77 \n"
art += " == \n"
art += " 77IIIIIIIIIIIIIIIIII777 \n"
art += " =7 7= \n"
art += " 7 7 \n"
art += " =7 7= \n"
art += " =7 7= \n"
art += " =77 7777777777777777777 77= \n"
art += " 7777 777777777777777777777 7777 \n"
art += " 7777 7777777777777777777 7777 \n"
art += " =77 77= \n"
art += " =7 7= \n"
art += " 7 7 \n"
art += " 7= =7 \n"
art += " 77= =77 \n"
art += " =7777777777777777777= \n"
art += " \n"
art += " ====IIIIIIIIII===== \n"
art += " =77777= =77777= \n"
art += " =777= =777= \n"
art += " =777= =777=\n"
art += " \n"
art += " NetApp SolidFire Version {0} " \
"\n".format(version)
art += " \n"
return art
|
def venda_mensal(*args):
telaCaixa = args[0]
telaMensal = args[1]
cursor = args[2]
QtWidgets = args[3]
data1 = telaMensal.data_mensal.text()
cursor.execute("select sum(qt_pizzas), sum(qt_esfihas), sum(qt_bebidas), sum(qt_outros), sum(total) from caixa where extract(year_month from data2) = %s " % data1)
dados = cursor.fetchall()
if dados == ((None, None, None, None, None),):
dados = (('', '', '', '', ''),)
telaCaixa.tableWidget.setRowCount(len(dados))
telaCaixa.tableWidget.setColumnCount(5)
for i in range(0, len(dados)):
for j in range(5):
telaCaixa.tableWidget.setItem(i, j, QtWidgets.QTableWidgetItem(str(dados[i][j])))
telaMensal.hide() |
class ApiException(Exception):
pass
class ResourceNotFound(ApiException):
pass
class InternalServerException(ApiException):
pass
class UserNotFound(ApiException):
pass
class Ratelimited(ApiException):
pass
class InvalidMetric(ApiException):
pass
class AuthenticationException(ApiException):
pass
|
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
arr = [0 for _ in range(len(nums))]
for num in nums:
arr[num - 1] += 1
ans = []
for i in range(len(arr)):
if arr[i] == 0:
ans.append(i + 1)
return ans
|
s = "abdcd"
count = 0
for vowelsItem in s:
if vowelsItem in "aeiou":
count += 1
print("Number of vowels: " + str(count)) |
# Python3 implementation to
# find first element
# occurring k times
# function to find the
# first element occurring
# k number of times
def firstElement(arr, n, k):
# dictionary to count
# occurrences of
# each element
count_map = {};
for i in range(0, n):
if(arr[i] in count_map.keys()):
count_map[arr[i]] += 1
else:
count_map[arr[i]] = 1
i += 1
for i in range(0, n):
# if count of element == k ,
# then it is the required
# first element
if (count_map[arr[i]] == k):
return arr[i]
i += 1
# Driver Code
if __name__=="__main__":
arr = input().split(" ")
n = len(arr)
k = int(input())
print(firstElement(arr, n, k)) |
rooms = int(input())
free_chairs = 0
game_on = True
for current_room in range(1, rooms + 1):
command = input().split()
chairs = len(command[0])
visitors = int(command[1])
if chairs > visitors:
free_chairs += chairs - visitors
elif chairs < visitors:
needed_chairs_in_room = visitors - chairs
print(f"{needed_chairs_in_room} more chairs needed in room {current_room}")
game_on = False
if game_on:
print(f"Game On, {free_chairs} free chairs left")
|
def main():
students = []
number_students = int(input())
while number_students > 0:
student = input()
students.append(student)
number_students -= 1
number_days = int(input())
all_missing_students = []
while number_days > 0:
curr_num_students = int(input())
curr_students = []
while curr_num_students > 0:
curr_student = input()
curr_students.append(curr_student)
curr_num_students -= 1
curr_missing = []
for i in students:
if i not in curr_students:
curr_missing.append(i)
all_missing_students.append(curr_missing)
number_days -= 1
print(all_missing_students)
if __name__ == '__main__':
main()
|
"""
Input Options
-------------
model_path : Input path to generated models - hdf5 file
input_catalog : Input catalog path
input_format : Input catalog format, see astropy.Table
documentation for available formats
z_col : Column name for source redshifts
ID_col : Column name for source IDs
flux_col_end : Suffix corresponding to flux columns
fluxerr_col_end : Suffix corresponding to flux error columns
filts_used : Indices of filters in model file to be used for fitting.
If 'None', assumes all filters to be used.
"""
model_path = 'candels.goodss.models.savetest.hdf'
output_name = 'candels_test.cat'
input_catalog = 'data/CANDELS.GOODSS.example.cat'
input_format = 'ascii.commented_header'
z_col = 'Photo_z'
ID_col = 'ID'
flux_col_end = '_FLUX'
fluxerr_col_end = '_FLUXERR'
filts_used = None
"""
Fitting Options
---------------
fitting_mode :
Desired option for fitting mode/outputs,
'simple' - Simple single best-fit model
'hist' - Additional mass and sfr pdf outputs
include_rest : Calculate rest-frame magnitudes for best-fit model (True/False)
ncpus : Number of parallel processes to use when fitting
flux_corr : Correction to convert input fluxes to total
flux_err : Additional fractional flux error added to all bands in quadrature
"""
fitting_mode = 'hist'
include_rest = True
ncpus = 4
zp_offsets = 'test_offsets.txt'
temp_err = None #'TEMPLATE_ERROR.v2.0.zfourge.txt'
flux_corr = 1
flux_err = 0.
nmin_bands = 14.
"""
Output Options
--------------
output_catalog : Path for output catalog
output_format : Output catalog format, see astropy.Table
documentation for available formats
output_hdf : Path for output hdf5 file ('hist' mode only)
"""
output_hdf_path = 'candels_test.hdf'
output_catalog_path = 'candels_test.cat'
output_format = 'ascii.commented_header'
|
num = int(input('Digite um número: '))
op = int(input('''Escolha:
1 - Conversão binária;
2 - Conversão octal;
3 - conversão hexadecimal;
'''))
if op == 1:
binary = format(num, 'b')
print('Após escolher a opção {}, opnúmero {} em sua forma Binária equivale à {}'.format(op, num, binary))
elif op == 2:
octal = format(num, 'o')
print('Após escolher a opção {}, o número {} em sua forma Octal equivale à {}'.format(op, num, octal))
else:
hexa = format(num, 'x')
print('Após escolher a opção {}, o número {} em sua forma Hexadecimal equivale à {}'.format(op, num, hexa))
|
def AAsInPeptideListCount(PeptidesListFileLocation):
PeptidesListFile = open(PeptidesListFileLocation, 'r')
Lines = PeptidesListFile.readlines()
PeptidesListFile.close
AminoAcidsCount = {'A':0, 'C':0, 'D':0, 'E':0,
'F':0, 'G':0, 'H':0, 'I':0,
'K':0, 'L':0, 'M':0, 'N':0,
'P':0, 'Q':0, 'R':0, 'S':0,
'T':0, 'V':0, 'W':0, 'Y':0,
'y':0, 'X':0, 'Z':0
}
# populate the dictionary, so that Peptides are the keys and
for Line in Lines:
Line = Line.strip('\n')
for i in range(len(Line)):
AminoAcidsCount[Line[i]] += 1
return AminoAcidsCount
def AAQuantitiesForSYRO(AAQuantitiesForSYROFileName, PeptidesListFileLocation):
AAData = {'A':('Ala','Fmoc-Ala-OH H2O', 311.34),
'C':('Cys','Fmoc-Cys(Trt)-OH', 585.72),
'D':('Asp','Fmoc-Asp(OtBu)-OH',411.46),
'E':('Glu','Fmoc-Glu(OtBu)-OH',425.49),
'F':('Phe','Fmoc-Phe-OH',387.40),
'G':('Gly','Fmoc-Gly-OH',297.31),
'H':('His','Fmoc-His(Trt)-OH',619.72),
'I':('Ile','Fmoc-Ile-OH',353.42),
'K':('Lys','Fmoc-Lys(Boc)-OH',468.55),
'L':('Leu','Fmoc-Leu-OH',353.42),
'M':('Met','Fmoc-Met-OH',371.45),
'N':('Asn','Fmoc-Asn(Trt)-OH',596.68),
'P':('Pro','Fmoc-Pro-OH',337.38),
'Q':('Gln','Fmoc-Gln(Trt)-OH',610.72),
'R':('Arg','Fmoc-Arg(Pbf)-OH',648.77),
'S':('Ser','Fmoc-Ser(tBu)-OH',383.45),
'T':('Thr','Fmoc-Thr(tBu)-OH',397.48),
'V':('Val','Fmoc-Val-OH',339.39),
'W':('Trp','Fmoc-Trp(Boc)-OH',526.59),
'Y':('Tyr','Fmoc-Tyr(tBu)-OH',459.54),
'y':('D-Tyr','Fmoc-D-Tyr(tBu)-OH',459.54),
'X':('HONH-Glu','Fmoc-(tBu)ONH-Glu-OH',440.50),
'Z':('HONH-ASub','Fmoc-(tBu)ONH-ASub-OH',482.50)
}
AAQuantitiesForSYRO = open(AAQuantitiesForSYROFileName, 'w')
AAQuantitiesForSYRO.write('AA' + ',' +
'Name' + ',' +
'Formula' + ',' +
'#' + ',' +
'MW(g/mol)' + ',' +
'Q(mol)' + ',' +
'Q(g)' + ',' +
'V (mL)' + '\n')
AAList = AAsInPeptideListCount(PeptidesListFileLocation)
TotalNumberOfSteps = sum(AAList.values())
for AminoAcid in AAList:
AAName = AAData[AminoAcid][0]
AAFormula = AAData[AminoAcid][1]
AACount = AAList[AminoAcid]
if AACount > 0:
AADilutionVolume = 1.1 * (2 * (0.0006 + (AACount - 1) * 0.0003))
else:
AADilutionVolume = 0
AAMolecularWeight = AAData[AminoAcid][2]
AAMoleQuantity = AADilutionVolume * 0.5
AAGrQuantity = AAMoleQuantity * AAMolecularWeight
AAQuantitiesForSYRO.write(AminoAcid + ',' +
AAName + ',' +
AAFormula + ',' +
str(AACount) + ',' +
'{:.2f}'.format(AAMolecularWeight) + ',' +
'{:.3f}'.format(AAMoleQuantity) + ',' +
'{:.3f}'.format(AAGrQuantity) + ',' +
'{:.3f}'.format(AADilutionVolume * 1000) + ',' + '\n')
MWofHBTU = 379.25
MWofHOBt = 171.134
MWofDIPEA = 129.25
DofDIPEA = 0.742
HBTUinDMFvolume = 2.2 * TotalNumberOfSteps * 0.000345
QofHBTU = 0.43 * HBTUinDMFvolume * MWofHBTU
QofHOBt = 0.43 * HBTUinDMFvolume * MWofHOBt
DIPEAinNMPvolume = 2.2 * TotalNumberOfSteps * 0.000150
QofDIPEA = 2.2 * DIPEAinNMPvolume * MWofDIPEA
VofDIPEA = QofDIPEA/DofDIPEA
VofPiperidineInDMF = 2.2 * TotalNumberOfSteps * 0.000900
AAQuantitiesForSYRO.write('HBTU quantity (g)' + ',' + '{:.2f}'.format(QofHBTU) + '\n' +
'HOBt.H2O quantity (g)' + ',' + '{:.2f}'.format(QofHOBt) + '\n' +
'HBTU & HOBt.H2O in DMF (mL)' + ',' + '{:.2f}'.format(1000 * HBTUinDMFvolume) + '\n' +
'DIPEA quantity (g)' + ',' + '{:.2f}'.format(QofDIPEA) + '\n' +
'DIPEA volume (mL)' + ',' + '{:.2f}'.format(VofDIPEA) + '\n' +
'DIPEA in NMP (mL)' + ',' + '{:.2f}'.format(1000 * DIPEAinNMPvolume) + '\n' +
'40% piperidine in DMF (mL)' + ',' + '{:.2f}'.format(1000 * VofPiperidineInDMF) + '\n')
AAQuantitiesForSYRO.close
#_____________________________RUNNING THE FUNCTION_____________________________#
#___AAQuantitiesForSYROFileName, PeptidesListFileLocation___
AAQuantitiesForSYRO('CloneSynthesis Test.csv', '/Volumes/NIKITA 2GB/CloneSynthesis.txt')
|
a = 25
b = 0o31
c = 0x19
print(a)
print(b)
print(c)
|
class MaxSparseList:
def __init__(self, firstMember, limit: int,
weight: callable = lambda x: x[0],
value: callable = lambda x: x[1]):
self.weight = weight
self.value = value
self.data = [firstMember]
self.limit = limit
return
def append(self, newMember):
w = self.weight(newMember)
if w > self.limit:
return 1
if self.value(self.data[-1]) >= self.value(newMember):
return 2
if self.weight(self.data[-1]) == w:
_ = self.data.pop()
self.data.append(newMember)
return 0
|
""" Python implementation of Paradox HD7X cameras (and future other modules)."""
class ParadoxModuleError(Exception):
"""Generic exception for Paradox modules."""
class ParadoxCameraError(ParadoxModuleError):
"""Generic exception for Camera modules."""
|
## Editing same list and then separating at the end
"""
# Definition for a Node.
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
"""
class Solution:
def copyRandomList(self, head: 'Node') -> 'Node':
if head==None: return head
# Add new nodes in old list
c = head
while (c!=None):
_next = c.next
c.next = Node(c.val)
c.next.next = _next
c = _next
# Assign random pointers to new nodes
c = head
while (c!=None):
if c.random!=None:
c.next.random = c.random.next
c = c.next.next
# Separate both linked lists
c = head
copyHead = head.next
copy = copyHead
while (copy.next!=None):
c.next = c.next.next
c = c.next
copy.next = copy.next.next
copy = copy.next
c.next = c.next.next
return copyHead
|
class RGBColor:
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __str__(self):
return "rgb({},{},{})".format(self.r, self.g, self.b)
def as_hex(self):
return HexColor("#%02x%02x%02x" % (self.r, self.g, self.b))
def as_cmyk(self):
k = min(1-self.r, 1-self.g, 1-self.b)
c = (1-self.r-k)/(1-k)
m = (1-self.g-k)/(1-k)
y = (1-self.b-k)/(1-k)
return CMYKColor(c, m, y, k)
def as_hsl(self):
r_scaled = self.r/255
g_scaled = self.g/255
b_scaled = self.b/255
c_max = max(r_scaled, g_scaled, b_scaled)
c_min = min(r_scaled, g_scaled, b_scaled)
lightness = (c_max + c_min) / 2
if c_max == c_min:
hue = 0
saturation = 0
else:
delta = c_max - c_min
hue = {
r_scaled: 60*((g_scaled-b_scaled)/delta % 6),
g_scaled: 60*((b_scaled-r_scaled)/delta+2),
b_scaled: 60*((r_scaled-g_scaled)/delta+4),
}[c_max]
saturation = delta/(1-abs(2*lightness-1))
return HSLColor(hue, saturation, lightness)
def as_rgb(self):
return self
def as_rgba(self):
return [self.r, self.g, self.b, self.a]
def complementary(self):
hsl = self.as_hsl(self.r, self.g, self.b)
comp_hue = hsl.h + 180
if comp_hue > 360:
comp_hue = comp_hue - 360
hsl.h = comp_hue
return hsl
def analogous(self):
pass
class RGBAColor:
def __init__(self, r, g, b, a=255):
self.r = r
self.g = g
self.b = b
self.a = a
def __str__(self):
return "rgba({},{},{},{})".format(self.r, self.g, self.b, self.a)
class HexColor:
def __init__(self, hexcode):
self.code =hexcode
def __str__(self):
return self.code
class CMYKColor:
def __init__(self, c, m, y, k):
self.c = c
self.m = m
self.y = y
self.k = k
def __str__(self):
return "cmyk({},{},{},{})".format(self.c, self.m, self.y, self.k)
class HSLColor:
def __init__(self, h, s, l):
self.h = h
self.s = s
self.l = l
def __str__(self):
return "hsl({},{},{})".format(self.h, self.s, self.l)
if __name__ == "__main__":
color = RGBColor(10, 10, 13)
print(color)
print(color.as_cmyk())
print(color.as_hsl())
print(color.as_hex())
|
class HightonConstants:
# is used for requests
GET = 'GET'
POST = 'POST'
PUT = 'PUT'
DELETE = 'DELETE'
HIGHRISE_URL = 'highrisehq.com'
# Company
COMPANIES = 'companies'
COMPANY = 'company'
COMPANY_NAME = 'company-name'
COMPANY_ID = 'company-id'
# Case
KASES = 'kases'
# Deal
DEALS = 'deals'
TASK = 'task'
TASKS = 'tasks'
# Person
PEOPLE = 'people'
PERSON = 'person'
EMAIL = 'email'
EMAILS = 'emails'
USER = 'user'
USERS = 'users'
GROUP = 'group'
GROUPS = 'groups'
NAME = 'name'
TITLE = 'title'
FIRST_NAME = 'first-name'
LAST_NAME = 'last-name'
CONTACT_DATA = 'contact-data'
PARENT_ID = 'parent-id'
EMAIL_ADDRESS = 'email-address'
EMAIL_ADDRESSES = 'email-addresses'
TOKEN = 'token'
DROPBOX = 'dropbox'
ADMIN = 'admin'
WEB_ADDRESS = 'web-address'
WEB_ADDRESSES = 'web-addresses'
PHONE_NUMBER = 'phone-number'
PHONE_NUMBERS = 'phone-numbers'
SUBJECT_DATA = 'subject_data'
SUBJECT_DATAS = 'subject_datas'
ADDRESS = 'address'
ADDRESSES = 'addresses'
DEAL_CATEGORIES = 'deal_categories'
DEAL_CATEGORY = 'deal-category'
TASK_CATEGORIES = 'task_categories'
TASK_CATEGORY = 'task-category'
NOTE = 'note'
NOTES = 'notes'
TAG = 'tag'
TAGS = 'tags'
SUBJECT_ID = 'subject-id'
SUBJECT_FIELD = 'subject-field'
SUBJECT_FIELDS = 'subject_fields'
SUBJECT_FIELD_ID = 'subject_field_id'
SUBJECT_FIELD_LABEL = 'subject_field_label'
URL = 'url'
ZIP = 'zip'
CITY = 'city'
STATE = 'state'
STREET = 'street'
NUMBER = 'number'
COUNTRY = 'country'
LOCATION = 'location'
ID = 'id'
BODY = 'body'
TYPE = 'type'
VALUE = 'value'
LABEL = 'label'
SEARCH = 'search'
COMMENT = 'comment'
COMMENTS = 'comments'
BACKGROUND = 'background'
RECORDING_ID = 'recording-id'
FRAME = 'frame'
ALERT_AT = 'alert-at'
PUBLIC = 'public'
RECURRING_PERIOD = 'recurring-period'
ANCHOR_TYPE = 'anchor-type'
DONE_AT = 'done-at'
AUTHOR_ID = 'author-id'
CLOSED_AT = 'closed-at'
CREATED_AT = 'created-at'
UPDATED_AT = 'updated-at'
VISIBLE_TO = 'visible-to'
GROUP_ID = 'group-id'
OWNER_ID = 'owner-id'
LINKEDIN_URL = 'linkedin-url'
AVATAR_URL = 'avatar_url'
ALL = 'all'
DEAL = 'deal'
PARTY = 'party'
PARTIES = 'parties'
CASE = 'kase'
CASES = 'kases'
TWITTER_ACCOUNTS = 'twitter-accounts'
TWITTER_ACCOUNT = 'twitter-account'
USERNAME = 'username'
PROTOCOL = 'protocol'
COLOR = 'color'
INSTANT_MESSENGERS = 'instant-messengers'
INSTANT_MESSENGER = 'instant-messenger'
ASSOCIATED_PARTIES = 'associated-parties'
ASSOCIATED_PARTY = 'associated-party'
ACCOUNT_ID = 'account-id'
CATEGORY_ID = 'category-id'
CURRENCY = 'currency'
DURATION = 'duration'
PARTY_ID = 'party-id'
PRICE = 'price'
PRICE_TYPE = 'price-type'
RESPONSIBLE_PARTY_ID = 'responsible-party-id'
STATUS = 'status'
STATUS_CHANGED_ON = 'status-changed-on'
CATEGORY = 'category'
SIZE = 'size'
DUE_AT = 'due-at'
ELEMENTS_COUNT = 'elements-count'
WON = 'won'
PENDING = 'pending'
LOST = 'lost'
COLLECTION_ID = 'collection-id'
COLLECTION_TYPE = 'collection-type'
ATTACHMENTS = 'attachments'
ATTACHMENT = 'attachment'
SUBJECT_NAME = 'subject-name'
SUBJECT_TYPE = 'subject-type'
SUBJECT_TYPES = [COMPANIES, KASES, DEALS, PEOPLE, ]
CUSTOM_FIELD_TYPES = [PARTY, DEAL, ALL, ]
|
"""
we define a video object to record video information.
"""
# coding: utf-8
class Video:
"""
obj
"""
def __init__(self, video_id):
self.video_id = video_id
self.user_id = ''
self.title = ''
self.upload_time = '' # timestamp
self.avatar_path = ''
self.avatar_url = ''
self.des = ''
def dump(self):
"""for insert a new video object to sqlite database."""
return (self.video_id, self.user_id,
self.title, self.upload_time,
self.avatar_path, self.avatar_url,
self.des)
|
""" GLSL shader code to render bitmap glyphs.\
:download:`[source] <../../../litGL/glsl_bitmap.py>`
Author:
2020-2021 Nicola Creati
Copyright:
2020-2021 Nicola Creati <ncreati@inogs.it>
License:
MIT/X11 License (see
:download:`license.txt <../../../license.txt>`)
"""
#:
VERTEX_SHADER = """
#version 330
layout(location=0) in vec2 position;
layout(location=1) in vec2 tex;
layout(location=2) in vec4 gp;
uniform mat4 T_MVP;
out vs_output
{
vec2 texCoord;
flat uvec4 glyphParam;
} vs_out;
void main()
{
gl_Position = T_MVP * vec4(position.x, position.y, 0.0f, 1.0f);
vs_out.texCoord = tex;
vs_out.glyphParam = uvec4(gp);
}
"""
#:
FRAGMENT_SHADER = """
#version 330
in vs_output
{
vec2 texCoord;
flat uvec4 glyphParam;
} fs_in;
out vec4 fragColor;
uniform sampler2D u_colorsTex;
uniform vec4 u_color;
void main()
{
vec4 sampled = texture(u_colorsTex, fs_in.texCoord);
fragColor = vec4(sampled.xyz, sampled.w * u_color.w);
}
"""
|
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
odd = head
even = even_head = head.next
while even is not None and even.next is not None:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = even_head
return head
def test_odd_even_list_1():
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
r = Solution().oddEvenList(a)
assert r.val == 1
assert r.next.val == 3
assert r.next.next.val == 5
assert r.next.next.next.val == 2
assert r.next.next.next.next.val == 4
def test_odd_even_list_2():
a = ListNode(2)
b = ListNode(1)
c = ListNode(3)
d = ListNode(5)
e = ListNode(6)
f = ListNode(4)
g = ListNode(7)
a.next = b
b.next = c
c.next = d
d.next = e
e.next = f
f.next = g
r = Solution().oddEvenList(a)
assert r.val == 2
assert r.next.val == 3
assert r.next.next.val == 6
assert r.next.next.next.val == 7
assert r.next.next.next.next.val == 1
assert r.next.next.next.next.next.val == 5
assert r.next.next.next.next.next.next.val == 4
|
class BraviaProtocol:
# def __init__():
# def makeQuery(self, parameters):
# queries = [];
# while parameters:
# if parameters[0] in self.protocol.keys():
# queries.append(self.protocol[parameters[0]] + "?")
# parameters = parameters[1:]
# return queries
# def makeCommands(self, params):
# commands = []
# for c, p in params.items():
# if c in self.protocol.keys():
# commands.append(str(list(self.protocol.values())[list(self.protocol.keys()).index(c)] + p))
# return commands
def parseEvents(self, events):
has_changed = True
# while events:
# ev = events[0][0:2]
# if ev in self.protocol.values():
# val = ''
# ob = events[0][2:]
# key = list(self.protocol.keys())[list(self.protocol.values()).index(ev)]
# if key in self.state.keys():
# val = self.state[key]
# if ob != val:
# has_changed = True
# self.state[key] = ob
# events = events[1:]
return has_changed
# def getState(self):
# return self.state
|
class Value():
def __init__(self):
self._value = None
def __set__(self, obj, value):
self._value = value
def __get__(self, obj, obj_type):
return self._value - obj.commission * self._value |
# Sieve of Eratosthenes Algorithm
def sieve(num):
'''
algorithm Sieve of Eratosthenes is
input: an integer n > 1.
output: all prime numbers from 2 through n.
let A be an array of Boolean values, indexed by integers 2 to n,
initially all set to true.
for i = 2, 3, 4, ..., not exceeding √n do
if A[i] is true
for j = i^2, i^2+i, i^2+2i, i^2+3i, ..., not exceeding n do
A[j] := false
return all i such that A[i] is true.
'''
# Array of Boolean Values of num length
result = [False, False] # Index of 0 and 1 is going to be False
result += [True] * (num - 1)
upper_limit = int(num ** 0.5) + 1
for i in range(2, upper_limit):
if result[i]: # if result[i] == True:
for j in range(i*i, num+1, i):
result[j] = False
# end of double for loops
prime_locations = []
# return all i such that A[i] is true.
for i in range(len(result)):
if result[i]:
prime_locations.append(i)
return prime_locations
# end of sieve
|
# Given nums = [2, 7, 11, 15], target = 9,
# Because nums[0] + nums[1] = 2 + 7 = 9,
# return [0, 1].
# brute force - time complexity O(n^2)
def two_sum(list, target):
for f_index, f_value in enumerate(list):
for s_index, s_value in enumerate(list[f_index+1:]):
if (f_value + s_value) == target:
return [f_index, list.index(s_value)]
return None
|
SECRET_KEY = 'XXX'
DEBUG=False
# API-specific
API_500PX_KEY = 'XXX'
API_500PX_SECRET = 'XXX'
API_RIJKS = 'XXX'
FLICKR_KEY = 'XXX'
FLICKR_SECRET = 'XXX'
# Database-specific
SQLALCHEMY_DATABASE_URI = 'postgresql://{}:{}@{}:{}/{}'.format('cctest',
'cctest',
'localhost',
'5432',
'openledgertest')
SQLALCHEMY_TRACK_MODIFICATIONS = False
DEBUG_TB_ENABLED = False
TESTING=True
|
#!/usr/bin/env python3
"""Project Euler - Problem 17 Module"""
def problem17(limit):
"""Problem 17 - Number letter counts"""
# store known results
result = 0
for x in range(1, limit+1):
wl = 0
# thousends
t = int(x/THOUSAND)
if t > 0:
wl += len(LANGUAGE_DICT[t]) + len(LANGUAGE_DICT[THOUSAND])
# hundreds
h = int( (x % THOUSAND) / HUNDRED)
if (h > 0):
wl += len(LANGUAGE_DICT[h]) + len(LANGUAGE_DICT[HUNDRED])
# < 100
h_remainder = int(x % HUNDRED)
if h_remainder > 0:
if (h > 0):
wl += 3 # "and"
if (h_remainder < 20):
wl += len(LANGUAGE_DICT[h_remainder])
else:
d = int( h_remainder / TEN)
if (d > 0):
wl += len(LANGUAGE_DICT[d*TEN])
s = h_remainder % TEN
if (s > 0):
wl += len(LANGUAGE_DICT[s])
result += wl
return result
TEN = 10
HUNDRED = 100
THOUSAND = 1000
# Dictionary
LANGUAGE_DICT = {}
LANGUAGE_DICT[1] = "one"
LANGUAGE_DICT[2] = "two"
LANGUAGE_DICT[3] = "three"
LANGUAGE_DICT[4] = "four"
LANGUAGE_DICT[5] = "five"
LANGUAGE_DICT[6] = "six"
LANGUAGE_DICT[7] = "seven"
LANGUAGE_DICT[8] = "eight"
LANGUAGE_DICT[9] = "nine"
LANGUAGE_DICT[TEN] = "ten"
LANGUAGE_DICT[11] = "eleven"
LANGUAGE_DICT[12] = "twelve"
LANGUAGE_DICT[13] = "thirteen"
LANGUAGE_DICT[14] = "fourteen"
LANGUAGE_DICT[15] = "fifteen"
LANGUAGE_DICT[16] = "sixteen"
LANGUAGE_DICT[17] = "seventeen"
LANGUAGE_DICT[18] = "eighteen"
LANGUAGE_DICT[19] = "nineteen"
LANGUAGE_DICT[20] = "twenty"
LANGUAGE_DICT[30] = "thirty"
LANGUAGE_DICT[40] = "forty"
LANGUAGE_DICT[50] = "fifty"
LANGUAGE_DICT[60] = "sixty"
LANGUAGE_DICT[70] = "seventy"
LANGUAGE_DICT[80] = "eighty"
LANGUAGE_DICT[90] = "ninety"
LANGUAGE_DICT[HUNDRED] = "hundred"
LANGUAGE_DICT[THOUSAND] = "thousand"
def run():
"""Default Run Method"""
return problem17(1000)
if __name__ == '__main__':
print("Result: ", run())
|
_runs_on_key = "runs-on"
def execute(obj: dict) -> None:
default_runner = obj.get(_runs_on_key)
if not default_runner:
return
for job in obj.get("jobs", {}).values():
if _runs_on_key not in job:
job[_runs_on_key] = default_runner
# Clean up the left-overs
obj.pop(_runs_on_key)
|
class SisCheckpointSubstage(basestring):
"""
sis checkpoint sub-stage
Possible values:
<ul>
<li> "Sort_pass2" - Sorting the fingerprints for deduplication
</ul>
"""
@staticmethod
def get_api_name():
return "sis-checkpoint-substage"
|
# **args
def save_user(**user):
print(user['name'])
#**user retorna um dict
save_user(id=1, name='admin') |
class Service(object):
class Version(object):
def __init__(self, number, created_at, updated_at, deleted_at):
self.number = number
self.created_at = created_at
self.updated_at = updated_at
self.deleted_at = deleted_at
def __init__(self, id, name, version, versions, **kwargs):
self.id = id
self.name = name
self.version = version
self.versions = versions
class Invoice(object):
class Region(object):
class Details(object):
class Tier(object):
def __init__(self, name, units, price, discounted_price, total, **kwargs):
self.name = name
self.units = units
self.price = price
self.discounted_price = discounted_price
self.total = total
def __init__(self, tiers, total, **kwargs):
self.tiers = tiers
self.total = total
@property
def total_units(self):
"""
:return: The number of Gigabytes if bandwidth or the number of requests
"""
return sum([t.units for t in self.tiers])
class Bandwidth(Details):
pass
class Requests(Details):
pass
def __init__(self, bandwidth, requests, cost, **kwargs):
self.bandwidth = bandwidth
self.requests = requests
self.cost = cost
def __init__(self, invoice_id, start_time, end_time, regions, **kwargs):
self.invoice_id = invoice_id
self.start_time = start_time
self.end_time = end_time
self.regions = regions
class Stats(object):
class DailyStats(object):
def __init__(self, service_id, start_time, bandwidth, requests, **kwargs):
self.service_id = service_id
self.start_time = start_time
self.bandwidth = bandwidth
self.requests = requests
def __init__(self, daily_stats, region, **kwargs):
self.daily_stats = daily_stats
self.region = region
@property
def total_bandwidth(self):
return sum([d.bandwidth for d in self.daily_stats])
@property
def total_requests(self):
return sum([d.requests for d in self.daily_stats])
@property
def days(self):
return len(self.daily_stats)
|
# keys TabbinPoint
OFFSET_DX = 'OFFSET_DX' # DOUBLE
OFFSET_DY = 'OFFSET_DY' # DOUBLE
OFFSET_DZ = 'OFFSET_DZ' # DOUBLE
OFFSET_DLENGTH = 'OFFSET_DLENGTH' # DOUBLE
OFFSET_LINTENSITY = 'OFFSET_LINTENSITY' # LONG
OFFSET_IFILTER_OBSOLETE = 'OFFSET_IFILTER_OBSOLETE' # SHORT
OFFSET_ISYMSETTING_OBSOLETE = 'OFFSET_ISYMSETTING_OBSOLETE' # SHORT
OFFSET_ISWSMODE_OBSOLETE = 'OFFSET_ISWSMODE_OBSOLETE' # SHORT
OFFSET_IPHTSCANTYPE = 'OFFSET_IPHTSCANTYPE' # SHORT
OFFSET_IXPIX = 'OFFSET_IXPIX' # SHORT
OFFSET_IYPIX = 'OFFSET_IYPIX' # SHORT
OFFSET_FCENTROIDX = 'OFFSET_FCENTROIDX' # FLOAT, starts from 0
OFFSET_FCENTROIDY = 'OFFSET_FCENTROIDY' # FLOAT, starts from 0
OFFSET_DAPHTSTARTANGLESRAD = 'OFFSET_DAPHTSTARTANGLESRAD' # 6x DOUBLE
OFFSET_DAPHTENDANGLESRAD = 'OFFSET_DAPHTENDANGLESRAD' # 6x DOUBLE
OFFSET_LCALCULATIONSTATUS = 'OFFSET_LCALCULATIONSTATUS' # LONG
OFFSET_UTWINGROUPFLAGS = 'OFFSET_UTWINGROUPFLAGS' # TWINGROUPFLAGS 4x BYTE
OFFSET_DWRUNFRAME1BASED = 'OFFSET_DWRUNFRAME1BASED' # DWORD
OFFSET_DWFRAMESTAMP_OR_LO_RINGNUMBER_HI_FRAMEID = 'OFFSET_DWFRAMESTAMP_OR_LO_RINGNUMBER_HI_FRAMEID' # DWORD
# keys CrysalisTabbinController
OFFSET_GROUPSTART = "OFFSET_GROUPSTART"
OFFSET_GROUPKEY = "OFFSET_GROUPKEY"
OFFSET_GROUPNEXT = "OFFSET_GROUPNEXT"
OFFSET_POINT_NUM = "OFFSET_POINT_NUM"
OFFSET_POINT_LIST = "OFFSET_POINT_LIST"
OFFSET_IVERSION_TABBIN_HEADER = "OFFSET_IVERSION_TABBIN_HEADER"
OFFSET_GROUP_LIST = "OFFSET_GROUP_LIST"
OFFSET_POINT_LISTNEXT = "OFFSET_POINT_LIST_INCREMENT"
|
# -*- coding: utf-8 -*-
"""
TSPL - TimScriptProgrammingLanguage
A simple programming language and interpreter in python
- more of a learning device than a practical use language
Created on Sat May 9 20:24:51 2020
@author: tim_s
"""
class Exp:
""" An expression to be evaluated
can put default behaviour here
"""
def __init__(self):
pass
def eval(self):
return None
def __str__(self):
return ""
def has_zero(self):
return False
class Nul(Exp):
""" Used to represent a null value """
def __init__(self):
super().__init__()
def __str__(self):
return "nul"
class Int(Exp):
""" A constant int """
def __init__(self, i):
super().__init__()
self.i = i
def eval(self):
return self.i
def __str__(self):
return str(self.i)
def has_zero(self):
return self.i == 0
class Negate(Exp):
""" Negated expression """
def __init__(self, e):
super().__init__()
self.e = e
def eval(self):
return Int(-(self.e.eval()))
def __str__(self):
return "-(" + str(self.e) + ")"
def has_zero(self):
return self.e.has_zero()
class Add(Exp):
""" Expression representing the result
of adding two expressions
"""
def __init__(self, e1, e2):
super().__init__()
self.e1 = e1
self.e2 = e2
def eval(self):
return Int(self.e1.eval() + self.e2.eval())
def __str__(self):
return "(" + str(self.e1) + " + " + str(self.e2) + ")"
def has_zero(self):
return self.e1.has_zero() or self.e2.has_zero()
class Multiply(Exp):
""" Expression representing the result
of multiplying two expressions
"""
def __init__(self, e1, e2):
super().__init__()
self.e1 = e1
self.e2 = e2
def eval(self):
return Int(self.e1.eval().i * self.e2.eval().i)
def __str__(self):
return "(" + str(self.e1) + " * " + str(self.e2) + ")"
def has_zero(self):
self.e1.has_zero() or self.e2.has_zero()
# TODO: change implementation to use pure OOP
# class Divide(Exp):
# """ Expression representing the result
# of dividing two expressions
# """
# def __init(self, exp1: Exp, exp2: Exp):
# super().__init__()
# self.exp1 = exp1
# self.exp2 = exp2
# class Variable(Exp):
# """ A variable mapping a string to an expression """
# def __init__(self, name: str, value: Exp):
# super().__init__()
# self.name = name
# self.value = value
# class Pair(Exp):
# """ A pair of expressions
# use Nul expression to end list
# ex: Pair(e1, Pair(e2, Nul)) == [e1, e2]
# """
# def __init__(self, exp1: Exp, exp2: Exp):
# super().__init__()
# self.exp1 = exp1
# self.exp2 = exp2
|
# Tests Python 3.5+'s ops
# BINARY_MATRIX_MULTIPLY and INPLACE_MATRIX_MULTIPLY
# code taken from pycdc tests/35_matrix_mult_oper.pyc.src
m = [1, 2] @ [3, 4]
m @= [5, 6]
|
apple=map(int,input().split())
high=int(input())+30
sum=0
for i in apple:
if i<=high:sum+=1
print(sum) |
TEST = """initial state: #..#.#..##......###...###
...## => #
..#.. => #
.#... => #
.#.#. => #
.#.## => #
.##.. => #
.#### => #
#.#.# => #
#.### => #
##.#. => #
##.## => #
###.. => #
###.# => #
####. => #
""".splitlines()
def read_lines():
with open('input.txt', 'r') as f:
return [l.strip() for l in f.readlines()]
def parse_lines(lines):
initial_state = lines[0][15:]
rules = {}
for line in lines[2:]:
pattern, _, result = line.partition(' => ')
rules[pattern] = result
return initial_state, rules
def step(state, rules):
result = '..'
for idx in range(len(state) - 4):
c = rules.get(state[idx:idx + 5], '.')
result += c
return result + '..'
def value(state, offset):
first = state.find('#')
result = 0
for i in range(first, len(state)):
if state[i] == '#':
result += (i + offset)
return result
def shift(state, offset):
idx = state.find('#')
if idx < 5:
state = ('.' * 10) + state
offset -= 10
elif idx > 15:
state = state[10:]
offset += 10
idx = state.rfind('#')
if idx > (len(state) - 5):
state = state + ('.' * 10)
elif idx < (len(state) - 15):
state = state[:-10]
return state, offset
def run(state, rules, steps):
offset = 0
for i in range(steps):
state, offset = shift(state, offset)
state = step(state, rules)
return value(state, offset)
if __name__ == '__main__':
# lines = TEST
lines = read_lines()
state, rules = parse_lines(lines)
result = run(state, rules, 20)
print("Part1: sum = %d" % result)
# somewhere below 1000 the values get regular and repeat ...
offset = run(state, rules, 1000)
delta = run(state, rules, 2000) - offset
steps = 50000000000
print("Part2: steps = %d, sum = %d" % (steps, (steps / 1000 - 1) * delta + offset))
|
# -*- coding: utf-8 -*-
SYSTEM = "O"
USER = "I"
TYPE_CHAT = (
(SYSTEM, u'Gozokia'),
(USER, u'User'),
)
|
class FluidSettings:
type = None
|
class AtbashCipher:
def encrypt(self, string):
lst = []
for elem in string.lower():
if elem.isalpha():
lst+=chr(219-ord(elem))
else:
lst+=[elem]
return ''.join(lst).lower()
def decrypt(self, string):
return self.encrypt(string).lower() #same result for encryption |
def forward(t):
t.penup()
t.forward(3)
def no_draw_forward(t):
t.pendown()
t.forward(3)
axiom = 'A'
n = 5
subs = {
'A': 'ABA',
'B': 'BBB'
}
graphics = {
'A': lambda t: forward(t),
'B': lambda t: no_draw_forward(t)
}
|
_base_ = "./FlowNet512_1.5AugCosyAAEGray_Aggressive_Flat_Pbr_01_ape.py"
OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_Aggressive_Flat_lmPbr_SO/benchvise"
DATASETS = dict(TRAIN=("lm_pbr_benchvise_train",), TEST=("lm_real_benchvise_test",))
# bbnc7
# objects benchvise Avg(1)
# ad_2 10.77 10.77
# ad_5 48.01 48.01
# ad_10 92.92 92.92
# rete_2 43.55 43.55
# rete_5 99.32 99.32
# rete_10 100.00 100.00
# re_2 57.32 57.32
# re_5 99.32 99.32
# re_10 100.00 100.00
# te_2 82.25 82.25
# te_5 100.00 100.00
# te_10 100.00 100.00
# proj_2 74.88 74.88
# proj_5 99.22 99.22
# proj_10 100.00 100.00
# re 1.97 1.97
# te 0.01 0.01
|
class ChannelLengthException(Exception):
'''channel searched is more than 16 characters
use with the command line functions
'''
pass
class ChannelCharactersException(Exception):
'''
it should not contain characters that cannot be used in a channel
'''
pass
class ChannelQuotesException(Exception):
'''
it should remove any quotation marks
'''
pass
class ChannelEmptyException(Exception):
'''
it should not be an empty string
'''
pass
class ChannelTypeException(Exception):
'''
the channel type should be able to be made to a string
throw exception when it fails to be made a string
'''
class ChannelMissingException(Exception):
'''
the channel doesnt exist
'''
class ChannelAlreadyEnteredException(Exception):
'''for when a channel already exists in a data structure .
raise this exception
'''
|
# Algorithm: Longest monotonic subsequence
# Overall Time Complexity: O(n^2).
# Space Complexity: O(n).
# Author: https://www.linkedin.com/in/kilar.
def monotonic_subsequence(arr):
Dict = {}
maximum = 0
for i in range(len(arr)):
Dict[i] = [arr[i]]
for j in range(i + 1, len(arr)):
if arr[j] >= Dict[i][-1]:
Dict[i].append(arr[j])
for m in Dict:
temp = maximum
maximum = max(maximum, len(Dict[m]))
if temp < maximum:
key = m
return Dict[key]
|
class ArticleCandidate:
"""This is a helpclass to store the result of an article after it was extracted. Every implemented extractor
returns an ArticleCanditate as result.
"""
url = None
title = None
description = None
text = None
topimage = None
author = None
publish_date = None
extractor = None
language = None
|
class Record:
def __init__(self, row_id):
self.row_id = row_id
class Table:
lookup_table = {}
@classmethod
def get_record(cls, row_id: int) -> Record:
"""
if row_id not in cls.lookup_table,
instantiate Record object on the fly.
"""
if row_id not in cls.lookup_table.keys():
# There must be more args.
cls.lookup_table[row_id] = Record(row_id)
return cls.lookup_table[row_id]
if __name__ == '__main__':
Table.get_record(1)
|
#!/usr/bin/env python3
# Количество программ с обязательным и избегаемым этапами
c = 0
def run(n, w10=False, w16=False):
global c
if n == 10:
w10 = True
if n == 16:
w16 = True
if n > 21:
return
elif n == 21:
if w10 and not w16:
c += 1
else:
run(n + 1, w10, w16)
run(n * 2, w10, w16)
run(1)
print(c)
|
#!/usr/bin/env python
# coding: utf-8
# In[1]:
def hangman(word):
wrong = 0
stages = ["",
"________ ",
"| ",
"| | ",
"| 0 ",
"| / | \ ",
"| / \ ",
"| "
]
rletters = list(word)
board = ["_"] * len(word)
win = False
print("ハングマンへようこそ!")
while wrong < len(stages) - 1:
print("\n")
msg = "1文字を予想してね"
char = input(msg)
if char in rletters:
cind = rletters.index(char)
board[cind] = char
rletters[cind] = '$'
else:
wrong += 1
print(" ".join(board))
e = wrong + 1
print("\n".join(stages[0:e]))
if "_" not in board:
print("あなたの勝ち!")
print(" ".join(board))
win = True
break
if not win:
print("\n".join(stages[0:wrong+1]))
print("あなたの負け!正解は {}.".format(word))
# In[2]:
hangman("cat")
# In[4]:
hangman("dog")
# In[ ]:
|
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
red = 0
white = 0
blue = 0
for i in nums:
if i == 0:
red += 1
elif i == 1:
white += 1
else:
blue += 1
for i in range(len(nums)):
if red:
nums[i] = 0
red -= 1
elif white:
nums[i] = 1
white -= 1
else:
nums[i] = 2
|
# p43.py
str1 = input().split()
str1.reverse()
def exp():
s = str1.pop()
if s[0] == '+':
return exp() + exp()
elif s[0] == '-':
return exp() - exp()
elif s[0] == '*':
return exp() * exp()
elif s[0] == '/':
return exp() / exp()
else:
return float(s)
print(int(exp()))
|
#!/usr/bin/env python3
# calculate path of lowest risk
# use Dijkstra algorithm
risk = []
with open('input', 'r') as data:
lines = data.readlines()
for line in lines:
risk.append([int(l) for l in line.strip()])
# prepare nodes
# we might get up with x <-> y again...
graph = []
for y in range(len(risk)):
graph.append([{"visited": False, "risk": 10000000} for x in range(len(risk[y]))])
def visit_neighbors(position, graph):
x = position[0]
y = position[1]
# if neighbor was not evaluated and path through current
# costs less, then update count
if x-1 >= 0:
if not graph[x-1][y]["visited"]:
if graph[x][y]["risk"] + risk[x-1][y] < graph[x-1][y]["risk"]:
graph[x-1][y]["risk"] = graph[x][y]["risk"] + risk[x-1][y]
if x+1 < len(graph[y]):
if not graph[x+1][y]["visited"]:
if graph[x][y]["risk"] + risk[x+1][y] < graph[x+1][y]["risk"]:
graph[x+1][y]["risk"] = graph[x][y]["risk"] + risk[x+1][y]
if y-1 >= 0:
if not graph[x][y-1]["visited"]:
if graph[x][y]["risk"] + risk[x][y-1] < graph[x][y-1]["risk"]:
graph[x][y-1]["risk"] = graph[x][y]["risk"] + risk[x][y-1]
if y+1 < len(graph):
if not graph[x][y+1]["visited"]:
if graph[x][y]["risk"] + risk[x][y+1] < graph[x][y+1]["risk"]:
graph[x][y+1]["risk"] = graph[x][y]["risk"] + risk[x][y+1]
return graph
def get_lowest_unvisited(graph):
lowest = None
for y in range(len(graph)):
for x in range(len(graph[y])):
if not graph[x][y]["visited"]:
if lowest == None or graph[x][y]["risk"] < graph[lowest[0]][lowest[1]]["risk"]:
lowest = [x, y]
return lowest
# enter the starting node
position = [0,0]
graph[0][0]["visited"] = True
# special: start node is not counted
graph[0][0]["risk"] = 0
end = [len(graph)-1, len(graph[0])-1]
print(str(end))
while position != end:
graph = visit_neighbors(position, graph)
graph[position[0]][position[1]]["visited"] = True
position = get_lowest_unvisited(graph)
#for y in range(len(graph)):
# for x in range(len(graph[y])):
# risk = graph[y][x]["risk"]
# print(f'{risk:02d}', end=" ")
# print("")
#print(str(position))
print(graph[end[0]][end[1]]["risk"])
|
stack = []
stack.append("Moby Dick")
stack.append("The Great Gatsby")
stack.append("Hamlet")
stack.pop()
stack.append("The Iliad")
stack.append("Pride and Prejudice")
stack.pop()
stack.append("To Kill a Mockingbird")
stack.append("Gulliver's Travels")
stack.append("Don Quixote")
stack.pop()
stack.pop()
stack.pop()
stack.pop()
print(stack) # ['Moby Dick', 'The Great Gatsby'] |
MOCK_PLAYER = {
"_id": 1234,
"uuid": "2ad3kfei9ikmd",
"displayname": "TestPlayer123",
"knownAliases": ["1234", "test", "TestPlayer123"],
"firstLogin": 123456,
"lastLogin": 150996,
"achievementsOneTime": ["MVP", "MVP2", "BedwarsMVP"],
"achievementPoints": 300,
"achievements": {"bedwars_level": 5, "general_challenger": 7, "bedwars_wins": 18},
"networkExp": 3400,
"challenges": {"all_time": {"DUELS_challenge": 1, "BEDWARS_challenge": 6}},
"mostRecentGameType": "BEDWARS",
"socialMedia": {"links": {"DISCORD": "test#1234"}},
"karma": 8888,
"mcVersionRp": "1.8.9",
"petStats": {},
"currentGadget": "Dummy thingy",
}
|
# -*- coding: utf-8 -*
INN_TEST_WEIGHTS_10 = (2, 4, 10, 3, 5, 9, 4, 6, 8, 0)
INN_TEST_WEIGHTS_12_0 = (7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0, 0)
INN_TEST_WEIGHTS_12_1 = (3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8, 0)
def test_inn_org(inn):
""" returns True if inn of the organisation pass the check
"""
if len(inn) != 10:
return False
res = 0
for i, char in enumerate(inn):
res += int(char) * INN_TEST_WEIGHTS_10[i]
res = res % 11 % 10
return res == int(inn[-1])
def test_inn_person(inn):
""" returns True if inn of the person pass the check
"""
if len(inn) != 12:
return False
res1 = 0
for i, char in enumerate(inn):
res1 += int(char) * INN_TEST_WEIGHTS_12_0[i]
res1 = res1 % 11 % 10
res2 = 0
for i, char in enumerate(inn):
res2 += int(char) * INN_TEST_WEIGHTS_12_1[i]
res2 = res2 % 11 % 10
return (res1 == int(inn[-2])) and (res2 == int(inn[-1]))
def test_inn(inn):
""" returns True if inn pass the check
"""
if len(inn) == 10:
return test_inn_org(inn)
elif len(inn) == 12:
return test_inn_person(inn)
return False
BANK_ACC_TEST_WEIGHTS = ((7, 1, 3) * 8)[:-1]
def test_bank_number(anumber):
if not isinstance(anumber, str) and not anumber.isdigit():
return False
if len(anumber) != 23:
return False
res = 0
for i, char in enumerate(anumber):
res += int(char) * BANK_ACC_TEST_WEIGHTS[i]
return (res % 10) == 0
def test_bank_corr_account_number(account, bik):
return len(account) == 20 and len(bik) == 7 and \
test_bank_number('0' + bik[4:6] + account)
def test_bank_account_number(account, bik):
return len(account) == 20 and len(bik) == 7 and \
test_bank_number(bik[-3:] + account)
|
class Solution:
def XXX(self, root: TreeNode) -> int:
self.maxleftlength = 0
self.maxrightlength = 0
return self.dp(root)
def dp(self,root):
if(root is None):
return 0
self.maxleftlength = self.dp(root.left)
self.maxrightlength = self.dp(root.right)
return max(self.maxleftlength,self.maxrightlength)+1
|
{'application':{'type':'Application',
'name':'GuiPyBlog',
'backgrounds': [
{'type':'Background',
'name':'bgTextRouter',
'title':'TextRouter 0.60',
'size':(650, 426),
'statusBar':1,
'icon':'tr.ico',
'style':['resizeable'],
'menubar': {'type':'MenuBar',
'menus': [
{'type':'Menu',
'name':'menuFile',
'label':'&File',
'items': [
{'type':'MenuItem',
'name':'menuFileLoad',
'label':'&Open',
},
{'type':'MenuItem',
'name':'menuFileLoadFrom',
'label':'Op&en...',
},
{'type':'MenuItem',
'name':'menuFileSave',
'label':'&Save',
},
{'type':'MenuItem',
'name':'menuFileSaveAs',
'label':'Save &As...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuFileLoadConfig',
'label':'&Load Config...',
},
{'type':'MenuItem',
'name':'menuFileSaveConfig',
'label':'S&ave Config',
},
{'type':'MenuItem',
'name':'menuFileSaveConfigAs',
'label':'Sa&ve Config As...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuFilePreferences',
'label':'&Preferences...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuFileExit',
'label':'E&xit\tCtrl+Q',
'command':'exit',
},
]
},
{'type':'Menu',
'name':'Edit',
'label':'&Edit',
'items': [
{'type':'MenuItem',
'name':'menuEditUndo',
'label':'&Undo\tCtrl+Z',
},
{'type':'MenuItem',
'name':'menuEditRedo',
'label':'&Redo\tCtrl+Y',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuEditCut',
'label':'Cu&t\tCtrl+X',
},
{'type':'MenuItem',
'name':'menuEditCopy',
'label':'&Copy\tCtrl+C',
},
{'type':'MenuItem',
'name':'menuEditPaste',
'label':'&Paste\tCtrl+V',
},
{ 'type':'MenuItem', 'name':'editSep2', 'label':'-' },
{ 'type':'MenuItem',
'name':'menuEditFind',
'label':'&Find...\tCtrl+F',
'command':'doEditFind'},
{ 'type':'MenuItem',
'name':'menuEditFindNext',
'label':'&Find Next\tF3',
'command':'doEditFindNext'},
{'type':'MenuItem',
'name':'editSep3',
'label':'-',
},
{'type':'MenuItem',
'name':'menuEditRemoveNewlines',
'label':'Remove &Newlines',
},
{'type':'MenuItem',
'name':'menuEditWrapText',
'label':'&Wrap Text',
},
{'type':'MenuItem',
'name':'editSep4',
'label':'-',
},
{'type':'MenuItem',
'name':'menuEditClear',
'label':'Cle&ar\tDel',
},
{'type':'MenuItem',
'name':'menuEditSelectAll',
'label':'Select A&ll\tCtrl+A',
},
]
},
{'type':'Menu',
'name':'HTML',
'label':'F&ormat',
'items': [
{'type':'MenuItem',
'name':'menuHtmlBold',
'label':'&Bold\tCtrl+B',
'command':'menuHtmlMake',
},
{'type':'MenuItem',
'name':'menuHtmlItalic',
'label':'&Italic\tCtrl+I',
'command':'menuHtmlMake',
},
{'type':'MenuItem',
'name':'menuHtmlCenter',
'label':'&Center',
},
{'type':'MenuItem',
'name':'menuHtmlCode',
'label':'C&ode',
'command':'menuHtmlMake',
},
{'type':'MenuItem',
'name':'menuHtmlBlockquote',
'label':'Block"e',
'command':'menuHtmlMake',
},
{'type':'MenuItem',
'name':'htmlSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuHtmlAddLink',
'label':'&Add Link...\tCtrl+L',
'command':'menuHtmlAddLink',
},
{'type':'MenuItem',
'name':'htmlSep2',
'label':'-',
},
{'type':'MenuItem',
'name':'menuHtmlStripHTML',
'label':'&Strip HTML\tCtrl+G',
},
{'type':'MenuItem',
'name':'htmlSep2',
'label':'-',
},
{'type':'MenuItem',
'name':'menuHtmlPreferences',
'label':'Preferences...',
},
]
},
{'type':'Menu',
'name':'menuRouteTo',
'label':'&Route Text To...',
'items': [
{'type':'MenuItem',
'name':'menuRouteToBlogger',
'label':'&Blogger\tCtrl+W',
},
{'type':'MenuItem',
'name':'menuRouteToManila',
'label':'&Manila\tCtrl+E',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuRouteToEmailPredefined',
'label':'&Predefined Email...\tCtrl+R',
},
{'type':'MenuItem',
'name':'menuRouteToEmail',
'label':'&New Email...\tCtrl+T',
},
# {'type':'MenuItem',
# 'name':'editSep1',
# 'label':'-',
# },
# {'type':'MenuItem',
# 'name':'menuRouteToRSS',
# 'label':'RSS File...\tAlt-R',
# },
]
},
{'type':'Menu',
'name':'menuManila',
'label':'&Manila',
'items': [
{'type':'MenuItem',
'name':'menuManilaLogin',
'label':'&Login',
},
{'type':'MenuItem',
'name':'menuManilaFlipHomepage',
'label':'&Flip Homepage...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaAddToHP',
'label':'&Add To Homepage',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaGetHP',
'label':'&Get Current Homepage',
},
{'type':'MenuItem',
'name':'menuManilaSetAsHP',
'label':'&Set As Homepage',
},
{'type':'MenuItem',
'name':'menuManilaSetHPFromOPML',
'label':'Set &Homepage From OPML',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaGetStoryList',
'label':'Get Story Lis&t',
},
{'type':'MenuItem',
'name':'menuManilaDownloadStory',
'label':'&Download Story...',
},
{'type':'MenuItem',
'name':'menuManilaUploadStory',
'label':'&Upload Story...',
},
{'type':'MenuItem',
'name':'menuManilaPostNewStory',
'label':'Post As &New Story',
},
{'type':'MenuItem',
'name':'menuManilaSetStoryAsHP',
'label':'S&et Story As Homepage',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaUploadPicture',
'label':'Upload &Image...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaJumpTo',
'label':'&Jump To URL...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaChooseActiveAccount',
'label':'Choose Active Account...',
},
{'type':'MenuItem',
'name':'menuManilaNewAccount',
'label':'New Account...',
},
{'type':'MenuItem',
'name':'menuManilaEditAccount',
'label':'Edit Account...',
},
{'type':'MenuItem',
'name':'menuManilaRemoveAccount',
'label':'Remove Account...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuManilaPreferences',
'label':'&Preferences...',
},
]
},
{'type':'Menu',
'name':'menuBlogger',
'label':'&Blogger',
'items': [
{'type':'MenuItem',
'name':'menuBloggerLogin',
'label':'&Login',
},
{'type':'MenuItem',
'name':'menuBloggerChooseBlog',
'label':'&Choose Blog...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuBloggerFetchPosts',
'label':'&Fetch Previous Posts',
},
{'type':'MenuItem',
'name':'menuBloggerInsertPrevPost',
'label':'&Insert Previous Post...',
},
{'type':'MenuItem',
'name':'menuBloggerGetPost',
'label':'Ge&t Post By ID...',
},
{'type':'MenuItem',
'name':'menuBloggerUpdatePost',
'label':'&Update Post',
},
{'type':'MenuItem',
'name':'menuBloggerDeletePost',
'label':'&Delete Post...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuBloggerGetTemplate',
'label':'&Get Template...',
},
{'type':'MenuItem',
'name':'menuBloggerSetTemplate',
'label':'&Set Template...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuBloggerJumpTo',
'label':'&Jump To Blog...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuBloggerChooseActiveAccount',
'label':'Choose Active Account...',
},
{'type':'MenuItem',
'name':'menuBloggerNewAccount',
'label':'New Account...',
},
{'type':'MenuItem',
'name':'menuBloggerEditAccount',
'label':'Edit Account...',
},
{'type':'MenuItem',
'name':'menuBloggerRemoveAccount',
'label':'Remove Account...',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuBloggerPreferences',
'label':'&Preferences...',
},
]
},
{'type':'Menu',
'name':'menuEmail',
'label':'Emai&l',
'items': [
{'type':'MenuItem',
'name':'menuEmailNewEmailRcpt',
'label':'New Email Recipient',
},
{'type':'MenuItem',
'name':'menuEmailRemoveEmailRcpt',
'label':'Remove Recipient',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuEmailPreferences',
'label':'&Preferences...',
},
# {'type':'MenuItem',
# 'name':'editSep1',
# 'label':'-',
# },
# {'type':'MenuItem',
# 'name':'menuSettingsRSS',
# 'label':'RSS Files...',
# },
]
},
{'type':'Menu',
'name':'menuUtilities',
'label':'&Utilities',
'items': [
{'type':'MenuItem',
'name':'menuUtilitiesExternalEditor',
'label':'&External Editor',
},
{'type':'MenuItem',
'name':'menuUtilitiesTextScroller',
'label':'&Text Auto-Scroller',
},
{'type':'MenuItem',
'name':'menuUtilitiesApplyFilter',
'label':'&Apply Filter',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuUtilitiesNewFilter',
'label':'&New Filter',
},
{'type':'MenuItem',
'name':'menuUtilitiesRemoveFilter',
'label':'&Remove Filter',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuUtilitiesNewShortcut',
'label':'New &Shortcut',
},
{'type':'MenuItem',
'name':'menuUtilitiesRemoveShortcut',
'label':'Remove S&hortcut',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
# {'type':'MenuItem',
# 'name':'menuUtilitiesLoadShortcuts',
# 'label':'&Load Shortcuts...',
# },
# {'type':'MenuItem',
# 'name':'menuUtilitiesSaveShortcuts',
# 'label':'Sa&ve Shortcuts...',
# },
# {'type':'MenuItem',
# 'name':'editSep1',
# 'label':'-',
# },
{'type':'MenuItem',
'name':'menuUtilitiesPreferences',
'label':'&Preferences...',
},
]
},
{'type':'Menu',
'name':'menuHelp',
'label':'&Help',
'items': [
{'type':'MenuItem',
'name':'menuHelpHelp',
'label':'&Help (loads browser)',
},
{'type':'MenuItem',
'name':'menuHelpReadme',
'label':'&README (loads browser)',
},
{'type':'MenuItem',
'name':'editSep1',
'label':'-',
},
{'type':'MenuItem',
'name':'menuHelpAbout',
'label':'&About TextRouter...',
},
]
},
]
},
'components': [
{'type':'StaticText',
'name':'lblSubject',
'position':(0, 0),
'size':(80, -1),
'text':'Title/Subject:',
},
{'type':'TextField',
'name':'area2',
'position':(100, 0),
'size':(530, 22),
},
{'type':'TextArea',
'name':'area1',
'position':(0, 40),
'size':(640, 300),
},
{'type':'Button',
'name':'buttonClearIt',
'position':(1, 303),
'size':(120, -1),
'label':'Clear It',
},
{'type':'Button',
'name':'buttonClipIt',
'position':(1, 327),
'size':(120, -1),
'label':'Get Clipboard Text',
},
{'type':'RadioGroup',
'name':'nextInputActionMode',
'position':(131, 303),
#'size':(240, -1),
'label':'Input Action:',
'layout':'horizontal',
'items':['inserts', 'appends', 'replaces'],
'stringSelection':'inserts',
'toolTip':'Controls how the next text input action (from file, clipboard, remote server) works.'
},
{'type':'RadioGroup',
'name':'nextOutputActionMode',
'position':(380, 303),
#'size':(160, -1),
'label':'Output Action Works On:',
'layout':'horizontal',
'items':['all', 'selection'],
'stringSelection':'all',
'toolTip':'Controls how the next text output action (to file, blogger, manila, email) works.'
},
] # end components
} # end background
] # end backgrounds
} }
|
"""
Given a string of numbers and operators, return all possible results from computing
all the different possible ways to group numbers and operators. The valid operators
are +, - and *.
Input: "2-1-1".
((2-1)-1) = 0
(2-(1-1)) = 2
Time complexity of this algorithm is Catalan number.
"""
def way_to_compute(input):
ans = []
for i in range(len(input)):
c = input[i]
if c in '-*+':
left = way_to_compute(input[:i])
right = way_to_compute(input[i+1:])
if c == "-":
ans.append( left - right )
elif c == "+":
ans.append( left + right )
elif c == "*":
ans.append( left * right )
if not ans:
ans.append(int(input))
return ans
print(way_to_compute("2*3-4*5"))
|
WARNING_HEADER = '[\033[1m\033[93mWARNING\033[0m]'
def warning_message(message_text):
print('{header} {text}'.format(header=WARNING_HEADER, text=message_text))
|
class WebsocketError(Exception):
pass
class NoTokenError(WebsocketError):
pass
|
a,b=0,1
while b<10:
print(b)
a,b=b,a+b
|
# while loops
"""
a = 1
b = 10
while a < b:
print(a) #will go on forever
"""
# Docstringed loop above. Uncomment to see an infinite loop
# then kill it or wait for Python to reach an error
a = 1
b = 10
while a < b:
print(a)
a = a +1 # Now it will stop
# Bonus: calculate the iterations before this stops
while True:
# Asks you things forever
answer = input('Are you happy?')
# Unless you are forced into optimism
if answer == 'yes':
break
|
def thank_you(donation):
if donation >= 1000:
print("Thank you for your donation! You have achieved platinum donation status!")
elif donation >= 500:
print("Thank you for your donation! You have achieved gold donation status!")
elif donation >= 100:
print("Thank you for your donation! You have achieved silver donation status!")
else:
print("Thank you for your donation! You have achieved bronze donation status!")
thank_you(500)
def grade_converter(gpa):
grade = "F"
if gpa >= 4.0:
grade = "A"
elif gpa >= 3.0:
grade = "B"
elif gpa >= 2.0:
grade = "C"
elif gpa >= 1.0:
grade = "D"
return grade
print(grade_converter(2.0)) |
'''
This file holds all the constants that are required for programming the LIS3DH
including register addresses and their values
'''
'''
The LIS3DH I2C address
'''
LIS3DH_I2C_ADDR = 0x18
'''
The LIS3DH Register Map
'''
#0x00 - 0x06 - reserved
STATUS_REG_AUX = 0x07
OUT_ADC1_L = 0x08
OUT_ADC1_H = 0x09
OUT_ADC2_L = 0x0A
OUT_ADC2_H = 0x0B
OUT_ADC3_L = 0x0C
OUT_ADC3_H = 0x0D
INT_COUNTER_REG = 0x0E
WHO_AM_I = 0x0F
# 0x10 0x1E - reserved
TEMP_CFG_REG = 0x1F
CTRL_REG1 = 0x20
CTRL_REG2 = 0x21
CTRL_REG3 = 0x22
CTRL_REG4 = 0x23
CTRL_REG5 = 0x24
CTRL_REG6 = 0x25
REFERENCE = 0x26
STATUS_REG2 = 0x27
OUT_X_L = 0x28
OUT_X_H = 0x29
OUT_Y_L = 0x2A
OUT_Y_H = 0x2B
OUT_Z_L = 0x2C
OUT_Z_H = 0x2D
FIFO_CTRL_REG = 0x2E
FIFO_SRC_REG = 0x2F
INT1_CFG = 0x30
INT1_SOURCE = 0x31
INT1_THS = 0x32
INT1_DURATION = 0x33
#0x34 - 0x37 - reserved
CLICK_CFG = 0x38
CLICK_SRC = 0x39
CLICK_THS = 0x3A
TIME_LIMIT = 0x3B
TIME_LATENCY = 0x3C
TIME_WINDOW = 0x3D
'''
Values to select range of the accelerometer
'''
RANGE_2G = 0b00
RANGE_4G = 0b01
RANGE_8G = 0b10
RANGE_16G = 0b11
'''
Values to select data refresh rate of the accelerometer
'''
RATE_400HZ = 0b0111
RATE_200HZ = 0b0110
RATE_100HZ = 0b0101
RATE_50HZ = 0b0100
RATE_25HZ = 0b0011
RATE_10HZ = 0b0010
RATE_1HZ = 0b0001
RATE_POWERDOWN = 0
RATE_LOWPOWER_1K6HZ = 0b1000
RATE_LOWPOWER_5KHZ = 0b1001
'''
The WHO_AM_I reply
'''
WHO_AM_I_ID = 0x33
|
def moveDictionary():
electro_shock = {"Name" : "Electro Shock", \
"Kind" : "atk",\
"Pwr" : 25, \
"Acc" : 95, \
"Crit" : 80, \
"Txt" : "releases one thousand volts of static"}
#special
heal = {"Name" : "Heal", \
"Kind" : "heal",\
"Pwr" : 28, \
"Acc" : 36, \
"Crit" : 5, \
"Txt" : "attempts to put itself back together"}
robot_punch = {"Name" : "Robot Punch", \
"Kind" : "atk",\
"Pwr" : 40, \
"Acc" : 70, \
"Crit" : 20, \
"Txt" : "reels back and slugs hard"}
robot_slap = {"Name" : "Robot Slap", \
"Kind" : "atk",\
"Pwr" : 32, \
"Acc" : 90, \
"Crit" : 20, \
"Txt" : "slaps a hoe"}
robot_headbutt = {"Name" : "Robot Headbutt", \
"Kind" : "atk",\
"Pwr" : 45, \
"Acc" : 20, \
"Crit" : 80, \
"Txt" : "attempts a powerful attack"}
#special
moveDic = {"electro_shock" : electro_shock,\
"heal" : heal, \
"robot_punch" : robot_punch,\
"robot_slap" : robot_slap,\
"robot_headbutt" : robot_headbutt}
return moveDic
##dictionary = moveDictionary() #module testing
##print(type(dictionary)) #module print test
|
sv = float(input('Salaria? R$'))
sn = sv + (sv * 15 / 100)
print('salario antigo R${:.2f}\nCom 15% de aumento\nsalário novo R${:.2f}'.format(sv, sn))
|
"""
limis management - messages
Messages used for logging and exception handling.
"""
COMMAND_CREATE_PROJECT_RUN_COMPLETED = 'Completed creating limis project: "{}".'
COMMAND_CREATE_PROJECT_RUN_ERROR = 'Error creating project in directory: "{}".\nError Message: {}'
COMMAND_CREATE_PROJECT_RUN_STARTED = 'Creating limis project: "{}".'
COMMAND_CREATE_SERVICE_RUN_COMPLETED = 'Completed creating limis service: "{}".'
COMMAND_CREATE_SERVICE_RUN_ERROR = 'Error creating service in directory: "{}".\nError Message: {}'
COMMAND_CREATE_SERVICE_RUN_STARTED = 'Creating limis service: "{}".'
COMMAND_LINE_INTERFACE_COMMAND_REQUIRED = 'Error: Command required, none specified.\n\nValid commands:'
COMMAND_LINE_INTERFACE_HELP_COMMAND = '{} - {}'
COMMAND_LINE_INTERFACE_RUN_INVALID_ARGUMENTS = 'Error: Invalid arguments.\n\nValid arguments:'
COMMAND_LINE_INTERFACE_RUN_UNKNOWN_COMMAND = 'Error: "{}" is not a valid command.'
COMMAND_SERVER_INVALID_PORT = 'Error: "{}" is not a valid port.'
COMMAND_SERVER_INVALID_ROOT_SERVICES = 'Error: Root services not properly defined.'
COMMAND_INVALID_ARGUMENT = 'Error: invalid argument.'
COMMAND_UNKNOWN_ARGUMENT = 'Error: "{}" is not a valid argument.'
COMMAND_VERSION = 'limis - {}'
|
class Solution:
def rob(self, nums):
robbed, notRobbed = 0, 0
for i in nums:
robbed, notRobbed = notRobbed + i, max(robbed, notRobbed)
return max(robbed, notRobbed)
|
# Common package prefixes, in the order we want to check for them
_PREFIXES = (".com.", ".org.", ".net.", ".io.")
# By default bazel computes the name of test classes based on the
# standard Maven directory structure, which we may not always use,
# so try to compute the correct package name.
def get_package_name():
pkg = native.package_name().replace("/", ".")
for prefix in _PREFIXES:
idx = pkg.find(prefix)
if idx != -1:
return pkg[idx + 1:] + "."
return ""
# Converts a file name into what is hopefully a valid class name.
def get_class_name(src):
# Strip the suffix from the source
idx = src.rindex(".")
name = src[:idx].replace("/", ".")
for prefix in _PREFIXES:
idx = name.find(prefix)
if idx != -1:
return name[idx + 1:]
pkg = get_package_name()
if pkg:
return pkg + name
return name
|
numbers = [int(i) for i in input().split(" ")]
opposite_numbers = []
for current_num in numbers:
if current_num >= 0:
opposite_numbers.append(-current_num)
elif current_num < 0:
opposite_numbers.append(abs(current_num))
print(opposite_numbers) |
def finder(data, x):
if x == 0:
return data[x]
v1 = data[x]
v2 = finder(data, x-1)
if v1 > v2:
return v1
else:
return v2
print(finder([0, -247, 341, 1001, 741, 22])) |
def extractStrictlybromanceCom(item):
'''
Parser for 'strictlybromance.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('grave robbers\' chronicles', 'grave robbers\' chronicles', 'translated'),
('haunted houses\' chronicles', 'haunted houses\' chronicles', 'translated'),
('the trial game of life', 'the trial game of life', 'translated'),
('the invasion day', 'The Invasion Day', 'translated'),
('saving unpermitted', 'saving unpermitted', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
class Solution:
def largestTimeFromDigits(self, nums: List[int]) -> str:
res=[]
def per(depth):
if depth==len(nums)-1:
res.append(nums[:])
for i in range(depth,len(nums)):
nums[i],nums[depth]=nums[depth],nums[i]
per(depth+1)
nums[i],nums[depth]=nums[depth],nums[i]
per(0)
re=""
for i in res:
if i[0]*10 +i[1]<24 and i[2]*10+i[3]<60:
re=max(re,str(i[0])+str(i[1])+':'+str(i[2])+str(i[3]))
return re
|
def fbx_references_elements(root, scene_data):
"""
Have no idea what references are in FBX currently... Just writing empty element.
"""
docs = elem_empty(root, b"References")
|
EPS = 1.0e-16
PI = 3.141592653589793
|
#all binary
allSensors = ['D021', 'D022', 'D023', 'D024',
'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032', 'M001',
'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010',
'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019',
'M020']
doorSensors = ['D021', 'D022', 'D023', 'D024',
'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032']
motionSensors = ['M001', 'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010',
'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019',
'M020']
doorFalse = "CLOSE"
doorTrue = "OPEN"
motionFalse = "OFF"
motionTrue = "ON"
allActivities = ['Bathing', 'Bed_Toilet_Transition', 'Eating', 'Enter_Home', 'Housekeeping', 'Leave_Home',
'Meal_Preparation', 'Other_Activity', 'Personal_Hygiene', 'Relax', 'Sleeping_Not_in_Bed',
'Sleeping_in_Bed', 'Take_Medicine', 'Work']
sensColToOrd = { val : i for i, val in enumerate(allSensors)}
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
timeMidn = "TimeFromMid"
class rawLabels:
time = "Time"
sensor = "Sensor"
signal = "Signal"
activity = "Activity"
correctOrder = [time, sensor, signal, activity]
rl = rawLabels
features = [rl.time, rl.signal] + allSensors + allActivities
conditionals = [timeMidn] + week
conditionalSize = len(conditionals)
colOrdConditional = {day : i+1 for i, day in enumerate(week)}
colOrdConditional[timeMidn] = 0
allBinaryColumns = [rl.signal] + allSensors + allActivities + week
correctOrder = features + conditionals
class start_stop:
def __init__(self, start, length):
self.start = start
self.stop = start + length
class pivots:
time = start_stop(0,1)
signal = start_stop(time.stop, 1)
sensors = start_stop(signal.stop, len(allSensors))
activities = start_stop(sensors.stop, len(allActivities))
features = start_stop(0, activities.stop)
timeLabels = start_stop(activities.stop, len(conditionals))
weekdays = start_stop(timeLabels.start, 1)
colOrder = [rl.time, rl.signal] + allSensors + allActivities + conditionals
ordinalColDict = {i:c for i, c in enumerate(colOrder)}
colOrdinalDict = {c:i for i, c in enumerate(colOrder)}
class home_names:
allHomes = "All Real Home"
synthetic = "Fake Home"
home1 = "H1"
home2 = "H2"
home3 = "H3" |
f = [1, 1, 2, 6, 4]
for _ in range(int(input())):
n = int(input())
if n <= 4:
print(f[n])
else:
print(0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.