content
stringlengths
7
1.05M
""" module for creating generic constants used by multiple modules """ """ The cloudwatch dashboard grid positioning system will automatically set x and y coordinates of every widget in the list, based on the next available x,y on the dashboard, from left to right, then top to bottom. As long as we specify height and width, and are ok with this default positioning behavior, positioning can be as simple as specifying the height and width of the widget. doc: https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/CloudWatch-Dashboard-Body-Structure.html#CloudWatch-Dashboard-Properties-Widgets-Structure """ positioning = { 'width': 24, 'height': 3 }
# %% [1128. Number of Equivalent Domino Pairs](https://leetcode.com/problems/number-of-equivalent-domino-pairs/) class Solution: def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int: c = collections.Counter(tuple(sorted(i)) for i in dominoes) return sum(n * (n - 1) // 2 for n in c.values())
print("hi\nmyname is : abdullah") print("And in this code we will do ") #Files print("Files") #______________________# with open("information.txt" , "r") as f: print(f.read())
""" DESCRIPTION Gerald Appel developed Moving Average Convergence/Divergence as an indicator of the change in a security's underlying price trend. The theory suggests that when a price is trending, it is expected, from time to time, that speculative forces "test" the trend. MACD shows characteristics of both a trending indicator and an oscillator. While the primary function is to identify turning points in a trend, the level at which the signals occur determines the strength of the reading. CALCULATION MACD Line: MACD=Period1 Exponential MA (Fast) - Period2 Exponential MA (Slow) MACD Signal Line: Sig=Period3 Exponential MA of MACD Line MACD Diff: Diff=MACD - Sig where: Period1 = N Period of the Fast Exponential MA The default Period1 is 12 Period2 = N Period of the Slow Exponential MA The default Period2 is 26 Period3 = N Period Exponential MA for the Signal Line The default Period3 is 9 MACD Period: N Period = For daily, N=days; weekly, N=weeks, ... MACD omits non-trading days from computations. Formula: MACD Line: (12-day EMA - 26-day EMA) Signal Line: 9-day EMA of MACD Line MACD Histogram: MACD Line - Signal Line Validation: validated with results from Bloomberg """ # Standard MACD function def macd(ohlcv, short_period=12, long_period=26, signal_period=9, ohlcv_series="close"): _ohlcv = ohlcv[[ohlcv_series]].copy(deep=True) _ohlcv["short"] = _ohlcv[ohlcv_series].ewm(span=short_period, min_periods=short_period).mean() _ohlcv["long"] = _ohlcv[ohlcv_series].ewm(span=long_period, min_periods=long_period).mean() _ohlcv["macd"] = _ohlcv["short"] - _ohlcv["long"] _ohlcv["signal"] = _ohlcv["macd"].ewm(span=signal_period, min_periods=signal_period).mean() _ohlcv["hist"] = _ohlcv["macd"] - _ohlcv["signal"] return _ohlcv[["macd", "signal", "hist"]]
def canTransform1(start, end): startX = "".join([c for c in start if c != "X"]) endX = "".join([c for c in end if c != "X"]) if startX != endX: return False startR = [i for i in range(len(start)) if start[i] == "R"] startL = [i for i in range(len(start)) if start[i] == "L"] endR = [i for i in range(len(end)) if end[i] == "R"] endL = [i for i in range(len(end)) if end[i] == "L"] for s, e in zip(startR, endR): if s > e: return False for s, e in zip(startL, endL): if s < e: return False return True def canTransform2(start, end): n = len(start) i, j = 0, 0 while i < n or j < n: while i < n and start[i] == "X": i += 1 while j < n and end[j] == "X": j += 1 if (i < n) != (j < n): return False if i < n and j < n: if (start[i] != end[j]) or (start[i] == "L" and i < j) or (end[j] == "R" and i > j): return False i += 1 j += 1 return True print(canTransform1("RXXLRXRXL", "XRLXXRRLX")) # True print(canTransform2("RXXLRXRXL", "XRLXXRRLX")) # True print(canTransform1("XXXXXLXXXX", "LXXXXXXXXX")) # True print(canTransform2("XXXXXLXXXX", "LXXXXXXXXX")) # True print(canTransform1("RXR", "XXR")) # False print(canTransform2("RXR", "XXR")) # False
n = int(input()) lst = sorted([int(input()) for i in range(n)]) ans = sorted(set(range(lst[0], lst[len(lst) - 1])).difference(lst)) if lst[0] > 1: for i in range(1, lst[0]): ans.append(i) if (len(ans) != 0): print(*sorted(ans), sep='\n') else: print("good job")
# # PySNMP MIB module HH3C-RCR-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-RCR-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:29:21 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection") hh3cCommon, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cCommon") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Counter32, ModuleIdentity, Integer32, IpAddress, Bits, Unsigned32, Counter64, iso, TimeTicks, NotificationType, ObjectIdentity, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "ModuleIdentity", "Integer32", "IpAddress", "Bits", "Unsigned32", "Counter64", "iso", "TimeTicks", "NotificationType", "ObjectIdentity", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") hh3cRcr = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 48)) hh3cRcr.setRevisions(('2005-06-28 19:36',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hh3cRcr.setRevisionsDescriptions(('The modified revision of this MIB module. Rewrite the whole MIB.',)) if mibBuilder.loadTexts: hh3cRcr.setLastUpdated('200506281936Z') if mibBuilder.loadTexts: hh3cRcr.setOrganization('Hangzhou H3C Tech. Co., Ltd.') if mibBuilder.loadTexts: hh3cRcr.setContactInfo('Platform Team Hangzhou H3C Tech. Co., Ltd. Hai-Dian District Beijing P.R. China http://www.h3c.com Zip:100085 ') if mibBuilder.loadTexts: hh3cRcr.setDescription("This MIB is applicable to router-devices. It's made for RCR (Resilient Controllable Routing). RCR provides an effective resolution which can dynamically auto-adjust outbound traffic to the optimal external interface by monitoring the performance and traffic load of each external interface. It provides the functions of intelligentized traffic load distribution and the optimal external interface selection. This can optimally utilize the external interfaces. Furthermore, RCR realized the function which can select the optimal external interface based on different classes of operation flow.") hh3cRcrMR = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1)) hh3cRcrMRGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 1)) hh3cRcrMRAllMaxUsedBandRate = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100))).setUnits('%').setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrMRAllMaxUsedBandRate.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMRAllMaxUsedBandRate.setDescription('The max used band rate of all external interfaces on member router-devices(MRs) which are controlled by RCR.') hh3cRcrMRAllMinUsedBandRate = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('%').setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrMRAllMinUsedBandRate.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMRAllMinUsedBandRate.setDescription('The min used band rate of all external interfaces on MRs which are controlled by RCR.') hh3cRcrMRListenTime = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1440))).setUnits('minute').setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrMRListenTime.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMRListenTime.setDescription('The persistent time of a probe on member router-device(MR) which is controlled by RCR.') hh3cRcrMRStateTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 2), ) if mibBuilder.loadTexts: hh3cRcrMRStateTable.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMRStateTable.setDescription('This table contains state information of each MR which is controlled by RCR.') hh3cRcrMRStateEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 2, 1), ).setIndexNames((0, "HH3C-RCR-MIB", "hh3cRcrMRName")) if mibBuilder.loadTexts: hh3cRcrMRStateEntry.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMRStateEntry.setDescription('Entry items') hh3cRcrMRName = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 2, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))) if mibBuilder.loadTexts: hh3cRcrMRName.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMRName.setDescription('The name of MR which is controlled by RCR.') hh3cRcrMRState = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("down", 1), ("up", 2), ("controlled", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrMRState.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMRState.setDescription('The state of MR where identified on the controller router-device(CR). down: The MR has been enabled but has not connected to the CR with TCP connection. up: The MR has already successfully connected to the CR but has not been ready for adjusting route. controlled: The MR has already passed the consultation with the CR and could be controlled by it.') hh3cRcrMRAuthType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("simple", 1), ("md5", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrMRAuthType.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMRAuthType.setDescription('The authentication type of communication packet between CR and MR.') hh3cRcrMRAuthPwd = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 2, 1, 4), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrMRAuthPwd.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMRAuthPwd.setDescription('The authentication password of communication packet between CR and MR. Reading this object always results in an OCTET STRING of length zero; authentication may not be bypassed by reading the MIB object.') hh3cRcrMROutIfStateTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 3), ) if mibBuilder.loadTexts: hh3cRcrMROutIfStateTable.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMROutIfStateTable.setDescription('This table contains the external interface states of each MR which is controlled by RCR.') hh3cRcrMROutIfStateEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 3, 1), ).setIndexNames((0, "HH3C-RCR-MIB", "hh3cRcrMRName"), (0, "HH3C-RCR-MIB", "hh3cRcrMROutIfName")) if mibBuilder.loadTexts: hh3cRcrMROutIfStateEntry.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMROutIfStateEntry.setDescription('Entry items') hh3cRcrMROutIfName = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 3, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 48))) if mibBuilder.loadTexts: hh3cRcrMROutIfName.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMROutIfName.setDescription('The name of external interface on each MR.') hh3cRcrMROutIfState = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("down", 1), ("up", 2), ("notExist", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrMROutIfState.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMROutIfState.setDescription('The state of external interface on each MR.') hh3cRcrMROutIfMaxUsedBandRate = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100))).setUnits('%').setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrMROutIfMaxUsedBandRate.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMROutIfMaxUsedBandRate.setDescription('The max spendable bandwidth rate on external interface.') hh3cRcrMROutIfMinUsedBandRate = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('%').setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrMROutIfMinUsedBandRate.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMROutIfMinUsedBandRate.setDescription('The min spendable bandwidth rate on external interface.') hh3cRcrMROutIfUsedBandRate = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 1, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrMROutIfUsedBandRate.setStatus('current') if mibBuilder.loadTexts: hh3cRcrMROutIfUsedBandRate.setDescription('The used bandwidth rate on external interface.') hh3cRcrCR = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2)) hh3cRcrCRGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 1)) hh3cRcrCRState = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("down", 1), ("init", 2), ("active", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrCRState.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRState.setDescription('The state of the CR which is controlled by RCR. down: The CR has been enabled but has not started a TCP connection server. init: The CR has started a TCP connection server and has been waiting for MR connection, but has not been ready for adjusting route. active: The CR is ready for adjusting route.') hh3cRcrCRPortNum = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRPortNum.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRPortNum.setDescription('The communication port number between CR and MR.') hh3cRcrCRCtrlMode = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("control", 1), ("observe", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRCtrlMode.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRCtrlMode.setDescription('The observe mode or control mode is configured to operate in the CR. observe: The CR monitors prefixes and external interfaces based on default and user-defined policies and then reports the status of the network and the decisions that should be made but does not implement any changes. controlled: The CR monitors prefixes and external interfaces based on default and user-defined policies and then reports the status of the network and the decisions that should be made and implement any changes.') hh3cRcrCRChooseMode = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("good", 1), ("best", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRChooseMode.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRChooseMode.setDescription('The algorithm used to choose an alternative external interface for a prefix. good: The first external interface that conforms to the policy is selected as the new external interface. best: Information is collected from all external interfaces and the best one is selected even though the best external interface may not be in-policy.') hh3cRcrCRKeepaliveTime = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000))).setUnits('second').setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRKeepaliveTime.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRKeepaliveTime.setDescription('The interval time of the transmission of the keepalive communication packet between CR and MR.') hh3cRcrCRPolicyMode = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("prefix", 1), ("operation", 2), ("study", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRPolicyMode.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRPolicyMode.setDescription('The chosen policy mode which decides to change what prefix. prefix: An RCR policy is designed to select IP prefixes or to select RCR learn policies using a match clause and then to apply RCR policy configurations using a set clause. operation: To deside to adjusted prefixes based on operation which user configured. study: To learn and optimize prefixes based on the highest throughput or the highest delay.') hh3cRcrCRStudyMode = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("maxThoughout", 1), ("maxDelay", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRStudyMode.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRStudyMode.setDescription("The mode of collecting prefix in studying configuration mode. It's to collect either the prefix of max thoughtout or the prefix of max delay time. It doesn't have a value when CR isn't in studying configuration mode.") hh3cRcrCRStudyIpPrefixNum = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2500))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRStudyIpPrefixNum.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRStudyIpPrefixNum.setDescription('The max number of collecting prefix in studying configuration mode.') hh3cRcrCRIpPrefixLen = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32)).clone(24)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRIpPrefixLen.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRIpPrefixLen.setDescription('The mask length of collecting prefix in configuration mode.') hh3cRcrCRRcrPolicyTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 2), ) if mibBuilder.loadTexts: hh3cRcrCRRcrPolicyTable.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRRcrPolicyTable.setDescription('This table contains objects to get statistic information of interfaces on a device.') hh3cRcrCRRcrPolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 2, 1), ).setIndexNames((0, "HH3C-RCR-MIB", "hh3cRcrCRRcrPlyID")) if mibBuilder.loadTexts: hh3cRcrCRRcrPolicyEntry.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRRcrPolicyEntry.setDescription('Entry items') hh3cRcrCRRcrPlyID = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: hh3cRcrCRRcrPlyID.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRRcrPlyID.setDescription('The ID of RCR policy which the user has configured.') hh3cRcrCRRcrPlyMatchIPListName = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 2, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 19))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRRcrPlyMatchIPListName.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRRcrPlyMatchIPListName.setDescription('The matched IP prefix list name of RCR policy which the user has configured.') hh3cRcrCRRcrPlyMatchStudyEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRRcrPlyMatchStudyEnable.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRRcrPlyMatchStudyEnable.setDescription('Whether the RCR policy which the user has configured is matched for studying prefix mode.') hh3cRcrCRRcrPlyMatchOperPlyName = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 2, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 19))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRRcrPlyMatchOperPlyName.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRRcrPlyMatchOperPlyName.setDescription('The matched operation policy name of RCR policy which the user has configured.') hh3cRcrCRRcrAclNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(3000, 3999))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRRcrAclNumber.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRRcrAclNumber.setDescription('The matched acl number of RCR operation policy which the user has configured.') hh3cRcrCRRcrPlyDelayTime = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10000))).setUnits('millisecond').setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRRcrPlyDelayTime.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRRcrPlyDelayTime.setDescription('The absolute maximum delay time. The range of values that can be configured is from 1 to 10000.') hh3cRcrCRRcrPlyLossRate = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100))).setUnits('%').setMaxAccess("readwrite") if mibBuilder.loadTexts: hh3cRcrCRRcrPlyLossRate.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRRcrPlyLossRate.setDescription('The packet loss percent of prefix which the CR concerns.') hh3cRcrCRMatPrefixPerfTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 3), ) if mibBuilder.loadTexts: hh3cRcrCRMatPrefixPerfTable.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRMatPrefixPerfTable.setDescription('This table contains the matched prefix performance information.') hh3cRcrCRMatPrefixPerfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 3, 1), ).setIndexNames((0, "HH3C-RCR-MIB", "hh3cRcrCRMatPrefPerfAddrType"), (0, "HH3C-RCR-MIB", "hh3cRcrCRMatPrefPerfDestIPAddr"), (0, "HH3C-RCR-MIB", "hh3cRcrCRMatPrefPerfDestMaskLen")) if mibBuilder.loadTexts: hh3cRcrCRMatPrefixPerfEntry.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRMatPrefixPerfEntry.setDescription('Entry items') hh3cRcrCRMatPrefPerfAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 3, 1, 1), InetAddressType()) if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfAddrType.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfAddrType.setDescription('The destination IP addresses type of matched prefix which the CR wants (IPv4 or IPv6).') hh3cRcrCRMatPrefPerfDestIPAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 3, 1, 2), InetAddress()) if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfDestIPAddr.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfDestIPAddr.setDescription('The destination IP address of matched prefix which the CR wants.') hh3cRcrCRMatPrefPerfDestMaskLen = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 32))) if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfDestMaskLen.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfDestMaskLen.setDescription('The destination IP address mask length of matched prefix which the CR wants.') hh3cRcrCRMatPrefPerfDelayTime = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10000))).setUnits('second').setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfDelayTime.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfDelayTime.setDescription('The absolute maximum delay time of prefix which the CR has configured.') hh3cRcrCRMatPrefPerfLossRate = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100))).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfLossRate.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfLossRate.setDescription('The packet loss percent of prefix which the CR has configured.') hh3cRcrCRMatPrefPerfThroughput = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 3, 1, 6), Integer32()).setUnits('kb').setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfThroughput.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRMatPrefPerfThroughput.setDescription('The bandwidth of prefix which the CR has monitored.') hh3cRcrCRAdjustPrefixTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4), ) if mibBuilder.loadTexts: hh3cRcrCRAdjustPrefixTable.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjustPrefixTable.setDescription('This table contains objects to get adjusted prefix information which the CR controlled.') hh3cRcrCRAdjustPrefixEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4, 1), ).setIndexNames((0, "HH3C-RCR-MIB", "hh3cRcrCRAdjuPrefDestAddrType"), (0, "HH3C-RCR-MIB", "hh3cRcrCRAdjuPrefDestAddr"), (0, "HH3C-RCR-MIB", "hh3cRcrCRAdjuPrefMaskLen"), (0, "HH3C-RCR-MIB", "hh3cRcrCRAdjuPrefPreMRName"), (0, "HH3C-RCR-MIB", "hh3cRcrCRAdjuPrefPreOutIfName")) if mibBuilder.loadTexts: hh3cRcrCRAdjustPrefixEntry.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjustPrefixEntry.setDescription('Entry items') hh3cRcrCRAdjuPrefDestAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4, 1, 1), InetAddressType()) if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefDestAddrType.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefDestAddrType.setDescription('The IP address type of the adjusted prefix which CR controlled (IPv4 or IPv6).') hh3cRcrCRAdjuPrefDestAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4, 1, 2), InetAddress()) if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefDestAddr.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefDestAddr.setDescription('The IP address of the adjusted prefix which CR controlled.') hh3cRcrCRAdjuPrefMaskLen = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 32))) if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefMaskLen.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefMaskLen.setDescription('The IP address mask length of the adjusted prefix which CR controlled.') hh3cRcrCRAdjuPrefPreMRName = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))) if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefPreMRName.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefPreMRName.setDescription('The name of the MR which the previous outbound traffic flows through.') hh3cRcrCRAdjuPrefPreOutIfName = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 48))) if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefPreOutIfName.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefPreOutIfName.setDescription('The name of the external interface on the MR which the previous outbound traffic flows through.') hh3cRcrCRAdjuPrefCurMRName = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefCurMRName.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefCurMRName.setDescription('The name of the MR which the current outbound traffic flows through.') hh3cRcrCRAdjuPrefCurOutIfName = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4, 1, 7), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefCurOutIfName.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefCurOutIfName.setDescription('The name of the external interface on the MR which the current outbound traffic flows through.') hh3cRcrCRAdjuPrefPersistTime = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4, 1, 8), Integer32()).setUnits('second').setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefPersistTime.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefPersistTime.setDescription('The persisting time from the time which the adjusted outbound traffic has been adjusted by CR to now.') hh3cRcrCRAdjuPrefAgeTime = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 48, 2, 4, 1, 9), Integer32()).setUnits('second').setMaxAccess("readonly") if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefAgeTime.setStatus('current') if mibBuilder.loadTexts: hh3cRcrCRAdjuPrefAgeTime.setDescription('The time which the adjusted prefix remains.') mibBuilder.exportSymbols("HH3C-RCR-MIB", hh3cRcrCRAdjuPrefDestAddr=hh3cRcrCRAdjuPrefDestAddr, hh3cRcrCRMatPrefPerfDestIPAddr=hh3cRcrCRMatPrefPerfDestIPAddr, hh3cRcrCRMatPrefPerfDestMaskLen=hh3cRcrCRMatPrefPerfDestMaskLen, hh3cRcrMR=hh3cRcrMR, hh3cRcrCRStudyMode=hh3cRcrCRStudyMode, hh3cRcrMRName=hh3cRcrMRName, hh3cRcrCRRcrPlyID=hh3cRcrCRRcrPlyID, hh3cRcrCRRcrPlyMatchOperPlyName=hh3cRcrCRRcrPlyMatchOperPlyName, hh3cRcrCRMatPrefixPerfEntry=hh3cRcrCRMatPrefixPerfEntry, hh3cRcrCRAdjuPrefPreOutIfName=hh3cRcrCRAdjuPrefPreOutIfName, hh3cRcrMRGroup=hh3cRcrMRGroup, hh3cRcrMRStateEntry=hh3cRcrMRStateEntry, hh3cRcrCR=hh3cRcrCR, hh3cRcrCRPortNum=hh3cRcrCRPortNum, hh3cRcrCRRcrPlyLossRate=hh3cRcrCRRcrPlyLossRate, hh3cRcrMROutIfUsedBandRate=hh3cRcrMROutIfUsedBandRate, hh3cRcr=hh3cRcr, hh3cRcrMRAuthType=hh3cRcrMRAuthType, hh3cRcrMRAuthPwd=hh3cRcrMRAuthPwd, hh3cRcrCRRcrAclNumber=hh3cRcrCRRcrAclNumber, hh3cRcrCRChooseMode=hh3cRcrCRChooseMode, hh3cRcrCRAdjustPrefixTable=hh3cRcrCRAdjustPrefixTable, hh3cRcrMROutIfStateEntry=hh3cRcrMROutIfStateEntry, hh3cRcrCRMatPrefPerfThroughput=hh3cRcrCRMatPrefPerfThroughput, hh3cRcrCRGroup=hh3cRcrCRGroup, hh3cRcrCRAdjuPrefPreMRName=hh3cRcrCRAdjuPrefPreMRName, hh3cRcrCRAdjustPrefixEntry=hh3cRcrCRAdjustPrefixEntry, hh3cRcrCRMatPrefPerfAddrType=hh3cRcrCRMatPrefPerfAddrType, hh3cRcrMRStateTable=hh3cRcrMRStateTable, hh3cRcrCRAdjuPrefCurOutIfName=hh3cRcrCRAdjuPrefCurOutIfName, hh3cRcrCRAdjuPrefAgeTime=hh3cRcrCRAdjuPrefAgeTime, hh3cRcrCRMatPrefixPerfTable=hh3cRcrCRMatPrefixPerfTable, hh3cRcrMROutIfMaxUsedBandRate=hh3cRcrMROutIfMaxUsedBandRate, hh3cRcrMROutIfStateTable=hh3cRcrMROutIfStateTable, hh3cRcrMRAllMaxUsedBandRate=hh3cRcrMRAllMaxUsedBandRate, hh3cRcrCRCtrlMode=hh3cRcrCRCtrlMode, hh3cRcrCRRcrPlyMatchStudyEnable=hh3cRcrCRRcrPlyMatchStudyEnable, hh3cRcrMRState=hh3cRcrMRState, hh3cRcrCRKeepaliveTime=hh3cRcrCRKeepaliveTime, hh3cRcrMROutIfState=hh3cRcrMROutIfState, hh3cRcrMROutIfMinUsedBandRate=hh3cRcrMROutIfMinUsedBandRate, hh3cRcrCRIpPrefixLen=hh3cRcrCRIpPrefixLen, hh3cRcrCRMatPrefPerfLossRate=hh3cRcrCRMatPrefPerfLossRate, hh3cRcrMRAllMinUsedBandRate=hh3cRcrMRAllMinUsedBandRate, hh3cRcrMRListenTime=hh3cRcrMRListenTime, hh3cRcrCRStudyIpPrefixNum=hh3cRcrCRStudyIpPrefixNum, hh3cRcrCRRcrPolicyEntry=hh3cRcrCRRcrPolicyEntry, hh3cRcrCRRcrPlyMatchIPListName=hh3cRcrCRRcrPlyMatchIPListName, hh3cRcrCRAdjuPrefDestAddrType=hh3cRcrCRAdjuPrefDestAddrType, hh3cRcrCRMatPrefPerfDelayTime=hh3cRcrCRMatPrefPerfDelayTime, hh3cRcrMROutIfName=hh3cRcrMROutIfName, hh3cRcrCRState=hh3cRcrCRState, hh3cRcrCRRcrPolicyTable=hh3cRcrCRRcrPolicyTable, hh3cRcrCRAdjuPrefMaskLen=hh3cRcrCRAdjuPrefMaskLen, hh3cRcrCRAdjuPrefCurMRName=hh3cRcrCRAdjuPrefCurMRName, hh3cRcrCRRcrPlyDelayTime=hh3cRcrCRRcrPlyDelayTime, PYSNMP_MODULE_ID=hh3cRcr, hh3cRcrCRPolicyMode=hh3cRcrCRPolicyMode, hh3cRcrCRAdjuPrefPersistTime=hh3cRcrCRAdjuPrefPersistTime)
# Painter's Partition Problem # https://www.interviewbit.com/problems/painters-partition-problem/ # # You have to paint N boards of length {A0, A1, A2, A3 … AN-1}. There are K painters available # and you are also given how much time a painter takes to paint 1 unit of board. You have to get # this job done as soon as possible under the constraints that any painter will only paint # contiguous sections of board. # # 2 painters cannot share a board to paint. That is to say, a board # cannot be painted partially by one painter, and partially by another. # A painter will only paint contiguous boards. Which means a # configuration where painter 1 paints board 1 and 3 but not 2 is # invalid. # # Return the ans % 10000003 # # Input : # K : Number of painters # T : Time taken by painter to paint 1 unit of board # L : A List which will represent length of each board # # Output: # return minimum time to paint all boards % 10000003 # # Example # # Input : # K : 2 # T : 5 # L : [1, 10] # # Output : 50 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # class Solution: def num_of_painters(self, A, B): n, s = 1, 0 for elem in A: s += elem if s > B: n, s = n + 1, elem return n # @param A : integer # @param B : integer # @param C : list of integers # @return an integer def paint(self, A, B, C): C = list(map(lambda x: x * B, C)) l, r = max(C), sum(C) while l < r: mid = (l + r) // 2 n = self.num_of_painters(C, mid) if n > A: l = mid + 1 else: r = mid return l % 10000003 # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # if __name__ == "__main__": s = Solution() A = 3 B = 10 C = [640, 435, 647, 352, 8, 90, 960, 329, 859] print(s.paint(A, B, C))
# Copyright 2019-2020 The ASReview Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def test_get_projects(client): """Test get projects.""" response = client.get("/api/projects") json_data = response.get_json() assert "result" in json_data assert isinstance(json_data["result"], list)
""" 0 = possible pathway 1 = wall 2 = rat's path """ board = [ [0, 0, 0, 0, 0], [1, 1, 0, 1, 0], [0, 0, 0, 1, 0], [0, 1, 1, 1, 1], [0, 0, 0, 0, 0], ] moves = [(0, 1), (1, 0), (0, -1), (-1, 0)] def main(): if solve(board, 0, 0, 0): print("Solvable") [print(row) for row in board] else: print("Not Solvable") def solve(board, new_x, new_y, pos): if isAllowed(new_x, new_y): old_val = board[new_x][new_y] board[new_x][new_y] = 2 # print("Pos: ", pos, " | x: ", new_x, " | y: ", new_y) if isCompleted(): return True for x, y in moves: if solve(board, new_x + x, new_y + y, pos + 1): return True board[new_x][new_y] = old_val return False def isAllowed(x, y): if x >= 0 and x < 5 and y >= 0 and y < 5 and board[x][y] == 0: return True return False def isCompleted(): if board[4][4] == 2: return True return False if __name__ == "__main__": main()
# -*- coding: utf-8 -*- __version__ = '0.1.0' __author__ = 'Ramiro Gómez <code@ramiro.org>' __name__ = 'procrust' __description__ = 'Limit the time you procrastinate by blocking websites via the hosts file' __all__ = []
# x_5_5 # # 「while文」を使って鬼退治のメンバーを1行づつ表示するコードを追加してください members = ['桃太郎', 'いぬ', 'さる', 'きじ'] number = 0 while number < 10: print(number) number += 1
DATA_DIR = "/path/your_data_path" IDX_DIR = "/path/your_index_path" FILE_ROOT = "./test" CALIB_FILE = "./imagenet_int8_cache" MODEL_FILE = "./resnet_imagenet.uff"
search_success_response = {'timestamp': 1579714500, 'articleCount': 10, 'articles': [ {'title': 'Recovering Lost Sales with Facebook Messenger Marketing', 'description': 'With Facebook Messenger marketing, ecommerce companies can connect with shoppers and site visitors directly through Facebook chatbots, creating a new channel for engagement. Similar to email marketing ...', 'url': 'https://multichannelmerchant.com/blog/recovering-lost-sales-facebook-messenger-marketing/', 'image': 'https://images.gnews.io/a1fcd0818cbc64341e6e8b8c8cde5897', 'publishedAt': '2020-01-17 12:35:00 UTC', 'source': {'name': 'Multichannel Merchant', 'url': 'https://multichannelmerchant.com'}}, {'title': 'How to grow your business in 2020: The essential marketing toolkit you need in your arsenal', 'description': 'Also, chatbots offer a 24-hour service and eliminate the delay that comes with customer reps. This is where LivePerson comes in. LivePerson uses artificial intelligence to automate up to 70% of ...', 'url': 'https://www.smartinsights.com/managing-digital-marketing/growth-hacking/how-to-grow-your-business-in-2020/', 'image': None, 'publishedAt': '2020-01-15 08:32:00 UTC', 'source': {'name': 'Smart Insights', 'url': 'https://www.smartinsights.com'}}, {'title': 'Chatbots Market Assessment of Competitors 2020-2029', 'description': 'Global News for Chatbots Market Study 2020-2029, by Segment (TalkBot, Elbot, ELise), Playing a Pivotal Role in Expanding by (Phone, Pad, Desktop PC, Laptop), Investment Analysis by Leading ...', 'url': 'https://www.marketwatch.com/press-release/chatbots-market-assessment-of-competitors-2020-2029-2020-01-15', 'image': None, 'publishedAt': '2020-01-15 03:46:00 UTC', 'source': {'name': 'MarketWatch', 'url': 'https://www.marketwatch.com'}}, {'title': 'Global Advanced Chatbots Market 2019 EGain Coporation, Creative Virtual, Next IT Corp', 'description': 'Access complete report here @ http://www.marketresearchstore.com/report/global-advanced-chatbots-market-report-2019-651858 The examination underlines the immense driving business players : Artificial ...', 'url': 'https://www.openpr.com/news/1895901/global-advanced-chatbots-market-2019-egain-coporation', 'image': None, 'publishedAt': '2020-01-14 04:31:00 UTC', 'source': {'name': 'openpr.com', 'url': 'https://www.openpr.com'}}, {'title': 'AI in marketing: How to find the right use cases, people and technology', 'description': 'Among the common use cases are the following: intelligent chatbots, smarter personalized digital advertising, content generation and curation, AI-powered account or lead scoring, AI-assisted email ...', 'url': 'https://www.clickz.com/ai-in-marketing-how-to-find-the-right-use-cases-people-and-technology/259376/', 'image': 'https://images.gnews.io/0a9cd2f2a023dcbd09a43c69bfc91386', 'publishedAt': '2020-01-10 05:03:00 UTC', 'source': {'name': 'ClickZ', 'url': 'https://www.clickz.com'}}, {'title': 'Five Conversational AI Predictions For 2020', 'description': 'The year 2020 will be an exciting time for conversational artificial intelligence (AI), as chatbots join forces with other digital assistants and integrate deeper into back-end technologies to deliver ...', 'url': 'https://www.forbes.com/sites/forbescommunicationscouncil/2020/01/10/five-conversational-ai-predictions-for-2020/', 'image': 'https://images.gnews.io/0f6b8ddc6ccf18eaf535b219dc81103e', 'publishedAt': '2020-01-10 03:08:00 UTC', 'source': {'name': 'Forbes', 'url': 'https://www.forbes.com'}}, { 'title': 'Global Chatbots Market Grow with Noteworthy CAGR of around 35.08% by 2023| Accounted for USD 88.5 Million in 2015', 'description': 'The global chatbots market has been segmented by end-use into large enterprise, small and medium sized enterprise, out of which, the large scale enterprise segment is estimated to be the largest ...', 'url': 'https://www.marketwatch.com/press-release/global-chatbots-market-grow-with-noteworthy-cagr-of-around-3508-by-2023-accounted-for-usd-885-million-in-2015-2020-01-10', 'image': None, 'publishedAt': '2020-01-10 01:41:00 UTC', 'source': {'name': 'MarketWatch', 'url': 'https://www.marketwatch.com'}}, {'title': 'The Chinese startup using chatbots to revolutionize hotel bookings', 'description': 'The platform has signed deals with 25 partners while 120 more are in the pipeline, according to Wang. It also works with more than 100 travel content and product suppliers including Asian booking ...', 'url': 'https://technode.com/2020/01/08/the-chinese-startup-using-chatbots-to-revolutionize-hotel-booking/', 'image': 'https://images.gnews.io/2c547b4795e6b09055cf8c41f29d8ccf', 'publishedAt': '2020-01-08 20:00:00 UTC', 'source': {'name': 'TechNode', 'url': 'https://technode.com'}}, {'title': 'AI poses risks, but the White House says regulators shouldn’t “needlessly hamper” innovation', 'description': 'Artificial intelligence is here, and it’s impacting our lives in real ways — whether it’s the Alexa smart speaker on our nightstand, online customer service chatbots, or the smart replies Google ...', 'url': 'https://www.vox.com/recode/2020/1/8/21056809/artificial-intelligence-new-ai-principles-white-house', 'image': 'https://images.gnews.io/0e368b57437de7a3654aade8782aff75', 'publishedAt': '2020-01-08 16:30:00 UTC', 'source': {'name': 'Vox', 'url': 'https://www.vox.com'}}, {'title': "Samsung's Neon 'artificial humans' look like super-realistic video chatbots", 'description': "Samsung Neon isn't a robot or a voice assistant like Siri or Alexa. Instead, it's a simulated human assistant that appears on a screen and learns about people to help it give intelligent responses -- ...", 'url': 'https://www.cnbc.com/2020/01/06/samsung-neon-artificial-human-announced-at-ces-2020.html', 'image': 'https://images.gnews.io/214618b3fc601ad80704b8e2b20ba957', 'publishedAt': '2020-01-08 15:16:00 UTC', 'source': {'name': 'CNBC', 'url': 'https://www.cnbc.com'}}]} top_news_success_response = {"timestamp": 1583496614, "articleCount": 10, "articles": [ {"title": "Coronavirus: Britons quarantined on cruise ship off San Francisco", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMifWh0dHBzOi8vd3d3LnRoZWd1YXJkaWFuLmNvbS93b3JsZC8yMDIwL21hci8wNi9jb3JvbmF2aXJ1cy1icml0b25zLXF1YXJhbnRpbmVkLW9uLWNydWlzZS1zaGlwLW9mZi1zYW4tZnJhbmNpc2NvLWdyYW5kLXByaW5jZXNz0gF9aHR0cHM6Ly9hbXAudGhlZ3VhcmRpYW4uY29tL3dvcmxkLzIwMjAvbWFyLzA2L2Nvcm9uYXZpcnVzLWJyaXRvbnMtcXVhcmFudGluZWQtb24tY3J1aXNlLXNoaXAtb2ZmLXNhbi1mcmFuY2lzY28tZ3JhbmQtcHJpbmNlc3M?oc=5", "image": None, "publishedAt": "2020-03-06 10:03:00 UTC", "source": {"name": "The Guardian", "url": "https:\/\/www.theguardian.com"}}, {"title": "Ceasefire in Syria after Russia and Turkey strike deal", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiW2h0dHBzOi8vbmV3cy5za3kuY29tL3N0b3J5L3J1c3NpYS1hbmQtdHVya2V5LWFncmVlLWNlYXNlZmlyZS1pbi1ub3J0aHdlc3Rlcm4tc3lyaWEtMTE5NTA0NDjSAV9odHRwczovL25ld3Muc2t5LmNvbS9zdG9yeS9hbXAvcnVzc2lhLWFuZC10dXJrZXktYWdyZWUtY2Vhc2VmaXJlLWluLW5vcnRod2VzdGVybi1zeXJpYS0xMTk1MDQ0OA?oc=5", "image": None, "publishedAt": "2020-03-05 22:30:00 UTC", "source": {"name": "Sky News", "url": "https:\/\/news.sky.com"}}, {"title": "Vatican City reports its first case of coronavirus, days after Pope tested negative", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMidWh0dHBzOi8vd3d3LmRhaWx5bWFpbC5jby51ay9uZXdzL2FydGljbGUtODA4MjI1OS9WYXRpY2FuLUNpdHktcmVwb3J0cy1jYXNlLWNvcm9uYXZpcnVzLWRheXMtUG9wZS10ZXN0ZWQtbmVnYXRpdmUuaHRtbNIBeWh0dHBzOi8vd3d3LmRhaWx5bWFpbC5jby51ay9uZXdzL2FydGljbGUtODA4MjI1OS9hbXAvVmF0aWNhbi1DaXR5LXJlcG9ydHMtY2FzZS1jb3JvbmF2aXJ1cy1kYXlzLVBvcGUtdGVzdGVkLW5lZ2F0aXZlLmh0bWw?oc=5", "image": None, "publishedAt": "2020-03-06 09:32:00 UTC", "source": {"name": "Daily Mail", "url": "https:\/\/www.dailymail.co.uk"}}, {"title": "Bomb squad called and two held after suspicious device found in car in Luton", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMicGh0dHBzOi8vbmV3cy5za3kuY29tL3N0b3J5L2JvbWItc3F1YWQtY2FsbGVkLWFuZC10d28taGVsZC1hZnRlci1zdXNwaWNpb3VzLWRldmljZS1mb3VuZC1pbi1jYXItaW4tbHV0b24tMTE5NTA3ODfSAXRodHRwczovL25ld3Muc2t5LmNvbS9zdG9yeS9hbXAvYm9tYi1zcXVhZC1jYWxsZWQtYW5kLXR3by1oZWxkLWFmdGVyLXN1c3BpY2lvdXMtZGV2aWNlLWZvdW5kLWluLWNhci1pbi1sdXRvbi0xMTk1MDc4Nw?oc=5", "image": None, "publishedAt": "2020-03-06 10:22:00 UTC", "source": {"name": "Sky News", "url": "https:\/\/news.sky.com"}}, {"title": "Boris Johnson's government has already spent \u00a34.4bn on Brexit preparations, new figures reveal", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMib2h0dHBzOi8vd3d3LmluZGVwZW5kZW50LmNvLnVrL25ld3MvdWsvcG9saXRpY3MvYnJleGl0LWNvc3QtYm9yaXMtam9obnNvbi1sZWF2ZS1ldS1ib3JkZXItY29udHJvbHMtYTkzNzgwNjYuaHRtbNIBc2h0dHBzOi8vd3d3LmluZGVwZW5kZW50LmNvLnVrL25ld3MvdWsvcG9saXRpY3MvYnJleGl0LWNvc3QtYm9yaXMtam9obnNvbi1sZWF2ZS1ldS1ib3JkZXItY29udHJvbHMtYTkzNzgwNjYuaHRtbD9hbXA?oc=5", "image": None, "publishedAt": "2020-03-06 07:04:00 UTC", "source": {"name": "The Independent", "url": "https:\/\/www.independent.co.uk"}}, {"title": "Mum goes days without food in icy cold home and struggles sending son to \u00a31 playgroup", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiSWh0dHBzOi8vd3d3Lm1pcnJvci5jby51ay9uZXdzL3VrLW5ld3MvbXVtLWdvZXMtZGF5cy13aXRob3V0LWZvb2QtMjE2NDE5NTPSAU1odHRwczovL3d3dy5taXJyb3IuY28udWsvbmV3cy91ay1uZXdzL211bS1nb2VzLWRheXMtd2l0aG91dC1mb29kLTIxNjQxOTUzLmFtcA?oc=5", "image": None, "publishedAt": "2020-03-06 10:03:00 UTC", "source": {"name": "Mirror Online", "url": "https:\/\/www.mirror.co.uk"}}, {"title": "Meghan Markle sends Twitter into meltdown as viewers think she \u2018pushed\u2019 Harry out the way", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMid2h0dHBzOi8vd3d3LmV4cHJlc3MuY28udWsvbmV3cy9yb3lhbC8xMjUxNjA0L21lZ2hhbi1tYXJrbGUtcHJpbmNlLWhhcnJ5LWR1Y2hlc3MtcHVzaGVzLWR1a2UtdXByb2FyLXVrLW5ld3Mtcm95YWwtZmFtaWx50gF7aHR0cHM6Ly93d3cuZXhwcmVzcy5jby51ay9uZXdzL3JveWFsLzEyNTE2MDQvbWVnaGFuLW1hcmtsZS1wcmluY2UtaGFycnktZHVjaGVzcy1wdXNoZXMtZHVrZS11cHJvYXItdWstbmV3cy1yb3lhbC1mYW1pbHkvYW1w?oc=5", "image": None, "publishedAt": "2020-03-06 04:47:00 UTC", "source": {"name": "Express", "url": "https:\/\/www.express.co.uk"}}, {"title": "Supermarket rejects minister's food supplies claim", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiLGh0dHBzOi8vd3d3LmJiYy5jby51ay9uZXdzL2J1c2luZXNzLTUxNzY5MTg00gEwaHR0cHM6Ly93d3cuYmJjLmNvLnVrL25ld3MvYW1wL2J1c2luZXNzLTUxNzY5MTg0?oc=5", "image": None, "publishedAt": "2020-03-06 11:26:02 UTC", "source": {"name": "BBC News", "url": "https:\/\/www.bbc.co.uk"}}, {"title": "Coronavirus news", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMieGh0dHBzOi8vd3d3LmluZGVwZW5kZW50LmNvLnVrL25ld3MvaGVhbHRoL2Nvcm9uYXZpcnVzLW5ld3MtbGl2ZS1zeW1wdG9tcy1jb3ZpZC0xOS11ay11cy1pdGFseS1jYXNlcy1sYXRlc3QtYTkzODA1MjYuaHRtbNIBfGh0dHBzOi8vd3d3LmluZGVwZW5kZW50LmNvLnVrL25ld3MvaGVhbHRoL2Nvcm9uYXZpcnVzLW5ld3MtbGl2ZS1zeW1wdG9tcy1jb3ZpZC0xOS11ay11cy1pdGFseS1jYXNlcy1sYXRlc3QtYTkzODA1MjYuaHRtbD9hbXA?oc=5", "image": None, "publishedAt": "2020-03-06 09:18:00 UTC", "source": {"name": "The Independent", "url": "https:\/\/www.independent.co.uk"}}, {"title": "Amber Rudd hits out at 'rude' Oxford students after talk cancelled", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMicWh0dHBzOi8vd3d3LnRoZWd1YXJkaWFuLmNvbS9wb2xpdGljcy8yMDIwL21hci8wNi9hbWJlci1ydWRkLWhpdHMtb3V0LWF0LXJ1ZGUtb3hmb3JkLXN0dWRlbnRzLWFmdGVyLXRhbGstY2FuY2VsbGVk0gFxaHR0cHM6Ly9hbXAudGhlZ3VhcmRpYW4uY29tL3BvbGl0aWNzLzIwMjAvbWFyLzA2L2FtYmVyLXJ1ZGQtaGl0cy1vdXQtYXQtcnVkZS1veGZvcmQtc3R1ZGVudHMtYWZ0ZXItdGFsay1jYW5jZWxsZWQ?oc=5", "image": None, "publishedAt": "2020-03-06 10:16:09 UTC", "source": {"name": "The Guardian", "url": "https:\/\/www.theguardian.com"}}]} topics_success_response = {"timestamp": 1583482937, "articleCount": 10, "articles": [ {"title": "A triple folding phone? Hands-on with TCL's working DragonHinge prototype", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiYGh0dHBzOi8vd3d3LmNuZXQuY29tL25ld3MvdHJpcGxlLWZvbGRpbmctcGhvbmUtaGFuZHMtb24td2l0aC10Y2xzLXdvcmtpbmctZHJhZ29uaGluZ2UtcHJvdG90eXBlL9IBa2h0dHBzOi8vd3d3LmNuZXQuY29tL2dvb2dsZS1hbXAvbmV3cy90cmlwbGUtZm9sZGluZy1waG9uZS1oYW5kcy1vbi13aXRoLXRjbHMtd29ya2luZy1kcmFnb25oaW5nZS1wcm90b3R5cGUv?oc=5", "image": None, "publishedAt": "2020-03-06 05:22:00 UTC", "source": {"name": "CNET", "url": "https:\/\/www.cnet.com"}}, {"title": "Windows 10 April 2020 Update", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiK2h0dHBzOi8vd3d3LnlvdXR1YmUuY29tL3dhdGNoP3Y9S2g5TFZxZFhiTTTSAQA?oc=5", "image": None, "publishedAt": "2020-03-06 04:37:55 UTC", "source": {"name": "Windows Central", "url": "https:\/\/www.youtube.com"}}, {"title": "Miyamoto Says The Success Of The Switch Was All Thanks To The \"Good Timing\" Of Its Release", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMigQFodHRwOi8vd3d3Lm5pbnRlbmRvbGlmZS5jb20vbmV3cy8yMDIwLzAzL21peWFtb3RvX3NheXNfdGhlX3N1Y2Nlc3Nfb2ZfdGhlX3N3aXRjaF93YXNfYWxsX3RoYW5rc190b190aGVfZ29vZF90aW1pbmdfb2ZfaXRzX3JlbGVhc2XSAQA?oc=5", "image": None, "publishedAt": "2020-03-06 03:05:00 UTC", "source": {"name": "Nintendo Life", "url": "http:\/\/www.nintendolife.com"}}, {"title": "How to livestream the Oppo Find X2 and Oppo Smartwatch launch [Video]", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiOmh0dHBzOi8vOXRvNWdvb2dsZS5jb20vMjAyMC8wMy8wNS9vcHBvLWZpbmQteDItbGl2ZXN0cmVhbS_SAT5odHRwczovLzl0bzVnb29nbGUuY29tLzIwMjAvMDMvMDUvb3Bwby1maW5kLXgyLWxpdmVzdHJlYW0vYW1wLw?oc=5", "image": None, "publishedAt": "2020-03-06 03:00:00 UTC", "source": {"name": "9to5Google", "url": "https:\/\/9to5google.com"}}, {"title": "Xbox Series X and PS5 graphics hardware will finally kiss goodbye to weird-looking hair", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMicWh0dHBzOi8vd3d3LmdhbWVzcmFkYXIuY29tL3hib3gtc2VyaWVzLXhzLTEyLXRlcmFmbG9wLWdwdS1tZWFucy13ZS1jYW4tZmluYWxseS1zYXktZ29vZGJ5ZS10by13ZWlyZC1sb29raW5nLWhhaXIv0gF1aHR0cHM6Ly93d3cuZ2FtZXNyYWRhci5jb20vYW1wL3hib3gtc2VyaWVzLXhzLTEyLXRlcmFmbG9wLWdwdS1tZWFucy13ZS1jYW4tZmluYWxseS1zYXktZ29vZGJ5ZS10by13ZWlyZC1sb29raW5nLWhhaXIv?oc=5", "image": None, "publishedAt": "2020-03-06 02:44:00 UTC", "source": {"name": "GamesRadar+", "url": "https:\/\/www.gamesradar.com"}}, {"title": "Santa Clara County Asks Apple, Google and Others to Cancel Large In-Person Meetings and Conferences", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiVGh0dHBzOi8vd3d3Lm1hY3J1bW9ycy5jb20vMjAyMC8wMy8wNS9zYW50YS1jbGFyYS1jb3VudHktY292aWQtMTktY2FuY2VsLWNvbmZlcmVuY2VzL9IBWGh0dHBzOi8vd3d3Lm1hY3J1bW9ycy5jb20vMjAyMC8wMy8wNS9zYW50YS1jbGFyYS1jb3VudHktY292aWQtMTktY2FuY2VsLWNvbmZlcmVuY2VzL2FtcC8?oc=5", "image": None, "publishedAt": "2020-03-06 02:22:00 UTC", "source": {"name": "MacRumors", "url": "https:\/\/www.macrumors.com"}}, {"title": "Porsche Explains Why The New 911 Turbo S Is Way More Powerful", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiRGh0dHBzOi8vd3d3Lm1vdG9yMS5jb20vbmV3cy80MDI2MTYvcG9yc2NoZS05MTEtdHVyYm8tcG93ZXItaW5jcmVhc2Uv0gEA?oc=5", "image": None, "publishedAt": "2020-03-06 02:00:58 UTC", "source": {"name": "Motor1 ", "url": "https:\/\/www.motor1.com"}}, {"title": "Twitch Streamer Suspended After Accidentally Firing Real Gun At His Monitor", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiVWh0dHBzOi8va290YWt1LmNvbS90d2l0Y2gtc3RyZWFtZXItc3VzcGVuZGVkLWFmdGVyLWFjY2lkZW50YWxseS1maXJpbmctcmVhLTE4NDIxMzUyNjfSAVlodHRwczovL2tvdGFrdS5jb20vdHdpdGNoLXN0cmVhbWVyLXN1c3BlbmRlZC1hZnRlci1hY2NpZGVudGFsbHktZmlyaW5nLXJlYS0xODQyMTM1MjY3L2FtcA?oc=5", "image": None, "publishedAt": "2020-03-06 02:00:00 UTC", "source": {"name": "Kotaku", "url": "https:\/\/kotaku.com"}}, {"title": "Pokemon Mystery Dungeon: Rescue Team DX Review", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiYWh0dHBzOi8vd3d3LmdhbWVzcG90LmNvbS9yZXZpZXdzL3Bva2Vtb24tbXlzdGVyeS1kdW5nZW9uLXJlc2N1ZS10ZWFtLWR4LXJldmlldy1iZXR0LzE5MDAtNjQxNzQyNC_SAWVodHRwczovL3d3dy5nYW1lc3BvdC5jb20vYW1wLXJldmlld3MvcG9rZW1vbi1teXN0ZXJ5LWR1bmdlb24tcmVzY3VlLXRlYW0tZHgtcmV2aWV3LWJldHQvMTkwMC02NDE3NDI0Lw?oc=5", "image": None, "publishedAt": "2020-03-06 00:59:00 UTC", "source": {"name": "GameSpot", "url": "https:\/\/www.gamespot.com"}}, {"title": "Apple Issues New Warning Affecting Millions Of iPhone Users", "description": "", "url": "https:\/\/news.google.com\/__i\/rss\/rd\/articles\/CBMiZGh0dHBzOi8vd3d3LmZvcmJlcy5jb20vc2l0ZXMvZ29yZG9ua2VsbHkvMjAyMC8wMy8wNS9hcHBsZS1pcGhvbmUtcmVwYWlyLXdhcm5pbmctbmV3LWlwaG9uZS11cGdyYWRlcy_SAWhodHRwczovL3d3dy5mb3JiZXMuY29tL3NpdGVzL2dvcmRvbmtlbGx5LzIwMjAvMDMvMDUvYXBwbGUtaXBob25lLXJlcGFpci13YXJuaW5nLW5ldy1pcGhvbmUtdXBncmFkZXMvYW1wLw?oc=5", "image": None, "publishedAt": "2020-03-06 00:30:00 UTC", "source": {"name": "Forbes", "url": "https:\/\/www.forbes.com"}}]}
#Vimos que n = 42 é legal. E 42 = n? """Não é legal porque estariamos forçando a maquina a reservar o espaço 42 para N. No caso de um IDE, ele não permitirá, o nome da variável terá erro. Não pode ser númérica e nem começar com número.""" #Ou x = y = 1? """Se for apenas parâmetros simples, é correto. Listas, tuplas e dicionários não é permitido""" #Em algumas linguagens, cada instrução termina em um ponto e vírgula ;. O que #acontece se você puser um ponto e vírgula no fim de uma instrução no Python? """No python serve como separação de código. Isto é, quando começa e termina outro código na mesma linha.Este comando é opcional.""" #E se puser um ponto no fim de uma instrução? """O ponto é um método. Isto é, podemos modificar a variável especificada indicando seu nome, ponto(.) e o que desejamos.""" #Em notação matemática é possível multiplicar x e y desta forma: xy. O que acontece #se você tentar fazer o mesmo no Python? """Ele entenderá que 'xy' é um objeto e não fará multiplicação."""
APP_DIRECTORY_NAME = "APP" SRC_DIRECTORY_NAME = "src" TEMPLATES_DIRECTORY_NAME = "templates" # Production React Js Template files having Github Repository Links REACTJS_TEMPLATES_URLS_DICT = { "package.json-tpl": "https://raw.githubusercontent.com/Jitensid/django-webpack-dev-server/main/assets/reactjs/package.json-tpl", "webpack.config.js-tpl": "https://raw.githubusercontent.com/Jitensid/django-webpack-dev-server/main/assets/reactjs/webpack.config.js-tpl", "babel.config.json-tpl": "https://raw.githubusercontent.com/Jitensid/django-webpack-dev-server/main/assets/reactjs/babel.config.json-tpl", "App.js-tpl": "https://raw.githubusercontent.com/Jitensid/django-webpack-dev-server/main/assets/reactjs/App.js-tpl", "index.js-tpl": "https://raw.githubusercontent.com/Jitensid/django-webpack-dev-server/main/assets/reactjs/index.js-tpl", "App.css-tpl": "https://raw.githubusercontent.com/Jitensid/django-webpack-dev-server/main/assets/reactjs/App.css-tpl", "reactlogo.png": "https://raw.githubusercontent.com/Jitensid/django-webpack-dev-server/main/assets/reactjs/reactlogo.png", } # Template files specific to react js configuration PROD_REACTJS_TEMPLATE_FILES = [ ( APP_DIRECTORY_NAME, "package.json", REACTJS_TEMPLATES_URLS_DICT["package.json-tpl"], ), ( APP_DIRECTORY_NAME, "webpack.config.js", REACTJS_TEMPLATES_URLS_DICT["webpack.config.js-tpl"], ), ( APP_DIRECTORY_NAME, "babel.config.json", REACTJS_TEMPLATES_URLS_DICT["babel.config.json-tpl"], ), (SRC_DIRECTORY_NAME, "App.js", REACTJS_TEMPLATES_URLS_DICT["App.js-tpl"]), (SRC_DIRECTORY_NAME, "index.js", REACTJS_TEMPLATES_URLS_DICT["index.js-tpl"]), (SRC_DIRECTORY_NAME, "App.css", REACTJS_TEMPLATES_URLS_DICT["App.css-tpl"]), (SRC_DIRECTORY_NAME, "reactlogo.png", REACTJS_TEMPLATES_URLS_DICT["reactlogo.png"]), ]
# SPDX-License-Identifier: GPL-3.0-only def make_definitions(f, ecpp, bcpp, all_enums, all_bitfields, all_structs_arranged): f.write("// SPDX-License-Identifier: GPL-3.0-only\n\n// This file was auto-generated.\n// If you want to edit this, edit the .json definitions and rerun the generator script, instead.\n\n") header_name = "INVADER__TAG__HEK__CLASS__DEFINITION_HPP" f.write("#ifndef {}\n".format(header_name)) f.write("#define {}\n\n".format(header_name)) f.write("#include \"../../hek/data_type.hpp\"\n\n") f.write("namespace Invader::HEK {\n") ecpp.write("// SPDX-License-Identifier: GPL-3.0-only\n\n// This file was auto-generated.\n// If you want to edit this, edit the .json definitions and rerun the generator script, instead.\n\n") ecpp.write("#include <cstring>\n") ecpp.write("#include <invader/printf.hpp>\n") ecpp.write("#include <invader/tag/hek/definition.hpp>\n\n") ecpp.write("namespace Invader::HEK {\n") bcpp.write("// SPDX-License-Identifier: GPL-3.0-only\n\n// This file was auto-generated.\n// If you want to edit this, edit the .json definitions and rerun the generator script, instead.\n\n") bcpp.write("#include <cstring>\n") bcpp.write("#include <cctype>\n") bcpp.write("#include <invader/printf.hpp>\n") bcpp.write("#include <invader/tag/hek/definition.hpp>\n\n") bcpp.write("namespace Invader::HEK {\n") # Convert PascalCase to UPPER_SNAKE_CASE def format_enum(prefix, value): return "{}_{}".format(prefix,value.upper()).replace("-", "_") def format_enum_str(value): return value.lower() def write_enum(name, fields, fields_pretty, type, cpp): f.write(" enum {} : {} {{\n".format(name, type)) prefix = "" name_to_consider = name.replace("HUD", "Hud").replace("UI", "Ui").replace("GBX", "Gbx") for i in name_to_consider: if prefix != "" and i.isupper(): prefix += "_" prefix += i.upper() for n in range(0,len(fields)): f.write(" {}{},\n".format(format_enum(prefix, fields[n]), " = static_cast<{}>(1) << {}".format(type, n) if (cpp == bcpp) else "")) f.write(" {}\n".format(format_enum(prefix, "enum_count"))) f.write(" };\n") f.write(" /**\n") f.write(" * Get the string representation of the enum.\n") f.write(" * @param value value of the enum\n") f.write(" * @return string representation of the enum\n") f.write(" */\n") f.write(" const char *{}_to_string({} value);\n".format(name, name)) cpp.write(" const char *{}_to_string({} value) {{\n".format(name, name)) cpp.write(" switch(value) {\n") for n in fields: cpp.write(" case {}::{}:\n".format(name, format_enum(prefix, n))) cpp.write(" return \"{}\";\n".format(format_enum_str(n))) cpp.write(" default:\n") cpp.write(" throw std::exception();\n") cpp.write(" }\n") cpp.write(" }\n") f.write(" /**\n") f.write(" * Get the pretty string representation of the enum.\n") f.write(" * @param value value of the enum\n") f.write(" * @return pretty string representation of the enum\n") f.write(" */\n") f.write(" const char *{}_to_string_pretty({} value);\n".format(name, name)) cpp.write(" const char *{}_to_string_pretty({} value) {{\n".format(name, name)) cpp.write(" switch(value) {\n") for n in range(0,len(fields)): cpp.write(" case {}::{}:\n".format(name, format_enum(prefix, fields[n]))) cpp.write(" return \"{}\";\n".format(fields_pretty[n])) cpp.write(" default:\n") cpp.write(" throw std::exception();\n") cpp.write(" }\n") cpp.write(" }\n") f.write(" /**\n") f.write(" * Get the enum value from the string.\n") f.write(" * @param value value of the enum as a string\n") f.write(" * @return value of the enum\n") f.write(" */\n") f.write(" {} {}_from_string(const char *value);\n".format(name, name)) cpp.write(" {} {}_from_string(const char *value) {{\n".format(name, name)) for n in range(0,len(fields)): cpp.write(" {}if(std::strcmp(value, \"{}\") == 0) {{\n".format("" if n == 0 else "else ", format_enum_str(fields[n]))) cpp.write(" return {}::{};\n".format(name, format_enum(prefix, fields[n]))) cpp.write(" }\n") cpp.write(" else {\n") cpp.write(" throw std::exception();\n") cpp.write(" }\n") cpp.write(" }\n") f.write("\n") # Write enums at the top first, then bitfields for e in all_enums: write_enum(e["name"], e["options_formatted"], e["options"], "TagEnum", ecpp) for b in all_bitfields: f.write(" using {} = std::uint{}_t;\n".format(b["name"], b["width"])) write_enum("{}Flag".format(b["name"]), b["fields_formatted"], b["fields"], "std::uint{}_t".format(b["width"]), bcpp) ecpp.write("}\n") bcpp.write("}\n") # Now the hard part padding_present = False for s in all_structs_arranged: f.write(" ENDIAN_TEMPLATE(EndianType) struct {} {}{{\n".format(s["name"], ": {}<EndianType> ".format(s["inherits"]) if "inherits" in s else "")) for n in s["fields"]: type_to_write = n["type"] if type_to_write.startswith("int") or type_to_write.startswith("uint"): type_to_write = "std::{}_t".format(type_to_write) elif type_to_write == "pad": f.write(" PAD(0x{:X});\n".format(n["size"])) continue if "flagged" in n and n["flagged"]: type_to_write = "FlaggedInt<{}>".format(type_to_write) name = n["member_name"] if "count" in n: name = "{}[{}]".format(name, n["count"]) format_to_use = None default_endian = "EndianType" if "endian" in n: if n["endian"] == "little": default_endian = "LittleEndian" elif n["endian"] == "big": default_endian = "BigEndian" elif n["endian"] == None: default_endian = None if type_to_write == "TagReflexive": f.write(" TagReflexive<{}, {}> {};\n".format(default_endian, n["struct"], name)) else: if default_endian is None: format_to_use = "{}" elif "compound" in n and n["compound"]: format_to_use = "{{}}<{}>".format(default_endian) else: format_to_use = "{}<{{}}>".format(default_endian) if "bounds" in n and n["bounds"]: f.write(" Bounds<{}> {};\n".format(format_to_use.format(type_to_write), name)) else: f.write(" {} {};\n".format(format_to_use.format(type_to_write), name)) # Make sure we have all of the structs we depend on, too depended_structs = [] dependency = s padding_present = False while dependency is not None: depended_structs.append(dependency) if not padding_present: for n in dependency["fields"]: if n["type"] == "pad": padding_present = True break if "inherits" in dependency: dependency_name = dependency["inherits"] dependency = None for ds in all_structs_arranged: if ds["name"] == dependency_name: dependency = ds break else: break # And we can't forget the copy part f.write(" ENDIAN_TEMPLATE(NewEndian) operator {}<NewEndian>() const {{\n".format(s["name"])) f.write(" {}<NewEndian> copy{};\n".format(s["name"], " = {}" if padding_present else "")) for ds in depended_structs: for n in ds["fields"]: if n["type"] == "pad": continue else: f.write(" {}({});\n".format("COPY_THIS_ARRAY" if "count" in n else "COPY_THIS", n["member_name"])) f.write(" return copy;\n") f.write(" }\n") f.write(" };\n") f.write(" static_assert(sizeof({}<NativeEndian>) == 0x{:X});\n\n".format(s["name"], s["size"])) f.write("}\n\n") f.write("#endif\n")
def run_gbrt(d, r, t, ne=0, lr=0.1, md=3, trs=0, frs=0, mf=7): X_train, X_test, y_train, y_test = train_test_split( np.append(r, d, 1), t, random_state=trs) gbrt = GradientBoostingClassifier( n_estimators=ne, learning_rate=lr, max_depth=md, max_features=mf, random_state=frs) gbrt.fit(X_train[:, 1:], y_train) print("Training score: {:.3f}".format(gbrt.score(X_train[:, 1:], y_train))) print("Test score: {:.3f}".format(gbrt.score(X_test[:, 1:], y_test))) plot_feature_importances(gbrt) preds = gbrt.predict(X_test[:, 1:]) print(preds) print('Predictions: {} {}'.format(type(preds), preds.shape)) dec = gbrt.decision_function(X_test[:, 1:]) print('Decision function: {} {}'.format(type(dec), dec.shape)) print(dec[:3]) probs = gbrt.predict_proba(X_test[:, 1:]) print('Probabilities: {} {}'.format(type(probs), probs.shape)) print(probs[:3]) outcomes = np.append(X_test, np.reshape(preds, (-1, 1)), 1) print(outcomes[:6])
class Solution: def buildArray(self, target: List[int], n: int) -> List[str]: res = [] n = min(max(target), n) for i in range(1, n+1): if i in target: res += ["Push"] else: res += ["Push","Pop"] return res
expected_output = { "vrf": { "default": { "source_address": "172.16.10.13", "path": { "172.16.121.10 BRI0": { "neighbor_address": "172.16.121.10", "neighbor_host": "sj1.cisco.com", "distance_preferred_lookup": True, "recursion_count": 0, "interface_name": "BRI0", "originated_topology": "ipv4 unicast base", "lookup_topology": "ipv4 multicast base", "route_mask": "172.16.0.0/16", "table_type": "unicast", } }, "source_host": "host1", } } }
a = True b = False if a == b: print(1) else: print(0)
#!/usr/bin/env python3 i = 1 for x in range(-10000, 10000): for y in range(-10000, 10000): if (abs(x)+abs(y)) < 100: i += 1 print(i)
class BaseChild: payload = { "patient": { "lastName": "Deeererederepwswdwewwdw", "firstName": "Allakirillohldldwwwlflrereeeded", "middleName": "Ballerffffff", "birthDate": "2011-05-29", "sex": True, "isAutoPhone": True }, "linkType": "6", } def __init__(self): pass def post_info(self, payload): return payload
ENTRY_POINT = 'smallest_change' #[PROMPT] def smallest_change(arr): """ Given an array arr of integers, find the minimum number of elements that need to be changed to make the array palindromic. A palindromic array is an array that is read the same backwards and forwards. In one change, you can change one element to any other element. For example: smallest_change([1,2,3,5,4,7,9,6]) == 4 smallest_change([1, 2, 3, 4, 3, 2, 2]) == 1 smallest_change([1, 2, 3, 2, 1]) == 0 """ #[SOLUTION] ans = 0 for i in range(len(arr) // 2): if arr[i] != arr[len(arr) - i - 1]: ans += 1 return ans #[CHECK] def check(candidate): # Check some simple cases assert candidate([1,2,3,5,4,7,9,6]) == 4 assert candidate([1, 2, 3, 4, 3, 2, 2]) == 1 assert candidate([1, 4, 2]) == 1 assert candidate([1, 4, 4, 2]) == 1 # Check some edge cases that are easy to work out by hand. assert candidate([1, 2, 3, 2, 1]) == 0 assert candidate([3, 1, 1, 3]) == 0 assert candidate([1]) == 0 assert candidate([0, 1]) == 1
# Write a dictionary or list to hdfs best_params = { "Key1": 123, "Key2": "hello" } save_path = "hdfs://nameservice1/user/duc.nguyenv3/projects/01_lgbm_modeling/data/output/best_params.json" sdf = ( spark .sparkContext .parallelize([best_params]) .toDF() .coalesce(1) .write .mode("overwrite") .json(save_path) ) # Load the dict to SparkDF json_df = spark.read.json(save_path)
""" Test module for learning python packaging. """ NAME = "pybinson"
''' Title : sWAP cASE Subdomain : Strings Domain : Python Author : Kalpak Seal Created : 29 September 2016 ''' __author__ = 'Kalpak Seal' inputString = raw_input() finalString = "" for i in range(0, len(inputString)): currentChar = inputString[i] if currentChar.islower() or currentChar.isupper(): finalString += currentChar.swapcase() else: finalString += currentChar print(finalString) ''' # Alternative One liner: print ''.join([i.lower() if i.isupper() else i.upper() for i in raw_input()]) '''
class Singleton(object): def __init__(self, func): self._func = func def Instance(self,*a,**k): try: return self._instance except AttributeError: self._instance = self._func(*a,**k) return self._instance def __call__(self): raise TypeError('Singletons must be accessed by `Instance`.') def __instancecheck__(self,inst): return isinstance(inst,self._func) @Singleton class App(object): def __init__(self, ): pass a= App.Instance() b=App.Instance() print(a is b)
FILE_TEMPLATE = "19C_{0:05d}.xml" header = """<?xml version="1.0" encoding="UTF-8" ?><marc:collection xmlns:marc="http://www.loc.gov/MARC21/slim" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd"> """ footer = "</marc:collection>\n" CHUNKSIZE = 1000 chunk = 1 records = [] with open("19C.xml", "r") as xmlblob: count = 0 records.append(xmlblob.next()) for rawline in xmlblob: line = rawline.decode("utf-8") if line.startswith("<marc:record>"): count += 1 if count == CHUNKSIZE: # store file print("Storing file - {0}".format(chunk)) with open(FILE_TEMPLATE.format(chunk), "w") as chunkfile: for item in records: chunkfile.write(item.encode("utf-8")) chunkfile.write(footer.encode("utf-8")) records = [header] chunk += 1 count = 0 records.append(line)
# # PySNMP MIB module BLUECOAT-AV-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BLUECOAT-AV-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:22:33 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, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection") blueCoatMgmt, = mibBuilder.importSymbols("BLUECOAT-MIB", "blueCoatMgmt") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") NotificationType, ObjectIdentity, Integer32, Counter32, Bits, ModuleIdentity, iso, Unsigned32, IpAddress, MibIdentifier, TimeTicks, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "ObjectIdentity", "Integer32", "Counter32", "Bits", "ModuleIdentity", "iso", "Unsigned32", "IpAddress", "MibIdentifier", "TimeTicks", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64") DateAndTime, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "DateAndTime", "TextualConvention", "DisplayString") blueCoatAvMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 3417, 2, 10)) if mibBuilder.loadTexts: blueCoatAvMib.setLastUpdated('0704160000Z') if mibBuilder.loadTexts: blueCoatAvMib.setOrganization('Blue Coat Systems, Inc.') blueCoatAvMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1)) blueCoatAvMibNotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 3417, 2, 10, 2)) blueCoatAvMibNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3)) avFilesScanned = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1, 1), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: avFilesScanned.setStatus('current') avVirusesDetected = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: avVirusesDetected.setStatus('current') avPatternVersion = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: avPatternVersion.setStatus('current') avPatternDateTime = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1, 4), DateAndTime()).setMaxAccess("readonly") if mibBuilder.loadTexts: avPatternDateTime.setStatus('current') avEngineVersion = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: avEngineVersion.setStatus('current') avVendorName = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1, 6), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: avVendorName.setStatus('current') avLicenseDaysRemaining = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: avLicenseDaysRemaining.setStatus('current') avPublishedFirmwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: avPublishedFirmwareVersion.setStatus('current') avInstalledFirmwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1, 9), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: avInstalledFirmwareVersion.setStatus('current') avSlowICAPConnections = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 1, 10), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: avSlowICAPConnections.setStatus('current') avUpdateFailureReason = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 2, 1), DisplayString()) if mibBuilder.loadTexts: avUpdateFailureReason.setStatus('current') avUrl = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 2, 2), DisplayString()) if mibBuilder.loadTexts: avUrl.setStatus('current') avVirusName = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 2, 3), DisplayString()) if mibBuilder.loadTexts: avVirusName.setStatus('current') avVirusDetails = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 2, 4), DisplayString()) if mibBuilder.loadTexts: avVirusDetails.setStatus('current') avErrorCode = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 2, 5), DisplayString()) if mibBuilder.loadTexts: avErrorCode.setStatus('current') avErrorDetails = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 2, 6), DisplayString()) if mibBuilder.loadTexts: avErrorDetails.setStatus('current') avPreviousFirmwareVersion = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 2, 7), DisplayString()) if mibBuilder.loadTexts: avPreviousFirmwareVersion.setStatus('current') avICTMWarningReason = MibScalar((1, 3, 6, 1, 4, 1, 3417, 2, 10, 2, 8), DisplayString()) if mibBuilder.loadTexts: avICTMWarningReason.setStatus('current') avAntivirusUpdateSuccess = NotificationType((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3, 1)).setObjects(("BLUECOAT-AV-MIB", "avVendorName"), ("BLUECOAT-AV-MIB", "avEngineVersion"), ("BLUECOAT-AV-MIB", "avPatternVersion"), ("BLUECOAT-AV-MIB", "avPatternDateTime")) if mibBuilder.loadTexts: avAntivirusUpdateSuccess.setStatus('current') avAntivirusUpdateFailed = NotificationType((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3, 2)).setObjects(("BLUECOAT-AV-MIB", "avUpdateFailureReason"), ("BLUECOAT-AV-MIB", "avVendorName"), ("BLUECOAT-AV-MIB", "avEngineVersion"), ("BLUECOAT-AV-MIB", "avPatternVersion"), ("BLUECOAT-AV-MIB", "avPatternDateTime")) if mibBuilder.loadTexts: avAntivirusUpdateFailed.setStatus('current') avVirusDetected = NotificationType((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3, 3)).setObjects(("BLUECOAT-AV-MIB", "avUrl"), ("BLUECOAT-AV-MIB", "avVirusName"), ("BLUECOAT-AV-MIB", "avVirusDetails")) if mibBuilder.loadTexts: avVirusDetected.setStatus('current') avFileServed = NotificationType((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3, 4)).setObjects(("BLUECOAT-AV-MIB", "avUrl"), ("BLUECOAT-AV-MIB", "avErrorCode"), ("BLUECOAT-AV-MIB", "avErrorDetails")) if mibBuilder.loadTexts: avFileServed.setStatus('current') avFileBlocked = NotificationType((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3, 5)).setObjects(("BLUECOAT-AV-MIB", "avUrl"), ("BLUECOAT-AV-MIB", "avErrorCode"), ("BLUECOAT-AV-MIB", "avErrorDetails")) if mibBuilder.loadTexts: avFileBlocked.setStatus('current') avNewFirmwareAvailable = NotificationType((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3, 6)).setObjects(("BLUECOAT-AV-MIB", "avInstalledFirmwareVersion"), ("BLUECOAT-AV-MIB", "avPublishedFirmwareVersion")) if mibBuilder.loadTexts: avNewFirmwareAvailable.setStatus('current') avFirmwareUpdateSuccess = NotificationType((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3, 7)).setObjects(("BLUECOAT-AV-MIB", "avPreviousFirmwareVersion"), ("BLUECOAT-AV-MIB", "avInstalledFirmwareVersion")) if mibBuilder.loadTexts: avFirmwareUpdateSuccess.setStatus('current') avFirmwareUpdateFailed = NotificationType((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3, 8)).setObjects(("BLUECOAT-AV-MIB", "avInstalledFirmwareVersion"), ("BLUECOAT-AV-MIB", "avPublishedFirmwareVersion"), ("BLUECOAT-AV-MIB", "avUpdateFailureReason")) if mibBuilder.loadTexts: avFirmwareUpdateFailed.setStatus('current') avAntivirusLicenseWarning = NotificationType((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3, 9)).setObjects(("BLUECOAT-AV-MIB", "avVendorName"), ("BLUECOAT-AV-MIB", "avLicenseDaysRemaining")) if mibBuilder.loadTexts: avAntivirusLicenseWarning.setStatus('current') avICTMWarning = NotificationType((1, 3, 6, 1, 4, 1, 3417, 2, 10, 3, 10)).setObjects(("BLUECOAT-AV-MIB", "avICTMWarningReason"), ("BLUECOAT-AV-MIB", "avSlowICAPConnections")) if mibBuilder.loadTexts: avICTMWarning.setStatus('current') mibBuilder.exportSymbols("BLUECOAT-AV-MIB", avErrorDetails=avErrorDetails, blueCoatAvMib=blueCoatAvMib, avPatternDateTime=avPatternDateTime, PYSNMP_MODULE_ID=blueCoatAvMib, avPatternVersion=avPatternVersion, avVendorName=avVendorName, avUrl=avUrl, avFileBlocked=avFileBlocked, avPublishedFirmwareVersion=avPublishedFirmwareVersion, avFirmwareUpdateSuccess=avFirmwareUpdateSuccess, avFirmwareUpdateFailed=avFirmwareUpdateFailed, blueCoatAvMibNotifications=blueCoatAvMibNotifications, avLicenseDaysRemaining=avLicenseDaysRemaining, avFilesScanned=avFilesScanned, avUpdateFailureReason=avUpdateFailureReason, blueCoatAvMibObjects=blueCoatAvMibObjects, blueCoatAvMibNotificationObjects=blueCoatAvMibNotificationObjects, avEngineVersion=avEngineVersion, avVirusDetected=avVirusDetected, avICTMWarning=avICTMWarning, avAntivirusUpdateFailed=avAntivirusUpdateFailed, avErrorCode=avErrorCode, avAntivirusUpdateSuccess=avAntivirusUpdateSuccess, avVirusName=avVirusName, avSlowICAPConnections=avSlowICAPConnections, avAntivirusLicenseWarning=avAntivirusLicenseWarning, avFileServed=avFileServed, avInstalledFirmwareVersion=avInstalledFirmwareVersion, avICTMWarningReason=avICTMWarningReason, avVirusesDetected=avVirusesDetected, avPreviousFirmwareVersion=avPreviousFirmwareVersion, avVirusDetails=avVirusDetails, avNewFirmwareAvailable=avNewFirmwareAvailable)
""" A set of helpers functions and constants for supporting the bot engine. """ _LANG_SET = { 'ar': ' Arabic', 'bg': 'Bulgarian', 'ca': 'Catalan', 'zh-CHS': 'Chinese (Simplified)', 'zh-CHT': 'Chinese (Traditional)', 'cs': 'Czech', 'da': 'Danish', 'nl': 'Dutch', 'en': 'Inglês', 'et': 'Estonian', 'fi': 'Finnish', 'fr': 'Francês', 'de': 'Alemão', 'el': 'Greek', 'ht': 'Haitian Creole', 'he': 'Hebrew', 'hi': 'Hindi', 'hu': 'Hungarian', 'id': 'Indonesian', 'it': 'Italian', 'ja': 'Japanese', 'ko': 'Korean', 'lv': 'Latvian', 'lt': 'Lithuanian', 'mww': 'Hmong Daw', 'no': 'Norwegian', 'pl': 'Polish', 'pt': 'Português', 'ro': 'Romanian', 'ru': 'Russian', 'sk': 'Slovak', 'sl': 'Slovenian', 'es': 'Spanish', 'sv': 'Swedish', 'th': 'Thai', 'tr': 'Turkish', 'uk': 'Ukrainian', 'vi': 'Vietnamese', } def get_lang_name(lang_id): """ Returns the name of a language by its id. """ return _LANG_SET[lang_id] def start_rank(): """ Create the structure for ranking with the languages available for translating.""" ocurrence_dict = {lang_id: 1 for lang_id, name in _LANG_SET.items()} ranking = list([lang_id for lang_id, name in _LANG_SET.items()]) return ranking, ocurrence_dict def rating_calc(item, ocurrences, last_ocurrences, total_ocurrences): """ Calculates the rating of the target language. """ rating = ocurrences / total_ocurrences if item in last_ocurrences: rating *= 2 if last_ocurrences and item == last_ocurrences[-1]: rating *= 4 return rating
def notas(* n, sit=False): """[Função para analisar notas e situações de cários alunos] Args: n (float): [Uma ou mais notas dos alunos (aceita várias)] sit (bool, optional): [Indica se deve ou não adicionar a situação]. Defaults to False. Returns: [dict]: [Dicionário com várias informações sobre a situação da turma] """ r = dict() r['total'] = len(n) r['maior'] = max(n) r['menor'] = min(n) r['média'] = sum(n)/len(n) if sit: if r['média'] >= 7: r['situação'] = 'BOA' elif r['média'] >= 5: r['situação'] = 'RAZOÁVEL' else: r['situação'] = 'RUIM' return r resp = notas(5.5, 9.5, 10, 6.5, sit=True) print(resp)
class PartialFillHandlingEnum: PARTIAL_FILL_UNSET = 0 PARTIAL_FILL_HANDLING_REDUCE_QUANTITY = 1 PARTIAL_FILL_HANDLING_IMMEDIATE_CANCEL = 2
'''Exercício Python 015: Escreva um programa que pergunte a quantidade de Km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado. ''' msg = f'{"Aluguel de Veículos":^30}' print('*'*len(msg)) print(msg) print('*'*len(msg)) dias_alugado = int(input('\nInsira a quantidade de dias que o veículo foi alugado: ')) km_percorridos = float(input('Quantos quilômetros foram percorridos? ')) valor_a_pagar = (dias_alugado * 60) + (km_percorridos * 0.15) print(f'\n O valor a ser pago será de R${valor_a_pagar:.2f}.')
SKILL_SAMPLE_TYPES = ( ("dc", "DC"), ("mod", "Modifier"), )
def emulate(instructions): # did we already run a specific instruction? previous = [False for _ in range(len(instructions))] acc, i = 0, 0 while i < len(instructions): # infinite loop detected if previous[i]: return None previous[i] = True instr, value = instructions[i] # emulate if instr == "acc": acc += value elif instr == "jmp": i += value continue i += 1 return acc instructions = [] with open("input.txt", "r") as file: for line in file.readlines(): instructions.append([line[:3], int(line[4:])]) # keep flipping instructions until we find one that doesn't end up in an infinite loop for i in range(len(instructions)): # we only care about jmp's and nop's if instructions[i][0] == "acc": continue # keep a copy of the original instruction original = instructions[i][0] if instructions[i][0] == "jmp": instructions[i][0] = "nop" elif instructions[i][0] == "nop": instructions[i][0] = "jmp" result = emulate(instructions) # we found code that runs if result != None: print(result) break # restore to original instructions[i][0] = original
flowerpot_price = 4.00 flower_seeds_price = 1.00 soil_price = 5.00 tax_rate = 0.06 number_of_pots = int(input('How many flowerpots? ')) number_of_seeds = int(input('How many packs of seeds? ')) number_of_bags = int(input('How many bags of soil? ')) cost_of_items = (number_of_pots * flowerpot_price) + (number_of_seeds * flower_seeds_price) + (number_of_bags * soil_price) print(cost_of_items)
class Field: cells = () def __init__(self, w, h): print('Game Field Created!')
# Given an input string (s) and a pattern (p), # implement regular expression matching with support for '.' and '*'. # '.' Matches any single character. # '*' Matches zero or more of the preceding element. # The matching should cover the entire input string (not partial). # Note: # s could be empty and contains only lowercase letters a-z. # p could be empty and contains only lowercase letters a-z, and characters like . or *. # Example 1: # Input: # s = "aa" # p = "a" # Output: false # Explanation: "a" does not match the entire string "aa". # Example 2: # Input: # s = "aa" # p = "a*" # Output: true # Explanation: '*' means zero or more of the preceding element, 'a'. # Therefore, by repeating 'a' once, it becomes "aa". # Example 3: # Input: # s = "ab" # p = ".*" # Output: true # Explanation: ".*" means "zero or more (*) of any character (.)". # Example 4: # Input: # s = "aab" # p = "c*a*b" # Output: true # Explanation: c can be repeated 0 times, a can be repeated 1 time. # Therefore, it matches "aab". # Example 5: # Input: # s = "mississippi" # p = "mis*is*p*." # Output: false class Solution: def isMatch(self, s: str, p: str) -> bool: # M1.递归 if not p: return not s first_match = bool(s) and p[0] in {s[0], '.'} if len(p) >= 2 and p[1] == '*': return (self.isMatch(s, p[2:]) or first_match and self.isMatch(s[1:], p)) else: return first_match and self.isMatch(s[1:], p[1:]) # M2. DP O(nm) n, m = len(s), len(p) s, p = ' ' + s, ' ' + p dp = [[False] * (m + 1) for _ in range(n + 1)] dp[0][0] = True for i in range(n+1): for j in range(1, m+1): if j + 1 <= m and p[j + 1] == '*': continue if i>0 and p[j] != '*': dp[i][j] = dp[i-1][j-1] and (s[i] == p[j] or p[j] == '.') elif p[j] == '*': dp[i][j] = dp[i][j-2] or i != 0 and dp[i-1][j] and (s[i] == p[j - 1] or p[j-1] == '.') return dp[n][m]
class Entry(object): def __init__(self, record, value): self.record = record self.value = value def __lt__(self, other): # to make a max-heap return self.value > other.value def to_json(self): return {"record": self.record.to_json(), "value": self.value}
# # PySNMP MIB module HUAWEI-TASK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-TASK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:37:15 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") ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion") hwDatacomm, = mibBuilder.importSymbols("HUAWEI-MIB", "hwDatacomm") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") ModuleIdentity, iso, Counter64, Gauge32, NotificationType, ObjectIdentity, Bits, Integer32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, TimeTicks, Counter32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "iso", "Counter64", "Gauge32", "NotificationType", "ObjectIdentity", "Bits", "Integer32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "TimeTicks", "Counter32", "MibIdentifier") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") hwTask = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27)) hwTask.setRevisions(('2014-09-25 00:00', '2003-07-31 00:00',)) if mibBuilder.loadTexts: hwTask.setLastUpdated('201409250000Z') if mibBuilder.loadTexts: hwTask.setOrganization('Huawei Technologies Co.,Ltd.') class HwTaskStatusType(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 4, 5, 6, 8, 17, 21, 33, 37, 65, 69, 128, 256, 513, 517)) namedValues = NamedValues(("normalready", 0), ("block", 1), ("sleep", 2), ("suspend", 4), ("blockAndSuspend", 5), ("sleptAndSuspend", 6), ("running", 8), ("queueblock", 17), ("queueblockAndSuspend", 21), ("semaphoreblock", 33), ("semaphoreblockAandSuspend", 37), ("eventblock", 65), ("eventblockAndSuspend", 69), ("prioblock", 128), ("preemptready", 256), ("writequeueblock", 513), ("writequeueblockAndSuspend", 517)) hwTaskObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1)) hwTaskTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 1), ) if mibBuilder.loadTexts: hwTaskTable.setStatus('current') hwTaskEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 1, 1), ).setIndexNames((0, "HUAWEI-TASK-MIB", "hwTaskIndex"), (0, "HUAWEI-TASK-MIB", "hwTaskID")) if mibBuilder.loadTexts: hwTaskEntry.setStatus('current') hwTaskIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 1, 1, 1), Gauge32()) if mibBuilder.loadTexts: hwTaskIndex.setStatus('current') hwTaskID = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 1, 1, 2), Gauge32()) if mibBuilder.loadTexts: hwTaskID.setStatus('current') hwTaskName = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: hwTaskName.setStatus('current') hwTaskStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 1, 1, 4), HwTaskStatusType()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwTaskStatus.setStatus('current') hwTaskCpuUsage = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 1, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwTaskCpuUsage.setStatus('current') hwTaskuSecs = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 1, 1, 6), Gauge32()).setUnits('millseconds').setMaxAccess("readonly") if mibBuilder.loadTexts: hwTaskuSecs.setStatus('current') hwKeyTaskTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 2), ) if mibBuilder.loadTexts: hwKeyTaskTable.setStatus('current') hwKeyTaskEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 2, 1), ).setIndexNames((0, "HUAWEI-TASK-MIB", "hwKeyTaskIndex"), (0, "HUAWEI-TASK-MIB", "hwKeyTaskID")) if mibBuilder.loadTexts: hwKeyTaskEntry.setStatus('current') hwKeyTaskIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: hwKeyTaskIndex.setStatus('current') hwKeyTaskID = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 2, 1, 2), Integer32()) if mibBuilder.loadTexts: hwKeyTaskID.setStatus('current') hwKeyTaskName = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: hwKeyTaskName.setStatus('current') hwKeyTaskCpuUsage = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 1, 2, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwKeyTaskCpuUsage.setStatus('current') hwTaskNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 2)) hwTaskConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 3)) hwTaskCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 3, 1)) hwTaskCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 3, 1, 1)).setObjects(("HUAWEI-TASK-MIB", "hwTaskGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hwTaskCompliance = hwTaskCompliance.setStatus('current') hwTaskGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 3, 2)) hwTaskGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 3, 2, 1)).setObjects(("HUAWEI-TASK-MIB", "hwTaskName"), ("HUAWEI-TASK-MIB", "hwTaskStatus"), ("HUAWEI-TASK-MIB", "hwTaskCpuUsage"), ("HUAWEI-TASK-MIB", "hwTaskuSecs")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hwTaskGroup = hwTaskGroup.setStatus('current') hwKeyTaskGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 2011, 5, 25, 27, 3, 2, 2)).setObjects(("HUAWEI-TASK-MIB", "hwKeyTaskName"), ("HUAWEI-TASK-MIB", "hwKeyTaskCpuUsage")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): hwKeyTaskGroup = hwKeyTaskGroup.setStatus('current') mibBuilder.exportSymbols("HUAWEI-TASK-MIB", hwKeyTaskName=hwKeyTaskName, PYSNMP_MODULE_ID=hwTask, hwKeyTaskCpuUsage=hwKeyTaskCpuUsage, hwTaskGroup=hwTaskGroup, hwTaskCompliances=hwTaskCompliances, hwTaskName=hwTaskName, hwKeyTaskIndex=hwKeyTaskIndex, hwTask=hwTask, hwKeyTaskTable=hwKeyTaskTable, hwKeyTaskEntry=hwKeyTaskEntry, hwKeyTaskID=hwKeyTaskID, hwTaskID=hwTaskID, hwTaskStatus=hwTaskStatus, hwTaskuSecs=hwTaskuSecs, hwTaskCpuUsage=hwTaskCpuUsage, hwTaskIndex=hwTaskIndex, hwTaskGroups=hwTaskGroups, hwTaskConformance=hwTaskConformance, hwTaskObjects=hwTaskObjects, hwTaskTable=hwTaskTable, hwTaskEntry=hwTaskEntry, hwTaskNotifications=hwTaskNotifications, hwKeyTaskGroup=hwKeyTaskGroup, hwTaskCompliance=hwTaskCompliance, HwTaskStatusType=HwTaskStatusType)
# keyword param for the ProfileHandler KEY_DATASET_OBJECT_ID = 'dataset_object_id' KEY_SAVE_ROW_COUNT = 'save_row_count' KEY_DATASET_IS_DJANGO_FILEFIELD = 'dataset_is_django_filefield' KEY_DATASET_IS_FILEPATH = 'dataset_is_filepath' VAR_TYPE_BOOLEAN = 'Boolean' VAR_TYPE_CATEGORICAL = 'Categorical' VAR_TYPE_NUMERICAL = 'Numerical' VAR_TYPE_INTEGER = 'Integer' VAR_TYPE_FLOAT = 'Float' NUMERIC_VAR_TYPES = [VAR_TYPE_NUMERICAL, VAR_TYPE_INTEGER, VAR_TYPE_FLOAT] VALID_VAR_TYPES = [VAR_TYPE_BOOLEAN, VAR_TYPE_CATEGORICAL, VAR_TYPE_NUMERICAL, VAR_TYPE_INTEGER, VAR_TYPE_FLOAT] KW_MAX_NUM_FEATURES = 'max_num_features' # ----------------------------- ERR_MSG_COLUMN_LIMIT = 'The column_limit may be "None" or an integer greater than 0.' ERR_MSG_SOURCE_FILE_DOES_NOT_EXIST = 'The source file does not exist for dataset: ' ERR_MSG_DATASET_POINTER_NOT_FIELDFILE = 'The dataset pointer is not a Django FieldFile object.' ERR_FAILED_TO_READ_DATASET = 'Failed to read the dataset.' ERR_DATASET_POINTER_NOT_SET = 'In order to profile the data, the "dataset_pointer" must be set.'
""" day22-part1.py Created on 2020-12-22 Updated on 2020-12-22 Copyright © Ryan Kan """ # INPUT with open("input.txt", "r") as f: content = f.read()[:-1] f.close() # Split the content into player 1's cards and player 2's cards sections = content.split("\n\n") player1Cards = [int(x) for x in sections[0][10:].split("\n")] player2Cards = [int(x) for x in sections[1][10:].split("\n")] # COMPUTATION # Simulate the game roundNo = 1 while len(player1Cards) != 0 and len(player2Cards) != 0: print(f"-- Round {roundNo} --") print("Player 1's deck:", ", ".join([str(x) for x in player1Cards])) print("Player 2's deck:", ", ".join([str(x) for x in player2Cards])) # Draw both top cards from the players' hands player1Card = player1Cards[0] player2Card = player2Cards[0] print("Player 1 plays:", player1Card) print("Player 2 plays:", player2Card) # Remove the cards from the players' hands player1Cards.pop(0) player2Cards.pop(0) # See who wins the round if player1Card > player2Card: # Append `player1Card` and `player2Card` to the end of `player1Cards` in that order player1Cards = player1Cards[::-1] player1Cards.insert(0, player1Card) player1Cards.insert(0, player2Card) player1Cards = player1Cards[::-1] print("Player 1 wins the round!") else: # Append `player2Card` and `player1Card` to the end of `player2Cards` in that order player2Cards = player2Cards[::-1] player2Cards.insert(0, player2Card) player2Cards.insert(0, player1Card) player2Cards = player2Cards[::-1] print("Player 2 wins the round!") roundNo += 1 print() print("== Post-game Results ==") print("Player 1's deck:", ", ".join([str(x) for x in player1Cards])) print("Player 2's deck:", ", ".join([str(x) for x in player2Cards])) print() # Get the winning hand if len(player1Cards) != 0: winningDeck = player1Cards else: winningDeck = player2Cards # Calculate the score score = 0 for i, card in enumerate(winningDeck[::-1]): score += card * (i + 1) # OUTPUT print("Score:", score)
#! /usr/bin/env python3 # check if a word is palindromic without reversing it def isPalindrome(word): end = len(word) start = 0 retval = True while start < end+1: left = word[start] right = word[end-1] if left != right: retval = False break start += 1 end -= 1 return retval print(isPalindrome("wwaabbaawwz"))
class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: None Do not return anything, modify matrix in-place instead. """ if len(matrix) == 0 or len(matrix[0]) == 0: return matrix rcnt = len(matrix) ccnt = len(matrix[0]) horz, verz = False, False for i in range(ccnt): if matrix[0][i] == 0: horz = True break for i in range(rcnt): if matrix[i][0] == 0: verz = True break # exclude outmost row and column, and if one cell at (i,j) is 0 # then mark (i, 0) and (0, j) as 0. # i.e. we use these two outmost row and column for bookkeeping. for i in range(1, rcnt): for j in range(1, ccnt): if matrix[i][j] == 0: matrix[i][0] = 0 matrix[0][j] = 0 for i in range(1, rcnt): for j in range(1, ccnt): if matrix[i][0] == 0 or matrix[0][j] == 0: matrix[i][j] = 0 # zero outmost row & col if necessary. if horz: for i in range(ccnt): matrix[0][i] = 0 if verz: for i in range(rcnt): matrix[i][0] = 0
class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=46): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f'Ola {id(self)}' if __name__ == '__main__': nilton = Pessoa(nome='Nilton') roberto = Pessoa(nilton, nome='Roberto') print(Pessoa.cumprimentar(roberto)) print(id(roberto)) print(roberto.cumprimentar()) print(roberto.nome) print(roberto.idade) for filho in roberto.filhos: print(filho.nome) roberto.sobrenome = 'Goncalves' del roberto.filhos roberto.olhos = 1 del roberto.olhos print(roberto.__dict__) print(nilton.__dict__) Pessoa.olhos = 3 print(Pessoa.olhos) print(roberto.olhos) print(nilton.olhos) print(id(Pessoa.olhos), id(roberto), id(nilton.olhos))
AIRTABLE_EXPORT_JOB_DOWNLOADING_PENDING = "pending" AIRTABLE_EXPORT_JOB_DOWNLOADING_FAILED = "failed" AIRTABLE_EXPORT_JOB_DOWNLOADING_FINISHED = "finished" AIRTABLE_EXPORT_JOB_DOWNLOADING_BASE = "downloading-base" AIRTABLE_EXPORT_JOB_CONVERTING = "converting" AIRTABLE_EXPORT_JOB_DOWNLOADING_FILES = "downloading-files" AIRTABLE_BASEROW_COLOR_MAPPING = { "blue": "blue", "cyan": "light-blue", "teal": "light-green", "green": "green", "yellow": "light-orange", "orange": "orange", "red": "light-red", "pink": "red", "purple": "dark-blue", "gray": "light-gray", }
#!/usr/bin/env python3 """Advent of Code 2020 Day 06 - Custom Customs.""" with open ('inputs/day_06.txt', 'r') as forms: groups = [group_answers.strip() for group_answers in forms.read().split('\n\n')] overall_yes = 0 for group in groups: group_yes = set() for member_yes in group.split('\n'): for char in member_yes: group_yes.add(char) overall_yes += len(group_yes) # Answer One print("Sum of all groups yes counts:", overall_yes) overall_group_yes = 0 for group in groups: members = group.split('\n') group_yes = set([char for char in members[0]]) for member in members[1:]: group_yes = set([char for char in member]).intersection(group_yes) overall_group_yes += len(group_yes) # Answer Two print("Sum of all group overall yes counts:", overall_group_yes)
print("Rathinn") print("AM.EN.U4AIE19052") print("AIE") print("Anime Rocks")
"""Constants about physical keg shell.""" # Most common shell sizes, from smalles to largest. MINI = "mini" CORNY_25 = "corny-2_5-gal" CORNY_30 = "corny-3-gal" CORNY = "corny" SIXTH_BARREL = "sixth" EURO_30_LITER = "euro-30-liter" EURO_HALF_BARREL = "euro-half" QUARTER_BARREL = "quarter" EURO = "euro" HALF_BARREL = "half-barrel" OTHER = "other" VOLUMES_ML = { MINI: 5000, CORNY_25: 9463.53, CORNY_30: 11356.2, CORNY: 18927.1, SIXTH_BARREL: 19570.6, EURO_30_LITER: 300000.0, EURO_HALF_BARREL: 50000.0, QUARTER_BARREL: 29336.9, EURO: 100000.0, HALF_BARREL: 58673.9, OTHER: 0.0, } DESCRIPTIONS = { MINI: "Mini Keg (5 L)", CORNY_25: "Corny Keg (2.5 gal)", CORNY_30: "Corny Keg (3.0 gal)", CORNY: "Corny Keg (5 gal)", SIXTH_BARREL: "Sixth Barrel (5.17 gal)", EURO_30_LITER: "European DIN (30 L)", EURO_HALF_BARREL: "European Half Barrel (50 L)", QUARTER_BARREL: "Quarter Barrel (7.75 gal)", EURO: "European Full Barrel (100 L)", HALF_BARREL: "Half Barrel (15.5 gal)", OTHER: "Other", } CHOICES = [(x, DESCRIPTIONS[x]) for x in reversed(sorted(VOLUMES_ML, key=VOLUMES_ML.get))] def find_closest_keg_size(volume_ml, tolerance_ml=100.0): """Returns the nearest fuzzy match name within tolerance_ml. If no match is found, OTHER is returned. """ for size_name, size_volume_ml in list(VOLUMES_ML.items()): diff = abs(volume_ml - size_volume_ml) if diff <= tolerance_ml: return size_name return OTHER def get_description(keg_type): return DESCRIPTIONS.get(keg_type, "Unknown")
"""Consts used by rpi_camera.""" DOMAIN = "rpi_camera" CONF_HORIZONTAL_FLIP = "horizontal_flip" CONF_IMAGE_HEIGHT = "image_height" CONF_IMAGE_QUALITY = "image_quality" CONF_IMAGE_ROTATION = "image_rotation" CONF_IMAGE_WIDTH = "image_width" CONF_OVERLAY_METADATA = "overlay_metadata" CONF_OVERLAY_TIMESTAMP = "overlay_timestamp" CONF_TIMELAPSE = "timelapse" CONF_VERTICAL_FLIP = "vertical_flip" DEFAULT_HORIZONTAL_FLIP = 0 DEFAULT_IMAGE_HEIGHT = 480 DEFAULT_IMAGE_QUALITY = 7 DEFAULT_IMAGE_ROTATION = 0 DEFAULT_IMAGE_WIDTH = 640 DEFAULT_NAME = "Raspberry Pi Camera" DEFAULT_TIMELAPSE = 1000 DEFAULT_VERTICAL_FLIP = 0
# Desafio 097: Faça um programa que tenha uma função chamada escreva(), que # receba um texto qualquer como parâmetro e mostre uma mensagem com tamanho # adaptável. def escreva(texto): tamanho = len(texto) + 4 print('~' * tamanho) print(f'{texto:^{tamanho}}') print('~' * tamanho) texto = input('Digite um texto para o título: ') escreva(texto)
# Backtracking class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: if not candidates: return candidates.sort() paths = [] results = [] index = 0 cursum = 0 # paths, results, index, candidates, cursum, target self.dfs(paths,results,index,candidates,cursum, target) return results def dfs(self,paths, results,index,candidates,cursum,target): if cursum > target: return # append path must use list to new a paths if cursum == target: results.append(list(paths)) return for i in range(index,len(candidates)): paths.append(candidates[i]) cursum += candidates[i] self.dfs(paths,results,i,candidates,cursum,target) paths.pop() cursum -= candidates[i] # https://www.jiuzhang.com/problem/combination-sum/ class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: results = [] def backtrack(remain,comb,start): if remain == 0: # make a deep copy of the current combination results.append(list(comb)) return # not satify condition elif remain <0: # exceed the scope, stop exploration. return for i in range(start,len(candidates)): # add the number into the combination comb.append(candidates[i]) # give the current number another chance, rather than moving on backtrack(remain-candidates[i],comb,i) # backtrack, remove the number from the combination comb.pop() backtrack(target,[],0) return results # Refer from # https://leetcode.com/problems/combination-sum/solution/ # Time: O(N^(T/M)+1) # Let N be the number of candidates, T be the target value, and M be the minimal value among the candidates. # Space:O(T/M) # V2 class Solution(object): def combinationSum(self, candidates, target): ret = [] self.dfs(candidates, target, [], ret) return ret def dfs(self, nums, target, path, ret): if target < 0: return if target == 0: ret.append(path) return for i in range(len(nums)): # Here we have to use concatenation because if we use append, then path will be passed by # reference and it will cause allocation problem self.dfs(nums[i:], target-nums[i], path+[nums[i]], ret) # V3 class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: res = [] self.backtrack(0,candidates,target,[],res) return res def backtrack(self,start,candidates,target,path,res): if target <0: return if target ==0: res.append(path) return for i in range(start,len(candidates)): self.backtrack(i,candidates,target-candidates[i],path+[candidates[i]],res)
# final def sum_of_args(args): result = 0 for i in args: result += i return result print(sum_of_args(args=[1,2,3,4]))
''' https://leetcode.com/contest/weekly-contest-182/problems/find-lucky-integer-in-an-array/ ''' class Solution: def findLucky(self, arr: List[int]) -> int: for a in sorted(arr)[::-1]: if a == arr.count(a): return a return -1
####Use the loop 'while' # input a and b a = int(input()) b = int(input()) if a > b : print('it is not the total') else : i = a total = 0 while i <= b : total += i i += 1 print(total)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def file(): print('step1') yield 1 print('step2') yield 2 return '应该停止了' print('2') yield 123 m = 0 while m < 10: try: x = file() j = next(x) print('数据:', j) except StopIteration as e: print('数据是:', e.value) m = m + 1
# Write your solution for 1.3 here! x=0 i=0 while x<10000: i+=1 x+=i print(i)
# This is the Python adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/). # # Copyright 2021 Huawei Technologies Co., Ltd # # 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. # ============================================================================ """ Define constants""" # Arithmetic kScalarAdd = "ScalarAdd" kScalarSub = "ScalarSub" kScalarMul = "ScalarMul" kScalarDiv = "ScalarDiv" kScalarFloordiv = "ScalarFloordiv" kScalarMod = "ScalarMod" kScalarPow = "ScalarPow" kScalarTrunc = "ScalarTrunc" kScalarFloor = "ScalarFloor" kScalarUadd = "ScalarUadd" kScalarUsub = "ScalarUsub" kTupleGetItem = "TupleGetItem" kMakeTuple = "MakeTuple" kGather = "Gather"
tile_size = 25 # size of tiles in the board screen_width = 400 # width of the screen screen_height = 400 # height of the screen
class Queue: def __init__(self,list = None): if list == None: self.item =[] else : self.item = list def enQueue(self,i): self.item.append(i) def size(self): return len(self.item) def isEmpty(self): return len(self.item)==0 def deQueue(self): return self.item.pop(0) def showresult(r,b,heat,freeze,mistake): print("Red Team : \n",r.size(),'\n',"".join(reversed(r.item)) if r.size()!=0 else "Empty",'\n',heat," Explosive(s) ! ! ! (HEAT)",sep="") if mistake>0: print("Blue Team Made (a) Mistake(s)",mistake,"Bomb(s)") print("----------TENETTENET----------") print(": maeT eulB\n",b.size(),'\n',"".join(reversed(b.item)) if b.size() != 0 else "ytpmE","\n","(EZEERF) ! ! ! (s)evisolpxE ",freeze,sep="") def TENET(r,b): bombl = Queue() heat,freeze,mistake = 0,0,0 newr = Queue() count = len(b.item)-2 j= 0 while j < count: if b.item[j] == b.item[j+1] == b.item[j+2]: bombl.enQueue(b.item[j]) # del b.item[j:j+3] for _ in range(3): b.item.pop(j) count-=1 j-=1 freeze +=1 j+=1 # print(bombl.item) for i in range(r.size()): newr.enQueue(r.item[i]) # print("before",newr.item) if newr.size()>=3: if newr.item[-1]==newr.item[-2]==newr.item[-3]: if not bombl.isEmpty(): bombq = bombl.deQueue() if bombq == newr.item[-1]: mistake+=1 for _ in range(2): newr.item.pop() else : newr.item.insert(-1,bombq) else: heat+=1 for _ in range(3): newr.item.pop() # print("after",newr.item) showresult(newr,b,heat,freeze,mistake) r,b = input("Enter Input (Red, Blue) : ").split() r = Queue(list(r)) b = Queue(list(b[::-1])) # print(r.item,b.item) TENET(r,b) # print("heat",heat,"Freeze",freeze,"mistake",mistake)
def test_signup_new_account(app): username = "user1" password = "test" app.james.ensure_user_exists(username, password)
list_var = [1, 2] dict_var = { "key1": "value1" } setVar = {1, 2, 3}
n = int(input()) cnt1, cnt2 = {}, {} for i in range(n): x, y = map(int, input().split()) cnt1[x+y] = cnt1.get(x+y, 0) + 1 cnt2[x-y] = cnt2.get(x-y, 0) + 1 ans = 0 for t in cnt1.values(): ans += t*(t-1)//2 for t in cnt2.values(): ans += t*(t-1)//2 print(ans)
#No python podemos fazer de três maneiras uma tupla: (), Uma lista: [], e um dicionário:{} lanche = ('Hamburger','Suco','Pizza','Pudim') print(lanche)# Vai aparecer todos, ou mostrar a tupla inteira print(lanche[1])# Vai aparecer o seleciondo print(lanche[-2])# Vai mostrar o que está atrás do selecionado print(lanche[1:3])# Vai mostrar do 1 ao 3 mas ele será ignorado mostrando apenas do 1 ao 2 print(lanche[2:])# Vai do 2 até o final print(lanche[:2])# Mostra do inicio ao elemento 2 mas ele vai ignorar o ultimo elemento no caso o 2 print(lanche[-2:])# Vai começar na pízza (1) e vai até o final """ Obs.: Tuplas são imutáveis dentro do código pois se vc tentar fazer assim para tentar mudalas dará erro, como no exemplo: lanche[1]='Refrigerante' print(lanche[1]) """ print(len(lanche))# Mostra o número de tuplas dentro da variavél #Posso fazer uma estrutura de repetição assim: for comida in lanche:# Essa linha é igual a linha 22 print(f"Eu vou comer {comida}") print("Comi demais") print("-----------------------------------------") #Ou assim: for cont in range(0,len(lanche)): print(cont)#aqui ele enumera a posição das tuplas na variavél print("-----------------------------------------") #Ou assim: for cont in range(0,len(lanche)):# Essa linha é igual a linha 18 print(lanche[cont]) print("-----------------------------------------") #fora esses exmplos também posso fazer assim caso eu queira mostrar a posição: for cont in range(0, len(lanche)): print(f"Eu vou comer {lanche[cont]} na posição {cont}") print("-----------------------------------------") # Ou posso usar para enumerar assim: for pos, comida in enumerate(lanche): print(f"Eu vou comer {comida} na posição {pos}") #Saindo das estruturas de repetição #Se eu quiser organizar as tuplas eu uso sorted, obs.: o método sorted não muda as posições das tuplas, apenas as organiza print(sorted(lanche)) # Vai deixar os valores da variável em ordem não alterando nada #Se eu tiver outro exemplo de tupla abaixo e tentar somalas: a = (2, 5, 4) b = (5, 8, 1, 2) c = a + b print(c)# Se eu tentar somalás ele vai apenas junta-lás print(len(c))# para ver o tamanho da tupla em c print(c.count(5))# se eu quiser contar quantos vezes aparece um valor dentro de uma tupla, aqui no caso 5 #Obs.: No caso da de baixo se eu tentar mostrar o index, ou seja a posição em que o valor está como a variavel index, ele vai mostrar a do valor juntado, por exemplo: print(c) print(c.index(8))# Aqui ele vai mostrar a posição do valor pós junção, já que a variavél c é uma nova tupla # Obs.: E como faço caso tenha dois valores iguais dentro de uma tupla? #Simples print(c) print(c.index(5))# Se eu pegar um dos 5 e colocar só ele, ele vai mostrar o primeiro que aparece mas para mostrar o segundo print(c.index(5, 2))# Isso é o que chamamos de deslocamento; Lenbre que sempre nasce apartir do 0 #Se eu tiver diferentes tipos de dados a tupla aceita sem problemas pessoa = ('Lucas', 19, 'M', 70.55) print(pessoa) # Caso eu queira apagar apenas um valor da tupla vai dar erro, mas eu posso apagar uma tupla inteira del(pessoa) #Se eu colocar para um print mostrar o valor dentro de pessoa vai dar erro pois pessoa foi deletado da memoria
def valid_oci_group(parser): add_oci_group(parser) def add_oci_group(parser): oci_group = parser.add_argument_group(title="OCI arguments") oci_group.add_argument("--oci-profile-name", default="") oci_group.add_argument("--oci-profile-compartment-id", default="") # HACK to extract the set provider from the cli oci_group.add_argument("--oci", action="store_true", default=True)
def sievePrimeGen(n): primes = [True] * (n + 1) ans = [] for i in range(2, int(n * (1 / 2) + 1)): if primes[i] == True: for j in range(i * 2, n + 1, i): primes[j] = False for i in range(2, n + 1): if primes[i] == True: ans.append(i) i += 1 return ans print(sievePrimeGen(int(input("Enter the number upto which prime nos. should be generated - ")))) """ * n = number uptill which prime nos are to be generated * primes initially has all elements True by default * LOGIC * Instead of checking wheather all nums are prime - we remove(make them False) the multiples of prime nos less than sqrt of n * Remaining ones which are True are Prime and False are non Prime * * COMPLEXITY - O(N * log(log(n))) """
class Card: def __repr__(self): return str((self.name, self.rules, self.value)) class Batman(Card): def __init__(self): self.name = 'Batman' self.value = 1 self.rules = "Guess a player's hand" self.action = 'guess' class Catwoman(Card): def __init__(self): self.name = 'Catwoman' self.value = 2 self.rules = 'Look at a hand' self.action = 'look' class Bane(Card): def __init__(self): self.name = 'Bane' self.value = 3 self.rules = 'Compare hands; lower hand is out' self.action = 'compare' class Robin(Card): def __init__(self): self.name = 'Robin' self.value = 4 self.rules = 'Protection until next turn' self.action = 'immune' class PoisonIvy(Card): def __init__(self): self.name = 'Poison Ivy' self.value = 5 self.rules = 'One player discards their hand' self.action = 'discard' class TwoFace(Card): def __init__(self): self.name = 'Two-Face' self.value = 6 self.rules = 'Trade hands' self.action = 'trade' class HarleyQuinn(Card): def __init__(self): self.name = 'Harley Quinn' self.value = 7 self.rules = 'Discard if caught with TWO-FACE or POISON IVY' self.action = 'nop' class Joker(Card): def __init__(self): self.name = 'Joker' self.value = 8 self.rules = 'Lose if discarded' self.action = 'lose' def get_card(v): return { 1: Batman, 2: Catwoman, 3: Bane, 4: Robin, 5: PoisonIvy, 6: TwoFace, 7: HarleyQuinn, 8: Joker }[v]()
#Escreva um programa qye converat uma temperatura digitada em °C e converta para °F. c=float(input('Informe a temperatura em °C: ')) f=9*c/5+32 print('A temperatura de {}°C corresponde a {}°F'.format(c,f))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': ''' in-order traversal ''' self.found = False def inorder(node, target): if not node: return if node.left: l = inorder(node.left, target) if l: return l if self.found: return node elif node == target: self.found = True if node.right: r = inorder(node.right, target) if r: return r return res = inorder(root, p) return res ## 4/8/2021: iterative solution # class Solution: # def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': # ''' # inorder traversal the tree, find the child node of the target node # ''' # curr = None # stack = [] # while True: # while root: # stack.append(root) # root = root.left # if not stack: # return None # node = stack.pop() # if curr == p: # return node # curr = node # root = node.right
db_host_name="127.0.0.1" db_name="TestDB" db_user="testuser" db_password="test123" db_table_name="brady"
# # This file is part of BDC-DB. # Copyright (C) 2020 INPE. # # BDC-DB is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """Define mock of flask app that extends BDC-DB.""" SCHEMA = 'myapp'
''' Created on 13 Jun 2016 @author: a ''' class InvalidPasswords(): BAD_PASSWORDS = ['1234567890','qwertyuiop','123456789','password1','photoshop', '11111111','12345678','1qaz2wsx','access14','adobe123','baseball', 'bigdaddy','butthead','cocacola','computer','corvette','danielle',\ 'dolphins','einstein','firebird','football','hardcore','iloveyou',\ 'internet','jennifer','marlboro','maverick','mercedes','michelle',\ 'midnight','mistress','mountain','nicholas','passw0rd','password',\ 'pa#sword','princess','qwertyui','redskins','redwings','rush2112',\ 'samantha','scorpion','srinivas','startrek','starwars','steelers',\ 'sunshine','superman','swimming','trustno1','victoria','whatever',\ 'xxxxxxxx','1234567','7777777','8675309','abgrtyu','amateur','anthony',\ 'arsenal','a#shole','bigc#ck','bigdick','bigtits','bitches','blondes',\ 'bl#wjob','bond007','brandon','broncos','bulldog','cameron','captain',\ 'charles','charlie','chelsea','chester','chicago','chicken','c#mming',\ 'c#mshot','college','cowboys','crystal','diamond','dolphin','extreme',\ 'f#cking','f#ckyou','ferrari','fishing','florida','forever','freedom',\ 'gandalf','gateway','gregory','heather','hooters','hunting','jackson',\ 'jasmine','jessica','johnson','leather','letmein','madison','matthew',\ 'maxwell','melissa','michael','monster','mustang','naughty','ncc1701',\ 'newyork','nipples','packers','panther','panties','patrick','peaches',\ 'phantom','phoenix','porsche','private','p#ssies','raiders','rainbow',\ 'rangers','rebecca','richard','rosebud','scooter','scorpio','shannon',\ 'success','testing','thunder','thx1138','tiffany','trouble','voyager',\ 'warrior','welcome','william','winston','yankees','zxcvbnm','123456',\ '111111','112233','121212','123123','123456','131313','232323','654321',\ '666666','696969','777777','987654','aaaaaa','abc123','access','action',\ 'albert','alexis','amanda','andrea','andrew','angela','angels','animal',\ 'apollo','apples','arthur','asdfgh','ashley','Aaugust','austin','azerty',\ 'badboy','bailey','banana','barney','batman','beaver','beavis','bigdog',\ 'birdie','biteme','blazer','blonde','blowme','bonnie','booboo','booger',\ 'boomer','boston','brandy','braves','brazil','bronco','buster','butter',\ 'calvin','camaro','canada','carlos','carter','casper','cheese','coffee',\ 'compaq','cookie','cooper','cowboy','dakota','dallas','daniel','debbie',\ 'dennis','diablo','doctor','doggie','donald','dragon','dreams','driver',\ 'eagle1','eagles','edward','erotic','falcon','f#cked','f#cker','f#ckme',\ 'fender','flower','flyers','freddy','gators','gemini','george','giants',\ 'ginger','golden','golfer','gordon','guitar','gunner','hammer','hannah',\ 'harley','helpme','hentai','hockey','horney','hotdog','hunter','iceman',\ 'iwantu','jackie','jaguar','jasper','jeremy','johnny','jordan','joseph',\ 'joshua','junior','justin','killer','knight','ladies','lakers','lauren',\ 'legend','little','london','lovers','maddog','maggie','magnum','marine',\ 'martin','marvin','master','matrix','member','merlin','mickey','miller',\ 'monica','monkey','morgan','mother','muffin','murphy','nascar','nathan',\ 'nicole','nipple','oliver','orange','parker','peanut','pepper','player',\ 'please','pookie','prince','purple','qazwsx','qwerty','rabbit','rachel',\ 'racing','ranger','redsox','robert','rocket','runner','russia','samson',\ 'sandra','saturn','scooby','secret','sexsex','shadow','shaved','sierra',\ 'silver','skippy','slayer','smokey','snoopy','soccer','sophie','spanky',\ 'sparky','spider','squirt','steven','sticky','stupid','suckit','summer',\ 'surfer','sydney','taylor','tennis','teresa','tester','theman','thomas',\ 'tigers','tigger','tomcat','topgun','toyota','travis','tucker','turtle',\ 'united','vagina','victor','viking','voodoo','walter','willie','wilson',\ 'winner','winter','wizard','xavier','xxxxxx','yamaha','yankee','yellow',\ 'zxcvbn','zzzzzz','qwerty123', 'qwerty12']
# None datatype a = None print(a) # Numeric datatype (int,float,complex,bool) b = 4 print(type(b)) c = 2.5 print(type(c)) d = 4 + 5j print(type(d)) bool = b > c print(type(bool)) e = int(c) print(e) f = complex(e, b) print(f) print(int(True)) # List datatype lst = [1, 2, 3, 4, 5] print(lst) # Set datatype s = {4, 8, 2, 1, 6, 3} print(s) # Tuple datatypes tup = (10, 20, 50, 40, 30) print(tup) # String datatype str = 'Sunny' print(str) # Range datatype k = list(range(10)) print(k) l = list(range(11, 21, 2)) print(l) # Dictionary datatype d = {1: 'sunny', 'raj': 'python', 2.4: 'java'} print(d) print(d.keys()) print(d.values()) print(d[2.4])
# this menu.py only installs the SetLoop examples. # get script location (necessaary for loading toolsets) dirName = os.path.dirname( os.path.abspath(__file__)).replace('\\', '/') # get node toolbar nodes = nuke.menu('Nodes') # make group entry for examples in toolsets menu group = nodes.addMenu('ToolSets/SetLoop Examples', index=2) # make adding examples a function def addExample(fileName, toolSetName): # add individual examples group.addCommand('(' + toolSetName + ') ' + fileName, "nuke.loadToolset('" + dirName + '/' + fileName + ".nk')", icon = fileName + '.png') # add each example addExample('Geo Loop', 'SetLoop') addExample('Motion Graphics', 'SetLoop') addExample('Julia Set 1', 'SetLoop') addExample('Julia Set 2', 'SetLoop') addExample('Julia Set 3', 'SetLoop') addExample('Mandelbrot 1', 'SetLoop') addExample('Mandelbrot 2', 'SetLoop') addExample('Reaction Diffusion 1', 'SetLoop') addExample('Reaction Diffusion 2', 'SetLoop') addExample('Reaction Diffusion 3', 'SetLoop')
_base_ = ["./FlowNet512_1.5AugCosyAAEGray_Flat_Pbr_01_ape.py"] OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_Flat_lmPbr_SO/camera" DATASETS = dict(TRAIN=("lm_pbr_camera_train",), TEST=("lm_real_camera_test",)) # bbnc7 # objects camera Avg(1) # ad_2 26.86 26.86 # ad_5 84.41 84.41 # ad_10 99.12 99.12 # rete_2 40.88 40.88 # rete_5 99.12 99.12 # rete_10 100.00 100.00 # re_2 40.98 40.98 # re_5 99.12 99.12 # re_10 100.00 100.00 # te_2 99.51 99.51 # te_5 100.00 100.00 # te_10 100.00 100.00 # proj_2 81.76 81.76 # proj_5 99.31 99.31 # proj_10 100.00 100.00 # re 2.34 2.34 # te 0.01 0.01 # init by mlBCE # objects camera Avg(1) # ad_2 28.43 28.43 # ad_5 84.31 84.31 # ad_10 99.22 99.22 # rete_2 40.20 40.20 # rete_5 99.02 99.02 # rete_10 100.00 100.00 # re_2 40.29 40.29 # re_5 99.02 99.02 # re_10 100.00 100.00 # te_2 99.51 99.51 # te_5 100.00 100.00 # te_10 100.00 100.00 # proj_2 82.06 82.06 # proj_5 99.31 99.31 # proj_10 100.00 100.00 # re 2.34 2.34 # te 0.01 0.01
# Function to square every digit of a number. # Eg. 9119 will become 811181, because 9^2 is 81 and 1^2 is 1. def square_each_number(num): result= '' list = [int(d) for d in str(num)] square_list = [i ** 2 for i in list] for i in square_list: result += str(i) return float(result) test.assert_equals(square_digits(9119), 811181)
# QUESTION: # # This problem was asked by Google. # # Given the root to a binary tree, implement serialize(root), which serializes # the tree into a string, and deserialize(s), which deserializes the string # back into the tree. # # For example, given the following Node class # # class Node: # def __init__(self, val, left=None, right=None): # self.val = val # self.left = left # self.right = right # The following test should pass: # # node = Node('root', Node('left', Node('left.left')), Node('right')) # assert deserialize(serialize(node)).left.left.val == 'left.left' class Node(object): def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def solution(L): # Sanity check if not L: return None # Return the identity if the element-count is fewer than 3 if len(L) < 3: return L # Prevent division-by-zero for i in range(0, len(L)): if L[i] == 0: return None product = 1 multiply = lambda x, y: x * y divide = lambda x: product // x product = reduce(multiply, L) return list(map(divide, L))
def reverseBits(n): head = 15 tail = 0 while head > tail: headBit = (n >> head) & 1 tailBit = (n >> tail) & 1 if headBit != tailBit: bitMask = (1 << head) | (1 << tail) n ^= bitMask head -= 1 tail += 1 return n
class MolGraphInterface: r"""The `MolGraphInterface` defines the base class interface to handle a molecular graph. The method implementation to generate a mol-instance from smiles etc. can be obtained from different backends like `rdkit`. The mol-instance of a chemical informatics package like `rdkit` is treated via composition. The interface is designed to extract a graph from a mol instance not to make a mol object from a graph. """ def __init__(self, mol=None, add_hydrogen: bool = False): """Set the mol attribute for composition. This mol instances will be the backends molecule class. Args: mol: Instance of a molecule from chemical informatics package. add_hydrogen (bool): Whether to add or ignore hydrogen in the molecule. """ self.mol = mol self._add_hydrogen = add_hydrogen def from_smiles(self, smile: str, **kwargs): """Main method to generate a molecule from smiles string representation. Args: smile (str): Smile string representation of a molecule. Returns: self """ raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") def to_smiles(self): """Return a smile string representation of the mol instance. Returns: smile (str): Smile string. """ raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") def from_mol_block(self, mol_block: str): """Set mol-instance from a more extensive string representation containing coordinates and bond information. Args: mol_block (str): Mol-block representation of a molecule. Returns: self """ raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") def to_mol_block(self): """Make a more extensive string representation containing coordinates and bond information from self. Returns: mol_block (str): Mol-block representation of a molecule. """ raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") @property def node_number(self): """Return list of node numbers which is the atomic number of atoms in the molecule""" raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") @property def node_symbol(self): """Return a list of atomic symbols of the molecule.""" raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") @property def node_coordinates(self): """Return a list of atomic coordinates of the molecule.""" raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") @property def edge_indices(self): """Return a list of edge indices of the molecule.""" raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") @property def edge_number(self): """Return a list of edge number that represents the bond order.""" raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") def edge_attributes(self, properties: list, encoder: dict): """Make edge attributes. Args: properties (list): List of string identifier for a molecular property. Must match backend features. encoder (dict): A dictionary of callable encoder function or class for each string identifier. Returns: list: List of attributes after processed by the encoder. """ raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") def node_attributes(self, properties: list, encoder: dict): """Make node attributes. Args: properties (list): List of string identifier for a molecular property. Must match backend features. encoder (dict): A dictionary of callable encoder function or class for each string identifier. Returns: list: List of attributes after processed by the encoder. """ raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") def graph_attributes(self, properties: list, encoder: dict): """Make graph attributes. Args: properties (list): List of string identifier for a molecular property. Must match backend features. encoder (dict): A dictionary of callable encoder function or class for each string identifier. Returns: list: List of attributes after processed by the encoder. """ raise NotImplementedError("ERROR:kgcnn: Method for `MolGraphInterface` must be implemented in sub-class.") @staticmethod def _check_encoder(encoder: dict, possible_keys: list): """Verify and check if encoder dictionary inputs is within possible properties. If a key has to be removed, a warning is issued. Args: encoder (dict): Dictionary of callable encoder function or class. Key matches properties. possible_keys (list): List of allowed keys for encoder. Returns: dict: Cleaned encoder dictionary. """ if encoder is None: encoder = {} else: encoder_unknown = [x for x in encoder if x not in possible_keys] if len(encoder_unknown) > 0: print("WARNING: Encoder property not known", encoder_unknown) encoder = {key: value for key, value in encoder.items() if key not in encoder_unknown} return encoder @staticmethod def _check_properties_list(properties: list, possible_properties: list, attribute_name: str): """Verify and check if list of string identifier match expected properties. If an identifier has to be removed, a warning is issued. Args: properties (list): List of requested string identifier. Key matches properties. possible_properties (list): List of allowed string identifier for properties. attribute_name(str): A name for the properties. Returns: dict: Cleaned encoder dictionary. """ if properties is None: props = [x for x in possible_properties] else: props_unknown = [x for x in properties if x not in possible_properties] if len(props_unknown) > 0: print("WARNING: %s property is not defined, ignore following keys:" % attribute_name, props_unknown) props = [x for x in properties if x in possible_properties] return props
# from Data Structures, Spring 2019 class Graph: """Representation of a simple graph using an adjacency map.""" #------------------------- nested Vertex class ------------------------- class Vertex: """Lightweight vertex structure for a graph.""" # __slots__ = '_element' def __init__(self, idx, goal=None,proof_tree=None,proof=None): """Do not call constructor directly. Use Graph's insert_vertex(x).""" self.goal = goal self.idx = idx self.proof_tree = proof_tree self.proof = proof # def element(self): # """Return element associated with this vertex.""" # return self._element def __hash__(self): # will allow vertex to be a map/set key return hash(self.idx) def __str__(self): return "VERTEX ({}, {})".format(self.idx,self.goal) # return str(self.goal) def __repr__(self): return "VERTEX ({}, {})".format(self.idx,self.goal) def __ge__(self,v2): if not isinstance(v2,type(self)): raise ValueError("not a vertex to compare") return self.idx >= v2.idx def __eq__(self,v2): if not isinstance(v2,type(self)): raise ValueError("not a vertex to compare") return self.idx==v2.idx and self.goal==v2.goal and self.proof_tree==v2.proof_tree # return str(self.goal) #------------------------- nested Edge class ------------------------- class Edge: """Lightweight edge structure for a graph.""" # __slots__ = '_origin', '_destination', '_element' def __init__(self, u, v, rule_encoding=None,matching_dict=None): """Do not call constructor directly. Use Graph's insert_edge(u,v,x).""" self._origin = u self._destination = v self.rule_encoding = rule_encoding self.matching_dict = matching_dict def endpoints(self): """Return (u,v) tuple for vertices u and v.""" return (self._origin, self._destination) def opposite(self, v): """Return the vertex that is opposite v on this edge.""" if not isinstance(v, Graph.Vertex): raise TypeError('v must be a Vertex') return self._destination if v is self._origin else self._origin raise ValueError('v not incident to edge') # def element(self): # """Return element associated with this edge.""" # return self._element def __hash__(self): # will allow edge to be a map/set key return hash( (self._origin, self._destination) ) def __str__(self): return '({0},{1},{2},{3})'.format(self._origin,self._destination,self.rule_encoding,self.matching_dict) def __repr__(self): if self._origin.idx < self._destination.idx: u = self._origin v = self._destination else: u = self._destination v = self._origin return 'EDGE: ({0},{1},{2},{3})'.format(u,v,self.rule_encoding,self.matching_dict) #------------------------- Graph methods ------------------------- def __init__(self, directed=False): """Create an empty graph (undirected, by default). Graph is directed if optional paramter is set to True. """ self._outgoing = {} # only create second map for directed graph; use alias for undirected self._incoming = {} if directed else self._outgoing def __str__(self): def edge_key(e): if e._origin.idx < e._destination.idx: u = e._origin v = e._destination else: u = e._destination v = e._origin return u.idx edges = list(self.edges()) sorted_edges = sorted(edges,key=lambda x:edge_key(x)) result = [] for each in sorted_edges: result.append(str(each) + "\n") return "".join(result) def size(self): return len(self.vertices()) def dfs(self,start_node): # retrun an iteration in the dfs order def dfs_inner(start_node,visited): visited.append(start_node) adj_list = list(self._outgoing[start_node].keys()) for i in range(len(adj_list)): has_visited = False for j in visited: if j == adj_list[i]: has_visited = True break if not has_visited: dfs_inner(adj_list[i],visited) return visited if len(self._outgoing)==0: return [] to_return = dfs_inner(start_node,[]) return to_return def _validate_vertex(self, v): """Verify that v is a Vertex of this graph.""" if not isinstance(v, self.Vertex): raise TypeError('Vertex expected') if v not in self._outgoing: raise ValueError('Vertex does not belong to this graph.') def is_directed(self): """Return True if this is a directed graph; False if undirected. Property is based on the original declaration of the graph, not its contents. """ return self._incoming is not self._outgoing # directed if maps are distinct def vertex_count(self): """Return the number of vertices in the graph.""" return len(self._outgoing) def vertices(self): """Return an iteration of all vertices of the graph.""" return self._outgoing.keys() def edge_count(self): """Return the number of edges in the graph.""" total = sum(len(self._outgoing[v]) for v in self._outgoing) # for undirected graphs, make sure not to double-count edges return total if self.is_directed() else total // 2 def edges(self): """Return a set of all edges of the graph.""" result = set() # avoid double-reporting edges of undirected graph for secondary_map in self._outgoing.values(): result.update(secondary_map.values()) # add edges to resulting set return result def get_edge(self, u, v): """Return the edge from u to v, or None if not adjacent.""" self._validate_vertex(u) self._validate_vertex(v) return self._outgoing[u].get(v) # returns None if v not adjacent def degree(self, v, outgoing=True): """Return number of (outgoing) edges incident to vertex v in the graph. If graph is directed, optional parameter used to count incoming edges. """ self._validate_vertex(v) adj = self._outgoing if outgoing else self._incoming return len(adj[v]) def incident_edges(self, v, outgoing=True): """Return all (outgoing) edges incident to vertex v in the graph. If graph is directed, optional parameter used to request incoming edges. """ self._validate_vertex(v) adj = self._outgoing if outgoing else self._incoming for edge in adj[v].values(): yield edge def insert_vertex(self, x=None): """Insert and return a new Vertex with element x.""" idx = len(self._outgoing) v = self.Vertex(idx,x) #create a new instance in the vertex class self._outgoing[v] = {} if self.is_directed(): self._incoming[v] = {} # need distinct map for incoming edges return v def insert_edge(self, u, v, rule_encoding=None,matching_dict=None): """Insert and return a new Edge from u to v with auxiliary element x. Raise a ValueError if u and v are not vertices of the graph. Raise a ValueError if u and v are already adjacent. """ if self.get_edge(u, v) is not None: # includes error checking raise ValueError('u and v are already adjacent') e = self.Edge(u, v, rule_encoding,matching_dict) self._outgoing[u][v] = e self._incoming[v][u] = e return e def find_root(self): if self.size()==0: return None return self.idx_to_vertex(0) def idx_to_vertex(self,idx): # input: idx of a vertex # return the vertex if len(self._outgoing)==0 or idx>=len(self._incoming): raise ValueError('vertex DNE') for i in self._outgoing.keys(): if i.idx==idx: return i return None # raise ValueError('vertex DNE') def goal_to_vertex(self,goal): # input: goal of a vertex # return the vertex if len(self._outgoing)==0: print("GOAL: ",goal) raise ValueError('vertex DNE') for i in self._outgoing.keys(): if i.goal==goal: return i return None # raise ValueError('vertex DNE') def encoding_to_edge(self,rule_encoding): # input: encoding of a edge # return :the corresponding edge if the edge exists, none otherwise edges = list(self.edges()) for i in range(len(edges)): if edges[i].rule_encoding==rule_encoding: return edges[i] return None def first_vertex_without_goal(self): # return the vertex with the smallest idx that is without goal vertices=sorted(self.vertices(), key = lambda u: u.idx) for i in range(len(vertices)): if vertices[i].goal==None or vertices[i].goal=="": return vertices[i] return None def incoming_edge(self,v): # find the edge that connects v to a vertex of smaller idx incident_edges = self.incident_edges(v) incident_edges = list(incident_edges) curr_idx = v.idx curr_edge = None for i in range(len(incident_edges)): u,v = incident_edges[i].endpoints() if u.idx<=curr_idx and v.idx<=curr_idx: curr_edge = incident_edges[i] return curr_edge return curr_edge
""".. Ignore pydocstyle D400. =============== Resolwe Toolkit =============== This module includes general processes, schemas, tools and docker image definitions. """
def get(s, register): if s in 'abcdefghijklmnopqrstuvwxyz': return register[s] return int(s) def solveQuestion(inputPath): fileP = open(inputPath, 'r') instVals = [line.split() for line in fileP.read().strip().split("\n")] fileP.close() registers = {} registers[0] = {} registers[1] = {} for char in 'abcdefghijklmnopqrstuvwxyz': registers[0][char] = 0 registers[1][char] = 0 registers[1]['p'] = 1 indexs = [0, 0] sentData = [[], []] state = ['ok', 'ok'] programId = 0 register = registers[programId] index = indexs[programId] total = 0 while True: if instVals[index][0] == 'set': register[instVals[index][1]] = get(instVals[index][2], register) elif instVals[index][0] == 'add': register[instVals[index][1]] += get(instVals[index][2], register) elif instVals[index][0] == 'snd': if programId == 1: total += 1 sentData[programId].append(get(instVals[index][1], register)) elif instVals[index][0] == 'mul': register[instVals[index][1]] *= get(instVals[index][2], register) elif instVals[index][0] == 'mod': register[instVals[index][1]] %= get(instVals[index][2], register) elif instVals[index][0] == 'rcv': if sentData[1 - programId]: # the other program has sent data state[programId] = 'ok' register[instVals[index][1]] = sentData[1 - programId].pop(0) else: # Switch to other prog if state[1 - programId] == 'done': break if len(sentData[programId]) == 0 and state[1 - programId] == 'r': break indexs[programId] = index state[programId] = 'r' programId = 1 - programId index = indexs[programId] - 1 register = registers[programId] elif instVals[index][0] == 'jgz': if get(instVals[index][1], register) > 0: index += get(instVals[index][2], register) - 1 index += 1 if not 0 <= index < len(instVals): if state[1 - programId] == 'done': break state[programId] = 'done' indexs[programId] = index programId = 1 - programId index = indexs[programId] register = registers[programId] return total print(solveQuestion('InputD18Q2.txt'))
class ColumnWidthChangingEventArgs(CancelEventArgs): """ Provides data for the System.Windows.Forms.ListView.ColumnWidthChanging event. ColumnWidthChangingEventArgs(columnIndex: int,newWidth: int,cancel: bool) ColumnWidthChangingEventArgs(columnIndex: int,newWidth: int) """ @staticmethod def __new__(self, columnIndex, newWidth, cancel=None): """ __new__(cls: type,columnIndex: int,newWidth: int,cancel: bool) __new__(cls: type,columnIndex: int,newWidth: int) """ pass ColumnIndex = property( lambda self: object(), lambda self, v: None, lambda self: None ) """Gets the index of the column whose width is changing. Get: ColumnIndex(self: ColumnWidthChangingEventArgs) -> int """ NewWidth = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets or sets the new width for the column. Get: NewWidth(self: ColumnWidthChangingEventArgs) -> int Set: NewWidth(self: ColumnWidthChangingEventArgs)=value """
# import standard modules # import third party modules # import third party modules class Layer(object): """ Parent class for all layer classes used for a model. For this framework is does only have one attribute which all layers share, however, it is important to keep things sorted in case of future enrichment. """ def __init__(self): self.cache = None # placeholder for incoming for modified data which must be captured
""" URL lookup for common views """ common_urls = [ ]
PRECISION = 100 class PiCalculator(object): def __init__(self, precision): self.precision = precision def divide_one_by(self, b): divider = 1 result = "" for x in range(self.precision): if divider // b == 0: divider *= 10 result += "0" else: partial = divider // b divider -= partial * b divider *= 10 result += str(partial) return "%s.%s" % (result[0], result[1:]) def add_two_strings(self, a, b): assert len(a) == len(b) a = a[::-1] b = b[::-1] result = '' overflow = 0 for i, _ in enumerate(a): if a[i] == '.': result += '.' continue r = int(a[i]) + int(b[i]) + overflow if r >= 10: overflow = r // 10 r -= 10 else: overflow = 0 result += str(r) return result[::-1] if overflow == 0 else str(overflow) + result[::-1] def sub_two_strings(self, a, b): assert len(a) == len(b) a = a[::-1] b = b[::-1] result = '' overflow = 0 for i, _ in enumerate(a): if a[i] == '.': result += '.' continue r = int(a[i]) - int(b[i]) - overflow if r < 0: overflow = 1 r += 10 else: overflow = 0 result += str(r) return result[::-1] def multiply_string_by_four(self, a): a = a[::-1] result = '' overflow = 0 for i in a: if i == '.': result += '.' continue r = int(i) * 4 + overflow if r >= 10: overflow = r // 10 r = r - overflow * 10 else: overflow = 0 result += str(r) return result[::-1] if overflow == 0 else str(overflow) + result[::-1] if __name__ == '__main__': ITERATIONS = 10000 PRECISION = 100 pi_calculator = PiCalculator(PRECISION) result_list = [] for a in range(1, ITERATIONS, 2): result_list.append(pi_calculator.divide_one_by(a)) result = result_list[0] for i, _ in enumerate(result_list, 1): try: if i % 2 != 0: result = pi_calculator.sub_two_strings(result, result_list[i]) else: result = pi_calculator.add_two_strings(result, result_list[i]) except IndexError: pass print(pi_calculator.multiply_string_by_four(result))
def area(a, b): return (a * b) / 2 print(area(6, 9)) print(area(5, 8))
class Notify(): def __get__(self, instance, owner): print('正在读取资料') def __set__(self, instance, value): print('正在设置') def __delete__(self, instance): print('正在删除') class MyDes(): x = Notify()
'''1. Написать программу, которая будет складывать, вычитать, умножать или делить два числа. Числа и знак операции вводятся пользователем. После выполнения вычисления программа не должна завершаться, а должна запрашивать новые данные для вычислений. Завершение программы должно выполняться при вводе символа '0' в качестве знака операции. Если пользователь вводит неверный знак (не "0", "+", "-", "*", "/"), то программа должна сообщать ему об ошибке и снова запрашивать знак операции. Также сообщать пользователю о невозможности деления на ноль, если он ввел 0 в качестве делителя.''' while True: try: number1, operation, number2 = [ i for i in input( 'Введите математическое выражение (число операнд число): ' ).split() ] except ValueError: print('Неправильный ввод.') continue number1 = int(number1) number2 = int(number2) if operation == '0': break elif operation == '+': print(f'{number1} {operation} {number2} = {number1 + number2}') elif operation == '-': print(f'{number1} {operation} {number2} = {number1 - number2}') elif operation == '*': print(f'{number1} {operation} {number2} = {number1 * number2}') elif operation == '/': try: print(f'{number1} {operation} {number2} = {number1 / number2}') except ZeroDivisionError: print('Ошибка. Деление на ноль')
# returns the classification or None if no classification could be determined def calcClass(arr): sel0 = arr[0] > 0.0 sel1 = arr[1] > 0.0 if sel0 and sel1: # is selection valid? if not then we just ignore the result! n = 2 maxSelVal = float("-inf") maxSelIdx = None for iIdx in range(n): if arr[iIdx] > maxSelVal: maxSelIdx = iIdx maxSelVal = arr[iIdx] return maxSelIdx else: return None # no classification was possible
""" Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. Example 1: Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree: 3 / \ 4 5 / \ \ 5 4 7 Note: The merging process must start from the root nodes of both trees. """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if t1 is None and t2 is None: return None else: result_root = TreeNode(0) stack = [] if t1 is None: result_root.val = t2.val stack.append((None, t2.right, result_root, False)) stack.append((None, t2.left, result_root, True)) else: if t2 is None: result_root.val = t1.val stack.append((t1.right, None, result_root, False)) stack.append((t1.left, None, result_root, True)) else: result_root.val = t1.val + t2.val stack.append((t1.right, t2.right, result_root, False)) stack.append((t1.left, t2.left, result_root, True)) while len(stack) > 0: node_tuple = stack.pop() t1_node = node_tuple[0] t2_node = node_tuple[1] result_parent = node_tuple[2] is_left_child = node_tuple[3] if t1_node is None and t2_node is None: continue else: if t1_node is None: result_node = TreeNode(t2_node.val) stack.append((None, t2_node.right, result_node, False)) stack.append((None, t2_node.left, result_node, True)) else: if t2_node is None: result_node = TreeNode(t1_node.val) stack.append( (t1_node.right, None, result_node, False)) stack.append( (t1_node.left, None, result_node, True)) else: result_node = TreeNode(t1_node.val + t2_node.val) stack.append( (t1_node.right, t2_node.right, result_node, False)) stack.append( (t1_node.left, t2_node.left, result_node, True)) if is_left_child: result_parent.left = result_node else: result_parent.right = result_node return result_root def create_tree(values): values_len = len(values) if values_len == 0: return None root = TreeNode(values[0]) nodes = [] nodes.append(root) i = 1 while i < values_len: node_parent = nodes.pop(0) left_value = values[i] if left_value is None: node_parent.left = None else: left_node = TreeNode(left_value) node_parent.left = left_node nodes.append(left_node) i += 1 if i < values_len: right_value = values[i] right_node = TreeNode(right_value) node_parent.right = right_node nodes.append(right_node) i += 1 return root if __name__ == "__main__": tests = [ # ([[1, 3, 2, 5], [2, 1, 3, None, 4, None, 7]]), ([[], [1]]) ] s = Solution() for t in tests: s.mergeTrees(create_tree(t[0]), create_tree(t[1]))
''' Leetcode problem No 301 Remove Invalid Parentheses Solution written by Xuqiang Fang on 5 July, 2018 ''' class Solution(object): def removeInvalidParentheses(self, s): """ :type s: str :rtype: List[str] """ l = 0; r = 0 for c in s: if c == '(': l += 1 if l == 0: if c == ')': r += 1 else: if c == ')': l -= 1 ans = [] self.dfs(s, 0, l, r, ans) return ans def dfs(self, s, start, l, r, ans): if l == 0 and r == 0: if self.isValid(s): ans.append(s) return for i in range(start, len(s)): if i != start and s[i] == s[i-1]: continue if s[i] == '(' or s[i] == ')': curr = s[:i] + s[i+1:] if r > 0: self.dfs(curr, i, l, r-1, ans) elif l > 0: self.dfs(curr, i, l-1, r, ans) def isValid(self, s): count = 0 for c in s: if c == '(': count += 1 if c == ')': count -= 1 if count < 0: return False return count == 0 def combination(self, l, c):#select c from l ''' l is a list, we have to select c elements from l ''' ans = set() self.dfs_(ans, l, c, []) return ans def dfs_(self, ans, l, c, t): if len(t) > c: return if len(t) == c: ans.add(tuple(t)) return for j in l: if j not in t: t.append(j) self.dfs(ans, l, c, t) t.remove(j) def main(): s = Solution() print(s.removeInvalidParentheses('()())()')) print(s.removeInvalidParentheses('(a)())()')) print(s.removeInvalidParentheses(')(')) print(s.removeInvalidParentheses(')()()()((((()))()(')) print(s.removeInvalidParentheses('((((()))()')) print(len(s.removeInvalidParentheses('((((()()(fdsfas90()))((((((())))))))))(fsdafs()))()()afdsafsfs)'))) print(s.removeInvalidParentheses('((((()()(fdsfas90()))((((((())))))))))(fsdafs()))()()afdsafsfs)')) main()
# -*- coding: utf-8 -*- """Implementation of the ``tcell_crg_report`` step This step collects all of the calls and information gathered for the BIH T cell CRG and generates an Excel report for each patient. .. note:: Status: not implemented yet ========== Step Input ========== The BIH T cell CRG report generator uses the following as input: - ``somatic_variant_annotation`` - ``somatic_epitope_prediction`` - ``somatic_variant_checking`` - ``somatic_ngs_sanity_checks`` =========== Step Output =========== .. note:: TODO ===================== Default Configuration ===================== The default configuration is as follows. .. include:: DEFAULT_CONFIG_tcell_crg_report.rst ============================= Available Gene Fusion Callers ============================= - ``cnvkit`` """ __author__ = "Manuel Holtgrewe <manuel.holtgrewe@bihealth.de>" #: Default configuration for the tcell_crg_report step DEFAULT_CONFIG = r""" # Default configuration tcell_crg_report step_config: tcell_crg_report: path_somatic_variant_annotation: ../somatic_variant_annotation # REQUIRED """
#Tipo string n = str(input('Digite um valor')) print(n) #tipo inteiro n1 = int(input('Digite um valor')) print(n1) #tipo float n2 = float(input('Digite um valor real')) print(n2) #tipo booleano v = bool(input('Insira um número')) print('Quando o tipo e bool a pergunta se {} é verdadeiro ou falto'.format(v)) #Tipo métedo is b = input(' digite um número') print(b.isnumeric()) print(b.isalpha()) print(b.isdecimal())
def MAD(data : np.array): """ returns the median absolute deviation of a distribution useful for non-normal distributions, etc. """ return np.median(abs(data - np.median(data)))
class Solution: def search(self, arr, target) -> int: """O(logn) time | O(1) space""" l, h = 0, len(arr)-1 while l <= h: mid = (l+h)//2 if arr[mid] == target: return mid elif target < arr[mid]: if arr[l] <= target or arr[l] > arr[mid]: h = mid - 1 else: l = mid + 1 else: if arr[h] >= target or arr[h] < arr[mid]: l = mid + 1 else: h = mid - 1 return -1
__doc__ = """Just a sketch for now. """ __author__ = "Rui Campos" class Element(dict): def __init__(self, Z): self.__dict__[Z] = 1 self.Z = Z def __mul__(self, other): #usual checks if not (isinstance(other, float) or isinstance(other, int)): return NotImplemented self.__dict__[Z] *= other def __add__(self, other): if isinstance(other, float) or isinstance(other, int): return NotImplemented return Molecule()
""" utils.py Copyright 2011 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation version 2 of the License. w3af is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with w3af; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ def is_black_image(img_inst): """:return: True if the image is completely black""" img_width, img_height = img_inst.size for x in xrange(img_width): for y in xrange(img_height): # 0 means black color if img_inst.getpixel((x, y)) != 0: return False return True
_base_ = './faster_rcnn_obb_r50_fpn_1x_dota2.0.py' # fp16 settings fp16 = dict(loss_scale=512.)