content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
num1=int(input('Enter the first number:')) num2=int(input('Enter the second number:')) sum=lambda num1,num2:num1+num2 diff=lambda num1,num2:num1-num2 mul=lambda num1,num2:num1*num2 div=lambda num1,num2:num1//num2 print("Sum is:",sum(num1,num2)) print("Difference is:",diff(num1,num2)) print("Multiply is",mul(num1,num2)) print("Division is:",div(num1,num2))
num1 = int(input('Enter the first number:')) num2 = int(input('Enter the second number:')) sum = lambda num1, num2: num1 + num2 diff = lambda num1, num2: num1 - num2 mul = lambda num1, num2: num1 * num2 div = lambda num1, num2: num1 // num2 print('Sum is:', sum(num1, num2)) print('Difference is:', diff(num1, num2)) print('Multiply is', mul(num1, num2)) print('Division is:', div(num1, num2))
SECRET_KEY='development-key' MYSQL_DATABASE_USER='root' MYSQL_DATABASE_PASSWORD='classroom' MYSQL_DATABASE_DB='Ascott_InvMgmt' MYSQL_DATABASE_HOST='dogfood.coxb3venarbl.ap-southeast-1.rds.amazonaws.com' UPLOADS_DEFAULT_DEST = 'static/img/items/' UPLOADS_DEFAULT_URL = 'http://localhost:5000/static/img/items/' UPLOADED_IMAGES_DEST = 'static/img/items/' UPLOADED_IMAGES_URL = 'http://localhost:5000/static/img/items/' BABEL_LOCALES = ('en', 'zh', 'ms', 'ta') BABEL_DEFAULT_LOCALE = "en" # Property-specific info # Timezone string follows TZ format (see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) TIMEZONE = "Asia/Singapore" PROP_NAME = "Capstone Room"
secret_key = 'development-key' mysql_database_user = 'root' mysql_database_password = 'classroom' mysql_database_db = 'Ascott_InvMgmt' mysql_database_host = 'dogfood.coxb3venarbl.ap-southeast-1.rds.amazonaws.com' uploads_default_dest = 'static/img/items/' uploads_default_url = 'http://localhost:5000/static/img/items/' uploaded_images_dest = 'static/img/items/' uploaded_images_url = 'http://localhost:5000/static/img/items/' babel_locales = ('en', 'zh', 'ms', 'ta') babel_default_locale = 'en' timezone = 'Asia/Singapore' prop_name = 'Capstone Room'
class ThreadModule(object): '''docstring for ThreadModule''' def __init__(self, ): super().__init__()
class Threadmodule(object): """docstring for ThreadModule""" def __init__(self): super().__init__()
# Copyright (c) 2014, MapR Technologies # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. OOZIE = 'Oozie' HIVE = 'Hive' HIVE_METASTORE = 'HiveMetastore' HIVE_SERVER2 = 'HiveServer2' CLDB = 'CLDB' FILE_SERVER = 'FileServer' ZOOKEEPER = 'ZooKeeper' RESOURCE_MANAGER = 'ResourceManager' HISTORY_SERVER = 'HistoryServer' IS_M7_ENABLED = 'Enable MapR-DB' GENERAL = 'general' JOBTRACKER = 'JobTracker' NODE_MANAGER = 'NodeManager' DATANODE = 'Datanode' TASK_TRACKER = 'TaskTracker' SECONDARY_NAMENODE = 'SecondaryNamenode' NFS = 'NFS' WEB_SERVER = 'Webserver' WAIT_OOZIE_INTERVAL = 300 WAIT_NODE_ALARM_NO_HEARTBEAT = 360 ecosystem_components = ['Oozie', 'Hive-Metastore', 'HiveServer2', 'HBase-Master', 'HBase-RegionServer', 'HBase-Client', 'Pig']
oozie = 'Oozie' hive = 'Hive' hive_metastore = 'HiveMetastore' hive_server2 = 'HiveServer2' cldb = 'CLDB' file_server = 'FileServer' zookeeper = 'ZooKeeper' resource_manager = 'ResourceManager' history_server = 'HistoryServer' is_m7_enabled = 'Enable MapR-DB' general = 'general' jobtracker = 'JobTracker' node_manager = 'NodeManager' datanode = 'Datanode' task_tracker = 'TaskTracker' secondary_namenode = 'SecondaryNamenode' nfs = 'NFS' web_server = 'Webserver' wait_oozie_interval = 300 wait_node_alarm_no_heartbeat = 360 ecosystem_components = ['Oozie', 'Hive-Metastore', 'HiveServer2', 'HBase-Master', 'HBase-RegionServer', 'HBase-Client', 'Pig']
def Analysis(cipherText): alphabet = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ', [0] * 27)) for letter in cipherText: if letter.isalpha(): alphabet[letter] += 1 for key, value in alphabet.items(): alphabet[key] = value * (value - 1) IC = sum(alphabet.values()) / (len(cipherText) * len(cipherText) - 1) key_len = abs(((0.027 * len(cipherText)) / (len(cipherText) - 1) * IC - 0.038 * len(cipherText) + 0.065)) IC = "%.6f" % IC key_len = "%.2f" % key_len return float(IC), key_len
def analysis(cipherText): alphabet = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ', [0] * 27)) for letter in cipherText: if letter.isalpha(): alphabet[letter] += 1 for (key, value) in alphabet.items(): alphabet[key] = value * (value - 1) ic = sum(alphabet.values()) / (len(cipherText) * len(cipherText) - 1) key_len = abs(0.027 * len(cipherText) / (len(cipherText) - 1) * IC - 0.038 * len(cipherText) + 0.065) ic = '%.6f' % IC key_len = '%.2f' % key_len return (float(IC), key_len)
# find nth fibonacci number using recursion. # sample output: # 21 def findnthfibnumber(n, map={1: 0, 2: 1}): if n in map: return map[n] else: map[n] = findnthfibnumber(n-1, map) + findnthfibnumber(n-2, map) return map[n] print (findnthfibnumber(9))
def findnthfibnumber(n, map={1: 0, 2: 1}): if n in map: return map[n] else: map[n] = findnthfibnumber(n - 1, map) + findnthfibnumber(n - 2, map) return map[n] print(findnthfibnumber(9))
class Solution: def countElements(self, arr: List[int]) -> int: d = {} count = 0 for i in arr: d[i] = 1 for x in arr: if x+1 in d.keys(): count += 1 return count
class Solution: def count_elements(self, arr: List[int]) -> int: d = {} count = 0 for i in arr: d[i] = 1 for x in arr: if x + 1 in d.keys(): count += 1 return count
def part_1() -> None: h_pos: int = 0 v_pos: int = 0 with open("../data/day2.txt", "r") as dFile: for row in dFile.readlines(): value: int = int(row.split(" ")[1]) match row.split(" ")[0]: case "forward": h_pos += value case "down": v_pos += value case "up": v_pos -= value case _: raise ValueError(f"Unsupported command {row.split(' ')[0]}") print("Day: 2 | Part: 1 | Result:", h_pos * v_pos) def part_2() -> None: h_pos: int = 0 v_pos: int = 0 aim : int = 0 with open("../data/day2.txt", "r") as dFile: for row in dFile.readlines(): value: int = int(row.split(" ")[1]) match row.split(" ")[0]: case "forward": h_pos += value v_pos += value * aim case "down": aim += value case "up": aim -= value case _: raise ValueError(f"Unsupported command {row.split(' ')[0]}") print("Day: 2 | Part: 2 | Result:", h_pos * v_pos) if __name__ == "__main__": part_1() part_2()
def part_1() -> None: h_pos: int = 0 v_pos: int = 0 with open('../data/day2.txt', 'r') as d_file: for row in dFile.readlines(): value: int = int(row.split(' ')[1]) match row.split(' ')[0]: case 'forward': h_pos += value case 'down': v_pos += value case 'up': v_pos -= value case _: raise value_error(f"Unsupported command {row.split(' ')[0]}") print('Day: 2 | Part: 1 | Result:', h_pos * v_pos) def part_2() -> None: h_pos: int = 0 v_pos: int = 0 aim: int = 0 with open('../data/day2.txt', 'r') as d_file: for row in dFile.readlines(): value: int = int(row.split(' ')[1]) match row.split(' ')[0]: case 'forward': h_pos += value v_pos += value * aim case 'down': aim += value case 'up': aim -= value case _: raise value_error(f"Unsupported command {row.split(' ')[0]}") print('Day: 2 | Part: 2 | Result:', h_pos * v_pos) if __name__ == '__main__': part_1() part_2()
pkgname = "libffi8" pkgver = "3.4.2" pkgrel = 0 build_style = "gnu_configure" configure_args = [ "--includedir=/usr/include", "--disable-multi-os-directory", "--with-pic" ] hostmakedepends = ["pkgconf"] # actually only on x86 and arm (tramp.c code) but it does not hurt makedepends = ["linux-headers"] checkdepends = ["dejagnu"] pkgdesc = "Library supporting Foreign Function Interfaces" maintainer = "q66 <q66@chimera-linux.org>" license = "MIT" url = "http://sourceware.org/libffi" source = f"https://github.com/libffi/libffi/releases/download/v{pkgver}/libffi-{pkgver}.tar.gz" sha256 = "540fb721619a6aba3bdeef7d940d8e9e0e6d2c193595bc243241b77ff9e93620" # missing checkdepends for now options = ["!check"] def post_install(self): self.install_license("LICENSE") @subpackage("libffi-devel") def _devel(self): return self.default_devel(man = True, extra = ["usr/share/info"])
pkgname = 'libffi8' pkgver = '3.4.2' pkgrel = 0 build_style = 'gnu_configure' configure_args = ['--includedir=/usr/include', '--disable-multi-os-directory', '--with-pic'] hostmakedepends = ['pkgconf'] makedepends = ['linux-headers'] checkdepends = ['dejagnu'] pkgdesc = 'Library supporting Foreign Function Interfaces' maintainer = 'q66 <q66@chimera-linux.org>' license = 'MIT' url = 'http://sourceware.org/libffi' source = f'https://github.com/libffi/libffi/releases/download/v{pkgver}/libffi-{pkgver}.tar.gz' sha256 = '540fb721619a6aba3bdeef7d940d8e9e0e6d2c193595bc243241b77ff9e93620' options = ['!check'] def post_install(self): self.install_license('LICENSE') @subpackage('libffi-devel') def _devel(self): return self.default_devel(man=True, extra=['usr/share/info'])
# # PySNMP MIB module HPN-ICF-L2VPN-PWE3-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-L2VPN-PWE3-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:27:17 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection") hpnicfCommon, = mibBuilder.importSymbols("HPN-ICF-OID-MIB", "hpnicfCommon") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Gauge32, Bits, MibIdentifier, Counter64, ModuleIdentity, Counter32, Unsigned32, ObjectIdentity, IpAddress, NotificationType, iso, TimeTicks, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Bits", "MibIdentifier", "Counter64", "ModuleIdentity", "Counter32", "Unsigned32", "ObjectIdentity", "IpAddress", "NotificationType", "iso", "TimeTicks", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") DisplayString, RowStatus, TextualConvention, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TextualConvention", "TruthValue") hpnicfL2VpnPwe3 = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78)) if mibBuilder.loadTexts: hpnicfL2VpnPwe3.setLastUpdated('200703310000Z') if mibBuilder.loadTexts: hpnicfL2VpnPwe3.setOrganization('') class HpnicfL2VpnVcEncapsType(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 255)) namedValues = NamedValues(("frameRelayDlciMartini", 1), ("atmAal5SduVccTransport", 2), ("atmTransparentCellTransport", 3), ("ethernetTagged", 4), ("ethernet", 5), ("hdlc", 6), ("ppp", 7), ("cem", 8), ("atmN2OneVccCellTransport", 9), ("atmN2OneVpcCellTransport", 10), ("ipLayer2Transport", 11), ("atmOne2OneVccCellMode", 12), ("atmOne2OneVpcCellMode", 13), ("atmAal5PduVccTransport", 14), ("frameRelayPortMode", 15), ("cep", 16), ("saE1oP", 17), ("saT1oP", 18), ("saE3oP", 19), ("saT3oP", 20), ("cESoPsnBasicMode", 21), ("tDMoIPbasicMode", 22), ("l2VpnCESoPSNTDMwithCAS", 23), ("l2VpnTDMoIPTDMwithCAS", 24), ("frameRelayDlci", 25), ("ipInterworking", 64), ("unknown", 255)) hpnicfL2VpnPwe3ScalarGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 1)) hpnicfPwVcTrapOpen = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hpnicfPwVcTrapOpen.setStatus('current') hpnicfL2VpnPwe3Table = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2)) hpnicfPwVcTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1), ) if mibBuilder.loadTexts: hpnicfPwVcTable.setStatus('current') hpnicfPwVcEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1), ).setIndexNames((0, "HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcIndex")) if mibBuilder.loadTexts: hpnicfPwVcEntry.setStatus('current') hpnicfPwVcIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 1), Integer32()) if mibBuilder.loadTexts: hpnicfPwVcIndex.setStatus('current') hpnicfPwVcID = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 2), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcID.setStatus('current') hpnicfPwVcType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 3), HpnicfL2VpnVcEncapsType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcType.setStatus('current') hpnicfPwVcPeerAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 4), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcPeerAddr.setStatus('current') hpnicfPwVcMtu = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 5), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcMtu.setStatus('current') hpnicfPwVcCfgType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("primary", 1), ("backup", 2), ("multiPort", 3)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcCfgType.setStatus('current') hpnicfPwVcInboundLabel = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 7), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfPwVcInboundLabel.setStatus('current') hpnicfPwVcOutboundLabel = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 8), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfPwVcOutboundLabel.setStatus('current') hpnicfPwVcIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 9), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcIfIndex.setStatus('current') hpnicfPwVcAcStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("down", 1), ("up", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfPwVcAcStatus.setStatus('current') hpnicfPwVcStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("down", 1), ("up", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hpnicfPwVcStatus.setStatus('current') hpnicfPwVcRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 12), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hpnicfPwVcRowStatus.setStatus('current') hpnicfL2VpnPwe3Notifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3)) hpnicfPwVcSwitchWtoP = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 1)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr")) if mibBuilder.loadTexts: hpnicfPwVcSwitchWtoP.setStatus('current') hpnicfPwVcSwitchPtoW = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 2)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr")) if mibBuilder.loadTexts: hpnicfPwVcSwitchPtoW.setStatus('current') hpnicfPwVcDown = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 3)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr")) if mibBuilder.loadTexts: hpnicfPwVcDown.setStatus('current') hpnicfPwVcUp = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 4)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr")) if mibBuilder.loadTexts: hpnicfPwVcUp.setStatus('current') hpnicfPwVcDeleted = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 5)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr")) if mibBuilder.loadTexts: hpnicfPwVcDeleted.setStatus('current') mibBuilder.exportSymbols("HPN-ICF-L2VPN-PWE3-MIB", hpnicfPwVcEntry=hpnicfPwVcEntry, hpnicfPwVcOutboundLabel=hpnicfPwVcOutboundLabel, hpnicfPwVcID=hpnicfPwVcID, hpnicfL2VpnPwe3Table=hpnicfL2VpnPwe3Table, hpnicfL2VpnPwe3=hpnicfL2VpnPwe3, hpnicfPwVcTable=hpnicfPwVcTable, hpnicfPwVcSwitchPtoW=hpnicfPwVcSwitchPtoW, PYSNMP_MODULE_ID=hpnicfL2VpnPwe3, hpnicfPwVcAcStatus=hpnicfPwVcAcStatus, hpnicfPwVcDeleted=hpnicfPwVcDeleted, hpnicfPwVcStatus=hpnicfPwVcStatus, hpnicfL2VpnPwe3Notifications=hpnicfL2VpnPwe3Notifications, hpnicfPwVcMtu=hpnicfPwVcMtu, hpnicfPwVcSwitchWtoP=hpnicfPwVcSwitchWtoP, hpnicfPwVcIndex=hpnicfPwVcIndex, hpnicfPwVcUp=hpnicfPwVcUp, hpnicfPwVcDown=hpnicfPwVcDown, hpnicfPwVcIfIndex=hpnicfPwVcIfIndex, hpnicfPwVcType=hpnicfPwVcType, hpnicfPwVcCfgType=hpnicfPwVcCfgType, hpnicfPwVcInboundLabel=hpnicfPwVcInboundLabel, HpnicfL2VpnVcEncapsType=HpnicfL2VpnVcEncapsType, hpnicfPwVcRowStatus=hpnicfPwVcRowStatus, hpnicfL2VpnPwe3ScalarGroup=hpnicfL2VpnPwe3ScalarGroup, hpnicfPwVcTrapOpen=hpnicfPwVcTrapOpen, hpnicfPwVcPeerAddr=hpnicfPwVcPeerAddr)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, constraints_union, single_value_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection') (hpnicf_common,) = mibBuilder.importSymbols('HPN-ICF-OID-MIB', 'hpnicfCommon') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (gauge32, bits, mib_identifier, counter64, module_identity, counter32, unsigned32, object_identity, ip_address, notification_type, iso, time_ticks, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Bits', 'MibIdentifier', 'Counter64', 'ModuleIdentity', 'Counter32', 'Unsigned32', 'ObjectIdentity', 'IpAddress', 'NotificationType', 'iso', 'TimeTicks', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn') (display_string, row_status, textual_convention, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'RowStatus', 'TextualConvention', 'TruthValue') hpnicf_l2_vpn_pwe3 = module_identity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78)) if mibBuilder.loadTexts: hpnicfL2VpnPwe3.setLastUpdated('200703310000Z') if mibBuilder.loadTexts: hpnicfL2VpnPwe3.setOrganization('') class Hpnicfl2Vpnvcencapstype(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 255)) named_values = named_values(('frameRelayDlciMartini', 1), ('atmAal5SduVccTransport', 2), ('atmTransparentCellTransport', 3), ('ethernetTagged', 4), ('ethernet', 5), ('hdlc', 6), ('ppp', 7), ('cem', 8), ('atmN2OneVccCellTransport', 9), ('atmN2OneVpcCellTransport', 10), ('ipLayer2Transport', 11), ('atmOne2OneVccCellMode', 12), ('atmOne2OneVpcCellMode', 13), ('atmAal5PduVccTransport', 14), ('frameRelayPortMode', 15), ('cep', 16), ('saE1oP', 17), ('saT1oP', 18), ('saE3oP', 19), ('saT3oP', 20), ('cESoPsnBasicMode', 21), ('tDMoIPbasicMode', 22), ('l2VpnCESoPSNTDMwithCAS', 23), ('l2VpnTDMoIPTDMwithCAS', 24), ('frameRelayDlci', 25), ('ipInterworking', 64), ('unknown', 255)) hpnicf_l2_vpn_pwe3_scalar_group = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 1)) hpnicf_pw_vc_trap_open = mib_scalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 1, 1), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hpnicfPwVcTrapOpen.setStatus('current') hpnicf_l2_vpn_pwe3_table = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2)) hpnicf_pw_vc_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1)) if mibBuilder.loadTexts: hpnicfPwVcTable.setStatus('current') hpnicf_pw_vc_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1)).setIndexNames((0, 'HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcIndex')) if mibBuilder.loadTexts: hpnicfPwVcEntry.setStatus('current') hpnicf_pw_vc_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 1), integer32()) if mibBuilder.loadTexts: hpnicfPwVcIndex.setStatus('current') hpnicf_pw_vc_id = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 2), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcID.setStatus('current') hpnicf_pw_vc_type = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 3), hpnicf_l2_vpn_vc_encaps_type()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcType.setStatus('current') hpnicf_pw_vc_peer_addr = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 4), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcPeerAddr.setStatus('current') hpnicf_pw_vc_mtu = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 5), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcMtu.setStatus('current') hpnicf_pw_vc_cfg_type = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('primary', 1), ('backup', 2), ('multiPort', 3)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcCfgType.setStatus('current') hpnicf_pw_vc_inbound_label = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 7), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfPwVcInboundLabel.setStatus('current') hpnicf_pw_vc_outbound_label = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 8), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfPwVcOutboundLabel.setStatus('current') hpnicf_pw_vc_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 9), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcIfIndex.setStatus('current') hpnicf_pw_vc_ac_status = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('down', 1), ('up', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfPwVcAcStatus.setStatus('current') hpnicf_pw_vc_status = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('down', 1), ('up', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: hpnicfPwVcStatus.setStatus('current') hpnicf_pw_vc_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 12), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hpnicfPwVcRowStatus.setStatus('current') hpnicf_l2_vpn_pwe3_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3)) hpnicf_pw_vc_switch_wto_p = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 1)).setObjects(('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr')) if mibBuilder.loadTexts: hpnicfPwVcSwitchWtoP.setStatus('current') hpnicf_pw_vc_switch_pto_w = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 2)).setObjects(('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr')) if mibBuilder.loadTexts: hpnicfPwVcSwitchPtoW.setStatus('current') hpnicf_pw_vc_down = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 3)).setObjects(('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr')) if mibBuilder.loadTexts: hpnicfPwVcDown.setStatus('current') hpnicf_pw_vc_up = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 4)).setObjects(('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr')) if mibBuilder.loadTexts: hpnicfPwVcUp.setStatus('current') hpnicf_pw_vc_deleted = notification_type((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 5)).setObjects(('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcID'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcType'), ('HPN-ICF-L2VPN-PWE3-MIB', 'hpnicfPwVcPeerAddr')) if mibBuilder.loadTexts: hpnicfPwVcDeleted.setStatus('current') mibBuilder.exportSymbols('HPN-ICF-L2VPN-PWE3-MIB', hpnicfPwVcEntry=hpnicfPwVcEntry, hpnicfPwVcOutboundLabel=hpnicfPwVcOutboundLabel, hpnicfPwVcID=hpnicfPwVcID, hpnicfL2VpnPwe3Table=hpnicfL2VpnPwe3Table, hpnicfL2VpnPwe3=hpnicfL2VpnPwe3, hpnicfPwVcTable=hpnicfPwVcTable, hpnicfPwVcSwitchPtoW=hpnicfPwVcSwitchPtoW, PYSNMP_MODULE_ID=hpnicfL2VpnPwe3, hpnicfPwVcAcStatus=hpnicfPwVcAcStatus, hpnicfPwVcDeleted=hpnicfPwVcDeleted, hpnicfPwVcStatus=hpnicfPwVcStatus, hpnicfL2VpnPwe3Notifications=hpnicfL2VpnPwe3Notifications, hpnicfPwVcMtu=hpnicfPwVcMtu, hpnicfPwVcSwitchWtoP=hpnicfPwVcSwitchWtoP, hpnicfPwVcIndex=hpnicfPwVcIndex, hpnicfPwVcUp=hpnicfPwVcUp, hpnicfPwVcDown=hpnicfPwVcDown, hpnicfPwVcIfIndex=hpnicfPwVcIfIndex, hpnicfPwVcType=hpnicfPwVcType, hpnicfPwVcCfgType=hpnicfPwVcCfgType, hpnicfPwVcInboundLabel=hpnicfPwVcInboundLabel, HpnicfL2VpnVcEncapsType=HpnicfL2VpnVcEncapsType, hpnicfPwVcRowStatus=hpnicfPwVcRowStatus, hpnicfL2VpnPwe3ScalarGroup=hpnicfL2VpnPwe3ScalarGroup, hpnicfPwVcTrapOpen=hpnicfPwVcTrapOpen, hpnicfPwVcPeerAddr=hpnicfPwVcPeerAddr)
{ "targets": [ { "target_name": "gameLauncher", "conditions": [ ["OS==\"win\"", { "sources": [ "srcs/windows/GameLauncher.cpp" ] }], ["OS==\"linux\"", { "sources": [ "srcs/linux/GameLauncher.cpp" ] }] ] } ] }
{'targets': [{'target_name': 'gameLauncher', 'conditions': [['OS=="win"', {'sources': ['srcs/windows/GameLauncher.cpp']}], ['OS=="linux"', {'sources': ['srcs/linux/GameLauncher.cpp']}]]}]}
# pylint: disable=undefined-variable ## Whether to include output from clients other than this one sharing the same # kernel. # Required for jupyter-vim, see: # https://github.com/jupyter-vim/jupyter-vim#jupyter-configuration c.ZMQTerminalInteractiveShell.include_other_output = True ## Text to display before the first prompt. Will be formatted with variables # {version} and {kernel_banner}. c.ZMQTerminalInteractiveShell.banner = 'Jupyter console {version}' ## Shortcut style to use at the prompt. 'vi' or 'emacs'. #c.ZMQTerminalInteractiveShell.editing_mode = 'emacs' ## The name of a Pygments style to use for syntax highlighting c.ZMQTerminalInteractiveShell.highlighting_style = 'solarized-dark' ## How many history items to load into memory c.ZMQTerminalInteractiveShell.history_load_length = 1000 ## Use 24bit colors instead of 256 colors in prompt highlighting. If your # terminal supports true color, the following command should print 'TRUECOLOR' # in orange: printf "\x1b[38;2;255;100;0mTRUECOLOR\x1b[0m\n" c.ZMQTerminalInteractiveShell.true_color = True
c.ZMQTerminalInteractiveShell.include_other_output = True c.ZMQTerminalInteractiveShell.banner = 'Jupyter console {version}' c.ZMQTerminalInteractiveShell.highlighting_style = 'solarized-dark' c.ZMQTerminalInteractiveShell.history_load_length = 1000 c.ZMQTerminalInteractiveShell.true_color = True
# Function to count number of substrings # with exactly k unique characters def countkDist(str1, k): n = len(str1) # Initialize result res = 0 # Consider all substrings beginning # with str[i] for i in range(0, n): dist_count = 0 # Initializing array with 0 cnt = [0] * 27 # Consider all substrings between str[i..j] for j in range(i, n): # If this is a new character for this # substring, increment dist_count. if(cnt[ord(str1[j]) - 97] == 0): dist_count += 1 # Increment count of current character cnt[ord(str1[j]) - 97] += 1 # If distinct character count becomes k, # then increment result. if(dist_count == k): res += 1 if(dist_count > k): break return res
def countk_dist(str1, k): n = len(str1) res = 0 for i in range(0, n): dist_count = 0 cnt = [0] * 27 for j in range(i, n): if cnt[ord(str1[j]) - 97] == 0: dist_count += 1 cnt[ord(str1[j]) - 97] += 1 if dist_count == k: res += 1 if dist_count > k: break return res
def check_order(scale_list): ascending_list = sorted(scale_list) descending_list = sorted(scale_list, reverse=True) if scale_list == ascending_list: return "ascending" elif scale_list == descending_list: return "descending" else: return "mixed" def main(): scale_list = input().split() result_value = check_order(scale_list) print(result_value) if __name__ == "__main__": main()
def check_order(scale_list): ascending_list = sorted(scale_list) descending_list = sorted(scale_list, reverse=True) if scale_list == ascending_list: return 'ascending' elif scale_list == descending_list: return 'descending' else: return 'mixed' def main(): scale_list = input().split() result_value = check_order(scale_list) print(result_value) if __name__ == '__main__': main()
#! /usr/bin/env python3 # -*- coding: UTF-8 -*- #------------------------------------------------------------------------------ def asSeparator () : return "//" + ("-" * 78) + "\n" #------------------------------------------------------------------------------ def generateInterruptSection (interruptSectionName) : sCode = asSeparator () sCode += "// INTERRUPT - SECTION: " + interruptSectionName + "\n" sCode += asSeparator () + "\n" sCode += " .section .text.interrupt." + interruptSectionName + ", \"ax\", %progbits\n\n" sCode += " .align 1\n" sCode += " .global interrupt." + interruptSectionName + "\n" sCode += " .type interrupt." + interruptSectionName + ", %function\n\n" sCode += "interrupt." + interruptSectionName + ":\n" sCode += "//----------------------------------------- R2 <- CPU INDEX\n" sCode += " ldr r3, = 0xD0000000 + 0x000 // Address of SIO CPUID control register\n" sCode += " ldr r2, [r3] // R2 <- 0 for CPU0, 1 for CPU 1\n" sCode += "//----------------------------------------- Activity led On\n" sCode += " MACRO_ACTIVITY_LED_0_OR_1_ON // R2 should contain CPU index\n" sCode += "//--- Save registers\n" sCode += " push {r4, lr}\n" sCode += "//--- R4 <- Address of SPINLOCK 0 (rp2040 datasheet, 2.3.1.7, page 42)\n" sCode += " ldr r4, = 0xD0000000 + 0x100\n" sCode += "//--- Read: attempt to claim the lock. Read value is nonzero if the lock was\n" sCode += "// successfully claimed, or zero if the lock had already been claimed\n" sCode += "// by a previous read (rp2040 datasheet, section 2.3.1.3 page 30).\n" sCode += interruptSectionName +".spinlock.busy.wait:\n" sCode += " ldr r0, [r4]\n" sCode += " cmp r0, #0\n" sCode += " beq " + interruptSectionName +".spinlock.busy.wait\n" sCode += "//--- Call section, interrupts disabled, spinlock successfully claimed\n" sCode += " bl interrupt.section." + interruptSectionName + "\n" sCode += "//--- Write (any value): release the lock (rp2040 datasheet, section 2.3.1.3 page 30).\n" sCode += "// The next attempt to claim the lock will be successful.\n" sCode += " str r0, [r4]\n" sCode += "//--- Return\n" sCode += " pop {r4, pc}\n\n" return ("", sCode) #------------------------------------------------------------------------------ # ENTRY POINT #------------------------------------------------------------------------------ def buildSectionInterruptCode (interruptSectionList): #------------------------------ Destination file strings cppFile = "" sFile = "" #------------------------------ Iterate on section sectionList for interruptSectionName in interruptSectionList : (cppCode, sCode) = generateInterruptSection (interruptSectionName) cppFile += cppCode sFile += sCode #------------------------------ Return return (cppFile, sFile) #------------------------------------------------------------------------------
def as_separator(): return '//' + '-' * 78 + '\n' def generate_interrupt_section(interruptSectionName): s_code = as_separator() s_code += '// INTERRUPT - SECTION: ' + interruptSectionName + '\n' s_code += as_separator() + '\n' s_code += ' .section .text.interrupt.' + interruptSectionName + ', "ax", %progbits\n\n' s_code += ' .align 1\n' s_code += ' .global interrupt.' + interruptSectionName + '\n' s_code += ' .type interrupt.' + interruptSectionName + ', %function\n\n' s_code += 'interrupt.' + interruptSectionName + ':\n' s_code += '//----------------------------------------- R2 <- CPU INDEX\n' s_code += ' ldr r3, = 0xD0000000 + 0x000 // Address of SIO CPUID control register\n' s_code += ' ldr r2, [r3] // R2 <- 0 for CPU0, 1 for CPU 1\n' s_code += '//----------------------------------------- Activity led On\n' s_code += ' MACRO_ACTIVITY_LED_0_OR_1_ON // R2 should contain CPU index\n' s_code += '//--- Save registers\n' s_code += ' push {r4, lr}\n' s_code += '//--- R4 <- Address of SPINLOCK 0 (rp2040 datasheet, 2.3.1.7, page 42)\n' s_code += ' ldr r4, = 0xD0000000 + 0x100\n' s_code += '//--- Read: attempt to claim the lock. Read value is nonzero if the lock was\n' s_code += '// successfully claimed, or zero if the lock had already been claimed\n' s_code += '// by a previous read (rp2040 datasheet, section 2.3.1.3 page 30).\n' s_code += interruptSectionName + '.spinlock.busy.wait:\n' s_code += ' ldr r0, [r4]\n' s_code += ' cmp r0, #0\n' s_code += ' beq ' + interruptSectionName + '.spinlock.busy.wait\n' s_code += '//--- Call section, interrupts disabled, spinlock successfully claimed\n' s_code += ' bl interrupt.section.' + interruptSectionName + '\n' s_code += '//--- Write (any value): release the lock (rp2040 datasheet, section 2.3.1.3 page 30).\n' s_code += '// The next attempt to claim the lock will be successful.\n' s_code += ' str r0, [r4]\n' s_code += '//--- Return\n' s_code += ' pop {r4, pc}\n\n' return ('', sCode) def build_section_interrupt_code(interruptSectionList): cpp_file = '' s_file = '' for interrupt_section_name in interruptSectionList: (cpp_code, s_code) = generate_interrupt_section(interruptSectionName) cpp_file += cppCode s_file += sCode return (cppFile, sFile)
in_str = list(str(input())) str_len = len(in_str) # letters set set_letters = set(in_str) set_len = len(set_letters) if str_len == set_len: print("Unique") else: print("Deja Vu")
in_str = list(str(input())) str_len = len(in_str) set_letters = set(in_str) set_len = len(set_letters) if str_len == set_len: print('Unique') else: print('Deja Vu')
# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. { 'includes': [ '../build/common.gypi', ], 'targets': [ { 'target_name': 'peerconnection_unittests', 'type': '<(gtest_target_type)', 'dependencies': [ '<(DEPTH)/testing/gmock.gyp:gmock', '<(webrtc_root)/api/api.gyp:libjingle_peerconnection', '<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils', '<(webrtc_root)/common.gyp:webrtc_common', '<(webrtc_root)/media/media.gyp:rtc_unittest_main', '<(webrtc_root)/pc/pc.gyp:rtc_pc', ], 'direct_dependent_settings': { 'include_dirs': [ '<(DEPTH)/testing/gmock/include', ], }, 'defines': [ # Feature selection. 'HAVE_SCTP', ], 'sources': [ 'datachannel_unittest.cc', 'dtlsidentitystore_unittest.cc', 'dtmfsender_unittest.cc', 'fakemetricsobserver.cc', 'fakemetricsobserver.h', 'jsepsessiondescription_unittest.cc', 'localaudiosource_unittest.cc', 'mediaconstraintsinterface_unittest.cc', 'mediastream_unittest.cc', 'peerconnection_unittest.cc', 'peerconnectionendtoend_unittest.cc', 'peerconnectionfactory_unittest.cc', 'peerconnectioninterface_unittest.cc', 'proxy_unittest.cc', 'rtpsenderreceiver_unittest.cc', 'statscollector_unittest.cc', 'test/fakeaudiocapturemodule.cc', 'test/fakeaudiocapturemodule.h', 'test/fakeaudiocapturemodule_unittest.cc', 'test/fakeconstraints.h', 'test/fakedatachannelprovider.h', 'test/fakedtlsidentitystore.h', 'test/fakeperiodicvideocapturer.h', 'test/fakevideotrackrenderer.h', 'test/mockpeerconnectionobservers.h', 'test/peerconnectiontestwrapper.h', 'test/peerconnectiontestwrapper.cc', 'test/testsdpstrings.h', 'videocapturertracksource_unittest.cc', 'videotrack_unittest.cc', 'webrtcsdp_unittest.cc', 'webrtcsession_unittest.cc', ], # TODO(kjellander): Make the code compile without disabling these flags. # See https://bugs.chromium.org/p/webrtc/issues/detail?id=3307 'cflags': [ '-Wno-sign-compare', ], 'cflags!': [ '-Wextra', ], 'cflags_cc!': [ '-Woverloaded-virtual', ], 'msvs_disabled_warnings': [ 4245, # conversion from 'int' to 'size_t', signed/unsigned mismatch. 4267, # conversion from 'size_t' to 'int', possible loss of data. 4389, # signed/unsigned mismatch. ], 'conditions': [ ['clang==1', { # TODO(kjellander): Make the code compile without disabling these flags. # See https://bugs.chromium.org/p/webrtc/issues/detail?id=3307 'cflags!': [ '-Wextra', ], 'xcode_settings': { 'WARNING_CFLAGS!': ['-Wextra'], }, }], ['OS=="android"', { 'sources': [ 'test/androidtestinitializer.cc', 'test/androidtestinitializer.h', ], 'dependencies': [ '<(DEPTH)/testing/android/native_test.gyp:native_test_native_code', '<(webrtc_root)/api/api.gyp:libjingle_peerconnection_jni', ], }], ['OS=="win" and clang==1', { 'msvs_settings': { 'VCCLCompilerTool': { 'AdditionalOptions': [ # Disable warnings failing when compiling with Clang on Windows. # https://bugs.chromium.org/p/webrtc/issues/detail?id=5366 '-Wno-sign-compare', '-Wno-unused-function', ], }, }, }], ['use_quic==1', { 'dependencies': [ '<(DEPTH)/third_party/libquic/libquic.gyp:libquic', ], 'sources': [ 'quicdatachannel_unittest.cc', 'quicdatatransport_unittest.cc', ], 'export_dependent_settings': [ '<(DEPTH)/third_party/libquic/libquic.gyp:libquic', ], }], ], # conditions }, # target peerconnection_unittests ], # targets 'conditions': [ ['OS=="android"', { 'targets': [ { 'target_name': 'libjingle_peerconnection_android_unittest', 'type': 'none', 'dependencies': [ '<(webrtc_root)/api/api.gyp:libjingle_peerconnection_java', ], 'variables': { 'apk_name': 'libjingle_peerconnection_android_unittest', 'java_in_dir': 'androidtests', 'resource_dir': 'androidtests/res', 'native_lib_target': 'libjingle_peerconnection_so', 'is_test_apk': 1, 'test_type': 'instrumentation', 'tested_apk_path': '', 'never_lint': 1, }, 'includes': [ '../../build/java_apk.gypi', '../../build/android/test_runner.gypi', ], }, ], # targets }], # OS=="android" ['OS=="android"', { 'targets': [ { 'target_name': 'peerconnection_unittests_apk_target', 'type': 'none', 'dependencies': [ '<(apk_tests_path):peerconnection_unittests_apk', ], }, ], 'conditions': [ ['test_isolation_mode != "noop"', { 'targets': [ { 'target_name': 'peerconnection_unittests_apk_run', 'type': 'none', 'dependencies': [ '<(apk_tests_path):peerconnection_unittests_apk', ], 'includes': [ '../build/isolate.gypi', ], 'sources': [ 'peerconnection_unittests_apk.isolate', ], }, ] } ], ], }], # OS=="android" ['test_isolation_mode != "noop"', { 'targets': [ { 'target_name': 'peerconnection_unittests_run', 'type': 'none', 'dependencies': [ 'peerconnection_unittests', ], 'includes': [ '../build/isolate.gypi', ], 'sources': [ 'peerconnection_unittests.isolate', ], }, ], # targets }], # test_isolation_mode != "noop" ], # conditions }
{'includes': ['../build/common.gypi'], 'targets': [{'target_name': 'peerconnection_unittests', 'type': '<(gtest_target_type)', 'dependencies': ['<(DEPTH)/testing/gmock.gyp:gmock', '<(webrtc_root)/api/api.gyp:libjingle_peerconnection', '<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils', '<(webrtc_root)/common.gyp:webrtc_common', '<(webrtc_root)/media/media.gyp:rtc_unittest_main', '<(webrtc_root)/pc/pc.gyp:rtc_pc'], 'direct_dependent_settings': {'include_dirs': ['<(DEPTH)/testing/gmock/include']}, 'defines': ['HAVE_SCTP'], 'sources': ['datachannel_unittest.cc', 'dtlsidentitystore_unittest.cc', 'dtmfsender_unittest.cc', 'fakemetricsobserver.cc', 'fakemetricsobserver.h', 'jsepsessiondescription_unittest.cc', 'localaudiosource_unittest.cc', 'mediaconstraintsinterface_unittest.cc', 'mediastream_unittest.cc', 'peerconnection_unittest.cc', 'peerconnectionendtoend_unittest.cc', 'peerconnectionfactory_unittest.cc', 'peerconnectioninterface_unittest.cc', 'proxy_unittest.cc', 'rtpsenderreceiver_unittest.cc', 'statscollector_unittest.cc', 'test/fakeaudiocapturemodule.cc', 'test/fakeaudiocapturemodule.h', 'test/fakeaudiocapturemodule_unittest.cc', 'test/fakeconstraints.h', 'test/fakedatachannelprovider.h', 'test/fakedtlsidentitystore.h', 'test/fakeperiodicvideocapturer.h', 'test/fakevideotrackrenderer.h', 'test/mockpeerconnectionobservers.h', 'test/peerconnectiontestwrapper.h', 'test/peerconnectiontestwrapper.cc', 'test/testsdpstrings.h', 'videocapturertracksource_unittest.cc', 'videotrack_unittest.cc', 'webrtcsdp_unittest.cc', 'webrtcsession_unittest.cc'], 'cflags': ['-Wno-sign-compare'], 'cflags!': ['-Wextra'], 'cflags_cc!': ['-Woverloaded-virtual'], 'msvs_disabled_warnings': [4245, 4267, 4389], 'conditions': [['clang==1', {'cflags!': ['-Wextra'], 'xcode_settings': {'WARNING_CFLAGS!': ['-Wextra']}}], ['OS=="android"', {'sources': ['test/androidtestinitializer.cc', 'test/androidtestinitializer.h'], 'dependencies': ['<(DEPTH)/testing/android/native_test.gyp:native_test_native_code', '<(webrtc_root)/api/api.gyp:libjingle_peerconnection_jni']}], ['OS=="win" and clang==1', {'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': ['-Wno-sign-compare', '-Wno-unused-function']}}}], ['use_quic==1', {'dependencies': ['<(DEPTH)/third_party/libquic/libquic.gyp:libquic'], 'sources': ['quicdatachannel_unittest.cc', 'quicdatatransport_unittest.cc'], 'export_dependent_settings': ['<(DEPTH)/third_party/libquic/libquic.gyp:libquic']}]]}], 'conditions': [['OS=="android"', {'targets': [{'target_name': 'libjingle_peerconnection_android_unittest', 'type': 'none', 'dependencies': ['<(webrtc_root)/api/api.gyp:libjingle_peerconnection_java'], 'variables': {'apk_name': 'libjingle_peerconnection_android_unittest', 'java_in_dir': 'androidtests', 'resource_dir': 'androidtests/res', 'native_lib_target': 'libjingle_peerconnection_so', 'is_test_apk': 1, 'test_type': 'instrumentation', 'tested_apk_path': '', 'never_lint': 1}, 'includes': ['../../build/java_apk.gypi', '../../build/android/test_runner.gypi']}]}], ['OS=="android"', {'targets': [{'target_name': 'peerconnection_unittests_apk_target', 'type': 'none', 'dependencies': ['<(apk_tests_path):peerconnection_unittests_apk']}], 'conditions': [['test_isolation_mode != "noop"', {'targets': [{'target_name': 'peerconnection_unittests_apk_run', 'type': 'none', 'dependencies': ['<(apk_tests_path):peerconnection_unittests_apk'], 'includes': ['../build/isolate.gypi'], 'sources': ['peerconnection_unittests_apk.isolate']}]}]]}], ['test_isolation_mode != "noop"', {'targets': [{'target_name': 'peerconnection_unittests_run', 'type': 'none', 'dependencies': ['peerconnection_unittests'], 'includes': ['../build/isolate.gypi'], 'sources': ['peerconnection_unittests.isolate']}]}]]}
txtFile=open("/Users/chenchaoyang/Desktop/python/Python/content/content.txt","r") while True: line=txtFile.readline() if not line: break else: print(line) txtFile.close()
txt_file = open('/Users/chenchaoyang/Desktop/python/Python/content/content.txt', 'r') while True: line = txtFile.readline() if not line: break else: print(line) txtFile.close()
# Extra parsing for markdown (Highlighting and alert boxes) def parse(rtxt, look, control): txtl = rtxt.split(look) i, j = 0, 0 ret_text = "" while i < len(txtl): if j == 0: # This is the start before the specified tag, add it normally ret_text += control.start(txtl[i]) j+=1 elif j == 1: # This is the text we actually want to parse ret_text += control.inner(txtl[i]) j+=1 else: ret_text += control.end(txtl[i]) j = 1 i+=1 return ret_text class Control(): def start(self, s): return s def inner(self, s): return s def end(self, s): return s class HighlightControl(Control): def inner(self, s): return "<span class='highlight'>" + s + "</span>" class BoxControl(Control): def inner(self, s): style = s.split("\n")[0].strip().replace("<br />", "") # This controls info, alert, danger, warning, error etc... if style == "info": # info box return "<div class='alert-info white' style='color: white !important;'><i class='fa fa-info-circle i-m3' aria-hidden='true'></i><span class='bold'>Info</span>" + s.replace("info", "", 1) + "</div>" return s # This adds the == highlighter and ::: boxes def emd(txt: str) -> str: # == highlighting ret_text = parse(txt, "==", HighlightControl()) # ::: boxes ret_text = parse(ret_text, ":::", BoxControl()) return ret_text # Test cases #emd.emd("Hi ==Highlight== We love you == meow == What about you? == mew == ::: info\nHellow world:::")
def parse(rtxt, look, control): txtl = rtxt.split(look) (i, j) = (0, 0) ret_text = '' while i < len(txtl): if j == 0: ret_text += control.start(txtl[i]) j += 1 elif j == 1: ret_text += control.inner(txtl[i]) j += 1 else: ret_text += control.end(txtl[i]) j = 1 i += 1 return ret_text class Control: def start(self, s): return s def inner(self, s): return s def end(self, s): return s class Highlightcontrol(Control): def inner(self, s): return "<span class='highlight'>" + s + '</span>' class Boxcontrol(Control): def inner(self, s): style = s.split('\n')[0].strip().replace('<br />', '') if style == 'info': return "<div class='alert-info white' style='color: white !important;'><i class='fa fa-info-circle i-m3' aria-hidden='true'></i><span class='bold'>Info</span>" + s.replace('info', '', 1) + '</div>' return s def emd(txt: str) -> str: ret_text = parse(txt, '==', highlight_control()) ret_text = parse(ret_text, ':::', box_control()) return ret_text
# Copyright 2021, Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # returns fullfillment response for dialogflow detect_intent call # [START dialogflow_webhook] # TODO: change the default Entry Point text to handleWebhook def handleWebhook(request): req = request.get_json() responseText = "" intent = req["queryResult"]["intent"]["displayName"] if intent == "Default Welcome Intent": responseText = "Hello from a GCF Webhook" elif intent == "get-agent-name": responseText = "My name is Flowhook" else: responseText = f"There are no fulfillment responses defined for Intent {intent}" # You can also use the google.cloud.dialogflowcx_v3.types.WebhookRequest protos instead of manually writing the json object res = {"fulfillmentMessages": [{"text": {"text": [responseText]}}]} return res # [END dialogflow_webhook]
def handle_webhook(request): req = request.get_json() response_text = '' intent = req['queryResult']['intent']['displayName'] if intent == 'Default Welcome Intent': response_text = 'Hello from a GCF Webhook' elif intent == 'get-agent-name': response_text = 'My name is Flowhook' else: response_text = f'There are no fulfillment responses defined for Intent {intent}' res = {'fulfillmentMessages': [{'text': {'text': [responseText]}}]} return res
class TxtReader: def __init__(self, f): self.f = f def parse(self): file = open(self.f) line = file.readline() while line: print(line) line = file.readline() file.close #t = TxtReader('sample.txt') #t.parse()
class Txtreader: def __init__(self, f): self.f = f def parse(self): file = open(self.f) line = file.readline() while line: print(line) line = file.readline() file.close
# -*- coding: utf-8 -*- def greet(name): i =0 # while True: # i +=1 first_name, surname = name.split(' ') return 'Hello {0}, {1}'.format(surname, first_name) def suggest_travel(distance): if distance > 5: return 'You should take the train.' elif distance > 2: return 'You should cycle.' else: return 'Stop being lazy and walk!' def fizz_buzz(n): if n%3==0 and n%5==0: return 'FizzBuzz' elif n%3==0: return 'Fizz' elif n%5==0: return 'Buzz' else: return n def sum_odd_numbers(n): my_sum=0 for i in range(1,n): if i%2!=0: my_sum = my_sum + i return my_sum def double_char(word): double_word = "" # initialise double_word as an empty string for character in word: double_word = double_word + character*2 return double_word def sum_div3_numbers(n): my_sum=0 for i in range(1,n): if i%3==0: my_sum = my_sum + i return my_sum def sum_numbers(n): my_sum=0 for i in range(1,n): my_sum = my_sum + i return my_sum
def greet(name): i = 0 (first_name, surname) = name.split(' ') return 'Hello {0}, {1}'.format(surname, first_name) def suggest_travel(distance): if distance > 5: return 'You should take the train.' elif distance > 2: return 'You should cycle.' else: return 'Stop being lazy and walk!' def fizz_buzz(n): if n % 3 == 0 and n % 5 == 0: return 'FizzBuzz' elif n % 3 == 0: return 'Fizz' elif n % 5 == 0: return 'Buzz' else: return n def sum_odd_numbers(n): my_sum = 0 for i in range(1, n): if i % 2 != 0: my_sum = my_sum + i return my_sum def double_char(word): double_word = '' for character in word: double_word = double_word + character * 2 return double_word def sum_div3_numbers(n): my_sum = 0 for i in range(1, n): if i % 3 == 0: my_sum = my_sum + i return my_sum def sum_numbers(n): my_sum = 0 for i in range(1, n): my_sum = my_sum + i return my_sum
# Para criar uma lista com 5 elementos '_' # ex. ['_', '_', '_', '_', '_'] print("Lista com elementos iguais") lista = [] for i in range(5): lista.append('_') print("Lista: ", lista) # Alternativa lista_alternativa = ['_' for i in range(5)] print("Modo Alternativdo de criar lista: ", lista_alternativa) # Para criar uma lista com 6 numeros # ex. [0, 1, 2, 3, 4, 5] print("Lista com numeros na sequencia") lista = [] for i in range(6): lista.append(i) print("Lista: ", lista) # Alternativa lista_alternativa = [i for i in range(6)] print("Modo Alternativdo de criar lista: ", lista_alternativa) # Para criar uma lista com 6 numeros pares # ex. [0, 2, 4, 6, 8, 10] print("Lista com 6 numeros pares na sequencia") lista = [] for i in range(6): lista.append(i * 2) print("Lista: ", lista) # Alternativa lista_alternativa = [i * 2 for i in range(6)] print("Modo Alternativdo de criar lista: ", lista_alternativa) # Para criar uma matriz com elementos repetidos # ex. [ ['_', '_', '_'], # ['_', '_', '_'], # ['_', '_', '_'] # ] print("Matriz 3x3 com elementos repetidos") matriz = [] for l in range(3): linha = [] for c in range(6): linha.append('_') matriz.append(linha) print("Matriz: ", matriz) # Alternativa matriz_alternativa = [['_' for c in range(3)] for l in range(3)] print("Modo Alternativdo de criar matriz: ", matriz_alternativa)
print('Lista com elementos iguais') lista = [] for i in range(5): lista.append('_') print('Lista: ', lista) lista_alternativa = ['_' for i in range(5)] print('Modo Alternativdo de criar lista: ', lista_alternativa) print('Lista com numeros na sequencia') lista = [] for i in range(6): lista.append(i) print('Lista: ', lista) lista_alternativa = [i for i in range(6)] print('Modo Alternativdo de criar lista: ', lista_alternativa) print('Lista com 6 numeros pares na sequencia') lista = [] for i in range(6): lista.append(i * 2) print('Lista: ', lista) lista_alternativa = [i * 2 for i in range(6)] print('Modo Alternativdo de criar lista: ', lista_alternativa) print('Matriz 3x3 com elementos repetidos') matriz = [] for l in range(3): linha = [] for c in range(6): linha.append('_') matriz.append(linha) print('Matriz: ', matriz) matriz_alternativa = [['_' for c in range(3)] for l in range(3)] print('Modo Alternativdo de criar matriz: ', matriz_alternativa)
#hack RSA, caluclate the p,q,d in order by given t,n,e def finitePrimeHack(t, n, e): res_list = [] # find p & q for i in range(2, t): if n % i == 0: p = i q = n//p res_list.append(p) res_list.append(q) #sort the list as p <= q res_list.sort() # find the d which is modular inverse of e d = 0 y = 1 far = (p-1)*(q-1) while (((far * y) + 1) % e) != 0: y += 1 d = (far * y + 1) // e res_list.append(d) # print(res_list) return res_list def blockSizeHack(blocks, n, e): SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.' string = [] p = 0 q = 0 for i in range(2, n): if n % i == 0: p = i q = n//p break x = (p-1)*(q-1) y = 1 d = 0 while (((x * y) + 1) % e) != 0: y += 1 d = (x * y + 1) // e for i in range(len(blocks)): blockInt = pow(blocks[i], d, n) if blockInt < len(SYMBOLS)**i and blockInt != 0: blockInt = blockInt % (len(SYMBOLS)**i) else: blockInt = blockInt // (len(SYMBOLS)**i) string.append(SYMBOLS[blockInt]) return ''.join(string) def main(): # # question1 t = 100 n = 493 e = 5 print(finitePrimeHack(t, n, e)) # question3 blocks = [2361958428825, 564784031984, 693733403745, 693733403745, 2246930915779, 1969885380643] n = 3328101456763 e = 1827871 print(blockSizeHack(blocks, n, e)) if __name__ == "__main__": main()
def finite_prime_hack(t, n, e): res_list = [] for i in range(2, t): if n % i == 0: p = i q = n // p res_list.append(p) res_list.append(q) res_list.sort() d = 0 y = 1 far = (p - 1) * (q - 1) while (far * y + 1) % e != 0: y += 1 d = (far * y + 1) // e res_list.append(d) return res_list def block_size_hack(blocks, n, e): symbols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.' string = [] p = 0 q = 0 for i in range(2, n): if n % i == 0: p = i q = n // p break x = (p - 1) * (q - 1) y = 1 d = 0 while (x * y + 1) % e != 0: y += 1 d = (x * y + 1) // e for i in range(len(blocks)): block_int = pow(blocks[i], d, n) if blockInt < len(SYMBOLS) ** i and blockInt != 0: block_int = blockInt % len(SYMBOLS) ** i else: block_int = blockInt // len(SYMBOLS) ** i string.append(SYMBOLS[blockInt]) return ''.join(string) def main(): t = 100 n = 493 e = 5 print(finite_prime_hack(t, n, e)) blocks = [2361958428825, 564784031984, 693733403745, 693733403745, 2246930915779, 1969885380643] n = 3328101456763 e = 1827871 print(block_size_hack(blocks, n, e)) if __name__ == '__main__': main()
n1 = int(input()) n2 = int(input()) n3 = int(input()) if n1 > n2 > n3: print(n3) print(n2) print(n1) elif n2 > n1 > n3: print(n3) print(n1) print(n2) elif n1 > n3 > n2: print(n2) print(n3) print(n1) elif n2 > n3 > n1: print(n1) print(n3) print(n2) elif n3 > n2 > n1: print(n1) print(n2) print(n3) elif n3 > n1 > n2: print(n2) print(n1) print(n3)
n1 = int(input()) n2 = int(input()) n3 = int(input()) if n1 > n2 > n3: print(n3) print(n2) print(n1) elif n2 > n1 > n3: print(n3) print(n1) print(n2) elif n1 > n3 > n2: print(n2) print(n3) print(n1) elif n2 > n3 > n1: print(n1) print(n3) print(n2) elif n3 > n2 > n1: print(n1) print(n2) print(n3) elif n3 > n1 > n2: print(n2) print(n1) print(n3)
# https://codeforces.com/problemset/problem/959/A n = int(input()) print('Mahmoud' if n%2 == 0 else 'Ehab')
n = int(input()) print('Mahmoud' if n % 2 == 0 else 'Ehab')
# # Copyright (c) 2017-2018 Joy Diamond. All rights reserved. # @gem('Sapphire.Parse1Atom') def gem(): show = 7 @share def parse1_map_element(): if qk() is not none: #my_line('qk: %r', qk()) raise_unknown_line() token = parse1_atom() if token.is_right_brace: return token if token.is_special_operator: raise_unknown_line() operator = qk() if operator is none: if qn() is not none: raise_unknown_line() operator = tokenize_operator() else: wk(none) if not operator.is_colon: token = parse1_ternary_expression__X__any_expression(token, operator) operator = qk() if operator is none: raise_unknown_line() wk(none) if not operator.is_colon: raise_unknown_line() return conjure_map_element(token, operator, parse1_ternary_expression()) @share def parse1_map__left_brace(left_brace): # # 1 # left = parse1_map_element() if left.is_right_brace: return conjure_empty_map(left_brace, left) operator = qk() if operator is none: operator = tokenize_operator() else: wk(none) if operator.is_keyword_for: left = parse1_comprehension_expression__X__any_expression(left, operator) operator = qk() if operator is none: operator = tokenize_operator() else: wk(none) if operator.is_right_brace: return conjure_map_expression_1(left_brace, left, operator) if not operator.is_comma: raise_unknown_line() token = parse1_map_element() if token.is_right_brace: return conjure_map_expression_1(left_brace, left, conjure__comma__right_brace(operator, token)) many = [left, token] many_frill = [operator] while 7 is 7: operator = qk() if operator is none: raise_unknown_line() wk(none) if operator.is_right_brace: return conjure_map_expression_many(left_brace, many, many_frill, operator) if not operator.is_comma: raise_unknown_line() token = parse1_map_element() if token.is_right_brace: return conjure_map_expression_many( left_brace, many, many_frill, conjure__comma__right_brace(operator, token), ) many_frill.append(operator) many.append(token) @share def parse1__parenthesized_expression__left_parenthesis(left_parenthesis): # # 1 # # # TODO: # Replace this with 'parse1__parenthesis__first_atom' & handle a right-parenthesis as an empty tuple # middle_1 = parse1_atom() if middle_1.is_right_parenthesis: return conjure_empty_tuple(left_parenthesis, middle_1) if middle_1.is_special_operator: raise_unknown_line() operator_1 = qk() if operator_1 is none: operator_1 = tokenize_operator() else: wk(none) #my_line('operator_1: %r', operator_1) if not operator_1.is_end_of_ternary_expression: middle_1 = parse1_ternary_expression__X__any_expression(middle_1, operator_1) operator_1 = qk() wk(none) if operator_1.is_right_parenthesis: return conjure_parenthesized_expression(left_parenthesis, middle_1, operator_1) if operator_1.is_comma__right_parenthesis: return conjure_parenthesized_tuple_expression_1(left_parenthesis, middle_1, operator_1) if not operator_1.is_comma: raise_unknown_line() # # 2 # middle_2 = parse1_atom() if middle_2.is_right_parenthesis: return conjure_parenthesized_tuple_expression_1( left_parenthesis, middle_1, conjure_comma__right_parenthesis(operator_1, middle_2), ) if middle_2.is_special_operator: raise_unknown_line() operator_2 = tokenize_operator() if not operator_2.is_end_of_ternary_expression: middle_2 = parse1_ternary_expression__X__any_expression(middle_2, operator_2) operator_2 = qk() wk(none) if operator_2.is__optional_comma__right_parenthesis: return conjure_tuple_expression_2(left_parenthesis, middle_1, operator_1, middle_2, operator_2) if not operator_2.is_comma: raise_unknown_line() # # 3 # middle_3 = parse1_atom() if middle_3.is_right_parenthesis: return conjure_tuple_expression_2( left_parenthesis, middle_1, operator_1, middle_2, conjure_comma__right_parenthesis(operator_2, middle_3), ) if middle_3.is_special_operator: raise_unknown_line() many = [middle_1, middle_2] many_frill = [operator_1, operator_2] while 7 is 7: operator_7 = tokenize_operator() if not operator_7.is_end_of_ternary_expression: middle_3 = parse1_ternary_expression__X__any_expression(middle_3, operator_7) operator_7 = qk() wk(none) many.append(middle_3) if operator_7.is__optional_comma__right_parenthesis: return conjure_tuple_expression_many(left_parenthesis, many, many_frill, operator_7) if not operator_7.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_parenthesis: return conjure_tuple_expression_many( left_parenthesis, many, many_frill, conjure_comma__right_parenthesis(operator_7, middle_3), ) if middle_3.is_special_operator: raise_unknown_line() many_frill.append(operator_7) @share def parse1__list_expression__left_square_bracket(left_square_bracket): # # 1 # middle_1 = parse1_atom() if middle_1.is_right_square_bracket: return conjure_empty_list(left_square_bracket, middle_1) if middle_1.is_special_operator: raise_unknown_line() operator_1 = tokenize_operator() if not operator_1.is_end_of_comprehension_expression: middle_1 = parse1_comprehension_expression__X__any_expression(middle_1, operator_1) operator_1 = qk() wk(none) if operator_1.is__optional_comma__right_square_bracket: return conjure_list_expression_1(left_square_bracket, middle_1, operator_1) if not operator_1.is_comma: #my_line('line: %d; middle_1: %r; operator_1: %r', ql(), middle_1, operator_1) raise_unknown_line() # # 2 # middle_2 = parse1_atom() if middle_2.is_right_square_bracket: return conjure_list_expression_1( left_square_bracket, middle_1, conjure_comma__right_square_bracket(operator_1, middle_2), ) if middle_2.is_special_operator: raise_unknown_line() operator_2 = tokenize_operator() if not operator_2.is_end_of_ternary_expression: middle_2 = parse1_ternary_expression__X__any_expression(middle_2, operator_2) operator_2 = qk() wk(none) if operator_2.is__optional_comma__right_square_bracket: return conjure_list_expression_2(left_square_bracket, middle_1, operator_1, middle_2, operator_2) if not operator_2.is_comma: raise_unknown_line() # # 3 # middle_3 = parse1_atom() if middle_3.is_right_square_bracket: return conjure_list_expression_2( left_square_bracket, middle_1, operator_1, middle_2, conjure_comma__right_square_bracket(operator_2, middle_3), ) if middle_3.is_special_operator: raise_unknown_line() many = [middle_1, middle_2] many_frill = [operator_1, operator_2] while 7 is 7: operator_7 = tokenize_operator() if not operator_7.is_end_of_ternary_expression: middle_3 = parse1_ternary_expression__X__any_expression(middle_3, operator_7) operator_7 = qk() wk(none) many.append(middle_3) if operator_7.is__optional_comma__right_square_bracket: return conjure_list_expression_many(left_square_bracket, many, many_frill, operator_7) if not operator_7.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_square_bracket: return conjure_list_expression_many( left_square_bracket, many, many_frill, conjure_comma__right_square_bracket(operator_7, middle_3), ) if middle_3.is_special_operator: raise_unknown_line() many_frill.append(operator_7) @share def parse1_atom(): assert qk() is none assert qn() is none m = atom_match(qs(), qj()) if m is none: #my_line('full: %r; s: %r', portray_string(qs()), portray_string(qs()[qj() :])) raise_unknown_line() token = analyze_atom(m) if token.is__atom__or__special_operator: return token if token.is_left_parenthesis: return parse1__parenthesized_expression__left_parenthesis(token) if token.is_left_square_bracket: return parse1__list_expression__left_square_bracket(token) if token.is_left_brace: return parse1_map__left_brace(token) if token.is_keyword_not: return parse1_not_expression__operator(token) if token.is_minus_sign: return parse1_negative_expression__operator(token) if token.is_tilde_sign: return parse1_twos_complement_expression__operator(token) if token.is_star_sign: return conjure_star_argument(token, parse1_ternary_expression()) my_line('token: %r', token) assert 0 raise_unknown_line()
@gem('Sapphire.Parse1Atom') def gem(): show = 7 @share def parse1_map_element(): if qk() is not none: raise_unknown_line() token = parse1_atom() if token.is_right_brace: return token if token.is_special_operator: raise_unknown_line() operator = qk() if operator is none: if qn() is not none: raise_unknown_line() operator = tokenize_operator() else: wk(none) if not operator.is_colon: token = parse1_ternary_expression__x__any_expression(token, operator) operator = qk() if operator is none: raise_unknown_line() wk(none) if not operator.is_colon: raise_unknown_line() return conjure_map_element(token, operator, parse1_ternary_expression()) @share def parse1_map__left_brace(left_brace): left = parse1_map_element() if left.is_right_brace: return conjure_empty_map(left_brace, left) operator = qk() if operator is none: operator = tokenize_operator() else: wk(none) if operator.is_keyword_for: left = parse1_comprehension_expression__x__any_expression(left, operator) operator = qk() if operator is none: operator = tokenize_operator() else: wk(none) if operator.is_right_brace: return conjure_map_expression_1(left_brace, left, operator) if not operator.is_comma: raise_unknown_line() token = parse1_map_element() if token.is_right_brace: return conjure_map_expression_1(left_brace, left, conjure__comma__right_brace(operator, token)) many = [left, token] many_frill = [operator] while 7 is 7: operator = qk() if operator is none: raise_unknown_line() wk(none) if operator.is_right_brace: return conjure_map_expression_many(left_brace, many, many_frill, operator) if not operator.is_comma: raise_unknown_line() token = parse1_map_element() if token.is_right_brace: return conjure_map_expression_many(left_brace, many, many_frill, conjure__comma__right_brace(operator, token)) many_frill.append(operator) many.append(token) @share def parse1__parenthesized_expression__left_parenthesis(left_parenthesis): middle_1 = parse1_atom() if middle_1.is_right_parenthesis: return conjure_empty_tuple(left_parenthesis, middle_1) if middle_1.is_special_operator: raise_unknown_line() operator_1 = qk() if operator_1 is none: operator_1 = tokenize_operator() else: wk(none) if not operator_1.is_end_of_ternary_expression: middle_1 = parse1_ternary_expression__x__any_expression(middle_1, operator_1) operator_1 = qk() wk(none) if operator_1.is_right_parenthesis: return conjure_parenthesized_expression(left_parenthesis, middle_1, operator_1) if operator_1.is_comma__right_parenthesis: return conjure_parenthesized_tuple_expression_1(left_parenthesis, middle_1, operator_1) if not operator_1.is_comma: raise_unknown_line() middle_2 = parse1_atom() if middle_2.is_right_parenthesis: return conjure_parenthesized_tuple_expression_1(left_parenthesis, middle_1, conjure_comma__right_parenthesis(operator_1, middle_2)) if middle_2.is_special_operator: raise_unknown_line() operator_2 = tokenize_operator() if not operator_2.is_end_of_ternary_expression: middle_2 = parse1_ternary_expression__x__any_expression(middle_2, operator_2) operator_2 = qk() wk(none) if operator_2.is__optional_comma__right_parenthesis: return conjure_tuple_expression_2(left_parenthesis, middle_1, operator_1, middle_2, operator_2) if not operator_2.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_parenthesis: return conjure_tuple_expression_2(left_parenthesis, middle_1, operator_1, middle_2, conjure_comma__right_parenthesis(operator_2, middle_3)) if middle_3.is_special_operator: raise_unknown_line() many = [middle_1, middle_2] many_frill = [operator_1, operator_2] while 7 is 7: operator_7 = tokenize_operator() if not operator_7.is_end_of_ternary_expression: middle_3 = parse1_ternary_expression__x__any_expression(middle_3, operator_7) operator_7 = qk() wk(none) many.append(middle_3) if operator_7.is__optional_comma__right_parenthesis: return conjure_tuple_expression_many(left_parenthesis, many, many_frill, operator_7) if not operator_7.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_parenthesis: return conjure_tuple_expression_many(left_parenthesis, many, many_frill, conjure_comma__right_parenthesis(operator_7, middle_3)) if middle_3.is_special_operator: raise_unknown_line() many_frill.append(operator_7) @share def parse1__list_expression__left_square_bracket(left_square_bracket): middle_1 = parse1_atom() if middle_1.is_right_square_bracket: return conjure_empty_list(left_square_bracket, middle_1) if middle_1.is_special_operator: raise_unknown_line() operator_1 = tokenize_operator() if not operator_1.is_end_of_comprehension_expression: middle_1 = parse1_comprehension_expression__x__any_expression(middle_1, operator_1) operator_1 = qk() wk(none) if operator_1.is__optional_comma__right_square_bracket: return conjure_list_expression_1(left_square_bracket, middle_1, operator_1) if not operator_1.is_comma: raise_unknown_line() middle_2 = parse1_atom() if middle_2.is_right_square_bracket: return conjure_list_expression_1(left_square_bracket, middle_1, conjure_comma__right_square_bracket(operator_1, middle_2)) if middle_2.is_special_operator: raise_unknown_line() operator_2 = tokenize_operator() if not operator_2.is_end_of_ternary_expression: middle_2 = parse1_ternary_expression__x__any_expression(middle_2, operator_2) operator_2 = qk() wk(none) if operator_2.is__optional_comma__right_square_bracket: return conjure_list_expression_2(left_square_bracket, middle_1, operator_1, middle_2, operator_2) if not operator_2.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_square_bracket: return conjure_list_expression_2(left_square_bracket, middle_1, operator_1, middle_2, conjure_comma__right_square_bracket(operator_2, middle_3)) if middle_3.is_special_operator: raise_unknown_line() many = [middle_1, middle_2] many_frill = [operator_1, operator_2] while 7 is 7: operator_7 = tokenize_operator() if not operator_7.is_end_of_ternary_expression: middle_3 = parse1_ternary_expression__x__any_expression(middle_3, operator_7) operator_7 = qk() wk(none) many.append(middle_3) if operator_7.is__optional_comma__right_square_bracket: return conjure_list_expression_many(left_square_bracket, many, many_frill, operator_7) if not operator_7.is_comma: raise_unknown_line() middle_3 = parse1_atom() if middle_3.is_right_square_bracket: return conjure_list_expression_many(left_square_bracket, many, many_frill, conjure_comma__right_square_bracket(operator_7, middle_3)) if middle_3.is_special_operator: raise_unknown_line() many_frill.append(operator_7) @share def parse1_atom(): assert qk() is none assert qn() is none m = atom_match(qs(), qj()) if m is none: raise_unknown_line() token = analyze_atom(m) if token.is__atom__or__special_operator: return token if token.is_left_parenthesis: return parse1__parenthesized_expression__left_parenthesis(token) if token.is_left_square_bracket: return parse1__list_expression__left_square_bracket(token) if token.is_left_brace: return parse1_map__left_brace(token) if token.is_keyword_not: return parse1_not_expression__operator(token) if token.is_minus_sign: return parse1_negative_expression__operator(token) if token.is_tilde_sign: return parse1_twos_complement_expression__operator(token) if token.is_star_sign: return conjure_star_argument(token, parse1_ternary_expression()) my_line('token: %r', token) assert 0 raise_unknown_line()
def calculateFuel(weight): return int(weight / 3)-2 # Part 1 total = 0 with open("/Users/a318196/Code/AdventOfCode2020/20191201/input.txt") as file: for line in file: total += calculateFuel(int(line)) print ('Total part 1: ' + str(total)) # Part 2 total = 0 with open("/Users/a318196/Code/AdventOfCode2020/20191201/input.txt") as file: for line in file: fuel = calculateFuel(int(line)) additionalFuel = calculateFuel(fuel) while additionalFuel > 0: fuel += additionalFuel additionalFuel = calculateFuel(additionalFuel) total += fuel print ('Total part 2: ' + str(total))
def calculate_fuel(weight): return int(weight / 3) - 2 total = 0 with open('/Users/a318196/Code/AdventOfCode2020/20191201/input.txt') as file: for line in file: total += calculate_fuel(int(line)) print('Total part 1: ' + str(total)) total = 0 with open('/Users/a318196/Code/AdventOfCode2020/20191201/input.txt') as file: for line in file: fuel = calculate_fuel(int(line)) additional_fuel = calculate_fuel(fuel) while additionalFuel > 0: fuel += additionalFuel additional_fuel = calculate_fuel(additionalFuel) total += fuel print('Total part 2: ' + str(total))
class FLAG_OPTIONS: MUTLIPLE_SEGMENTS_EXIST = 0x1 ALL_PROPERLY_ALIGNED = 0x2 SEG_UNMAPPED = 0x4 NEXT_SEG_UNMAPPED = 0x8 SEQ_REV_COMP = 0x10 NEXT_SEQ_REV_COMP = 0x20 FIRST_SEQ_IN_TEMP = 0x40 LAST_SEQ_IN_TEMP = 0x80 SECONDARY_ALG = 0x100 POOR_QUALITY = 0x200 DUPLICATE_READ = 0x400 SUPPLEMENTARY_ALG = 0x800
class Flag_Options: mutliple_segments_exist = 1 all_properly_aligned = 2 seg_unmapped = 4 next_seg_unmapped = 8 seq_rev_comp = 16 next_seq_rev_comp = 32 first_seq_in_temp = 64 last_seq_in_temp = 128 secondary_alg = 256 poor_quality = 512 duplicate_read = 1024 supplementary_alg = 2048
secure_log_path = "/var/log/secure"; secure_log_score_tokens = \ { "Invalid user": 3, "User root": 5, "Failed password": 2 }; secure_log_score_limit = 10; #firewall-cmd --permanent --ipset=some_set --add-entry=xxx.xxx.xxx.xxx firewalld_ipset_name = "ips2drop"; ##################################################### # technical section # ##################################################### # time_stamp_pattern = ""; ip_address_pattern = r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"; abuse_report_mail_pattern = r"abuse@[a-zA-Z]+\.[a-zA-Z]+"; #####################################################
secure_log_path = '/var/log/secure' secure_log_score_tokens = {'Invalid user': 3, 'User root': 5, 'Failed password': 2} secure_log_score_limit = 10 firewalld_ipset_name = 'ips2drop' ip_address_pattern = '[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}' abuse_report_mail_pattern = 'abuse@[a-zA-Z]+\\.[a-zA-Z]+'
a, b, c, d = map(int, input().split()) s = a + b + c + d a, b, c, d = map(int, input().split()) t = a + b + c + d print(max(s, t))
(a, b, c, d) = map(int, input().split()) s = a + b + c + d (a, b, c, d) = map(int, input().split()) t = a + b + c + d print(max(s, t))
# Copyright (c) Nikita Sychev, 29.04.2017 # Licensed by MIT a = input() b = input() c = input() n = len(a) a_new = "" b_new = "" c_new = "" for i in range(n): unused = chr(ord('A') + ord('B') + ord('C') + ord('?') - ord(a[i]) - ord(b[i]) - ord(c[i])) if a[i] == '?': a_new += unused else: a_new += a[i] if b[i] == '?': b_new += unused else: b_new += b[i] if c[i] == '?': c_new += unused else: c_new += c[i] print(a_new) print(b_new) print(c_new)
a = input() b = input() c = input() n = len(a) a_new = '' b_new = '' c_new = '' for i in range(n): unused = chr(ord('A') + ord('B') + ord('C') + ord('?') - ord(a[i]) - ord(b[i]) - ord(c[i])) if a[i] == '?': a_new += unused else: a_new += a[i] if b[i] == '?': b_new += unused else: b_new += b[i] if c[i] == '?': c_new += unused else: c_new += c[i] print(a_new) print(b_new) print(c_new)
def sum(x,y): print("sum"," =",(x+y)) def subtract(x,y): print("difference"," =",(x-y)) def divide(x,y): print("division"," =",(x/y)) def multiply(x,y): print("multiplication"," =",(x/y))
def sum(x, y): print('sum', ' =', x + y) def subtract(x, y): print('difference', ' =', x - y) def divide(x, y): print('division', ' =', x / y) def multiply(x, y): print('multiplication', ' =', x / y)
# 110. Balanced Binary Tree # Runtime: 3232 ms, faster than 5.10% of Python3 online submissions for Balanced Binary Tree. # Memory Usage: 17.6 MB, less than 100.00% of Python3 online submissions for Balanced Binary Tree. # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: # Recursive def isBalanced(self, root: TreeNode) -> bool: if not root: return True else: def get_depth(node: TreeNode) -> int: if not node: return 0 else: return max(get_depth(node.left), get_depth(node.right)) + 1 depth_diff = abs(get_depth(root.left) - get_depth(root.right)) <= 1 balance_child = self.isBalanced(root.left) and self.isBalanced(root.right) return depth_diff and balance_child
class Solution: def is_balanced(self, root: TreeNode) -> bool: if not root: return True else: def get_depth(node: TreeNode) -> int: if not node: return 0 else: return max(get_depth(node.left), get_depth(node.right)) + 1 depth_diff = abs(get_depth(root.left) - get_depth(root.right)) <= 1 balance_child = self.isBalanced(root.left) and self.isBalanced(root.right) return depth_diff and balance_child
# Link: https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/ # Time: O(N) # Space: O(N) def reverse_parentheses(s): stack, queue = [], [] for char in s: if char == ")": while stack[-1] != "(": queue.append(stack.pop()) stack.pop() # remove '(' while queue: stack.append(queue.pop(0)) else: stack.append(char) return "".join(stack) def main(): s = "(ed(et(oc))el)" print(reverse_parentheses(s)) if __name__ == "__main__": main()
def reverse_parentheses(s): (stack, queue) = ([], []) for char in s: if char == ')': while stack[-1] != '(': queue.append(stack.pop()) stack.pop() while queue: stack.append(queue.pop(0)) else: stack.append(char) return ''.join(stack) def main(): s = '(ed(et(oc))el)' print(reverse_parentheses(s)) if __name__ == '__main__': main()
x = input("Enter a string") y = input("Enter a string") z = input("Enter a string") for i in range(10): print("This is some output from the lab ",i) print("Your input was " + x) print("Your input was " + y) print("Your input was " + z)
x = input('Enter a string') y = input('Enter a string') z = input('Enter a string') for i in range(10): print('This is some output from the lab ', i) print('Your input was ' + x) print('Your input was ' + y) print('Your input was ' + z)
class Solution: def reverseBits(self, n): result = 0 for i in range(32): result <<= 1 if n & 1 > 0: result += 1 n >>= 1 return result
class Solution: def reverse_bits(self, n): result = 0 for i in range(32): result <<= 1 if n & 1 > 0: result += 1 n >>= 1 return result
i = 1 n = 1 S = int(0) while i <= 39: somar = i/n S = S + somar n = n*2 i = i + 2 print('%.2f'%S)
i = 1 n = 1 s = int(0) while i <= 39: somar = i / n s = S + somar n = n * 2 i = i + 2 print('%.2f' % S)
''' Class to define a LIFO Stack ''' class UnderflowException(Exception): ''' Raised when any element access operation is attempted on an empty stack. ''' pass class Stack(object): ''' Implements a Stack or a LIFO-style collection of elements. ''' def __init__(self): self.stack = [] def push(self, elem): ''' Push an element to the top of the stack. ''' self.stack.append(elem) def pop(self): ''' Remove and returns the top element of the stack. ''' if self.stack: return self.stack.pop() else: raise UnderflowException("Stack is empty!!") def top(self): ''' Returns the next element of the stack. ''' if self.stack: return self.stack[-1] else: return None def isEmpty(self): ''' Returns True iff stack is empty. ''' return len(self.stack) == 0 def makeCopy(self): ''' Returns a new object which is an exact copy of the current stack ''' newObj = Stack() newObj.stack = list(self.stack) return newObj
""" Class to define a LIFO Stack """ class Underflowexception(Exception): """ Raised when any element access operation is attempted on an empty stack. """ pass class Stack(object): """ Implements a Stack or a LIFO-style collection of elements. """ def __init__(self): self.stack = [] def push(self, elem): """ Push an element to the top of the stack. """ self.stack.append(elem) def pop(self): """ Remove and returns the top element of the stack. """ if self.stack: return self.stack.pop() else: raise underflow_exception('Stack is empty!!') def top(self): """ Returns the next element of the stack. """ if self.stack: return self.stack[-1] else: return None def is_empty(self): """ Returns True iff stack is empty. """ return len(self.stack) == 0 def make_copy(self): """ Returns a new object which is an exact copy of the current stack """ new_obj = stack() newObj.stack = list(self.stack) return newObj
#!/usr/bin/env python3 def eval_jumps1(jumps): cloned = list(jumps) pc = 0 i = 0 while 0 <= pc < len(cloned): old_pc = cloned[pc] cloned[pc] += 1 pc += old_pc i += 1 return i def eval_jumps2(jumps): cloned = list(jumps) pc = 0 i = 0 while 0 <= pc < len(cloned): old_pc = cloned[pc] if cloned[pc] >= 3: cloned[pc] -= 1 else: cloned[pc] += 1 pc += old_pc i += 1 return i def main(): jumps = [] with open('input.txt') as fh: for line in fh: jumps.append(int(line)) print(eval_jumps1(jumps)) print(eval_jumps2(jumps)) if __name__ == '__main__': main()
def eval_jumps1(jumps): cloned = list(jumps) pc = 0 i = 0 while 0 <= pc < len(cloned): old_pc = cloned[pc] cloned[pc] += 1 pc += old_pc i += 1 return i def eval_jumps2(jumps): cloned = list(jumps) pc = 0 i = 0 while 0 <= pc < len(cloned): old_pc = cloned[pc] if cloned[pc] >= 3: cloned[pc] -= 1 else: cloned[pc] += 1 pc += old_pc i += 1 return i def main(): jumps = [] with open('input.txt') as fh: for line in fh: jumps.append(int(line)) print(eval_jumps1(jumps)) print(eval_jumps2(jumps)) if __name__ == '__main__': main()
class Solution: def solve(self, n, k): ans = [] for i in range(k): ans.append(x := max(1,n-26*(k-i-1))) n -= x return "".join(chr(ord('a')+x-1) for x in ans)
class Solution: def solve(self, n, k): ans = [] for i in range(k): ans.append((x := max(1, n - 26 * (k - i - 1)))) n -= x return ''.join((chr(ord('a') + x - 1) for x in ans))
load("@build_bazel_rules_nodejs//:index.bzl", "pkg_web") load(":tools/ngsw_config.bzl", _ngsw_config = "ngsw_config") def pkg_pwa( name, srcs, index_html, ngsw_config, additional_root_paths = []): pkg_web( name = "%s_web" % name, srcs = srcs + ["@npm//:node_modules/@angular/service-worker/ngsw-worker.js", "@npm//:node_modules/zone.js/dist/zone.min.js"], additional_root_paths = additional_root_paths + ["npm/node_modules/@angular/service-worker"], visibility = ["//visibility:private"], ) _ngsw_config( name = name, src = ":%s_web" % name, config = ngsw_config, index_html = index_html, tags = ["app"], )
load('@build_bazel_rules_nodejs//:index.bzl', 'pkg_web') load(':tools/ngsw_config.bzl', _ngsw_config='ngsw_config') def pkg_pwa(name, srcs, index_html, ngsw_config, additional_root_paths=[]): pkg_web(name='%s_web' % name, srcs=srcs + ['@npm//:node_modules/@angular/service-worker/ngsw-worker.js', '@npm//:node_modules/zone.js/dist/zone.min.js'], additional_root_paths=additional_root_paths + ['npm/node_modules/@angular/service-worker'], visibility=['//visibility:private']) _ngsw_config(name=name, src=':%s_web' % name, config=ngsw_config, index_html=index_html, tags=['app'])
def calculate_amstrong_numbers_3_digits(): result = [] for item in range(100, 1000): sum = 0 for number in str(item): sum += int(number) ** 3 if sum == item: result.append(item) return result print("3-digit Amstrong Numbers:") print(calculate_amstrong_numbers_3_digits())
def calculate_amstrong_numbers_3_digits(): result = [] for item in range(100, 1000): sum = 0 for number in str(item): sum += int(number) ** 3 if sum == item: result.append(item) return result print('3-digit Amstrong Numbers:') print(calculate_amstrong_numbers_3_digits())
def int_to_Roman(num): val = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] syb = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" ] roman_num = '' i = 0 while num > 0: for _ in range(num // val[i]): roman_num += syb[i] num -= val[i] i += 1 return roman_num num = int(input()) if(num>=1 and num<=3999): while(num>=1 and num<=3999): roman = str(int_to_Roman(num)) max=ord(roman[0]) for i in range(len(roman)): if(max<ord(roman[i])): max = ord(roman[i]) base = max - ord('A') + 11 new_num = 0 for i in range(len(roman)): r = roman[len(roman)-i-1] n1 = ord(roman[len(roman)-i-1]) - ord('A') + 10 new_num = new_num + (n1*(base**i)) num = new_num print(num) else: print(num)
def int_to__roman(num): val = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] syb = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'] roman_num = '' i = 0 while num > 0: for _ in range(num // val[i]): roman_num += syb[i] num -= val[i] i += 1 return roman_num num = int(input()) if num >= 1 and num <= 3999: while num >= 1 and num <= 3999: roman = str(int_to__roman(num)) max = ord(roman[0]) for i in range(len(roman)): if max < ord(roman[i]): max = ord(roman[i]) base = max - ord('A') + 11 new_num = 0 for i in range(len(roman)): r = roman[len(roman) - i - 1] n1 = ord(roman[len(roman) - i - 1]) - ord('A') + 10 new_num = new_num + n1 * base ** i num = new_num print(num) else: print(num)
class A: def f(self): return B() a = A() a.f() # NameError: name 'B' is not defined b = B() # NameError: name 'B' is not defined def f(): b = B() f() # NameError: name 'B' is not defined class B: pass
class A: def f(self): return b() a = a() a.f() b = b() def f(): b = b() f() class B: pass
def reverse_list(items): start = 0 end = len(items) - 1 while start < end: items[start], items[end] = items[end], items[start] start += 1 end -= 1 return items if __name__ == '__main__': items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(reverse_list(items))
def reverse_list(items): start = 0 end = len(items) - 1 while start < end: (items[start], items[end]) = (items[end], items[start]) start += 1 end -= 1 return items if __name__ == '__main__': items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(reverse_list(items))
#!/usr/bin/python3 # # MAGIC_SEED = 1956 #PATH TRAIN_PATH = 'train' PREDICT_PATH = 'predict' # Dataset properties CSV_PATH="C:\\Users\\dmitr_000\\.keras\\datasets\\Imbalance_data.csv" # Header names DT_DSET ="Date Time" RCPOWER_DSET= "Imbalance" DISCRET =10 # The time cutoffs for the formation of the validation and test sequence in the format of the parameter passed # to the timedelta() like as 'days=<value>' or 'hours=<value>' or 'minutes=<value>' # TEST_CUT_OFF = 60 # 'hours=1' VAL_CUT_OFF = 360 # 'hours=6' 'days=1' # Log files LOG_FILE_NAME="Imbalance" #training model EPOCHS=10 N_STEPS = 32 N_FEATURES = 1 #LSTM models LSTM_POSSIBLE_TYPES={'LSTM':(0,"Vanilla_LSTM"), 'stacked LSTM':(1,"Stacked_LSTM") ,\ 'Bidirectional LSTM':(2,"B_dir_LSTM"),'CNN LSTM':(3,"CNN_LSTM")} LSTM_TYPE='LSTM' UNITS =32 #CNN models FILTERS = 64 KERNEL_SIZE = 2 POOL_SIZE = 2 FOLDER_PATH_SAVED_CNN_MODEL="ConvNN" #MLP model HIDDEN_NEYRONS = 16 DROPOUT = 0.2 FOLDER_PATH_SAVED_MLP_MODEL="MLP" # Chartin. Matplotlib.pyplot is used for charting STOP_ON_CHART_SHOW=False # simple class for logging class _loging(): pass
magic_seed = 1956 train_path = 'train' predict_path = 'predict' csv_path = 'C:\\Users\\dmitr_000\\.keras\\datasets\\Imbalance_data.csv' dt_dset = 'Date Time' rcpower_dset = 'Imbalance' discret = 10 test_cut_off = 60 val_cut_off = 360 log_file_name = 'Imbalance' epochs = 10 n_steps = 32 n_features = 1 lstm_possible_types = {'LSTM': (0, 'Vanilla_LSTM'), 'stacked LSTM': (1, 'Stacked_LSTM'), 'Bidirectional LSTM': (2, 'B_dir_LSTM'), 'CNN LSTM': (3, 'CNN_LSTM')} lstm_type = 'LSTM' units = 32 filters = 64 kernel_size = 2 pool_size = 2 folder_path_saved_cnn_model = 'ConvNN' hidden_neyrons = 16 dropout = 0.2 folder_path_saved_mlp_model = 'MLP' stop_on_chart_show = False class _Loging: pass
def unsupervised_distr(distr): variables = {k: k + '_u' for k in distr.var + distr.cond_var if k != 'z'} distr_unsupervised = distr.replace_var(**variables) return distr_unsupervised, variables def unsupervised_distr_no_var(distr): variables = {k: k + '_u' for k in distr.var + distr.cond_var if k != 'z'} distr_unsupervised = distr.replace_var(**variables) return distr_unsupervised
def unsupervised_distr(distr): variables = {k: k + '_u' for k in distr.var + distr.cond_var if k != 'z'} distr_unsupervised = distr.replace_var(**variables) return (distr_unsupervised, variables) def unsupervised_distr_no_var(distr): variables = {k: k + '_u' for k in distr.var + distr.cond_var if k != 'z'} distr_unsupervised = distr.replace_var(**variables) return distr_unsupervised
class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: table = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] return len({''.join(table[ord(c) - ord('a')] for c in word) for word in words})
class Solution: def unique_morse_representations(self, words: List[str]) -> int: table = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..'] return len({''.join((table[ord(c) - ord('a')] for c in word)) for word in words})
expected_output = { "list_of_neighbors": ["192.168.197.254"], "vrf": { "default": { "neighbor": { "192.168.197.254": { "address_family": { "ipv4 unicast": { "advertise_bit": 0, "bgp_table_version": 1, "dynamic_slow_peer_recovered": "never", "index": 0, "last_detected_dynamic_slow_peer": "never", "last_received_refresh_end_of_rib": "never", "last_received_refresh_start_of_rib": "never", "last_sent_refresh_end_of_rib": "1w5d", "last_sent_refresh_start_of_rib": "1w5d", "local_policy_denied_prefixes_counters": { "inbound": {"total": 0}, "outbound": {"total": 0}, }, "max_nlri": 0, "min_nlri": 0, "neighbor_version": "1/0", "output_queue_size": 0, "prefix_activity_counters": { "received": { "explicit_withdraw": 0, "implicit_withdraw": 0, "prefixes_current": 0, "prefixes_total": 0, "used_as_bestpath": 0, "used_as_multipath": 0, }, "sent": { "explicit_withdraw": 0, "implicit_withdraw": 0, "prefixes_current": 0, "prefixes_total": 0, "used_as_bestpath": "n/a", "used_as_multipath": "n/a", }, }, "refresh_activity_counters": { "received": { "refresh_end_of_rib": 0, "refresh_start_of_rib": 0, }, "sent": { "refresh_end_of_rib": 1, "refresh_start_of_rib": 1, }, }, "refresh_epoch": 1, "refresh_out": 0, "slow_peer_detection": False, "slow_peer_split_update_group_dynamic": False, }, "l2vpn vpls": { "advertise_bit": 1, "bgp_table_version": 9431, "community_attribute_sent": True, "dynamic_slow_peer_recovered": "never", "extended_community_attribute_sent": True, "index": 38, "last_detected_dynamic_slow_peer": "never", "last_received_refresh_end_of_rib": "02:01:32", "last_received_refresh_start_of_rib": "02:01:36", "last_sent_refresh_end_of_rib": "02:41:38", "last_sent_refresh_start_of_rib": "02:41:38", "local_policy_denied_prefixes_counters": { "inbound": { "bestpath_from_this_peer": "n/a", "total": 0, }, "outbound": { "bestpath_from_this_peer": 402, "total": 402, }, }, "max_nlri": 199, "min_nlri": 0, "neighbor_version": "9431/0", "output_queue_size": 0, "prefix_activity_counters": { "received": { "explicit_withdraw": 0, "implicit_withdraw": 402, "prefixes_total": 603, "used_as_bestpath": 201, "used_as_multipath": 0, }, "sent": { "explicit_withdraw": 307, "implicit_withdraw": 5646, "prefixes_total": 6356, "used_as_bestpath": "n/a", "used_as_multipath": "n/a", }, }, "refresh_activity_counters": { "received": { "refresh_end_of_rib": 2, "refresh_start_of_rib": 2, }, "sent": { "refresh_end_of_rib": 1, "refresh_start_of_rib": 1, }, }, "refresh_epoch": 3, "refresh_in": 4, "refresh_out": 0, "route_reflector_client": True, "slow_peer_detection": False, "slow_peer_split_update_group_dynamic": False, "suppress_ldp_signaling": True, "update_group_member": 38, }, "vpnv4 unicast": { "advertise_bit": 2, "bgp_table_version": 29454374, "dynamic_slow_peer_recovered": "never", "extended_community_attribute_sent": True, "index": 44, "last_detected_dynamic_slow_peer": "never", "last_received_refresh_end_of_rib": "02:01:32", "last_received_refresh_start_of_rib": "02:01:36", "last_sent_refresh_end_of_rib": "02:41:11", "last_sent_refresh_start_of_rib": "02:41:38", "local_policy_denied_prefixes_counters": { "inbound": { "bestpath_from_this_peer": "n/a", "total": 0, }, "outbound": { "bestpath_from_this_peer": 3100, "total": 3100, }, }, "max_nlri": 270, "min_nlri": 0, "neighbor_version": "29454374/0", "output_queue_size": 0, "prefix_activity_counters": { "received": { "explicit_withdraw": 206, "implicit_withdraw": 40708, "prefixes_total": 61115, "used_as_bestpath": 20201, "used_as_multipath": 0, }, "sent": { "explicit_withdraw": 1131817, "implicit_withdraw": 64677991, "prefixes_total": 68207251, "used_as_bestpath": "n/a", "used_as_multipath": "n/a", }, }, "refresh_activity_counters": { "received": { "refresh_end_of_rib": 1, "refresh_start_of_rib": 1, }, "sent": { "refresh_end_of_rib": 1, "refresh_start_of_rib": 1, }, }, "refresh_epoch": 2, "refresh_in": 4, "refresh_out": 27, "route_reflector_client": True, "slow_peer_detection": False, "slow_peer_split_update_group_dynamic": False, "update_group_member": 44, }, }, "bgp_neighbor_session": {"sessions": 1}, "bgp_negotiated_capabilities": { "enhanced_refresh": "advertised and received", "four_octets_asn": "advertised and received", "graceful_restart": "advertised and received", "graceful_restart_af_advertised_by_peer": [ "vpnv4 unicast", "l2vpn vpls", ], "ipv4_unicast": "advertised", "l2vpn_vpls": "advertised and received", "multisession": "advertised", "remote_restart_timer": 120, "route_refresh": "advertised and received(new)", "stateful_switchover": "NO for session 1", "vpnv4_unicast": "advertised and received", }, "bgp_negotiated_keepalive_timers": { "hold_time": 90, "keepalive_interval": 30, "min_holdtime": 0, }, "bgp_neighbor_counters": { "messages": { "in_queue_depth": 0, "out_queue_depth": 0, "received": { "keepalives": 346, "notifications": 0, "opens": 1, "route_refresh": 0, "total": 13183, "updates": 12830, }, "sent": { "keepalives": 347, "notifications": 0, "opens": 1, "route_refresh": 4, "total": 12180, "updates": 11824, }, } }, "bgp_session_transport": { "address_tracking_status": "enabled", "connection": { "dropped": 38, "established": 39, "last_reset": "02:42:06", "reset_reason": "Peer closed the session", }, "gr_restart_time": 120, "gr_stalepath_time": 360, "graceful_restart": "enabled", "min_time_between_advertisement_runs": 0, "rib_route_ip": "192.168.197.254", "sso": False, "tcp_connection": False, "tcp_path_mtu_discovery": "enabled", }, "bgp_version": 4, "link": "internal", "remote_as": 5918, "router_id": "192.168.197.254", "session_state": "Idle", "shutdown": False, } } } }, }
expected_output = {'list_of_neighbors': ['192.168.197.254'], 'vrf': {'default': {'neighbor': {'192.168.197.254': {'address_family': {'ipv4 unicast': {'advertise_bit': 0, 'bgp_table_version': 1, 'dynamic_slow_peer_recovered': 'never', 'index': 0, 'last_detected_dynamic_slow_peer': 'never', 'last_received_refresh_end_of_rib': 'never', 'last_received_refresh_start_of_rib': 'never', 'last_sent_refresh_end_of_rib': '1w5d', 'last_sent_refresh_start_of_rib': '1w5d', 'local_policy_denied_prefixes_counters': {'inbound': {'total': 0}, 'outbound': {'total': 0}}, 'max_nlri': 0, 'min_nlri': 0, 'neighbor_version': '1/0', 'output_queue_size': 0, 'prefix_activity_counters': {'received': {'explicit_withdraw': 0, 'implicit_withdraw': 0, 'prefixes_current': 0, 'prefixes_total': 0, 'used_as_bestpath': 0, 'used_as_multipath': 0}, 'sent': {'explicit_withdraw': 0, 'implicit_withdraw': 0, 'prefixes_current': 0, 'prefixes_total': 0, 'used_as_bestpath': 'n/a', 'used_as_multipath': 'n/a'}}, 'refresh_activity_counters': {'received': {'refresh_end_of_rib': 0, 'refresh_start_of_rib': 0}, 'sent': {'refresh_end_of_rib': 1, 'refresh_start_of_rib': 1}}, 'refresh_epoch': 1, 'refresh_out': 0, 'slow_peer_detection': False, 'slow_peer_split_update_group_dynamic': False}, 'l2vpn vpls': {'advertise_bit': 1, 'bgp_table_version': 9431, 'community_attribute_sent': True, 'dynamic_slow_peer_recovered': 'never', 'extended_community_attribute_sent': True, 'index': 38, 'last_detected_dynamic_slow_peer': 'never', 'last_received_refresh_end_of_rib': '02:01:32', 'last_received_refresh_start_of_rib': '02:01:36', 'last_sent_refresh_end_of_rib': '02:41:38', 'last_sent_refresh_start_of_rib': '02:41:38', 'local_policy_denied_prefixes_counters': {'inbound': {'bestpath_from_this_peer': 'n/a', 'total': 0}, 'outbound': {'bestpath_from_this_peer': 402, 'total': 402}}, 'max_nlri': 199, 'min_nlri': 0, 'neighbor_version': '9431/0', 'output_queue_size': 0, 'prefix_activity_counters': {'received': {'explicit_withdraw': 0, 'implicit_withdraw': 402, 'prefixes_total': 603, 'used_as_bestpath': 201, 'used_as_multipath': 0}, 'sent': {'explicit_withdraw': 307, 'implicit_withdraw': 5646, 'prefixes_total': 6356, 'used_as_bestpath': 'n/a', 'used_as_multipath': 'n/a'}}, 'refresh_activity_counters': {'received': {'refresh_end_of_rib': 2, 'refresh_start_of_rib': 2}, 'sent': {'refresh_end_of_rib': 1, 'refresh_start_of_rib': 1}}, 'refresh_epoch': 3, 'refresh_in': 4, 'refresh_out': 0, 'route_reflector_client': True, 'slow_peer_detection': False, 'slow_peer_split_update_group_dynamic': False, 'suppress_ldp_signaling': True, 'update_group_member': 38}, 'vpnv4 unicast': {'advertise_bit': 2, 'bgp_table_version': 29454374, 'dynamic_slow_peer_recovered': 'never', 'extended_community_attribute_sent': True, 'index': 44, 'last_detected_dynamic_slow_peer': 'never', 'last_received_refresh_end_of_rib': '02:01:32', 'last_received_refresh_start_of_rib': '02:01:36', 'last_sent_refresh_end_of_rib': '02:41:11', 'last_sent_refresh_start_of_rib': '02:41:38', 'local_policy_denied_prefixes_counters': {'inbound': {'bestpath_from_this_peer': 'n/a', 'total': 0}, 'outbound': {'bestpath_from_this_peer': 3100, 'total': 3100}}, 'max_nlri': 270, 'min_nlri': 0, 'neighbor_version': '29454374/0', 'output_queue_size': 0, 'prefix_activity_counters': {'received': {'explicit_withdraw': 206, 'implicit_withdraw': 40708, 'prefixes_total': 61115, 'used_as_bestpath': 20201, 'used_as_multipath': 0}, 'sent': {'explicit_withdraw': 1131817, 'implicit_withdraw': 64677991, 'prefixes_total': 68207251, 'used_as_bestpath': 'n/a', 'used_as_multipath': 'n/a'}}, 'refresh_activity_counters': {'received': {'refresh_end_of_rib': 1, 'refresh_start_of_rib': 1}, 'sent': {'refresh_end_of_rib': 1, 'refresh_start_of_rib': 1}}, 'refresh_epoch': 2, 'refresh_in': 4, 'refresh_out': 27, 'route_reflector_client': True, 'slow_peer_detection': False, 'slow_peer_split_update_group_dynamic': False, 'update_group_member': 44}}, 'bgp_neighbor_session': {'sessions': 1}, 'bgp_negotiated_capabilities': {'enhanced_refresh': 'advertised and received', 'four_octets_asn': 'advertised and received', 'graceful_restart': 'advertised and received', 'graceful_restart_af_advertised_by_peer': ['vpnv4 unicast', 'l2vpn vpls'], 'ipv4_unicast': 'advertised', 'l2vpn_vpls': 'advertised and received', 'multisession': 'advertised', 'remote_restart_timer': 120, 'route_refresh': 'advertised and received(new)', 'stateful_switchover': 'NO for session 1', 'vpnv4_unicast': 'advertised and received'}, 'bgp_negotiated_keepalive_timers': {'hold_time': 90, 'keepalive_interval': 30, 'min_holdtime': 0}, 'bgp_neighbor_counters': {'messages': {'in_queue_depth': 0, 'out_queue_depth': 0, 'received': {'keepalives': 346, 'notifications': 0, 'opens': 1, 'route_refresh': 0, 'total': 13183, 'updates': 12830}, 'sent': {'keepalives': 347, 'notifications': 0, 'opens': 1, 'route_refresh': 4, 'total': 12180, 'updates': 11824}}}, 'bgp_session_transport': {'address_tracking_status': 'enabled', 'connection': {'dropped': 38, 'established': 39, 'last_reset': '02:42:06', 'reset_reason': 'Peer closed the session'}, 'gr_restart_time': 120, 'gr_stalepath_time': 360, 'graceful_restart': 'enabled', 'min_time_between_advertisement_runs': 0, 'rib_route_ip': '192.168.197.254', 'sso': False, 'tcp_connection': False, 'tcp_path_mtu_discovery': 'enabled'}, 'bgp_version': 4, 'link': 'internal', 'remote_as': 5918, 'router_id': '192.168.197.254', 'session_state': 'Idle', 'shutdown': False}}}}}
def check_paranthesis(inp): stack = [] c = 1 for i in inp: if i in ['(','[','{']: stack.append(i) c += 1 else: if len(stack) == 0: return c elif (i == ')' and stack[-1] == '(') or (i == ']' and stack[-1] == '[') or (i == '}' and stack[-1] == '{'): stack.pop() c += 1 else: return c return 0 if __name__ == "__main__": inp = input() print(check_paranthesis(inp)) ''' got a string containing {,},[,],(,). you have to check that the paranthesis are balanced or not. if yes than print 0 else print the index+1 value where error occurs input 1. {([])}[] 2. {{[]}}} output 1. 0 2. 7 '''
def check_paranthesis(inp): stack = [] c = 1 for i in inp: if i in ['(', '[', '{']: stack.append(i) c += 1 elif len(stack) == 0: return c elif i == ')' and stack[-1] == '(' or (i == ']' and stack[-1] == '[') or (i == '}' and stack[-1] == '{'): stack.pop() c += 1 else: return c return 0 if __name__ == '__main__': inp = input() print(check_paranthesis(inp)) ' got a string containing {,},[,],(,). you have to check that the paranthesis are balanced or not.\n if yes than print 0 else print the index+1 value where error occurs\n \ninput\n1. {([])}[]\n2. {{[]}}} \n\noutput\n\n1. 0\n2. 7 '
# Bazel macro that instantiates a native cc_test rule for an S2 test. def s2test(name, deps = [], size = "small"): native.cc_test( name = name, srcs = ["%s.cc" % (name)], copts = [ "-Iexternal/gtest/include", "-DS2_TEST_DEGENERACIES", "-DS2_USE_GFLAGS", "-DS2_USE_GLOG", "-DHASH_NAMESPACE=std", "-Wno-deprecated-declarations", "-Wno-format", "-Wno-non-virtual-dtor", "-Wno-parentheses", "-Wno-sign-compare", "-Wno-strict-aliasing", "-Wno-unused-function", "-Wno-unused-private-field", "-Wno-unused-variable", "-Wno-unused-function", ], deps = [":s2testing"] + deps, size = size, )
def s2test(name, deps=[], size='small'): native.cc_test(name=name, srcs=['%s.cc' % name], copts=['-Iexternal/gtest/include', '-DS2_TEST_DEGENERACIES', '-DS2_USE_GFLAGS', '-DS2_USE_GLOG', '-DHASH_NAMESPACE=std', '-Wno-deprecated-declarations', '-Wno-format', '-Wno-non-virtual-dtor', '-Wno-parentheses', '-Wno-sign-compare', '-Wno-strict-aliasing', '-Wno-unused-function', '-Wno-unused-private-field', '-Wno-unused-variable', '-Wno-unused-function'], deps=[':s2testing'] + deps, size=size)
# # PySNMP MIB module CT-DAWANDEVCONN-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CT-DAWANDEVCONN-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:28:40 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) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint") cabletron, = mibBuilder.importSymbols("CTRON-OIDS", "cabletron") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Gauge32, ModuleIdentity, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Counter32, NotificationType, MibIdentifier, Integer32, iso, Counter64, IpAddress, Unsigned32, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "ModuleIdentity", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Counter32", "NotificationType", "MibIdentifier", "Integer32", "iso", "Counter64", "IpAddress", "Unsigned32", "TimeTicks") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ctSSA = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4497)) daWanDevConn = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4497, 23)) daWanDevConnTable = MibTable((1, 3, 6, 1, 4, 1, 52, 4497, 23, 1), ) if mibBuilder.loadTexts: daWanDevConnTable.setStatus('mandatory') if mibBuilder.loadTexts: daWanDevConnTable.setDescription('A list of Demand Access remote WAN connections') daWanDevConnEntry = MibTableRow((1, 3, 6, 1, 4, 1, 52, 4497, 23, 1, 1), ).setIndexNames((0, "CT-DAWANDEVCONN-MIB", "daWanDeviceIndex"), (0, "CT-DAWANDEVCONN-MIB", "daWanConnectionIndex")) if mibBuilder.loadTexts: daWanDevConnEntry.setStatus('mandatory') if mibBuilder.loadTexts: daWanDevConnEntry.setDescription('An entry containing wan connection information and statistics.') daWanDeviceIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4497, 23, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: daWanDeviceIndex.setStatus('mandatory') if mibBuilder.loadTexts: daWanDeviceIndex.setDescription('This is the index into this table. This index uniquely identifies the connection associated with the device.') daWanConnectionIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4497, 23, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: daWanConnectionIndex.setStatus('mandatory') if mibBuilder.loadTexts: daWanConnectionIndex.setDescription('This is the index into this table. This index uniquely identifies the connection associated with the device.') mibBuilder.exportSymbols("CT-DAWANDEVCONN-MIB", daWanDeviceIndex=daWanDeviceIndex, daWanConnectionIndex=daWanConnectionIndex, daWanDevConnEntry=daWanDevConnEntry, daWanDevConn=daWanDevConn, daWanDevConnTable=daWanDevConnTable, ctSSA=ctSSA)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint') (cabletron,) = mibBuilder.importSymbols('CTRON-OIDS', 'cabletron') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (gauge32, module_identity, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, bits, counter32, notification_type, mib_identifier, integer32, iso, counter64, ip_address, unsigned32, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'ModuleIdentity', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'Counter32', 'NotificationType', 'MibIdentifier', 'Integer32', 'iso', 'Counter64', 'IpAddress', 'Unsigned32', 'TimeTicks') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') ct_ssa = mib_identifier((1, 3, 6, 1, 4, 1, 52, 4497)) da_wan_dev_conn = mib_identifier((1, 3, 6, 1, 4, 1, 52, 4497, 23)) da_wan_dev_conn_table = mib_table((1, 3, 6, 1, 4, 1, 52, 4497, 23, 1)) if mibBuilder.loadTexts: daWanDevConnTable.setStatus('mandatory') if mibBuilder.loadTexts: daWanDevConnTable.setDescription('A list of Demand Access remote WAN connections') da_wan_dev_conn_entry = mib_table_row((1, 3, 6, 1, 4, 1, 52, 4497, 23, 1, 1)).setIndexNames((0, 'CT-DAWANDEVCONN-MIB', 'daWanDeviceIndex'), (0, 'CT-DAWANDEVCONN-MIB', 'daWanConnectionIndex')) if mibBuilder.loadTexts: daWanDevConnEntry.setStatus('mandatory') if mibBuilder.loadTexts: daWanDevConnEntry.setDescription('An entry containing wan connection information and statistics.') da_wan_device_index = mib_table_column((1, 3, 6, 1, 4, 1, 52, 4497, 23, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: daWanDeviceIndex.setStatus('mandatory') if mibBuilder.loadTexts: daWanDeviceIndex.setDescription('This is the index into this table. This index uniquely identifies the connection associated with the device.') da_wan_connection_index = mib_table_column((1, 3, 6, 1, 4, 1, 52, 4497, 23, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: daWanConnectionIndex.setStatus('mandatory') if mibBuilder.loadTexts: daWanConnectionIndex.setDescription('This is the index into this table. This index uniquely identifies the connection associated with the device.') mibBuilder.exportSymbols('CT-DAWANDEVCONN-MIB', daWanDeviceIndex=daWanDeviceIndex, daWanConnectionIndex=daWanConnectionIndex, daWanDevConnEntry=daWanDevConnEntry, daWanDevConn=daWanDevConn, daWanDevConnTable=daWanDevConnTable, ctSSA=ctSSA)
class Node(object): def __init__(self, item): self.item = item self.next = None def get_item(self): return self.item def get_next(self): return self.next def set_item(self, new_item): self.item = new_item def set_next(self, new_next): self.next = new_next class LinkedList(object): def __init__(self): self.head = None def is_empty(self): return self.head == None def add(self, item): temp = Node(item) temp.set_next(self.head) self.head = temp def count_size(self): count = 0 current = self.head while current is not None: count += 1 current = current.get_next() return count def search(self, item): found = False current = self.head while not found and current is not None: if item == current.get_item(): found = True current = current.get_next() return found def remove(self, item): found = False current = self.head previous = None while not found: if item == current.get_item(): found = true else: previous = current current = current.get_next() if previous == None: self.head = current.get_next() else: previous.set_next(current.get_next())
class Node(object): def __init__(self, item): self.item = item self.next = None def get_item(self): return self.item def get_next(self): return self.next def set_item(self, new_item): self.item = new_item def set_next(self, new_next): self.next = new_next class Linkedlist(object): def __init__(self): self.head = None def is_empty(self): return self.head == None def add(self, item): temp = node(item) temp.set_next(self.head) self.head = temp def count_size(self): count = 0 current = self.head while current is not None: count += 1 current = current.get_next() return count def search(self, item): found = False current = self.head while not found and current is not None: if item == current.get_item(): found = True current = current.get_next() return found def remove(self, item): found = False current = self.head previous = None while not found: if item == current.get_item(): found = true else: previous = current current = current.get_next() if previous == None: self.head = current.get_next() else: previous.set_next(current.get_next())
# The major optimization is to do arithmetic in base 10 in the main loop, avoiding division and modulo def compute(): # Initialize n = 1000000000 # The pattern is greater than 10^18, so start searching at 10^9 ndigits = [0] * 10 # In base 10, little-endian temp = n for i in range(len(ndigits)): ndigits[i] = temp % 10 temp //= 10 n2digits = [0] * 19 # Based on length of pattern temp = n * n for i in range(len(n2digits)): n2digits[i] = temp % 10 temp //= 10 # Increment and search while not is_concealed_square(n2digits): # Add 20n + 100 so that n2digits = (n + 10)^2 add_20n(ndigits, n2digits) add_10pow(n2digits, 2) # Since n^2 ends with 0, n must end with 0 n += 10 add_10pow(ndigits, 1) # Now n2digits = n^2 return str(n) def is_concealed_square(n): for i in range(1, 10): # Scan for 1 to 9 if n[20 - i * 2] != i: return False return n[0] == 0 # Special case for 0 def add_10pow(n, i): while n[i] == 9: n[i] = 0 i += 1 n[i] += 1 def add_20n(n, n2): carry = 0 i = 0 while i < len(n): sum = n[i] * 2 + n2[i + 1] + carry n2[i + 1] = sum % 10 carry = sum // 10 i += 1 i += 1 while carry > 0: sum = n2[i] + carry n2[i] = sum % 10 carry = sum // 10 i += 1 if __name__ == "__main__": print(compute())
def compute(): n = 1000000000 ndigits = [0] * 10 temp = n for i in range(len(ndigits)): ndigits[i] = temp % 10 temp //= 10 n2digits = [0] * 19 temp = n * n for i in range(len(n2digits)): n2digits[i] = temp % 10 temp //= 10 while not is_concealed_square(n2digits): add_20n(ndigits, n2digits) add_10pow(n2digits, 2) n += 10 add_10pow(ndigits, 1) return str(n) def is_concealed_square(n): for i in range(1, 10): if n[20 - i * 2] != i: return False return n[0] == 0 def add_10pow(n, i): while n[i] == 9: n[i] = 0 i += 1 n[i] += 1 def add_20n(n, n2): carry = 0 i = 0 while i < len(n): sum = n[i] * 2 + n2[i + 1] + carry n2[i + 1] = sum % 10 carry = sum // 10 i += 1 i += 1 while carry > 0: sum = n2[i] + carry n2[i] = sum % 10 carry = sum // 10 i += 1 if __name__ == '__main__': print(compute())
def parse_string_time(input_time: str) -> float: total_amount = 0 times = _slice_input_times(input_time) for _amount, duration_type in times: amount = _to_float(_amount) multiplier = _parse_multiplier(duration_type) total_amount += amount * multiplier return total_amount def _parse_multiplier(duration_type): multiplier = 0 if 'ms' == duration_type: multiplier = .001 elif 'sec' == duration_type: multiplier = 1 elif 'min' == duration_type: multiplier = 60 elif 'hr' == duration_type: multiplier = 60 return multiplier def _slice_input_times(input_time: str) -> iter: input_time_chunks = iter(input_time.split(' ')) input_time_tuples = zip(input_time_chunks, input_time_chunks) return input_time_tuples def _to_float(amount: str) -> float: try: amount = float(amount) except: amount = 0.0 return amount
def parse_string_time(input_time: str) -> float: total_amount = 0 times = _slice_input_times(input_time) for (_amount, duration_type) in times: amount = _to_float(_amount) multiplier = _parse_multiplier(duration_type) total_amount += amount * multiplier return total_amount def _parse_multiplier(duration_type): multiplier = 0 if 'ms' == duration_type: multiplier = 0.001 elif 'sec' == duration_type: multiplier = 1 elif 'min' == duration_type: multiplier = 60 elif 'hr' == duration_type: multiplier = 60 return multiplier def _slice_input_times(input_time: str) -> iter: input_time_chunks = iter(input_time.split(' ')) input_time_tuples = zip(input_time_chunks, input_time_chunks) return input_time_tuples def _to_float(amount: str) -> float: try: amount = float(amount) except: amount = 0.0 return amount
HITBOX_OCTANE = 0 HITBOX_DOMINUS = 1 HITBOX_PLANK = 2 HITBOX_BREAKOUT = 3 HITBOX_HYBRID = 4 HITBOX_BATMOBILE = 5
hitbox_octane = 0 hitbox_dominus = 1 hitbox_plank = 2 hitbox_breakout = 3 hitbox_hybrid = 4 hitbox_batmobile = 5
N, M = map(int, input().split()) A = list(map(int, input().split())) threshold = sum(A) / (4 * M) if len([a for a in A if a >= threshold]) >= M: print('Yes') else: print('No')
(n, m) = map(int, input().split()) a = list(map(int, input().split())) threshold = sum(A) / (4 * M) if len([a for a in A if a >= threshold]) >= M: print('Yes') else: print('No')
class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: # exception if len(strs) == 0: return "" # sort first! strs.sort() # strategy # compare first and last string in sorted strings! # pick first element in strs pick = strs[0] prefix = '' for i in range (len(pick)): if strs[len(strs)-1][i] == pick[i]: prefix += strs[len(strs)-1][i] else: break return prefix
class Solution: def longest_common_prefix(self, strs: List[str]) -> str: if len(strs) == 0: return '' strs.sort() pick = strs[0] prefix = '' for i in range(len(pick)): if strs[len(strs) - 1][i] == pick[i]: prefix += strs[len(strs) - 1][i] else: break return prefix
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class BST: def __init__(self): self.root = None def _add(self, node, data): if data <= node.data: if node.left: self._add(node.left, data) else: node.left = Node(data) else: if node.right: self._add(node.right, data) else: node.right = Node(data) def add(self, data): if self.root: self._add(self.root, data) else: self.root = Node(data) def same_tree(self, t1, t2): if not t1 and not t2: return True if not t1 or not t2: return False if t1.data != t2.data: return False return self.same_tree(t1.left, t2.left) and self.same_tree(t1.right, t2.right) def main(): B1 = BST() nodes = [8, 3, 10, 1, 6, 4, 7, 13, 14] for n in nodes: B1.add(n) B2 = BST() nodes = [8, 3, 10, 1, 6, 4, 7, 13, 14] for n in nodes: B2.add(n) print(B1.same_tree(B1.root, B2.root)) if __name__ == '__main__': main()
class Node: def __init__(self, data): self.data = data self.left = None self.right = None class Bst: def __init__(self): self.root = None def _add(self, node, data): if data <= node.data: if node.left: self._add(node.left, data) else: node.left = node(data) elif node.right: self._add(node.right, data) else: node.right = node(data) def add(self, data): if self.root: self._add(self.root, data) else: self.root = node(data) def same_tree(self, t1, t2): if not t1 and (not t2): return True if not t1 or not t2: return False if t1.data != t2.data: return False return self.same_tree(t1.left, t2.left) and self.same_tree(t1.right, t2.right) def main(): b1 = bst() nodes = [8, 3, 10, 1, 6, 4, 7, 13, 14] for n in nodes: B1.add(n) b2 = bst() nodes = [8, 3, 10, 1, 6, 4, 7, 13, 14] for n in nodes: B2.add(n) print(B1.same_tree(B1.root, B2.root)) if __name__ == '__main__': main()
class SymbolMapper(object): def __init__(self): self.symbolmap = {0: '0', 1: '+', -1: '-'} @staticmethod def normalize(value): return 0 if value == 0 else value / abs(value) def inputs2symbols(self, inputs): return map( lambda value: self.symbolmap[SymbolMapper.normalize(value)], inputs)
class Symbolmapper(object): def __init__(self): self.symbolmap = {0: '0', 1: '+', -1: '-'} @staticmethod def normalize(value): return 0 if value == 0 else value / abs(value) def inputs2symbols(self, inputs): return map(lambda value: self.symbolmap[SymbolMapper.normalize(value)], inputs)
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # (c)2021 .direwolf <kururinmiracle@outlook.com> # Licensed under the MIT License. class AffNoteTypeError(Exception): pass class AffNoteIndexError(Exception): pass class AffNoteValueError(Exception): pass class AffSceneTypeError(Exception): pass class AffReadError(Exception): pass
class Affnotetypeerror(Exception): pass class Affnoteindexerror(Exception): pass class Affnotevalueerror(Exception): pass class Affscenetypeerror(Exception): pass class Affreaderror(Exception): pass
# Ignore file list ignore_filelist = [ 'teslagun.activeitem', 'teslagun2.activeitem', ] ignore_filelist_patch = [ ]
ignore_filelist = ['teslagun.activeitem', 'teslagun2.activeitem'] ignore_filelist_patch = []
# funcao como parametro de funcao # so imprime se o numero estiver correto def imprime_com_condicao(num, fcond): if fcond(num): print(num) def par(x): return x % 2 == 0 def impar(x): return not par(x) # Programa Principal # neste caso nao imprimira imprime_com_condicao(5, par)
def imprime_com_condicao(num, fcond): if fcond(num): print(num) def par(x): return x % 2 == 0 def impar(x): return not par(x) imprime_com_condicao(5, par)
n = int(input().strip()) a = list(map(int, input().strip().split(' '))) swaps = 0 for i in range(n): temp=0 for j in range(n-1): if a[j] > a[j+1]: temp = a[j] a[j] = a[j+1] a[j+1] = temp swaps+=1 if swaps==0: print("Array is sorted in", swaps, "swaps.") print("First Element:", a[0]) print("Last Element:", a[-1]) else: print("Array is sorted in", swaps, "swaps.") print("First Element:", a[0]) print("Last Element:", a[-1])
n = int(input().strip()) a = list(map(int, input().strip().split(' '))) swaps = 0 for i in range(n): temp = 0 for j in range(n - 1): if a[j] > a[j + 1]: temp = a[j] a[j] = a[j + 1] a[j + 1] = temp swaps += 1 if swaps == 0: print('Array is sorted in', swaps, 'swaps.') print('First Element:', a[0]) print('Last Element:', a[-1]) else: print('Array is sorted in', swaps, 'swaps.') print('First Element:', a[0]) print('Last Element:', a[-1])
t = int(input()) for i in range(t): r = int(input()) length = r*5 width = length*0.6 left = -1*length*0.45 right = length*0.55 w = width/2 # print coordinates print('Case '+str(i+1)+':') # upper left print("%.0f %.0f" % (left, w)) # upper right print("%.0f %.0f" % (right, w)) # lower right print("%.0f %.0f" % (right, -1*w)) # lower left print("%.0f %.0f" % (left, -1*w))
t = int(input()) for i in range(t): r = int(input()) length = r * 5 width = length * 0.6 left = -1 * length * 0.45 right = length * 0.55 w = width / 2 print('Case ' + str(i + 1) + ':') print('%.0f %.0f' % (left, w)) print('%.0f %.0f' % (right, w)) print('%.0f %.0f' % (right, -1 * w)) print('%.0f %.0f' % (left, -1 * w))
myString = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." inTab = "yzabcdefghijklmnopqrstuvwx" outTab = "abcdefghijklmnopqrstuvwxyz" transTab = str.maketrans(inTab, outTab) outString = myString.translate(transTab) print(outString) urlStr = "map" outUrl = urlStr.translate(transTab) print(outUrl)
my_string = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." in_tab = 'yzabcdefghijklmnopqrstuvwx' out_tab = 'abcdefghijklmnopqrstuvwxyz' trans_tab = str.maketrans(inTab, outTab) out_string = myString.translate(transTab) print(outString) url_str = 'map' out_url = urlStr.translate(transTab) print(outUrl)
def sortByHeight(a): heights = [] # Store all the heights in a list for i in range(len(a)): if a[i] != -1: heights.append(a[i]) # Sort the heights heights = sorted(heights) # Replace the heights in the original list j = 0 for i in range(len(a)): if a[i] != -1: a[i] = heights[j] j += 1 return a
def sort_by_height(a): heights = [] for i in range(len(a)): if a[i] != -1: heights.append(a[i]) heights = sorted(heights) j = 0 for i in range(len(a)): if a[i] != -1: a[i] = heights[j] j += 1 return a
class Solution: def reverseWords(self, set): return ' '.join(set.split()[::-1]) if __name__ == "__main__": solution = Solution() print(solution.reverseWords("the sky is blue")) print(solution.reverseWords(" hello world! "))
class Solution: def reverse_words(self, set): return ' '.join(set.split()[::-1]) if __name__ == '__main__': solution = solution() print(solution.reverseWords('the sky is blue')) print(solution.reverseWords(' hello world! '))
class SleuthError(Exception): pass class SleuthNotFoundError(SleuthError): pass
class Sleutherror(Exception): pass class Sleuthnotfounderror(SleuthError): pass
def insertion_sort(nums: list[float]) -> list[float]: for start in range(1, len(nums)): index = start while nums[index] < nums[index - 1] and index > 0: nums[index], nums[index - 1] = nums[index - 1], nums[index] index -= 1 return nums
def insertion_sort(nums: list[float]) -> list[float]: for start in range(1, len(nums)): index = start while nums[index] < nums[index - 1] and index > 0: (nums[index], nums[index - 1]) = (nums[index - 1], nums[index]) index -= 1 return nums
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. bing_edge = { 'color': { 'color': '#228372' }, 'title': 'Bing-related Parsing Functions', 'label': 'B' } def run(unfurl, node): if node.data_type == 'url.query.pair': if 'bing' in unfurl.find_preceding_domain(node): if node.key == 'pq': unfurl.add_to_queue( data_type='descriptor', key=None, value=f'"Previous" Search Query: {node.value}', hover='Previous terms entered by the user; auto-complete or suggestions <br>' 'may have been used to reach the actual search terms (in <b>q</b>)', parent_id=node.node_id, incoming_edge_config=bing_edge) elif node.key == 'q': unfurl.add_to_queue( data_type='descriptor', key=None, value=f'Search Query: {node.value}', hover='Terms used in the Bing search', parent_id=node.node_id, incoming_edge_config=bing_edge) elif node.key == 'first': unfurl.add_to_queue( data_type='descriptor', key=None, value=f'Starting Result: {node.value}', hover='Bing search by default shows 8 results per page; higher <br>' '"first" values may indicate browsing more subsequent results pages.', parent_id=node.node_id, incoming_edge_config=bing_edge)
bing_edge = {'color': {'color': '#228372'}, 'title': 'Bing-related Parsing Functions', 'label': 'B'} def run(unfurl, node): if node.data_type == 'url.query.pair': if 'bing' in unfurl.find_preceding_domain(node): if node.key == 'pq': unfurl.add_to_queue(data_type='descriptor', key=None, value=f'"Previous" Search Query: {node.value}', hover='Previous terms entered by the user; auto-complete or suggestions <br>may have been used to reach the actual search terms (in <b>q</b>)', parent_id=node.node_id, incoming_edge_config=bing_edge) elif node.key == 'q': unfurl.add_to_queue(data_type='descriptor', key=None, value=f'Search Query: {node.value}', hover='Terms used in the Bing search', parent_id=node.node_id, incoming_edge_config=bing_edge) elif node.key == 'first': unfurl.add_to_queue(data_type='descriptor', key=None, value=f'Starting Result: {node.value}', hover='Bing search by default shows 8 results per page; higher <br>"first" values may indicate browsing more subsequent results pages.', parent_id=node.node_id, incoming_edge_config=bing_edge)
class Term(str): @property def is_variable(self): return self[0] == "?" @property def is_constant(self): return self[0] != "?" @property def arity(self): return 0 class ListTerm(tuple): def __init__(self, *args): self.is_function = None tuple.__init__(self, *args) def function(self): ' must *only* be one level deep ' if self.is_function is None: self.is_function = True for term in self: if not isinstance(term, Term): self.is_function = False break return self.is_function @property def is_constant(self): ' all elements are constant (recursive definition) ' for term in self: if not term.is_constant: return False return True @property def arity(self): return len(self) def __str__(self): return "(%s)" % " ".join(str(x) for x in self) __repr__ = __str__ ############################################################################### def is_function(term): if isinstance(term, ListTerm): return term.function() return False ############################################################################### def tokenize(s): return s.replace('(', ' ( ').replace(')', ' ) ').split() class SymbolFactory(object): def __init__(self): self.symbol_pool = dict() def create(self, clz, *args): # make args hashable new_args = [] for arg in args: if isinstance(arg, list): arg = tuple(arg) new_args.append(arg) args = tuple(new_args) # symbol[clz] -> clz_pool[args] -> instance try: clz_pool = self.symbol_pool[clz] except KeyError: clz_pool = self.symbol_pool[clz] = {} try: instance = clz_pool[args] except KeyError: instance = clz_pool[args] = clz(*args) return instance def to_symbols(self, s): stack = [] current_list = [] # strip comment lines lines = [] for line in s.splitlines(): line = line.strip() useful = line.split(";") line = useful[0].strip() if line: lines.append(line) s = " ".join(lines) for token in tokenize(s): if token == '(': stack.append(current_list) current_list = [] elif token == ')': list_term = self.create(ListTerm, current_list) current_list = stack.pop() current_list.append(list_term) else: current_list.append(self.create(Term, token)) for sexpr in current_list: assert isinstance(sexpr, (Term, ListTerm)) yield sexpr def symbolize(self, string): ' takes a single symbol as a string and internalises ' line = list(self.to_symbols(string)) assert len(line) == 1 return line[0]
class Term(str): @property def is_variable(self): return self[0] == '?' @property def is_constant(self): return self[0] != '?' @property def arity(self): return 0 class Listterm(tuple): def __init__(self, *args): self.is_function = None tuple.__init__(self, *args) def function(self): """ must *only* be one level deep """ if self.is_function is None: self.is_function = True for term in self: if not isinstance(term, Term): self.is_function = False break return self.is_function @property def is_constant(self): """ all elements are constant (recursive definition) """ for term in self: if not term.is_constant: return False return True @property def arity(self): return len(self) def __str__(self): return '(%s)' % ' '.join((str(x) for x in self)) __repr__ = __str__ def is_function(term): if isinstance(term, ListTerm): return term.function() return False def tokenize(s): return s.replace('(', ' ( ').replace(')', ' ) ').split() class Symbolfactory(object): def __init__(self): self.symbol_pool = dict() def create(self, clz, *args): new_args = [] for arg in args: if isinstance(arg, list): arg = tuple(arg) new_args.append(arg) args = tuple(new_args) try: clz_pool = self.symbol_pool[clz] except KeyError: clz_pool = self.symbol_pool[clz] = {} try: instance = clz_pool[args] except KeyError: instance = clz_pool[args] = clz(*args) return instance def to_symbols(self, s): stack = [] current_list = [] lines = [] for line in s.splitlines(): line = line.strip() useful = line.split(';') line = useful[0].strip() if line: lines.append(line) s = ' '.join(lines) for token in tokenize(s): if token == '(': stack.append(current_list) current_list = [] elif token == ')': list_term = self.create(ListTerm, current_list) current_list = stack.pop() current_list.append(list_term) else: current_list.append(self.create(Term, token)) for sexpr in current_list: assert isinstance(sexpr, (Term, ListTerm)) yield sexpr def symbolize(self, string): """ takes a single symbol as a string and internalises """ line = list(self.to_symbols(string)) assert len(line) == 1 return line[0]
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( a , b , k ) : c1 = ( b - a ) - 1 c2 = ( k - b ) + ( a - 1 ) if ( c1 == c2 ) : return 0 return min ( c1 , c2 ) #TOFILL if __name__ == '__main__': param = [ (83,98,86,), (3,39,87,), (11,96,30,), (50,67,48,), (40,16,32,), (62,86,76,), (40,78,71,), (66,11,74,), (6,9,19,), (25,5,5,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
def f_gold(a, b, k): c1 = b - a - 1 c2 = k - b + (a - 1) if c1 == c2: return 0 return min(c1, c2) if __name__ == '__main__': param = [(83, 98, 86), (3, 39, 87), (11, 96, 30), (50, 67, 48), (40, 16, 32), (62, 86, 76), (40, 78, 71), (66, 11, 74), (6, 9, 19), (25, 5, 5)] n_success = 0 for (i, parameters_set) in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print('#Results: %i, %i' % (n_success, len(param)))
def get_locale_name(something, lang): if type(something) == str: pass if type(something) == list: pass if type(something) == dict: pass
def get_locale_name(something, lang): if type(something) == str: pass if type(something) == list: pass if type(something) == dict: pass
phoneNumber = {} x = int(input()) for i in range(x): name, number = input().split() phoneNumber[name] = number for i in range(x): query_name = input() if query_name in phoneNumber.keys(): print(query_name + "=" + phoneNumber[query_name]) else: print("Not found")
phone_number = {} x = int(input()) for i in range(x): (name, number) = input().split() phoneNumber[name] = number for i in range(x): query_name = input() if query_name in phoneNumber.keys(): print(query_name + '=' + phoneNumber[query_name]) else: print('Not found')
AVAILABLE = [ { 'account_name': 'ExampleTwitterMarkovBot', # derived from https://twitter.com/ExampleTwitterMarkovBot 'corpora': ('example_corpus1', 'example_corpus2'), 'description': 'An example configuration for a bot instance', 'twitter_key': '', # twitter app API key 'twitter_secret': '' # twitter app API secret } ]
available = [{'account_name': 'ExampleTwitterMarkovBot', 'corpora': ('example_corpus1', 'example_corpus2'), 'description': 'An example configuration for a bot instance', 'twitter_key': '', 'twitter_secret': ''}]
if __name__ == "__main__": with open("input.txt", "r") as f: input_list = f.readlines() x = 0 y = 0 for input in input_list: command, string_val = input.split(" ") val = int(string_val) if command == "forward": x += val elif command == "down": y += val elif command == "up": y -= val else: raise ValueError(f"{command} is not a valid command") print(x * y)
if __name__ == '__main__': with open('input.txt', 'r') as f: input_list = f.readlines() x = 0 y = 0 for input in input_list: (command, string_val) = input.split(' ') val = int(string_val) if command == 'forward': x += val elif command == 'down': y += val elif command == 'up': y -= val else: raise value_error(f'{command} is not a valid command') print(x * y)
class TransactionError(Exception): pass class TransactionTimeoutError(Exception): pass class TransactionFinished(Exception): pass
class Transactionerror(Exception): pass class Transactiontimeouterror(Exception): pass class Transactionfinished(Exception): pass
class AdvancedArithmetic(object): def divisorSum(n): raise NotImplementedError class Calculator(AdvancedArithmetic): def divisorSum(self, n): divisor_sum = 0 for divisor in range(2, n): if n % divisor == 0: divisor_sum += divisor return divisor_sum + n + (0 if n is 1 else 1)
class Advancedarithmetic(object): def divisor_sum(n): raise NotImplementedError class Calculator(AdvancedArithmetic): def divisor_sum(self, n): divisor_sum = 0 for divisor in range(2, n): if n % divisor == 0: divisor_sum += divisor return divisor_sum + n + (0 if n is 1 else 1)
def gcd(a: int, b: int) -> int: # supposed a >= b if b > a: return gcd(b, a) elif a % b == 0: return b return gcd(b, a % b)
def gcd(a: int, b: int) -> int: if b > a: return gcd(b, a) elif a % b == 0: return b return gcd(b, a % b)
def data_loader(f_name, l_name): with open(f_name, mode='r', encoding='utf-8') as f: data = list(set(f.readlines())) label = [l_name for i in range(len(data))] return data, label
def data_loader(f_name, l_name): with open(f_name, mode='r', encoding='utf-8') as f: data = list(set(f.readlines())) label = [l_name for i in range(len(data))] return (data, label)
def in_order_traversal(node, visit_func): if node is not None: in_order_traversal(node.left, visit_func) visit_func(node.data) in_order_traversal(node.right, visit_func) def pre_order_traversal(node, visit_func): if node is not None: visit_func(node.data) pre_order_traversal(node.left, visit_func) pre_order_traversal(node.right, visit_func) def post_order_traversal(node, visit_func): if node is not None: post_order_traversal(node.left, visit_func) post_order_traversal(node.right, visit_func) visit_func(node.data)
def in_order_traversal(node, visit_func): if node is not None: in_order_traversal(node.left, visit_func) visit_func(node.data) in_order_traversal(node.right, visit_func) def pre_order_traversal(node, visit_func): if node is not None: visit_func(node.data) pre_order_traversal(node.left, visit_func) pre_order_traversal(node.right, visit_func) def post_order_traversal(node, visit_func): if node is not None: post_order_traversal(node.left, visit_func) post_order_traversal(node.right, visit_func) visit_func(node.data)
''' Desenvolva um algoritmo que solicite seu ano de nacimento e o ano anoAtual Calcule a idade e apresente na tela. Para fins de simplificacao, despreze o dia e mes do ano. Apos o calculo verifique se a idade e maior ou igual a 18 anos e apresente na tela a mensagen informando que ja e possivel tirar a carteira de motorista caso seja de maior. ''' nasc = int(input("Digite seu ano de nacimento: \n")) anoAtual = int(input('Digite o ano atual: \n')) r = anoAtual - nasc print('Voce tem {} anos de idade'.format(r)) if(r >= 18): print("Ual vc ja pode tirar sua carteira com {} anos ".format(r))
""" Desenvolva um algoritmo que solicite seu ano de nacimento e o ano anoAtual Calcule a idade e apresente na tela. Para fins de simplificacao, despreze o dia e mes do ano. Apos o calculo verifique se a idade e maior ou igual a 18 anos e apresente na tela a mensagen informando que ja e possivel tirar a carteira de motorista caso seja de maior. """ nasc = int(input('Digite seu ano de nacimento: \n')) ano_atual = int(input('Digite o ano atual: \n')) r = anoAtual - nasc print('Voce tem {} anos de idade'.format(r)) if r >= 18: print('Ual vc ja pode tirar sua carteira com {} anos '.format(r))
class Feature: def __init__(self, name, selector, data_type, number_of_values, patterns): self.name = name self.selector = selector self.pattern = patterns[data_type] self.multiple_values = number_of_values != 'single'
class Feature: def __init__(self, name, selector, data_type, number_of_values, patterns): self.name = name self.selector = selector self.pattern = patterns[data_type] self.multiple_values = number_of_values != 'single'
def get_multiples(num=1,c=10): # if n > 0: (what about negative multiples?) a = 0 num2 = num while a < c: if num2%num == 0: yield num2 num2 += 1 a += 1 else: num2 += 1 multiples_two = get_multiples(2,3) for i in multiples_two: print(i) default_multiples = get_multiples() multiples_5 = get_multiples(5,6) l = [] for i in range(6): l.append(next(multiples_5)) print(l) # OR for i in range(11): # this results in a StopIteration (as by default c=10) print(next(default_multiples))
def get_multiples(num=1, c=10): a = 0 num2 = num while a < c: if num2 % num == 0: yield num2 num2 += 1 a += 1 else: num2 += 1 multiples_two = get_multiples(2, 3) for i in multiples_two: print(i) default_multiples = get_multiples() multiples_5 = get_multiples(5, 6) l = [] for i in range(6): l.append(next(multiples_5)) print(l) for i in range(11): print(next(default_multiples))
# Copyright 2010-2011, RTLCores. All rights reserved. # http://rtlcores.com # See LICENSE.txt class CmdArgs(list): def __init__(self, value=[], cmd=None): list.__init__(self, value) self.cmd = cmd def conv(self): if(self.cmd == None): return self else: return self.cmd(self)
class Cmdargs(list): def __init__(self, value=[], cmd=None): list.__init__(self, value) self.cmd = cmd def conv(self): if self.cmd == None: return self else: return self.cmd(self)
def main() -> None: n, m = map(int, input().split()) g = [[] for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) u -= 1 v -= 1 g[u].append(v) g[v].append(u) INF = 1 << 60 min_length = [INF] * (1 << n) remain = 1 << n min_length[0] = 0 remain -= 1 # bfs added_to_que = [[False] * n for _ in range(1 << n)] for i in range(n): added_to_que[1 << i][i] = True current_length = 1 que = [(1 << i, i) for i in range(n)] while remain: new_que = [] for s, i in que: if min_length[s] == INF: min_length[s] = current_length remain -= 1 for j in g[i]: t = s ^ (1 << j) if added_to_que[t][j]: continue added_to_que[t][j] = True new_que.append((t, j)) current_length += 1 que = new_que print(sum(min_length)) if __name__ == "__main__": main()
def main() -> None: (n, m) = map(int, input().split()) g = [[] for _ in range(n)] for _ in range(m): (u, v) = map(int, input().split()) u -= 1 v -= 1 g[u].append(v) g[v].append(u) inf = 1 << 60 min_length = [INF] * (1 << n) remain = 1 << n min_length[0] = 0 remain -= 1 added_to_que = [[False] * n for _ in range(1 << n)] for i in range(n): added_to_que[1 << i][i] = True current_length = 1 que = [(1 << i, i) for i in range(n)] while remain: new_que = [] for (s, i) in que: if min_length[s] == INF: min_length[s] = current_length remain -= 1 for j in g[i]: t = s ^ 1 << j if added_to_que[t][j]: continue added_to_que[t][j] = True new_que.append((t, j)) current_length += 1 que = new_que print(sum(min_length)) if __name__ == '__main__': main()
# import libraries and modules # provide a class storing the configuration of the back-end engine class LXMconfig: # constructor of the class def __init__(self): self.idb_c1 = None self.idb_c2 = None self.idb_c3 = None self.lxm_conf = {} self.program_name = "lx_allocator" self.lxm_conf["header_request_id"] = 0 self.lxm_conf["header_forwarded_for"] = 1 self.lxm_conf["service_ip"] = "0.0.0.0" self.lxm_conf["service_port"] = 9000 self.lxm_conf["influx_server"] = "0.0.0.0" self.lxm_conf["influx_port"] = 8086 self.lxm_conf["debug"] = 1 self.lxm_conf["hard_exit"] = True self.lxm_conf["hard_startup"] = True self.lxm_conf["lxm_db1"] = "lxm_ddi_performance" self.lxm_conf["lxm_db2"] = "lxm_allocation" self.lxm_conf["lxm_db3"] = "lxm_maintenance" self.lxm_conf["cleanup_maintenance"] = 1 self.lxm_conf["backend_URL"] = None self.lxm_conf["keycloak_URL"] = None self.lxm_conf["KC_REALM"] = None self.lxm_conf["KC_CLID"] = None self.lxm_conf["KC_SECRET"] = None self.lxm_conf["heappe_middleware_available"] = 0 self.lxm_conf["openstack_available"] = 0 self.lxm_conf["hpc_centers"] = None self.lxm_conf["heappe_service_URLs"] = None self.lxm_conf["transfer_sizes"] = "" self.lxm_conf["transfer_speeds"] = "" # define configuration routines def getConfiguration(self, conf_path): config = conf_path conf = open(config, "r") go = True while go: line = conf.readline() if line == "": go = False else: # the character '#' is used to put a line comment in the # configuration file if (line[0] == "#") or (line[0] == "\n") or (line[0] == "\t"): continue fields = line.split("=") param = str(fields[0]) value = str(fields[1]) param = param.strip("\n ") value = value.strip("\n ") # parse the file and create the configuration dictionary if param == "influx_server": self.lxm_conf["influx_server"] = value elif param == "influx_port": self.lxm_conf["influx_port"] = int(value) elif param == "debug": self.lxm_conf["debug"] = int(value) elif param == "service_ip": self.lxm_conf["service_ip"] = value elif param == "service_port": self.lxm_conf["service_port"] = int(value) elif param == "influx_db1": self.lxm_conf["lxm_db1"] = value elif param == "influx_db2": self.lxm_conf["lxm_db2"] = value elif param == "influx_db3": self.lxm_conf["lxm_db3"] = value elif param == "cleanup_maintenance": self.lxm_conf["cleanup_maintenance"] = int(value) elif param == "header_request_id": self.lxm_conf["header_request_id"] = int(value) elif param == "header_forwarded_for": self.lxm_conf["header_forwarded_for"] = int(value) elif param == "hard_exit": if int(value) == 1: self.lxm_conf["hard_exit"] = True else: self.lxm_conf["hard_exit"] = False elif param == "hard_startup": if int(value) == 1: self.lxm_conf["hard_startup"] = True else: self.lxm_conf["hard_startup"] = False elif param == "hpc_centers": self.lxm_conf["hpc_centers"] = value elif param == "transfer_sizes": self.lxm_conf["transfer_sizes"] = value elif param == "transfer_speeds": self.lxm_conf["transfer_speeds"] = value elif param == "heappe_middleware_available": self.lxm_conf["heappe_middleware_available"] = int(value) elif ( param == "heappe_service_URLs" and self.lxm_conf["heappe_middleware_available"] == 1 ): self.lxm_conf["heappe_service_URLs"] = value elif param == "openstack_available": self.lxm_conf["openstack_available"] = int(value) elif param == "backend_URL": self.lxm_conf["backend_URL"] = value elif param == "keycloak_URL": self.lxm_conf["keycloak_URL"] = value elif param == "KC_REALM": self.lxm_conf["KC_REALM"] = value elif param == "KC_CLID": self.lxm_conf["KC_CLID"] = value elif param == "KC_SECRET": self.lxm_conf["KC_SECRET"] = value else: print(" error - unrecognized option (%s)" % (param)) conf.close() return 0 # print out the current configuration def postConfiguration(self): if self.lxm_conf["debug"] == 1: print(" --------------------------------------------------------") print(" Backend Service Configuration:") print(" --------------------------------------------------------") if self.lxm_conf["hard_exit"]: print(" hard-exit mode : True") else: print(" hard-exit mode : False") if self.lxm_conf["hard_startup"]: print(" hard-startup mode : True") else: print(" hard-startup mode : False") print(" debug mode : %d" % (self.lxm_conf["debug"])) print(" service address : %s " % (self.lxm_conf["service_ip"])) print(" service port : %-5d " % (self.lxm_conf["service_port"])) print(" influxDB address : %s " % (self.lxm_conf["influx_server"])) print(" influxDB port : %-5d " % (self.lxm_conf["influx_port"])) print(" db_client_1 : %s " % (self.lxm_conf["lxm_db1"])) print(" db_client_2 : %s " % (self.lxm_conf["lxm_db2"])) print(" db_client_3 : %s " % (self.lxm_conf["lxm_db3"])) print(" --------------------------------------------------------") # executing some action before serving the routes (initialization) if self.lxm_conf["debug"] == 1: print(" (dbg) the webapp is more verbose to support debugging") return 0
class Lxmconfig: def __init__(self): self.idb_c1 = None self.idb_c2 = None self.idb_c3 = None self.lxm_conf = {} self.program_name = 'lx_allocator' self.lxm_conf['header_request_id'] = 0 self.lxm_conf['header_forwarded_for'] = 1 self.lxm_conf['service_ip'] = '0.0.0.0' self.lxm_conf['service_port'] = 9000 self.lxm_conf['influx_server'] = '0.0.0.0' self.lxm_conf['influx_port'] = 8086 self.lxm_conf['debug'] = 1 self.lxm_conf['hard_exit'] = True self.lxm_conf['hard_startup'] = True self.lxm_conf['lxm_db1'] = 'lxm_ddi_performance' self.lxm_conf['lxm_db2'] = 'lxm_allocation' self.lxm_conf['lxm_db3'] = 'lxm_maintenance' self.lxm_conf['cleanup_maintenance'] = 1 self.lxm_conf['backend_URL'] = None self.lxm_conf['keycloak_URL'] = None self.lxm_conf['KC_REALM'] = None self.lxm_conf['KC_CLID'] = None self.lxm_conf['KC_SECRET'] = None self.lxm_conf['heappe_middleware_available'] = 0 self.lxm_conf['openstack_available'] = 0 self.lxm_conf['hpc_centers'] = None self.lxm_conf['heappe_service_URLs'] = None self.lxm_conf['transfer_sizes'] = '' self.lxm_conf['transfer_speeds'] = '' def get_configuration(self, conf_path): config = conf_path conf = open(config, 'r') go = True while go: line = conf.readline() if line == '': go = False else: if line[0] == '#' or line[0] == '\n' or line[0] == '\t': continue fields = line.split('=') param = str(fields[0]) value = str(fields[1]) param = param.strip('\n ') value = value.strip('\n ') if param == 'influx_server': self.lxm_conf['influx_server'] = value elif param == 'influx_port': self.lxm_conf['influx_port'] = int(value) elif param == 'debug': self.lxm_conf['debug'] = int(value) elif param == 'service_ip': self.lxm_conf['service_ip'] = value elif param == 'service_port': self.lxm_conf['service_port'] = int(value) elif param == 'influx_db1': self.lxm_conf['lxm_db1'] = value elif param == 'influx_db2': self.lxm_conf['lxm_db2'] = value elif param == 'influx_db3': self.lxm_conf['lxm_db3'] = value elif param == 'cleanup_maintenance': self.lxm_conf['cleanup_maintenance'] = int(value) elif param == 'header_request_id': self.lxm_conf['header_request_id'] = int(value) elif param == 'header_forwarded_for': self.lxm_conf['header_forwarded_for'] = int(value) elif param == 'hard_exit': if int(value) == 1: self.lxm_conf['hard_exit'] = True else: self.lxm_conf['hard_exit'] = False elif param == 'hard_startup': if int(value) == 1: self.lxm_conf['hard_startup'] = True else: self.lxm_conf['hard_startup'] = False elif param == 'hpc_centers': self.lxm_conf['hpc_centers'] = value elif param == 'transfer_sizes': self.lxm_conf['transfer_sizes'] = value elif param == 'transfer_speeds': self.lxm_conf['transfer_speeds'] = value elif param == 'heappe_middleware_available': self.lxm_conf['heappe_middleware_available'] = int(value) elif param == 'heappe_service_URLs' and self.lxm_conf['heappe_middleware_available'] == 1: self.lxm_conf['heappe_service_URLs'] = value elif param == 'openstack_available': self.lxm_conf['openstack_available'] = int(value) elif param == 'backend_URL': self.lxm_conf['backend_URL'] = value elif param == 'keycloak_URL': self.lxm_conf['keycloak_URL'] = value elif param == 'KC_REALM': self.lxm_conf['KC_REALM'] = value elif param == 'KC_CLID': self.lxm_conf['KC_CLID'] = value elif param == 'KC_SECRET': self.lxm_conf['KC_SECRET'] = value else: print(' error - unrecognized option (%s)' % param) conf.close() return 0 def post_configuration(self): if self.lxm_conf['debug'] == 1: print(' --------------------------------------------------------') print(' Backend Service Configuration:') print(' --------------------------------------------------------') if self.lxm_conf['hard_exit']: print(' hard-exit mode : True') else: print(' hard-exit mode : False') if self.lxm_conf['hard_startup']: print(' hard-startup mode : True') else: print(' hard-startup mode : False') print(' debug mode : %d' % self.lxm_conf['debug']) print(' service address : %s ' % self.lxm_conf['service_ip']) print(' service port : %-5d ' % self.lxm_conf['service_port']) print(' influxDB address : %s ' % self.lxm_conf['influx_server']) print(' influxDB port : %-5d ' % self.lxm_conf['influx_port']) print(' db_client_1 : %s ' % self.lxm_conf['lxm_db1']) print(' db_client_2 : %s ' % self.lxm_conf['lxm_db2']) print(' db_client_3 : %s ' % self.lxm_conf['lxm_db3']) print(' --------------------------------------------------------') if self.lxm_conf['debug'] == 1: print(' (dbg) the webapp is more verbose to support debugging') return 0
{ "targets": [ { "target_name": "priorityqueue_native", "sources": [ "src/priorityqueue_native.cpp", "src/ObjectHolder.cpp", "src/index.d.ts"], "cflags": ["-Wall", "-std=c++11"], 'xcode_settings': { 'OTHER_CFLAGS': [ '-std=c++11' ], }, "conditions": [ [ 'OS=="mac"', { "xcode_settings": { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'OTHER_CPLUSPLUSFLAGS' : ['-std=c++11','-stdlib=libc++'], 'OTHER_LDFLAGS': ['-stdlib=libc++'], 'MACOSX_DEPLOYMENT_TARGET': '10.7' } } ] ] } ] }
{'targets': [{'target_name': 'priorityqueue_native', 'sources': ['src/priorityqueue_native.cpp', 'src/ObjectHolder.cpp', 'src/index.d.ts'], 'cflags': ['-Wall', '-std=c++11'], 'xcode_settings': {'OTHER_CFLAGS': ['-std=c++11']}, 'conditions': [['OS=="mac"', {'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'OTHER_CPLUSPLUSFLAGS': ['-std=c++11', '-stdlib=libc++'], 'OTHER_LDFLAGS': ['-stdlib=libc++'], 'MACOSX_DEPLOYMENT_TARGET': '10.7'}}]]}]}
''' ''' print('\nNested Function\n') def function_1(text): text = text def function_2(): print(text) function_2() if __name__ == '__main__': function_1('Welcome') print('\n closure Function \n') def function_1(text): text = text def function_2(): print(text) return function_2 if __name__ == '__main__': myFunction = function_1('Thanks !') myFunction()
""" """ print('\nNested Function\n') def function_1(text): text = text def function_2(): print(text) function_2() if __name__ == '__main__': function_1('Welcome') print('\n closure Function \n') def function_1(text): text = text def function_2(): print(text) return function_2 if __name__ == '__main__': my_function = function_1('Thanks !') my_function()
# def mul(a=1,b=3): # c=a*b # return c # def add(a=1,b=2): # c=a+b # return c class Student: def __init__(self,first,last,kid): self.fname = first self.lname = last self.kid = kid self.email = first + '.' + last +'@tamuk.edu' def firstname(self): return self.fname stu_1 = Student('ashwitha','devireddy','k00442409') stu_2 = Student('santosh','kesireddy','k00442410') print(stu_1.email) print(stu_2.email) print(stu_1.firstname())
class Student: def __init__(self, first, last, kid): self.fname = first self.lname = last self.kid = kid self.email = first + '.' + last + '@tamuk.edu' def firstname(self): return self.fname stu_1 = student('ashwitha', 'devireddy', 'k00442409') stu_2 = student('santosh', 'kesireddy', 'k00442410') print(stu_1.email) print(stu_2.email) print(stu_1.firstname())
def get_initial(name): initial = name[0:1].upper() return initial first_name = input('Enter your first name: ') first_name_initial = get_initial (first_name) middle_name = input('Enter your middle name: ') middle_name_initial = get_initial (middle_name) last_name = input('Enter your last name: ') last_name_initial = get_initial (last_name) print('You initials are: ' + first_name_initial + middle_name_initial + last_name_initial)
def get_initial(name): initial = name[0:1].upper() return initial first_name = input('Enter your first name: ') first_name_initial = get_initial(first_name) middle_name = input('Enter your middle name: ') middle_name_initial = get_initial(middle_name) last_name = input('Enter your last name: ') last_name_initial = get_initial(last_name) print('You initials are: ' + first_name_initial + middle_name_initial + last_name_initial)
class Password: ''' class of the password file ''' def __init__(self, page, password): self.page = page self.password = password ''' function for class properties ''' ''' user properties ''' user_password = [] def save_page(self): Password.user_passwords.append(self) ''' save password created by new user ''' def delete_page(self): Password.user_passwords.remove(self) ''' deletes password created by new user ''' def display_page(cls): return cls.user_passwords ''' displays new user passwords generated ''' def find_by_page(cls, pager): for pagy in cls.user_passwords: if pagy.page == pager: return pagy ''' function generates new user generated passwords ''' def page_exists(cls, pager): for pagy in cls.user_passwords: if pagy.page == pager: return pagy return False ''' functions displays already generated account credentials '''
class Password: """ class of the password file """ def __init__(self, page, password): self.page = page self.password = password '\nfunction for class properties\n' '\nuser properties\n' user_password = [] def save_page(self): Password.user_passwords.append(self) '\n save password created by new user\n ' def delete_page(self): Password.user_passwords.remove(self) '\n deletes password created by new user\n ' def display_page(cls): return cls.user_passwords '\ndisplays new user passwords generated\n' def find_by_page(cls, pager): for pagy in cls.user_passwords: if pagy.page == pager: return pagy '\nfunction generates new user generated passwords\n' def page_exists(cls, pager): for pagy in cls.user_passwords: if pagy.page == pager: return pagy return False '\nfunctions displays already generated account credentials \n'
while True: try: e = str(input()).strip() c = e.replace('.', '').replace('-', '') s = 0 for i in range(9): s += int(c[i]) * (i + 1) b1 = s % 11 b1 = 0 if b1 == 10 else b1 s = 0 if b1 == int(e[-2]): for i in range(9): s += int(c[i]) * (9 - i) b2 = s % 11 b2 = 0 if b2 == 10 else b2 if b2 == int(e[-1]): print('CPF valido') else: print('CPF invalido') else: print('CPF invalido') except EOFError: break
while True: try: e = str(input()).strip() c = e.replace('.', '').replace('-', '') s = 0 for i in range(9): s += int(c[i]) * (i + 1) b1 = s % 11 b1 = 0 if b1 == 10 else b1 s = 0 if b1 == int(e[-2]): for i in range(9): s += int(c[i]) * (9 - i) b2 = s % 11 b2 = 0 if b2 == 10 else b2 if b2 == int(e[-1]): print('CPF valido') else: print('CPF invalido') else: print('CPF invalido') except EOFError: break
# Intersection of 2 arrays class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: counter = None result = [] if len(nums1) < len(nums2): counter = collections.Counter(nums1) for n in nums2: if n in counter and counter[n] > 0: counter[n] -= 1 result.append(n) else: counter = collections.Counter(nums2) for n in nums1: if n in counter and counter[n] > 0: counter[n] -= 1 result.append(n) return result
class Solution: def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: counter = None result = [] if len(nums1) < len(nums2): counter = collections.Counter(nums1) for n in nums2: if n in counter and counter[n] > 0: counter[n] -= 1 result.append(n) else: counter = collections.Counter(nums2) for n in nums1: if n in counter and counter[n] > 0: counter[n] -= 1 result.append(n) return result
class propertyDecorator(object): def __init__(self, x): self._x = x @property def x(self): return self._x @x.setter def x(self, value): self._x = value pd = propertyDecorator(100) print(pd.x) pd.x = 10 print(pd.x)
class Propertydecorator(object): def __init__(self, x): self._x = x @property def x(self): return self._x @x.setter def x(self, value): self._x = value pd = property_decorator(100) print(pd.x) pd.x = 10 print(pd.x)
countries = ["USA", "Spain", "France", "Canada"] for country in countries: print(country) data = "Hello from python" for out in data: print(out) for numero in range(8): print(numero)
countries = ['USA', 'Spain', 'France', 'Canada'] for country in countries: print(country) data = 'Hello from python' for out in data: print(out) for numero in range(8): print(numero)
# X = { # "0xFF": { # "id": 255, # "name": "meta", # "0x00": { # "type_id": 0, # "type_name": "sequence_number", # "length": 2, # "params": [ # "nmsb", # "nlsb" # ], # "dtype": "int", # "mask": [ # 255, # 255 # ], # "default" : [0, 0] # }, # "0x01": { # "type_id": 1, # "type_name": "text_event", # "length": -1, # "params": "text", # "dtype": "str", # "mask": 127, # "default" : "Enter the Text" # }, # "0x02": { # "type_id": 2, # "type_name": "copyright_notice", # "length": -1, # "params": "text", # "dtype": "str", # "mask": 127, # "default" : "No Copyright" # }, # "0x03": { # "type_id": 3, # "type_name": "track_name", # "length": -1, # "params": "text", # "dtype": "str", # "mask": 127, # "default" : "Track 0" # }, # "0x04": { # "type_id": 4, # "type_name": "instrument_name", # "length": -1, # "params": "text", # "dtype": "str", # "mask": 127, # "default" : "Piano" # }, # "0x05": { # "type_id": 5, # "type_name": "lyrics", # "length": -1, # "params": "text", # "dtype": "str", # "mask": 127, # "default" : "LYRICS" # }, # "0x06": { # "type_id": 6, # "type_name": "marker", # "length": -1, # "params": "text", # "dtype": "str", # "mask": 127, # "default" : "*" # }, # "0x07": { # "type_id": 7, # "type_name": "cue_point", # "length": -1, # "params": "text", # "dtype": "str", # "mask": 127, # "default" : "-" # }, # "0x20": { # "type_id": 32, # "type_name": "midi_ch_prefix", # "length": 1, # "params": [ # "channel" # ], # "dtype": "int", # "mask": [ # 15 # ], # "default" : [0] # }, # "0x21": { # "type_id": 33, # "type_name": "midi_port", # "length": 1, # "params": [ # "port_no" # ], # "dtype": "int", # "mask": [ # 15 # ], # "default" : [0] # }, # "0x2F": { # "type_id": 47, # "type_name": "end_of_track", # "length": 0, # "params": None, # "dtype": "None", # "mask": 127, # "default" : None # }, # "0x51": { # "type_id": 81, # "type_name": "set_tempo", # "length": 3, # "params": [ # "musec_per_quat_note", # "musec_per_quat_note", # "musec_per_quat_note" # ], # "dtype": "int", # "mask": [ # 127, # 127, # 127 # ], # "default" : [0, 0, 0] # }, # "0x54": { # "type_id": 84, # "type_name": "smpte_offset", # "length": 5, # "params": [ # "hr", # "min", # "sec", # "fr", # "subfr" # ], # "dtype": "int", # "mask": [ # 24, # 60, # 60, # 30, # 100 # ], # "default" : [0, 0 , 0, 0, 0] # }, # "0x58": { # "type_id": 88, # "type_name": "time_sig", # "length": 4, # "params": [ # "numer", # "denom", # "metro", # "32nds" # ], # "dtype": "int", # "mask": [ # 255, # 255, # 255, # 255 # ], # "default" : [0, 0, 0, 0] # }, # "0x59": { # "type_id": 89, # "type_name": "key_sig", # "length": 2, # "params": [ # "key", # "scale" # ], # "dtype": "int", # "mask": [ # 15, # 1 # ], # "default" : [0, 1] # }, # "0x7F": { # "type_id": 127, # "type_name": "sequence_specifier", # "length": -1, # "params": "text", # "dtype": "any", # "mask": 127, # "default" : [0] # } # } # } X = { 255: { 0: {'dtype': 'int', 'length': 2, 'mask': (255, 255), 'params': ('nmsb', 'nlsb'), 'type_id': 0, 'type_name': 'sequence_number', "default" : [0, 0] }, 1: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 1, 'type_name': 'text_event', "default" : "Enter the Text" }, 2: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 2, 'type_name': 'copyright_notice', "default" : "No Copyright" }, 3: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 3, 'type_name': 'track_name', "default" : "Track 0" }, 4: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 4, 'type_name': 'instrument_name', "default" : "Piano" }, 5: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 5, 'type_name': 'lyrics', "default" : "LYRICS" }, 6: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 6, 'type_name': 'marker', "default" : "*" }, 7: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 7, 'type_name': 'cue_point', "default" : "-" }, 32: {'dtype': 'int', 'length': 1, 'mask': (15,), 'params': ('channel',), 'type_id': 32, 'type_name': 'midi_ch_prefix', "default" : [0] }, 33: {'dtype': 'int', 'length': 1, 'mask': (15,), 'params': ('port_no',), 'type_id': 33, 'type_name': 'midi_port', "default" : [0] }, 47: {'dtype': 'None', 'length': 0, 'mask': 127, 'params': None, 'type_id': 47, 'type_name': 'end_of_track', "default" : None }, 81: {'dtype': 'int', 'length': 3, 'mask': (127, 127, 127), 'params': ('musec_per_quat_note', 'musec_per_quat_note', 'musec_per_quat_note'), 'type_id': 81, 'type_name': 'set_tempo', "default" : [0, 0, 0] }, 84: {'dtype': 'int', 'length': 5, 'mask': (24, 60, 60, 30, 100), 'params': ('hr', 'min', 'sec', 'fr', 'subfr'), 'type_id': 84, 'type_name': 'smpte_offset', "default" : [0, 0, 0, 0, 0] }, 88: {'dtype': 'int', 'length': 4, 'mask': (255, 255, 255, 255), 'type_id': 88, 'type_name': 'time_sig', "default" : [0, 0, 0, 0] }, 89: {'dtype': 'int', 'length': 2, 'mask': (15, 1), 'params': ('key', 'scale'), 'type_id': 89, 'type_name': 'key_sig', "default" : [0, 0] }, 127: {'dtype': 'any', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 127, 'type_name': 'sequence_specifier', "default" : [0,] }, 'id': 255, 'name': 'meta' } }
x = {255: {0: {'dtype': 'int', 'length': 2, 'mask': (255, 255), 'params': ('nmsb', 'nlsb'), 'type_id': 0, 'type_name': 'sequence_number', 'default': [0, 0]}, 1: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 1, 'type_name': 'text_event', 'default': 'Enter the Text'}, 2: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 2, 'type_name': 'copyright_notice', 'default': 'No Copyright'}, 3: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 3, 'type_name': 'track_name', 'default': 'Track 0'}, 4: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 4, 'type_name': 'instrument_name', 'default': 'Piano'}, 5: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 5, 'type_name': 'lyrics', 'default': 'LYRICS'}, 6: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 6, 'type_name': 'marker', 'default': '*'}, 7: {'dtype': 'str', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 7, 'type_name': 'cue_point', 'default': '-'}, 32: {'dtype': 'int', 'length': 1, 'mask': (15,), 'params': ('channel',), 'type_id': 32, 'type_name': 'midi_ch_prefix', 'default': [0]}, 33: {'dtype': 'int', 'length': 1, 'mask': (15,), 'params': ('port_no',), 'type_id': 33, 'type_name': 'midi_port', 'default': [0]}, 47: {'dtype': 'None', 'length': 0, 'mask': 127, 'params': None, 'type_id': 47, 'type_name': 'end_of_track', 'default': None}, 81: {'dtype': 'int', 'length': 3, 'mask': (127, 127, 127), 'params': ('musec_per_quat_note', 'musec_per_quat_note', 'musec_per_quat_note'), 'type_id': 81, 'type_name': 'set_tempo', 'default': [0, 0, 0]}, 84: {'dtype': 'int', 'length': 5, 'mask': (24, 60, 60, 30, 100), 'params': ('hr', 'min', 'sec', 'fr', 'subfr'), 'type_id': 84, 'type_name': 'smpte_offset', 'default': [0, 0, 0, 0, 0]}, 88: {'dtype': 'int', 'length': 4, 'mask': (255, 255, 255, 255), 'type_id': 88, 'type_name': 'time_sig', 'default': [0, 0, 0, 0]}, 89: {'dtype': 'int', 'length': 2, 'mask': (15, 1), 'params': ('key', 'scale'), 'type_id': 89, 'type_name': 'key_sig', 'default': [0, 0]}, 127: {'dtype': 'any', 'length': -1, 'mask': 127, 'params': 'text', 'type_id': 127, 'type_name': 'sequence_specifier', 'default': [0]}, 'id': 255, 'name': 'meta'}}
def make_car(car_manufacturer,car_model,**Other_attributes): Other_attributes['car_model']=car_model Other_attributes['car_manufacturer']=car_manufacturer return Other_attributes print(make_car('Toyota','Rav 4',color='blue'))
def make_car(car_manufacturer, car_model, **Other_attributes): Other_attributes['car_model'] = car_model Other_attributes['car_manufacturer'] = car_manufacturer return Other_attributes print(make_car('Toyota', 'Rav 4', color='blue'))