content
stringlengths 7
1.05M
|
---|
"""
There are some spherical balloons spread in two-dimensional space. For each
balloon, provided input is the start and end coordinates of the horizontal
diameter. Since it's horizontal, y-coordinates don't matter, and hence the
x-coordinates of start and end of the diameter suffice. The start is always
smaller than the end.
An arrow can be shot up exactly vertically from different points along the
x-axis. A balloon with x(start) and x(end) bursts by an arrow shot at x if
x(start) ≤ x ≤ x(end). There is no limit to the number of arrows that can
be shot. An arrow once shot keeps traveling up infinitely.
Given an array points where points[i] = [x(start), x(end)], return the
minimum number of arrows that must be shot to burst all balloons.
Example:
Input: points = [[10,16],[2,8],[1,6],[7,12]]
Output: 2
Explanation: One way is to shoot one arrow for example at x = 6
(bursting the balloons [2,8] and [1,6]) and another arrow at
x = 11 (bursting the other two balloons).
Example:
Input: points = [[1,2],[3,4],[5,6],[7,8]]
Output: 4
Example:
Input: points = [[1,2],[2,3],[3,4],[4,5]]
Output: 2
Example:
Input: points = [[1,2]]
Output: 1
Example:
Input: points = [[2,3],[2,3]]
Output: 1
Constraints:
- 0 <= points.length <= 10**4
- points.length == 2
- -2**31 <= xstart < xend <= 2**31 - 1
"""
#Difficulty: Medium
#45 / 45 test cases passed.
#Runtime: 424 ms
#Memory Usage: 18.4 MB
#Runtime: 424 ms, faster than 86.48% of Python3 online submissions for Minimum Number of Arrows to Burst Balloons.
#Memory Usage: 18.4 MB, less than 97.86% of Python3 online submissions for Minimum Number of Arrows to Burst Balloons.
class Solution:
def findMinArrowShots(self, points: List[List[int]]) -> int:
i = 0
length = len(points)
points.sort(key=lambda points : points[1])
while True:
j = i + 1
if j >= length:
return length
if points[j][0] <= points[i][1]:
points.pop(j)
i -= 1
length -= 1
i += 1
|
"""
https://leetcode.com/problems/diameter-of-binary-tree/
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
"""
# Thanks to the solution provided by the problem.
# time complexity: O(n), space complexity: O(1)
# 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 diameterOfBinaryTree(self, root: TreeNode) -> int:
self.long = 1
self.dfs(root)
return self.long - 1
def dfs(self, root: TreeNode) -> int:
if root is None:
return 0
left = self.dfs(root.left)
right = self.dfs(root.right)
self.long = max(self.long, left + right + 1)
return max(left, right) + 1
|
# Som del av et spørrespill skal du lage en klasse for flervalgspørsmål.
# Et flervalgspørsmål skal ha en spørsmålstekst, ei liste med svaralternativer
# (hvert svaralternativ er en tekststreng), og et tall som sier hvilket av
# svaralternativene som er korrekt.Klassen skal ha en __str__ metode som returnerer
# en streng som inneholder spørsmålsteksten og nummerte svaralternativer
# på et lett leselig format. Klassen skal ha en sjekk_svar metode som tar
# som parameter et heltall som representerer hvilket svar brukeren velger.
# Sjekk_svar metoden skal sjekke om svaret brukeren har oppgitt er korrekt.
class Question:
def __init__(self, question: str, correct: int, alt: list,): # Klassen tar inn tre argument, og alle har definert verditype :str, :int, :list
self.question = question
self.alt = alt
self.correct = correct
def sjekk_svar(self, answer):
return answer - 1 == self.correct # kontollerar om brukeres svar == correct, (-1 fordi python byrjar å telle på 0)
def korrekt_svar_tekst(self):
return print(f'Rett svar er: {self.alt[self.correct]} \n') #returnerar rett svar
def ask(self):
print(self) #printar spørsmål og alternativ, synar __str__
inn_1 = input('Svar frå spiller 1: ') # tek inn svar frå spiller 1
inn_2 = input('Svar frå spiller 2: ') # tek inn svar frå spiller 2
try:
correct_1 = self.sjekk_svar(int(inn_1)) #sendar svar frå spiller 1 til def sjekk_svar
except:
correct_1 = False
try:
correct_2 = self.sjekk_svar(int(inn_2)) #sendar svar frå spiller 2 til def sjekk_svar
except:
correct_2 = False
print('Spiller 1: '+ ('Riktig svar!' if correct_1 else 'Feil svar')) #printar ut om svaret var rett eller feil, dersom correct_1 er True blir if utførst og 'Riktig svar' printa
if correct_1 == True:
self.poeng_1 += 1
print('Spiller 2: '+ ('Riktig svar!' if correct_2 else 'Feil svar'))
if correct_2 == True:
self.poeng_2 += 1
self.korrekt_svar_tekst() # hentar korrekt_svar_tekst, tek ikkje argument fordi den finn dei via self.
def __str__(self):
questions_str = '' # sett questions_str = lik ei blank str for at python veit kva verdi type det skal vær og for at det skal være ein verdi i variabelen
for i in range(0, len(self.alt)): # ein for loop som går frå 0 og til og med lengda av alternativ i lista alt.
questions_str += f'{i + 1}. {self.alt[i]} \n'
return f'{self.question} \n{questions_str}'
def les_fil():
with open('sporsmaalsfil.txt') as sporsmaal:
liste_retur = []
for linje in sporsmaal:
sporsmaal_liste = ''
sporsmaal_split = linje.split(':')
sporsmaal_liste = sporsmaal_split
sporsmaal_liste[2] = sporsmaal_liste[2].strip()[1:-1].split(', ')
liste_retur.append(Question(sporsmaal_liste[0],sporsmaal_liste[1],sporsmaal_liste[2]))
return liste_retur
if __name__ == "__main__":
sporsmaal_liste = les_fil()
for a in sporsmaal_liste:
print(a.ask())
|
#
# PySNMP MIB module TRANGO-APEX-TRAP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRANGO-APEX-TRAP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:19:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, NotificationType, IpAddress, Gauge32, Unsigned32, TimeTicks, iso, ModuleIdentity, Bits, Counter32, Integer32, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "NotificationType", "IpAddress", "Gauge32", "Unsigned32", "TimeTicks", "iso", "ModuleIdentity", "Bits", "Counter32", "Integer32", "ObjectIdentity")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
MibScalar, MibTable, MibTableRow, MibTableColumn, apex, NotificationType, Unsigned32, ModuleIdentity, ObjectIdentity = mibBuilder.importSymbols("TRANGO-APEX-MIB", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "apex", "NotificationType", "Unsigned32", "ModuleIdentity", "ObjectIdentity")
class DisplayString(OctetString):
pass
trangotrap = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6))
trapReboot = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 1))
if mibBuilder.loadTexts: trapReboot.setStatus('current')
trapStartUp = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 2))
if mibBuilder.loadTexts: trapStartUp.setStatus('current')
traplock = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3))
trapModemLock = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 1))
if mibBuilder.loadTexts: trapModemLock.setStatus('current')
trapTimingLock = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 2))
if mibBuilder.loadTexts: trapTimingLock.setStatus('current')
trapInnerCodeLock = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 3))
if mibBuilder.loadTexts: trapInnerCodeLock.setStatus('current')
trapEqualizerLock = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 4))
if mibBuilder.loadTexts: trapEqualizerLock.setStatus('current')
trapFrameSyncLock = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 3, 5))
if mibBuilder.loadTexts: trapFrameSyncLock.setStatus('current')
trapthreshold = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4))
trapmse = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 1))
trapMSEMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 1, 1))
if mibBuilder.loadTexts: trapMSEMinThreshold.setStatus('current')
trapMSEMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 1, 2))
if mibBuilder.loadTexts: trapMSEMaxThreshold.setStatus('current')
trapber = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 2))
trapBERMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 2, 1))
if mibBuilder.loadTexts: trapBERMinThreshold.setStatus('current')
trapBERMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 2, 2))
if mibBuilder.loadTexts: trapBERMaxThreshold.setStatus('current')
trapfer = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 3))
trapFERMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 3, 1))
if mibBuilder.loadTexts: trapFERMinThreshold.setStatus('current')
trapFERMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 3, 2))
if mibBuilder.loadTexts: trapFERMaxThreshold.setStatus('current')
traprssi = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 4))
trapRSSIMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 4, 1))
if mibBuilder.loadTexts: trapRSSIMinThreshold.setStatus('current')
trapRSSIMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 4, 2))
if mibBuilder.loadTexts: trapRSSIMaxThreshold.setStatus('current')
trapidutemp = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 5))
trapIDUTempMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 5, 1))
if mibBuilder.loadTexts: trapIDUTempMinThreshold.setStatus('current')
trapIDUTempMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 5, 2))
if mibBuilder.loadTexts: trapIDUTempMaxThreshold.setStatus('current')
trapodutemp = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 6))
trapODUTempMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 6, 1))
if mibBuilder.loadTexts: trapODUTempMinThreshold.setStatus('current')
trapODUTempMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 6, 2))
if mibBuilder.loadTexts: trapODUTempMaxThreshold.setStatus('current')
trapinport = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 7))
trapInPortUtilMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 7, 1))
if mibBuilder.loadTexts: trapInPortUtilMinThreshold.setStatus('current')
trapInPortUtilMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 7, 2))
if mibBuilder.loadTexts: trapInPortUtilMaxThreshold.setStatus('current')
trapoutport = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 8))
trapOutPortUtilMinThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 8, 1))
if mibBuilder.loadTexts: trapOutPortUtilMinThreshold.setStatus('current')
trapOutPortUtilMaxThreshold = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 4, 8, 2))
if mibBuilder.loadTexts: trapOutPortUtilMaxThreshold.setStatus('current')
trapstandby = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5))
trapStandbyLinkDown = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5, 1))
if mibBuilder.loadTexts: trapStandbyLinkDown.setStatus('current')
trapStandbyLinkUp = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5, 2))
if mibBuilder.loadTexts: trapStandbyLinkUp.setStatus('current')
trapSwitchover = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 5, 3))
if mibBuilder.loadTexts: trapSwitchover.setStatus('current')
trapeth = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6))
trapethstatus = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1))
trapEth1StatusUpdate = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 1))
if mibBuilder.loadTexts: trapEth1StatusUpdate.setStatus('current')
trapEth2StatusUpdate = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 2))
if mibBuilder.loadTexts: trapEth2StatusUpdate.setStatus('current')
trapEth3StatusUpdate = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 3))
if mibBuilder.loadTexts: trapEth3StatusUpdate.setStatus('current')
trapEth4StatusUpdate = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 6, 1, 4))
if mibBuilder.loadTexts: trapEth4StatusUpdate.setStatus('current')
trapDownShift = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 8))
if mibBuilder.loadTexts: trapDownShift.setStatus('current')
trapRapidPortShutdown = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 9))
if mibBuilder.loadTexts: trapRapidPortShutdown.setStatus('current')
trapRPSPortUp = NotificationType((1, 3, 6, 1, 4, 1, 5454, 1, 60, 6, 10))
if mibBuilder.loadTexts: trapRPSPortUp.setStatus('current')
mibBuilder.exportSymbols("TRANGO-APEX-TRAP-MIB", trapber=trapber, trapEth3StatusUpdate=trapEth3StatusUpdate, DisplayString=DisplayString, trapFERMinThreshold=trapFERMinThreshold, trapStandbyLinkDown=trapStandbyLinkDown, trapInPortUtilMinThreshold=trapInPortUtilMinThreshold, trapMSEMinThreshold=trapMSEMinThreshold, trapRSSIMaxThreshold=trapRSSIMaxThreshold, traprssi=traprssi, trapStandbyLinkUp=trapStandbyLinkUp, trapIDUTempMinThreshold=trapIDUTempMinThreshold, trapRapidPortShutdown=trapRapidPortShutdown, trangotrap=trangotrap, trapStartUp=trapStartUp, trapMSEMaxThreshold=trapMSEMaxThreshold, trapSwitchover=trapSwitchover, traplock=traplock, trapethstatus=trapethstatus, trapEth2StatusUpdate=trapEth2StatusUpdate, trapodutemp=trapodutemp, trapinport=trapinport, trapReboot=trapReboot, trapthreshold=trapthreshold, trapmse=trapmse, trapEth4StatusUpdate=trapEth4StatusUpdate, trapIDUTempMaxThreshold=trapIDUTempMaxThreshold, trapFrameSyncLock=trapFrameSyncLock, trapOutPortUtilMinThreshold=trapOutPortUtilMinThreshold, trapInnerCodeLock=trapInnerCodeLock, trapfer=trapfer, trapTimingLock=trapTimingLock, trapFERMaxThreshold=trapFERMaxThreshold, trapstandby=trapstandby, trapModemLock=trapModemLock, trapInPortUtilMaxThreshold=trapInPortUtilMaxThreshold, trapOutPortUtilMaxThreshold=trapOutPortUtilMaxThreshold, trapoutport=trapoutport, trapODUTempMinThreshold=trapODUTempMinThreshold, trapDownShift=trapDownShift, trapBERMinThreshold=trapBERMinThreshold, trapRPSPortUp=trapRPSPortUp, trapEqualizerLock=trapEqualizerLock, trapeth=trapeth, trapRSSIMinThreshold=trapRSSIMinThreshold, trapEth1StatusUpdate=trapEth1StatusUpdate, trapidutemp=trapidutemp, trapODUTempMaxThreshold=trapODUTempMaxThreshold, trapBERMaxThreshold=trapBERMaxThreshold)
|
"""
District Mapping
================
Defines the algorithms that perform the mapping from precincts to districts.
"""
|
print('Digite um número inteiro positivo de três dígitos (100 a 999), para gerar o número invertido')
num = int(input('Número: '))
num = str(num)
reverso = num[::-1]
print(f'O número ao contrário de: {num} é: {reverso}') |
# -*- coding: utf-8 -*-
i = 1
for x in range(60, -1, -5):
print('I={} J={}'.format(i, x))
i += 3
|
def process(N):
temp = str(N)
temp = temp.replace('4','2')
res1 = int(temp)
res2 = N-res1
return res1,res2
T = int(input())
for t in range(T):
N = int(input())
res1,res2 = process(N)
print('Case #{}: {} {}'.format(t+1,res1,res2)) |
class T:
WORK_REQUEST = 1
WORK_REPLY = 2
REDUCE = 3
BARRIER = 4
TOKEN = 7
class Tally:
total_dirs = 0
total_files = 0
total_filesize = 0
total_stat_filesize = 0
total_symlinks = 0
total_skipped = 0
total_sparse = 0
max_files = 0
total_nlinks = 0
total_nlinked_files = 0
total_0byte_files = 0
devfile_cnt = 0
devfile_sz = 0
spcnt = 0 # stripe cnt account per process
# ZFS
total_blocks = 0
class G:
ZERO = 0
ABORT = -1
WHITE = 50
BLACK = 51
NONE = -99
TERMINATE = -100
MSG = 99
MSG_VALID = True
MSG_INVALID = False
fmt1 = '%(asctime)s - %(levelname)s - %(rank)s:%(filename)s:%(lineno)d - %(message)s'
fmt2 = '%(asctime)s - %(rank)s:%(filename)s:%(lineno)d - %(message)s'
bare_fmt = '%(name)s - %(levelname)s - %(message)s'
mpi_fmt = '%(name)s - %(levelname)s - %(rank)s - %(message)s'
bare_fmt2 = '%(message)s'
str = {WHITE: "white", BLACK: "black", NONE: "not set", TERMINATE: "terminate",
ABORT: "abort", MSG: "message"}
KEY = "key"
VAL = "val"
logger = None
logfile = None
loglevel = "warn"
use_store = False
fix_opt = False
preserve = False
DB_BUFSIZE = 10000
memitem_threshold = 100000
tempdir = None
total_chunks = 0
rid = None
chk_file = None
chk_file_db = None
totalsize = 0
src = None
dest = None
args_src = None
args_dest = None
resume = None
reduce_interval = 30
reduce_enabled = False
verbosity = 0
am_root = False
copytype = 'dir2dir'
# Lustre file system
fs_lustre = None
lfs_bin = None
stripe_threshold = None
b0 = 0
b4k = 4 * 1024
b8k = 8 * 1024
b16k = 16 * 1024
b32k = 32 * 1024
b64k = 64 * 1024
b128k = 128 * 1024
b256k = 256 * 1024
b512k = 512 * 1024
b1m = 1024 * 1024
b2m = 2 * b1m
b4m = 4 * b1m
b8m = 8 * b1m
b16m = 16 * b1m
b32m = 32 * b1m
b64m = 64 * b1m
b128m = 128 * b1m
b256m = 256 * b1m
b512m = 512 * b1m
b1g = 1024 * b1m
b4g = 4 * b1g
b16g = 16 * b1g
b64g = 64 * b1g
b128g = 128 * b1g
b256g = 256 * b1g
b512g = 512 * b1g
b1tb = 1024 * b1g
b4tb = 4 * b1tb
FSZ_BOUND = 64 * b1tb
# 25 bins
bins = [b0, b4k, b8k, b16k, b32k, b64k, b128k, b256k, b512k,
b1m, b2m, b4m, b16m, b32m, b64m, b128m, b256m, b512m,
b1g, b4g, b64g, b128g, b256g, b512g, b1tb, b4tb]
# 17 bins, the last bin is special
# This is error-prone, to be refactored.
# bins_fmt = ["B1_000k_004k", "B1_004k_008k", "B1_008k_016k", "B1_016k_032k", "B1_032k_064k", "B1_064k_256k",
# "B1_256k_512k", "B1_512k_001m",
# "B2_001m_004m", "B2_m004_016m", "B2_016m_512m", "B2_512m_001g",
# "B3_001g_100g", "B3_100g_256g", "B3_256g_512g",
# "B4_512g_001t",
# "B5_001t_up"]
# GPFS
gpfs_block_size = ("256k", "512k", "b1m", "b4m", "b8m", "b16m", "b32m")
gpfs_block_cnt = [0, 0, 0, 0, 0, 0, 0]
gpfs_subs = (b256k/32, b512k/32, b1m/32, b4m/32, b8m/32, b16m/32, b32m/32)
dev_suffixes = [".C", ".CC", ".CU", ".H", ".CPP", ".HPP", ".CXX", ".F", ".I", ".II",
".F90", ".F95", ".F03", ".FOR", ".O", ".A", ".SO", ".S",
".IN", ".M4", ".CACHE", ".PY", ".PYC"]
|
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# 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.
"""Implementation of the `swift_c_module` rule."""
load(":swift_common.bzl", "swift_common")
load(":utils.bzl", "merge_runfiles")
def _swift_c_module_impl(ctx):
module_map = ctx.file.module_map
deps = ctx.attr.deps
cc_infos = [dep[CcInfo] for dep in deps]
data_runfiles = [dep[DefaultInfo].data_runfiles for dep in deps]
default_runfiles = [dep[DefaultInfo].default_runfiles for dep in deps]
if cc_infos:
cc_info = cc_common.merge_cc_infos(cc_infos = cc_infos)
compilation_context = cc_info.compilation_context
else:
cc_info = None
compilation_context = cc_common.create_compilation_context()
providers = [
# We must repropagate the dependencies' DefaultInfos, otherwise we
# will lose runtime dependencies that the library expects to be
# there during a test (or a regular `bazel run`).
DefaultInfo(
data_runfiles = merge_runfiles(data_runfiles),
default_runfiles = merge_runfiles(default_runfiles),
files = depset([module_map]),
),
swift_common.create_swift_info(
modules = [
swift_common.create_module(
name = ctx.attr.module_name,
clang = swift_common.create_clang_module(
compilation_context = compilation_context,
module_map = module_map,
# TODO(b/142867898): Precompile the module and place it
# here.
precompiled_module = None,
),
),
],
),
]
if cc_info:
providers.append(cc_info)
return providers
swift_c_module = rule(
attrs = {
"module_map": attr.label(
allow_single_file = True,
doc = """\
The module map file that should be loaded to import the C library dependency
into Swift.
""",
mandatory = True,
),
"module_name": attr.string(
doc = """\
The name of the top-level module in the module map that this target represents.
A single `module.modulemap` file can define multiple top-level modules. When
building with implicit modules, the presence of that module map allows any of
the modules defined in it to be imported. When building explicit modules,
however, there is a one-to-one correspondence between top-level modules and
BUILD targets and the module name must be known without reading the module map
file, so it must be provided directly. Therefore, one may have multiple
`swift_c_module` targets that reference the same `module.modulemap` file but
with different module names and headers.
""",
mandatory = True,
),
"deps": attr.label_list(
allow_empty = False,
doc = """\
A list of C targets (or anything propagating `CcInfo`) that are dependencies of
this target and whose headers may be referenced by the module map.
""",
mandatory = True,
providers = [[CcInfo]],
),
},
doc = """\
Wraps one or more C targets in a new module map that allows it to be imported
into Swift to access its C interfaces.
The `cc_library` rule in Bazel does not produce module maps that are compatible
with Swift. In order to make interop between Swift and C possible, users have
one of two options:
1. **Use an auto-generated module map.** In this case, the `swift_c_module`
rule is not needed. If a `cc_library` is a direct dependency of a
`swift_{binary,library,test}` target, a module map will be automatically
generated for it and the module's name will be derived from the Bazel target
label (in the same fashion that module names for Swift targets are derived).
The module name can be overridden by setting the `swift_module` tag on the
`cc_library`; e.g., `tags = ["swift_module=MyModule"]`.
2. **Use a custom module map.** For finer control over the headers that are
exported by the module, use the `swift_c_module` rule to provide a custom
module map that specifies the name of the module, its headers, and any other
module information. The `cc_library` targets that contain the headers that
you wish to expose to Swift should be listed in the `deps` of your
`swift_c_module` (and by listing multiple targets, you can export multiple
libraries under a single module if desired). Then, your
`swift_{binary,library,test}` targets should depend on the `swift_c_module`
target, not on the underlying `cc_library` target(s).
NOTE: Swift at this time does not support interop directly with C++. Any headers
referenced by a module map that is imported into Swift must have only C features
visible, often by using preprocessor conditions like `#if __cplusplus` to hide
any C++ declarations.
""",
implementation = _swift_c_module_impl,
)
|
class ProgramError(Exception):
"""Generic exception class for errors in this program."""
pass
class PluginError(ProgramError):
pass
class NoOptionError(ProgramError):
pass
class ExtCommandError(ProgramError):
pass
|
''' 23. Faça um programa que receba o valor do salário mínimo, o turno de trabalho (M
— matutino; V — vespertino; ou N — noturno), a categoria (O — operário; G —
gerente) e o número de horas trabalhadas no mês de um funcionário. Suponha a
digitação apenas de dados válidos e, quando houver digitação de letras, utilize
maiúsculas. Calcule e mostre:
■ O coeficiente do salário, de acordo com a tabela a seguir.
Turno de trabalho Valor do coeficiente
M - matutino 10% do salário mínimo
V - Vespertino 15% do salário mínimo
N - Noturno 12% do salário mínimo
■ O valor do salário bruto, ou seja, o número de horas trabalhadas multiplicado pelo
valor do coeficiente do salário.
■ O imposto, de acordo com a tabela a seguir.
Categoria Salário Bruto Imposto sobre o salário bruto
O - Operário >= R$ 300,00 5%
O - Operário < R$ 300,00 3%
G - Gerente >= R$ 400,00 6%
G - Gerente < R$ 400,00 4%
■ A gratificação, de acordo com as regras a seguir.
Se o funcionário preencher todos os requisitos a seguir, sua gratificação será de
R$ 50,00; caso contrário, será de R$ 30,00. Os requisitos são:
Turno: Noturno
Número de horas trabalhadas: Superior a 80 horas
■ O auxílio alimentação, de acordo com as seguintes regras.
Se o funcionário preencher algum dos requisitos a seguir, seu auxílio alimentação será
de um terço do seu salário bruto; caso contrário, será de metade do seu salário bruto.
Os requisitos são:
Categoria: Operário
Coeficiente do salário: < = 25
■ O salário líquido, ou seja, salário bruto menos imposto mais gratificação mais auxílio
alimentação.
■ A classificação, de acordo com a tabela a seguir:
Salário líquido Mensagem
Menor que R$ 350,00 Mal remunerado
Entre R$ 350,00 e R$ 600,00 Normal
Maior que R$ 600,00 Bem remunerado ''' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/12/15 11:26
# @Author : glacier
# @Site : 二进制计算
# @File : binary_array_to_number.py
# @Software: PyCharm Edu
# def binary_array_to_number(arr):
# sum = 0
# index = len(arr)-1
# i = 0
# while(index >= 0):
# sum += mul(arr[i],index)
# i += 1
# index -=1
# print(sum)
#
# def mul(index,arg2):
# print(index,arg2)
# for i in range(arg2):
# index = index * 2
# return index
def binary_array_to_number(arr):
# return int("".join(map(str,arr)),2)
print("".join(map(str,arr)),2)
binary_array_to_number([0,0,1,1])
|
# Types
Symbol = str # A Lisp Symbol is implemented as a Python str
List = list # A Lisp List is implemented as a Python list
Number = (int, float) # A Lisp Number is implemented as a Python int or float
# Exp = Union[Symbol, Exp]
def atom(token):
"Numbers become numbers; every other token is a symbol."
try:
return int(token)
except ValueError:
try:
return float(token)
except ValueError:
return Symbol(token)
|
def GetInfoMsg():
infoMsg = "This python snippet is triggered by the 'cmd' property.\r\n"
infoMsg += "Any command line may be triggered with the 'cmd' property.\r\n"
return infoMsg
if __name__ == "__main__":
print(GetInfoMsg()) |
def shift_rect(rect, direction, distance=48):
if direction == 'left':
rect.left -= distance
elif direction == 'right':
rect.left += distance
elif direction == 'up':
rect.top -= distance
elif direction == 'down':
rect.top += distance
return rect
|
"""
Desafio 016
Problema: Crie um programa que leia um número Real qualquer
pelo teclado e mostre na tela a sua porção Inteira."""
n = float(input('Digite um valor:'))
print(f'O número {n} tem a parte inteira {int(n)}')
|
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 6 17:11:11 2018
@author: Haider Raheem
"""
a= float(input("Type a : "))
b= float(input("Type b : "))
c= float(input("Type c : "))
x= (a*b)+(b*c)+(c*a)
y= (a+b+c)
r= x/y
print( )
print("The result of the calculation is {0:.2f}".format(r)) |
'''Crie um programa que leia varios numeros inteiros
o programa so vai parar qunado o usuario digitar 999
no final mostre a soma entre eles e quanto foram digitados'''
soma = total = 0
while True:
valor = int(input('## 999 para parar ###\n'
'Digite um valor: '))
if valor == 999:
break
total += 1
soma += valor
print(f'Vc digitou {total} valores e a soma entre eles é {soma}') |
# Programa Principal
def teste():
x = 8
print(f'Na função teste, n vale {n}')
print(f'Na função teste x vale {x}')
n = 2
print(f'No programa principal, n vale {n}')
teste()
print(f'No programa principal, x vale {x}')
|
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ObjectStatusEnum(object):
"""Implementation of the 'ObjectStatus' enum.
Specifies the status of an object during a Restore Task.
'kFilesCloned' indicates that the cloning has completed.
'kFetchedEntityInfo' indicates that information about the object was
fetched from the primary source.
'kVMCreated' indicates that the new VM was created.
'kRelocationStarted' indicates that restoring to a different
resource pool has started.
'kFinished' indicates that the Restore Task has finished.
Whether it was successful or not is indicated by the error code that
that is stored with the Restore Task.
'kAborted' indicates that the Restore Task was aborted before
trying to restore this object. This can happen if the
Restore Task encounters a global error.
For example during a 'kCloneVMs' Restore Task, the datastore
could not be mounted. The entire Restore Task is aborted
before trying to create VMs on the primary source.
'kDataCopyStarted' indicates that the disk copy is started.
'kInProgress' captures a generic in-progress state and can be used by
restore
operations that don't track individual states.
Attributes:
KFILESCLONED: TODO: type description here.
KFETCHEDENTITYINFO: TODO: type description here.
KVMCREATED: TODO: type description here.
KRELOCATIONSTARTED: TODO: type description here.
KFINISHED: TODO: type description here.
KABORTED: TODO: type description here.
KDATACOPYSTARTED: TODO: type description here.
KINPROGRESS: TODO: type description here.
"""
KFILESCLONED = 'kFilesCloned'
KFETCHEDENTITYINFO = 'kFetchedEntityInfo'
KVMCREATED = 'kVMCreated'
KRELOCATIONSTARTED = 'kRelocationStarted'
KFINISHED = 'kFinished'
KABORTED = 'kAborted'
KDATACOPYSTARTED = 'kDataCopyStarted'
KINPROGRESS = 'kInProgress'
|
# 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 getLonelyNodes(self, root: TreeNode) -> List[int]:
lonely_nodes = []
def dfs(node, is_lonely):
if node is None:
return
if is_lonely:
lonely_nodes.append(node.val)
if (node.left is None) ^ (node.right is None):
is_lonely = True
else:
is_lonely = False
dfs(node.left, is_lonely)
dfs(node.right, is_lonely)
dfs(root, False)
return lonely_nodes |
# -*- coding: utf-8 -*-
__title__ = "flloat"
__description__ = "A Python implementation of the FLLOAT library."
__url__ = "https://github.com/marcofavorito/flloat.git"
__version__ = "1.0.0a0"
__author__ = "Marco Favorito"
__author_email__ = "marco.favorito@gmail.com"
__license__ = "MIT license"
__copyright__ = "2019 Marco Favorito"
|
class Solution:
def rotatedDigits(self, N: 'int') -> 'int':
result = 0
for nr in range(1, N + 1):
ok = False
for digit in str(nr):
if digit in '347':
break
if digit in '6952':
ok = True
else:
result += int(ok)
return result
|
#--------------------------------------------------------------------------------
# SoCaTel - Backend data storage API endpoints docker container
# These tokens are needed for database access.
#--------------------------------------------------------------------------------
#===============================================================================
# SoCaTel Knowledge Base Deployment
#===============================================================================
# The following are the pre-defined names of elasticsearch indices for the SoCaTel project which
# host data shared with the front-end.
elastic_user_index = "so_user"
elastic_group_index = "so_group"
elastic_organisation_index = "so_organisation"
elastic_service_index = "so_service"
elastic_host = "<insert_elastic_host>" # e.g. "127.0.0.1"
elastic_port = "9200" # Default Elasticsearch port, change accordingly
elastic_user = "<insert_elasticsearch_username>"
elastic_passwd = "<insert_elasticsearch_password>"
#===============================================================================
#===============================================================================
# Linked Pipes ETL Configuration
#===============================================================================
# The following correspond to the URLs corresponding to the linked pipes executions,
# which need to be setup beforehand. They are set to localhost, change according to deployment details
path = "http://127.0.0.1:32800/resources/executions"
user_pipeline = "http://127.0.0.1:32800/resources/pipelines/1578586195746"
group_pipeline = "http://127.0.0.1:32800/resources/pipelines/1578586045942"
organisation_pipeline = "http://127.0.0.1:32800/resources/pipelines/1575531753483"
service_pipeline = "http://127.0.0.1:32800/resources/pipelines/1565080262463"
#===============================================================================
|
x1 = 1
y1 = 0
x2 = 0
y2 = -2
m1 = (y2 / x1)
x1 = 2
y1 = 2
x2 = 6
y2 = 10
m2 = (y2 - y1 / x2 - x1)
diff = m1 - m2
print(f'Diff of 8 and 9: {diff:.2f}') # 10 |
# https://www.codechef.com/problems/COPS
for T in range(int(input())):
M,x,y=map(int,input().split())
m,a = list(map(int,input().split())),list(range(1,101))
for i in m:
for j in range(i-x*y,i+1+x*y):
if(j in a): a.remove(j)
print(len(a)) |
# -*- coding: utf-8 -*-
"""
wordpress
~~~~
tamper for wordpress
:author: LoRexxar <LoRexxar@gmail.com>
:homepage: https://github.com/LoRexxar/Kunlun-M
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 LoRexxar. All rights reserved
"""
wordpress = {
"esc_url": [1000, 10001, 10002],
"esc_js": [1000, 10001, 10002],
"esc_html": [1000, 10001, 10002],
"esc_attr": [1000, 10001, 10002],
"esc_textarea": [1000, 10001, 10002],
"tag_escape": [1000, 10001, 10002],
"esc_sql": [1004, 1005, 1006],
"_real_escape": [1004, 1005, 1006],
}
wordpress_controlled = [] |
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: a ListNode
@param k: An integer
@return: a ListNode
@ O(n) time | O(1) space
"""
def reverseKGroup(self, head, k):
dummy = jump = ListNode(0)
dummy.next = left = right = head
while True:
count = 0
while right and count < k: # use r to locate the range
right = right.next
count += 1
if count == k: # if size k satisfied, reverse the inner linked list
pre = right
cur = left
for _ in range(k):
cur.next = pre
cur = cur.next
pre = cur # standard reversing
jump.next = pre
jump = left
left = right # connect two k-groups
else:
return dummy.next
'''
def reverseList(self, head):
prev = None
curr = head
while curr:
next = curr.next
curr.next = prev
prev = curr
curr = next
return prev
''' |
# -*- coding: utf-8 -*-
"""
Wrapper class for Bluetooth LE servers returned from calling
:py:meth:`bleak.discover`.
Created on 2018-04-23 by hbldh <henrik.blidh@nedomkull.com>
"""
class BLEDevice(object):
"""A simple wrapper class representing a BLE server detected during
a `discover` call.
- When using Windows backend, `details` attribute is a
`Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisement` object.
- When using Linux backend, `details` attribute is a
string path to the DBus device object.
- When using macOS backend, `details` attribute will be
something else.
"""
def __init__(self, address, name, details=None, uuids=[], manufacturer_data={}):
self.address = address
self.name = name if name else "Unknown"
self.details = details
self.uuids = uuids
self.manufacturer_data = manufacturer_data
def __str__(self):
return "{0}: {1}".format(self.address, self.name)
|
#
# Hubblemon - Yet another general purpose system monitor
#
# Copyright 2015 NAVER Corp.
#
# 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 jquery:
def __init__(self):
self.scripts = []
def render(self):
pass
def autocomplete(self, id):
ret = jquery_autocomplete(id)
self.scripts.append(ret)
return ret
def button(self, id):
ret = jquery_button(id)
self.scripts.append(ret)
return ret
def selectable(self, id):
ret = jquery_selectable(id)
self.scripts.append(ret)
return ret
def radio(self, id):
ret = jquery_radio(id)
self.scripts.append(ret)
return ret
class jscript:
def __init__(self, action):
self.action = action
def render(self):
js_template = self.get_js_template()
return js_template % (self.action)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
%s;
});
</script>
'''
return js_template
class jqueryui:
def __init__(self, id):
self.id = id
self.target = None
def val(self, v = None):
if v is None:
return "$('#%s').val()" % (self.id)
else:
return "$('#%s').val(%s)" % (self.id, v)
def val_str(self, v = None):
if v is None:
return "$('#%s').val()" % (self.id)
else:
return "$('#%s').val('%s')" % (self.id, v)
def text(self, v = None):
if v is None:
return "$('#%s').text()" % (self.id)
else:
return "$('#%s').text(%s)" % (self.id, v)
def text_str(self, v = None):
if v is None:
return "$('#%s').text()" % (self.id)
else:
return "$('#%s').text('%s')" % (self.id, v)
class jquery_autocomplete(jqueryui):
def set(self, source, action):
self.source = source
self.action = action
def render(self):
raw_data = self.source.__repr__()
js_template = self.get_js_template()
return js_template % (self.id, raw_data, self.action, self.id)
def source(self, url):
return "$('#%s').autocomplete('option', 'source', %s);" % (self.id, url)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
$('#%s').autocomplete({
source: %s,
minLength: 0,
select: function( event, ui ) {
%s;
return false;
}
}).focus(function(){
$(this).autocomplete('search', $(this).val())});
});
</script>
<input type="text" id="%s">
'''
return js_template
# TODO
class jquery_selectable(jqueryui):
def __init__(self, id):
self.id = id
self.select_list = []
def push_item(self, item):
self.select_list.append(item)
def render(self):
select_list = ''
for item in self.select_list:
select_list += "<li class='ui-widget-content'>%s</li>\n" % item
js_template = self.get_js_template()
id = self.id
return js_template % (id, id, id, id, id, select_list)
def get_js_template(self):
js_template = '''
<style>
#%s .ui-selecting { background: #FECA40; }
#%s .ui-selected { background: #F39814; color: white; }
#%s { list-style-type: none; margin:0; padding:0; }
.ui-widget-content { display:inline; margin: 0 0 0 0; padding: 0 0 0 0; border: 1; }
</style>
<script type="text/javascript">
$(function() {
$('#%s').selectable();
});
</script>
<ul id='%s'>
%s
</ul>
'''
return js_template
class jquery_button(jqueryui):
def __init__(self, id):
self.id = id
self.action = ''
def set_action(self, action):
self.action = action
def render(self):
js_template = self.get_js_template()
return js_template % (self.id, self.action, self.id, self.id)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
$('#%s').button().click(
function() {
%s;
}
);
});
</script>
<button id='%s' float>%s</button>
'''
return js_template
class jquery_radio(jqueryui):
def __init__(self, id):
self.id = id
self.action = ''
self.button_list = []
def push_item(self, item):
self.button_list.append(item)
def set_action(self, action):
self.action = action
def render(self):
button_list = ''
for item in self.button_list:
button_list += "<input type='radio' id='%s' name='radio'><label for='%s'>%s</label>" % (item, item, item)
js_template = self.get_js_template()
id = self.id
return js_template % (id, id, self.action, id, button_list)
def get_js_template(self):
js_template = '''
<script type="text/javascript">
$(function() {
$('#%s').buttonset();
$('#%s :radio').click(function() {
%s;
});
});
</script>
<ul id='%s' style="display:inline">
%s
</ul>
'''
return js_template
|
class DataGridViewCellStateChangedEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.DataGridView.CellStateChanged event.
DataGridViewCellStateChangedEventArgs(dataGridViewCell: DataGridViewCell,stateChanged: DataGridViewElementStates)
"""
@staticmethod
def __new__(self, dataGridViewCell, stateChanged):
""" __new__(cls: type,dataGridViewCell: DataGridViewCell,stateChanged: DataGridViewElementStates) """
pass
Cell = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Gets the System.Windows.Forms.DataGridViewCell that has a changed state.
Get: Cell(self: DataGridViewCellStateChangedEventArgs) -> DataGridViewCell
"""
StateChanged = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Gets the state that has changed on the cell.
Get: StateChanged(self: DataGridViewCellStateChangedEventArgs) -> DataGridViewElementStates
"""
|
description = 'Verify the user cannot log in if password value is missing'
pages = ['login']
def test(data):
navigate(data.env.url)
send_keys(login.username_input, 'admin')
click(login.login_button)
capture('Verify the correct error message is shown')
verify_text_in_element(login.error_list, 'Password is required')
|
#######################################################################
# Copyright (C) 2017 Shangtong Zhang(zhangshangtong.cpp@gmail.com) #
# Permission given to modify the code as long as you keep this #
# declaration at the top #
#######################################################################
class ConstantSchedule:
def __init__(self, val):
self.val = val
def __call__(self, steps=1):
return self.val
class LinearSchedule:
def __init__(self, start, end=None, steps=None):
if end is None:
end = start
steps = 1
self.inc = (end - start) / float(steps)
self.current = start
self.end = end
if end > start:
self.bound = min
else:
self.bound = max
def __call__(self, steps=1):
val = self.current
self.current = self.bound(self.current + self.inc * steps, self.end)
return val |
"""Version details for python-marketman
This file shamelessly taken from the requests library"""
__title__ = 'python-marketman'
__description__ = 'A basic Marketman.com REST API client.'
__url__ = 'https://github.com/LukasKlement/python-marketman'
__version__ = '0.1'
__author__ = 'Lukas Klement'
__author_email__ = 'lukas.klement@me.com'
__license__ = 'Apache 2.0'
__maintainer__ = 'Lukas Klement'
__maintainer_email__ = 'lukas.klement@me.com'
__keywords__ = 'python marketman marketman.com'
|
# Разработать класс IterInt, который наследует функциональность стандартного типа int, но добавляет
# возможность итерировать по цифрам числа
class IterInt(int):
pass
n = IterInt(12346)
for digit in n:
print("digit = ", digit)
# Выведет:
# digit = 1
# digit = 2
# digit = 3
# digit = 4
# digit = 6 |
def forward(w,s,b,y):
Yhat= w * s + b
output = (Yhat-y)**2
return output, Yhat
def derivative_W(x, output, Yhat, y):
return ((2 * output) * (Yhat - y)) * x # w
def derivative_B(b, output, Yhat, y):
return ((2 * output) * (Yhat - y)) * b #bias
def main():
w = 1.0 #weight
x = 2.0 #sample
b = 1.0 #bias
y = 2.0*x #rule
learning = 1e-1
epoch = 3
for i in range(epoch+1):
output, Yhat = forward(w,x,b,y)
print("-----------------------------------------------------------------------------")
print("w:",w)
print("\tw*b:",w*x)
print("x:",x,"\t\tsum:", w*x+b)
print("\tb:",b,"\t\t\tg1:",abs(Yhat-y),"\tg2:",abs(Yhat-y)**2,"\tloss:",output)
print("\t\tY=2*x:", y)
print("-----------------------------------------------------------------------------")
if output == 0.0:
break
gw = derivative_W(x, output, Yhat, y)
gb = derivative_B(b, output, Yhat, y)
w -= learning * gw
b -= learning * gb
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
"""Top-level package for Test."""
__author__ = """Lana Maidenbaum"""
__email__ = 'lana.maidenbaum@zeel.com'
__version__ = '0.1.1'
|
"""
SpEC
~~~~~~~~~~~~~~~~~~~
Sparsity, Explainability, and Communication
:copyright: (c) 2019 by Marcos Treviso
:licence: MIT, see LICENSE for more details
"""
# Generate your own AsciiArt at:
# patorjk.com/software/taag/#f=Calvin%20S&t=SpEC
__banner__ = """
_____ _____ _____
| __|___| __| |
|__ | . | __| --|
|_____| _|_____|_____|
|_|
"""
__prog__ = "spec"
__title__ = 'SpEC'
__summary__ = 'Sparsity, Explainability, and Communication'
__uri__ = 'https://github.com/mtreviso/spec'
__version__ = '0.0.1'
__author__ = 'Marcos V. Treviso and Andre F. T. Martins'
__email__ = 'marcostreviso@gmail.com'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019 Marcos Treviso'
|
# 第一行一个*,第二行两个*........ 共十行
# 打印乘法口诀
n = 1
while n <= 10:
n1 = n
while n1:
print("*", end = "")
n1 -= 1
print()
n += 1
n2 = 1
n3 = 1
while n2 < 10:
while n3 <= n2:
print(f"{n3}*{n2}={n3*n2}",end="\t")
n3 += 1
print()
n2 += 1
n3 = 1
n4 = 0
while n4 < 40:
n5 = 0
if n4 < 20:
while n5 < n4:
print(' ',end='')
n5 += 1
print('*')
else:
n5 = 39 - n4
while n5:
print(' ',end='')
n5 -= 1
print('*')
n4 += 1
|
def banner(message, length, header='=', footer='*'):
print()
print(header * length)
print((' ' * (length//2 - len(message)//2)), message)
print(footer * length)
def banner_v2(length, footer='-'):
print(footer * length)
print()
|
# Soft-serve Damage Skin
success = sm.addDamageSkin(2434951)
if success:
sm.chat("The Soft-serve Damage Skin has been added to your account's damage skin collection.")
|
num1 = 100
num2 = 200
num3 = 300
num4 = 400
num5 = 500
mum6 = 600
num7 = 700
num8 = 800
|
# Link - https://leetcode.com/problems/implement-strstr/
"""
28. Implement strStr()
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:
Input: haystack = "", needle = ""
Output: 0
Constraints:
0 <= haystack.length, needle.length <= 5 * 104
haystack and needle consist of only lower-case English characters.
"""
class Solution:
def strStr(self, haystack: str, needle: str) -> int:
if len(needle) == 0:
return 0
else:
try:
return haystack.index(needle)
except ValueError:
return -1
|
# 短信签名
SMS_SIGN = 'demo'
# 短信验证码模板ID
SMS_VERIFICATION_CODE_TEMPLATE_ID = 'SMS_151231777'
|
def required_model(name: object, kwargs: object) -> object:
required_fields = kwargs['required_fields'] if 'required_fields' in kwargs else []
task_f = kwargs['required_task_fields'] if 'required_task_fields' in kwargs else []
proc_f = kwargs['required_proc_fields'] if 'required_proc_fields' in kwargs else []
display_name = kwargs['display_name'] if 'display_name' in kwargs else name
def f(klass):
return klass
return f |
# -*- coding: utf-8 -*-
"""
Created on 2018/9/20
@author: gaoan
"""
ORDER_NO = "order_no"
PREVIEW_ORDER = "preview_order"
PLACE_ORDER = "place_order"
CANCEL_ORDER = "cancel_order"
MODIFY_ORDER = "modify_order"
"""
账户/资产
"""
ACCOUNTS = "accounts"
ASSETS = "assets"
POSITIONS = "positions"
ORDERS = "orders"
ACTIVE_ORDERS = "active_orders" # 待成交订单
INACTIVE_ORDERS = "inactive_orders" # 已撤销订单
FILLED_ORDERS = "filled_orders" # 已成交订单
"""
合约
"""
CONTRACT = "contract"
CONTRACTS = "contracts"
"""
行情
"""
MARKET_STATE = "market_state"
ALL_SYMBOLS = "all_symbols"
ALL_SYMBOL_NAMES = "all_symbol_names"
BRIEF = "brief"
STOCK_DETAIL = "stock_detail"
TIMELINE = "timeline"
KLINE = "kline"
TRADE_TICK = "trade_tick"
QUOTE_REAL_TIME = "quote_real_time"
QUOTE_SHORTABLE_STOCKS = "quote_shortable_stocks"
QUOTE_STOCK_TRADE = "quote_stock_trade"
# 期权行情
OPTION_EXPIRATION = "option_expiration"
OPTION_CHAIN = "option_chain"
OPTION_BRIEF = "option_brief"
OPTION_KLINE = "option_kline"
OPTION_TRADE_TICK = "option_trade_tick"
# 期货行情
FUTURE_EXCHANGE = "future_exchange"
FUTURE_CONTRACT_BY_CONTRACT_CODE = "future_contract_by_contract_code"
FUTURE_CONTRACT_BY_EXCHANGE_CODE = "future_contract_by_exchange_code"
FUTURE_CONTINUOUS_CONTRACTS = "future_continuous_contracts"
FUTURE_CURRENT_CONTRACT = "future_current_contract"
FUTURE_KLINE = "future_kline"
FUTURE_REAL_TIME_QUOTE = "future_real_time_quote"
FUTURE_TICK = "future_tick"
FUTURE_TRADING_DATE = "future_trading_date"
# 公司行动, 财务数据
FINANCIAL_DAILY = 'financial_daily'
FINANCIAL_REPORT = 'financial_report'
CORPORATE_ACTION = 'corporate_action'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Unit:
def __init__(self, x, y, color, name):
self.x = x
self.y = y
self.color = color
self.name = name
self.taken = False
class OpUnit(Unit):
def __init__(self, x, y, color, name):
super().__init__(x, y, color, name)
self.blue = 0.0 |
#!/usr/bin/env python
#coding: utf-8
class Node:
def __init__(self, elem=None, next=None):
self.elem = elem
self.next = next
if __name__ == "__main__":
n1 = Node(1, None)
n2 = Node(2, None)
n1.next = n2
|
def test_check_sanity(client):
resp = client.get('/sanity')
assert resp.status_code == 200
assert 'Sanity check passed.' == resp.data.decode()
# 'list collections' tests
def test_get_api_root(client):
resp = client.get('/', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert 'keys_url' in resp_data
assert len(resp_data) == 1
assert resp_data['keys_url'][-5:] == '/keys'
def test_delete_api_root_not_allowed(client):
resp = client.delete('/', content_type='application/json')
assert resp.status_code == 405
# 'list keys' tests
def test_get_empty_keys_list(client):
resp = client.get('/keys', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert len(resp_data) == 0
def test_get_nonempty_keys_list(client, keys, add_to_keys):
add_to_keys({'key': 'babboon', 'value': 'Larry'})
add_to_keys({'key': 'bees', 'value': ['Ann', 'Joe', 'Dee']})
resp = client.get('/keys', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert isinstance(resp_data, list)
assert len(resp_data) == 2
for doc_idx in (0, 1):
for k in ('key', 'http_url'):
assert k in resp_data[doc_idx]
if resp_data[doc_idx]['key'] == 'babboon':
assert resp_data[doc_idx]['http_url'][-13:] == '/keys/babboon'
else:
assert resp_data[doc_idx]['http_url'][-10:] == '/keys/bees'
def test_delete_on_keys_not_allowed(client):
resp = client.delete('/keys', content_type='application/json')
assert resp.status_code == 405
# 'get a key' tests
def test_get_existing_key(client, keys, add_to_keys):
add_to_keys({'key': 'babboon', 'value': 'Larry'})
add_to_keys({'key': 'bees', 'value': ['Ann', 'Joe', 'Dee']})
resp = client.get('/keys/bees', content_type='application/json')
assert resp.status_code == 200
resp_data = resp.get_json()
assert isinstance(resp_data, dict)
for k in ('key', 'http_url', 'value'):
assert k in resp_data
assert resp_data['key'] == 'bees'
assert resp_data['http_url'][-10:] == '/keys/bees'
assert resp_data['value'] == ['Ann', 'Joe', 'Dee']
def test_get_nonexisting_key(client, keys):
resp = client.get('/keys/bees', content_type='application/json')
assert resp.status_code == 404
def test_post_on_a_key_not_allowed(client):
resp = client.post('/keys/bees', content_type='application/json')
assert resp.status_code == 405
# 'create a key' tests
def test_create_new_key(client, keys):
new_doc = {'key': 'oscillator', 'value': 'Colpitts'}
resp = client.post(
'/keys',
json=new_doc,
content_type='application/json'
)
assert resp.status_code == 201
resp_data = resp.get_json()
assert isinstance(resp_data, dict)
for k in ('key', 'http_url', 'value'):
assert k in resp_data
assert resp_data['key'] == new_doc['key']
assert resp_data['value'] == new_doc['value']
assert resp_data['http_url'][-16:] == '/keys/oscillator'
def test_create_duplicate_key(client, keys, add_to_keys):
new_doc = {'key': 'oscillator', 'value': 'Colpitts'}
add_to_keys(new_doc.copy())
resp = client.post(
'/keys',
json=new_doc,
content_type='application/json'
)
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == "Can't create duplicate key (oscillator)."
def test_create_new_key_missing_key(client, keys):
new_doc = {'value': 'Colpitts'}
resp = client.post(
'/keys',
json=new_doc,
content_type='application/json'
)
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == 'Please provide the missing "key" parameter!'
def test_create_new_key_missing_value(client, keys):
new_doc = {'key': 'oscillator'}
resp = client.post(
'/keys',
json=new_doc,
content_type='application/json'
)
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == 'Please provide the missing "value" ' \
'parameter!'
# 'update a key' tests
def test_update_a_key_existing(client, keys, add_to_keys):
add_to_keys({'key': 'oscillator', 'value': 'Colpitts'})
update_value = {'value': ['Pierce', 'Hartley']}
resp = client.put(
'/keys/oscillator',
json=update_value,
content_type='application/json'
)
assert resp.status_code == 204
def test_update_a_key_nonexisting(client, keys, add_to_keys):
add_to_keys({'key': 'oscillator', 'value': 'Colpitts'})
update_value = {'value': ['Pierce', 'Hartley']}
resp = client.put(
'/keys/gadget',
json=update_value,
content_type='application/json'
)
assert resp.status_code == 400
resp_data = resp.get_json()
assert 'error' in resp_data
assert resp_data['error'] == 'Update failed.'
# 'delete a key' tests
def test_delete_a_key_existing(client, keys, add_to_keys):
add_to_keys({'key': 'oscillator', 'value': 'Colpitts'})
resp = client.delete(
'/keys/oscillator',
content_type='application/json'
)
assert resp.status_code == 204
def test_delete_a_key_nonexisting(client, keys):
resp = client.delete(
'/keys/oscillator',
content_type='application/json'
)
assert resp.status_code == 404
|
dias = int(input("quantos dias voce deseja alugar o carro? "))
km = float(input("Quantos kilometros você andou? "))
pago = dias * 60 + (km * 0.15)
print("o valor do aluguel do carro foi de R$ {:.2f}" .format(pago))
|
def factorial(num):
# 재귀함수를 세울 때는 탈출 조건부터 찾는다.
if num <= 1:
return 1
return factorial(num - 1) * num
def main():
print(factorial(5))
# return 120
if __name__ == "__main__":
main() |
'''
Single perceptron can replicate a NAND gate
https://en.wikipedia.org/wiki/NAND_logic
inputs | output
0 0 1
0 1 1
1 0 1
1 1 0
'''
def dot_product(vec1,vec2):
if (len(vec1) != len(vec2)):
print("input vector lengths are not equal")
print(len(vec1))
print(len(vec2))
reslt=0
for indx in range(len(vec1)):
reslt=reslt+vec1[indx]*vec2[indx]
return reslt
def perceptron(input_binary_vector,weight_vector,bias):
reslt = dot_product(input_binary_vector,weight_vector)
if ( reslt + bias <= 0 ): # aka reslt <= threshold
output=0
else: # reslt > threshold, aka reslt + bias > 0
output=1
return output
def nand(input_binary_vector):
if (len(input_binary_vector) != 2):
print("input vector length is not 2; this is an NAND gate!")
return int(not (input_binary_vector[0] and input_binary_vector[1]))
# weight. Higher value means more important
w = [-2, -2]
bias = 3
for indx in range(4):
# input decision factors; value 0 or 1
if (indx == 0): x = [ 0, 0]
elif (indx == 1): x = [ 1, 0]
elif (indx == 2): x = [ 0, 1]
elif (indx == 3): x = [ 1, 1]
else: print("error in indx")
print("input: "+str(x[0])+", "+str(x[1]))
print("preceptron: "+str(perceptron(x,w,bias)))
print("NAND: "+str(nand(x)))
|
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
def solution(A):
# write your code in Python 3.6
dictionary = {}
for number in A:
if dictionary.get(number) == None:
dictionary[number] = 1
else:
dictionary[number] += 1
for key in dictionary.keys():
if dictionary.get(key) % 2 == 1:
return key
|
print(4+3);
print("Hello");
print('Who are you');
print('This is Pradeep\'s python program');
print(r'C:\Users\N51254\Documents\NetBeansProjects');
print("Pradeep "*5); |
# -*- coding: utf-8 -*-
def setup_argparser(parser):
"""コマンドパーサーのセットアップ。
パーサーは共有されるので、被らないように上手く調整すること。
:param parser: ``argparse.ArgumentParser`` のインスタンス。
"""
pass
def setup_app(args):
"""コマンドパース後のセットアップ。
:param args: ``parser.arg_parse()`` の戻り値。
"""
pass
def on_open(client):
"""WebSocketのコネクションが成立した時に呼ばれる。
"""
pass
def on_close(client):
"""WebSocketのコネクションが切れた時に呼ばれる。
"""
pass
def on_setup(client, data):
client.emit("print", "Hello world!")
|
class Bank():
def __init__(self):
pass
def reduce(self, source, to):
return source.reduce(to)
|
first_angle = int(input("Lütfen ilk açıyı giriniz: "))
second_angle = int(input("Lütfen ilk açıyı giriniz: "))
gelenAcilar = {first_angle, second_angle}
eskenar = {60, 60, 60}
dik = {25, 65, 90}
ikizKenar = {45, 45, 90}
cesitKenar = {120, 41, 19}
if gelenAcilar.intersection(ikizKenar):
print("ikizkenar")
elif gelenAcilar.intersection(eskenar):
print("eskenar")
elif gelenAcilar.intersection(dik):
print("dik")
elif gelenAcilar.intersection(cesitKenar):
print("cesitKenar")
"""
aci1 = input("1. Açıyı Giriniz:")
aci2 = input("2. Açıyı Giriniz:")
if (aci1 and aci2) and (aci1.isdigit() and aci2.isdigit()):
aci1,aci2 = int(aci1),int(aci2)
liste = [aci1,aci2,(180-(aci1+aci2))]
if sum(liste) == 180:
if len(set(liste)) == 2:
print("İkizkenar üçgen")
if len(set(liste)) == 3:
print("Çeşitkenar üçgen")
if 90 in liste:
print("Dik Üçgen")
if len(set(liste)) == 1:
print("Eşkenar Üçgen")
else:
print("Açı Hatası")
else:
print("Giriş Hatası")
"""
text = input("Enter text")
counter = {}
for char in text:
if char in counter.keys():
counter[char] = 0
else :
counter[char] = counter[char] + 1
print(counter)
|
"""
Solution to Word in Reverse
"""
if __name__ == '__main__':
while True:
word = input('Enter a word: ')
word = str(word)
i = len(word)
reversed_word = ''
while i > 0:
reversed_word += word[i - 1]
i -= 1
print('{reversed_word}\n'.format(reversed_word=reversed_word))
|
def convert_fizzbuzz(n: int) -> str:
s = str(n)
if n % 3 == 0 and n % 5 == 0:
s = "FizzBuzz"
if n % 3 == 0:
s = "Fizz"
if n % 5 == 0:
s = "Buzz"
return s
def fizzbuzz() -> None:
"""
1から100までの整数nに対して
* nが3の倍数かつ5の倍数の時はFizzBuzz
* nが3の倍数の時はFizz
* nが5の倍数の時はBuzz
* それ以外の時はn
を標準出力に一行ずつプリントする
"""
for i in range(100):
print(convert_fizzbuzz(i))
if __name__ == "__main__":
fizzbuzz()
|
# -*- coding: utf-8 -*-
"""
Ceci est un module avec les tests unitaires et les tests d'intégrations.
"""
|
MAX_MEMORY = 5 * 1024 * 2 ** 10 # 5 MB
BUFFER_SIZE = 1 * 512 * 2 ** 10 # 512 KB
class DataSourceInterface(object):
"""Provides a uniform API regardless of how the data should be fetched."""
def __init__(self, target, preload=False, **kwargs):
raise NotImplementedError()
@property
def is_loaded(self):
raise NotImplementedError()
def load(self):
"""
Loads the data if not already loaded.
"""
raise NotImplementedError()
def size(self, force_load=False):
"""
Returns the size of the data.
If the datasource has not loaded the data yet (see preload argument in constructor), the size is by default equal to 0.
Set force_load to True if you want to trigger data loading if not done yet.
:param boolean force_load: if set to True will force data loading if not done yet.
"""
raise NotImplementedError()
def get_reader(self):
"""
Returns an independent reader (with the read and seek methods).
The data will be automatically loaded if not done yet.
"""
raise NotImplementedError()
|
SQLALCHEMY_DATABASE_URI = 'sqlite:///database.sqlite'
SECRET_KEY = 'F12Zr47j\3yX R~X@H!jmM]Lwf/,?KT'
SAVE_FOLDER = '../../../projects'
SQLALCHEMY_TRACK_MODIFICATIONS = 'False'
PORT = '3000'
STATIC_FOLDER = '../../client/dist/static'
|
class BinaryTree:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insert_left(self, data):
if self.left is None:
self.left = BinaryTree(data)
else:
self.left = BinaryTree(data, left=self.left)
def insert_right(self, data):
if self.right is None:
self.right = BinaryTree(data)
else:
self.right = BinaryTree(data, right=self.right)
def get_left_child(self):
return self.left
def get_right_child(self):
return self.right
def set_root_value(self, new_value):
self.data = new_value
def get_root_value(self):
return self.data
def __repr__(self):
return str(self.data)
bt = BinaryTree('*')
bt.insert_left('+')
bt.insert_right('-')
# * + -
print(bt.get_root_value(), bt.get_left_child(), bt.get_right_child())
bt.set_root_value('/')
# / + -
print(bt.get_root_value(), bt.get_left_child(), bt.get_right_child())
bt.insert_left(3)
bt.insert_right(4)
# 未能达成:(3 + 4) / (7 - 2),原因是插入子节点时,只能在根节点上操作
# / 3 + None 4 None -
print(bt.get_root_value(),
bt.get_left_child(),
bt.get_left_child().get_left_child(),
bt.get_left_child().get_right_child(),
bt.get_right_child(),
bt.get_right_child().get_left_child(),
bt.get_right_child().get_right_child(),
)
|
discovery_node_rpc_url='https://ctz.solidwallet.io/api/v3'
request_data = {
"jsonrpc": "2.0",
"id": 1234,
"method": "icx_call",
"params": {
"to": "cx0000000000000000000000000000000000000000",
"dataType": "call",
"data": {
"method": "getPReps",
"params": {
"startRanking": "0x1",
"endRanking": "0xaaa"
}
}
}
}
|
# jaylin
hours = float(input("Enter hours worked: "))
rate = float(input("Enter hourly rate: "))
if (rate >= 15):
pay=(hours* rate)
print("Pay: $", pay)
else:
print("I'm sorry " + str(rate) + " is lower than the minimum wage!")
|
## 删除排序数组中的重复项
# 方法: 快慢指针 时间:O(n) 空间:O(1)
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
s = 0
for f in range(0, len(nums)):
if nums[f] != nums[s]:
s += 1
nums[s] = nums[f]
return s + 1 |
# This is a namespace package. See also:
# http://pythonhosted.org/distribute/setuptools.html#namespace-packages
# http://osdir.com/ml/python.distutils.devel/2006-08/msg00029.html
__import__('pkg_resources').declare_namespace(__name__)
|
# put your python code here
def event_time(hours, minutes, seconds):
return (hours * 3600) + (minutes * 60) + seconds
def time_difference(a, b):
return abs(a - b)
hours_1 = int(input())
minutes_1 = int(input())
seconds_1 = int(input())
hours_2 = int(input())
minutes_2 = int(input())
seconds_2 = int(input())
event_1 = event_time(hours_1, minutes_1, seconds_1)
event_2 = event_time(hours_2, minutes_2, seconds_2)
print(time_difference(event_1, event_2))
|
# buildifier: disable=module-docstring
# buildifier: disable=function-docstring-header
def detect_root(source):
"""Detects the path to the topmost directory of the 'source' outputs.
To be used with external build systems to point to the source code/tools directories.
Args:
source (Target): A filegroup of source files
Returns:
string: The relative path to the root source directory
"""
sources = source.files.to_list()
if len(sources) == 0:
return ""
root = None
level = -1
# find topmost directory
for file in sources:
file_level = _get_level(file.path)
# If there is no level set or the current file's level
# is greather than what we have logged, update the root
if level == -1 or level > file_level:
root = file
level = file_level
if not root:
fail("No root source or directory was found")
if root.is_source:
return root.dirname
# Note this code path will never be hit due to a bug upstream Bazel
# https://github.com/bazelbuild/bazel/issues/12954
# If the root is not a source file, it must be a directory.
# Thus the path is returned
return root.path
def _get_level(path):
"""Determine the number of sub directories `path` is contained in
Args:
path (string): The target path
Returns:
int: The directory depth of `path`
"""
normalized = path
# This for loop ensures there are no double `//` substrings.
# A for loop is used because there's not currently a `while`
# or a better mechanism for guaranteeing all `//` have been
# cleaned up.
for i in range(len(path)):
new_normalized = normalized.replace("//", "/")
if len(new_normalized) == len(normalized):
break
normalized = new_normalized
return normalized.count("/")
# buildifier: disable=function-docstring-header
# buildifier: disable=function-docstring-args
# buildifier: disable=function-docstring-return
def filter_containing_dirs_from_inputs(input_files_list):
"""When the directories are also passed in the filegroup with the sources,
we get into a situation when we have containing in the sources list,
which is not allowed by Bazel (execroot creation code fails).
The parent directories will be created for us in the execroot anyway,
so we filter them out."""
# This puts directories in front of their children in list
sorted_list = sorted(input_files_list)
contains_map = {}
for input in input_files_list:
# If the immediate parent directory is already in the list, remove it
if contains_map.get(input.dirname):
contains_map.pop(input.dirname)
contains_map[input.path] = input
return contains_map.values()
|
def get_config_cs2en():
config = {}
# Settings which should be given at start time, but are not, for convenience
config['the_task'] = 0
# Settings ----------------------------------------------------------------
config['allTagsSplit'] = 'allTagsSplit/' # can be 'allTagsSplit/', 'POSextra/' or ''
config['identity_init'] = True
config['early_stopping'] = False # this has no use for now
config['use_attention'] = True # if we want attention output at test time; still no effect for training
# Model related -----------------------------------------------------------
# Definition of the error function; right now only included in baseline_ets
config['error_fct'] = 'categorical_cross_entropy'
# Sequences longer than this will be discarded
config['seq_len'] = 50
# Number of hidden units in encoder/decoder GRU
config['enc_nhids'] = 100 # orig: 100
config['dec_nhids'] = 100 # orig: 100
# For the initialization of the parameters.
config['rng_value'] = 11
# Dimension of the word embedding matrix in encoder/decoder
config['enc_embed'] = 100 # orig: 300
config['dec_embed'] = 100 # orig: 300
# Where to save model, this corresponds to 'prefix' in groundhog
config['saveto'] = 'model'
# Optimization related ----------------------------------------------------
# Batch size
config['batch_size'] = 20
# This many batches will be read ahead and sorted
config['sort_k_batches'] = 12
# Optimization step rule
config['step_rule'] = 'AdaDelta'
# Gradient clipping threshold
config['step_clipping'] = 1.
# Std of weight initialization
config['weight_scale'] = 0.01
# Regularization related --------------------------------------------------
# Weight noise flag for feed forward layers
config['weight_noise_ff'] = False
# Weight noise flag for recurrent layers
config['weight_noise_rec'] = False
# Dropout ratio, applied only after readout maxout
config['dropout'] = 0.5
# Vocabulary/dataset/embeddings related ----------------------------------------------
# Corpus vocabulary pickle file
config['corpus_data'] = '/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/Corpora/corpus_voc_'
# Root directory for dataset
datadir = '/mounts/Users/cisintern/huiming/SIGMORPHON/Code/src/baseline/'
# Module name of the stream that will be used
config['stream'] = 'stream'
# Source and target vocabularies
if config['the_task'] > 1:
config['src_vocab'] = ['/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/forRnn/', '_src_voc_task' + str(config['the_task']) + '.pkl']
config['trg_vocab'] = ['/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/forRnn/', '_trg_voc_task' + str(config['the_task']) + '.pkl'] # introduce "german" or so here
else:
config['src_vocab'] = ['/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/forRnn/', '_src_voc.pkl']
config['trg_vocab'] = ['/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/forRnn/', '_trg_voc.pkl'] # introduce "german" or so here
# Source and target datasets
config['src_data'] = ['/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/forRnn/', '-task' + str(config['the_task']) + '-train_src']
config['trg_data'] = ['/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/forRnn/', '-task' + str(config['the_task']) + '-train_trg']
# Source and target vocabulary sizes, should include bos, eos, unk tokens
# This will be read at runtime from a file.
config['src_vocab_size'] = 159
config['trg_vocab_size'] = 61
# Special tokens and indexes
config['unk_id'] = 1
config['bow_token'] = '<S>'
config['eow_token'] = '</S>'
config['unk_token'] = '<UNK>'
# Validation set source file; this is the test file, because there is only a test set for two languages
config['val_set'] = ['/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/forRnn/', '-task' + str(config['the_task']) + '-test_src']
# Validation set gold file
config['val_set_grndtruth'] = ['/mounts/Users/cisintern/huiming/SIGMORPHON/Code/data/forRnn/', '-task' + str(config['the_task']) + '-test_trg']
# Print validation output to file
config['output_val_set'] = False
# Validation output file
config['val_set_out'] = config['saveto'] + '/validation_out.txt'
# Beam-size
config['beam_size'] = 12
# Path to pretrained embeddings
config['embeddings'] = ['/mounts/Users/cisintern/huiming/universal-mri/Code/_FINAL_ST_MODELS/t1_high/task2/Ens_1_model_', '_100_100']
# Timing/monitoring related -----------------------------------------------
# Maximum number of epochs
config['finish_after'] = 100
# Reload model from files if exist
config['reload'] = True
# Save model after this many updates
config['save_freq'] = 500
# Show samples from model after this many updates
config['sampling_freq'] = 50
# Show this many samples at each sampling
config['hook_samples'] = 2
# Start bleu validation after this many updates
config['val_burn_in'] = 80000
config['lang'] = None
return config
|
ALLOWED_HOSTS = ['testserver']
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': ':memory:'
}
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'iosDevCourse'
},
'local': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
'LOCATION': 'iosDevCourse'
}
}
|
#!/usr/bin/env python
"""
_Scripts_
"""
|
my_dictionary = {
'type': 'Fruits',
'name': 'Apple',
'color': 'Green',
'available': True,
'number': 25
}
print(my_dictionary)
print(my_dictionary['name'])
# searching with wrong key
print(my_dictionary['weight'])
###############################################################
# printing keys and values
for d in my_dictionary:
print(d, my_dictionary[d])
# printing values direct
for data in my_dictionary.values():
print(data)
###############################################################
# modify a value
my_dictionary['color'] = 'Red'
print(my_dictionary)
###############################################################
# inserting new item
my_dictionary['weight'] = '5k'
print(my_dictionary)
###############################################################
# deleting an item
del my_dictionary['weight']
print(my_dictionary)
###############################################################
|
vTotal = 0
i = 0
vMenorValor = 0
cont = 1
vMenorValorItem = ''
while True:
vItem = str(input('Insira o nome do produto: '))
vValor = float(input('Valor do produto: R$'))
vTotal = vTotal + vValor
if vValor >= 1000:
i = i + 1
if cont == 1:
vMenorValor = vValor
vMenorValorItem = vItem
else:
if vValor < vMenorValor:
vMenorValor = vValor
vMenorValorItem = vItem
cont = cont + 1
vAns = ' '
while vAns not in 'YyNnSs':
vAns = str(input('Deseja continuar [Y/N]? '))
if vAns in 'Nn':
break
print('-'*40)
#print('{:-^40}'.format('Fim do Programa'))
print('Fim do Programa'.center(40,'-'))
print(f'Temos {i} produto(s) custando mais que R$1000.00')
print(f'O produto mais barato foi o {vMenorValorItem} custando R${vMenorValor:.2f}')
|
# Tai Sakuma <tai.sakuma@gmail.com>
##__________________________________________________________________||
class Parallel(object):
def __init__(self, progressMonitor, communicationChannel, workingarea=None):
self.progressMonitor = progressMonitor
self.communicationChannel = communicationChannel
self.workingarea = workingarea
def __repr__(self):
name_value_pairs = (
('progressMonitor', self.progressMonitor),
('communicationChannel', self.communicationChannel),
('workingarea', self.workingarea)
)
return '{}({})'.format(
self.__class__.__name__,
', '.join(['{}={!r}'.format(n, v) for n, v in name_value_pairs]),
)
def begin(self):
self.progressMonitor.begin()
self.communicationChannel.begin()
def terminate(self):
self.communicationChannel.terminate()
def end(self):
self.progressMonitor.end()
self.communicationChannel.end()
##__________________________________________________________________||
|
"""Solution to Project Euler Problem 1
https://projecteuler.net/problem=1
"""
NUMBERS = 3, 5
MAXIMUM = 1000
def compute(*numbers, maximum=MAXIMUM):
"""Compute the sum of the multiples of `numbers` below `maximum`."""
if not numbers:
numbers = NUMBERS
multiples = tuple(set(range(0, maximum, number)) for number in numbers)
return sum(set().union(*multiples))
|
# Algorithms > Warmup > Compare the Triplets
# Compare the elements in two triplets.
#
# https://www.hackerrank.com/challenges/compare-the-triplets/problem
#
a = map(int, input().split())
b = map(int, input().split())
alice, bob = 0, 0
for i, j in zip(a, b):
if i > j:
alice += 1
elif i < j:
bob += 1
print(alice, bob)
|
# Gerard Hanlon, 30.01.2018
# A program that displays Fibonacci numbers.
def fib(n):
"""This function returns the nth Fibonacci numbers."""
i = 0 # variable i = the first fibonacci number
j = 1 # variable j = the second fibonacci number
n = n - 1 # variable n = n - 1
while n >= 0: # while n is greater than 0
i, j = j, i + j # 0, 1 = 1, 0 + 1
n = n - 1 # we want the script to add the number preceeding it
return i # return the new value of i
name = "Hanlon" # My surname
first = name[0] # The first letter of my Surname- H
last = name [-1] # The last letter of my surname- N
firstno = ord (first) # The fibonacci number for 8- H is the 8th letter in the alphabet
lastno = ord(last) # The fibonacci for number 14- N is the 14th letter in the alphabet
x = firstno + lastno # x = the final fibonacci number we are looking for- The fibonacci numbers of the first and last letters of my surname added together
ans = fib(x) # ans = the fibonacci of x
print("My surname is", name) # prints my surname
print("The first letter", first, "is number", firstno) # returns the fibonacci of the first letter of my surname
print("The last letter", last, "is number", lastno) # returns the fibonacci number of the last letter of my surname
print("Fibonacci number", x, "is", ans) # x = the total fibonacci number
|
'''
Normal Counting sort without any associated array to keep track of
Time Complexity = O(n)
Space Complexity = O(n + k)
Auxilary Space = O(k)
'''
def countingSort(a):
b = [0]*(max(a) + 1)
c = []
for i in range(len(a)):
b[a[i]] += 1
for i in range(len(b)):
if(b[i] != 0):
for j in range(b[i]):
c.append(i)
return c
|
# 创建变量,外星人为绿色
alien_color = 'green'
# 条件判断
if alien_color == 'green':
print("You get 5 points.")
elif alien_color == 'yellow':
print("\nYou get 10 points.")
else:
print("\nYou get 15 points.")
# 创建变量,外星人为黄色
alien_color = 'yellow'
# 条件判断
if alien_color == 'green':
print("You get 5 points.")
elif alien_color == 'yellow':
print("\nYou get 10 points.")
else:
print("\nYou get 15 points.")
# 创建变量,外星人为红色
alien_color = 'red'
# 条件判断
if alien_color == 'green':
print("You get 5 points.")
elif alien_color == 'yellow':
print("\nYou get 10 points.")
else:
print("\nYou get 15 points.") |
n,m=map(int,input().split())
L = [list(map(int,input().split())) for i in range(m)]
ans = 0
L.sort(key = lambda t:t[0],reverse = True)
for i in L[:-1]:
ans += max(0,n-i[0])
print(ans) |
"""
A-Z: 65-90
a-z: 97-122
"""
dic = {}
n = 0
for i in range(10):
dic[n] = str(i)
n += 1
for i in range(65, 91):
dic[n] = chr(i)
n += 1
for i in range(97, 123):
dic[n] = chr(i)
n += 1
print(dic)
|
lst = ['инженер-конструктор Игорь', 'главный бухгалтер МАРИНА', 'токарь высшего разряда нИКОЛАй', 'директор аэлита']
some_str = ''
i = 0
for elem in lst:
some_str = elem
lst[i] = some_str.split()
some_str = ''
i += 1
for i in lst:
for j in range(len(i)):
if j == len(i)-1:
some_str = i[j]
name = some_str.capitalize()
print(f'Привет, {name}!')
|
N = int(input())
def factorial(N):
if N == 0:
return 1
return N * factorial(N-1)
print(factorial(N))
|
# -*- coding:utf-8 -*-
# ---------------------------------------------
# @file Function.py
# @description Function
# @author WcJun
# @date 2020/06/20
# ---------------------------------------------
# 求两个数 n 加到 m 的和
def add(n, m):
s = 0
while n <= m:
s += n
n += 1
return s
# 求和
add = add(1, 100)
print(add)
|
class AreWeUnitTesting(object):
# no doc
Value = False
__all__ = []
|
# coding=utf-8
#
# @lc app=leetcode id=1108 lang=python
#
# [1108] Defanging an IP Address
#
# https://leetcode.com/problems/defanging-an-ip-address/description/
#
# algorithms
# Easy (85.21%)
# Likes: 66
# Dislikes: 256
# Total Accepted: 36.7K
# Total Submissions: 43.1K
# Testcase Example: '"1.1.1.1"'
#
# Given a valid (IPv4) IP address, return a defanged version of that IP
# address.
#
# A defanged IP address replaces every period "." with "[.]".
#
#
# Example 1:
# Input: address = "1.1.1.1"
# Output: "1[.]1[.]1[.]1"
# Example 2:
# Input: address = "255.100.50.0"
# Output: "255[.]100[.]50[.]0"
#
#
# Constraints:
#
#
# The given address is a valid IPv4 address.
#
#
class Solution(object):
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
result = ""
for add in address:
if add == ".":
result += "[.]"
else:
result += add
return result
|
CJ_PATH = r''
COOKIES_PATH = r''
CHAN_ID = ''
VID_ID = ''
|
class Rectangle:
def __init__(self, length, breadth, unit_cost=0):
self.length = length
self.breadth = breadth
self.unit_cost = unit_cost
def get_area(self):
return self.length * self.breadth
def calculate_cost(self):
area = self.get_area()
return area * self.unit_cost
# breadth = 120 units, length = 160 units, 1 sq unit cost = Rs 2000
r = Rectangle(160, 120, 2000)
print("Area of Rectangle: %s sq units" % (r.get_area()))
|
'''
You are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.
Example 1:
Input:
s = "barfoothefoobarman",
words = ["foo","bar"]
Output: [0,9]
Explanation: Substrings starting at index 0 and 9 are "barfoor" and "foobar" respectively.
The output order does not matter, returning [9,0] is fine too.
Example 2:
Input:
s = "wordgoodstudentgoodword",
words = ["word","student"]
Output: []
'''
class Solution(object):
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
res = []
if not s or not words or not words[0]:
return res
wdic = {}
for word in words:
if word in wdic:
wdic[word] += 1
else:
wdic[word] = 1
for i in xrange(len(s) - len(words) * len(words[0]) + 1):
tdic = {}
for j in xrange(len(words)):
tmp = s[i + j * len(words[0]): i + (j+1) * len(words[0])]
if tmp in wdic:
if tmp in tdic:
tdic[tmp] += 1
else:
tdic[tmp] = 1
if tdic[tmp] > wdic[tmp]:
break
if tdic == wdic:
res.append(i)
else:
break
return res
|
# URLs processed simultaneously
class Batch():
def __init__(self):
self._batch = 0
def set_batch(self, n_batch):
try:
self._batch = n_batch
except BaseException:
print("[ERROR] Can't set task batch number.")
def get_batch(self):
try:
return self._batch
except BaseException:
print("[ERROR] Can't get task batch number.")
|
playerFilesWin = {
"lib/avcodec-56.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/avformat-56.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/avutil-54.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/swscale-3.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/gen_files_list.py" : { "flag_deps" : True, "should_be_removed" : True },
"lib/crashrpt_lang.ini" : { "flag_deps" : True, "should_be_removed" : True },
"lib/CrashSender.exe" : { "flag_deps" : True, "should_be_removed" : True },
"lib/avcodec-57.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/avformat-57.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/avutil-55.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/swscale-4.dll" : { "flag_deps" : True, "should_be_removed" : True },
"lib/avcodec-58.dll" : { "flag_deps" : True},
"lib/avformat-58.dll" : { "flag_deps" : True},
"lib/avutil-56.dll" : { "flag_deps" : True},
"lib/swscale-5.dll" : { "flag_deps" : True},
"lib/cef.pak" : { "flag_deps" : True },
"lib/cef_100_percent.pak" : { "flag_deps" : True },
"lib/cef_200_percent.pak" : { "flag_deps" : True },
"lib/cef_extensions.pak" : { "flag_deps" : True },
"lib/chrome_elf.dll" : { "flag_deps" : True },
"lib/d3dcompiler_43.dll" : { "flag_deps" : True },
"lib/d3dcompiler_47.dll" : { "flag_deps" : True },
"lib/devtools_resources.pak" : { "flag_deps" : True },
"lib/icudtl.dat" : { "flag_deps" : True },
"lib/libcef.dll" : { "flag_deps" : True },
"lib/libEGL.dll" : { "flag_deps" : True },
"lib/libGLESv2.dll" : { "flag_deps" : True },
"lib/libGLESv1_CM.dll" : { "flag_deps" : True },
"lib/angle_util.dll" : { "flag_deps" : True },
"lib/natives_blob.bin" : { "flag_deps" : True },
"lib/snapshot_blob.bin" : { "flag_deps" : True },
"lib/v8_context_snapshot.bin" : { "flag_deps" : True },
"lib/widevinecdmadapter.dll" : { "flag_deps" : True, "should_be_removed" : True},
"lib/images/sample_app.png" : { "flag_deps" : True, "should_be_removed" : True},
"lib/locales/am.pak" : { "flag_deps" : True },
"lib/locales/ar.pak" : { "flag_deps" : True },
"lib/locales/bg.pak" : { "flag_deps" : True },
"lib/locales/bn.pak" : { "flag_deps" : True },
"lib/locales/ca.pak" : { "flag_deps" : True },
"lib/locales/cs.pak" : { "flag_deps" : True },
"lib/locales/da.pak" : { "flag_deps" : True },
"lib/locales/de.pak" : { "flag_deps" : True },
"lib/locales/el.pak" : { "flag_deps" : True },
"lib/locales/en-GB.pak" : { "flag_deps" : True },
"lib/locales/en-US.pak" : { "flag_deps" : True },
"lib/locales/es-419.pak" : { "flag_deps" : True },
"lib/locales/es.pak" : { "flag_deps" : True },
"lib/locales/et.pak" : { "flag_deps" : True },
"lib/locales/fa.pak" : { "flag_deps" : True },
"lib/locales/fi.pak" : { "flag_deps" : True },
"lib/locales/fil.pak" : { "flag_deps" : True },
"lib/locales/fr.pak" : { "flag_deps" : True },
"lib/locales/gu.pak" : { "flag_deps" : True },
"lib/locales/he.pak" : { "flag_deps" : True },
"lib/locales/hi.pak" : { "flag_deps" : True },
"lib/locales/hr.pak" : { "flag_deps" : True },
"lib/locales/hu.pak" : { "flag_deps" : True },
"lib/locales/id.pak" : { "flag_deps" : True },
"lib/locales/it.pak" : { "flag_deps" : True },
"lib/locales/ja.pak" : { "flag_deps" : True },
"lib/locales/kn.pak" : { "flag_deps" : True },
"lib/locales/ko.pak" : { "flag_deps" : True },
"lib/locales/lt.pak" : { "flag_deps" : True },
"lib/locales/lv.pak" : { "flag_deps" : True },
"lib/locales/ml.pak" : { "flag_deps" : True },
"lib/locales/mr.pak" : { "flag_deps" : True },
"lib/locales/ms.pak" : { "flag_deps" : True },
"lib/locales/nb.pak" : { "flag_deps" : True },
"lib/locales/nl.pak" : { "flag_deps" : True },
"lib/locales/pl.pak" : { "flag_deps" : True },
"lib/locales/pt-BR.pak" : { "flag_deps" : True },
"lib/locales/pt-PT.pak" : { "flag_deps" : True },
"lib/locales/ro.pak" : { "flag_deps" : True },
"lib/locales/ru.pak" : { "flag_deps" : True },
"lib/locales/sk.pak" : { "flag_deps" : True },
"lib/locales/sl.pak" : { "flag_deps" : True },
"lib/locales/sr.pak" : { "flag_deps" : True },
"lib/locales/sv.pak" : { "flag_deps" : True },
"lib/locales/sw.pak" : { "flag_deps" : True },
"lib/locales/ta.pak" : { "flag_deps" : True },
"lib/locales/te.pak" : { "flag_deps" : True },
"lib/locales/th.pak" : { "flag_deps" : True },
"lib/locales/tr.pak" : { "flag_deps" : True },
"lib/locales/uk.pak" : { "flag_deps" : True },
"lib/locales/vi.pak" : { "flag_deps" : True },
"lib/locales/zh-CN.pak" : { "flag_deps" : True },
"lib/locales/zh-TW.pak" : { "flag_deps" : True },
# "lib/localhost.pack" : {},
"lib/u2ec.dll" : { "should_be_removed" : True },
"lib/collector.dll" : { "should_be_removed" : True },
"lib/logging.dll" : {},
"lib/rtspclient.dll" : { "should_be_removed" : True },
"lib/crash_reporter.cfg" : {},
"lib/benchmark.data" : { "should_be_removed" : True },
"lib/background.ts" : { "should_be_removed" : True },
"lib/benchmark_fullhd_hi.data" : {},
"lib/benchmark_fullhd_low.data" : { "should_be_removed" : True },
"lib/benchmark_hdready_hi.data" : {},
"lib/benchmark_hdready_low.data" : { "should_be_removed" : True },
"lib/config.ini" : { "may_be_modified" : True, "may_be_removed" : True },
"quickreset.exe" : { "should_be_removed" : True },
"lib/LiquidSkyHelper.exe" : { "should_be_removed" : True },
"lib/lang_en.ini" : { "should_be_removed" : True },
"lib/render-cef.dll" : { "should_be_removed" : True },
"lib/player-cef.dll" : { "should_be_removed" : True },
"lib/render-cuda.dll" : { "should_be_removed" : True },
"lib/render-ffmpeg.dll" : {},
"lib/render-ffmpeg-hw.dll" : { "should_be_removed" : True},
"lib/usb_driver.exe" : { "should_be_removed" : True },
#default liquidsky version
"LiquidSkyClient.exe" : {},
"lib/LiquidSky.exe" : {},
"lib/usb_driver.msi" : { "should_be_removed" : True },
"lib/UsbHelper.exe" : { "should_be_removed" : True },
"lib/Vivien.exe" : { "should_be_removed" : True },
"VivienClient.exe" : { "should_be_removed" : True },
}
#if you add any new file to verizon, please make sure that it is included to main list too
playerFilesWinCast = {
"lib/usb_driver.msi" : {},
"lib/UsbHelper.exe" : {},
"lib/Vivien.exe" : {},
"VivienClient.exe" : {},
"lib/LiquidSky.exe" : { "should_be_removed" : True },
"LiquidSkyClient.exe" : { "should_be_removed" : True },
"lib/localhost1.pack" : { "should_be_removed" : True },
"lib/localhost2.pack" : { "should_be_removed" : True },
"lib/localhost3.pack" : { "should_be_removed" : True },
"lib/localhost4.pack" : { "should_be_removed" : True },
}
playerFilesMac = {
"Frameworks/Chromium Embedded Framework.framework/Chromium Embedded Framework" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/am.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/ar.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/bg.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/bn.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/ca.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/cef.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/cef_100_percent.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/cef_200_percent.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/cef_extensions.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/cs.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/da.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/de.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/devtools_resources.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/el.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/en.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/en_GB.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/es.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/es_419.lproj/locale.pak": { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/et.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/fa.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/fi.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/fil.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/fr.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/gu.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/he.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/hi.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/hr.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/hu.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/icudtl.dat" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/id.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/Info.plist" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/it.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/ja.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/kn.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/ko.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/lt.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/lv.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/ml.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/mr.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/ms.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/natives_blob.bin" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/nb.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/nl.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/pl.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/pt_BR.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/pt_PT.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/ro.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/ru.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/sk.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/sl.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/snapshot_blob.bin" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/sr.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/sv.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/sw.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/ta.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/te.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/th.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/tr.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/uk.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/vi.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/zh_CN.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/Chromium Embedded Framework.framework/Resources/zh_TW.lproj/locale.pak" : { "access_mode" : "644" },
"Frameworks/LiquidSky Helper.app/Contents/Info.plist" : { "access_mode" : "644" },
"Frameworks/LiquidSky Helper.app/Contents/MacOS/LiquidSky Helper" : { "access_mode" : "755" },
"Info.plist" : { "access_mode" : "644" },
"MacOS/libavcodec.dylib" : { "access_mode" : "644" },
"MacOS/libavformat.dylib" : { "access_mode" : "644" },
"MacOS/libavutil.dylib" : { "access_mode" : "644" },
"MacOS/libcollector.dylib" : { "access_mode" : "644", "should_be_removed" : True },
"MacOS/liblogging.dylib" : { "access_mode" : "644" },
"MacOS/libplayer-cef.dylib" : { "access_mode" : "644" },
"MacOS/librender-ffmpeg-hw.dylib" : { "access_mode" : "644" },
"MacOS/librender-ffmpeg.dylib" : { "access_mode" : "644" },
"MacOS/librtspclient.dylib" : { "access_mode" : "644" },
"MacOS/libswscale.dylib" : { "access_mode" : "644" },
"MacOS/LiquidSky" : { "access_mode" : "755", "should_be_removed" : True },
"MacOS/liquidsky-client" : { "access_mode" : "755" },
"Resources/background.ts" : { "access_mode" : "644", "should_be_removed" : True },
"Resources/benchmark_fullhd_hi.data" : { "access_mode" : "644", "should_be_removed" : True },
"Resources/benchmark_hdready_hi.data" : { "access_mode" : "644", "should_be_removed" : True },
"Resources/lang_en.ini" : { "access_mode" : "644" },
"Resources/liquidsky.icns" : { "access_mode" : "644" },
"Resources/localhost.pack" : { "access_mode" : "644" },
}
streamerFilesWin = {
"avcodec-57.dll" : { "should_be_removed" : True },
"avformat-57.dll" : { "should_be_removed" : True },
"avutil-55.dll" : { "should_be_removed" : True },
"swscale-4.dll" : { "should_be_removed" : True },
"avcodec-58.dll" : {},
"avformat-58.dll" : {},
"avutil-56.dll" : {},
"swscale-5.dll" : {},
"crashrpt_lang.ini" : {},
"CrashSender.exe" : {},
"osk-monitor.exe" : {},
"osk.exe" : {},
"sky.cfg" : { "may_be_modified" : True, "may_be_removed" : True },
"streamer-service.exe" : {},
"streamer-updater.exe" : { "should_be_removed" : True },
"update-executor.exe" : {},
"streamer.exe" : { "should_be_removed" : True },
"SkyBeam.exe" : {},
"storagetool.exe" : {},
"setuptool.exe" : {},
"vmhelper.dll" : {},
"logging.dll" : {},
"changelang.exe" : {},
"app-sender.exe" : {},
"process-monitor.exe" : {},
"webrtc-lib.dll" : {},
"lsfb.exe" : {},
}
streamerFilesWinCast = {
"usb-service.exe" : {},
}
branchIniDisabled = {
"lib/branch.ini" : { "should_be_removed" : True },
}
branchIniEnabled = {
"lib/branch.ini" : {},
}
targets = {
"player-win" : { "files" : playerFilesWin, "path" : ["buildproject", "player"], "brands" : { "cast" : playerFilesWinCast }, },
"player-mac" : { "files" : playerFilesMac, "path" : ["buildproject", "LiquidSky.app", "Contents"], "brands" : {}, },
"streamer-win" : { "files" : streamerFilesWin, "path" : ["buildproject", "streamer"], "brands" : { "cast" : streamerFilesWinCast }, },
}
|
# Hello world program to demonstrate running PYthon files
print('Hello, world!')
print('I live on a volcano!')
|
class Productivity:
def __init__(self, irradiance, hours,capacity):
self.irradiance = irradiance
self.hours = hours
self.capacity = capacity
def getUnits(self):
print(self.irradiance)
totalpower = 0
print(totalpower)
for i in self.irradiance:
power = int(self.capacity) * int(i) /1000
totalpower = totalpower+power
# units= (self.irradiance*self.area*self.hours)/1000
print(totalpower)
return totalpower
|
def create_platform_routes(server):
metrics = server._augur.metrics
|
__version__ = '0.1.7'
default_app_config = 'dynamic_databases.apps.DynamicDatabasesConfig'
|
PHYSICS_TECHS = {
"tech_databank_uplinks",
"tech_basic_science_lab_1",
"tech_curator_lab",
"tech_archeology_lab",
"tech_physics_lab_1",
"tech_physics_lab_2",
"tech_physics_lab_3",
"tech_global_research_initiative",
"tech_administrative_ai",
"tech_cryostasis_1",
"tech_cryostasis_2",
"tech_self_aware_logic",
"tech_automated_exploration",
"tech_sapient_ai",
"tech_positronic_implants",
"tech_combat_computers_1",
"tech_combat_computers_2",
"tech_combat_computers_3",
"tech_combat_computers_autonomous",
"tech_auxiliary_fire_control",
"tech_synchronized_defences",
"tech_fission_power",
"tech_fusion_power",
"tech_cold_fusion_power",
"tech_antimatter_power",
"tech_zero_point_power",
"tech_reactor_boosters_1",
"tech_reactor_boosters_2",
"tech_reactor_boosters_3",
"tech_shields_1",
"tech_shields_2",
"tech_shields_3",
"tech_shields_4",
"tech_shields_5",
"tech_shield_rechargers_1",
"tech_planetary_shield_generator",
"tech_sensors_2",
"tech_sensors_3",
"tech_sensors_4",
"tech_power_plant_1",
"tech_power_plant_2",
"tech_power_plant_3",
"tech_power_plant_4",
"tech_power_hub_1",
"tech_power_hub_2",
"tech_hyper_drive_1",
"tech_hyper_drive_2",
"tech_hyper_drive_3",
"tech_wormhole_stabilization",
"tech_gateway_activation",
"tech_gateway_construction",
"tech_jump_drive_1",
"tech_ftl_inhibitor",
"tech_matter_generator",
}
SOCIETY_TECHS = {
"tech_planetary_defenses",
"tech_eco_simulation",
"tech_hydroponics",
"tech_gene_crops",
"tech_nano_vitality_crops",
"tech_nutrient_replication",
"tech_biolab_1",
"tech_biolab_2",
"tech_biolab_3",
"tech_alien_life_studies",
"tech_colonization_1",
"tech_colonization_2",
"tech_colonization_3",
"tech_colonization_4",
"tech_colonization_5",
"tech_tomb_world_adaption",
"tech_space_trading",
"tech_frontier_health",
"tech_frontier_hospital",
"tech_tb_mountain_range",
"tech_tb_volcano",
"tech_tb_dangerous_wildlife",
"tech_tb_dense_jungle",
"tech_tb_quicksand_basin",
"tech_tb_noxious_swamp",
"tech_tb_massive_glacier",
"tech_tb_toxic_kelp",
"tech_tb_deep_sinkhole",
"tech_terrestrial_sculpting",
"tech_ecological_adaptation",
"tech_climate_restoration",
"tech_genome_mapping",
"tech_vitality_boosters",
"tech_epigenetic_triggers",
"tech_cloning",
"tech_gene_banks",
"tech_gene_seed_purification",
"tech_morphogenetic_field_mastery",
"tech_gene_tailoring",
"tech_glandular_acclimation",
"tech_genetic_resequencing",
"tech_gene_expressions",
"tech_selected_lineages",
"tech_capacity_boosters",
"tech_regenerative_hull_tissue",
"tech_doctrine_fleet_size_1",
"tech_doctrine_fleet_size_2",
"tech_doctrine_fleet_size_3",
"tech_doctrine_fleet_size_4",
"tech_doctrine_fleet_size_5",
"tech_interstellar_fleet_traditions",
"tech_refit_standards",
"tech_command_matrix",
"tech_doctrine_navy_size_1",
"tech_doctrine_navy_size_2",
"tech_doctrine_navy_size_3",
"tech_doctrine_navy_size_4",
"tech_centralized_command",
"tech_combat_training",
"tech_ground_defense_planning",
"tech_global_defense_grid",
"tech_psionic_theory",
"tech_telepathy",
"tech_precognition_interface",
"tech_psi_jump_drive_1",
"tech_galactic_ambitions",
"tech_manifest_destiny",
"tech_interstellar_campaigns",
"tech_galactic_campaigns",
"tech_planetary_government",
"tech_planetary_unification",
"tech_colonial_centralization",
"tech_galactic_administration",
"tech_galactic_markets",
"tech_subdermal_stimulation",
"tech_galactic_benevolence",
"tech_adaptive_bureaucracy",
"tech_colonial_bureaucracy",
"tech_galactic_bureaucracy",
"tech_living_state",
"tech_collective_self",
"tech_autonomous_agents",
"tech_embodied_dynamism",
"tech_neural_implants",
"tech_artificial_moral_codes",
"tech_synthetic_thought_patterns",
"tech_collective_production_methods",
"tech_resource_processing_algorithms",
"tech_cultural_heritage",
"tech_heritage_site",
"tech_hypercomms_forum",
"tech_autocurating_vault",
"tech_holographic_rituals",
"tech_consecration_fields",
"tech_transcendent_faith",
"tech_ascension_theory",
"tech_ascension_theory_apoc",
"tech_psionic_shield",
}
ENGINEERING_TECHS = {
"tech_space_exploration",
"tech_corvettes",
"tech_destroyers",
"tech_cruisers",
"tech_battleships",
"tech_titans",
"tech_corvette_build_speed",
"tech_corvette_hull_1",
"tech_corvette_hull_2",
"tech_destroyer_build_speed",
"tech_destroyer_hull_1",
"tech_destroyer_hull_2",
"tech_cruiser_build_speed",
"tech_cruiser_hull_1",
"tech_cruiser_hull_2",
"tech_battleship_build_speed",
"tech_battleship_hull_1",
"tech_battleship_hull_2",
"tech_titan_hull_1",
"tech_titan_hull_2",
"tech_starbase_1",
"tech_starbase_2",
"tech_starbase_3",
"tech_starbase_4",
"tech_starbase_5",
"tech_modular_engineering",
"tech_space_defense_station_improvement",
"tech_strike_craft_1",
"tech_strike_craft_2",
"tech_strike_craft_3",
"tech_assault_armies",
"tech_ship_armor_1",
"tech_ship_armor_2",
"tech_ship_armor_3",
"tech_ship_armor_4",
"tech_ship_armor_5",
"tech_crystal_armor_1",
"tech_crystal_armor_2",
"tech_thrusters_1",
"tech_thrusters_2",
"tech_thrusters_3",
"tech_thrusters_4",
"tech_space_defense_station_1",
"tech_defense_platform_hull_1",
"tech_basic_industry",
"tech_powered_exoskeletons",
"tech_mining_network_2",
"tech_mining_network_3",
"tech_mining_network_4",
"tech_mineral_processing_1",
"tech_mineral_processing_2",
"tech_engineering_lab_1",
"tech_engineering_lab_2",
"tech_engineering_lab_3",
"tech_robotic_workers",
"tech_droid_workers",
"tech_synthetic_workers",
"tech_synthetic_leaders",
"tech_space_construction",
"tech_afterburners_1",
"tech_afterburners_2",
"tech_assembly_pattern",
"tech_construction_templates",
"tech_mega_engineering",
}
ALL_KNOWN_TECHS = set.union(PHYSICS_TECHS, ENGINEERING_TECHS, SOCIETY_TECHS)
ASCENSION_PERKS = {
"ap_enigmatic_engineering", #: "Enigmatic Engineering",
"ap_nihilistic_acquisition", #: "Nihilistic Acquisition",
"ap_colossus", #: "Colossus",
"ap_engineered_evolution", #: "Engineered Evolution",
"ap_evolutionary_mastery", #: "Evolutionary Mastery",
"ap_the_flesh_is_weak", #: "The Flesh is Weak",
"ap_synthetic_evolution", #: "Synthetic Evolution",
"ap_mind_over_matter", #: "Mind over Matter",
"ap_transcendence", #: "Transcendence",
"ap_world_shaper", #: "World Shaper",
"ap_galactic_force_projection", #: "Galactic Force Projection",
"ap_defender_of_the_galaxy", #: "Defender of the Galaxy",
"ap_interstellar_dominion", #: "Interstellar Dominion",
"ap_grasp_the_void", #: "Grasp the Void",
"ap_eternal_vigilance", #: "Eternal Vigilance",
"ap_galactic_contender", #: "Galactic Contender",
"ap_technological_ascendancy", #: "Technological Ascendancy",
"ap_one_vision", #: "One Vision",
"ap_consecrated_worlds", #: "Consecrate Worlds",
"ap_mastery_of_nature", #: "Mastery of Nature",
"ap_imperial_prerogative", #: "Imperial Prerogative",
"ap_executive_vigor", #: "Executive Vigor",
"ap_transcendent_learning", #: "Transcendent Learning",
"ap_shared_destiny", #: "Shared Destiny",
"ap_voidborn", #: "Voidborn",
"ap_master_builders", #: "Master Builders",
"ap_galactic_wonders", #: "Galactic Wonders",
"ap_synthetic_age", #: "Synthetic Age",
"ap_machine_worlds", #: "Machine Worlds",
}
COLONIZABLE_PLANET_CLASSES_PLANETS = {
"pc_desert",
"pc_arid",
"pc_savannah",
"pc_tropical",
"pc_continental",
"pc_ocean",
"pc_tundra",
"pc_arctic",
"pc_alpine",
"pc_gaia",
"pc_nuked",
"pc_machine",
}
COLONIZABLE_PLANET_CLASSES_MEGA_STRUCTURES = {
"pc_ringworld_habitable",
"pc_habitat",
}
# Planet classes for the planetary diversity mod
# (see https://steamcommunity.com/workshop/filedetails/discussion/1466534202/3397295779078104093/)
COLONIZABLE_PLANET_CLASSES_PD_PLANETS = {
"pc_antarctic",
"pc_deadcity",
"pc_retinal",
"pc_irradiated_terrestrial",
"pc_lush",
"pc_geocrystalline",
"pc_marginal",
"pc_irradiated_marginal",
"pc_marginal_cold",
"pc_crystal",
"pc_floating",
"pc_graveyard",
"pc_mushroom",
"pc_city",
"pc_archive",
"pc_biolumen",
"pc_technoorganic",
"pc_tidallylocked",
"pc_glacial",
"pc_frozen_desert",
"pc_steppe",
"pc_hadesert",
"pc_boreal",
"pc_sandsea",
"pc_subarctic",
"pc_geothermal",
"pc_cascadian",
"pc_swamp",
"pc_mangrove",
"pc_desertislands",
"pc_mesa",
"pc_oasis",
"pc_hajungle",
"pc_methane",
"pc_ammonia",
}
COLONIZABLE_PLANET_CLASSES = (
COLONIZABLE_PLANET_CLASSES_PLANETS
| COLONIZABLE_PLANET_CLASSES_MEGA_STRUCTURES
| COLONIZABLE_PLANET_CLASSES_PD_PLANETS
)
DESTROYED_BY_WEAPONS_PLANET_CLASSES = {
"pc_shattered",
"pc_shielded",
"pc_ringworld_shielded",
"pc_habitat_shielded",
"pc_ringworld_habitable_damaged",
}
DESTROYED_BY_EVENTS_AND_CRISES_PLANET_CLASSES = {
"pc_egg_cracked",
"pc_shrouded",
"pc_ai",
"pc_infested",
"pc_gray_goo",
}
DESTROYED_PLANET_CLASSES = (
DESTROYED_BY_WEAPONS_PLANET_CLASSES | DESTROYED_BY_EVENTS_AND_CRISES_PLANET_CLASSES
)
def is_destroyed_planet(planet_class):
return planet_class in DESTROYED_PLANET_CLASSES
def is_colonizable_planet(planet_class):
return planet_class in COLONIZABLE_PLANET_CLASSES
def is_colonizable_megastructure(planet_class):
return planet_class in COLONIZABLE_PLANET_CLASSES_MEGA_STRUCTURES
LOWERCASE_WORDS = {"the", "in", "of", "for", "is", "over", "under"}
WORD_REPLACEMENT = {
"Ai": "AI",
"Ftl": "FTL",
"Tb": "Tile Blocker",
}
def convert_id_to_name(object_id: str, remove_prefix="") -> str:
words = [word for word in object_id.split("_") if word != remove_prefix]
words = [
word.capitalize() if word not in LOWERCASE_WORDS else word for word in words
]
words = [WORD_REPLACEMENT.get(word, word) for word in words]
return " ".join(words)
|
# Custom errors in classes.
class TooManyPagesReadError(ValueError):
pass
class Book:
def __init__(self, title, page_count):
self.title = title
self.page_count = page_count
self.pages_read = 0
def __repr__(self):
return (
f"<Book {self.title}, read {self.pages_read} pages out of {self.page_count}>"
)
def read(self, pages):
if self.pages_read + pages > self.page_count:
msg = f"You tried to read {self.pages_read + pages} but this book only has {self.page_count} pages."
raise TooManyPagesReadError(msg)
self.pages_read += pages
print(f"You have now read {self.pages_read} pages out of {self.page_count}")
book_1 = Book("Fluent Python", 800)
try:
book_1.read(450)
book_1.read(800)
except TooManyPagesReadError as e:
print(e)
finally:
print(book_1)
|
""" Trapping rain water: Given an array of non negative integers, they are height of bars.
Find how much water can you collect between there bars """
"""Solution: """
def rain_water(a) -> int:
n = len(a)
res = 0
for i in range(1, n-1):
lmax = a[i]
for j in range(i):
lmax = max(lmax, a[j])
rmax = a[i]
for j in range(i+1, n):
rmax = max(rmax, a[j])
res = res + (min(lmax, rmax) - a[i])
return res
def rain_water_eff(a) -> int:
n = len(a)
res = 0
lmax = [0]*n
rmax = [0]*n
lmax[0] = a[0]
for i in range(1, n):
lmax[i] = max(lmax[i-1], a[i])
rmax[n-1] = a[n-1]
for i in range(n-2, 0, -1):
rmax[i] = max(rmax[i + 1], a[i])
for i in range(1, n-1):
res = res + min(lmax[i], rmax[i]) - a[i]
return res
def main():
arr_input = [5, 0, 6, 2, 3]
a1 = rain_water_eff(arr_input)
print(a1)
a2 = rain_water(arr_input)
#print(a2)
# Using the special variable
# __name__
if __name__ == "__main__":
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.