content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
b=int(input()) x_1=b i=0 while True: a=b//10+(b%10) b=(b%10)*10+a%10 i+=1 x=b if x==x_1: break print(i)
b = int(input()) x_1 = b i = 0 while True: a = b // 10 + b % 10 b = b % 10 * 10 + a % 10 i += 1 x = b if x == x_1: break print(i)
class Stack: def __init__ (self): self.elements = [] def is_empty(self): return self.elements == [] def push(self, item): self.elements.append(item) def pop(self): return self.elements.pop() def peek(self): return self.elements[-1] def size(self): return len(self.elements)
class Stack: def __init__(self): self.elements = [] def is_empty(self): return self.elements == [] def push(self, item): self.elements.append(item) def pop(self): return self.elements.pop() def peek(self): return self.elements[-1] def size(self): return len(self.elements)
# -*- coding: utf-8 -*- # open repositories """Todo: move src for acquiring data""" 'http://www.opendoar.org/countrylist.php' better = 'http://oaister.worldcat.org/' # Should access Terms and Conditions all the time.
"""Todo: move src for acquiring data""" 'http://www.opendoar.org/countrylist.php' better = 'http://oaister.worldcat.org/'
n = int(input()) l = [] for i in range(1, n): if (i < 3): l.append(1) else: l.append(l[len(l) - 1] + l[len(l) -2]) print(i, ": ", l[i-1])
n = int(input()) l = [] for i in range(1, n): if i < 3: l.append(1) else: l.append(l[len(l) - 1] + l[len(l) - 2]) print(i, ': ', l[i - 1])
python = Runtime.createAndStart("python","Python") mouth = Runtime.createAndStart("Mouth","MouthControl") arduino = mouth.getArduino() arduino.connect('COM11') jaw = mouth.getJaw() jaw.detach() jaw.attach(arduino,11) mouth.setmouth(110,120) mouth.autoAttach = False speech = Runtime.createAndStart("Speech","AcapelaSpeech") mouth.setMouth(speech) speech.setVoice("Will") def onEndSpeaking(text): mouth.setmouth(90,120) jaw.moveTo(95) sleep(.5) mouth.setmouth(110,120) python.subscribe(speech.getName(),"publishEndSpeaking") # Start of main script speech.speakBlocking("I'm speaking a very long text to test mouth movement") speech.speakBlocking("A new sentence to test another long sentece") speech.speakBlocking("And one more")
python = Runtime.createAndStart('python', 'Python') mouth = Runtime.createAndStart('Mouth', 'MouthControl') arduino = mouth.getArduino() arduino.connect('COM11') jaw = mouth.getJaw() jaw.detach() jaw.attach(arduino, 11) mouth.setmouth(110, 120) mouth.autoAttach = False speech = Runtime.createAndStart('Speech', 'AcapelaSpeech') mouth.setMouth(speech) speech.setVoice('Will') def on_end_speaking(text): mouth.setmouth(90, 120) jaw.moveTo(95) sleep(0.5) mouth.setmouth(110, 120) python.subscribe(speech.getName(), 'publishEndSpeaking') speech.speakBlocking("I'm speaking a very long text to test mouth movement") speech.speakBlocking('A new sentence to test another long sentece') speech.speakBlocking('And one more')
""" Counting power sets http://www.codewars.com/kata/54381f0b6f032f933c000108/train/python """ def powers(lst): return 2 ** len(lst)
""" Counting power sets http://www.codewars.com/kata/54381f0b6f032f933c000108/train/python """ def powers(lst): return 2 ** len(lst)
# -*- coding: utf-8 -*- if __name__ == '__main__': s = input() t = input() mod_s = s for i in range(len(s)): mod_s = mod_s[1:] + mod_s[0] if mod_s == t: print('Yes') exit() print('No')
if __name__ == '__main__': s = input() t = input() mod_s = s for i in range(len(s)): mod_s = mod_s[1:] + mod_s[0] if mod_s == t: print('Yes') exit() print('No')
def test_cep_match(correios): matches = correios.match_cep(cep="28620000", cod="QC067757494BR") assert matches def test_cep_not_match_wrong_digit(correios): matches = correios.match_cep(cep="28620000", cod="QC067757490BR") assert not matches def test_cep_not_match(correios): matches = correios.match_cep(cep="28620001", cod="QC067757494BR") assert not matches def test_cod_not_match(correios): matches = correios.match_cep(cep="28620000", cod="QC067757480BR") assert not matches def test_invalid_cod_not_match(correios): matches = correios.match_cep(cep="28620000", cod="</objeto>QC067757480BR") assert not matches
def test_cep_match(correios): matches = correios.match_cep(cep='28620000', cod='QC067757494BR') assert matches def test_cep_not_match_wrong_digit(correios): matches = correios.match_cep(cep='28620000', cod='QC067757490BR') assert not matches def test_cep_not_match(correios): matches = correios.match_cep(cep='28620001', cod='QC067757494BR') assert not matches def test_cod_not_match(correios): matches = correios.match_cep(cep='28620000', cod='QC067757480BR') assert not matches def test_invalid_cod_not_match(correios): matches = correios.match_cep(cep='28620000', cod='</objeto>QC067757480BR') assert not matches
# This problem was recently asked by Apple: # You are given an array. Each element represents the price of a stock on that particular day. # Calculate and return the maximum profit you can make from buying and selling that stock only once. def buy_and_sell(arr): # Fill this in. maxP = -1 buy = 0 sell = 0 change = True # Loop control for i in range(0, len(arr) - 1): sell = arr[i + 1] if change: buy = arr[i] if sell < buy: change = True continue else: temp = sell - buy if temp > maxP: maxP = temp change = False return maxP print(buy_and_sell([9, 11, 8, 5, 7, 10])) # 5
def buy_and_sell(arr): max_p = -1 buy = 0 sell = 0 change = True for i in range(0, len(arr) - 1): sell = arr[i + 1] if change: buy = arr[i] if sell < buy: change = True continue else: temp = sell - buy if temp > maxP: max_p = temp change = False return maxP print(buy_and_sell([9, 11, 8, 5, 7, 10]))
#reference_number = 9 text = ' is a prime number ' print('................................') #print('This are numbers which can be divided into ' + str(reference_number)) for i in range(1, 100): first = i / i second = i/1 # print('Residual value of dividing ' + str(i) + ' / ' + str(reference_number) + ' = ' + str(residual)) if first == 1: if second == i: print(str(i) + text) #+ str(reference_number))
text = ' is a prime number ' print('................................') for i in range(1, 100): first = i / i second = i / 1 if first == 1: if second == i: print(str(i) + text)
def test_a(): x = "this" assert "h" in x def test_b(): x = "hello" assert "h" in x def test_c(): x = "world" assert "w" in x
def test_a(): x = 'this' assert 'h' in x def test_b(): x = 'hello' assert 'h' in x def test_c(): x = 'world' assert 'w' in x
# # PySNMP MIB module AIPPP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AIPPP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:00:42 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) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") TimeTicks, IpAddress, Counter64, ModuleIdentity, ObjectIdentity, iso, NotificationType, Unsigned32, MibIdentifier, enterprises, Bits, Integer32, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "IpAddress", "Counter64", "ModuleIdentity", "ObjectIdentity", "iso", "NotificationType", "Unsigned32", "MibIdentifier", "enterprises", "Bits", "Integer32", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32") TruthValue, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "TextualConvention", "DisplayString") class PositiveInteger(Integer32): subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 2147483647) aii = MibIdentifier((1, 3, 6, 1, 4, 1, 539)) aiPPP = ModuleIdentity((1, 3, 6, 1, 4, 1, 539, 25)) if mibBuilder.loadTexts: aiPPP.setLastUpdated('9909151700Z') if mibBuilder.loadTexts: aiPPP.setOrganization('Applied Innovation Inc.') aiPPPTable = MibTable((1, 3, 6, 1, 4, 1, 539, 25, 1), ) if mibBuilder.loadTexts: aiPPPTable.setStatus('current') aiPPPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 539, 25, 1, 1), ).setIndexNames((0, "AIPPP-MIB", "aipppLinkNumber")) if mibBuilder.loadTexts: aiPPPEntry.setStatus('current') aipppLinkNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 1), PositiveInteger()).setMaxAccess("readonly") if mibBuilder.loadTexts: aipppLinkNumber.setStatus('current') aipppNCPProtoOption = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("ipcp", 1), ("bcp", 2), ("ipcpbcp", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: aipppNCPProtoOption.setStatus('current') aipppLocalSecurityOption = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("pap", 2), ("chap", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: aipppLocalSecurityOption.setStatus('current') aipppIpSrcAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 4), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: aipppIpSrcAddr.setStatus('current') aipppIpDestAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 5), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: aipppIpDestAddr.setStatus('current') aipppIpSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 6), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: aipppIpSubnetMask.setStatus('current') aipppIpBcastAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: aipppIpBcastAddr.setStatus('current') aipppLocalRadiusOption = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("disabled", 1), ("enabled", 2), ("localfallback", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: aipppLocalRadiusOption.setStatus('current') aipppRemoteSecurityOption = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("pap", 2), ("chap", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: aipppRemoteSecurityOption.setStatus('current') aipppMultilinkOption = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("reject", 1), ("request", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: aipppMultilinkOption.setStatus('current') aipppMLGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: aipppMLGroup.setStatus('current') mibBuilder.exportSymbols("AIPPP-MIB", aipppMLGroup=aipppMLGroup, aipppLocalSecurityOption=aipppLocalSecurityOption, aiPPPEntry=aiPPPEntry, aipppIpBcastAddr=aipppIpBcastAddr, aipppMultilinkOption=aipppMultilinkOption, PYSNMP_MODULE_ID=aiPPP, aipppNCPProtoOption=aipppNCPProtoOption, aipppLocalRadiusOption=aipppLocalRadiusOption, PositiveInteger=PositiveInteger, aii=aii, aipppIpDestAddr=aipppIpDestAddr, aipppLinkNumber=aipppLinkNumber, aipppIpSrcAddr=aipppIpSrcAddr, aipppIpSubnetMask=aipppIpSubnetMask, aiPPP=aiPPP, aiPPPTable=aiPPPTable, aipppRemoteSecurityOption=aipppRemoteSecurityOption)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (time_ticks, ip_address, counter64, module_identity, object_identity, iso, notification_type, unsigned32, mib_identifier, enterprises, bits, integer32, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'IpAddress', 'Counter64', 'ModuleIdentity', 'ObjectIdentity', 'iso', 'NotificationType', 'Unsigned32', 'MibIdentifier', 'enterprises', 'Bits', 'Integer32', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32') (truth_value, textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TruthValue', 'TextualConvention', 'DisplayString') class Positiveinteger(Integer32): subtype_spec = Integer32.subtypeSpec + value_range_constraint(1, 2147483647) aii = mib_identifier((1, 3, 6, 1, 4, 1, 539)) ai_ppp = module_identity((1, 3, 6, 1, 4, 1, 539, 25)) if mibBuilder.loadTexts: aiPPP.setLastUpdated('9909151700Z') if mibBuilder.loadTexts: aiPPP.setOrganization('Applied Innovation Inc.') ai_ppp_table = mib_table((1, 3, 6, 1, 4, 1, 539, 25, 1)) if mibBuilder.loadTexts: aiPPPTable.setStatus('current') ai_ppp_entry = mib_table_row((1, 3, 6, 1, 4, 1, 539, 25, 1, 1)).setIndexNames((0, 'AIPPP-MIB', 'aipppLinkNumber')) if mibBuilder.loadTexts: aiPPPEntry.setStatus('current') aippp_link_number = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 1), positive_integer()).setMaxAccess('readonly') if mibBuilder.loadTexts: aipppLinkNumber.setStatus('current') aippp_ncp_proto_option = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('ipcp', 1), ('bcp', 2), ('ipcpbcp', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: aipppNCPProtoOption.setStatus('current') aippp_local_security_option = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('none', 1), ('pap', 2), ('chap', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: aipppLocalSecurityOption.setStatus('current') aippp_ip_src_addr = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 4), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: aipppIpSrcAddr.setStatus('current') aippp_ip_dest_addr = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 5), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: aipppIpDestAddr.setStatus('current') aippp_ip_subnet_mask = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 6), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: aipppIpSubnetMask.setStatus('current') aippp_ip_bcast_addr = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 7), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: aipppIpBcastAddr.setStatus('current') aippp_local_radius_option = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('disabled', 1), ('enabled', 2), ('localfallback', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: aipppLocalRadiusOption.setStatus('current') aippp_remote_security_option = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('none', 1), ('pap', 2), ('chap', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: aipppRemoteSecurityOption.setStatus('current') aippp_multilink_option = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('reject', 1), ('request', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: aipppMultilinkOption.setStatus('current') aippp_ml_group = mib_table_column((1, 3, 6, 1, 4, 1, 539, 25, 1, 1, 11), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readwrite') if mibBuilder.loadTexts: aipppMLGroup.setStatus('current') mibBuilder.exportSymbols('AIPPP-MIB', aipppMLGroup=aipppMLGroup, aipppLocalSecurityOption=aipppLocalSecurityOption, aiPPPEntry=aiPPPEntry, aipppIpBcastAddr=aipppIpBcastAddr, aipppMultilinkOption=aipppMultilinkOption, PYSNMP_MODULE_ID=aiPPP, aipppNCPProtoOption=aipppNCPProtoOption, aipppLocalRadiusOption=aipppLocalRadiusOption, PositiveInteger=PositiveInteger, aii=aii, aipppIpDestAddr=aipppIpDestAddr, aipppLinkNumber=aipppLinkNumber, aipppIpSrcAddr=aipppIpSrcAddr, aipppIpSubnetMask=aipppIpSubnetMask, aiPPP=aiPPP, aiPPPTable=aiPPPTable, aipppRemoteSecurityOption=aipppRemoteSecurityOption)
class S: """ Gets all keys from a dict and adds them as attribute to a class (also works with nested dicts) Parameters ---------- data : ``dict` The dict you want to convert """ def __init__(self, data: dict) -> None: self.__raw = data class _(dict): def __init__(self, *args, **kwargs): super(_, self).__init__(*args, **kwargs) self.__dict__ = self @classmethod def nested(cls, data): if not isinstance(data, dict): return data else: return cls({k: cls.nested(data[k]) for k in data}) for k, v in _.nested(data).items(): setattr(self, k, v) def __len__(self) -> int: return len([x for x in dir(self) if not x.startswith("_")]) def __repr__(self) -> str: return "<class 'S'>" def _new(self, new=None) -> None: """ Renews the data """ self.__init__(new or self.__raw)
class S: """ Gets all keys from a dict and adds them as attribute to a class (also works with nested dicts) Parameters ---------- data : ``dict` The dict you want to convert """ def __init__(self, data: dict) -> None: self.__raw = data class _(dict): def __init__(self, *args, **kwargs): super(_, self).__init__(*args, **kwargs) self.__dict__ = self @classmethod def nested(cls, data): if not isinstance(data, dict): return data else: return cls({k: cls.nested(data[k]) for k in data}) for (k, v) in _.nested(data).items(): setattr(self, k, v) def __len__(self) -> int: return len([x for x in dir(self) if not x.startswith('_')]) def __repr__(self) -> str: return "<class 'S'>" def _new(self, new=None) -> None: """ Renews the data """ self.__init__(new or self.__raw)
#350111 #a3_p10.py #Alexandru Sasu #a.sasu@jacobs-university.de def printframe(n, m, c): for j in range(0,m): print(c,end="") print() for i in range (1,n-1): print(c,end="") for j in range(1,m-1): print(" ",end="") print(c) for j in range(0,m): print(c,end="") print() n=int(input()) m=int(input()) c=input() printframe(n, m, c)
def printframe(n, m, c): for j in range(0, m): print(c, end='') print() for i in range(1, n - 1): print(c, end='') for j in range(1, m - 1): print(' ', end='') print(c) for j in range(0, m): print(c, end='') print() n = int(input()) m = int(input()) c = input() printframe(n, m, c)
x = True y=False print(x,y) num1=1 num2=2 resultado=num1<num2 print(resultado) if(num1 < num2): print("el valor num1 es menor que num2") else: print("el valor de num1 No es menor que num2")
x = True y = False print(x, y) num1 = 1 num2 = 2 resultado = num1 < num2 print(resultado) if num1 < num2: print('el valor num1 es menor que num2') else: print('el valor de num1 No es menor que num2')
class Solution: def isMirrorImage(self, left, right): if left is None and right is None: return True if left is None or right is None: return False if left.val != right.val: return False return self.isMirrorImage(left.left, right.right) and \ self.isMirrorImage(left.right, right.left) def isSymmetric(self, root): if root is None: return True return self.isMirrorImage(root.left, root.right)
class Solution: def is_mirror_image(self, left, right): if left is None and right is None: return True if left is None or right is None: return False if left.val != right.val: return False return self.isMirrorImage(left.left, right.right) and self.isMirrorImage(left.right, right.left) def is_symmetric(self, root): if root is None: return True return self.isMirrorImage(root.left, root.right)
# -*- coding: utf-8 -*- # # DVR-Scan: Find & Export Motion Events in Video Footage # -------------------------------------------------------------- # [ Site: https://github.com/Breakthrough/DVR-Scan/ ] # [ Documentation: http://dvr-scan.readthedocs.org/ ] # # This file contains all code for the main `dvr_scan` module. # # Copyright (C) 2016-2021 Brandon Castellano <http://www.bcastell.com>. # # DVR-Scan is licensed under the BSD 2-Clause License; see the included # LICENSE file or visit one of the following pages for details: # - https://github.com/Breakthrough/DVR-Scan/ # # This software uses Numpy and OpenCV; see the LICENSE-NUMPY and # LICENSE-OPENCV files or visit the above URL for details. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # """ DVR-Scan Unit Test Suite To run all available tests run `pytest -v` from the parent directory (i.e. the root project folder of DVR-Scan containing the scenedetect/ and tests/ folders). This will automatically find and run all of the test cases in the tests/ folder and display the results. """
""" DVR-Scan Unit Test Suite To run all available tests run `pytest -v` from the parent directory (i.e. the root project folder of DVR-Scan containing the scenedetect/ and tests/ folders). This will automatically find and run all of the test cases in the tests/ folder and display the results. """
# flake8: noqa def test_variable_substitution(variable_transform): text = "cd $HOME" assert variable_transform(text) == "cd %s" % HOME def test_variable_substitution_inverse(variable_transform): text = "cd %s" % HOME assert variable_transform(text, inverse=True) == "cd $HOME" def test_variable_substitution_only_at_start(variable_transform): """ Expansion of variables should only happen if token starts with a variable. Thus, assuming "$EDITOR" is a variable, "$EDITOR" should be expanded, but "x$EDITOR" should not. Thus if "EDITOR=vim", expansion of "xvim" should do nothing, not replace with 'f$EDITOR'. """ text = 'x$EDITOR' assert variable_transform(text) == text text = 'x%s' % EDITOR assert variable_transform(text, inverse=True) == text def test_variable_substitution_order(variable_transform): """Variable substitution should substitute longer values first.""" text = "cd %s" % HOME assert variable_transform(text, inverse=True) == "cd $HOME" def test_variable_substitution_id(variable_transform): text = "$HOME" assert variable_transform(variable_transform(text), inverse=True) == text def test_tilde_substitution1(tilde_transform, environment): """Tilde substitution should expand ``~`` as ``$HOME``.""" text = "cd ~" assert tilde_transform(text) == "cd %s" % environment['HOME'] text = "cd ~/Desktop" assert tilde_transform(text) == "cd %s/Desktop" % environment['HOME'] def test_tilde_substitution2(tilde_transform): """ Tilde substitution should not expand a tilde unless it is the prefix of a token. """ text = "git rebase -i HEAD~3" assert tilde_transform(text) == text def test_tilde_substitution_inverse(tilde_transform): """Tilde substitution should have an inverse.""" text = "~" assert tilde_transform(tilde_transform(text), inverse=True) == text def test_transform(transforms): text = "home" assert transform(text, transforms) == "cd %s" % HOME def test_transform_inverse(transforms): text = "cd %s" % HOME assert transform(text, transforms, inverse=True) == "home" def test_transform_id(transforms): text = "home" actual = transform(transform(text, transforms), transforms, inverse=True) assert actual == text
def test_variable_substitution(variable_transform): text = 'cd $HOME' assert variable_transform(text) == 'cd %s' % HOME def test_variable_substitution_inverse(variable_transform): text = 'cd %s' % HOME assert variable_transform(text, inverse=True) == 'cd $HOME' def test_variable_substitution_only_at_start(variable_transform): """ Expansion of variables should only happen if token starts with a variable. Thus, assuming "$EDITOR" is a variable, "$EDITOR" should be expanded, but "x$EDITOR" should not. Thus if "EDITOR=vim", expansion of "xvim" should do nothing, not replace with 'f$EDITOR'. """ text = 'x$EDITOR' assert variable_transform(text) == text text = 'x%s' % EDITOR assert variable_transform(text, inverse=True) == text def test_variable_substitution_order(variable_transform): """Variable substitution should substitute longer values first.""" text = 'cd %s' % HOME assert variable_transform(text, inverse=True) == 'cd $HOME' def test_variable_substitution_id(variable_transform): text = '$HOME' assert variable_transform(variable_transform(text), inverse=True) == text def test_tilde_substitution1(tilde_transform, environment): """Tilde substitution should expand ``~`` as ``$HOME``.""" text = 'cd ~' assert tilde_transform(text) == 'cd %s' % environment['HOME'] text = 'cd ~/Desktop' assert tilde_transform(text) == 'cd %s/Desktop' % environment['HOME'] def test_tilde_substitution2(tilde_transform): """ Tilde substitution should not expand a tilde unless it is the prefix of a token. """ text = 'git rebase -i HEAD~3' assert tilde_transform(text) == text def test_tilde_substitution_inverse(tilde_transform): """Tilde substitution should have an inverse.""" text = '~' assert tilde_transform(tilde_transform(text), inverse=True) == text def test_transform(transforms): text = 'home' assert transform(text, transforms) == 'cd %s' % HOME def test_transform_inverse(transforms): text = 'cd %s' % HOME assert transform(text, transforms, inverse=True) == 'home' def test_transform_id(transforms): text = 'home' actual = transform(transform(text, transforms), transforms, inverse=True) assert actual == text
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head or head.next == None: return head temp_dict = dict() pre = head while pre: if pre.val not in temp_dict.keys(): temp_dict[pre.val] = 1 else: temp_dict[pre.val] += 1 pre = pre.next temp = [] for i, value in temp_dict.items(): if value > 1: continue else: temp.append(i) result = ListNode(0) cur = result for value in temp: cur.next = ListNode(value) cur = cur.next return result.next
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def delete_duplicates(self, head: ListNode) -> ListNode: if not head or head.next == None: return head temp_dict = dict() pre = head while pre: if pre.val not in temp_dict.keys(): temp_dict[pre.val] = 1 else: temp_dict[pre.val] += 1 pre = pre.next temp = [] for (i, value) in temp_dict.items(): if value > 1: continue else: temp.append(i) result = list_node(0) cur = result for value in temp: cur.next = list_node(value) cur = cur.next return result.next
def binary_search(data, value): min = 0 max = len(data) - 1 while min <= max: mid = (min + max) // 2 if data[mid] == value: return mid elif data[mid] < value: min = mid + 1 else: max = mid - 1 return -1 if __name__ == '__main__': data = [i for i in range(10)] print(binary_search(data, 2))
def binary_search(data, value): min = 0 max = len(data) - 1 while min <= max: mid = (min + max) // 2 if data[mid] == value: return mid elif data[mid] < value: min = mid + 1 else: max = mid - 1 return -1 if __name__ == '__main__': data = [i for i in range(10)] print(binary_search(data, 2))
def jac_uniform(mesh, mask): # create Jacobian cv = mesh.get_control_volumes(cell_mask=mask) cvc = mesh.get_control_volume_centroids(cell_mask=mask) return 2 * (mesh.node_coords - cvc) * cv[:, None]
def jac_uniform(mesh, mask): cv = mesh.get_control_volumes(cell_mask=mask) cvc = mesh.get_control_volume_centroids(cell_mask=mask) return 2 * (mesh.node_coords - cvc) * cv[:, None]
def pig_it(text): l=text.split() count=0 for i in l: if i.isalpha(): tmp=list(i) tmp.append(tmp[0]) tmp.pop(0) tmp.extend(list('ay')) l[count]=''.join(tmp) count+=1 return ' '.join(l) ''' def pig_it(text): lst = text.split() return ' '.join( [word[1:] + word[:1] + 'ay' if word.isalpha() else word for word in lst]) '''
def pig_it(text): l = text.split() count = 0 for i in l: if i.isalpha(): tmp = list(i) tmp.append(tmp[0]) tmp.pop(0) tmp.extend(list('ay')) l[count] = ''.join(tmp) count += 1 return ' '.join(l) "\ndef pig_it(text):\n lst = text.split()\n return ' '.join( [word[1:] + word[:1] + 'ay' if word.isalpha() else word for word in lst])\n"
{ "targets": [ { "target_name": "glfw", "sources": [ "src/native/glfw.cc", "src/native/glad.c" ], "include_dirs": [ "src/native/deps/include", "<!@(pkg-config glfw3 --cflags-only-I | sed s/-I//g)" ], "libraries": [ "<!@(pkg-config --libs glfw3)", ], "library_dirs": [ "/usr/local/lib" ] }, { "target_name": "gles", "sources": [ "src/native/gles.cc" ], "include_dirs": [ "src/native/deps/include" ], "libraries": [], "library_dirs": [ "/usr/local/lib" ] } ] }
{'targets': [{'target_name': 'glfw', 'sources': ['src/native/glfw.cc', 'src/native/glad.c'], 'include_dirs': ['src/native/deps/include', '<!@(pkg-config glfw3 --cflags-only-I | sed s/-I//g)'], 'libraries': ['<!@(pkg-config --libs glfw3)'], 'library_dirs': ['/usr/local/lib']}, {'target_name': 'gles', 'sources': ['src/native/gles.cc'], 'include_dirs': ['src/native/deps/include'], 'libraries': [], 'library_dirs': ['/usr/local/lib']}]}
def foo(): return 'bar' COMMAND = foo
def foo(): return 'bar' command = foo
class HomeEventManager: def __init__(self, model): self._model = model def handle_mouse_event(self, event): for button in self.model.buttons: if button.rect.collidepoint(event.pos): return button return None @property def model(self): return self._model
class Homeeventmanager: def __init__(self, model): self._model = model def handle_mouse_event(self, event): for button in self.model.buttons: if button.rect.collidepoint(event.pos): return button return None @property def model(self): return self._model
class HashMap: def __init__(self, size): self.size = size self.map = [None] * self.size self.index = -1 def __str__(self): """ Method from HashMap that prints indices, keys, and values in map In: None Out: string """ if self.map is not None: for item in self.map: self.index += 1 print(f'{self.index}: {str(item)}') def hash(self, key): """ Method from HashMap that takes in a key In: string Out: Integer """ hashed_chars = 0 for char in str(key): hashed_chars += ord(char) * 599 return hashed_chars % self.size def add(self, key, value): """ Method from HashMap that takes in a key and value In: string and integer Out: adds key and value to an index in the map """ hash_key = self.hash(key) key_value = [key, value] if self.map[hash_key] is None: self.map[hash_key] = list([key_value]) return True else: for pair in self.map[hash_key]: if pair[0] == key: pair[1] = value return True self.map[hash_key].append(key_value) return True def contains(self, key): """ Method from HashMap that takes in a key In: string Out: boolean """ hash_key = self.hash(key) if self.map[hash_key] is not None: for pair in self.map[hash_key]: if pair[0] == key: return True return False def get(self, key): """ Method from HashMap that takes in a key In: string Out: string - returns value from map or None if does not exist """ hash_key = self.hash(key) if self.map[hash_key] is not None: for pair in self.map[hash_key]: if pair[0] == key: return pair[1] return None if __name__ == "__main__": h1 = HashMap(10) h1.add('fond', 'enamored') h1.add('wrath', 'anger') h1.add('diligent', 'employed') h1.add('outift', 'garb') h1.add('guide', 'usher') h2 = HashMap(10) h2.add('fond', 'averse') h2.add('wrath', 'delight') h2.add('diligent', 'idle') h2.add('guide', 'follow') h2.add('flow', 'jam')
class Hashmap: def __init__(self, size): self.size = size self.map = [None] * self.size self.index = -1 def __str__(self): """ Method from HashMap that prints indices, keys, and values in map In: None Out: string """ if self.map is not None: for item in self.map: self.index += 1 print(f'{self.index}: {str(item)}') def hash(self, key): """ Method from HashMap that takes in a key In: string Out: Integer """ hashed_chars = 0 for char in str(key): hashed_chars += ord(char) * 599 return hashed_chars % self.size def add(self, key, value): """ Method from HashMap that takes in a key and value In: string and integer Out: adds key and value to an index in the map """ hash_key = self.hash(key) key_value = [key, value] if self.map[hash_key] is None: self.map[hash_key] = list([key_value]) return True else: for pair in self.map[hash_key]: if pair[0] == key: pair[1] = value return True self.map[hash_key].append(key_value) return True def contains(self, key): """ Method from HashMap that takes in a key In: string Out: boolean """ hash_key = self.hash(key) if self.map[hash_key] is not None: for pair in self.map[hash_key]: if pair[0] == key: return True return False def get(self, key): """ Method from HashMap that takes in a key In: string Out: string - returns value from map or None if does not exist """ hash_key = self.hash(key) if self.map[hash_key] is not None: for pair in self.map[hash_key]: if pair[0] == key: return pair[1] return None if __name__ == '__main__': h1 = hash_map(10) h1.add('fond', 'enamored') h1.add('wrath', 'anger') h1.add('diligent', 'employed') h1.add('outift', 'garb') h1.add('guide', 'usher') h2 = hash_map(10) h2.add('fond', 'averse') h2.add('wrath', 'delight') h2.add('diligent', 'idle') h2.add('guide', 'follow') h2.add('flow', 'jam')
errors = { "BadRequest": {"message": "Bad Request", "status": 400}, "Forbidden": {"message": "Forbidden", "status": 403}, "NotFound": {"message": "Resource Not Found", "status": 404}, "MethodNotAllowed": {"message": "Method Not allowed", "status": 405}, "Conflict": { "message": "You can not add a duplicate resource.", "status": 409, }, "UnprocessableEntity": {"message": "unprocessable Entity", "status": 422}, "InternalServerError": {"message": "Internal Server Error", "status": 500}, }
errors = {'BadRequest': {'message': 'Bad Request', 'status': 400}, 'Forbidden': {'message': 'Forbidden', 'status': 403}, 'NotFound': {'message': 'Resource Not Found', 'status': 404}, 'MethodNotAllowed': {'message': 'Method Not allowed', 'status': 405}, 'Conflict': {'message': 'You can not add a duplicate resource.', 'status': 409}, 'UnprocessableEntity': {'message': 'unprocessable Entity', 'status': 422}, 'InternalServerError': {'message': 'Internal Server Error', 'status': 500}}
class Node: def __init__(self, data, depth): children_count = int(data.pop(0)) metadata_count = int(data.pop(0)) self.children = [] self.metadata = [] self.depth = depth for i in range(children_count): self.children.append(Node(data, depth + 1)) for i in range(metadata_count): self.metadata.append(int(data.pop(0))) def sum(self): return sum(map(lambda x: x.sum(), self.children)) + sum(self.metadata) def value(self): if len(self.children) == 0: return sum(self.metadata) return sum(map( lambda x: self.children[x - 1].value() if (x > 0 and x <= len(self.children)) else 0, self.metadata )) def __repr__(self): rep = ('- ' * self.depth) + 'v' + str(self.value()) + ' c' + \ str(len(self.children)) + ' - ' + \ ' '.join(map(str, self.metadata)) + '\n' for child in self.children: rep += child.__repr__() return rep def main(): input_data = read_input()[0].split(' ') tree = Node(input_data, 0) # Part 1 print(tree.sum()) # Part 2 print(tree.value()) def read_input(): '''Read the file and remove trailing new line characters''' f = open('input.txt', 'r') data = list(map(lambda x: x[:-1], f.readlines())) f.close() return data if __name__ == '__main__': main()
class Node: def __init__(self, data, depth): children_count = int(data.pop(0)) metadata_count = int(data.pop(0)) self.children = [] self.metadata = [] self.depth = depth for i in range(children_count): self.children.append(node(data, depth + 1)) for i in range(metadata_count): self.metadata.append(int(data.pop(0))) def sum(self): return sum(map(lambda x: x.sum(), self.children)) + sum(self.metadata) def value(self): if len(self.children) == 0: return sum(self.metadata) return sum(map(lambda x: self.children[x - 1].value() if x > 0 and x <= len(self.children) else 0, self.metadata)) def __repr__(self): rep = '- ' * self.depth + 'v' + str(self.value()) + ' c' + str(len(self.children)) + ' - ' + ' '.join(map(str, self.metadata)) + '\n' for child in self.children: rep += child.__repr__() return rep def main(): input_data = read_input()[0].split(' ') tree = node(input_data, 0) print(tree.sum()) print(tree.value()) def read_input(): """Read the file and remove trailing new line characters""" f = open('input.txt', 'r') data = list(map(lambda x: x[:-1], f.readlines())) f.close() return data if __name__ == '__main__': main()
""" Tuples: 1. immutable 2. heterogeneous data structures (i.e., their entries have different meanings) 3. ordered data structure that can be indexed and sliced like a list. 4. defined by listing a sequence of elements separated by commas, optionally contained within parentheses: () ex: my_location = (42, 11) # page number, line number List: 1. mutable 2. homogeneous sequences. Tuples have structure, lists have order. 3. ordered """ tuple_a = 1, 2 tuple_b = (1, 2) print(tuple_a == tuple_b) # True print(tuple_a[1]) # 2
""" Tuples: 1. immutable 2. heterogeneous data structures (i.e., their entries have different meanings) 3. ordered data structure that can be indexed and sliced like a list. 4. defined by listing a sequence of elements separated by commas, optionally contained within parentheses: () ex: my_location = (42, 11) # page number, line number List: 1. mutable 2. homogeneous sequences. Tuples have structure, lists have order. 3. ordered """ tuple_a = (1, 2) tuple_b = (1, 2) print(tuple_a == tuple_b) print(tuple_a[1])
#WAP to print the grade s1 = float(input("Enter marks for subject 1 :")) s2 = float(input("Enter marks for subject 2 :")) s3 = float(input("Enter marks for subject 3 :")) s4 = float(input("Enter marks for subject 4 :")) total = s1 + s2 + s3 + s4 avg = total / 4 print('Average marks:',avg) if avg >= 90: print("O") elif avg >= 80: print("E") elif avg >= 70: print("A") elif avg >= 60: print("B") elif avg >= 50: print("C") else: print("you are fail")
s1 = float(input('Enter marks for subject 1 :')) s2 = float(input('Enter marks for subject 2 :')) s3 = float(input('Enter marks for subject 3 :')) s4 = float(input('Enter marks for subject 4 :')) total = s1 + s2 + s3 + s4 avg = total / 4 print('Average marks:', avg) if avg >= 90: print('O') elif avg >= 80: print('E') elif avg >= 70: print('A') elif avg >= 60: print('B') elif avg >= 50: print('C') else: print('you are fail')
SAMPLEEXECUTION_TYPE_URI = "https://w3id.org/okn/o/sd#SampleExecution" SAMPLEEXECUTION_TYPE_NAME = "SampleExecution" GRID_TYPE_URI = "https://w3id.org/okn/o/sdm#Grid" GRID_TYPE_NAME = "Grid" DATASETSPECIFICATION_TYPE_URI = "https://w3id.org/okn/o/sd#DatasetSpecification" DATASETSPECIFICATION_TYPE_NAME = "DatasetSpecification" EMPIRICALMODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#EmpiricalModel" EMPIRICALMODEL_TYPE_NAME = "EmpiricalModel" GEOSHAPE_TYPE_URI = "https://w3id.org/okn/o/sdm#GeoShape" GEOSHAPE_TYPE_NAME = "GeoShape" CONFIGURATIONSETUP_TYPE_URI = "https://w3id.org/okn/o/sd#ConfigurationSetup" CONFIGURATIONSETUP_TYPE_NAME = "ConfigurationSetup" UNIT_TYPE_URI = "http://qudt.org/schema/qudt/Unit" UNIT_TYPE_NAME = "Unit" SAMPLECOLLECTION_TYPE_URI = "https://w3id.org/okn/o/sd#SampleCollection" SAMPLECOLLECTION_TYPE_NAME = "SampleCollection" THING_TYPE_URI = "http://www.w3.org/2002/07/owl#Thing" THING_TYPE_NAME = "Thing" DATATRANSFORMATION_TYPE_URI = "https://w3id.org/okn/o/sd#DataTransformation" DATATRANSFORMATION_TYPE_NAME = "DataTransformation" NUMERICALINDEX_TYPE_URI = "https://w3id.org/okn/o/sd#NumericalIndex" NUMERICALINDEX_TYPE_NAME = "NumericalIndex" EMULATOR_TYPE_URI = "https://w3id.org/okn/o/sdm#Emulator" EMULATOR_TYPE_NAME = "Emulator" MODELCONFIGURATION_TYPE_URI = "https://w3id.org/okn/o/sdm#ModelConfiguration" MODELCONFIGURATION_TYPE_NAME = "ModelConfiguration" SOFTWAREIMAGE_TYPE_URI = "https://w3id.org/okn/o/sd#SoftwareImage" SOFTWAREIMAGE_TYPE_NAME = "SoftwareImage" THEORYGUIDEDMODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#Theory-GuidedModel" THEORYGUIDEDMODEL_TYPE_NAME = "Theory-GuidedModel" SOFTWARE_TYPE_URI = "https://w3id.org/okn/o/sd#Software" SOFTWARE_TYPE_NAME = "Software" VARIABLEPRESENTATION_TYPE_URI = "https://w3id.org/okn/o/sd#VariablePresentation" VARIABLEPRESENTATION_TYPE_NAME = "VariablePresentation" SOFTWARECONFIGURATION_TYPE_URI = "https://w3id.org/okn/o/sd#SoftwareConfiguration" SOFTWARECONFIGURATION_TYPE_NAME = "SoftwareConfiguration" SOFTWAREVERSION_TYPE_URI = "https://w3id.org/okn/o/sd#SoftwareVersion" SOFTWAREVERSION_TYPE_NAME = "SoftwareVersion" FUNDINGINFORMATION_TYPE_URI = "https://w3id.org/okn/o/sd#FundingInformation" FUNDINGINFORMATION_TYPE_NAME = "FundingInformation" SAMPLERESOURCE_TYPE_URI = "https://w3id.org/okn/o/sd#SampleResource" SAMPLERESOURCE_TYPE_NAME = "SampleResource" PARAMETER_TYPE_URI = "https://w3id.org/okn/o/sd#Parameter" PARAMETER_TYPE_NAME = "Parameter" HYBRIDMODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#HybridModel" HYBRIDMODEL_TYPE_NAME = "HybridModel" CAUSALDIAGRAM_TYPE_URI = "https://w3id.org/okn/o/sdm#CausalDiagram" CAUSALDIAGRAM_TYPE_NAME = "CausalDiagram" SPATIALRESOLUTION_TYPE_URI = "https://w3id.org/okn/o/sdm#SpatialResolution" SPATIALRESOLUTION_TYPE_NAME = "SpatialResolution" PERSON_TYPE_URI = "https://w3id.org/okn/o/sd#Person" PERSON_TYPE_NAME = "Person" EQUATION_TYPE_URI = "https://w3id.org/okn/o/sdm#Equation" EQUATION_TYPE_NAME = "Equation" INTERVENTION_TYPE_URI = "https://w3id.org/okn/o/sdm#Intervention" INTERVENTION_TYPE_NAME = "Intervention" VARIABLE_TYPE_URI = "https://w3id.org/okn/o/sd#Variable" VARIABLE_TYPE_NAME = "Variable" POINTBASEDGRID_TYPE_URI = "https://w3id.org/okn/o/sdm#PointBasedGrid" POINTBASEDGRID_TYPE_NAME = "PointBasedGrid" VISUALIZATION_TYPE_URI = "https://w3id.org/okn/o/sd#Visualization" VISUALIZATION_TYPE_NAME = "Visualization" IMAGE_TYPE_URI = "https://w3id.org/okn/o/sd#Image" IMAGE_TYPE_NAME = "Image" CONSTRAINT_TYPE_URI = "https://w3id.org/okn/o/sd#Constraint" CONSTRAINT_TYPE_NAME = "Constraint" SOURCECODE_TYPE_URI = "https://w3id.org/okn/o/sd#SourceCode" SOURCECODE_TYPE_NAME = "SourceCode" TIMEINTERVAL_TYPE_URI = "https://w3id.org/okn/o/sdm#TimeInterval" TIMEINTERVAL_TYPE_NAME = "TimeInterval" ORGANIZATION_TYPE_URI = "https://w3id.org/okn/o/sd#Organization" ORGANIZATION_TYPE_NAME = "Organization" MODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#Model" MODEL_TYPE_NAME = "Model" MODELCATEGORY_TYPE_URI = "https://w3id.org/okn/o/sdm#ModelCategory" MODELCATEGORY_TYPE_NAME = "ModelCategory" UNIT_TYPE_URI = "https://w3id.org/okn/o/sd#Unit" UNIT_TYPE_NAME = "Unit" REGION_TYPE_URI = "https://w3id.org/okn/o/sdm#Region" REGION_TYPE_NAME = "Region" COUPLEDMODEL_TYPE_URI = "https://w3id.org/okn/o/sdm#CoupledModel" COUPLEDMODEL_TYPE_NAME = "CoupledModel" GEOCOORDINATES_TYPE_URI = "https://w3id.org/okn/o/sdm#GeoCoordinates" GEOCOORDINATES_TYPE_NAME = "GeoCoordinates" STANDARDVARIABLE_TYPE_URI = "https://w3id.org/okn/o/sd#StandardVariable" STANDARDVARIABLE_TYPE_NAME = "StandardVariable" SPATIALLYDISTRIBUTEDGRID_TYPE_URI = "https://w3id.org/okn/o/sdm#SpatiallyDistributedGrid" SPATIALLYDISTRIBUTEDGRID_TYPE_NAME = "SpatiallyDistributedGrid" DATATRANSFORMATIONSETUP_TYPE_URI = "https://w3id.org/okn/o/sd#DataTransformationSetup" DATATRANSFORMATIONSETUP_TYPE_NAME = "DataTransformationSetup" PROCESS_TYPE_URI = "https://w3id.org/okn/o/sdm#Process" PROCESS_TYPE_NAME = "Process" CATALOGIDENTIFIER_TYPE_URI = "https://w3id.org/okn/o/sd#CatalogIdentifier" CATALOGIDENTIFIER_TYPE_NAME = "CatalogIdentifier" MODELCONFIGURATIONSETUP_TYPE_URI = "https://w3id.org/okn/o/sdm#ModelConfigurationSetup" MODELCONFIGURATIONSETUP_TYPE_NAME = "ModelConfigurationSetup"
sampleexecution_type_uri = 'https://w3id.org/okn/o/sd#SampleExecution' sampleexecution_type_name = 'SampleExecution' grid_type_uri = 'https://w3id.org/okn/o/sdm#Grid' grid_type_name = 'Grid' datasetspecification_type_uri = 'https://w3id.org/okn/o/sd#DatasetSpecification' datasetspecification_type_name = 'DatasetSpecification' empiricalmodel_type_uri = 'https://w3id.org/okn/o/sdm#EmpiricalModel' empiricalmodel_type_name = 'EmpiricalModel' geoshape_type_uri = 'https://w3id.org/okn/o/sdm#GeoShape' geoshape_type_name = 'GeoShape' configurationsetup_type_uri = 'https://w3id.org/okn/o/sd#ConfigurationSetup' configurationsetup_type_name = 'ConfigurationSetup' unit_type_uri = 'http://qudt.org/schema/qudt/Unit' unit_type_name = 'Unit' samplecollection_type_uri = 'https://w3id.org/okn/o/sd#SampleCollection' samplecollection_type_name = 'SampleCollection' thing_type_uri = 'http://www.w3.org/2002/07/owl#Thing' thing_type_name = 'Thing' datatransformation_type_uri = 'https://w3id.org/okn/o/sd#DataTransformation' datatransformation_type_name = 'DataTransformation' numericalindex_type_uri = 'https://w3id.org/okn/o/sd#NumericalIndex' numericalindex_type_name = 'NumericalIndex' emulator_type_uri = 'https://w3id.org/okn/o/sdm#Emulator' emulator_type_name = 'Emulator' modelconfiguration_type_uri = 'https://w3id.org/okn/o/sdm#ModelConfiguration' modelconfiguration_type_name = 'ModelConfiguration' softwareimage_type_uri = 'https://w3id.org/okn/o/sd#SoftwareImage' softwareimage_type_name = 'SoftwareImage' theoryguidedmodel_type_uri = 'https://w3id.org/okn/o/sdm#Theory-GuidedModel' theoryguidedmodel_type_name = 'Theory-GuidedModel' software_type_uri = 'https://w3id.org/okn/o/sd#Software' software_type_name = 'Software' variablepresentation_type_uri = 'https://w3id.org/okn/o/sd#VariablePresentation' variablepresentation_type_name = 'VariablePresentation' softwareconfiguration_type_uri = 'https://w3id.org/okn/o/sd#SoftwareConfiguration' softwareconfiguration_type_name = 'SoftwareConfiguration' softwareversion_type_uri = 'https://w3id.org/okn/o/sd#SoftwareVersion' softwareversion_type_name = 'SoftwareVersion' fundinginformation_type_uri = 'https://w3id.org/okn/o/sd#FundingInformation' fundinginformation_type_name = 'FundingInformation' sampleresource_type_uri = 'https://w3id.org/okn/o/sd#SampleResource' sampleresource_type_name = 'SampleResource' parameter_type_uri = 'https://w3id.org/okn/o/sd#Parameter' parameter_type_name = 'Parameter' hybridmodel_type_uri = 'https://w3id.org/okn/o/sdm#HybridModel' hybridmodel_type_name = 'HybridModel' causaldiagram_type_uri = 'https://w3id.org/okn/o/sdm#CausalDiagram' causaldiagram_type_name = 'CausalDiagram' spatialresolution_type_uri = 'https://w3id.org/okn/o/sdm#SpatialResolution' spatialresolution_type_name = 'SpatialResolution' person_type_uri = 'https://w3id.org/okn/o/sd#Person' person_type_name = 'Person' equation_type_uri = 'https://w3id.org/okn/o/sdm#Equation' equation_type_name = 'Equation' intervention_type_uri = 'https://w3id.org/okn/o/sdm#Intervention' intervention_type_name = 'Intervention' variable_type_uri = 'https://w3id.org/okn/o/sd#Variable' variable_type_name = 'Variable' pointbasedgrid_type_uri = 'https://w3id.org/okn/o/sdm#PointBasedGrid' pointbasedgrid_type_name = 'PointBasedGrid' visualization_type_uri = 'https://w3id.org/okn/o/sd#Visualization' visualization_type_name = 'Visualization' image_type_uri = 'https://w3id.org/okn/o/sd#Image' image_type_name = 'Image' constraint_type_uri = 'https://w3id.org/okn/o/sd#Constraint' constraint_type_name = 'Constraint' sourcecode_type_uri = 'https://w3id.org/okn/o/sd#SourceCode' sourcecode_type_name = 'SourceCode' timeinterval_type_uri = 'https://w3id.org/okn/o/sdm#TimeInterval' timeinterval_type_name = 'TimeInterval' organization_type_uri = 'https://w3id.org/okn/o/sd#Organization' organization_type_name = 'Organization' model_type_uri = 'https://w3id.org/okn/o/sdm#Model' model_type_name = 'Model' modelcategory_type_uri = 'https://w3id.org/okn/o/sdm#ModelCategory' modelcategory_type_name = 'ModelCategory' unit_type_uri = 'https://w3id.org/okn/o/sd#Unit' unit_type_name = 'Unit' region_type_uri = 'https://w3id.org/okn/o/sdm#Region' region_type_name = 'Region' coupledmodel_type_uri = 'https://w3id.org/okn/o/sdm#CoupledModel' coupledmodel_type_name = 'CoupledModel' geocoordinates_type_uri = 'https://w3id.org/okn/o/sdm#GeoCoordinates' geocoordinates_type_name = 'GeoCoordinates' standardvariable_type_uri = 'https://w3id.org/okn/o/sd#StandardVariable' standardvariable_type_name = 'StandardVariable' spatiallydistributedgrid_type_uri = 'https://w3id.org/okn/o/sdm#SpatiallyDistributedGrid' spatiallydistributedgrid_type_name = 'SpatiallyDistributedGrid' datatransformationsetup_type_uri = 'https://w3id.org/okn/o/sd#DataTransformationSetup' datatransformationsetup_type_name = 'DataTransformationSetup' process_type_uri = 'https://w3id.org/okn/o/sdm#Process' process_type_name = 'Process' catalogidentifier_type_uri = 'https://w3id.org/okn/o/sd#CatalogIdentifier' catalogidentifier_type_name = 'CatalogIdentifier' modelconfigurationsetup_type_uri = 'https://w3id.org/okn/o/sdm#ModelConfigurationSetup' modelconfigurationsetup_type_name = 'ModelConfigurationSetup'
# Enter your code here. Read input from STDIN. Print output to STDOUT total = 0 n = int(input('')) size = list(map(int, input().split())) m = int(input('')) for i in range(m): order = list(map(int, input().split())) if order[0] in size: total = total + order[1] size.remove(order[0]) print(total)
total = 0 n = int(input('')) size = list(map(int, input().split())) m = int(input('')) for i in range(m): order = list(map(int, input().split())) if order[0] in size: total = total + order[1] size.remove(order[0]) print(total)
def missingTwo(nums: [int]) -> [int]: ret = 0 for i, num in enumerate(nums): ret ^= (i + 1) ret ^= num ret ^= len(nums) + 1 ret ^= len(nums) + 2 mask = 1 while mask & ret == 0: mask <<= 1 a, b = 0, 0 for i in range(1, len(nums) + 3): if i & mask: a ^= i else: b ^= i for num in nums: if num & mask: a ^= num else: b ^= num return [a, b] if __name__ == "__main__" : nums = [2,3] result = missingTwo(nums) print(result)
def missing_two(nums: [int]) -> [int]: ret = 0 for (i, num) in enumerate(nums): ret ^= i + 1 ret ^= num ret ^= len(nums) + 1 ret ^= len(nums) + 2 mask = 1 while mask & ret == 0: mask <<= 1 (a, b) = (0, 0) for i in range(1, len(nums) + 3): if i & mask: a ^= i else: b ^= i for num in nums: if num & mask: a ^= num else: b ^= num return [a, b] if __name__ == '__main__': nums = [2, 3] result = missing_two(nums) print(result)
def diff_records(left, right): ''' Given lists of [year, value] pairs, return list of [year, difference] pairs. Fails if the inputs are not for exactly corresponding years. ''' assert len(left) == len(right), \ 'Inputs have different lengths.' num_years = len(left) results = [] for i in range(num_years): left_year, left_value = left[i] right_year, right_value = right[i] assert left_year == right_year, \ 'Record {0} is for different years: {1} vs {2}'.format(i, left_year, right_year) difference = left_value - right_value results.append([left_year, difference]) return results print('one record:', diff_records([[1900, 1.0]], [[1900, 2.0]])) print('two records:', diff_records([[1900, 1.0], [1901, 10.0]], [[1900, 2.0], [1901, 20.0]]))
def diff_records(left, right): """ Given lists of [year, value] pairs, return list of [year, difference] pairs. Fails if the inputs are not for exactly corresponding years. """ assert len(left) == len(right), 'Inputs have different lengths.' num_years = len(left) results = [] for i in range(num_years): (left_year, left_value) = left[i] (right_year, right_value) = right[i] assert left_year == right_year, 'Record {0} is for different years: {1} vs {2}'.format(i, left_year, right_year) difference = left_value - right_value results.append([left_year, difference]) return results print('one record:', diff_records([[1900, 1.0]], [[1900, 2.0]])) print('two records:', diff_records([[1900, 1.0], [1901, 10.0]], [[1900, 2.0], [1901, 20.0]]))
#!/usr/bin/python3 # -*- encoding="UTF-8" -*- #parameters listR = [] # listC = [] listL = [] listM = [] listE = [] listF = [] listG = [] listH = [] listD = [] listDCV = [] listSinV = [] listPulseV = [] listACV = [] listDCI = [] listSinI = [] listDCParam = [] listACParam = [] listTranParam = [] listPlotDC = [] listPlotAC = [] listPlotTran = [] opExp = [] opValue = [] opValueString = '' opExpString = '' NodesDict = { #Dictionary of Nodes '0':0 } ParamDict = { 'GND':0 } STEP = '10p' #STEP GND = 0 #define GND port is 0 NetlistPath = '/home/sun/Files/AutoDesign/Projects/src/TestCircuits' #The netlist file path and name regExpV = r'^v' #V regExpI = r'^i' #I regExpR = r'^r' #R regExpC = r'^c' #C regExpL = r'^l' #L regExpMos = r'^m' #Mosfet regExpD = r'^d' #Diode regExpVCVS = r'^e' #VCVS regExpCCCS = r'^f' #CCCS regExpVCCS = r'^g' #VCCS regExpCCVS = r'^h' #CCVS regExpComment = r'^\*' #Comment line regExpExtend = r'^\+' #Extend regExpCommand = r'^\.' #Command line regExpCommandDC = r'^\.dc' #DC regExpCommandAC = r'^\.ac' #AC regExpCommandTran = r'^\.tran' #Tran regExpCommandPrint = r'^\.print' #print regExpCommandPlot = r'^\.plot' #Plot regExpCommandEnd = r'^\.end$' #END regExpCommandOptions = r'^\.options' #Option regExpCommandOp = r'^\.op' #OP regExpCommandParam = r'^\.param' #Param regExpCommandLib = r'^\.lib' #lib FloatWithUnit = r'^[-+]?[0-9]*\.?[0-9]+\s?[fpnumkgt]?e?g?$' #Float with unit FloatWithoutUnit = r'^[-+]?[0-9]*\.?[0-9]+' #Float without unit FolatUnit = r'[fpnumkgt]?e?g?$' #Float unit SciNum = r'^[-+]?[1-9]\.?[0-9]*e?[-+]?[0-9]+$' #Sci Num regExpPlotV = r'^v\((.+)\)$' regExpPlotI = r'^i\((.+)\)$' #MosFet
list_r = [] list_c = [] list_l = [] list_m = [] list_e = [] list_f = [] list_g = [] list_h = [] list_d = [] list_dcv = [] list_sin_v = [] list_pulse_v = [] list_acv = [] list_dci = [] list_sin_i = [] list_dc_param = [] list_ac_param = [] list_tran_param = [] list_plot_dc = [] list_plot_ac = [] list_plot_tran = [] op_exp = [] op_value = [] op_value_string = '' op_exp_string = '' nodes_dict = {'0': 0} param_dict = {'GND': 0} step = '10p' gnd = 0 netlist_path = '/home/sun/Files/AutoDesign/Projects/src/TestCircuits' reg_exp_v = '^v' reg_exp_i = '^i' reg_exp_r = '^r' reg_exp_c = '^c' reg_exp_l = '^l' reg_exp_mos = '^m' reg_exp_d = '^d' reg_exp_vcvs = '^e' reg_exp_cccs = '^f' reg_exp_vccs = '^g' reg_exp_ccvs = '^h' reg_exp_comment = '^\\*' reg_exp_extend = '^\\+' reg_exp_command = '^\\.' reg_exp_command_dc = '^\\.dc' reg_exp_command_ac = '^\\.ac' reg_exp_command_tran = '^\\.tran' reg_exp_command_print = '^\\.print' reg_exp_command_plot = '^\\.plot' reg_exp_command_end = '^\\.end$' reg_exp_command_options = '^\\.options' reg_exp_command_op = '^\\.op' reg_exp_command_param = '^\\.param' reg_exp_command_lib = '^\\.lib' float_with_unit = '^[-+]?[0-9]*\\.?[0-9]+\\s?[fpnumkgt]?e?g?$' float_without_unit = '^[-+]?[0-9]*\\.?[0-9]+' folat_unit = '[fpnumkgt]?e?g?$' sci_num = '^[-+]?[1-9]\\.?[0-9]*e?[-+]?[0-9]+$' reg_exp_plot_v = '^v\\((.+)\\)$' reg_exp_plot_i = '^i\\((.+)\\)$'
# Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. """ The symmetry package implements symmetry tools, e.g., spacegroup determination, etc. """
""" The symmetry package implements symmetry tools, e.g., spacegroup determination, etc. """
def math(): while True: i_put = int(input()) if i_put == 0: break else: for i in range(1, i_put+1): for j in range(1, i_put+1): print(i, end=' ') j += 1 print() if __name__ == '__main__': math()
def math(): while True: i_put = int(input()) if i_put == 0: break else: for i in range(1, i_put + 1): for j in range(1, i_put + 1): print(i, end=' ') j += 1 print() if __name__ == '__main__': math()
PLUGIN_NAME = 'plugin' PACKAGE_NAME = 'mock-plugin' PACKAGE_VERSION = '1.0' def create_plugin_url(plugin_tar_name, file_server): return '{0}/{1}'.format(file_server.url, plugin_tar_name) def plugin_struct(file_server, source=None, args=None, name=PLUGIN_NAME, executor=None, package_name=PACKAGE_NAME): return { 'source': create_plugin_url(source, file_server) if source else None, 'install_arguments': args, 'name': name, 'package_name': package_name, 'executor': executor, 'package_version': '0.0.0' }
plugin_name = 'plugin' package_name = 'mock-plugin' package_version = '1.0' def create_plugin_url(plugin_tar_name, file_server): return '{0}/{1}'.format(file_server.url, plugin_tar_name) def plugin_struct(file_server, source=None, args=None, name=PLUGIN_NAME, executor=None, package_name=PACKAGE_NAME): return {'source': create_plugin_url(source, file_server) if source else None, 'install_arguments': args, 'name': name, 'package_name': package_name, 'executor': executor, 'package_version': '0.0.0'}
""" Author Samuel Souik License MIT endswith.py """ def endswith(string, target): """ Description ---------- Check to see if the target string is the end of the string. Parameters ---------- string : str - string to check end of\n target : str - string to search for Returns ---------- bool - True if target is the end of string, False otherwise Examples ---------- >>> endswith('Sample string', 'ing') -> True >>> endswith('abcabcabc', 'abcd') -> False """ if not isinstance(string, str): raise TypeError("param 'string' must be a string") if not isinstance(target, str): raise TypeError("param 'target' must be a string") return string[len(target) * -1 :] == target
""" Author Samuel Souik License MIT endswith.py """ def endswith(string, target): """ Description ---------- Check to see if the target string is the end of the string. Parameters ---------- string : str - string to check end of target : str - string to search for Returns ---------- bool - True if target is the end of string, False otherwise Examples ---------- >>> endswith('Sample string', 'ing') -> True >>> endswith('abcabcabc', 'abcd') -> False """ if not isinstance(string, str): raise type_error("param 'string' must be a string") if not isinstance(target, str): raise type_error("param 'target' must be a string") return string[len(target) * -1:] == target
# Title: Reverse Linked List II # Link: https://leetcode.com/problems/reverse-linked-list-ii/ class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Problem: def reverse_between(self, head: ListNode, m: int, n: int) -> ListNode: cur = head part = None n = n - m head_end, tail_head = None, None m -= 1 while m: m -= 1 head_end = cur cur = cur.next part = cur while n: n -= 1 cur = cur.next tail_head = cur.next cur.next = None part = self._rev(part, tail_head) if head_end: head_end.next = part return head return part def _rev(self, head: ListNode, taile: ListNode) -> ListNode: cur, rev = head, taile while cur.next: cur, rev, rev.next = cur.next, cur, rev cur, rev, rev.next = cur.next, cur, rev return rev def solution(): head = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))) m = 1 n = 4 problem = Problem() return problem.reverse_between(head, m, n) def main(): print(solution()) if __name__ == '__main__': main()
class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next class Problem: def reverse_between(self, head: ListNode, m: int, n: int) -> ListNode: cur = head part = None n = n - m (head_end, tail_head) = (None, None) m -= 1 while m: m -= 1 head_end = cur cur = cur.next part = cur while n: n -= 1 cur = cur.next tail_head = cur.next cur.next = None part = self._rev(part, tail_head) if head_end: head_end.next = part return head return part def _rev(self, head: ListNode, taile: ListNode) -> ListNode: (cur, rev) = (head, taile) while cur.next: (cur, rev, rev.next) = (cur.next, cur, rev) (cur, rev, rev.next) = (cur.next, cur, rev) return rev def solution(): head = list_node(1, list_node(2, list_node(3, list_node(4, list_node(5))))) m = 1 n = 4 problem = problem() return problem.reverse_between(head, m, n) def main(): print(solution()) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """Collection of exceptions raised by requests-toolbelt.""" class StreamingError(Exception): """Used in :mod:`requests_toolbelt.downloadutils.stream`.""" pass
"""Collection of exceptions raised by requests-toolbelt.""" class Streamingerror(Exception): """Used in :mod:`requests_toolbelt.downloadutils.stream`.""" pass
class TestImporter: domain_file = "test/data/domain-woz.xml" dialogue_file = "test/data/woz-dialogue.xml" domain_file2 = "test/data/example-domain-params.xml" dialogue_file2 = "test/data/dialogue.xml" # def test_importer(self): # system = DialogueSystem(XMLDomainReader.extract_domain(self.domain_file)) # # # NEED GUI # # system.get_settings().show_gui = False # # Settings.nr_samples = Settings.nr_samples / 10.0 # importer = system.import_dialogue(self.dialogue_file) # system.start_system() # # while importer.is_alive(): # threading.Event().wait(250) # # # NEED DialogueRecorder # # self.assertEqual()assertEquals(20, StringUtils.count_occurences(system.get_module(DialogueRecorder).getRecord(), "systemTurn")) # # self.assertEqual(22, StringUtils.count_occurences(system.get_module(DialogueRecorder).getRecord(), "userTurn")) # # Settings.nr_samples = Settings.nr_samples * 10 # def test_importer2(self): # system = DialogueSystem(XMLDomainReader.extract_domain(self.domain_file)) # system.get_settings().show_gui = False # Settings.nr_samples = Settings.nr_samples / 5.0 # system.start_system() # importer = system.import_dialogue(self.dialogue_file) # importer.setWizardOfOzMode(True) # # while importer.is_alive(): # threading.Event().wait(300) # # # NEED DialogueRecorder # # self.assertEqual(20, StringUtils.count_occurences(system.get_module(DialogueRecorder).getRecord(), "systemTurn")) # # self.assertEqual(22, StringUtils.count_occurences(system.get_module(DialogueRecorder).getRecord(), "userTurn")) # # self.assertTrue(system.get_state().getChanceNode("theta_1").get_distrib().get_function().get_mean()[0] > 12.0) # Settings.nr_samples = Settings.nr_samples * 5 # def test_importer3(self): # system = DialogueSystem(XMLDomainReader.extract_domain(self.domain_file2)) # system.get_settings().showGUI = False # system.start_system() # importer = system.import_dialogue(self.dialogue_file2) # # while importer.is_alive(): # threading.Event().wait(300) # # # NEED DialogueRecorder # # self.assertEqual(10, StringUtils.count_occurences(system.get_module(DialogueRecorder).getRecord(), "systemTurn")) # # self.assertEqual(10, StringUtils.count_occurences(system.get_module(DialogueRecorder).getRecord(), "userTurn")) # # self.assertAlmostEqual(system.get_state().getChanceNode("theta_repeat").get_distrib().get_function().get_mean()[0], 0.0, delta=0.2) # def test_importer4(self): # system = DialogueSystem(XMLDomainReader.extract_domain(self.domain_file2)) # Settings.nr_samples = Settings.nr_samples * 3 # Settings.max_sampling_time = Settings.max_sampling_time * 3 # # # NEED GUI # # system.get_settings().show_gui = False # # system.start_system() # importer = system.import_dialogue(self.dialogue_file2) # importer.setWizardOfOzMode(True) # # while importer.is_alive(): # threading.Event().wait(250) # # # NEED DialogueRecorder # # self.assertEqual(10, StringUtils.count_occurences(system.get_module(DialogueRecorder).getRecord(), "systemTurn")) # # self.assertEqual(10, StringUtils.count_occurences(system.get_module(DialogueRecorder).getRecord(), "userTurn")) # # self.assertAlmostEqual(system.get_state().getChanceNode("theta_repeat").get_distrib().get_function().get_mean()[0], 1.35, delta=0.3) # # Settings.nr_samples = Settings.nr_samples / 3.0 # Settings.maxSamplingTime = Settings.maxSamplingTime / 3.0
class Testimporter: domain_file = 'test/data/domain-woz.xml' dialogue_file = 'test/data/woz-dialogue.xml' domain_file2 = 'test/data/example-domain-params.xml' dialogue_file2 = 'test/data/dialogue.xml'
# define a function that: # has one parameter, a number, and returns that number tripled. # Q1: What do you name the function? # A: number_tripled # Q2: What are the parameters, and what types of information do they refer to? # A: one parameter of type number # Q2: What calculations are you doing with that information? # A: the input number (parameter) is going to be multiplied 3 times # Q3: What information does the function return? # A: The function returns the result of the input trippled input parameter # 1 Examples # 2 Header: Decide param names and types, and return type. Write header of the func. # 3 Description: short description of the function for others to read # 4 Body: write body of the function # 5 Test: run examples to make sure you function body is correct def number_tripled(num: int) -> int: """ precondition: number is a number take as input a number and multiply the number 3 times >>> number_tripled(5) 125 >>> number_tripled(2.2) 6 """ return num*3 # Q: Does it work like you expect it to? # A:
def number_tripled(num: int) -> int: """ precondition: number is a number take as input a number and multiply the number 3 times >>> number_tripled(5) 125 >>> number_tripled(2.2) 6 """ return num * 3
def factorial(x): if x <= 0: return x+1 else: return x * factorial(x-1) result = [] while True: try: n = input().split() a = int(n[0]) b = int(n[1]) result.append(factorial(a) + factorial(b)) except EOFError: break for i in range(0,len(result)): print(result[i])
def factorial(x): if x <= 0: return x + 1 else: return x * factorial(x - 1) result = [] while True: try: n = input().split() a = int(n[0]) b = int(n[1]) result.append(factorial(a) + factorial(b)) except EOFError: break for i in range(0, len(result)): print(result[i])
# OUT OF PLACE retuns new different dictionary def replace_dict_value(d, bad_val, good_val): new_dict = {} for key, value in d.items(): if bad_val == value: new_dict[key] = good_val else: new_dict[key] = value return new_dict og_dict = {'a':5,'b':6,'c':5} print(og_dict) fresh_dict = replace_dict_value(og_dict , 5, 10) print("Original dict:",og_dict) print("New dict:", fresh_dict) # IN PLACE version which modifies the original def replace_dict_value_in_place(d, bad_val, good_val): for key in d: #check a keys to correct bad values - will be the same as "i in d: if d[key] == bad_val: #check for bad value 5 in dictionary d[key] = good_val #set good value if i == 5 return d # returns alias for d we could even survive without this return since d is already changed og_dict = {'a':5,'b':6,'c':5} print(og_dict) fresh_dict = replace_dict_value_in_place(og_dict , 5, 10) print("Original dict:",og_dict) print("New dict:", fresh_dict)
def replace_dict_value(d, bad_val, good_val): new_dict = {} for (key, value) in d.items(): if bad_val == value: new_dict[key] = good_val else: new_dict[key] = value return new_dict og_dict = {'a': 5, 'b': 6, 'c': 5} print(og_dict) fresh_dict = replace_dict_value(og_dict, 5, 10) print('Original dict:', og_dict) print('New dict:', fresh_dict) def replace_dict_value_in_place(d, bad_val, good_val): for key in d: if d[key] == bad_val: d[key] = good_val return d og_dict = {'a': 5, 'b': 6, 'c': 5} print(og_dict) fresh_dict = replace_dict_value_in_place(og_dict, 5, 10) print('Original dict:', og_dict) print('New dict:', fresh_dict)
Dict = {1:'Amrik', 2: 'Abhi'} print (Dict) ##call print(Dict[1]) print(Dict.get(2))
dict = {1: 'Amrik', 2: 'Abhi'} print(Dict) print(Dict[1]) print(Dict.get(2))
##HEADING: Primality algorithm #PROBLEM STATEMENT: """ TO CHECK WHETHER AN INTEGER IS PRIME OR NOT. IF THE INTEGER IS PRIME RETURN TRUE. ELSE RETURN FALSE. """ #SOLUTION-1: (BRUTE_FORCE) --> O(n) def isPrime1(n: int) -> bool: if(n<=1): return False elif(n==2): return True else: for i in range(2, n): if(n%i==0): return False return True #SOLUTION-2: (BETTER_BRUTE_FORCE) --> O(n/2)==O(n)! def isPrime2(n: int) -> bool: if(n<=1): return False elif(n==2): return True else: for i in range(2, n//2): if(n%i==0): return False return True #SOLUTION-3: (ALGORIHTHM) --> O(sqrt(n)) def isPrime3(n: int) -> bool: if(n<=1): return False elif(n<=3): return True elif(n%2==0 or n%3==0): return False else: for i in range(5, int(n**0.5)+1): if(n%i==0): return False return True #SOLUTION-4 (BETTER_ALGORITHM) --> O(sqrt(n)/3)==O(sqrt(n))! def isPrime4(n: int) -> bool: if(n<=1): return False elif(n<=3): return True elif(n%2==0 or n%3==0): return False else: i=5 while(i<=int(n**0.5)): if(n%i==0 or n%(i+2)==0): return False i=i+6 return True #DESCRIPTION: """ OPTIMIZATION-1: (ALGORITHM) INSTEAD OF CHECKING TILL n, WE CAN CHECK TILL sqrt(n). BECAUSE A LARGER FACTOR OF n MUST BE A MULTIPLE OF SMALLER FACTOR THAT HAS BEEN ALREADY CHECKED. OPTIMIZATION-2: (BETTER_ALGORITHM) ALL INTEGERS CAN BE EXPRESSED AS THE FORM OF 6k+i. WHERE k IS SOME INTEGER. AND i IS 0, 1, 2, 3, 4, 5. OF THESE PRIME NUMBERS TAKE THE FORM WHERE i = 1 OR 5. I.E. PRIME NUMBERS ARE OF FORM 6k+1 or 6k+5. OR 6k-1 or 6k+1. SO WE CHECK DIVISIBLITY BY NUMBERS OF THIS FORMS ONLY. HERE i IS ALWAYS OF FORM 6k-1. AND i+2 OF FORM 6k+1. NOTE: isprime() IS A FUNCTION IN sympy MODULE WHICH CHECKS THE PRIMALITY. """ #RELATED ALGORITHMS: """ -FERMAT PRIMALITY TEST METHOD -MILLER RABIN PRIMALITY TEST METHOD -SOLOVAY STRASSEN PRIMALITY TEST METHOD -PRIMALITY TEST USING LUCAS LEHMER SERIES -AKS(AGRAWAL-KAYAL-SAXENA) PRIMALITY TEST METHOD -LUCAS PRIMALITY TEST -WILSON PRIMALITY TEST -VANTIEGHEMS THEOREM FOR PRIMALITY TEST """
""" TO CHECK WHETHER AN INTEGER IS PRIME OR NOT. IF THE INTEGER IS PRIME RETURN TRUE. ELSE RETURN FALSE. """ def is_prime1(n: int) -> bool: if n <= 1: return False elif n == 2: return True else: for i in range(2, n): if n % i == 0: return False return True def is_prime2(n: int) -> bool: if n <= 1: return False elif n == 2: return True else: for i in range(2, n // 2): if n % i == 0: return False return True def is_prime3(n: int) -> bool: if n <= 1: return False elif n <= 3: return True elif n % 2 == 0 or n % 3 == 0: return False else: for i in range(5, int(n ** 0.5) + 1): if n % i == 0: return False return True def is_prime4(n: int) -> bool: if n <= 1: return False elif n <= 3: return True elif n % 2 == 0 or n % 3 == 0: return False else: i = 5 while i <= int(n ** 0.5): if n % i == 0 or n % (i + 2) == 0: return False i = i + 6 return True '\n OPTIMIZATION-1: (ALGORITHM)\n INSTEAD OF CHECKING TILL n, WE CAN CHECK TILL sqrt(n).\n BECAUSE A LARGER FACTOR OF n MUST BE A MULTIPLE OF SMALLER\n FACTOR THAT HAS BEEN ALREADY CHECKED.\n OPTIMIZATION-2: (BETTER_ALGORITHM)\n ALL INTEGERS CAN BE EXPRESSED AS THE FORM OF 6k+i.\n WHERE k IS SOME INTEGER. AND i IS 0, 1, 2, 3, 4, 5.\n OF THESE PRIME NUMBERS TAKE THE FORM WHERE i = 1 OR 5.\n I.E. PRIME NUMBERS ARE OF FORM 6k+1 or 6k+5.\n OR 6k-1 or 6k+1.\n SO WE CHECK DIVISIBLITY BY NUMBERS OF THIS FORMS ONLY.\n HERE i IS ALWAYS OF FORM 6k-1. AND i+2 OF FORM 6k+1.\n \n NOTE: isprime() IS A FUNCTION IN sympy MODULE WHICH CHECKS THE PRIMALITY.\n ' '\n -FERMAT PRIMALITY TEST METHOD\n -MILLER RABIN PRIMALITY TEST METHOD\n -SOLOVAY STRASSEN PRIMALITY TEST METHOD\n -PRIMALITY TEST USING LUCAS LEHMER SERIES\n -AKS(AGRAWAL-KAYAL-SAXENA) PRIMALITY TEST METHOD\n -LUCAS PRIMALITY TEST\n -WILSON PRIMALITY TEST\n -VANTIEGHEMS THEOREM FOR PRIMALITY TEST\n '
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return None return self.connect_right_pointers(root) def connect_right_pointers(self, root): """ """ node = root level = 0 # start off with root queue = [(node, level)] while queue: node, p_level = queue.pop(0) if node.left: queue.append((node.left, p_level+1)) if node.right: queue.append((node.right, p_level+1)) # check if queue is not empty if queue: # peek the top, if the levels are the same then we can connect next_node, n_level = queue[0] # if their level is equal then we can connect if p_level == n_level: node.next = next_node # if level is not equal else: node.next = None # else we pop the last item we just assign the next pointer to none else: node.next = None return root def connect_no_extra_space(self, root): """ Connects the tree nodes with right side of the node, if exists using no extra memory credit https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/37461/Java-solution-with-O(1)-memory%2B-O(n)-time """ # curr level level = root while level is not None: # curr node node = level while node is not None: # if left node and right exists if node.left: node.left.next = node.right # if only left node if node.right is not None and node.next is not None: node.right.next = node.next.left node = node.next # step down one level level = level.left
""" # Definition for a Node. class Node: def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None): self.val = val self.left = left self.right = right self.next = next """ class Solution: def connect(self, root: 'Node') -> 'Node': if not root: return None return self.connect_right_pointers(root) def connect_right_pointers(self, root): """ """ node = root level = 0 queue = [(node, level)] while queue: (node, p_level) = queue.pop(0) if node.left: queue.append((node.left, p_level + 1)) if node.right: queue.append((node.right, p_level + 1)) if queue: (next_node, n_level) = queue[0] if p_level == n_level: node.next = next_node else: node.next = None else: node.next = None return root def connect_no_extra_space(self, root): """ Connects the tree nodes with right side of the node, if exists using no extra memory credit https://leetcode.com/problems/populating-next-right-pointers-in-each-node/discuss/37461/Java-solution-with-O(1)-memory%2B-O(n)-time """ level = root while level is not None: node = level while node is not None: if node.left: node.left.next = node.right if node.right is not None and node.next is not None: node.right.next = node.next.left node = node.next level = level.left
# Copyright (c) 2016-2017 Dustin Doloff # Licensed under Apache License v2.0 load( "@bazel_toolbox//labels:labels.bzl", "executable_label", ) load( ":internal.bzl", "web_internal_generate_variables", ) generate_variables = rule( attrs = { "config": attr.label( mandatory = True, allow_single_file = True, ), "out_js": attr.output(), "out_css": attr.output(), "out_scss": attr.output(), "_generate_variables_script": executable_label(Label("//generate:generate_variables")), }, output_to_genfiles = True, implementation = web_internal_generate_variables, )
load('@bazel_toolbox//labels:labels.bzl', 'executable_label') load(':internal.bzl', 'web_internal_generate_variables') generate_variables = rule(attrs={'config': attr.label(mandatory=True, allow_single_file=True), 'out_js': attr.output(), 'out_css': attr.output(), 'out_scss': attr.output(), '_generate_variables_script': executable_label(label('//generate:generate_variables'))}, output_to_genfiles=True, implementation=web_internal_generate_variables)
"""title https://adventofcode.com/2021/day/1 """ def solve(data): return data def solve2(data): return data if __name__ == '__main__': input_data = open('input_data.txt').read() result = solve(input_data) print(f'Example 1: {result}') result = solve2(input_data) print(f'Example 2: {result}')
"""title https://adventofcode.com/2021/day/1 """ def solve(data): return data def solve2(data): return data if __name__ == '__main__': input_data = open('input_data.txt').read() result = solve(input_data) print(f'Example 1: {result}') result = solve2(input_data) print(f'Example 2: {result}')
#!/usr/bin/env python # encoding: utf-8 class Insertion(object): """Insertions do affect an applied sequence and do not store a sequence themselves. They are a skip if the length is less than 0 Args: index (int): the index into the `StrandSet` the `Insertion` occurs at length (int): length of `Insertion` """ __slots__ = '_length', '_index' def __init__(self, index, length): self._length = length self._index = index # end def def length(self): """This is the length of a sequence that is immutable by the strand Returns: int: length of `Insertion` """ return self._length def setLength(self, length): """Setter for the length Args: length (int): """ self._length = length # end def def updateIdx(self, delta): """Increment the index by delta Args: delta (int): can be negative """ self._index += delta # end def def idx(self): """ Returns: int: the index into the `StrandSet` the `Insertion` occurs at """ return self._index # end def def isSkip(self): """ Returns: bool: True is is a skip, False otherwise """ return self._length < 0 # end class
class Insertion(object): """Insertions do affect an applied sequence and do not store a sequence themselves. They are a skip if the length is less than 0 Args: index (int): the index into the `StrandSet` the `Insertion` occurs at length (int): length of `Insertion` """ __slots__ = ('_length', '_index') def __init__(self, index, length): self._length = length self._index = index def length(self): """This is the length of a sequence that is immutable by the strand Returns: int: length of `Insertion` """ return self._length def set_length(self, length): """Setter for the length Args: length (int): """ self._length = length def update_idx(self, delta): """Increment the index by delta Args: delta (int): can be negative """ self._index += delta def idx(self): """ Returns: int: the index into the `StrandSet` the `Insertion` occurs at """ return self._index def is_skip(self): """ Returns: bool: True is is a skip, False otherwise """ return self._length < 0
#https://www.codechef.com/problems/CHEFEZQ for _ in range(int(input())): q,k=map(int,input().split()) l=list(map(int,input().split())) rem=0 c=0 f=0 for i in range(q): rem+=l[i] if(rem-k<0): f=1 break c+=1 rem-=k print(c+1) if f else print(int(sum(l)/k)+1) '''in this problem we have to check weather chef free inbetween of queries print till that queries if not then sum of all queries + 1 '''
for _ in range(int(input())): (q, k) = map(int, input().split()) l = list(map(int, input().split())) rem = 0 c = 0 f = 0 for i in range(q): rem += l[i] if rem - k < 0: f = 1 break c += 1 rem -= k print(c + 1) if f else print(int(sum(l) / k) + 1) 'in this problem we have to check weather chef \nfree inbetween of queries print till that queries \nif not then sum of all queries + 1 '
# python_version >= '3.8' #: Okay class C: def __init__(self, a, /, b=None): pass #: N805:2:18 class C: def __init__(this, a, /, b=None): pass
class C: def __init__(self, a, /, b=None): pass class C: def __init__(this, a, /, b=None): pass
# Write your solution here def count_matching_elements(my_matrix: list, element: int): count = 0 for row in my_matrix: for item in row: if item == element: count += 1 return count if __name__ == "__main__": m = [[1, 2, 1], [0, 3, 4], [1, 0, 0]] print(count_matching_elements(m, 1))
def count_matching_elements(my_matrix: list, element: int): count = 0 for row in my_matrix: for item in row: if item == element: count += 1 return count if __name__ == '__main__': m = [[1, 2, 1], [0, 3, 4], [1, 0, 0]] print(count_matching_elements(m, 1))
{ "version": "eosio::abi/1.0", "types": [], "structs": [ { "name": "newaccount", "base": "", "fields": [ {"name":"account", "type":"name"}, {"name":"pub_key", "type":"public_key"} ] } ], "actions": [{ "name": "newaccount", "type": "newaccount", "ricardian_contract": "" }], "tables": [], "ricardian_clauses": [], "error_messages": [], "abi_extensions": [] }
{'version': 'eosio::abi/1.0', 'types': [], 'structs': [{'name': 'newaccount', 'base': '', 'fields': [{'name': 'account', 'type': 'name'}, {'name': 'pub_key', 'type': 'public_key'}]}], 'actions': [{'name': 'newaccount', 'type': 'newaccount', 'ricardian_contract': ''}], 'tables': [], 'ricardian_clauses': [], 'error_messages': [], 'abi_extensions': []}
iput = input('Multiphy number') divi = input ('Multiply By?') try: put = int(iput) di = int(divi) ans = put * di except: print('Invalid Value') quit() print(ans)
iput = input('Multiphy number') divi = input('Multiply By?') try: put = int(iput) di = int(divi) ans = put * di except: print('Invalid Value') quit() print(ans)
# Python3 program to find the # max LRproduct[i] among all i # Method to find the next greater # value in left side def nextGreaterInLeft(a): left_index = [0] * len(a) s = [] for i in range(len(a)): # Checking if current # element is greater than top while len(s) != 0 and a[i] >= a[s[-1]]: # Pop the element till we can't # get the larger value then # the current value s.pop() if len(s) != 0: left_index[i] = s[-1] else: left_index[i] = 0 # Else push the element in the stack s.append(i) return left_index # Method to find the next # greater value in right def nextGreaterInRight(a): right_index = [0] * len(a) s = [] for i in range(len(a) - 1, -1, -1): # Checking if current element # is greater than top while len(s) != 0 and a[i] >= a[s[-1]]: # Pop the element till we can't # get the larger value then # the current value s.pop() if len(s) != 0: right_index[i] = s[-1] else: right_index[i] = 0 # Else push the element in the stack s.append(i) return right_index def LRProduct(arr): # For each element storing # the index of just greater # element in left side left = nextGreaterInLeft(arr) # For each element storing # the index of just greater # element in right side right = nextGreaterInRight(arr) ans = -1 # As we know the answer will # belong to the range from # 1st index to second last index. # Because for 1st index left # will be 0 and for last # index right will be 0 for i in range(1, len(left) - 1): if left[i] == 0 or right[i] == 0: # Finding the max index product ans = max(ans, 0) else: temp = (left[i] + 1) * (right[i] + 1) # Finding the max index product ans = max(ans, temp) return ans # Driver Code arr = [ 5, 4, 3, 4, 5 ] print(LRProduct(arr))
def next_greater_in_left(a): left_index = [0] * len(a) s = [] for i in range(len(a)): while len(s) != 0 and a[i] >= a[s[-1]]: s.pop() if len(s) != 0: left_index[i] = s[-1] else: left_index[i] = 0 s.append(i) return left_index def next_greater_in_right(a): right_index = [0] * len(a) s = [] for i in range(len(a) - 1, -1, -1): while len(s) != 0 and a[i] >= a[s[-1]]: s.pop() if len(s) != 0: right_index[i] = s[-1] else: right_index[i] = 0 s.append(i) return right_index def lr_product(arr): left = next_greater_in_left(arr) right = next_greater_in_right(arr) ans = -1 for i in range(1, len(left) - 1): if left[i] == 0 or right[i] == 0: ans = max(ans, 0) else: temp = (left[i] + 1) * (right[i] + 1) ans = max(ans, temp) return ans arr = [5, 4, 3, 4, 5] print(lr_product(arr))
""" We can set t equal to the exponent: t = a^4 + 1 r(t) = e^t Then: dt/da = 4a^3 dr/dt = e^t Now we can use the chain rule: dr/da = dr/dt * dt/da = e^t(4a^3) = 4a^3e^{a^4 + 1} """
""" We can set t equal to the exponent: t = a^4 + 1 r(t) = e^t Then: dt/da = 4a^3 dr/dt = e^t Now we can use the chain rule: dr/da = dr/dt * dt/da = e^t(4a^3) = 4a^3e^{a^4 + 1} """
CALENDAR_CACHE_TIME = 5*60 # seconds CALENDAR_COLORS = ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854'] CALENDARS = [ { 'name': 'ATP Tennis 2018', 'color': CALENDAR_COLORS[0], 'url': '''https://p23-calendars.icloud.com/published/2/PMXFAiuTnEBHpFCFP8YdjnQt3zIkrpTgDwH58V9EWgy0_sZKiUMsrUl_DTyynnz5iCTEdu-h3ojPtsTwhzz59tWWK3zayhyHkYWvdcOaDeA''', }, { 'name': 'Holidays', 'color':CALENDAR_COLORS[4], 'url': 'https://calendar.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics', } ] TWILIO = { 'account-sid': 'your-account-sid', 'auth-token': 'your-auth-token', 'phone-number': '+12345678910' } SENDGRID = { 'api-key': 'your-key' } TODOIST = { 'apikey': 'your-key', 'projects': ['The list'] } SONOS = { 'ip': '192.168.0.9' }
calendar_cache_time = 5 * 60 calendar_colors = ['#66c2a5', '#fc8d62', '#8da0cb', '#e78ac3', '#a6d854'] calendars = [{'name': 'ATP Tennis 2018', 'color': CALENDAR_COLORS[0], 'url': 'https://p23-calendars.icloud.com/published/2/PMXFAiuTnEBHpFCFP8YdjnQt3zIkrpTgDwH58V9EWgy0_sZKiUMsrUl_DTyynnz5iCTEdu-h3ojPtsTwhzz59tWWK3zayhyHkYWvdcOaDeA'}, {'name': 'Holidays', 'color': CALENDAR_COLORS[4], 'url': 'https://calendar.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics'}] twilio = {'account-sid': 'your-account-sid', 'auth-token': 'your-auth-token', 'phone-number': '+12345678910'} sendgrid = {'api-key': 'your-key'} todoist = {'apikey': 'your-key', 'projects': ['The list']} sonos = {'ip': '192.168.0.9'}
class AbstractNotification(object): def show_message(self, title, message): """ Show message in the notification system of the OS. Parameters: title: The title of the notification. message: The notification message. """ raise NotImplementedError()
class Abstractnotification(object): def show_message(self, title, message): """ Show message in the notification system of the OS. Parameters: title: The title of the notification. message: The notification message. """ raise not_implemented_error()
""" File with rsa test keys. CAUTION: DO NOT USE THEM IN YOUR PRODUCTION CODE! """ private = '-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC7VJTUt9Us8cKj\nMzEfYyjiWA4R4/M2bS1GB4t7NXp98C3SC6dVMvDuictGeurT8jNbvJZHtCSuYEvu\nNMoSfm76oqFvAp8Gy0iz5sxjZmSnXyCdPEovGhLa0VzMaQ8s+CLOyS56YyCFGeJZ\nqgtzJ6GR3eqoYSW9b9UMvkBpZODSctWSNGj3P7jRFDO5VoTwCQAWbFnOjDfH5Ulg\np2PKSQnSJP3AJLQNFNe7br1XbrhV//eO+t51mIpGSDCUv3E0DDFcWDTH9cXDTTlR\nZVEiR2BwpZOOkE/Z0/BVnhZYL71oZV34bKfWjQIt6V/isSMahdsAASACp4ZTGtwi\nVuNd9tybAgMBAAECggEBAKTmjaS6tkK8BlPXClTQ2vpz/N6uxDeS35mXpqasqskV\nlaAidgg/sWqpjXDbXr93otIMLlWsM+X0CqMDgSXKejLS2jx4GDjI1ZTXg++0AMJ8\nsJ74pWzVDOfmCEQ/7wXs3+cbnXhKriO8Z036q92Qc1+N87SI38nkGa0ABH9CN83H\nmQqt4fB7UdHzuIRe/me2PGhIq5ZBzj6h3BpoPGzEP+x3l9YmK8t/1cN0pqI+dQwY\ndgfGjackLu/2qH80MCF7IyQaseZUOJyKrCLtSD/Iixv/hzDEUPfOCjFDgTpzf3cw\nta8+oE4wHCo1iI1/4TlPkwmXx4qSXtmw4aQPz7IDQvECgYEA8KNThCO2gsC2I9PQ\nDM/8Cw0O983WCDY+oi+7JPiNAJwv5DYBqEZB1QYdj06YD16XlC/HAZMsMku1na2T\nN0driwenQQWzoev3g2S7gRDoS/FCJSI3jJ+kjgtaA7Qmzlgk1TxODN+G1H91HW7t\n0l7VnL27IWyYo2qRRK3jzxqUiPUCgYEAx0oQs2reBQGMVZnApD1jeq7n4MvNLcPv\nt8b/eU9iUv6Y4Mj0Suo/AU8lYZXm8ubbqAlwz2VSVunD2tOplHyMUrtCtObAfVDU\nAhCndKaA9gApgfb3xw1IKbuQ1u4IF1FJl3VtumfQn//LiH1B3rXhcdyo3/vIttEk\n48RakUKClU8CgYEAzV7W3COOlDDcQd935DdtKBFRAPRPAlspQUnzMi5eSHMD/ISL\nDY5IiQHbIH83D4bvXq0X7qQoSBSNP7Dvv3HYuqMhf0DaegrlBuJllFVVq9qPVRnK\nxt1Il2HgxOBvbhOT+9in1BzA+YJ99UzC85O0Qz06A+CmtHEy4aZ2kj5hHjECgYEA\nmNS4+A8Fkss8Js1RieK2LniBxMgmYml3pfVLKGnzmng7H2+cwPLhPIzIuwytXywh\n2bzbsYEfYx3EoEVgMEpPhoarQnYPukrJO4gwE2o5Te6T5mJSZGlQJQj9q4ZB2Dfz\net6INsK0oG8XVGXSpQvQh3RUYekCZQkBBFcpqWpbIEsCgYAnM3DQf3FJoSnXaMhr\nVBIovic5l0xFkEHskAjFTevO86Fsz1C2aSeRKSqGFoOQ0tmJzBEs1R6KqnHInicD\nTQrKhArgLXX4v3CddjfTRJkFWDbE/CkvKZNOrcf1nhaGCPspRJj2KUkj1Fhl9Cnc\ndn/RsYEONbwQSjIfMPkvxF+8HQ==\n-----END PRIVATE KEY-----\n' public = '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo\n4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0/IzW7yWR7QkrmBL7jTKEn5u\n+qKhbwKfBstIs+bMY2Zkp18gnTxKLxoS2tFczGkPLPgizskuemMghRniWaoLcyeh\nkd3qqGElvW/VDL5AaWTg0nLVkjRo9z+40RQzuVaE8AkAFmxZzow3x+VJYKdjykkJ\n0iT9wCS0DRTXu269V264Vf/3jvredZiKRkgwlL9xNAwxXFg0x/XFw005UWVRIkdg\ncKWTjpBP2dPwVZ4WWC+9aGVd+Gyn1o0CLelf4rEjGoXbAAEgAqeGUxrcIlbjXfbc\nmwIDAQAB\n-----END PUBLIC KEY-----\n'
""" File with rsa test keys. CAUTION: DO NOT USE THEM IN YOUR PRODUCTION CODE! """ private = '-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC7VJTUt9Us8cKj\nMzEfYyjiWA4R4/M2bS1GB4t7NXp98C3SC6dVMvDuictGeurT8jNbvJZHtCSuYEvu\nNMoSfm76oqFvAp8Gy0iz5sxjZmSnXyCdPEovGhLa0VzMaQ8s+CLOyS56YyCFGeJZ\nqgtzJ6GR3eqoYSW9b9UMvkBpZODSctWSNGj3P7jRFDO5VoTwCQAWbFnOjDfH5Ulg\np2PKSQnSJP3AJLQNFNe7br1XbrhV//eO+t51mIpGSDCUv3E0DDFcWDTH9cXDTTlR\nZVEiR2BwpZOOkE/Z0/BVnhZYL71oZV34bKfWjQIt6V/isSMahdsAASACp4ZTGtwi\nVuNd9tybAgMBAAECggEBAKTmjaS6tkK8BlPXClTQ2vpz/N6uxDeS35mXpqasqskV\nlaAidgg/sWqpjXDbXr93otIMLlWsM+X0CqMDgSXKejLS2jx4GDjI1ZTXg++0AMJ8\nsJ74pWzVDOfmCEQ/7wXs3+cbnXhKriO8Z036q92Qc1+N87SI38nkGa0ABH9CN83H\nmQqt4fB7UdHzuIRe/me2PGhIq5ZBzj6h3BpoPGzEP+x3l9YmK8t/1cN0pqI+dQwY\ndgfGjackLu/2qH80MCF7IyQaseZUOJyKrCLtSD/Iixv/hzDEUPfOCjFDgTpzf3cw\nta8+oE4wHCo1iI1/4TlPkwmXx4qSXtmw4aQPz7IDQvECgYEA8KNThCO2gsC2I9PQ\nDM/8Cw0O983WCDY+oi+7JPiNAJwv5DYBqEZB1QYdj06YD16XlC/HAZMsMku1na2T\nN0driwenQQWzoev3g2S7gRDoS/FCJSI3jJ+kjgtaA7Qmzlgk1TxODN+G1H91HW7t\n0l7VnL27IWyYo2qRRK3jzxqUiPUCgYEAx0oQs2reBQGMVZnApD1jeq7n4MvNLcPv\nt8b/eU9iUv6Y4Mj0Suo/AU8lYZXm8ubbqAlwz2VSVunD2tOplHyMUrtCtObAfVDU\nAhCndKaA9gApgfb3xw1IKbuQ1u4IF1FJl3VtumfQn//LiH1B3rXhcdyo3/vIttEk\n48RakUKClU8CgYEAzV7W3COOlDDcQd935DdtKBFRAPRPAlspQUnzMi5eSHMD/ISL\nDY5IiQHbIH83D4bvXq0X7qQoSBSNP7Dvv3HYuqMhf0DaegrlBuJllFVVq9qPVRnK\nxt1Il2HgxOBvbhOT+9in1BzA+YJ99UzC85O0Qz06A+CmtHEy4aZ2kj5hHjECgYEA\nmNS4+A8Fkss8Js1RieK2LniBxMgmYml3pfVLKGnzmng7H2+cwPLhPIzIuwytXywh\n2bzbsYEfYx3EoEVgMEpPhoarQnYPukrJO4gwE2o5Te6T5mJSZGlQJQj9q4ZB2Dfz\net6INsK0oG8XVGXSpQvQh3RUYekCZQkBBFcpqWpbIEsCgYAnM3DQf3FJoSnXaMhr\nVBIovic5l0xFkEHskAjFTevO86Fsz1C2aSeRKSqGFoOQ0tmJzBEs1R6KqnHInicD\nTQrKhArgLXX4v3CddjfTRJkFWDbE/CkvKZNOrcf1nhaGCPspRJj2KUkj1Fhl9Cnc\ndn/RsYEONbwQSjIfMPkvxF+8HQ==\n-----END PRIVATE KEY-----\n' public = '-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu1SU1LfVLPHCozMxH2Mo\n4lgOEePzNm0tRgeLezV6ffAt0gunVTLw7onLRnrq0/IzW7yWR7QkrmBL7jTKEn5u\n+qKhbwKfBstIs+bMY2Zkp18gnTxKLxoS2tFczGkPLPgizskuemMghRniWaoLcyeh\nkd3qqGElvW/VDL5AaWTg0nLVkjRo9z+40RQzuVaE8AkAFmxZzow3x+VJYKdjykkJ\n0iT9wCS0DRTXu269V264Vf/3jvredZiKRkgwlL9xNAwxXFg0x/XFw005UWVRIkdg\ncKWTjpBP2dPwVZ4WWC+9aGVd+Gyn1o0CLelf4rEjGoXbAAEgAqeGUxrcIlbjXfbc\nmwIDAQAB\n-----END PUBLIC KEY-----\n'
# # PySNMP MIB module ZYXEL-CFM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-CFM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:43:08 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) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection") dot1agCfmMaIndex, dot1agCfmMdIndex, dot1agCfmMepIdentifier = mibBuilder.importSymbols("IEEE8021-CFM-MIB", "dot1agCfmMaIndex", "dot1agCfmMdIndex", "dot1agCfmMepIdentifier") EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") iso, NotificationType, TimeTicks, Gauge32, Counter64, Counter32, MibIdentifier, ModuleIdentity, Bits, Unsigned32, IpAddress, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "TimeTicks", "Gauge32", "Counter64", "Counter32", "MibIdentifier", "ModuleIdentity", "Bits", "Unsigned32", "IpAddress", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity") TextualConvention, DisplayString, TDomain = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "TDomain") esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt") zyxelCfm = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13)) if mibBuilder.loadTexts: zyxelCfm.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelCfm.setOrganization('Enterprise Solution ZyXEL') zyxelCfmSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1)) zyxelCfmStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 2)) zyCfmState = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyCfmState.setStatus('current') zyxelCfmMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2)) zyCfmMgmtIpAddressDomain = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2, 1), TDomain()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyCfmMgmtIpAddressDomain.setStatus('current') zyCfmMgmtIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2, 2), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyCfmMgmtIpAddress.setStatus('current') zyxelCfmMepTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2, 3), ) if mibBuilder.loadTexts: zyxelCfmMepTable.setStatus('current') zyxelCfmMepEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2, 3, 1), ).setIndexNames((0, "IEEE8021-CFM-MIB", "dot1agCfmMdIndex"), (0, "IEEE8021-CFM-MIB", "dot1agCfmMaIndex"), (0, "IEEE8021-CFM-MIB", "dot1agCfmMepIdentifier")) if mibBuilder.loadTexts: zyxelCfmMepEntry.setStatus('current') zyCfmMepTransmitLbmDataTlvSize = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2, 3, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 1500))).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyCfmMepTransmitLbmDataTlvSize.setStatus('current') zyCfmLinkTraceClear = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 2, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyCfmLinkTraceClear.setStatus('current') zyCfmMepCcmDbClear = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 2, 2), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyCfmMepCcmDbClear.setStatus('current') zyCfmMepDefectsClear = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 2, 3), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyCfmMepDefectsClear.setStatus('current') zyCfmMipCcmDbClear = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 2, 4), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyCfmMipCcmDbClear.setStatus('current') mibBuilder.exportSymbols("ZYXEL-CFM-MIB", zyxelCfm=zyxelCfm, zyCfmMgmtIpAddressDomain=zyCfmMgmtIpAddressDomain, zyCfmMgmtIpAddress=zyCfmMgmtIpAddress, zyCfmMipCcmDbClear=zyCfmMipCcmDbClear, zyxelCfmMibObjects=zyxelCfmMibObjects, zyxelCfmMepEntry=zyxelCfmMepEntry, zyCfmMepTransmitLbmDataTlvSize=zyCfmMepTransmitLbmDataTlvSize, zyCfmMepCcmDbClear=zyCfmMepCcmDbClear, zyxelCfmSetup=zyxelCfmSetup, PYSNMP_MODULE_ID=zyxelCfm, zyxelCfmStatus=zyxelCfmStatus, zyCfmMepDefectsClear=zyCfmMepDefectsClear, zyCfmState=zyCfmState, zyCfmLinkTraceClear=zyCfmLinkTraceClear, zyxelCfmMepTable=zyxelCfmMepTable)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection') (dot1ag_cfm_ma_index, dot1ag_cfm_md_index, dot1ag_cfm_mep_identifier) = mibBuilder.importSymbols('IEEE8021-CFM-MIB', 'dot1agCfmMaIndex', 'dot1agCfmMdIndex', 'dot1agCfmMepIdentifier') (enabled_status,) = mibBuilder.importSymbols('P-BRIDGE-MIB', 'EnabledStatus') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (iso, notification_type, time_ticks, gauge32, counter64, counter32, mib_identifier, module_identity, bits, unsigned32, ip_address, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'NotificationType', 'TimeTicks', 'Gauge32', 'Counter64', 'Counter32', 'MibIdentifier', 'ModuleIdentity', 'Bits', 'Unsigned32', 'IpAddress', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity') (textual_convention, display_string, t_domain) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString', 'TDomain') (es_mgmt,) = mibBuilder.importSymbols('ZYXEL-ES-SMI', 'esMgmt') zyxel_cfm = module_identity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13)) if mibBuilder.loadTexts: zyxelCfm.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelCfm.setOrganization('Enterprise Solution ZyXEL') zyxel_cfm_setup = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1)) zyxel_cfm_status = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 2)) zy_cfm_state = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 1), enabled_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyCfmState.setStatus('current') zyxel_cfm_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2)) zy_cfm_mgmt_ip_address_domain = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2, 1), t_domain()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyCfmMgmtIpAddressDomain.setStatus('current') zy_cfm_mgmt_ip_address = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2, 2), ip_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyCfmMgmtIpAddress.setStatus('current') zyxel_cfm_mep_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2, 3)) if mibBuilder.loadTexts: zyxelCfmMepTable.setStatus('current') zyxel_cfm_mep_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2, 3, 1)).setIndexNames((0, 'IEEE8021-CFM-MIB', 'dot1agCfmMdIndex'), (0, 'IEEE8021-CFM-MIB', 'dot1agCfmMaIndex'), (0, 'IEEE8021-CFM-MIB', 'dot1agCfmMepIdentifier')) if mibBuilder.loadTexts: zyxelCfmMepEntry.setStatus('current') zy_cfm_mep_transmit_lbm_data_tlv_size = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 1, 2, 3, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 1500))).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyCfmMepTransmitLbmDataTlvSize.setStatus('current') zy_cfm_link_trace_clear = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 2, 1), enabled_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyCfmLinkTraceClear.setStatus('current') zy_cfm_mep_ccm_db_clear = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 2, 2), enabled_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyCfmMepCcmDbClear.setStatus('current') zy_cfm_mep_defects_clear = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 2, 3), enabled_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyCfmMepDefectsClear.setStatus('current') zy_cfm_mip_ccm_db_clear = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 13, 2, 4), enabled_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyCfmMipCcmDbClear.setStatus('current') mibBuilder.exportSymbols('ZYXEL-CFM-MIB', zyxelCfm=zyxelCfm, zyCfmMgmtIpAddressDomain=zyCfmMgmtIpAddressDomain, zyCfmMgmtIpAddress=zyCfmMgmtIpAddress, zyCfmMipCcmDbClear=zyCfmMipCcmDbClear, zyxelCfmMibObjects=zyxelCfmMibObjects, zyxelCfmMepEntry=zyxelCfmMepEntry, zyCfmMepTransmitLbmDataTlvSize=zyCfmMepTransmitLbmDataTlvSize, zyCfmMepCcmDbClear=zyCfmMepCcmDbClear, zyxelCfmSetup=zyxelCfmSetup, PYSNMP_MODULE_ID=zyxelCfm, zyxelCfmStatus=zyxelCfmStatus, zyCfmMepDefectsClear=zyCfmMepDefectsClear, zyCfmState=zyCfmState, zyCfmLinkTraceClear=zyCfmLinkTraceClear, zyxelCfmMepTable=zyxelCfmMepTable)
N,M=map(int,input().split()) if M == 1 or M == 2: print("NEWBIE!") elif M<=N: print("OLDBIE!") else: print("TLE!")
(n, m) = map(int, input().split()) if M == 1 or M == 2: print('NEWBIE!') elif M <= N: print('OLDBIE!') else: print('TLE!')
# -*- coding: utf-8 -*- """ Created on Sun Dec 22 17:55:16 2019 @author: penko Return team information for the current set of OWL teams. Elements such as team colors, which may change from season to season, only return their current values. For example, the Florida Mayhem colors return Black and Pink instead of their old Yellow and Red """ ''' # packages used in this function import requests import pandas as pd ''' def getTeams(): # API call teams = requests.get('https://api.overwatchleague.com/v2/teams') if teams.status_code != 200: print("Error: Could not retrieve data from server. Code ", teams.status_code, sep='') return None t_json = teams.json() t_df = pd.DataFrame( [ { "id": t['id'], "name": t['name'], "abbr_name": t['abbreviatedName'], "division_id": t['divisionId'], "location": t['location'], "color_primary": t['colors']['primary']['color'], "color_secondary": t['colors']['secondary']['color'], "logo_main": t['logo']['main']['svg'] if 'main' in t['logo'] else "", "logo_alt": t['logo']['alt']['svg'] if 'alt' in t['logo'] else "", "logo_main_name": t['logo']['mainName']['svg'] if 'mainName' in t['logo'] else "", "logo_alt_dark": t['logo']['altDark']['svg'] if 'altDark' in t['logo'] else "" } for t in t_json['data'] ] ) return t_df
""" Created on Sun Dec 22 17:55:16 2019 @author: penko Return team information for the current set of OWL teams. Elements such as team colors, which may change from season to season, only return their current values. For example, the Florida Mayhem colors return Black and Pink instead of their old Yellow and Red """ '\n# packages used in this function\nimport requests\nimport pandas as pd\n' def get_teams(): teams = requests.get('https://api.overwatchleague.com/v2/teams') if teams.status_code != 200: print('Error: Could not retrieve data from server. Code ', teams.status_code, sep='') return None t_json = teams.json() t_df = pd.DataFrame([{'id': t['id'], 'name': t['name'], 'abbr_name': t['abbreviatedName'], 'division_id': t['divisionId'], 'location': t['location'], 'color_primary': t['colors']['primary']['color'], 'color_secondary': t['colors']['secondary']['color'], 'logo_main': t['logo']['main']['svg'] if 'main' in t['logo'] else '', 'logo_alt': t['logo']['alt']['svg'] if 'alt' in t['logo'] else '', 'logo_main_name': t['logo']['mainName']['svg'] if 'mainName' in t['logo'] else '', 'logo_alt_dark': t['logo']['altDark']['svg'] if 'altDark' in t['logo'] else ''} for t in t_json['data']]) return t_df
class AccountSetting: """Class for several configs""" username = 'loodahu' # Set username here password = '123456' # Set password here def get_username(self): return self.username def get_password(self): return self.password
class Accountsetting: """Class for several configs""" username = 'loodahu' password = '123456' def get_username(self): return self.username def get_password(self): return self.password
class MetricObjective: def __init__(self, task): self.task = task self.clear() def clear(self): self.total = 0 self.iter = 0 def step(self): self.total = 0 self.iter += 1 def update(self, logits, targets, args, metadata={}): self.total += args['obj'] def update2(self, args, metadata={}): self.total += args['loss'] def print(self, dataset_name, details=False): print('EVAL-OBJ\t{}-{}\tcurr-iter: {}\tobj: {}'.format(dataset_name, self.task, self.iter, self.total)) def log(self, tb_logger, dataset_name): tb_logger.log_value('{}/{}-obj'.format(dataset_name, self.task), self.total, self.iter)
class Metricobjective: def __init__(self, task): self.task = task self.clear() def clear(self): self.total = 0 self.iter = 0 def step(self): self.total = 0 self.iter += 1 def update(self, logits, targets, args, metadata={}): self.total += args['obj'] def update2(self, args, metadata={}): self.total += args['loss'] def print(self, dataset_name, details=False): print('EVAL-OBJ\t{}-{}\tcurr-iter: {}\tobj: {}'.format(dataset_name, self.task, self.iter, self.total)) def log(self, tb_logger, dataset_name): tb_logger.log_value('{}/{}-obj'.format(dataset_name, self.task), self.total, self.iter)
a = input("give numbers ")#1 while a.isdigit() != True: a = input("give numbers ")#1 b = input("give numbers ") while b == 0 or b.isdigit() != True: b = input("give numbers ") a = int(a) b = int(b) if str(a)[-1] in [0,2,4,6,8]: print("even") else: print("odd") print(int(a)/int(b))#2 x = 0#3 b = 0 while x <=(a**0.5): x += 1 while b <= x: if b *x == a: break else: b +=1 if b * x == a: print("not prime") break if x > a**0.5: print("prime") lst = [0,1] while lst[-1] < 100: lst.append(lst[-1]+lst[-2]) print(lst)
a = input('give numbers ') while a.isdigit() != True: a = input('give numbers ') b = input('give numbers ') while b == 0 or b.isdigit() != True: b = input('give numbers ') a = int(a) b = int(b) if str(a)[-1] in [0, 2, 4, 6, 8]: print('even') else: print('odd') print(int(a) / int(b)) x = 0 b = 0 while x <= a ** 0.5: x += 1 while b <= x: if b * x == a: break else: b += 1 if b * x == a: print('not prime') break if x > a ** 0.5: print('prime') lst = [0, 1] while lst[-1] < 100: lst.append(lst[-1] + lst[-2]) print(lst)
def setup(): size(500,500); background(0); smooth(); noLoop(); def draw(): strokeWeight(10); stroke(200); line(10, 10, 400, 400)
def setup(): size(500, 500) background(0) smooth() no_loop() def draw(): stroke_weight(10) stroke(200) line(10, 10, 400, 400)
def lower(o): t = type(o) if t == str: return o.lower() elif t in (list, tuple, set): return t(lower(i) for i in o) elif t == dict: return dict((lower(k), lower(v)) for k, v in o.items()) raise TypeError('Unable to lower %s (%s)' % (o, repr(o)))
def lower(o): t = type(o) if t == str: return o.lower() elif t in (list, tuple, set): return t((lower(i) for i in o)) elif t == dict: return dict(((lower(k), lower(v)) for (k, v) in o.items())) raise type_error('Unable to lower %s (%s)' % (o, repr(o)))
def extractAlbedo404BlogspotCom(item): ''' Parser for 'albedo404.blogspot.com' ''' vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or "preview" in item['title'].lower(): return None tagmap = [ ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel'), ] for tagname, name, tl_type in tagmap: if tagname in item['tags']: return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) if item['tags'] != []: return None if re.match("Ch \d+ Tondemo Skill de Isekai Hourou Meshi", item['title'], re.IGNORECASE): return buildReleaseMessageWithType(item, 'Tondemo Skill de Isekai Hourou Meshi', vol, chp, frag=frag, postfix=postfix, tl_type='translated') if re.match("Ch \d+ Sakyubasu ni Tensei Shita no de Miruku o Shiborimasu", item['title'], re.IGNORECASE): return buildReleaseMessageWithType(item, 'Sakyubasu ni Tensei Shita no de Miruku o Shiborimasu', vol, chp, frag=frag, postfix=postfix, tl_type='translated') return False
def extract_albedo404_blogspot_com(item): """ Parser for 'albedo404.blogspot.com' """ (vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')] for (tagname, name, tl_type) in tagmap: if tagname in item['tags']: return build_release_message_with_type(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type) if item['tags'] != []: return None if re.match('Ch \\d+ Tondemo Skill de Isekai Hourou Meshi', item['title'], re.IGNORECASE): return build_release_message_with_type(item, 'Tondemo Skill de Isekai Hourou Meshi', vol, chp, frag=frag, postfix=postfix, tl_type='translated') if re.match('Ch \\d+ Sakyubasu ni Tensei Shita no de Miruku o Shiborimasu', item['title'], re.IGNORECASE): return build_release_message_with_type(item, 'Sakyubasu ni Tensei Shita no de Miruku o Shiborimasu', vol, chp, frag=frag, postfix=postfix, tl_type='translated') return False
class FeatureDataResponseDto: def __init__(self, value = None, iterationCount = None, featureKey = None, sampleKey = None ): self.value = value self.iterationCount = iterationCount self.featureKey = featureKey self.sampleKey = sampleKey class FeatureDataRequestDto: def __init__(self, featureKey = None, sampleKey = None ): self.featureKey = featureKey self.sampleKey = sampleKey class BestFitDataRequestDto : def __init__(self, featureKey = None, featureValue = None, sampleKey = None, sampleValue = None ): self.featureKey = featureKey self.sampleKey = sampleKey self.featureValue = featureValue self.sampleValue = sampleValue
class Featuredataresponsedto: def __init__(self, value=None, iterationCount=None, featureKey=None, sampleKey=None): self.value = value self.iterationCount = iterationCount self.featureKey = featureKey self.sampleKey = sampleKey class Featuredatarequestdto: def __init__(self, featureKey=None, sampleKey=None): self.featureKey = featureKey self.sampleKey = sampleKey class Bestfitdatarequestdto: def __init__(self, featureKey=None, featureValue=None, sampleKey=None, sampleValue=None): self.featureKey = featureKey self.sampleKey = sampleKey self.featureValue = featureValue self.sampleValue = sampleValue
#zero if n == 0: yield [] return #modify for ig in partitions(n-1): yield [1] + ig if ig and (len(ig) < 2 or ig[1] > ig[0]): yield [ig[0] + 1] + ig[1:]
if n == 0: yield [] return for ig in partitions(n - 1): yield ([1] + ig) if ig and (len(ig) < 2 or ig[1] > ig[0]): yield ([ig[0] + 1] + ig[1:])
N = int(input()) for i in range(N): S = input().split() print(S) # ...... for string in S: if string.upper() == "THE": count += 1
n = int(input()) for i in range(N): s = input().split() print(S) for string in S: if string.upper() == 'THE': count += 1
print("BMI Calculator\n") weight = float(input("Input your weight (kg.) : ")) height = float(input("Input your height (cm.) : ")) / 100 bmi = weight / height ** 2 print("\nYour BMI = {:15,.2f}".format(bmi)) # print("\nYour BMI = {0:.2f}".format(float(input("Input your weight (kg.) : ")) / ((float(input("Input your height (cm.) : ")) / 100) ** 2)))
print('BMI Calculator\n') weight = float(input('Input your weight (kg.) : ')) height = float(input('Input your height (cm.) : ')) / 100 bmi = weight / height ** 2 print('\nYour BMI = {:15,.2f}'.format(bmi))
""" * User: lotus_zero * Date: 11/17/18 * Time: 16:25 PM * Brief: A program to calculate Multiple Circle Area with Check """ PI = 3.14159 def process (radius): return PI * radius * radius def main (): radius = 0.0 area = 0.0 n = int(input("# of Circles? \n")) for i in range (0,n): radius = float(input("Circle #{}".format(i)+" Radius = ? \n")) if radius < 0: return area else: area = process(radius) print("Area = {}".format(area)+"\n") return if __name__ == ("__main__"): main()
""" * User: lotus_zero * Date: 11/17/18 * Time: 16:25 PM * Brief: A program to calculate Multiple Circle Area with Check """ pi = 3.14159 def process(radius): return PI * radius * radius def main(): radius = 0.0 area = 0.0 n = int(input('# of Circles? \n')) for i in range(0, n): radius = float(input('Circle #{}'.format(i) + ' Radius = ? \n')) if radius < 0: return area else: area = process(radius) print('Area = {}'.format(area) + '\n') return if __name__ == '__main__': main()
# O(N) Solution: def leftIndex(n,arr,x): for i in range(n): if arr[i] == x: return i return -1 #______________________________________________________________________________________ # O(logN) Solution: Using Binary Search to find the first occurence of the element def leftIndex(N,A,x): lo=0 hi=N-1 mid=lo + ((hi-lo)//2) # binary search find the leftmost index of element while lo<=hi: mid=lo + ((hi-lo)//2) # if mid element is the required element, return if A[mid]==x and mid==0 or A[mid] == x and A[mid-1]<x: return mid # if mid is less than x, then go for right half if x > A[mid]: lo=mid+1 # else go for left half else: hi=mid-1 return -1
def left_index(n, arr, x): for i in range(n): if arr[i] == x: return i return -1 def left_index(N, A, x): lo = 0 hi = N - 1 mid = lo + (hi - lo) // 2 while lo <= hi: mid = lo + (hi - lo) // 2 if A[mid] == x and mid == 0 or (A[mid] == x and A[mid - 1] < x): return mid if x > A[mid]: lo = mid + 1 else: hi = mid - 1 return -1
''' Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of the array. Follow up: Could you solve it using only O(1) extra space? Example 1: Input: ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". Example 2: Input: ["a"] Output: Return 1, and the first 1 characters of the input array should be: ["a"] Explanation: Nothing is replaced. Example 3: Input: ["a","b","b","b","b","b","b","b","b","b","b","b","b"] Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. Explanation: Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12". Notice each digit has it's own entry in the array. Note: All characters have an ASCII value in [35, 126]. 1 <= len(chars) <= 1000. ''' def compress(chars): print(chars) # if length of an array is one return an array if len(chars) == 1: print(chars) return chars # if length is greater 2 and greater if len(chars) == 0: count = 0 else: count = 1 # go through the array # for i in range(1, len(chars)-1): i = 1 while i < len(chars): if chars[i] == chars[i-1]: count+=1 # i+=1 else: if count == 1: pass else: # pop count -1 times j = count-1 while j!= 0: # update j and i chars.pop(j) j-=1 i-=1 count = [x for x in str(count)] print("count is ", count, chars, i) l = len(count) z=0 while l>0: chars.insert(i, count[z]) z+=1 l-=1 i+=1 print("in loop after insert ", chars, i) # i-=len(count)-1 count = 1 # i+=0 print("after insert and if else ", chars, i) print(i, chars[i], count) i+=1 # chars.insert(i, count) # for the last count print(i, count) if count == 1: pass else: # pop count -1 times j = count-1 while j!= 0: # update j and i chars.pop(j) j-=1 i-=1 count = [x for x in str(count)] print("count is ", count) z=0 l = len(count) while l>0: chars.insert(i, count[z]) l-=1 i+=1 z+=1 print(chars) # compress(["a","a","b","b","c","c","c"]) print('*'*10) # compress(["a"]) print('*'*10) # compress(["a","b","b","b","b","b","b","b","b","b","b","b","b"]) print('*'*10) def compress2(chars): # chars.sort() dict_chars = {} for i in set(chars): dict_chars[i] = chars.count(i) print(dict_chars) print(sum([len(str(x)) for x in dict_chars.values()])) print(len(dict_chars)) for key, val in dict_chars.items(): if val != 1: ind = chars.index(str(key)) print(ind) i=ind+val-1 #remove dups while i > ind: chars.pop(i) i-=1 print(ind, i, chars) #insert count count = [x for x in str(val)] length = len(count) for i in range(length): chars.insert(ind+1+i, count[i]) print(chars) return len(chars) # compress2(["a","a","b","b","c","c","c"]) print('*'*10) # compress2(["a"]) print('*'*10) # compress2(["a","b","b","b","b","b","b","b","b","b","b","b","b"]) print('*'*10) # print(compress2(["w","w","w","w","w","b","b","g","g","g","g","a","a","a","i","i","i","i","y","y","p","v","v","v","u","u","u","y","y","y","y","y","y","y","y","y","s","q","q","q","q","q","q","q","q","q","q","n","n","n"])) print('*'*10) print(compress2(["a","b","c","d","e","f","g","g","g","g","g","g","g","g","g","g","g","g","a","b","c"]))
""" Given an array of characters, compress it in-place. The length after compression must always be smaller than or equal to the original array. Every element of the array should be a character (not int) of length 1. After you are done modifying the input array in-place, return the new length of the array. Follow up: Could you solve it using only O(1) extra space? Example 1: Input: ["a","a","b","b","c","c","c"] Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"] Explanation: "aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3". Example 2: Input: ["a"] Output: Return 1, and the first 1 characters of the input array should be: ["a"] Explanation: Nothing is replaced. Example 3: Input: ["a","b","b","b","b","b","b","b","b","b","b","b","b"] Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"]. Explanation: Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12". Notice each digit has it's own entry in the array. Note: All characters have an ASCII value in [35, 126]. 1 <= len(chars) <= 1000. """ def compress(chars): print(chars) if len(chars) == 1: print(chars) return chars if len(chars) == 0: count = 0 else: count = 1 i = 1 while i < len(chars): if chars[i] == chars[i - 1]: count += 1 else: if count == 1: pass else: j = count - 1 while j != 0: chars.pop(j) j -= 1 i -= 1 count = [x for x in str(count)] print('count is ', count, chars, i) l = len(count) z = 0 while l > 0: chars.insert(i, count[z]) z += 1 l -= 1 i += 1 print('in loop after insert ', chars, i) count = 1 print('after insert and if else ', chars, i) print(i, chars[i], count) i += 1 print(i, count) if count == 1: pass else: j = count - 1 while j != 0: chars.pop(j) j -= 1 i -= 1 count = [x for x in str(count)] print('count is ', count) z = 0 l = len(count) while l > 0: chars.insert(i, count[z]) l -= 1 i += 1 z += 1 print(chars) print('*' * 10) print('*' * 10) print('*' * 10) def compress2(chars): dict_chars = {} for i in set(chars): dict_chars[i] = chars.count(i) print(dict_chars) print(sum([len(str(x)) for x in dict_chars.values()])) print(len(dict_chars)) for (key, val) in dict_chars.items(): if val != 1: ind = chars.index(str(key)) print(ind) i = ind + val - 1 while i > ind: chars.pop(i) i -= 1 print(ind, i, chars) count = [x for x in str(val)] length = len(count) for i in range(length): chars.insert(ind + 1 + i, count[i]) print(chars) return len(chars) print('*' * 10) print('*' * 10) print('*' * 10) print('*' * 10) print(compress2(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'g', 'a', 'b', 'c']))
class Try(object): @staticmethod def print_hi(): print('hi')
class Try(object): @staticmethod def print_hi(): print('hi')
class Endpoint: def __init__(self, ID, data_center_latency): self.ID = ID self.data_center_latency = data_center_latency self.cache_server_connections = [] # def get_connection(self, cs): # if(cs in self.cache_server_connections_hash.keys()): # return self.cache_server_connections_hash[cs] # else: # return None
class Endpoint: def __init__(self, ID, data_center_latency): self.ID = ID self.data_center_latency = data_center_latency self.cache_server_connections = []
# 1038 code, quantity = input().split(" ") code = int(code) quantity = int(quantity) if code == 1: print("Total: R$ {0:.2f}".format(quantity * 4.00)) elif code == 2: print("Total: R$ {0:.2f}".format(quantity * 4.50)) elif code == 3: print("Total: R$ {0:.2f}".format(quantity * 5.00)) elif code == 4: print("Total: R$ {0:.2f}".format(quantity * 2.00)) elif code == 5: print("Total: R$ {0:.2f}".format(quantity * 1.50))
(code, quantity) = input().split(' ') code = int(code) quantity = int(quantity) if code == 1: print('Total: R$ {0:.2f}'.format(quantity * 4.0)) elif code == 2: print('Total: R$ {0:.2f}'.format(quantity * 4.5)) elif code == 3: print('Total: R$ {0:.2f}'.format(quantity * 5.0)) elif code == 4: print('Total: R$ {0:.2f}'.format(quantity * 2.0)) elif code == 5: print('Total: R$ {0:.2f}'.format(quantity * 1.5))
expected_output = { "route-information": { "route-table": { "active-route-count": "929", "destination-count": "929", "hidden-route-count": "0", "holddown-route-count": "0", "rt": [ { "rt-destination": "10.220.0.0/16", "rt-entry": { "active-tag": "*", "as-path": "(65151 65000) I", "bgp-metric-flags": "Nexthop Change", "local-preference": "120", "med": "12003", "nh": {"to": "Self"}, "protocol-name": "BGP", }, }, { "rt-destination": "10.229.0.0/16", "rt-entry": { "active-tag": "*", "as-path": "(65151 65000) I", "bgp-metric-flags": "Nexthop Change", "local-preference": "120", "med": "12003", "nh": {"to": "Self"}, "protocol-name": "BGP", }, }, { "rt-destination": "10.189.0.0/16", "rt-entry": { "active-tag": "*", "as-path": "(65151 65000) I", "bgp-metric-flags": "Nexthop Change", "local-preference": "120", "med": "12003", "nh": {"to": "Self"}, "protocol-name": "BGP", }, }, { "rt-destination": "10.151.0.0/16", "rt-entry": { "active-tag": "*", "as-path": "(65151 65000) I", "bgp-metric-flags": "Nexthop Change", "local-preference": "120", "med": "12003", "nh": {"to": "Self"}, "protocol-name": "BGP", }, }, { "rt-destination": "10.115.0.0/16", "rt-entry": { "active-tag": "*", "as-path": "(65151 65000) I", "bgp-metric-flags": "Nexthop Change", "local-preference": "120", "med": "12003", "nh": {"to": "Self"}, "protocol-name": "BGP", }, }, ], "table-name": "inet.0", "total-route-count": "1615", } } }
expected_output = {'route-information': {'route-table': {'active-route-count': '929', 'destination-count': '929', 'hidden-route-count': '0', 'holddown-route-count': '0', 'rt': [{'rt-destination': '10.220.0.0/16', 'rt-entry': {'active-tag': '*', 'as-path': '(65151 65000) I', 'bgp-metric-flags': 'Nexthop Change', 'local-preference': '120', 'med': '12003', 'nh': {'to': 'Self'}, 'protocol-name': 'BGP'}}, {'rt-destination': '10.229.0.0/16', 'rt-entry': {'active-tag': '*', 'as-path': '(65151 65000) I', 'bgp-metric-flags': 'Nexthop Change', 'local-preference': '120', 'med': '12003', 'nh': {'to': 'Self'}, 'protocol-name': 'BGP'}}, {'rt-destination': '10.189.0.0/16', 'rt-entry': {'active-tag': '*', 'as-path': '(65151 65000) I', 'bgp-metric-flags': 'Nexthop Change', 'local-preference': '120', 'med': '12003', 'nh': {'to': 'Self'}, 'protocol-name': 'BGP'}}, {'rt-destination': '10.151.0.0/16', 'rt-entry': {'active-tag': '*', 'as-path': '(65151 65000) I', 'bgp-metric-flags': 'Nexthop Change', 'local-preference': '120', 'med': '12003', 'nh': {'to': 'Self'}, 'protocol-name': 'BGP'}}, {'rt-destination': '10.115.0.0/16', 'rt-entry': {'active-tag': '*', 'as-path': '(65151 65000) I', 'bgp-metric-flags': 'Nexthop Change', 'local-preference': '120', 'med': '12003', 'nh': {'to': 'Self'}, 'protocol-name': 'BGP'}}], 'table-name': 'inet.0', 'total-route-count': '1615'}}}
# -*- coding: utf-8 -*- class Incrementor: def __init__(self, inf_bound, increment, sup_bound, step_duration): """Build a new Incrementor. Args: inf_bound (int or float): The inf bound (included). increment (int or float): The step increment. sup_bound (int or float): The sup bound (excluded). step_duration (int): The number of call to next() to change the value. """ self.inf_bound = inf_bound self.increment = increment self.sup_bound = sup_bound self.step_duration = step_duration self.count = 0 self.stepper = inf_bound @property def is_rising(self): """Whether the value will rise or not at the next change. Returns: bool: Whether the value will rise or not at the next change. """ return self.increment > 0 @property def will_change(self): """Whether the value will change or not at the next call to next(). Returns: bool: Whether the value will change or not at the next call to next(). """ return self.count + 1 == self.step_duration def next(self): """Prepare the next step of the simulation. Returns: The current value. """ value = self.stepper self.count += 1 if self.count == self.step_duration: self.count = 0 self.stepper += self.increment # Reverse the increment direction when the sup bound is reached if self.stepper >= self.sup_bound - self.increment: self.increment = -self.increment # Ensure the value is greater than the inf bound if self.stepper < self.inf_bound: value = self.inf_bound return value
class Incrementor: def __init__(self, inf_bound, increment, sup_bound, step_duration): """Build a new Incrementor. Args: inf_bound (int or float): The inf bound (included). increment (int or float): The step increment. sup_bound (int or float): The sup bound (excluded). step_duration (int): The number of call to next() to change the value. """ self.inf_bound = inf_bound self.increment = increment self.sup_bound = sup_bound self.step_duration = step_duration self.count = 0 self.stepper = inf_bound @property def is_rising(self): """Whether the value will rise or not at the next change. Returns: bool: Whether the value will rise or not at the next change. """ return self.increment > 0 @property def will_change(self): """Whether the value will change or not at the next call to next(). Returns: bool: Whether the value will change or not at the next call to next(). """ return self.count + 1 == self.step_duration def next(self): """Prepare the next step of the simulation. Returns: The current value. """ value = self.stepper self.count += 1 if self.count == self.step_duration: self.count = 0 self.stepper += self.increment if self.stepper >= self.sup_bound - self.increment: self.increment = -self.increment if self.stepper < self.inf_bound: value = self.inf_bound return value
# Modulo for i in range(0, 101): if i % 2 == 0: print (str(i) + " is even") else: print (str(i) + " is odd") print ("----------------------") # Without modulo for i in range (0,101): num = int(i/2) if (num * 2 == i): print (str(i) + " is even") else: print (str(i) + " is odd")
for i in range(0, 101): if i % 2 == 0: print(str(i) + ' is even') else: print(str(i) + ' is odd') print('----------------------') for i in range(0, 101): num = int(i / 2) if num * 2 == i: print(str(i) + ' is even') else: print(str(i) + ' is odd')
# csamiselo@github.com 15.10.2019 print("This is how i count my livestock") print("Goats",12 + 30 + 60) print("Cows", 13 + 15 + 10) print ("Layers" ,1000 + 250 + 503 ) print ("Are the layers more than the goats") print (12 + 30 + 60 < 1000 + 250 +503 )
print('This is how i count my livestock') print('Goats', 12 + 30 + 60) print('Cows', 13 + 15 + 10) print('Layers', 1000 + 250 + 503) print('Are the layers more than the goats') print(12 + 30 + 60 < 1000 + 250 + 503)
class CeleryConfig: # List of modules to import when the Celery worker starts. imports = ('apps.tasks',) ## Broker settings. broker_url = 'amqp://' ## Disable result backent and also ignore results. task_ignore_result = True
class Celeryconfig: imports = ('apps.tasks',) broker_url = 'amqp://' task_ignore_result = True
def if_pycaffe(if_true, if_false = []): return select({ "@caffe_tools//:caffe_python_layer": if_true, "//conditions:default": if_false }) def caffe_pkg(label): return select({ "//conditions:default": ["@caffe//" + label], "@caffe_tools//:use_caffe_rcnn": ["@caffe_rcnn//" + label], "@caffe_tools//:use_caffe_ssd": ["@caffe_ssd//" + label], })
def if_pycaffe(if_true, if_false=[]): return select({'@caffe_tools//:caffe_python_layer': if_true, '//conditions:default': if_false}) def caffe_pkg(label): return select({'//conditions:default': ['@caffe//' + label], '@caffe_tools//:use_caffe_rcnn': ['@caffe_rcnn//' + label], '@caffe_tools//:use_caffe_ssd': ['@caffe_ssd//' + label]})
frase = "Nos estamos procurando o rubi na floresta" rubi = frase[24:29] print (rubi)
frase = 'Nos estamos procurando o rubi na floresta' rubi = frase[24:29] print(rubi)
def spiralTraverse(array): num_elements = len(array) * len(array[0]) n = len(array) m = len(array[0]) it = 0 result = [] while num_elements > 0: # Up side for j in range(it, m - it): result.append(array[it][j]) num_elements -= 1 if num_elements == 0: break if num_elements == 0: continue # Right side for i in range(it + 1, n - it): result.append(array[i][m - 1 - it]) num_elements -= 1 if num_elements == 0: break if num_elements == 0: continue # Bottom side for j in reversed(range(it, m - 1 - it)): result.append(array[n - it - 1][j]) num_elements -= 1 if num_elements == 0: break if num_elements == 0: continue # Left side for i in reversed(range(it + 1, n - it - 1)): result.append(array[i][it]) num_elements -= 1 if num_elements == 0: break it += 1 return result
def spiral_traverse(array): num_elements = len(array) * len(array[0]) n = len(array) m = len(array[0]) it = 0 result = [] while num_elements > 0: for j in range(it, m - it): result.append(array[it][j]) num_elements -= 1 if num_elements == 0: break if num_elements == 0: continue for i in range(it + 1, n - it): result.append(array[i][m - 1 - it]) num_elements -= 1 if num_elements == 0: break if num_elements == 0: continue for j in reversed(range(it, m - 1 - it)): result.append(array[n - it - 1][j]) num_elements -= 1 if num_elements == 0: break if num_elements == 0: continue for i in reversed(range(it + 1, n - it - 1)): result.append(array[i][it]) num_elements -= 1 if num_elements == 0: break it += 1 return result
""" This is the base class for any AI component. All AIs inherit from this module, and implement the getMove() function, which takes a Grid object as a parameter and returns a move. """ class BaseAI: def getMove(self,grid): pass
""" This is the base class for any AI component. All AIs inherit from this module, and implement the getMove() function, which takes a Grid object as a parameter and returns a move. """ class Baseai: def get_move(self, grid): pass
""" The Ceasar cipher is one of the simplest and one of the earliest known ciphers. It is a type of substitution cipher that 'shifts' a letter by a fixed amount in the alphabet. For example with a shift = 3: a -> d b -> e . . . z -> c Programmed by Aladdin Persson <aladdin.persson at hotmail dot com> * 2019-11-07 Initial programming """ # This alphabet is of 27 letters since I included a space, but normally it is of 26 letters. # If you wish to include more letters you need to expand the alphabet used. For example you cannot use '!', '@' now. alphabet = "abcdefghijklmnopqrstuvwxyz " letter_to_index = dict(zip(alphabet, range(len(alphabet)))) index_to_letter = dict(zip(range(len(alphabet)), alphabet)) def encrypt(message, shift=3): cipher = "" for letter in message: number = (letter_to_index[letter] + shift) % len(letter_to_index) letter = index_to_letter[number] cipher += letter return cipher def decrypt(cipher, shift=3): decrypted = "" for letter in cipher: number = (letter_to_index[letter] - shift) % len(letter_to_index) letter = index_to_letter[number] decrypted += letter return decrypted # def main(): # message = 'attackatnoon' # cipher = encrypt(message, shift=3) # decrypted = decrypt(cipher, shift=3) # # print('Original message: ' + message) # print('Encrypted message: ' + cipher) # print('Decrypted message: ' + decrypted) # # main()
""" The Ceasar cipher is one of the simplest and one of the earliest known ciphers. It is a type of substitution cipher that 'shifts' a letter by a fixed amount in the alphabet. For example with a shift = 3: a -> d b -> e . . . z -> c Programmed by Aladdin Persson <aladdin.persson at hotmail dot com> * 2019-11-07 Initial programming """ alphabet = 'abcdefghijklmnopqrstuvwxyz ' letter_to_index = dict(zip(alphabet, range(len(alphabet)))) index_to_letter = dict(zip(range(len(alphabet)), alphabet)) def encrypt(message, shift=3): cipher = '' for letter in message: number = (letter_to_index[letter] + shift) % len(letter_to_index) letter = index_to_letter[number] cipher += letter return cipher def decrypt(cipher, shift=3): decrypted = '' for letter in cipher: number = (letter_to_index[letter] - shift) % len(letter_to_index) letter = index_to_letter[number] decrypted += letter return decrypted
class PantryModel: def get_ingredients(self, user_id): """Get all ingredients from in pantry and return a list of instances of the ingredient class. """ pass
class Pantrymodel: def get_ingredients(self, user_id): """Get all ingredients from in pantry and return a list of instances of the ingredient class. """ pass
# # @lc app=leetcode id=2 lang=python3 # # [2] Add Two Numbers # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: """ time: O(len(n)) n : max(len(l1), len(l2)) space: O(len(n)) """ total = cur = ListNode(0) carry = 0 while l1 or l2 or carry: sum_digit = carry if l1: sum_digit += l1.val l1 = l1.next if l2: sum_digit += l2.val l2 = l2.next cur.next = ListNode(sum_digit % 10) carry = sum_digit // 10 cur = cur.next return total.next # @lc code=end
class Solution: def add_two_numbers(self, l1: ListNode, l2: ListNode) -> ListNode: """ time: O(len(n)) n : max(len(l1), len(l2)) space: O(len(n)) """ total = cur = list_node(0) carry = 0 while l1 or l2 or carry: sum_digit = carry if l1: sum_digit += l1.val l1 = l1.next if l2: sum_digit += l2.val l2 = l2.next cur.next = list_node(sum_digit % 10) carry = sum_digit // 10 cur = cur.next return total.next
{ PDBConst.Name: "paymentmode", PDBConst.Columns: [ { PDBConst.Name: "ID", PDBConst.Attributes: ["tinyint", "not null", "primary key"] }, { PDBConst.Name: "Name", PDBConst.Attributes: ["varchar(128)", "not null"] }, { PDBConst.Name: "SID", PDBConst.Attributes: ["varchar(128)", "not null"] }], PDBConst.Initials: [ {"Name": "'Credit Card'", "ID": "1", "SID": "'sidTablePaymentMode1'"}, {"Name": "'Cash'", "ID": "2", "SID": "'sidTablePaymentMode2'"}, {"Name": "'Alipay'", "ID": "3", "SID": "'sidTablePaymentMode3'"}, {"Name": "'WeChat Wallet'", "ID": "4", "SID": "'sidTablePaymentMode4'"}, {"Name": "'Other'", "ID": "100", "SID": "'sidOther'"} ] }
{PDBConst.Name: 'paymentmode', PDBConst.Columns: [{PDBConst.Name: 'ID', PDBConst.Attributes: ['tinyint', 'not null', 'primary key']}, {PDBConst.Name: 'Name', PDBConst.Attributes: ['varchar(128)', 'not null']}, {PDBConst.Name: 'SID', PDBConst.Attributes: ['varchar(128)', 'not null']}], PDBConst.Initials: [{'Name': "'Credit Card'", 'ID': '1', 'SID': "'sidTablePaymentMode1'"}, {'Name': "'Cash'", 'ID': '2', 'SID': "'sidTablePaymentMode2'"}, {'Name': "'Alipay'", 'ID': '3', 'SID': "'sidTablePaymentMode3'"}, {'Name': "'WeChat Wallet'", 'ID': '4', 'SID': "'sidTablePaymentMode4'"}, {'Name': "'Other'", 'ID': '100', 'SID': "'sidOther'"}]}
class Graph(object): def __init__(self, graph_dict=None): if graph_dict == None: graph_dict = {} self.__graph_dict = graph_dict
class Graph(object): def __init__(self, graph_dict=None): if graph_dict == None: graph_dict = {} self.__graph_dict = graph_dict
def add_reporter_email_recipients(client=None, project_key=None, scenario_id=None, recipients=[]): """Append additional recipients to a scenario email reporter. """ prj = client.get_project(project_key) scn_settings = prj.get_scenario(scenario_id).get_settings() reporters = scn_settings.raw_reporters if not reporters: print("No reporter found, will do nohting.") else: for rep in reporters: messaging = rep["messaging"] if messaging["type"] == "mail-scenario": if messaging["configuration"]["recipient"]: sep = ', ' else: sep = '' messaging["configuration"]["recipient"] += (sep + ', '.join(recipients)) scn_settings.save()
def add_reporter_email_recipients(client=None, project_key=None, scenario_id=None, recipients=[]): """Append additional recipients to a scenario email reporter. """ prj = client.get_project(project_key) scn_settings = prj.get_scenario(scenario_id).get_settings() reporters = scn_settings.raw_reporters if not reporters: print('No reporter found, will do nohting.') else: for rep in reporters: messaging = rep['messaging'] if messaging['type'] == 'mail-scenario': if messaging['configuration']['recipient']: sep = ', ' else: sep = '' messaging['configuration']['recipient'] += sep + ', '.join(recipients) scn_settings.save()
main = { 'General': { 'Prop': { 'Labels': 'rw', 'AlarmStatus': 'r-' } } } cfgm = { 'General': { 'Prop': { 'Blacklist': 'rw' } } } fm = { 'Status': { 'Prop': { 'AlarmStatus': 'r-' }, 'Cmd': ( 'Acknowledge', ) }, 'Configuration': { 'Prop': { 'AlarmConfiguration': 'rw' } }, 'DuplicatedMac': { 'Prop': { 'DuplicatedMacAccessList': 'r-' }, 'Cmd': ( 'FlushMacAccessDuplicatedList', ) } } status = { 'DynamicList': { 'Prop': { 'DynamicList': 'r-' }, 'Cmd': ( 'FlushMacAccessDynamicList', 'DeleteMacAccessDynamicListEntry' ) }, 'UNIBlacklist': { 'Prop': { 'Blacklist': 'r-', 'BNGlist': 'r-' }, 'Cmd': ( 'DeleteMacAccessBNGlistEntry', ) } }
main = {'General': {'Prop': {'Labels': 'rw', 'AlarmStatus': 'r-'}}} cfgm = {'General': {'Prop': {'Blacklist': 'rw'}}} fm = {'Status': {'Prop': {'AlarmStatus': 'r-'}, 'Cmd': ('Acknowledge',)}, 'Configuration': {'Prop': {'AlarmConfiguration': 'rw'}}, 'DuplicatedMac': {'Prop': {'DuplicatedMacAccessList': 'r-'}, 'Cmd': ('FlushMacAccessDuplicatedList',)}} status = {'DynamicList': {'Prop': {'DynamicList': 'r-'}, 'Cmd': ('FlushMacAccessDynamicList', 'DeleteMacAccessDynamicListEntry')}, 'UNIBlacklist': {'Prop': {'Blacklist': 'r-', 'BNGlist': 'r-'}, 'Cmd': ('DeleteMacAccessBNGlistEntry',)}}
tiles = [ # Riker's Island - https://www.openstreetmap.org/relation/3955540 (10, 301, 384, 'Rikers Island'), # SF County Jail - https://www.openstreetmap.org/way/103383866 (14, 2621, 6332, 'SF County Jail') ] for z, x, y, name in tiles: assert_has_feature( z, x, y, 'pois', { 'kind': 'prison', 'name': name }) # Rikers Island also should have a landuse polygon assert_has_feature( 10, 301, 384, 'landuse', { 'kind': 'prison' })
tiles = [(10, 301, 384, 'Rikers Island'), (14, 2621, 6332, 'SF County Jail')] for (z, x, y, name) in tiles: assert_has_feature(z, x, y, 'pois', {'kind': 'prison', 'name': name}) assert_has_feature(10, 301, 384, 'landuse', {'kind': 'prison'})
def median(x): sorted_x = sorted(x) midpoint = len(x) // 2 if len(x) % 2: return sorted_x[midpoint] else: return (sorted_x[midpoint]+sorted_x[midpoint-1])/2 assert median([1]) == 1 assert median([1, 2]) == 1.5 assert median([1, 2, 3]) == 2 assert median([3,1,2]) == 2 assert median([3,1,4,2]) == 2.5 n = 9 #int(input()) arr = [3,7,8,5,12,14,21,13,18] #[int(v) for v in input().split()] q2 = median(arr) q1 = median([xi for xi in arr if xi < q2]) q3 = median([xi for xi in arr if xi > q2]) print(int(q1)) print(int(q2)) print(int(q3))
def median(x): sorted_x = sorted(x) midpoint = len(x) // 2 if len(x) % 2: return sorted_x[midpoint] else: return (sorted_x[midpoint] + sorted_x[midpoint - 1]) / 2 assert median([1]) == 1 assert median([1, 2]) == 1.5 assert median([1, 2, 3]) == 2 assert median([3, 1, 2]) == 2 assert median([3, 1, 4, 2]) == 2.5 n = 9 arr = [3, 7, 8, 5, 12, 14, 21, 13, 18] q2 = median(arr) q1 = median([xi for xi in arr if xi < q2]) q3 = median([xi for xi in arr if xi > q2]) print(int(q1)) print(int(q2)) print(int(q3))
#!/usr/bin/python3 #https://codeforces.com/contest/1426/problem/F def f(s): _,a,ab,abc = 1,0,0,0 for c in s: if c=='a': a += _ elif c=='b': ab += a elif c=='c': abc += ab else: abc *= 3 abc += ab ab *= 3 ab += a a *= 3 a += _ _ *= 3 return abc%1000000007 _ = input() s = input() print(f(s))
def f(s): (_, a, ab, abc) = (1, 0, 0, 0) for c in s: if c == 'a': a += _ elif c == 'b': ab += a elif c == 'c': abc += ab else: abc *= 3 abc += ab ab *= 3 ab += a a *= 3 a += _ _ *= 3 return abc % 1000000007 _ = input() s = input() print(f(s))
DEBUG = True INSTAGRAM_CLIENT_ID = '' INSTAGRAM_CLIENT_SECRET = '' INSTAGRAM_CALLBACK = 'http://cameo.gala-isen.fr/api/instagram/hub' MONGODB_NAME = 'cameo' MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 REDIS_HOST = 'localhost' REDIS_PORT = 6379
debug = True instagram_client_id = '' instagram_client_secret = '' instagram_callback = 'http://cameo.gala-isen.fr/api/instagram/hub' mongodb_name = 'cameo' mongodb_host = 'localhost' mongodb_port = 27017 redis_host = 'localhost' redis_port = 6379