content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# https://www.facebook.com/hackercup/problem/169401886867367/ __author__ = "Moonis Javed" __email__ = "monis.javed@gmail.com" def numberOfDays(arr): arr = sorted(arr) n = 0 while len(arr) > 0: k = arr[-1] w = k del arr[-1] while w <= 50: try: del arr[0] w += k except: break if w > 50: n += 1 return n if __name__ == "__main__": f = open("input2.txt").read().split("\n") writeF = open("output2.txt","w") n = int(f[0]) del f[0] for i in range(1,n+1): t = int(f[0]) del f[0] arr =[None]*t for j in xrange(t): arr[j] = int(f[0]) del f[0] writeF.write("Case #%d: %d\n" % (i,numberOfDays(arr))) # print i
__author__ = 'Moonis Javed' __email__ = 'monis.javed@gmail.com' def number_of_days(arr): arr = sorted(arr) n = 0 while len(arr) > 0: k = arr[-1] w = k del arr[-1] while w <= 50: try: del arr[0] w += k except: break if w > 50: n += 1 return n if __name__ == '__main__': f = open('input2.txt').read().split('\n') write_f = open('output2.txt', 'w') n = int(f[0]) del f[0] for i in range(1, n + 1): t = int(f[0]) del f[0] arr = [None] * t for j in xrange(t): arr[j] = int(f[0]) del f[0] writeF.write('Case #%d: %d\n' % (i, number_of_days(arr)))
class Robot: def __init__(self, left="MOTOR4", right="MOTOR2", config=1): print("init") def forward(self): print("forward") def backward(self): print("backward") def left(self): print("left") def right(self): print("right") def stop(self): print("stop")
class Robot: def __init__(self, left='MOTOR4', right='MOTOR2', config=1): print('init') def forward(self): print('forward') def backward(self): print('backward') def left(self): print('left') def right(self): print('right') def stop(self): print('stop')
"""Exceptions.""" class OandaError(Exception): """ Generic error class, catches oanda response errors """ def __init__(self, error_response): self.error_response = error_response msg = f"OANDA API returned error code {error_response['code']} ({error_response['message']}) " super(OandaError, self).__init__(msg) class BadEnvironment(Exception): """environment should be: sandbox, practice or live.""" def __init__(self, environment): msg = f"Environment '{environment}' does not exist" super(BadEnvironment, self).__init__(msg)
"""Exceptions.""" class Oandaerror(Exception): """ Generic error class, catches oanda response errors """ def __init__(self, error_response): self.error_response = error_response msg = f"OANDA API returned error code {error_response['code']} ({error_response['message']}) " super(OandaError, self).__init__(msg) class Badenvironment(Exception): """environment should be: sandbox, practice or live.""" def __init__(self, environment): msg = f"Environment '{environment}' does not exist" super(BadEnvironment, self).__init__(msg)
''' Created on 1.12.2016 @author: Darren '''''' Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). Note: Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. " '''
""" Created on 1.12.2016 @author: Darren Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). Note: Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. " """
#Represents an object class Object: def __init__(self,ID,name): self.name = name self.ID = ID self.importance = 1 #keep track of the events in which this file was the object self.modifiedIn = [] self.addedIn = [] self.deletedIn = [] def getName(self): return self.name def getID(self): return self.ID def getImportance(self): return self.importance #Add an event to the right list according to the modifier #@param event : Event object #@param modifier : "Added" "Deleted" or "Modified" def addEvent(self, event, modifier): if modifier == "Added": if(not event in self.addedIn): self.addedIn.append(event) elif modifier == "Deleted": if(not event in self.deletedIn): self.deletedIn.append(event) else: if(not event in self.modifiedIn): self.modifiedIn.append(event) #Function that calculates the importance of a object based on a ratio: #the number of months in which it was changed / the number of months is exists #@param firstAndLastTimeStamp = tuple with the first timestamp of the log and the last def calculateImportanceRatio(self,firstAndLastTimeStamp): addedTimestamps = [] for event in self.addedIn: addedTimestamps.append(event.getTimestamp()) addedTimestamps.sort() deletedTimestamps = [] for event in self.deletedIn: deletedTimestamps.append(event.getTimestamp()) deletedTimestamps.sort() timestamps = [] for event in self.modifiedIn: timestamps.append(event.getTimestamp()) for event in self.addedIn: timestamps.append(event.getTimestamp()) numberOfMonthsExistence = 0 numberOfMonthsChanged = 0 iteratorAdded = 0 iteratorDeleted = 0 if(not addedTimestamps): beginstamp = firstAndLastTimeStamp[0] #only 2 scenarios possible : 0 or 1 deleted timestamp if(not deletedTimestamps): endstamp = firstAndLastTimeStamp[1] else: endstamp = deletedTimestamps[0] numberOfMonthsExistence += self.calculateNumberOfMonthsExistence(beginstamp,endstamp) numberOfMonthsChanged += self.calculateNumberOfMonthsChanged(beginstamp,endstamp,timestamps) while(iteratorAdded < len(addedTimestamps)): beginstamp = addedTimestamps[iteratorAdded] iteratorAdded += 1 if(iteratorDeleted == len(deletedTimestamps)): #all deleted stamps are done endstamp = firstAndLastTimeStamp[1] else: endstamp = deletedTimestamps[iteratorDeleted] iteratorDeleted += 1 if(endstamp < beginstamp): beginstamp = firstAndLastTimeStamp[0] iteratorAdded -= 1 numberOfMonthsExistence += self.calculateNumberOfMonthsExistence(beginstamp,endstamp) numberOfMonthsChanged += self.calculateNumberOfMonthsChanged(beginstamp,endstamp,timestamps) importance = numberOfMonthsChanged/numberOfMonthsExistence #TO DO: what if importance = 0 ? if importance == 0 : importance = 0.00001 self.importance = importance #calculate how many months this object exists between these 2 timestamps def calculateNumberOfMonthsExistence(self,beginstamp, endstamp): numberOfMonths = abs(endstamp.year - beginstamp.year) * 12 + abs(endstamp.month - beginstamp.month) numberOfMonths += 1 return numberOfMonths #calculate in how many months between begin and end the object was changed #@param timestamps = list of timestamps when the file was committed def calculateNumberOfMonthsChanged(self,beginstamp,endstamp,timestamps): timestamps.sort() numberOfMonths = 0 currentMonth = -1 currentYear = -1 for stamp in timestamps: #only consider the timestamps between the timespan if((stamp >= beginstamp)and(stamp <= endstamp)): if((stamp.month != currentMonth) or (currentYear != stamp.year)): currentMonth = stamp.month currentYear = stamp.year numberOfMonths += 1 return numberOfMonths
class Object: def __init__(self, ID, name): self.name = name self.ID = ID self.importance = 1 self.modifiedIn = [] self.addedIn = [] self.deletedIn = [] def get_name(self): return self.name def get_id(self): return self.ID def get_importance(self): return self.importance def add_event(self, event, modifier): if modifier == 'Added': if not event in self.addedIn: self.addedIn.append(event) elif modifier == 'Deleted': if not event in self.deletedIn: self.deletedIn.append(event) elif not event in self.modifiedIn: self.modifiedIn.append(event) def calculate_importance_ratio(self, firstAndLastTimeStamp): added_timestamps = [] for event in self.addedIn: addedTimestamps.append(event.getTimestamp()) addedTimestamps.sort() deleted_timestamps = [] for event in self.deletedIn: deletedTimestamps.append(event.getTimestamp()) deletedTimestamps.sort() timestamps = [] for event in self.modifiedIn: timestamps.append(event.getTimestamp()) for event in self.addedIn: timestamps.append(event.getTimestamp()) number_of_months_existence = 0 number_of_months_changed = 0 iterator_added = 0 iterator_deleted = 0 if not addedTimestamps: beginstamp = firstAndLastTimeStamp[0] if not deletedTimestamps: endstamp = firstAndLastTimeStamp[1] else: endstamp = deletedTimestamps[0] number_of_months_existence += self.calculateNumberOfMonthsExistence(beginstamp, endstamp) number_of_months_changed += self.calculateNumberOfMonthsChanged(beginstamp, endstamp, timestamps) while iteratorAdded < len(addedTimestamps): beginstamp = addedTimestamps[iteratorAdded] iterator_added += 1 if iteratorDeleted == len(deletedTimestamps): endstamp = firstAndLastTimeStamp[1] else: endstamp = deletedTimestamps[iteratorDeleted] iterator_deleted += 1 if endstamp < beginstamp: beginstamp = firstAndLastTimeStamp[0] iterator_added -= 1 number_of_months_existence += self.calculateNumberOfMonthsExistence(beginstamp, endstamp) number_of_months_changed += self.calculateNumberOfMonthsChanged(beginstamp, endstamp, timestamps) importance = numberOfMonthsChanged / numberOfMonthsExistence if importance == 0: importance = 1e-05 self.importance = importance def calculate_number_of_months_existence(self, beginstamp, endstamp): number_of_months = abs(endstamp.year - beginstamp.year) * 12 + abs(endstamp.month - beginstamp.month) number_of_months += 1 return numberOfMonths def calculate_number_of_months_changed(self, beginstamp, endstamp, timestamps): timestamps.sort() number_of_months = 0 current_month = -1 current_year = -1 for stamp in timestamps: if stamp >= beginstamp and stamp <= endstamp: if stamp.month != currentMonth or currentYear != stamp.year: current_month = stamp.month current_year = stamp.year number_of_months += 1 return numberOfMonths
def uint(x): # casts x to unsigned int (1 byte) return x & 0xff def chunkify(string, size): # breaks up string into chunks of size chunks = [] for i in range(0, len(string), size): chunks.append(string[i:i + size]) return chunks def gen_rcons(rounds): # generates and returns round constants # the round constants don't depend on the # key so these constants could have been # hard coded, but I wanted to build it anyway rcons = [] for i in range(rounds): value = 0 if i + 1 > 1: if rcons[i - 1] >= 0x80: value = uint((2 * rcons[i - 1]) ^ 0x11b) else: value = uint(2 * rcons[i - 1]) else: value = 1 rcons.append(value) return list(map(lambda x: x << 24, rcons)) def generate_round_keys(key, rounds, sbox): # Generates round keys based on main key # basic variables used for looping, etc. key_size = len(key) * 8 R = rounds + 1 rcons = gen_rcons(rounds) # get round key constants N = key_size // 32 # split key into 32 bit words and parse to int K = [int(k.encode("utf-8").hex(), 16) for k in chunkify(key, 4)] W = [0] * (4 * R) # main loop to generate expanded round subkeys for i in range(4 * R): if i < N: W[i] = K[i] elif i >= N and i % N == 0: word_str = hex(W[i - 1])[2:].zfill(8) # turn int to 8 digit hex rot = word_str[2:] + word_str[:2] # rotate left 1 byte hex_bytes = chunkify(rot, 2) # split into byte chunks subvals = [sbox(hexb) for hexb in hex_bytes] # sub out hex bytes with s-box sval = (subvals[0] << 24) \ + (subvals[1] << 16) \ + (subvals[2] << 8) \ + subvals[3] # concat hex bytes and parse to 32 bit int W[i] = W[i - N] ^ sval ^ rcons[(i // N) - 1] elif i >= N and N > 6 and i % N == 4: word_str = hex(W[i - 1])[2:].zfill(8) # turn int to 8 digit hex hex_bytes = chunkify(word_str, 2) # split into byte chunks subvals = [sbox(hexb) for hexb in hex_bytes] # sub out hex bytes with s-box sval = (subvals[0] << 24) \ + (subvals[1] << 16) \ + (subvals[2] << 8) \ + subvals[3] # concat hex bytes and parse to 32 bit int W[i] = W[i - N] ^ sval else: W[i] = W[i - N] ^ W[i - 1] # subkeys are all 128 bits, but each entry is 32 bits # so combine all entries by groups of 4 for later use return [tuple(W[i:i + 4]) for i in range(0, len(W), 4)] def add_round_key(state, round_key): # adds each byte of the round key to the # respective byte of the state key = [] # round key is a tuple of 4, 32 bit ints for rk in round_key: hx = hex(rk)[2:].zfill(8) # turn int to hex # add each byte to the key list as an int key += [int(hx[i:i + 2], 16) for i in range(0, len(hx), 2)] for i in range(len(state)): # run through the state and add each byte to the # respective byte in the key key_state = [key[j] for j in range(i, len(key), 4)] state[i] = [sv ^ kv for sv, kv in zip(state[i], key_state)] return state
def uint(x): return x & 255 def chunkify(string, size): chunks = [] for i in range(0, len(string), size): chunks.append(string[i:i + size]) return chunks def gen_rcons(rounds): rcons = [] for i in range(rounds): value = 0 if i + 1 > 1: if rcons[i - 1] >= 128: value = uint(2 * rcons[i - 1] ^ 283) else: value = uint(2 * rcons[i - 1]) else: value = 1 rcons.append(value) return list(map(lambda x: x << 24, rcons)) def generate_round_keys(key, rounds, sbox): key_size = len(key) * 8 r = rounds + 1 rcons = gen_rcons(rounds) n = key_size // 32 k = [int(k.encode('utf-8').hex(), 16) for k in chunkify(key, 4)] w = [0] * (4 * R) for i in range(4 * R): if i < N: W[i] = K[i] elif i >= N and i % N == 0: word_str = hex(W[i - 1])[2:].zfill(8) rot = word_str[2:] + word_str[:2] hex_bytes = chunkify(rot, 2) subvals = [sbox(hexb) for hexb in hex_bytes] sval = (subvals[0] << 24) + (subvals[1] << 16) + (subvals[2] << 8) + subvals[3] W[i] = W[i - N] ^ sval ^ rcons[i // N - 1] elif i >= N and N > 6 and (i % N == 4): word_str = hex(W[i - 1])[2:].zfill(8) hex_bytes = chunkify(word_str, 2) subvals = [sbox(hexb) for hexb in hex_bytes] sval = (subvals[0] << 24) + (subvals[1] << 16) + (subvals[2] << 8) + subvals[3] W[i] = W[i - N] ^ sval else: W[i] = W[i - N] ^ W[i - 1] return [tuple(W[i:i + 4]) for i in range(0, len(W), 4)] def add_round_key(state, round_key): key = [] for rk in round_key: hx = hex(rk)[2:].zfill(8) key += [int(hx[i:i + 2], 16) for i in range(0, len(hx), 2)] for i in range(len(state)): key_state = [key[j] for j in range(i, len(key), 4)] state[i] = [sv ^ kv for (sv, kv) in zip(state[i], key_state)] return state
def modulus_three(n): r = n % 3 if r == 0: print("Multiple of 3") elif r == 1: print("Remainder 1") else: assert r == 2, "Remainder is not 2" print("Remainder 2") def modulus_four(n): r = n % 4 if r == 0: print("Multiple of 4") elif r == 1: print("Remainder 1") elif r == 2: print("Remainder 2") elif r == 3: print("Remainder 3") else: assert False, "This should never happen" if __name__ == '__main__': print(modulus_four(5))
def modulus_three(n): r = n % 3 if r == 0: print('Multiple of 3') elif r == 1: print('Remainder 1') else: assert r == 2, 'Remainder is not 2' print('Remainder 2') def modulus_four(n): r = n % 4 if r == 0: print('Multiple of 4') elif r == 1: print('Remainder 1') elif r == 2: print('Remainder 2') elif r == 3: print('Remainder 3') else: assert False, 'This should never happen' if __name__ == '__main__': print(modulus_four(5))
""" Contains classes to handle batch data components """ class ComponentDescriptor: """ Class for handling one component item """ def __init__(self, component, default=None): self._component = component self._default = default def __get__(self, instance, cls): try: if instance.data is None: out = self._default elif instance.pos is None: out = instance.data[self._component] else: pos = instance.pos[self._component] data = instance.data[self._component] out = data[pos] if data is not None else self._default except IndexError: out = self._default return out def __set__(self, instance, value): if instance.pos is None: new_data = list(instance.data) if instance.data is not None else [] new_data = new_data + [None for _ in range(max(len(instance.components) - len(new_data), 0))] new_data[self._component] = value instance.data = tuple(new_data) else: pos = instance.pos[self._component] instance.data[self._component][pos] = value class BaseComponentsTuple: """ Base class for a component tuple """ components = None def __init__(self, data=None, pos=None): if isinstance(data, BaseComponentsTuple): self.data = data.data else: self.data = data if pos is not None and not isinstance(pos, list): pos = [pos for _ in self.components] self.pos = pos def __str__(self): s = '' for comp in self.components: d = getattr(self, comp) s += comp + '\n' + str(d) + '\n' return s def as_tuple(self, components=None): """ Return components data as a tuple """ components = tuple(components or self.components) return tuple(getattr(self, comp) for comp in components) class MetaComponentsTuple(type): """ Class factory for a component tuple """ def __init__(cls, *args, **kwargs): _ = kwargs super().__init__(*args, (BaseComponentsTuple,), {}) def __new__(mcs, name, components): comp_class = super().__new__(mcs, name, (BaseComponentsTuple,), {}) comp_class.components = components for i, comp in enumerate(components): setattr(comp_class, comp, ComponentDescriptor(i)) globals()[comp_class.__name__] = comp_class return comp_class
""" Contains classes to handle batch data components """ class Componentdescriptor: """ Class for handling one component item """ def __init__(self, component, default=None): self._component = component self._default = default def __get__(self, instance, cls): try: if instance.data is None: out = self._default elif instance.pos is None: out = instance.data[self._component] else: pos = instance.pos[self._component] data = instance.data[self._component] out = data[pos] if data is not None else self._default except IndexError: out = self._default return out def __set__(self, instance, value): if instance.pos is None: new_data = list(instance.data) if instance.data is not None else [] new_data = new_data + [None for _ in range(max(len(instance.components) - len(new_data), 0))] new_data[self._component] = value instance.data = tuple(new_data) else: pos = instance.pos[self._component] instance.data[self._component][pos] = value class Basecomponentstuple: """ Base class for a component tuple """ components = None def __init__(self, data=None, pos=None): if isinstance(data, BaseComponentsTuple): self.data = data.data else: self.data = data if pos is not None and (not isinstance(pos, list)): pos = [pos for _ in self.components] self.pos = pos def __str__(self): s = '' for comp in self.components: d = getattr(self, comp) s += comp + '\n' + str(d) + '\n' return s def as_tuple(self, components=None): """ Return components data as a tuple """ components = tuple(components or self.components) return tuple((getattr(self, comp) for comp in components)) class Metacomponentstuple(type): """ Class factory for a component tuple """ def __init__(cls, *args, **kwargs): _ = kwargs super().__init__(*args, (BaseComponentsTuple,), {}) def __new__(mcs, name, components): comp_class = super().__new__(mcs, name, (BaseComponentsTuple,), {}) comp_class.components = components for (i, comp) in enumerate(components): setattr(comp_class, comp, component_descriptor(i)) globals()[comp_class.__name__] = comp_class return comp_class
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 7 03:26:16 2019 @author: sodatab MITx: 6.00.1x """ """ 03.6-Finger How Many --------------------- Consider the following sequence of expressions: animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} animals['d'] = ['donkey'] animals['d'].append('dog') animals['d'].append('dingo') We want to write some simple procedures that work on dictionaries to return information. First, write a procedure, called how_many, which returns the sum of the number of values associated with a dictionary. """ """Answer Script:""" def how_many(aDict): ''' aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. ''' sum = 0 for i in aDict.values(): sum += len(i) return sum
""" Created on Mon Oct 7 03:26:16 2019 @author: sodatab MITx: 6.00.1x """ "\n03.6-Finger How Many\n---------------------\n Consider the following sequence of expressions:\n\nanimals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}\n\nanimals['d'] = ['donkey']\nanimals['d'].append('dog')\nanimals['d'].append('dingo')\n\nWe want to write some simple procedures that work on dictionaries to return information.\n\nFirst, write a procedure, called how_many, which returns the sum of the number of values associated with a dictionary.\n" 'Answer Script:' def how_many(aDict): """ aDict: A dictionary, where all the values are lists. returns: int, how many values are in the dictionary. """ sum = 0 for i in aDict.values(): sum += len(i) return sum
BASE_FILES = "C:\\Users\\Dani\\repos-git\\shexerp3\\test\\t_files\\" BASE_FILES_GENERAL = BASE_FILES + "general\\" G1 = BASE_FILES + "t_graph_1.ttl" G1_NT = BASE_FILES + "t_graph_1.nt" G1_TSVO_SPO = BASE_FILES + "t_graph_1.tsv" G1_JSON_LD = BASE_FILES + "t_graph_1.json" G1_XML = BASE_FILES + "t_graph_1.xml" G1_N3 = BASE_FILES + "t_graph_1.n3" G1_ALL_CLASSES_NO_COMMENTS = BASE_FILES_GENERAL + "g1_all_classes_no_comments.shex" # PREFIX xml: <http://www.w3.org/XML/1998/namespace/> # PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> # PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> # PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> # PREFIX foaf: <http://xmlns.com/foaf/0.1/> # NAMESPACES_WITH_FOAF_AND_EX = {"http://example.org/" : "ex", # "http://www.w3.org/XML/1998/namespace/" : "xml", # "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf", # "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", # "http://www.w3.org/2001/XMLSchema#": "xsd", # "http://xmlns.com/foaf/0.1/": "foaf" # } def default_namespaces(): return {"http://example.org/": "ex", "http://www.w3.org/XML/1998/namespace/": "xml", "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf", "http://www.w3.org/2000/01/rdf-schema#": "rdfs", "http://www.w3.org/2001/XMLSchema#": "xsd", "http://xmlns.com/foaf/0.1/": "foaf" }
base_files = 'C:\\Users\\Dani\\repos-git\\shexerp3\\test\\t_files\\' base_files_general = BASE_FILES + 'general\\' g1 = BASE_FILES + 't_graph_1.ttl' g1_nt = BASE_FILES + 't_graph_1.nt' g1_tsvo_spo = BASE_FILES + 't_graph_1.tsv' g1_json_ld = BASE_FILES + 't_graph_1.json' g1_xml = BASE_FILES + 't_graph_1.xml' g1_n3 = BASE_FILES + 't_graph_1.n3' g1_all_classes_no_comments = BASE_FILES_GENERAL + 'g1_all_classes_no_comments.shex' def default_namespaces(): return {'http://example.org/': 'ex', 'http://www.w3.org/XML/1998/namespace/': 'xml', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf', 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs', 'http://www.w3.org/2001/XMLSchema#': 'xsd', 'http://xmlns.com/foaf/0.1/': 'foaf'}
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") def deps(): excludes = native.existing_rules().keys() if "bazel_installer" not in excludes: http_file( name = "bazel_installer", downloaded_file_path = "bazel-installer.sh", sha256 = "bd7a3a583a18640f58308c26e654239d412adaa833b6b6a7b57a216ab62fabc2", urls = [ "https://releases.bazel.build/4.0.0/release/bazel-4.0.0-installer-linux-x86_64.sh", "https://github.com/bazelbuild/bazel/releases/download/4.0.0/bazel-4.0.0-installer-linux-x86_64.sh", ], )
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file') def deps(): excludes = native.existing_rules().keys() if 'bazel_installer' not in excludes: http_file(name='bazel_installer', downloaded_file_path='bazel-installer.sh', sha256='bd7a3a583a18640f58308c26e654239d412adaa833b6b6a7b57a216ab62fabc2', urls=['https://releases.bazel.build/4.0.0/release/bazel-4.0.0-installer-linux-x86_64.sh', 'https://github.com/bazelbuild/bazel/releases/download/4.0.0/bazel-4.0.0-installer-linux-x86_64.sh'])
#!/usr/bin/python def test_vars(): """test variables in python""" int_var = 5 string_var = "hah" assert int_var == 5 assert string_var == 'hah' print("test vars is done") if __name__ == "__main__": test_vars()
def test_vars(): """test variables in python""" int_var = 5 string_var = 'hah' assert int_var == 5 assert string_var == 'hah' print('test vars is done') if __name__ == '__main__': test_vars()
class Programmer: def __init__(self, name, language, skills): self.name = name self.language = language self.skills = skills def watch_course(self, course_name, language, skills_earned): if not self.language == language: return f"{self.name} does not know {language}" self.skills += skills_earned return f"{self.name} watched {course_name}" def change_language(self, new_language, skills_needed): if not skills_needed <= self.skills: needed_skills = skills_needed - self.skills return f"{self.name} needs {needed_skills} more skills" if self.language == new_language: return f"{self.name} already knows {self.language}" previous_language = self.language self.language = new_language return f"{self.name} switched from {previous_language} to {new_language}"
class Programmer: def __init__(self, name, language, skills): self.name = name self.language = language self.skills = skills def watch_course(self, course_name, language, skills_earned): if not self.language == language: return f'{self.name} does not know {language}' self.skills += skills_earned return f'{self.name} watched {course_name}' def change_language(self, new_language, skills_needed): if not skills_needed <= self.skills: needed_skills = skills_needed - self.skills return f'{self.name} needs {needed_skills} more skills' if self.language == new_language: return f'{self.name} already knows {self.language}' previous_language = self.language self.language = new_language return f'{self.name} switched from {previous_language} to {new_language}'
#returns the value to the variable # x = 900 print(x) #print will take the argument x as the value in the variable #
x = 900 print(x)
def add(tree, x): if not tree: tree.extend([x, None, None]) print('DONE') return key = tree[0] if x == key: print('ALREADY') elif x < key: left = tree[1] if left == None: tree[1] = [x, None, None] print('DONE') else: add(left, x) elif x > key: right = tree[2] if right == None: tree[2] = [x, None, None] print('DONE') else: add(right, x) def find(tree, x): if not tree: return False key = tree[0] if x == key: return True elif x < key: left = tree[1] if left == None: return False else: return find(left, x) elif x > key: right = tree[2] if right == None: return False else: return find(right, x) def printtree(tree, count=0): # if not tree: # return if tree[1]: printtree(tree[1], count + 1) print(f"{''.join('.' * count)}{tree[0]}") if tree[2]: printtree(tree[2], count + 1) tree = [] with open('input.txt', 'r', encoding='utf-8') as file: string = file.readline().strip() while string != '': line = [i for i in string.split()] if line[0] == 'ADD': add(tree, int(line[1])) elif line[0] == 'SEARCH': if find(tree, int(line[1])): print('YES') else: print('NO') elif line[0] == 'PRINTTREE': printtree(tree) string = file.readline().strip()
def add(tree, x): if not tree: tree.extend([x, None, None]) print('DONE') return key = tree[0] if x == key: print('ALREADY') elif x < key: left = tree[1] if left == None: tree[1] = [x, None, None] print('DONE') else: add(left, x) elif x > key: right = tree[2] if right == None: tree[2] = [x, None, None] print('DONE') else: add(right, x) def find(tree, x): if not tree: return False key = tree[0] if x == key: return True elif x < key: left = tree[1] if left == None: return False else: return find(left, x) elif x > key: right = tree[2] if right == None: return False else: return find(right, x) def printtree(tree, count=0): if tree[1]: printtree(tree[1], count + 1) print(f"{''.join('.' * count)}{tree[0]}") if tree[2]: printtree(tree[2], count + 1) tree = [] with open('input.txt', 'r', encoding='utf-8') as file: string = file.readline().strip() while string != '': line = [i for i in string.split()] if line[0] == 'ADD': add(tree, int(line[1])) elif line[0] == 'SEARCH': if find(tree, int(line[1])): print('YES') else: print('NO') elif line[0] == 'PRINTTREE': printtree(tree) string = file.readline().strip()
batch_size, num_samples, sample_rate = 32, 32000, 16000.0 # A Tensor of [batch_size, num_samples] mono PCM samples in the range [-1, 1]. pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32) # A 1024-point STFT with frames of 64 ms and 75% overlap. stfts = tf.signal.stft(pcm, frame_length=1024, frame_step=256, fft_length=1024) spectrograms = tf.abs(stfts) # Warp the linear scale spectrograms into the mel-scale. num_spectrogram_bins = stfts.shape[-1].value lower_edge_hertz, upper_edge_hertz, num_mel_bins = 80.0, 7600.0, 80 linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix( num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz, upper_edge_hertz) mel_spectrograms = tf.tensordot( spectrograms, linear_to_mel_weight_matrix, 1) mel_spectrograms.set_shape(spectrograms.shape[:-1].concatenate( linear_to_mel_weight_matrix.shape[-1:])) # Compute a stabilized log to get log-magnitude mel-scale spectrograms. log_mel_spectrograms = tf.math.log(mel_spectrograms + 1e-6) # Compute MFCCs from log_mel_spectrograms and take the first 13. mfccs = tf.signal.mfccs_from_log_mel_spectrograms( log_mel_spectrograms)[..., :13]
(batch_size, num_samples, sample_rate) = (32, 32000, 16000.0) pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32) stfts = tf.signal.stft(pcm, frame_length=1024, frame_step=256, fft_length=1024) spectrograms = tf.abs(stfts) num_spectrogram_bins = stfts.shape[-1].value (lower_edge_hertz, upper_edge_hertz, num_mel_bins) = (80.0, 7600.0, 80) linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix(num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz, upper_edge_hertz) mel_spectrograms = tf.tensordot(spectrograms, linear_to_mel_weight_matrix, 1) mel_spectrograms.set_shape(spectrograms.shape[:-1].concatenate(linear_to_mel_weight_matrix.shape[-1:])) log_mel_spectrograms = tf.math.log(mel_spectrograms + 1e-06) mfccs = tf.signal.mfccs_from_log_mel_spectrograms(log_mel_spectrograms)[..., :13]
"""Top-level package for mynlp.""" __author__ = """Suneel Dondapati""" __email__ = 'dsuneel1@gmail.com' __version__ = '0.1.0'
"""Top-level package for mynlp.""" __author__ = 'Suneel Dondapati' __email__ = 'dsuneel1@gmail.com' __version__ = '0.1.0'
""" User Get Key Value Input Dictionary Start """ dic = { "google": "google is provide job and internship.", "amezon": "amezon is e-commerce store and cloud computing provider.", "zoom": "zoom is provide video call system to connecting meeating.", "microsoft": "microsoft is owner of windows and office software.." } # For beginner print("google") print("amezon") print("zoom") print("microsoft") key = input("search detail of dectionary! \n") print(dic[key.lower()]) # For advance while True: for index, item in dic.items(): print(index) key = input("search detail of dectionary! \n") print(dic[key.lower()]) if int(input("Press 1 to exit 0 to continue \n")): break """ User Get Key Value Input Dictionary End """
""" User Get Key Value Input Dictionary Start """ dic = {'google': 'google is provide job and internship.', 'amezon': 'amezon is e-commerce store and cloud computing provider.', 'zoom': 'zoom is provide video call system to connecting meeating.', 'microsoft': 'microsoft is owner of windows and office software..'} print('google') print('amezon') print('zoom') print('microsoft') key = input('search detail of dectionary! \n') print(dic[key.lower()]) while True: for (index, item) in dic.items(): print(index) key = input('search detail of dectionary! \n') print(dic[key.lower()]) if int(input('Press 1 to exit 0 to continue \n')): break '\nUser Get Key Value Input Dictionary End\n'
# Copyright 2016 Dave Kludt # # 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. sample_product = { "title": "Test", "us_url": "http://us.test.com", "uk_url": "http://uk.test.com", "active": True, "db_name": "test", "require_region": True, "doc_url": "http://doc.test.com", "pitchfork_url": "https://pitchfork/url" } sample_limit = { "product": "test", "title": "Test", "uri": "/limits", "slug": "test", "active": True, "absolute_path": "test/path", "absolute_type": "list", "limit_key": "test_limit", "value_key": "test_value" } sample_log = { "queried": ["dns"], "queried_by": "skeletor", "region": "dfw", "ddi": "123456", 'query_results': [] } sample_auth_failure = { 'message': ( '<strong>Error!</strong> Authentication has failed due to' ' incorrect token or DDI. Please check the token and DDI ' 'and try again.' ) } """ DNS Tests """ dns = { "title": "DNS", "us_url": "https://us.test.com", "uk_url": "https://uk.test.com", "active": True, "db_name": "dns", "require_region": True, "doc_url": "https://doc.test.com", "pitchfork_url": "https://pitchfork.url", "limit_maps": [] } dns_limit = { "product": "dns", "title": "Domains", "uri": "/limits", "slug": "domains", "active": True, "absolute_path": "limits.absolute", "absolute_type": "dict", "value_key": "", "limit_key": "domains" } dns_limit_return = { "limits": { "rate": [ { "regex": ".*/v\\d+\\.\\d+/(\\d+/domains/search).*", "limit": [ { "value": 20, "verb": "GET", "next-available": "2016-01-12T13:56:11.450Z", "remaining": 20, "unit": "MINUTE" } ], "uri": "*/domains/search*" } ], "absolute": { "domains": 500, "records per domain": 500 } } } dns_list_return = { "domains": [ { "comment": "Test", "updated": "2015-12-08T20:47:02.000+0000", "name": "test.net", "created": "2015-04-09T15:42:49.000+0000", "emailAddress": "skeletor@rackspace.com", "id": 123465798, "accountId": 1234567 } ], "totalEntries": 1 } dns_full_return = { 'dns': { 'values': {'Domains': 1}, 'limits': {'Domains': 500} } } """ Autoscale """ autoscale = { "title": "Autoscale", "us_url": "https://us.test.com", "uk_url": "https://uk.test.com", "active": True, "db_name": "autoscale", "require_region": True, "doc_url": "https://doc.test.com", "pitchfork_url": "https://pitchfork.url", "limit_maps": [] } autoscale_limit = { "product": "autoscale", "title": "Max Groups", "absolute_path": "limits.absolute", "uri": "/v1.0/{ddi}/limits", "slug": "max_groups", "value_key": "", "absolute_type": "dict", "active": True, "limit_key": "maxGroups" } autoscale_limit_return = { "limits": { "rate": [ { "regex": "/v1\\.0/execute/(.*)", "limit": [ { "value": 10, "verb": "ALL", "next-available": "2016-01-12T14:51:13.402Z", "remaining": 10, "unit": "SECOND" } ], "uri": "/v1.0/execute/*" } ], "absolute": { "maxGroups": 1000, "maxPoliciesPerGroup": 100, "maxWebhooksPerPolicy": 25 } } } autoscale_list_return = { "groups": [ { "state": { "status": "ACTIVE", "desiredCapacity": 0, "paused": False, "active": [], "pendingCapacity": 0, "activeCapacity": 0, "name": "test" }, "id": "d446f3c2-612f-41b8-92dc-4d6e1422bde2", "links": [ { "href": ( 'https://dfw.autoscale.api.rackspacecloud.com/v1.0' '/1234567/groups/d446f3c2-612f-41b8-92dc-4d6e1422bde2/' ), "rel": "self" } ] } ], "groups_links": [] } autoscale_full_return = { 'autoscale': { 'values': {'Max Groups': 1}, 'limits': {'Max Groups': 1000} } } """ Big Data """ big_data = { "title": "Big Data", "us_url": "https://us.test.com", "uk_url": "https://uk.test.com", "active": True, "db_name": "big_data", "require_region": True, "doc_url": "https://doc.test.com", "pitchfork_url": "https://pitchfork.url", "limit_maps": [] } big_data_limit = [ { "product": "big_data", "title": "Node Count", "absolute_path": "limits.absolute.node_count", "uri": "/v2/{ddi}/limits", "slug": "node_count", "value_key": "remaining", "absolute_type": "dict", "active": True, "limit_key": "limit" }, { "product": "big_data", "title": "Disk - MB", "absolute_path": "limits.absolute.disk", "uri": "/v2/{ddi}/limits", "slug": "disk_-_mb", "value_key": "remaining", "absolute_type": "dict", "active": True, "limit_key": "limit" } ] big_data_limit_return = { "limits": { "absolute": { "node_count": { "limit": 15, "remaining": 8 }, "disk": { "limit": 50000, "remaining": 25000 }, "ram": { "limit": 655360, "remaining": 555360 }, "vcpus": { "limit": 200, "remaining": 120 } } } } big_data_full_return = { 'big_data': { 'values': {'Node Count': 7, 'Disk - MB': 25000}, 'limits': {'Node Count': 15, 'Disk - MB': 50000} } } """ CBS """ cbs = { "title": "CBS", "us_url": "https://us.test.com", "uk_url": "https://uk.test.com", "active": True, "db_name": "cbs", "require_region": True, "doc_url": "https://doc.test.com", "pitchfork_url": "https://pitchfork.url", "limit_maps": [] } cbs_limit = { "product": "cbs", "title": "SATA - GB", "absolute_path": "quota_set.gigabytes_SATA", "uri": "/v1/{ddi}/os-quota-sets/{ddi}?usage=True", "slug": "sata_-_gb", "value_key": "in_use", "absolute_type": "dict", "active": True, "limit_key": "limit" } cbs_limit_return = { "quota_set": { "volumes": { "limit": -1, "reserved": 0, "in_use": 3 }, "gigabytes_SATA": { "limit": 10240, "reserved": 0, "in_use": 325 }, "gigabytes_SSD": { "limit": 10240, "reserved": 0, "in_use": 50 } } } cbs_full_return = { 'cbs': { 'values': {'SATA - GB': 9915}, 'limits': {'SATA - GB': 10240} } } """ Load Balancers """ clb = { "title": "Load Balancers", "us_url": "https://us.test.com", "uk_url": "https://uk.test.com", "active": True, "db_name": "load_balancers", "require_region": True, "doc_url": "https://doc.test.com", "pitchfork_url": "https://pitchfork.url", "limit_maps": [] } clb_limit = [ { "product": "load_balancers", "title": "Total Load Balancers", "uri": "/v1.0/{ddi}/loadbalancers/absolutelimits", "slug": "total_load_balancers", "active": True, "path": "absolute['LOADBALANCER_LIMIT']", "absolute_path": "absolute", "value_key": "", "absolute_type": "list", "limit_key": "LOADBALANCER_LIMIT" }, { "product": "load_balancers", "title": "Nodes per LB", "uri": "/v1.0/{ddi}/loadbalancers/absolutelimits", "slug": "nodes_per_lb", "active": True, "path": "absolute['NODE_LIMIT']", "absolute_path": "absolute", "value_key": "", "absolute_type": "list", "limit_key": "NODE_LIMIT" } ] clb_limit_return = { "absolute": [ { "name": "IPV6_LIMIT", "value": 25 }, { "name": "LOADBALANCER_LIMIT", "value": 25 }, { "name": "BATCH_DELETE_LIMIT", "value": 10 }, { "name": "ACCESS_LIST_LIMIT", "value": 100 }, { "name": "NODE_LIMIT", "value": 25 }, { "name": "NODE_META_LIMIT", "value": 25 }, { "name": "LOADBALANCER_META_LIMIT", "value": 25 }, { "name": "CERTIFICATE_MAPPING_LIMIT", "value": 20 } ] } clb_list_return = { "loadBalancers": [ { "status": "ACTIVE", "updated": { "time": "2016-01-12T16:04:44Z" }, "protocol": "HTTP", "name": "test", "algorithm": "LEAST_CONNECTIONS", "created": { "time": "2016-01-12T16:04:44Z" }, "virtualIps": [ { "ipVersion": "IPV4", "type": "PUBLIC", "id": 19875, "address": "148.62.0.226" }, { "ipVersion": "IPV6", "type": "PUBLIC", "id": 9318325, "address": "2001:4800:7904:0100:f46f:211b:0000:0001" } ], "id": 506497, "timeout": 30, "nodeCount": 0, "port": 80 } ] } clb_full_return = { 'load_balancers': { 'values': {'Total Load Balancers': 1}, 'limits': {'Total Load Balancers': 25, 'Nodes per LB': 25} } } """ Servers """ server = { "title": "Servers", "us_url": "https://us.test.com", "uk_url": "https://uk.test.com", "active": True, "db_name": "servers", "require_region": True, "doc_url": "https://doc.test.com", "pitchfork_url": "https://pitchfork.url", "limit_maps": [] } server_limit = [ { "product": "servers", "title": "Servers", "uri": "/v2/{ddi}/limits", "slug": "servers", "active": True, "path": "absolute['maxTotalInstances']", "absolute_path": "limits.absolute", "value_key": "", "absolute_type": "dict", "limit_key": "maxTotalInstances" }, { "product": "servers", "title": "Private Networks", "uri": "/v2/{ddi}/limits", "slug": "private_networks", "active": True, "path": "absolute['maxTotalPrivateNetworks']", "absolute_path": "limits.absolute", "value_key": "", "absolute_type": "dict", "limit_key": "maxTotalPrivateNetworks" }, { "product": "servers", "title": "Ram - MB", "uri": "/v2/{ddi}/limits", "slug": "ram_-_mb", "active": True, "path": "absolute['maxTotalRAMSize']", "absolute_path": "limits.absolute", "value_key": "", "absolute_type": "dict", "limit_key": "maxTotalRAMSize" } ] server_limit_return = { "limits": { "rate": [ { "regex": "/[^/]*/?$", "limit": [ { "next-available": "2016-01-12T16:14:47.624Z", "unit": "MINUTE", "verb": "GET", "remaining": 2200, "value": 2200 } ], "uri": "*" }, { "regex": ( "/v[^/]+/[^/]+/servers/([^/]+)/rax-si-image-schedule" ), "limit": [ { "next-available": "2016-01-12T16:14:47.624Z", "unit": "SECOND", "verb": "POST", "remaining": 10, "value": 10 } ], "uri": "/servers/{id}/rax-si-image-schedule" } ], "absolute": { "maxPersonalitySize": 1000, "maxTotalCores": -1, "maxPersonality": 5, "totalPrivateNetworksUsed": 1, "maxImageMeta": 40, "maxTotalPrivateNetworks": 10, "maxSecurityGroupRules": -1, "maxTotalKeypairs": 100, "totalRAMUsed": 4096, "maxSecurityGroups": -1, "totalFloatingIpsUsed": 0, "totalInstancesUsed": 3, "totalSecurityGroupsUsed": 0, "maxServerMeta": 40, "maxTotalFloatingIps": -1, "maxTotalInstances": 200, "totalCoresUsed": 4, "maxTotalRAMSize": 256000 } } } server_list_return = { "servers": [ { "OS-EXT-STS:task_state": None, "addresses": { "public": [ { "version": 4, "addr": "104.130.28.32" }, { "version": 6, "addr": "2001:4802:7803:104:be76:4eff:fe21:51b7" } ], "private": [ { "version": 4, "addr": "10.176.205.68" } ] }, "flavor": { "id": "general1-1", "links": [ { "href": ( "https://iad.servers.api.rackspacecloud.com" "/766030/flavors/general1-1" ), "rel": "bookmark" } ] }, "id": "3290e50d-888f-4500-a934-16c10f3b8a10", "user_id": "284275", "OS-DCF:diskConfig": "MANUAL", "accessIPv4": "104.130.28.32", "accessIPv6": "2001:4802:7803:104:be76:4eff:fe21:51b7", "progress": 100, "OS-EXT-STS:power_state": 1, "config_drive": "", "status": "ACTIVE", "updated": "2016-01-12T15:16:37Z", "name": "test-server", "created": "2016-01-12T15:15:39Z", "tenant_id": "1234567", "metadata": { "build_config": "", "rax_service_level_automation": "Complete" } } ] } server_list_processed_return = [ { 'status': 'ACTIVE', 'updated': '2016-01-12T15:16:37Z', 'OS-EXT-STS:task_state': None, 'user_id': '284275', 'addresses': { 'public': [ { 'version': 4, 'addr': '104.130.28.32' }, { 'version': 6, 'addr': '2001:4802:7803:104:be76:4eff:fe21:51b7' } ], 'private': [ { 'version': 4, 'addr': '10.176.205.68' } ] }, 'created': '2016-01-12T15:15:39Z', 'tenant_id': '1234567', 'OS-DCF:diskConfig': 'MANUAL', 'id': '3290e50d-888f-4500-a934-16c10f3b8a10', 'accessIPv4': '104.130.28.32', 'accessIPv6': '2001:4802:7803:104:be76:4eff:fe21:51b7', 'config_drive': '', 'progress': 100, 'OS-EXT-STS:power_state': 1, 'metadata': { 'build_config': '', 'rax_service_level_automation': 'Complete' }, 'flavor': { 'id': 'general1-1', 'links': [ { 'href': ( 'https://iad.servers.api.rackspacecloud.com' '/766030/flavors/general1-1' ), 'rel': 'bookmark' } ] }, 'name': 'test-server' } ] network_list_return = { "networks": [ { "status": "ACTIVE", "subnets": [ "879ff280-6f17-4fd8-b684-19237d88fc45" ], "name": "test-network", "admin_state_up": True, "tenant_id": "1234567", "shared": False, "id": "e737483a-00d7-4517-afc3-bd1fbbbd4cd3" } ] } network_processed_list = [ { 'status': 'ACTIVE', 'subnets': [ '879ff280-6f17-4fd8-b684-19237d88fc45' ], 'name': 'test-network', 'admin_state_up': True, 'tenant_id': '1234567', 'shared': False, 'id': 'e737483a-00d7-4517-afc3-bd1fbbbd4cd3' } ] server_flavor_return = { "flavor": { "ram": 1024, "name": "1 GB General Purpose v1", "OS-FLV-WITH-EXT-SPECS:extra_specs": { "number_of_data_disks": "0", "class": "general1", "disk_io_index": "40", "policy_class": "general_flavor" }, "vcpus": 1, "swap": "", "rxtx_factor": 200.0, "OS-FLV-EXT-DATA:ephemeral": 0, "disk": 20, "id": "general1-1" } } server_full_return = { 'servers': { 'values': { 'Private Networks': 1, 'Ram - MB': 1024, 'Servers': 1 }, 'limits': { 'Private Networks': 10, 'Ram - MB': 256000, 'Servers': 200 } } }
sample_product = {'title': 'Test', 'us_url': 'http://us.test.com', 'uk_url': 'http://uk.test.com', 'active': True, 'db_name': 'test', 'require_region': True, 'doc_url': 'http://doc.test.com', 'pitchfork_url': 'https://pitchfork/url'} sample_limit = {'product': 'test', 'title': 'Test', 'uri': '/limits', 'slug': 'test', 'active': True, 'absolute_path': 'test/path', 'absolute_type': 'list', 'limit_key': 'test_limit', 'value_key': 'test_value'} sample_log = {'queried': ['dns'], 'queried_by': 'skeletor', 'region': 'dfw', 'ddi': '123456', 'query_results': []} sample_auth_failure = {'message': '<strong>Error!</strong> Authentication has failed due to incorrect token or DDI. Please check the token and DDI and try again.'} ' DNS Tests ' dns = {'title': 'DNS', 'us_url': 'https://us.test.com', 'uk_url': 'https://uk.test.com', 'active': True, 'db_name': 'dns', 'require_region': True, 'doc_url': 'https://doc.test.com', 'pitchfork_url': 'https://pitchfork.url', 'limit_maps': []} dns_limit = {'product': 'dns', 'title': 'Domains', 'uri': '/limits', 'slug': 'domains', 'active': True, 'absolute_path': 'limits.absolute', 'absolute_type': 'dict', 'value_key': '', 'limit_key': 'domains'} dns_limit_return = {'limits': {'rate': [{'regex': '.*/v\\d+\\.\\d+/(\\d+/domains/search).*', 'limit': [{'value': 20, 'verb': 'GET', 'next-available': '2016-01-12T13:56:11.450Z', 'remaining': 20, 'unit': 'MINUTE'}], 'uri': '*/domains/search*'}], 'absolute': {'domains': 500, 'records per domain': 500}}} dns_list_return = {'domains': [{'comment': 'Test', 'updated': '2015-12-08T20:47:02.000+0000', 'name': 'test.net', 'created': '2015-04-09T15:42:49.000+0000', 'emailAddress': 'skeletor@rackspace.com', 'id': 123465798, 'accountId': 1234567}], 'totalEntries': 1} dns_full_return = {'dns': {'values': {'Domains': 1}, 'limits': {'Domains': 500}}} ' Autoscale ' autoscale = {'title': 'Autoscale', 'us_url': 'https://us.test.com', 'uk_url': 'https://uk.test.com', 'active': True, 'db_name': 'autoscale', 'require_region': True, 'doc_url': 'https://doc.test.com', 'pitchfork_url': 'https://pitchfork.url', 'limit_maps': []} autoscale_limit = {'product': 'autoscale', 'title': 'Max Groups', 'absolute_path': 'limits.absolute', 'uri': '/v1.0/{ddi}/limits', 'slug': 'max_groups', 'value_key': '', 'absolute_type': 'dict', 'active': True, 'limit_key': 'maxGroups'} autoscale_limit_return = {'limits': {'rate': [{'regex': '/v1\\.0/execute/(.*)', 'limit': [{'value': 10, 'verb': 'ALL', 'next-available': '2016-01-12T14:51:13.402Z', 'remaining': 10, 'unit': 'SECOND'}], 'uri': '/v1.0/execute/*'}], 'absolute': {'maxGroups': 1000, 'maxPoliciesPerGroup': 100, 'maxWebhooksPerPolicy': 25}}} autoscale_list_return = {'groups': [{'state': {'status': 'ACTIVE', 'desiredCapacity': 0, 'paused': False, 'active': [], 'pendingCapacity': 0, 'activeCapacity': 0, 'name': 'test'}, 'id': 'd446f3c2-612f-41b8-92dc-4d6e1422bde2', 'links': [{'href': 'https://dfw.autoscale.api.rackspacecloud.com/v1.0/1234567/groups/d446f3c2-612f-41b8-92dc-4d6e1422bde2/', 'rel': 'self'}]}], 'groups_links': []} autoscale_full_return = {'autoscale': {'values': {'Max Groups': 1}, 'limits': {'Max Groups': 1000}}} ' Big Data ' big_data = {'title': 'Big Data', 'us_url': 'https://us.test.com', 'uk_url': 'https://uk.test.com', 'active': True, 'db_name': 'big_data', 'require_region': True, 'doc_url': 'https://doc.test.com', 'pitchfork_url': 'https://pitchfork.url', 'limit_maps': []} big_data_limit = [{'product': 'big_data', 'title': 'Node Count', 'absolute_path': 'limits.absolute.node_count', 'uri': '/v2/{ddi}/limits', 'slug': 'node_count', 'value_key': 'remaining', 'absolute_type': 'dict', 'active': True, 'limit_key': 'limit'}, {'product': 'big_data', 'title': 'Disk - MB', 'absolute_path': 'limits.absolute.disk', 'uri': '/v2/{ddi}/limits', 'slug': 'disk_-_mb', 'value_key': 'remaining', 'absolute_type': 'dict', 'active': True, 'limit_key': 'limit'}] big_data_limit_return = {'limits': {'absolute': {'node_count': {'limit': 15, 'remaining': 8}, 'disk': {'limit': 50000, 'remaining': 25000}, 'ram': {'limit': 655360, 'remaining': 555360}, 'vcpus': {'limit': 200, 'remaining': 120}}}} big_data_full_return = {'big_data': {'values': {'Node Count': 7, 'Disk - MB': 25000}, 'limits': {'Node Count': 15, 'Disk - MB': 50000}}} ' CBS ' cbs = {'title': 'CBS', 'us_url': 'https://us.test.com', 'uk_url': 'https://uk.test.com', 'active': True, 'db_name': 'cbs', 'require_region': True, 'doc_url': 'https://doc.test.com', 'pitchfork_url': 'https://pitchfork.url', 'limit_maps': []} cbs_limit = {'product': 'cbs', 'title': 'SATA - GB', 'absolute_path': 'quota_set.gigabytes_SATA', 'uri': '/v1/{ddi}/os-quota-sets/{ddi}?usage=True', 'slug': 'sata_-_gb', 'value_key': 'in_use', 'absolute_type': 'dict', 'active': True, 'limit_key': 'limit'} cbs_limit_return = {'quota_set': {'volumes': {'limit': -1, 'reserved': 0, 'in_use': 3}, 'gigabytes_SATA': {'limit': 10240, 'reserved': 0, 'in_use': 325}, 'gigabytes_SSD': {'limit': 10240, 'reserved': 0, 'in_use': 50}}} cbs_full_return = {'cbs': {'values': {'SATA - GB': 9915}, 'limits': {'SATA - GB': 10240}}} ' Load Balancers ' clb = {'title': 'Load Balancers', 'us_url': 'https://us.test.com', 'uk_url': 'https://uk.test.com', 'active': True, 'db_name': 'load_balancers', 'require_region': True, 'doc_url': 'https://doc.test.com', 'pitchfork_url': 'https://pitchfork.url', 'limit_maps': []} clb_limit = [{'product': 'load_balancers', 'title': 'Total Load Balancers', 'uri': '/v1.0/{ddi}/loadbalancers/absolutelimits', 'slug': 'total_load_balancers', 'active': True, 'path': "absolute['LOADBALANCER_LIMIT']", 'absolute_path': 'absolute', 'value_key': '', 'absolute_type': 'list', 'limit_key': 'LOADBALANCER_LIMIT'}, {'product': 'load_balancers', 'title': 'Nodes per LB', 'uri': '/v1.0/{ddi}/loadbalancers/absolutelimits', 'slug': 'nodes_per_lb', 'active': True, 'path': "absolute['NODE_LIMIT']", 'absolute_path': 'absolute', 'value_key': '', 'absolute_type': 'list', 'limit_key': 'NODE_LIMIT'}] clb_limit_return = {'absolute': [{'name': 'IPV6_LIMIT', 'value': 25}, {'name': 'LOADBALANCER_LIMIT', 'value': 25}, {'name': 'BATCH_DELETE_LIMIT', 'value': 10}, {'name': 'ACCESS_LIST_LIMIT', 'value': 100}, {'name': 'NODE_LIMIT', 'value': 25}, {'name': 'NODE_META_LIMIT', 'value': 25}, {'name': 'LOADBALANCER_META_LIMIT', 'value': 25}, {'name': 'CERTIFICATE_MAPPING_LIMIT', 'value': 20}]} clb_list_return = {'loadBalancers': [{'status': 'ACTIVE', 'updated': {'time': '2016-01-12T16:04:44Z'}, 'protocol': 'HTTP', 'name': 'test', 'algorithm': 'LEAST_CONNECTIONS', 'created': {'time': '2016-01-12T16:04:44Z'}, 'virtualIps': [{'ipVersion': 'IPV4', 'type': 'PUBLIC', 'id': 19875, 'address': '148.62.0.226'}, {'ipVersion': 'IPV6', 'type': 'PUBLIC', 'id': 9318325, 'address': '2001:4800:7904:0100:f46f:211b:0000:0001'}], 'id': 506497, 'timeout': 30, 'nodeCount': 0, 'port': 80}]} clb_full_return = {'load_balancers': {'values': {'Total Load Balancers': 1}, 'limits': {'Total Load Balancers': 25, 'Nodes per LB': 25}}} ' Servers ' server = {'title': 'Servers', 'us_url': 'https://us.test.com', 'uk_url': 'https://uk.test.com', 'active': True, 'db_name': 'servers', 'require_region': True, 'doc_url': 'https://doc.test.com', 'pitchfork_url': 'https://pitchfork.url', 'limit_maps': []} server_limit = [{'product': 'servers', 'title': 'Servers', 'uri': '/v2/{ddi}/limits', 'slug': 'servers', 'active': True, 'path': "absolute['maxTotalInstances']", 'absolute_path': 'limits.absolute', 'value_key': '', 'absolute_type': 'dict', 'limit_key': 'maxTotalInstances'}, {'product': 'servers', 'title': 'Private Networks', 'uri': '/v2/{ddi}/limits', 'slug': 'private_networks', 'active': True, 'path': "absolute['maxTotalPrivateNetworks']", 'absolute_path': 'limits.absolute', 'value_key': '', 'absolute_type': 'dict', 'limit_key': 'maxTotalPrivateNetworks'}, {'product': 'servers', 'title': 'Ram - MB', 'uri': '/v2/{ddi}/limits', 'slug': 'ram_-_mb', 'active': True, 'path': "absolute['maxTotalRAMSize']", 'absolute_path': 'limits.absolute', 'value_key': '', 'absolute_type': 'dict', 'limit_key': 'maxTotalRAMSize'}] server_limit_return = {'limits': {'rate': [{'regex': '/[^/]*/?$', 'limit': [{'next-available': '2016-01-12T16:14:47.624Z', 'unit': 'MINUTE', 'verb': 'GET', 'remaining': 2200, 'value': 2200}], 'uri': '*'}, {'regex': '/v[^/]+/[^/]+/servers/([^/]+)/rax-si-image-schedule', 'limit': [{'next-available': '2016-01-12T16:14:47.624Z', 'unit': 'SECOND', 'verb': 'POST', 'remaining': 10, 'value': 10}], 'uri': '/servers/{id}/rax-si-image-schedule'}], 'absolute': {'maxPersonalitySize': 1000, 'maxTotalCores': -1, 'maxPersonality': 5, 'totalPrivateNetworksUsed': 1, 'maxImageMeta': 40, 'maxTotalPrivateNetworks': 10, 'maxSecurityGroupRules': -1, 'maxTotalKeypairs': 100, 'totalRAMUsed': 4096, 'maxSecurityGroups': -1, 'totalFloatingIpsUsed': 0, 'totalInstancesUsed': 3, 'totalSecurityGroupsUsed': 0, 'maxServerMeta': 40, 'maxTotalFloatingIps': -1, 'maxTotalInstances': 200, 'totalCoresUsed': 4, 'maxTotalRAMSize': 256000}}} server_list_return = {'servers': [{'OS-EXT-STS:task_state': None, 'addresses': {'public': [{'version': 4, 'addr': '104.130.28.32'}, {'version': 6, 'addr': '2001:4802:7803:104:be76:4eff:fe21:51b7'}], 'private': [{'version': 4, 'addr': '10.176.205.68'}]}, 'flavor': {'id': 'general1-1', 'links': [{'href': 'https://iad.servers.api.rackspacecloud.com/766030/flavors/general1-1', 'rel': 'bookmark'}]}, 'id': '3290e50d-888f-4500-a934-16c10f3b8a10', 'user_id': '284275', 'OS-DCF:diskConfig': 'MANUAL', 'accessIPv4': '104.130.28.32', 'accessIPv6': '2001:4802:7803:104:be76:4eff:fe21:51b7', 'progress': 100, 'OS-EXT-STS:power_state': 1, 'config_drive': '', 'status': 'ACTIVE', 'updated': '2016-01-12T15:16:37Z', 'name': 'test-server', 'created': '2016-01-12T15:15:39Z', 'tenant_id': '1234567', 'metadata': {'build_config': '', 'rax_service_level_automation': 'Complete'}}]} server_list_processed_return = [{'status': 'ACTIVE', 'updated': '2016-01-12T15:16:37Z', 'OS-EXT-STS:task_state': None, 'user_id': '284275', 'addresses': {'public': [{'version': 4, 'addr': '104.130.28.32'}, {'version': 6, 'addr': '2001:4802:7803:104:be76:4eff:fe21:51b7'}], 'private': [{'version': 4, 'addr': '10.176.205.68'}]}, 'created': '2016-01-12T15:15:39Z', 'tenant_id': '1234567', 'OS-DCF:diskConfig': 'MANUAL', 'id': '3290e50d-888f-4500-a934-16c10f3b8a10', 'accessIPv4': '104.130.28.32', 'accessIPv6': '2001:4802:7803:104:be76:4eff:fe21:51b7', 'config_drive': '', 'progress': 100, 'OS-EXT-STS:power_state': 1, 'metadata': {'build_config': '', 'rax_service_level_automation': 'Complete'}, 'flavor': {'id': 'general1-1', 'links': [{'href': 'https://iad.servers.api.rackspacecloud.com/766030/flavors/general1-1', 'rel': 'bookmark'}]}, 'name': 'test-server'}] network_list_return = {'networks': [{'status': 'ACTIVE', 'subnets': ['879ff280-6f17-4fd8-b684-19237d88fc45'], 'name': 'test-network', 'admin_state_up': True, 'tenant_id': '1234567', 'shared': False, 'id': 'e737483a-00d7-4517-afc3-bd1fbbbd4cd3'}]} network_processed_list = [{'status': 'ACTIVE', 'subnets': ['879ff280-6f17-4fd8-b684-19237d88fc45'], 'name': 'test-network', 'admin_state_up': True, 'tenant_id': '1234567', 'shared': False, 'id': 'e737483a-00d7-4517-afc3-bd1fbbbd4cd3'}] server_flavor_return = {'flavor': {'ram': 1024, 'name': '1 GB General Purpose v1', 'OS-FLV-WITH-EXT-SPECS:extra_specs': {'number_of_data_disks': '0', 'class': 'general1', 'disk_io_index': '40', 'policy_class': 'general_flavor'}, 'vcpus': 1, 'swap': '', 'rxtx_factor': 200.0, 'OS-FLV-EXT-DATA:ephemeral': 0, 'disk': 20, 'id': 'general1-1'}} server_full_return = {'servers': {'values': {'Private Networks': 1, 'Ram - MB': 1024, 'Servers': 1}, 'limits': {'Private Networks': 10, 'Ram - MB': 256000, 'Servers': 200}}}
class Element: dependencies = [] def __init__(self, name): self.name = name def add_dependencies(self, *elements): for element in elements: if not self.dependencies.__contains__(element): self.dependencies.append(element) def remove_dependencies(self, *elements): for element in elements: if self.dependencies.__contains__(element): self.dependencies.remove(element)
class Element: dependencies = [] def __init__(self, name): self.name = name def add_dependencies(self, *elements): for element in elements: if not self.dependencies.__contains__(element): self.dependencies.append(element) def remove_dependencies(self, *elements): for element in elements: if self.dependencies.__contains__(element): self.dependencies.remove(element)
# known contracts from protocol CONTRACTS = [ # NFT - Meteor Dust "terra1p70x7jkqhf37qa7qm4v23g4u4g8ka4ktxudxa7", # NFT - Eggs "terra1k0y373yxqne22pc9g7jvnr4qclpsxtafevtrpg", # NFT - Dragons "terra1vhuyuwwr4rkdpez5f5lmuqavut28h5dt29rpn6", # NFT - Loot "terra14gfnxnwl0yz6njzet4n33erq5n70wt79nm24el", ] def handle(exporter, elem, txinfo, contract): print(f"Levana! {contract}") #print(elem)
contracts = ['terra1p70x7jkqhf37qa7qm4v23g4u4g8ka4ktxudxa7', 'terra1k0y373yxqne22pc9g7jvnr4qclpsxtafevtrpg', 'terra1vhuyuwwr4rkdpez5f5lmuqavut28h5dt29rpn6', 'terra14gfnxnwl0yz6njzet4n33erq5n70wt79nm24el'] def handle(exporter, elem, txinfo, contract): print(f'Levana! {contract}')
def isPalindrome(string, i = 0): j = len(string) - 1 -i return True if i > j else string[i] == string[j] and isPalindrome(string, i+1) def isPalindrome(string): return string == string[::-1] def isPalindromeUsingIndexes(string): lIx = 0 rIdx = len(string) -1 while lIx < rIdx: if(string[lIx] != string [rIdx]): return False else: lIx += 1 rIdx -=1 return True
def is_palindrome(string, i=0): j = len(string) - 1 - i return True if i > j else string[i] == string[j] and is_palindrome(string, i + 1) def is_palindrome(string): return string == string[::-1] def is_palindrome_using_indexes(string): l_ix = 0 r_idx = len(string) - 1 while lIx < rIdx: if string[lIx] != string[rIdx]: return False else: l_ix += 1 r_idx -= 1 return True
# coding=utf-8 # *** WARNING: this file was generated by crd2pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** SNAKE_TO_CAMEL_CASE_TABLE = { "access_modes": "accessModes", "api_group": "apiGroup", "api_version": "apiVersion", "app_protocol": "appProtocol", "association_status": "associationStatus", "available_nodes": "availableNodes", "change_budget": "changeBudget", "client_ip": "clientIP", "cluster_ip": "clusterIP", "config_ref": "configRef", "daemon_set": "daemonSet", "data_source": "dataSource", "elasticsearch_association_status": "elasticsearchAssociationStatus", "elasticsearch_ref": "elasticsearchRef", "expected_nodes": "expectedNodes", "external_i_ps": "externalIPs", "external_name": "externalName", "external_traffic_policy": "externalTrafficPolicy", "file_realm": "fileRealm", "health_check_node_port": "healthCheckNodePort", "ip_family": "ipFamily", "kibana_association_status": "kibanaAssociationStatus", "kibana_ref": "kibanaRef", "last_probe_time": "lastProbeTime", "last_transition_time": "lastTransitionTime", "load_balancer_ip": "loadBalancerIP", "load_balancer_source_ranges": "loadBalancerSourceRanges", "match_expressions": "matchExpressions", "match_labels": "matchLabels", "max_surge": "maxSurge", "max_unavailable": "maxUnavailable", "min_available": "minAvailable", "node_port": "nodePort", "node_sets": "nodeSets", "pod_disruption_budget": "podDisruptionBudget", "pod_template": "podTemplate", "publish_not_ready_addresses": "publishNotReadyAddresses", "remote_clusters": "remoteClusters", "rolling_update": "rollingUpdate", "secret_name": "secretName", "secret_token_secret": "secretTokenSecret", "secure_settings": "secureSettings", "self_signed_certificate": "selfSignedCertificate", "service_account_name": "serviceAccountName", "session_affinity": "sessionAffinity", "session_affinity_config": "sessionAffinityConfig", "storage_class_name": "storageClassName", "subject_alt_names": "subjectAltNames", "target_port": "targetPort", "timeout_seconds": "timeoutSeconds", "topology_keys": "topologyKeys", "update_strategy": "updateStrategy", "volume_claim_templates": "volumeClaimTemplates", "volume_mode": "volumeMode", "volume_name": "volumeName", } CAMEL_TO_SNAKE_CASE_TABLE = { "accessModes": "access_modes", "apiGroup": "api_group", "apiVersion": "api_version", "appProtocol": "app_protocol", "associationStatus": "association_status", "availableNodes": "available_nodes", "changeBudget": "change_budget", "clientIP": "client_ip", "clusterIP": "cluster_ip", "configRef": "config_ref", "daemonSet": "daemon_set", "dataSource": "data_source", "elasticsearchAssociationStatus": "elasticsearch_association_status", "elasticsearchRef": "elasticsearch_ref", "expectedNodes": "expected_nodes", "externalIPs": "external_i_ps", "externalName": "external_name", "externalTrafficPolicy": "external_traffic_policy", "fileRealm": "file_realm", "healthCheckNodePort": "health_check_node_port", "ipFamily": "ip_family", "kibanaAssociationStatus": "kibana_association_status", "kibanaRef": "kibana_ref", "lastProbeTime": "last_probe_time", "lastTransitionTime": "last_transition_time", "loadBalancerIP": "load_balancer_ip", "loadBalancerSourceRanges": "load_balancer_source_ranges", "matchExpressions": "match_expressions", "matchLabels": "match_labels", "maxSurge": "max_surge", "maxUnavailable": "max_unavailable", "minAvailable": "min_available", "nodePort": "node_port", "nodeSets": "node_sets", "podDisruptionBudget": "pod_disruption_budget", "podTemplate": "pod_template", "publishNotReadyAddresses": "publish_not_ready_addresses", "remoteClusters": "remote_clusters", "rollingUpdate": "rolling_update", "secretName": "secret_name", "secretTokenSecret": "secret_token_secret", "secureSettings": "secure_settings", "selfSignedCertificate": "self_signed_certificate", "serviceAccountName": "service_account_name", "sessionAffinity": "session_affinity", "sessionAffinityConfig": "session_affinity_config", "storageClassName": "storage_class_name", "subjectAltNames": "subject_alt_names", "targetPort": "target_port", "timeoutSeconds": "timeout_seconds", "topologyKeys": "topology_keys", "updateStrategy": "update_strategy", "volumeClaimTemplates": "volume_claim_templates", "volumeMode": "volume_mode", "volumeName": "volume_name", }
snake_to_camel_case_table = {'access_modes': 'accessModes', 'api_group': 'apiGroup', 'api_version': 'apiVersion', 'app_protocol': 'appProtocol', 'association_status': 'associationStatus', 'available_nodes': 'availableNodes', 'change_budget': 'changeBudget', 'client_ip': 'clientIP', 'cluster_ip': 'clusterIP', 'config_ref': 'configRef', 'daemon_set': 'daemonSet', 'data_source': 'dataSource', 'elasticsearch_association_status': 'elasticsearchAssociationStatus', 'elasticsearch_ref': 'elasticsearchRef', 'expected_nodes': 'expectedNodes', 'external_i_ps': 'externalIPs', 'external_name': 'externalName', 'external_traffic_policy': 'externalTrafficPolicy', 'file_realm': 'fileRealm', 'health_check_node_port': 'healthCheckNodePort', 'ip_family': 'ipFamily', 'kibana_association_status': 'kibanaAssociationStatus', 'kibana_ref': 'kibanaRef', 'last_probe_time': 'lastProbeTime', 'last_transition_time': 'lastTransitionTime', 'load_balancer_ip': 'loadBalancerIP', 'load_balancer_source_ranges': 'loadBalancerSourceRanges', 'match_expressions': 'matchExpressions', 'match_labels': 'matchLabels', 'max_surge': 'maxSurge', 'max_unavailable': 'maxUnavailable', 'min_available': 'minAvailable', 'node_port': 'nodePort', 'node_sets': 'nodeSets', 'pod_disruption_budget': 'podDisruptionBudget', 'pod_template': 'podTemplate', 'publish_not_ready_addresses': 'publishNotReadyAddresses', 'remote_clusters': 'remoteClusters', 'rolling_update': 'rollingUpdate', 'secret_name': 'secretName', 'secret_token_secret': 'secretTokenSecret', 'secure_settings': 'secureSettings', 'self_signed_certificate': 'selfSignedCertificate', 'service_account_name': 'serviceAccountName', 'session_affinity': 'sessionAffinity', 'session_affinity_config': 'sessionAffinityConfig', 'storage_class_name': 'storageClassName', 'subject_alt_names': 'subjectAltNames', 'target_port': 'targetPort', 'timeout_seconds': 'timeoutSeconds', 'topology_keys': 'topologyKeys', 'update_strategy': 'updateStrategy', 'volume_claim_templates': 'volumeClaimTemplates', 'volume_mode': 'volumeMode', 'volume_name': 'volumeName'} camel_to_snake_case_table = {'accessModes': 'access_modes', 'apiGroup': 'api_group', 'apiVersion': 'api_version', 'appProtocol': 'app_protocol', 'associationStatus': 'association_status', 'availableNodes': 'available_nodes', 'changeBudget': 'change_budget', 'clientIP': 'client_ip', 'clusterIP': 'cluster_ip', 'configRef': 'config_ref', 'daemonSet': 'daemon_set', 'dataSource': 'data_source', 'elasticsearchAssociationStatus': 'elasticsearch_association_status', 'elasticsearchRef': 'elasticsearch_ref', 'expectedNodes': 'expected_nodes', 'externalIPs': 'external_i_ps', 'externalName': 'external_name', 'externalTrafficPolicy': 'external_traffic_policy', 'fileRealm': 'file_realm', 'healthCheckNodePort': 'health_check_node_port', 'ipFamily': 'ip_family', 'kibanaAssociationStatus': 'kibana_association_status', 'kibanaRef': 'kibana_ref', 'lastProbeTime': 'last_probe_time', 'lastTransitionTime': 'last_transition_time', 'loadBalancerIP': 'load_balancer_ip', 'loadBalancerSourceRanges': 'load_balancer_source_ranges', 'matchExpressions': 'match_expressions', 'matchLabels': 'match_labels', 'maxSurge': 'max_surge', 'maxUnavailable': 'max_unavailable', 'minAvailable': 'min_available', 'nodePort': 'node_port', 'nodeSets': 'node_sets', 'podDisruptionBudget': 'pod_disruption_budget', 'podTemplate': 'pod_template', 'publishNotReadyAddresses': 'publish_not_ready_addresses', 'remoteClusters': 'remote_clusters', 'rollingUpdate': 'rolling_update', 'secretName': 'secret_name', 'secretTokenSecret': 'secret_token_secret', 'secureSettings': 'secure_settings', 'selfSignedCertificate': 'self_signed_certificate', 'serviceAccountName': 'service_account_name', 'sessionAffinity': 'session_affinity', 'sessionAffinityConfig': 'session_affinity_config', 'storageClassName': 'storage_class_name', 'subjectAltNames': 'subject_alt_names', 'targetPort': 'target_port', 'timeoutSeconds': 'timeout_seconds', 'topologyKeys': 'topology_keys', 'updateStrategy': 'update_strategy', 'volumeClaimTemplates': 'volume_claim_templates', 'volumeMode': 'volume_mode', 'volumeName': 'volume_name'}
# -*- coding: utf-8 -*- # Importing Libraries """ # Commented out IPython magic to ensure Python compatibility. import torch import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import torch.nn as nn from tqdm import tqdm_notebook from sklearn.preprocessing import MinMaxScaler # %matplotlib inline torch.manual_seed(0) """# Loading Dataset""" sns.get_dataset_names() flight_data = sns.load_dataset("flights") flight_data.head() """# Preprocessing""" # Changing the plot size figsize = plt.rcParams["figure.figsize"] figsize[0] = 15 figsize[1] = 5 plt.rcParams["figure.figsize"] = figsize # Plotting the data plt.title("Time Series Representation of Data") plt.xlabel("Months") plt.ylabel("Passengers") plt.grid(True) plt.autoscale(axis = "x",tight=True) plt.plot(flight_data["passengers"]) #Please note that this is univariate time series data : consisting of one variable passengers # data = flight_data["passengers"].values.astype(float) print(data) print(len(data)) # Train-Test Split # Consider the last the 12 months data as evaluation data for testing the model's behaviour train_window = 12 train_data = data[:-train_window] test_data = data[-train_window:] print(len(train_data)) print(len(test_data)) # Normalizing the train-data scaler = MinMaxScaler(feature_range=(-1,1)) train_data_normalized = scaler.fit_transform(train_data.reshape(-1,1)) print(train_data_normalized[:10]) # Converting to Torch Tensor train_data_normalized = torch.FloatTensor(train_data_normalized).view(-1) print(train_data_normalized) # Final step is creating sequences of length 12 (12 months data) from the train-data and # the label for each sequence is the passenger_data for the (12+1)th Month def create_in_sequences(input_data,tw): in_seq = [] L = len(input_data) for i in range(L-tw): train_seq = input_data[i:i+tw] train_label = input_data[i+tw:i+tw+1] in_seq.append((train_seq,train_label)) return in_seq # Therefore, we get 120 train sequences along with the label value train_in_seq = create_in_sequences(train_data_normalized,train_window) print(len(train_in_seq)) print(train_in_seq[:5]) """# The Model Please note that the model considered here is: 1. LSTM layer with a univariate input sequence of length 12 and LSTM's previous hidden cell consisting of previous hidden state and previous cell state of length 100 and also , the size of LSTM's output is 100 2. The second layer is a Linear layer of 100 inputs from the LSTM's output and a single output size """ class LSTM(nn.Module): #LSTM Class inheriting the inbuilt nn.Module class for neural networks def __init__(self,input_size = 1,hidden_layer_size = 100, output_size = 1): super().__init__() #Calls the init function of the nn.Module superclass for being able to access its features self.hidden_layer_size = hidden_layer_size # Defines the size of h(t-1) [Previous hidden output] and c(t-1) [previous cell state] self.lstm = nn.LSTM(input_size,hidden_layer_size,dropout = 0.45) # definining the LSTM with univariate input,output and with a dropout regularization of 0.45 self.linear = nn.Linear(hidden_layer_size,output_size) # Linear layer which returns the weighted sum of 100 outputs from the LSTM self.hidden_cell = (torch.ones(1,1,self.hidden_layer_size), # This is the previous hidden state torch.ones(1,1,self.hidden_layer_size)) # This is the previous cell state def forward(self,input_seq): lstm_out, self.hidden_cell = self.lstm(input_seq.view(len(input_seq),1,-1),self.hidden_cell) #returns 1200 outputs from each of the 100 output neurons for the 12 valued sequence predictions = self.linear(lstm_out.view(len(input_seq),-1)) # Reshaped to make it compatible as an input to the linear layer return predictions[-1] # The last element contains the prediction model = LSTM() print(model) """# Loss Function and Learning Algorithm (Optimizer) Please note that for this simple model , * Loss Function considered is *Mean Squared Error* and * Optimization Function used is Stochastic Version of **Adam** *Optimizer*. """ loss_fn = nn.MSELoss() # Mean Squared Error Loss Function optimizer = torch.optim.Adam(model.parameters(),lr = 0.0002) # Adam Learning Algorithm """# Training""" epochs = 450 loss_plot = [] for epoch in tqdm_notebook(range(epochs), total=epochs, unit="epoch"): for seq,label in train_in_seq: optimizer.zero_grad() # makes the gradients zero for each new sequence model.hidden_cell = (torch.zeros(1,1,model.hidden_layer_size), # Initialising the previous hidden state and cell state for each new sequence torch.zeros(1,1,model.hidden_layer_size)) y_pred = model(seq) # Automatically calls the forward pass loss = loss_fn(y_pred,label) # Determining the loss loss.backward() # Backpropagation of loss and gradients computation optimizer.step() # Weights and Bias Updation loss_plot.append(loss.item()) # Some Bookkeeping plt.plot(loss_plot,'r-') plt.xlabel("Epochs") plt.ylabel("Loss : MSE") plt.show() print(loss_plot[-1]) """# Making Prediction Please note that for comparison purpose we use the training data's values and predicted data values to predict the number of passengers for the test data months and then compare them """ fut_pred = 12 test_inputs = train_data_normalized[-train_window: ].tolist() print(test_inputs) print(len(test_inputs)) model.eval() # Makes the model ready for evaluation for i in range(fut_pred): seq = torch.FloatTensor(test_inputs[-train_window: ]) # Converting to a tensor with torch.no_grad(): # Stops adding to the computational flow graph (stops being prepared for backpropagation) model.hidden_cell = (torch.zeros(1,1,model.hidden_layer_size), torch.zeros(1,1,model.hidden_layer_size)) test_inputs.append(model(seq).item()) predicted_outputs_normalized = [] predicted_outputs_normalized = test_inputs[-train_window: ] print(predicted_outputs_normalized) print(len(predicted_outputs_normalized)) """# Postprocessing""" predicted_outputs = scaler.inverse_transform(np.array(predicted_outputs_normalized).reshape(-1,1)) print(predicted_outputs) x = np.arange(132, 144, 1) print(x) """# Final Output""" figsize = plt.rcParams["figure.figsize"] figsize[0] = 15 figsize[1] = 5 plt.rcParams["figure.figsize"] = figsize plt.title('Month vs Passenger') plt.ylabel('Total Passengers') plt.grid(True) plt.autoscale(axis='x', tight=True) plt.plot(flight_data['passengers']) plt.plot(x,predicted_outputs) plt.show() figsize = plt.rcParams["figure.figsize"] figsize[0] = 15 figsize[1] = 5 plt.rcParams["figure.figsize"] = figsize plt.title('Month vs Passenger') plt.ylabel('Total Passengers') plt.grid(True) plt.autoscale(axis='x', tight=True) plt.plot(flight_data['passengers'][-train_window-5: ]) plt.plot(x,predicted_outputs) plt.show() """**Please observe that the model is able to get the trend of the passengers but it can be further fine-tuned by adding appropriate regularization methods**"""
""" # Commented out IPython magic to ensure Python compatibility. import torch import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import torch.nn as nn from tqdm import tqdm_notebook from sklearn.preprocessing import MinMaxScaler # %matplotlib inline torch.manual_seed(0) """ sns.get_dataset_names() flight_data = sns.load_dataset('flights') flight_data.head() '# Preprocessing' figsize = plt.rcParams['figure.figsize'] figsize[0] = 15 figsize[1] = 5 plt.rcParams['figure.figsize'] = figsize plt.title('Time Series Representation of Data') plt.xlabel('Months') plt.ylabel('Passengers') plt.grid(True) plt.autoscale(axis='x', tight=True) plt.plot(flight_data['passengers']) data = flight_data['passengers'].values.astype(float) print(data) print(len(data)) train_window = 12 train_data = data[:-train_window] test_data = data[-train_window:] print(len(train_data)) print(len(test_data)) scaler = min_max_scaler(feature_range=(-1, 1)) train_data_normalized = scaler.fit_transform(train_data.reshape(-1, 1)) print(train_data_normalized[:10]) train_data_normalized = torch.FloatTensor(train_data_normalized).view(-1) print(train_data_normalized) def create_in_sequences(input_data, tw): in_seq = [] l = len(input_data) for i in range(L - tw): train_seq = input_data[i:i + tw] train_label = input_data[i + tw:i + tw + 1] in_seq.append((train_seq, train_label)) return in_seq train_in_seq = create_in_sequences(train_data_normalized, train_window) print(len(train_in_seq)) print(train_in_seq[:5]) "# The Model\n\nPlease note that the model considered here is:\n\n\n1. LSTM layer with a univariate input sequence of length 12 and LSTM's previous hidden cell consisting of previous hidden state and previous cell state of length 100 and also , the size of LSTM's output is 100 \n2. The second layer is a Linear layer of 100 inputs from the LSTM's output and a single output size\n" class Lstm(nn.Module): def __init__(self, input_size=1, hidden_layer_size=100, output_size=1): super().__init__() self.hidden_layer_size = hidden_layer_size self.lstm = nn.LSTM(input_size, hidden_layer_size, dropout=0.45) self.linear = nn.Linear(hidden_layer_size, output_size) self.hidden_cell = (torch.ones(1, 1, self.hidden_layer_size), torch.ones(1, 1, self.hidden_layer_size)) def forward(self, input_seq): (lstm_out, self.hidden_cell) = self.lstm(input_seq.view(len(input_seq), 1, -1), self.hidden_cell) predictions = self.linear(lstm_out.view(len(input_seq), -1)) return predictions[-1] model = lstm() print(model) '# Loss Function and Learning Algorithm (Optimizer)\n\nPlease note that for this simple model , \n* Loss Function considered is *Mean Squared Error* and\n* Optimization Function used is Stochastic Version of **Adam** *Optimizer*.\n' loss_fn = nn.MSELoss() optimizer = torch.optim.Adam(model.parameters(), lr=0.0002) '# Training' epochs = 450 loss_plot = [] for epoch in tqdm_notebook(range(epochs), total=epochs, unit='epoch'): for (seq, label) in train_in_seq: optimizer.zero_grad() model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size), torch.zeros(1, 1, model.hidden_layer_size)) y_pred = model(seq) loss = loss_fn(y_pred, label) loss.backward() optimizer.step() loss_plot.append(loss.item()) plt.plot(loss_plot, 'r-') plt.xlabel('Epochs') plt.ylabel('Loss : MSE') plt.show() print(loss_plot[-1]) "# Making Prediction\n\nPlease note that for comparison purpose we use the training data's values and predicted data values to predict the number of passengers for the test data months and then compare them\n" fut_pred = 12 test_inputs = train_data_normalized[-train_window:].tolist() print(test_inputs) print(len(test_inputs)) model.eval() for i in range(fut_pred): seq = torch.FloatTensor(test_inputs[-train_window:]) with torch.no_grad(): model.hidden_cell = (torch.zeros(1, 1, model.hidden_layer_size), torch.zeros(1, 1, model.hidden_layer_size)) test_inputs.append(model(seq).item()) predicted_outputs_normalized = [] predicted_outputs_normalized = test_inputs[-train_window:] print(predicted_outputs_normalized) print(len(predicted_outputs_normalized)) '# Postprocessing' predicted_outputs = scaler.inverse_transform(np.array(predicted_outputs_normalized).reshape(-1, 1)) print(predicted_outputs) x = np.arange(132, 144, 1) print(x) '# Final Output' figsize = plt.rcParams['figure.figsize'] figsize[0] = 15 figsize[1] = 5 plt.rcParams['figure.figsize'] = figsize plt.title('Month vs Passenger') plt.ylabel('Total Passengers') plt.grid(True) plt.autoscale(axis='x', tight=True) plt.plot(flight_data['passengers']) plt.plot(x, predicted_outputs) plt.show() figsize = plt.rcParams['figure.figsize'] figsize[0] = 15 figsize[1] = 5 plt.rcParams['figure.figsize'] = figsize plt.title('Month vs Passenger') plt.ylabel('Total Passengers') plt.grid(True) plt.autoscale(axis='x', tight=True) plt.plot(flight_data['passengers'][-train_window - 5:]) plt.plot(x, predicted_outputs) plt.show() '**Please observe that the model is able to get the trend of the passengers but it can be further fine-tuned by adding appropriate regularization methods**'
# List of addresses within the Battle Animation Scripts for the following commands which cause screen flashes: # B0 - Set background palette color addition (absolute) # B5 - Add color to background palette (relative) # AF - Set background palette color subtraction (absolute) # B6 - Subtract color from background palette (relative) # By changing address + 1 to E0 (for absolute) or F0 (for relative), it causes no change to the background color (that is, no flash) BATTLE_ANIMATION_FLASHES = { "Goner": [ 0x100088, # AF E0 - set background color subtraction to 0 (black) 0x10008C, # B6 61 - increase background color subtraction by 1 (red) 0x100092, # B6 31 - decrease background color subtraction by 1 (yellow) 0x100098, # B6 81 - increase background color subtraction by 1 (cyan) 0x1000A1, # B6 91 - decrease background color subtraction by 1 (cyan) 0x1000A3, # B6 21 - increase background color subtraction by 1 (yellow) 0x1000D3, # B6 8F - increase background color subtraction by 15 (cyan) 0x1000DF, # B0 FF - set background color addition to 31 (white) 0x100172, # B5 F2 - decrease background color addition by 2 (white) ], "Final KEFKA Death": [ 0x10023A, # B0 FF - set background color addition to 31 (white) 0x100240, # B5 F4 - decrease background color addition by 4 (white) 0x100248, # B0 FF - set background color addition to 31 (white) 0x10024E, # B5 F4 - decrease background color addition by 4 (white) ], "Atom Edge": [ # Also True Edge 0x1003D0, # AF E0 - set background color subtraction to 0 (black) 0x1003DD, # B6 E1 - increase background color subtraction by 1 (black) 0x1003E6, # B6 E1 - increase background color subtraction by 1 (black) 0x10044B, # B6 F1 - decrease background color subtraction by 1 (black) 0x100457, # B6 F1 - decrease background color subtraction by 1 (black) ], "Boss Death": [ 0x100476, # B0 FF - set background color addition to 31 (white) 0x10047C, # B5 F4 - decrease background color addition by 4 (white) 0x100484, # B0 FF - set background color addition to 31 (white) 0x100497, # B5 F4 - decrease background color addition by 4 (white) ], "Transform into Magicite": [ 0x100F30, # B0 FF - set background color addition to 31 (white) 0x100F3F, # B5 F2 - decrease background color addition by 2 (white) 0x100F4E, # B5 F2 - decrease background color addition by 2 (white) ], "Purifier": [ 0x101340, # AF E0 - set background color subtraction to 0 (black) 0x101348, # B6 62 - increase background color subtraction by 2 (red) 0x101380, # B6 81 - increase background color subtraction by 1 (cyan) 0x10138A, # B6 F1 - decrease background color subtraction by 1 (black) ], "Wall": [ 0x10177B, # AF E0 - set background color subtraction to 0 (black) 0x10177F, # B6 61 - increase background color subtraction by 1 (red) 0x101788, # B6 51 - decrease background color subtraction by 1 (magenta) 0x101791, # B6 81 - increase background color subtraction by 1 (cyan) 0x10179A, # B6 31 - decrease background color subtraction by 1 (yellow) 0x1017A3, # B6 41 - increase background color subtraction by 1 (magenta) 0x1017AC, # B6 91 - decrease background color subtraction by 1 (cyan) 0x1017B5, # B6 51 - decrease background color subtraction by 1 (magenta) ], "Pearl": [ 0x10190E, # B0 E0 - set background color addition to 0 (white) 0x101913, # B5 E2 - increase background color addition by 2 (white) 0x10191E, # B5 F1 - decrease background color addition by 1 (white) 0x10193E, # B6 C2 - increase background color subtraction by 2 (blue) ], "Ice 3": [ 0x101978, # B0 FF - set background color addition to 31 (white) 0x10197B, # B5 F4 - decrease background color addition by 4 (white) 0x10197E, # B5 F4 - decrease background color addition by 4 (white) 0x101981, # B5 F4 - decrease background color addition by 4 (white) 0x101984, # B5 F4 - decrease background color addition by 4 (white) 0x101987, # B5 F4 - decrease background color addition by 4 (white) 0x10198A, # B5 F4 - decrease background color addition by 4 (white) 0x10198D, # B5 F4 - decrease background color addition by 4 (white) 0x101990, # B5 F4 - decrease background color addition by 4 (white) ], "Fire 3": [ 0x1019FA, # B0 9F - set background color addition to 31 (red) 0x101A1C, # B5 94 - decrease background color addition by 4 (red) ], "Sleep": [ 0x101A23, # AF E0 - set background color subtraction to 0 (black) 0x101A29, # B6 E1 - increase background color subtraction by 1 (black) 0x101A33, # B6 F1 - decrease background color subtraction by 1 (black) ], "7-Flush": [ 0x101B43, # AF E0 - set background color subtraction to 0 (black) 0x101B47, # B6 61 - increase background color subtraction by 1 (red) 0x101B4D, # B6 51 - decrease background color subtraction by 1 (magenta) 0x101B53, # B6 81 - increase background color subtraction by 1 (cyan) 0x101B59, # B6 31 - decrease background color subtraction by 1 (yellow) 0x101B5F, # B6 41 - increase background color subtraction by 1 (magenta) 0x101B65, # B6 91 - decrease background color subtraction by 1 (cyan) 0x101B6B, # B6 51 - decrease background color subtraction by 1 (magenta) ], "H-Bomb": [ 0x101BC5, # B0 E0 - set background color addition to 0 (white) 0x101BC9, # B5 E1 - increase background color addition by 1 (white) 0x101C13, # B5 F1 - decrease background color addition by 1 (white) ], "Revenger": [ 0x101C62, # AF E0 - set background color subtraction to 0 (black) 0x101C66, # B6 81 - increase background color subtraction by 1 (cyan) 0x101C6C, # B6 41 - increase background color subtraction by 1 (magenta) 0x101C72, # B6 91 - decrease background color subtraction by 1 (cyan) 0x101C78, # B6 21 - increase background color subtraction by 1 (yellow) 0x101C7E, # B6 51 - decrease background color subtraction by 1 (magenta) 0x101C84, # B6 81 - increase background color subtraction by 1 (cyan) 0x101C86, # B6 31 - decrease background color subtraction by 1 (yellow) 0x101C8C, # B6 91 - decrease background color subtraction by 1 (cyan) ], "Phantasm": [ 0x101DFD, # AF E0 - set background color subtraction to 0 (black) 0x101E03, # B6 E1 - increase background color subtraction by 1 (black) 0x101E07, # B0 FF - set background color addition to 31 (white) 0x101E0D, # B5 F4 - decrease background color addition by 4 (white) 0x101E15, # B6 E2 - increase background color subtraction by 2 (black) 0x101E1F, # B0 FF - set background color addition to 31 (white) 0x101E27, # B5 F4 - decrease background color addition by 4 (white) 0x101E2F, # B6 E2 - increase background color subtraction by 2 (black) 0x101E3B, # B6 F1 - decrease background color subtraction by 1 (black) ], "TigerBreak": [ 0x10240D, # B0 FF - set background color addition to 31 (white) 0x102411, # B5 F2 - decrease background color addition by 2 (white) 0x102416, # B5 F2 - decrease background color addition by 2 (white) ], "Metamorph": [ 0x102595, # AF E0 - set background color subtraction to 0 (black) 0x102599, # B6 61 - increase background color subtraction by 1 (red) 0x1025AF, # B6 71 - decrease background color subtraction by 1 (red) ], "Cat Rain": [ 0x102677, # B0 FF - set background color addition to 31 (white) 0x10267B, # B5 F1 - decrease background color addition by 1 (white) ], "Charm": [ 0x1026EE, # B0 FF - set background color addition to 31 (white) 0x1026FB, # B5 F1 - decrease background color addition by 1 (white) ], "Mirager": [ 0x102791, # B0 FF - set background color addition to 31 (white) 0x102795, # B5 F2 - decrease background color addition by 2 (white) ], "SabreSoul": [ 0x1027D3, # B0 FF - set background color addition to 31 (white) 0x1027DA, # B5 F2 - decrease background color addition by 2 (white) ], "Back Blade": [ 0x1028D3, # AF FF - set background color subtraction to 31 (black) 0x1028DF, # B6 F4 - decrease background color subtraction by 4 (black) ], "RoyalShock": [ 0x102967, # B0 FF - set background color addition to 31 (white) 0x10296B, # B5 F2 - decrease background color addition by 2 (white) 0x102973, # B5 F2 - decrease background color addition by 2 (white) ], "Overcast": [ 0x102C3A, # AF E0 - set background color subtraction to 0 (black) 0x102C55, # B6 E1 - increase background color subtraction by 1 (black) 0x102C8D, # B6 F1 - decrease background color subtraction by 1 (black) 0x102C91, # B6 F1 - decrease background color subtraction by 1 (black) ], "Disaster": [ 0x102CEE, # AF E0 - set background color subtraction to 0 (black) 0x102CF2, # B6 E1 - increase background color subtraction by 1 (black) 0x102D19, # B6 F1 - decrease background color subtraction by 1 (black) ], "ForceField": [ 0x102D3A, # B0 E0 - set background color addition to 0 (white) 0x102D48, # B5 E1 - increase background color addition by 1 (white) 0x102D64, # B5 F1 - decrease background color addition by 1 (white) ], "Terra/Tritoch Lightning": [ 0x102E05, # B0 E0 - set background color addition to 0 (white) 0x102E09, # B5 81 - increase background color addition by 1 (red) 0x102E24, # B5 61 - increase background color addition by 1 (cyan) ], "S. Cross": [ 0x102EDA, # AF E0 - set background color subtraction to 0 (black) 0x102EDE, # B6 E2 - increase background color subtraction by 2 (black) 0x102FA8, # B6 F2 - decrease background color subtraction by 2 (black) 0x102FB1, # B0 E0 - set background color addition to 0 (white) 0x102FBE, # B5 E2 - increase background color addition by 2 (white) 0x102FD9, # B5 F2 - decrease background color addition by 2 (white) ], "Mind Blast": [ 0x102FED, # B0 E0 - set background color addition to 0 (white) 0x102FF1, # B5 81 - increase background color addition by 1 (red) 0x102FF7, # B5 91 - decrease background color addition by 1 (red) 0x102FF9, # B5 21 - increase background color addition by 1 (blue) 0x102FFF, # B5 31 - decrease background color addition by 1 (blue) 0x103001, # B5 C1 - increase background color addition by 1 (yellow) 0x103007, # B5 91 - decrease background color addition by 1 (red) 0x10300D, # B5 51 - decrease background color addition by 1 (green) 0x103015, # B5 E2 - increase background color addition by 2 (white) 0x10301F, # B5 F1 - decrease background color addition by 1 (white) ], "Flare Star": [ 0x1030F5, # B0 E0 - set background color addition to 0 (white) 0x103106, # B5 81 - increase background color addition by 1 (red) 0x10310D, # B5 E2 - increase background color addition by 2 (white) 0x103123, # B5 71 - decrease background color addition by 1 (cyan) 0x10312E, # B5 91 - decrease background color addition by 1 (red) ], "Quasar": [ 0x1031D2, # AF E0 - set background color subtraction to 0 (black) 0x1031D6, # B6 E1 - increase background color subtraction by 1 (black) 0x1031FA, # B6 F1 - decrease background color subtraction by 1 (black) ], "R.Polarity": [ 0x10328B, # B0 FF - set background color addition to 31 (white) 0x103292, # B5 F1 - decrease background color addition by 1 (white) ], "Rippler": [ 0x1033C6, # B0 FF - set background color addition to 31 (white) 0x1033CA, # B5 F1 - decrease background color addition by 1 (white) ], "Step Mine": [ 0x1034D9, # B0 FF - set background color addition to 31 (white) 0x1034E0, # B5 F4 - decrease background color addition by 4 (white) ], "L.5 Doom": [ 0x1035E6, # B0 FF - set background color addition to 31 (white) 0x1035F6, # B5 F4 - decrease background color addition by 4 (white) ], "Megazerk": [ 0x103757, # B0 80 - set background color addition to 0 (red) 0x103761, # B5 82 - increase background color addition by 2 (red) 0x10378F, # B5 92 - decrease background color addition by 2 (red) 0x103795, # B5 92 - decrease background color addition by 2 (red) 0x10379B, # B5 92 - decrease background color addition by 2 (red) 0x1037A1, # B5 92 - decrease background color addition by 2 (red) 0x1037A7, # B5 92 - decrease background color addition by 2 (red) 0x1037AD, # B5 92 - decrease background color addition by 2 (red) 0x1037B3, # B5 92 - decrease background color addition by 2 (red) 0x1037B9, # B5 92 - decrease background color addition by 2 (red) 0x1037C0, # B5 92 - decrease background color addition by 2 (red) ], "Schiller": [ 0x103819, # B0 FF - set background color addition to 31 (white) 0x10381D, # B5 F4 - decrease background color addition by 4 (white) ], "WallChange": [ 0x10399E, # B0 FF - set background color addition to 31 (white) 0x1039A3, # B5 F2 - decrease background color addition by 2 (white) 0x1039A9, # B5 F2 - decrease background color addition by 2 (white) 0x1039AF, # B5 F2 - decrease background color addition by 2 (white) 0x1039B5, # B5 F2 - decrease background color addition by 2 (white) 0x1039BB, # B5 F2 - decrease background color addition by 2 (white) 0x1039C1, # B5 F2 - decrease background color addition by 2 (white) 0x1039C7, # B5 F2 - decrease background color addition by 2 (white) 0x1039CD, # B5 F2 - decrease background color addition by 2 (white) 0x1039D4, # B5 F2 - decrease background color addition by 2 (white) ], "Ultima": [ 0x1056CB, # AF 60 - set background color subtraction to 0 (red) 0x1056CF, # B6 C2 - increase background color subtraction by 2 (blue) 0x1056ED, # B0 FF - set background color addition to 31 (white) 0x1056F5, # B5 F1 - decrease background color addition by 1 (white) ], "Bolt 3": [ # Also Giga Volt 0x10588E, # B0 FF - set background color addition to 31 (white) 0x105893, # B5 F4 - decrease background color addition by 4 (white) 0x105896, # B5 F4 - decrease background color addition by 4 (white) 0x105899, # B5 F4 - decrease background color addition by 4 (white) 0x10589C, # B5 F4 - decrease background color addition by 4 (white) 0x1058A1, # B5 F4 - decrease background color addition by 4 (white) 0x1058A6, # B5 F4 - decrease background color addition by 4 (white) 0x1058AB, # B5 F4 - decrease background color addition by 4 (white) 0x1058B0, # B5 F4 - decrease background color addition by 4 (white) ], "X-Zone": [ 0x105A5D, # B0 FF - set background color addition to 31 (white) 0x105A6A, # B5 F2 - decrease background color addition by 2 (white) 0x105A79, # B5 F2 - decrease background color addition by 2 (white) ], "Dispel": [ 0x105DC2, # B0 FF - set background color addition to 31 (white) 0x105DC9, # B5 F1 - decrease background color addition by 1 (white) 0x105DD2, # B5 F1 - decrease background color addition by 1 (white) 0x105DDB, # B5 F1 - decrease background color addition by 1 (white) 0x105DE4, # B5 F1 - decrease background color addition by 1 (white) 0x105DED, # B5 F1 - decrease background color addition by 1 (white) ], "Muddle": [ # Also L.3 Muddle, Confusion 0x1060EA, # B0 FF - set background color addition to 31 (white) 0x1060EE, # B5 F1 - decrease background color addition by 1 (white) ], "Shock": [ 0x1068BE, # B0 FF - set background color addition to 31 (white) 0x1068D0, # B5 F1 - decrease background color addition by 1 (white) ], "Bum Rush": [ 0x106C3E, # B0 E0 - set background color addition to 0 (white) 0x106C47, # B0 E0 - set background color addition to 0 (white) 0x106C53, # B0 E0 - set background color addition to 0 (white) 0x106C7E, # B0 FF - set background color addition to 31 (white) 0x106C87, # B0 E0 - set background color addition to 0 (white) 0x106C95, # B0 FF - set background color addition to 31 (white) 0x106C9E, # B0 E0 - set background color addition to 0 (white) ], "Stunner": [ 0x1071BA, # B0 20 - set background color addition to 0 (blue) 0x1071C1, # B5 24 - increase background color addition by 4 (blue) 0x1071CA, # B5 24 - increase background color addition by 4 (blue) 0x1071D5, # B5 24 - increase background color addition by 4 (blue) 0x1071DE, # B5 24 - increase background color addition by 4 (blue) 0x1071E9, # B5 24 - increase background color addition by 4 (blue) 0x1071F2, # B5 24 - increase background color addition by 4 (blue) 0x1071FD, # B5 24 - increase background color addition by 4 (blue) 0x107206, # B5 24 - increase background color addition by 4 (blue) 0x107211, # B5 24 - increase background color addition by 4 (blue) 0x10721A, # B5 24 - increase background color addition by 4 (blue) 0x10725A, # B5 32 - decrease background color addition by 2 (blue) ], "Quadra Slam": [ # Also Quadra Slice 0x1073DC, # B0 FF - set background color addition to 31 (white) 0x1073EE, # B5 F2 - decrease background color addition by 2 (white) 0x1073F3, # B5 F2 - decrease background color addition by 2 (white) 0x107402, # B0 5F - set background color addition to 31 (green) 0x107424, # B5 54 - decrease background color addition by 4 (green) 0x107429, # B5 54 - decrease background color addition by 4 (green) 0x107436, # B0 3F - set background color addition to 31 (blue) 0x107458, # B5 34 - decrease background color addition by 4 (blue) 0x10745D, # B5 34 - decrease background color addition by 4 (blue) 0x107490, # B0 9F - set background color addition to 31 (red) 0x1074B2, # B5 94 - decrease background color addition by 4 (red) 0x1074B7, # B5 94 - decrease background color addition by 4 (red) ], "Slash": [ 0x1074F4, # B0 FF - set background color addition to 31 (white) 0x1074FD, # B5 F2 - decrease background color addition by 2 (white) 0x107507, # B5 F2 - decrease background color addition by 2 (white) ], "Flash": [ 0x107850, # B0 FF - set background color addition to 31 (white) 0x10785C, # B5 F1 - decrease background color addition by 1 (white) ] }
battle_animation_flashes = {'Goner': [1048712, 1048716, 1048722, 1048728, 1048737, 1048739, 1048787, 1048799, 1048946], 'Final KEFKA Death': [1049146, 1049152, 1049160, 1049166], 'Atom Edge': [1049552, 1049565, 1049574, 1049675, 1049687], 'Boss Death': [1049718, 1049724, 1049732, 1049751], 'Transform into Magicite': [1052464, 1052479, 1052494], 'Purifier': [1053504, 1053512, 1053568, 1053578], 'Wall': [1054587, 1054591, 1054600, 1054609, 1054618, 1054627, 1054636, 1054645], 'Pearl': [1054990, 1054995, 1055006, 1055038], 'Ice 3': [1055096, 1055099, 1055102, 1055105, 1055108, 1055111, 1055114, 1055117, 1055120], 'Fire 3': [1055226, 1055260], 'Sleep': [1055267, 1055273, 1055283], '7-Flush': [1055555, 1055559, 1055565, 1055571, 1055577, 1055583, 1055589, 1055595], 'H-Bomb': [1055685, 1055689, 1055763], 'Revenger': [1055842, 1055846, 1055852, 1055858, 1055864, 1055870, 1055876, 1055878, 1055884], 'Phantasm': [1056253, 1056259, 1056263, 1056269, 1056277, 1056287, 1056295, 1056303, 1056315], 'TigerBreak': [1057805, 1057809, 1057814], 'Metamorph': [1058197, 1058201, 1058223], 'Cat Rain': [1058423, 1058427], 'Charm': [1058542, 1058555], 'Mirager': [1058705, 1058709], 'SabreSoul': [1058771, 1058778], 'Back Blade': [1059027, 1059039], 'RoyalShock': [1059175, 1059179, 1059187], 'Overcast': [1059898, 1059925, 1059981, 1059985], 'Disaster': [1060078, 1060082, 1060121], 'ForceField': [1060154, 1060168, 1060196], 'Terra/Tritoch Lightning': [1060357, 1060361, 1060388], 'S. Cross': [1060570, 1060574, 1060776, 1060785, 1060798, 1060825], 'Mind Blast': [1060845, 1060849, 1060855, 1060857, 1060863, 1060865, 1060871, 1060877, 1060885, 1060895], 'Flare Star': [1061109, 1061126, 1061133, 1061155, 1061166], 'Quasar': [1061330, 1061334, 1061370], 'R.Polarity': [1061515, 1061522], 'Rippler': [1061830, 1061834], 'Step Mine': [1062105, 1062112], 'L.5 Doom': [1062374, 1062390], 'Megazerk': [1062743, 1062753, 1062799, 1062805, 1062811, 1062817, 1062823, 1062829, 1062835, 1062841, 1062848], 'Schiller': [1062937, 1062941], 'WallChange': [1063326, 1063331, 1063337, 1063343, 1063349, 1063355, 1063361, 1063367, 1063373, 1063380], 'Ultima': [1070795, 1070799, 1070829, 1070837], 'Bolt 3': [1071246, 1071251, 1071254, 1071257, 1071260, 1071265, 1071270, 1071275, 1071280], 'X-Zone': [1071709, 1071722, 1071737], 'Dispel': [1072578, 1072585, 1072594, 1072603, 1072612, 1072621], 'Muddle': [1073386, 1073390], 'Shock': [1075390, 1075408], 'Bum Rush': [1076286, 1076295, 1076307, 1076350, 1076359, 1076373, 1076382], 'Stunner': [1077690, 1077697, 1077706, 1077717, 1077726, 1077737, 1077746, 1077757, 1077766, 1077777, 1077786, 1077850], 'Quadra Slam': [1078236, 1078254, 1078259, 1078274, 1078308, 1078313, 1078326, 1078360, 1078365, 1078416, 1078450, 1078455], 'Slash': [1078516, 1078525, 1078535], 'Flash': [1079376, 1079388]}
class Solution: def maxEnvelopes(self, envelopes: List[List[int]]) -> int: if not envelopes: return 0 pairs = sorted(envelopes, key=lambda x: (x[0], -x[1])) result = [] for pair in pairs: height = pair[1] if len(result) == 0 or height > result[-1]: result.append(height) else: index = bisect.bisect_left(result, height) result[index] = height return len(result)
class Solution: def max_envelopes(self, envelopes: List[List[int]]) -> int: if not envelopes: return 0 pairs = sorted(envelopes, key=lambda x: (x[0], -x[1])) result = [] for pair in pairs: height = pair[1] if len(result) == 0 or height > result[-1]: result.append(height) else: index = bisect.bisect_left(result, height) result[index] = height return len(result)
# -*- coding: utf-8 -*- # This file is made to configure every file number at one place # Choose the place you are training at # AWS : 0, Own PC : 1 PC = 1 path_list = ["/jet/prs/workspace/", "."] url = path_list[PC] clothes = ['shirt', 'jeans', 'blazer', 'chino-pants', 'jacket', 'coat', 'hoody', 'training-pants', 't-shirt', 'polo-shirt', 'knit', 'slacks', 'sweat-shirt'] schedule = ['party', 'trip', 'sport', 'work', 'speech', 'daily', 'school', 'date'] weather = ['snow', 'sunny', 'cloudy', 'rain']
pc = 1 path_list = ['/jet/prs/workspace/', '.'] url = path_list[PC] clothes = ['shirt', 'jeans', 'blazer', 'chino-pants', 'jacket', 'coat', 'hoody', 'training-pants', 't-shirt', 'polo-shirt', 'knit', 'slacks', 'sweat-shirt'] schedule = ['party', 'trip', 'sport', 'work', 'speech', 'daily', 'school', 'date'] weather = ['snow', 'sunny', 'cloudy', 'rain']
def test_rm_long_opt_help(pycred): pycred('rm --help') def test_rm_short_opt_help(pycred): pycred('rm -h') def test_rm_none_existing_store_gives_exit_code_2(pycred, workspace): with workspace(): pycred('rm non-existing-store user', expected_exit_code=2)
def test_rm_long_opt_help(pycred): pycred('rm --help') def test_rm_short_opt_help(pycred): pycred('rm -h') def test_rm_none_existing_store_gives_exit_code_2(pycred, workspace): with workspace(): pycred('rm non-existing-store user', expected_exit_code=2)
# Application definition INSTALLED_APPS = [ 'django.contrib.staticfiles', 'django.contrib.sessions', 'authenticate', ] ROOT_URLCONF = 'auth_service.urls' WSGI_APPLICATION = 'auth_service.wsgi.application' # Use a non database session engine SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_SECURE = False
installed_apps = ['django.contrib.staticfiles', 'django.contrib.sessions', 'authenticate'] root_urlconf = 'auth_service.urls' wsgi_application = 'auth_service.wsgi.application' session_engine = 'django.contrib.sessions.backends.signed_cookies' session_cookie_secure = False
s=[] for i in range(int(input())): s.append(input()) cnt=0 while s: flag=True for i in range(len(s)//2): if s[i]<s[-(i+1)]: print(s[0],end='') s.pop(0) flag=False break elif s[-(i+1)]<s[i]: print(s[-1],end='') s.pop() flag=False break if flag: print(s[-1],end='') s.pop() cnt+=1 if cnt%80==0: print()
s = [] for i in range(int(input())): s.append(input()) cnt = 0 while s: flag = True for i in range(len(s) // 2): if s[i] < s[-(i + 1)]: print(s[0], end='') s.pop(0) flag = False break elif s[-(i + 1)] < s[i]: print(s[-1], end='') s.pop() flag = False break if flag: print(s[-1], end='') s.pop() cnt += 1 if cnt % 80 == 0: print()
cars=100 cars_in_space=5 drivers=20 pasengers=70 car_not_driven=cars-drivers cars_driven=drivers carpool_capacity=cars_driven*space_in_a_car average_passengers_percar=passengers/cars_driven print("There are", cars,"cars availble") print("There are only",drivers,"drivers availble") print("There will be",car_not_driven,"empty cars today") print("There are",cars_in_space,"space availble in car") print("We can transport",carpool_capacity,"peopletoday.") print("We have", passengers,"to carpool today.") print("We need to put about", average_passengers_per_car,"in each car.")
cars = 100 cars_in_space = 5 drivers = 20 pasengers = 70 car_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_percar = passengers / cars_driven print('There are', cars, 'cars availble') print('There are only', drivers, 'drivers availble') print('There will be', car_not_driven, 'empty cars today') print('There are', cars_in_space, 'space availble in car') print('We can transport', carpool_capacity, 'peopletoday.') print('We have', passengers, 'to carpool today.') print('We need to put about', average_passengers_per_car, 'in each car.')
# AUTOGENERATED! DO NOT EDIT! File to edit: dataset.ipynb (unless otherwise specified). __all__ = ['load_mp3', 'get_sample_label', 'preprocess_file', 'pad_by_zeros', 'split_file_by_window_size', 'wrapper_split_file_by_window_size', 'create_dataset_fixed_size', 'get_spectrogram', 'add_channel_dim'] # Cell def load_mp3(file): sample = tf.io.read_file(file) sample_audio = tfio.audio.decode_mp3(sample) return sample_audio # Cell def get_sample_label(file): sample = load_mp3(file) label = tf.argmax(tf.strings.split(file, '/')[1] == np.array(ebirds)) return sample, label # Cell def preprocess_file(sample_audio, label): # Only look at the first channel sample_audio = sample_audio[:,0] sample_audio_scaled = (sample_audio - tf.math.reduce_min(sample_audio))/(tf.math.reduce_max(sample_audio) - tf.math.reduce_min(sample_audio)) sample_audio_scaled = 2*(sample_audio_scaled - 0.5) return sample_audio_scaled, label # Cell def pad_by_zeros(sample, min_file_size, last_sample_size): padding_size = min_file_size - last_sample_size sample_padded = tf.pad(sample, paddings=[[tf.constant(0), padding_size]]) return sample_padded # Cell def split_file_by_window_size(sample, label): # number of subsamples given none overlapping window size. subsample_count = int(np.round(sample.shape[0]/min_file_size)) # ignore extremely long files for now subsample_limit = 75 if subsample_count <= subsample_limit: # if the last sample is at least half the window size, then pad it, if not, clip it. last_sample_size = sample.shape[0]%min_file_size if last_sample_size/min_file_size > 0.5: sample = pad_by_zeros(sample, min_file_size, last_sample_size) else: sample = sample[:subsample_count*min_file_size] sample = tf.reshape(sample, shape=[subsample_count, min_file_size]) label = tf.pad(tf.expand_dims(label, axis=0), paddings=[[0, subsample_count-1]], constant_values=label.numpy()) else: sample = tf.reshape(sample[:subsample_limit*min_file_size], shape=[subsample_limit, min_file_size]) label = tf.pad(tf.expand_dims(label, axis=0), paddings=[[0, 74]], constant_values=label.numpy()) return sample, label # Cell def wrapper_split_file_by_window_size(sample, label): sample, label = tf.py_function(split_file_by_window_size, inp=(sample, label), Tout=(sample.dtype, label.dtype)) return sample, label # Cell def create_dataset_fixed_size(ds): iterator = iter(ds) sample, label = iterator.next() samples_all = tf.unstack(sample) labels_all = tf.unstack(label) while True: try: sample, label = iterator.next() sample = tf.unstack(sample) label = tf.unstack(label) samples_all = tf.concat([samples_all, sample], axis=0) labels_all = tf.concat([labels_all, label], axis=0) except: break return samples_all, labels_all # Cell def get_spectrogram(sample, label): spectrogram = tfio.experimental.audio.spectrogram(sample, nfft=512, window=512, stride=256) return spectrogram, label # Cell def add_channel_dim(sample, label): sample = tf.expand_dims(sample, axis=-1) return sample, label
__all__ = ['load_mp3', 'get_sample_label', 'preprocess_file', 'pad_by_zeros', 'split_file_by_window_size', 'wrapper_split_file_by_window_size', 'create_dataset_fixed_size', 'get_spectrogram', 'add_channel_dim'] def load_mp3(file): sample = tf.io.read_file(file) sample_audio = tfio.audio.decode_mp3(sample) return sample_audio def get_sample_label(file): sample = load_mp3(file) label = tf.argmax(tf.strings.split(file, '/')[1] == np.array(ebirds)) return (sample, label) def preprocess_file(sample_audio, label): sample_audio = sample_audio[:, 0] sample_audio_scaled = (sample_audio - tf.math.reduce_min(sample_audio)) / (tf.math.reduce_max(sample_audio) - tf.math.reduce_min(sample_audio)) sample_audio_scaled = 2 * (sample_audio_scaled - 0.5) return (sample_audio_scaled, label) def pad_by_zeros(sample, min_file_size, last_sample_size): padding_size = min_file_size - last_sample_size sample_padded = tf.pad(sample, paddings=[[tf.constant(0), padding_size]]) return sample_padded def split_file_by_window_size(sample, label): subsample_count = int(np.round(sample.shape[0] / min_file_size)) subsample_limit = 75 if subsample_count <= subsample_limit: last_sample_size = sample.shape[0] % min_file_size if last_sample_size / min_file_size > 0.5: sample = pad_by_zeros(sample, min_file_size, last_sample_size) else: sample = sample[:subsample_count * min_file_size] sample = tf.reshape(sample, shape=[subsample_count, min_file_size]) label = tf.pad(tf.expand_dims(label, axis=0), paddings=[[0, subsample_count - 1]], constant_values=label.numpy()) else: sample = tf.reshape(sample[:subsample_limit * min_file_size], shape=[subsample_limit, min_file_size]) label = tf.pad(tf.expand_dims(label, axis=0), paddings=[[0, 74]], constant_values=label.numpy()) return (sample, label) def wrapper_split_file_by_window_size(sample, label): (sample, label) = tf.py_function(split_file_by_window_size, inp=(sample, label), Tout=(sample.dtype, label.dtype)) return (sample, label) def create_dataset_fixed_size(ds): iterator = iter(ds) (sample, label) = iterator.next() samples_all = tf.unstack(sample) labels_all = tf.unstack(label) while True: try: (sample, label) = iterator.next() sample = tf.unstack(sample) label = tf.unstack(label) samples_all = tf.concat([samples_all, sample], axis=0) labels_all = tf.concat([labels_all, label], axis=0) except: break return (samples_all, labels_all) def get_spectrogram(sample, label): spectrogram = tfio.experimental.audio.spectrogram(sample, nfft=512, window=512, stride=256) return (spectrogram, label) def add_channel_dim(sample, label): sample = tf.expand_dims(sample, axis=-1) return (sample, label)
# Copyright 2014-2015 ARM Limited # # Licensed under the Apache License, Version 2.0 # See LICENSE file for details. class mockData: """dictionary of mocking data for the mocking tests""" # dictionary to hold the mock data _data={} # function to add mock data to the _mock_data dictionary def _add(self,uri,status,payload): self._data[uri] = {"status":status, "payload":payload } return def getPayload(self,input): return self._data[input]['payload'] def getStatusCode(self,input): return self._data[input]['status'] # initialize the _mock_data dictionary with all the appropriate mocking data def __init__(self): self._add( uri="limits", status=200, payload='{"transaction-quota":10000,"transaction-count":259,"endpoint-quota":100,"endpoint-count":1}') self._add( uri="connectorVersion", status=200, payload='DeviceServer v3.0.0-520\nREST version = v2') self._add( uri="apiVersion", status=200, payload='["v1","v2"]') self._add( uri="endpoints", status=200, payload='[{"name":"51f540a2-3113-46e2-aef4-96e94a637b31","type":"test","status":"ACTIVE"}]') self._add( uri="resources", status=200, payload='[{"uri":"/Test/0/S","rt":"Static","obs":false,"type":""},{"uri":"/Test/0/D","rt":"Dynamic","obs":true,"type":""},{"uri":"/3/0/2","obs":false,"type":""},{"uri":"/3/0/1","obs":false,"type":""},{"uri":"/3/0/17","obs":false,"type":""},{"uri":"/3/0/0","obs":false,"type":""},{"uri":"/3/0/16","obs":false,"type":""},{"uri":"/3/0/11","obs":false,"type":""},{"uri":"/3/0/11/0","obs":false,"type":""},{"uri":"/3/0/4","obs":false,"type":""}]') #self._add( uri="", status=200, # payload="") #self._add( uri="", status=200, # payload="") #self._add( uri="", status=200, # payload="")
class Mockdata: """dictionary of mocking data for the mocking tests""" _data = {} def _add(self, uri, status, payload): self._data[uri] = {'status': status, 'payload': payload} return def get_payload(self, input): return self._data[input]['payload'] def get_status_code(self, input): return self._data[input]['status'] def __init__(self): self._add(uri='limits', status=200, payload='{"transaction-quota":10000,"transaction-count":259,"endpoint-quota":100,"endpoint-count":1}') self._add(uri='connectorVersion', status=200, payload='DeviceServer v3.0.0-520\nREST version = v2') self._add(uri='apiVersion', status=200, payload='["v1","v2"]') self._add(uri='endpoints', status=200, payload='[{"name":"51f540a2-3113-46e2-aef4-96e94a637b31","type":"test","status":"ACTIVE"}]') self._add(uri='resources', status=200, payload='[{"uri":"/Test/0/S","rt":"Static","obs":false,"type":""},{"uri":"/Test/0/D","rt":"Dynamic","obs":true,"type":""},{"uri":"/3/0/2","obs":false,"type":""},{"uri":"/3/0/1","obs":false,"type":""},{"uri":"/3/0/17","obs":false,"type":""},{"uri":"/3/0/0","obs":false,"type":""},{"uri":"/3/0/16","obs":false,"type":""},{"uri":"/3/0/11","obs":false,"type":""},{"uri":"/3/0/11/0","obs":false,"type":""},{"uri":"/3/0/4","obs":false,"type":""}]')
a = int(input()) b = int(input()) if a >=b*12: print("Buy it!") else: print("Try again")
a = int(input()) b = int(input()) if a >= b * 12: print('Buy it!') else: print('Try again')
# [weight, value] I = [[4, 8], [4, 7], [6, 14]] k = 8 def knapRecursive(I, k): return knapRecursiveAux(I, k, len(I) - 1) def knapRecursiveAux(I, k, hi): # final element if hi == 0: # too big for sack if I[hi][0] > k: return 0 # fits else: return I[hi][1] else: # too big for sack if I[hi][0] > k: return knapRecursiveAux(I, k, hi - 1) # fits else: # don't include it s1 = knapRecursiveAux(I, k, hi - 1) # include it s2 = I[hi][1] + knapRecursiveAux(I, k - I[hi][0], hi - 1) return max(s1, s2) print(knapRecursive(I, k))
i = [[4, 8], [4, 7], [6, 14]] k = 8 def knap_recursive(I, k): return knap_recursive_aux(I, k, len(I) - 1) def knap_recursive_aux(I, k, hi): if hi == 0: if I[hi][0] > k: return 0 else: return I[hi][1] elif I[hi][0] > k: return knap_recursive_aux(I, k, hi - 1) else: s1 = knap_recursive_aux(I, k, hi - 1) s2 = I[hi][1] + knap_recursive_aux(I, k - I[hi][0], hi - 1) return max(s1, s2) print(knap_recursive(I, k))
class Piece(object): def __init__(self, is_tall: bool = True, is_dark: bool = True, is_square: bool = True, is_solid: bool = True, string: str = None): if string: self.is_tall = (string[0] == "1") self.is_dark = (string[1] == "1") self.is_square = (string[2] == "1") self.is_solid = (string[3] == "1") else: self.is_tall = is_tall self.is_dark = is_dark self.is_square = is_square self.is_solid = is_solid def __str__(self): return "{0}{1}{2}{3}".format( '1' if self.is_tall else '0', '1' if self.is_dark else '0', '1' if self.is_square else '0', '1' if self.is_solid else '0' ) def __hash__(self): res = 0 res += 1 if self.is_tall else 0 res += 2 if self.is_dark else 0 res += 4 if self.is_square else 0 res += 8 if self.is_solid else 0 return res def __eq__(self, other_piece): if not isinstance(other_piece, type(self)): return False return self.__hash__() == other_piece.__hash__() def has_in_common_with(self, *other_pieces): all_pieces_are_as_tall = True all_pieces_are_as_dark = True all_pieces_are_as_square = True all_pieces_are_as_solid = True for p in other_pieces: if not(self.is_tall == p.is_tall): all_pieces_are_as_tall = False if not(self.is_dark == p.is_dark): all_pieces_are_as_dark = False if not(self.is_square == p.is_square): all_pieces_are_as_square = False if not(self.is_solid == p.is_solid): all_pieces_are_as_solid = False return (all_pieces_are_as_tall or all_pieces_are_as_dark or all_pieces_are_as_square or all_pieces_are_as_solid) if __name__ == "__main__": pass
class Piece(object): def __init__(self, is_tall: bool=True, is_dark: bool=True, is_square: bool=True, is_solid: bool=True, string: str=None): if string: self.is_tall = string[0] == '1' self.is_dark = string[1] == '1' self.is_square = string[2] == '1' self.is_solid = string[3] == '1' else: self.is_tall = is_tall self.is_dark = is_dark self.is_square = is_square self.is_solid = is_solid def __str__(self): return '{0}{1}{2}{3}'.format('1' if self.is_tall else '0', '1' if self.is_dark else '0', '1' if self.is_square else '0', '1' if self.is_solid else '0') def __hash__(self): res = 0 res += 1 if self.is_tall else 0 res += 2 if self.is_dark else 0 res += 4 if self.is_square else 0 res += 8 if self.is_solid else 0 return res def __eq__(self, other_piece): if not isinstance(other_piece, type(self)): return False return self.__hash__() == other_piece.__hash__() def has_in_common_with(self, *other_pieces): all_pieces_are_as_tall = True all_pieces_are_as_dark = True all_pieces_are_as_square = True all_pieces_are_as_solid = True for p in other_pieces: if not self.is_tall == p.is_tall: all_pieces_are_as_tall = False if not self.is_dark == p.is_dark: all_pieces_are_as_dark = False if not self.is_square == p.is_square: all_pieces_are_as_square = False if not self.is_solid == p.is_solid: all_pieces_are_as_solid = False return all_pieces_are_as_tall or all_pieces_are_as_dark or all_pieces_are_as_square or all_pieces_are_as_solid if __name__ == '__main__': pass
""" # Utilities for interacting with NCBI EUtilities relating to PubMed """ __version__ = "0.0.1"
""" # Utilities for interacting with NCBI EUtilities relating to PubMed """ __version__ = '0.0.1'
x = int(input('Podaj pierwsza liczbe calkowita: ')) y = int(input('Podaj druga liczbe calkowita: ')) z = int(input('Podaj trzecia liczbe calkowita: ')) print() if x > 10: print(x) if y > 10: print(y) if z > 10: print(z)
x = int(input('Podaj pierwsza liczbe calkowita: ')) y = int(input('Podaj druga liczbe calkowita: ')) z = int(input('Podaj trzecia liczbe calkowita: ')) print() if x > 10: print(x) if y > 10: print(y) if z > 10: print(z)
while True: try: dados = [] matriz = [] n = int(input()) for linha in range(0, n): for coluna in range(0, n): dados.append(0) matriz.append(dados[:]) dados.clear() # Numeros na diagonal for diagonal_principal in range(0, n): matriz[diagonal_principal][diagonal_principal] = 2 for diagonal_secundaria in range(0, n): matriz[diagonal_secundaria][n - 1 - diagonal_secundaria] = 3 # Matriz do numero 1 for linha in range(n // 3, n - n // 3): for coluna in range(n // 3, n - n // 3): matriz[linha][coluna] = 1 # Matriz do numero 4 matriz[n // 2][n // 2] = 4 # Print da Matriz completa for linha in range(0, len(matriz)): for coluna in range(0, len(matriz)): if coluna == 0: print(f"{matriz[linha][coluna]}", end="") else: print(f"{matriz[linha][coluna]}", end="") print() print() except EOFError: break
while True: try: dados = [] matriz = [] n = int(input()) for linha in range(0, n): for coluna in range(0, n): dados.append(0) matriz.append(dados[:]) dados.clear() for diagonal_principal in range(0, n): matriz[diagonal_principal][diagonal_principal] = 2 for diagonal_secundaria in range(0, n): matriz[diagonal_secundaria][n - 1 - diagonal_secundaria] = 3 for linha in range(n // 3, n - n // 3): for coluna in range(n // 3, n - n // 3): matriz[linha][coluna] = 1 matriz[n // 2][n // 2] = 4 for linha in range(0, len(matriz)): for coluna in range(0, len(matriz)): if coluna == 0: print(f'{matriz[linha][coluna]}', end='') else: print(f'{matriz[linha][coluna]}', end='') print() print() except EOFError: break
# query_strings.py ''' Since Sqlite queries are inserted as string in Python code, the queries can be stored here to save space in the modules where they are used. ''' delete_color_scheme = ''' DELETE FROM color_scheme WHERE color_scheme_id = ? ''' insert_color_scheme = ''' INSERT INTO color_scheme VALUES (null, ?, ?, ?, ?, 0, 0) ''' select_all_color_schemes = ''' SELECT bg, highlight_bg, head_bg, fg FROM color_scheme ''' select_all_color_schemes_plus = ''' SELECT bg, highlight_bg, head_bg, fg, built_in, color_scheme_id FROM color_scheme ''' select_color_scheme_current = ''' SELECT bg, highlight_bg, head_bg, fg FROM format WHERE format_id = 1 ''' select_current_database = ''' SELECT current_database FROM closing_state WHERE closing_state_id = 1 ''' select_font_scheme = ''' SELECT font_size, output_font, input_font FROM format WHERE format_id = 1 ''' select_opening_settings = ''' SELECT bg, highlight_bg, head_bg, fg, output_font, input_font, font_size, default_bg, default_highlight_bg, default_head_bg, default_fg, default_output_font, default_input_font, default_font_size FROM format WHERE format_id = 1 ''' update_color_scheme_null = ''' UPDATE format SET (bg, highlight_bg, head_bg, fg) = (null, null, null, null) WHERE format_id = 1 ''' update_current_database = ''' UPDATE closing_state SET current_database = ? WHERE closing_state_id = 1 ''' update_format_color_scheme = ''' UPDATE format SET (bg, highlight_bg, head_bg, fg) = (?, ?, ?, ?) WHERE format_id = 1 ''' update_format_fonts = ''' UPDATE format SET (font_size, output_font, input_font) = (?, ?, ?) WHERE format_id = 1 '''
""" Since Sqlite queries are inserted as string in Python code, the queries can be stored here to save space in the modules where they are used. """ delete_color_scheme = '\n DELETE FROM color_scheme \n WHERE color_scheme_id = ?\n' insert_color_scheme = '\n INSERT INTO color_scheme \n VALUES (null, ?, ?, ?, ?, 0, 0)\n' select_all_color_schemes = '\n SELECT bg, highlight_bg, head_bg, fg \n FROM color_scheme\n' select_all_color_schemes_plus = '\n SELECT bg, highlight_bg, head_bg, fg, built_in, color_scheme_id \n FROM color_scheme\n' select_color_scheme_current = '\n SELECT bg, highlight_bg, head_bg, fg \n FROM format \n WHERE format_id = 1\n' select_current_database = '\n SELECT current_database \n FROM closing_state \n WHERE closing_state_id = 1\n' select_font_scheme = '\n SELECT font_size, output_font, input_font\n FROM format\n WHERE format_id = 1\n' select_opening_settings = '\n SELECT \n bg,\n highlight_bg,\n head_bg, \n fg,\n output_font,\n input_font, \n font_size,\n default_bg,\n default_highlight_bg,\n default_head_bg, \n default_fg,\n default_output_font,\n default_input_font, \n default_font_size \n FROM format\n WHERE format_id = 1\n' update_color_scheme_null = '\n UPDATE format \n SET (bg, highlight_bg, head_bg, fg) = \n (null, null, null, null) \n WHERE format_id = 1\n' update_current_database = '\n UPDATE closing_state \n SET current_database = ? \n WHERE closing_state_id = 1\n' update_format_color_scheme = '\n UPDATE format \n SET (bg, highlight_bg, head_bg, fg) = (?, ?, ?, ?) \n WHERE format_id = 1 \n' update_format_fonts = '\n UPDATE format \n SET (font_size, output_font, input_font) = (?, ?, ?) \n WHERE format_id = 1\n'
""" HackerRank :: Reverse a singly-linked list https://www.hackerrank.com/challenges/reverse-a-linked-list/problem Complete the reverse function below. For your reference: SinglyLinkedListNode: int data SinglyLinkedListNode next """ def reverse(head): # head node value can be null # Keep track of previous node prev_node = None cur_node = head # Loop through - while node.next while cur_node: # Save node for overwriting cur_node next_node = cur_node.next # Set current node's next to prev_node cur_node.next = prev_node # Pass previous node to next iteration prev_node = cur_node cur_node = next_node return prev_node
""" HackerRank :: Reverse a singly-linked list https://www.hackerrank.com/challenges/reverse-a-linked-list/problem Complete the reverse function below. For your reference: SinglyLinkedListNode: int data SinglyLinkedListNode next """ def reverse(head): prev_node = None cur_node = head while cur_node: next_node = cur_node.next cur_node.next = prev_node prev_node = cur_node cur_node = next_node return prev_node
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'targets': [ { 'target_name': 'gfx', 'type': '<(component)', 'dependencies': [ '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/base.gyp:base_i18n', '<(DEPTH)/base/base.gyp:base_static', '<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '<(DEPTH)/net/net.gyp:net', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', '<(DEPTH)/third_party/libpng/libpng.gyp:libpng', '<(DEPTH)/third_party/zlib/zlib.gyp:zlib', '<(DEPTH)/url/url.gyp:url_lib', ], # text_elider.h includes ICU headers. 'export_dependent_settings': [ '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', ], 'defines': [ 'GFX_IMPLEMENTATION', ], 'sources': [ 'android/device_display_info.cc', 'android/device_display_info.h', 'android/gfx_jni_registrar.cc', 'android/gfx_jni_registrar.h', 'android/java_bitmap.cc', 'android/java_bitmap.h', 'android/shared_device_display_info.cc', 'android/shared_device_display_info.h', 'animation/animation.cc', 'animation/animation.h', 'animation/animation_container.cc', 'animation/animation_container.h', 'animation/animation_container_element.h', 'animation/animation_container_observer.h', 'animation/animation_delegate.h', 'animation/linear_animation.cc', 'animation/linear_animation.h', 'animation/multi_animation.cc', 'animation/multi_animation.h', 'animation/slide_animation.cc', 'animation/slide_animation.h', 'animation/throb_animation.cc', 'animation/throb_animation.h', 'animation/tween.cc', 'animation/tween.h', 'blit.cc', 'blit.h', 'box_f.cc', 'box_f.h', 'break_list.h', 'canvas.cc', 'canvas.h', 'canvas_android.cc', 'canvas_paint_gtk.cc', 'canvas_paint_gtk.h', 'canvas_paint_mac.h', 'canvas_paint_mac.mm', 'canvas_paint_win.cc', 'canvas_paint_win.h', 'canvas_skia.cc', 'canvas_skia_paint.h', 'codec/jpeg_codec.cc', 'codec/jpeg_codec.h', 'codec/png_codec.cc', 'codec/png_codec.h', 'color_analysis.cc', 'color_analysis.h', 'color_profile.cc', 'color_profile.h', 'color_profile_mac.cc', 'color_profile_win.cc', 'color_utils.cc', 'color_utils.h', 'display.cc', 'display.h', 'display_observer.cc', 'display_observer.h', 'favicon_size.cc', 'favicon_size.h', 'frame_time.h', 'font.cc', 'font.h', 'font_fallback_win.cc', 'font_fallback_win.h', 'font_list.cc', 'font_list.h', 'font_render_params_android.cc', 'font_render_params_linux.cc', 'font_render_params_linux.h', 'font_smoothing_win.cc', 'font_smoothing_win.h', 'gfx_export.h', 'gfx_paths.cc', 'gfx_paths.h', 'gpu_memory_buffer.cc', 'gpu_memory_buffer.h', 'image/canvas_image_source.cc', 'image/canvas_image_source.h', 'image/image.cc', 'image/image.h', 'image/image_family.cc', 'image/image_family.h', 'image/image_ios.mm', 'image/image_mac.mm', 'image/image_png_rep.cc', 'image/image_png_rep.h', 'image/image_skia.cc', 'image/image_skia.h', 'image/image_skia_operations.cc', 'image/image_skia_operations.h', 'image/image_skia_rep.cc', 'image/image_skia_rep.h', 'image/image_skia_source.h', 'image/image_skia_util_ios.h', 'image/image_skia_util_ios.mm', 'image/image_skia_util_mac.h', 'image/image_skia_util_mac.mm', 'image/image_util.cc', 'image/image_util.h', 'image/image_util_ios.mm', 'insets.cc', 'insets.h', 'insets_base.h', 'insets_f.cc', 'insets_f.h', 'interpolated_transform.cc', 'interpolated_transform.h', 'mac/scoped_ns_disable_screen_updates.h', 'matrix3_f.cc', 'matrix3_f.h', 'native_widget_types.h', 'ozone/dri/dri_skbitmap.cc', 'ozone/dri/dri_skbitmap.h', 'ozone/dri/dri_surface.cc', 'ozone/dri/dri_surface.h', 'ozone/dri/dri_surface_factory.cc', 'ozone/dri/dri_surface_factory.h', 'ozone/dri/dri_wrapper.cc', 'ozone/dri/dri_wrapper.h', 'ozone/dri/hardware_display_controller.cc', 'ozone/dri/hardware_display_controller.h', 'ozone/impl/file_surface_factory.cc', 'ozone/impl/file_surface_factory.h', 'ozone/surface_factory_ozone.cc', 'ozone/surface_factory_ozone.h', 'pango_util.cc', 'pango_util.h', 'path.cc', 'path.h', 'path_aura.cc', 'path_gtk.cc', 'path_win.cc', 'path_win.h', 'path_x11.cc', 'path_x11.h', 'platform_font.h', 'platform_font_android.cc', 'platform_font_ios.h', 'platform_font_ios.mm', 'platform_font_mac.h', 'platform_font_mac.mm', 'platform_font_ozone.cc', 'platform_font_pango.cc', 'platform_font_pango.h', 'platform_font_win.cc', 'platform_font_win.h', 'point.cc', 'point.h', 'point3_f.cc', 'point3_f.h', 'point_base.h', 'point_conversions.cc', 'point_conversions.h', 'point_f.cc', 'point_f.h', 'quad_f.cc', 'quad_f.h', 'range/range.cc', 'range/range.h', 'range/range_mac.mm', 'range/range_win.cc', 'rect.cc', 'rect.h', 'rect_base.h', 'rect_base_impl.h', 'rect_conversions.cc', 'rect_conversions.h', 'rect_f.cc', 'rect_f.h', 'render_text.cc', 'render_text.h', 'render_text_mac.cc', 'render_text_mac.h', 'render_text_ozone.cc', 'render_text_pango.cc', 'render_text_pango.h', 'render_text_win.cc', 'render_text_win.h', 'safe_integer_conversions.h', 'scoped_canvas.h', 'scoped_cg_context_save_gstate_mac.h', 'scoped_ns_graphics_context_save_gstate_mac.h', 'scoped_ns_graphics_context_save_gstate_mac.mm', 'scoped_ui_graphics_push_context_ios.h', 'scoped_ui_graphics_push_context_ios.mm', 'screen.cc', 'screen.h', 'screen_android.cc', 'screen_aura.cc', 'screen_gtk.cc', 'screen_ios.mm', 'screen_mac.mm', 'screen_win.cc', 'screen_win.h', 'scrollbar_size.cc', 'scrollbar_size.h', 'selection_model.cc', 'selection_model.h', 'sequential_id_generator.cc', 'sequential_id_generator.h', 'shadow_value.cc', 'shadow_value.h', 'size.cc', 'size.h', 'size_base.h', 'size_conversions.cc', 'size_conversions.h', 'size_f.cc', 'size_f.h', 'skbitmap_operations.cc', 'skbitmap_operations.h', 'skia_util.cc', 'skia_util.h', 'skia_utils_gtk.cc', 'skia_utils_gtk.h', 'switches.cc', 'switches.h', 'sys_color_change_listener.cc', 'sys_color_change_listener.h', 'text_constants.h', 'text_elider.cc', 'text_elider.h', 'text_utils.cc', 'text_utils.h', 'text_utils_android.cc', 'text_utils_ios.mm', 'text_utils_skia.cc', 'transform.cc', 'transform.h', 'transform_util.cc', 'transform_util.h', 'utf16_indexing.cc', 'utf16_indexing.h', 'vector2d.cc', 'vector2d.h', 'vector2d_conversions.cc', 'vector2d_conversions.h', 'vector2d_f.cc', 'vector2d_f.h', 'vector3d_f.cc', 'vector3d_f.h', 'win/dpi.cc', 'win/dpi.h', 'win/hwnd_util.cc', 'win/hwnd_util.h', 'win/scoped_set_map_mode.h', 'win/singleton_hwnd.cc', 'win/singleton_hwnd.h', 'win/window_impl.cc', 'win/window_impl.h', 'x/x11_atom_cache.cc', 'x/x11_atom_cache.h', 'x/x11_types.cc', 'x/x11_types.h', ], 'conditions': [ ['OS=="ios"', { # iOS only uses a subset of UI. 'sources/': [ ['exclude', '^codec/jpeg_codec\\.cc$'], ], }, { 'dependencies': [ '<(libjpeg_gyp_path):libjpeg', ], }], # TODO(asvitkine): Switch all platforms to use canvas_skia.cc. # http://crbug.com/105550 ['use_canvas_skia==1', { 'sources!': [ 'canvas_android.cc', ], }, { # use_canvas_skia!=1 'sources!': [ 'canvas_skia.cc', ], }], ['toolkit_uses_gtk == 1', { 'dependencies': [ '<(DEPTH)/build/linux/system.gyp:gtk', ], 'sources': [ 'gtk_native_view_id_manager.cc', 'gtk_native_view_id_manager.h', 'gtk_preserve_window.cc', 'gtk_preserve_window.h', 'gdk_compat.h', 'gtk_compat.h', 'gtk_util.cc', 'gtk_util.h', 'image/cairo_cached_surface.cc', 'image/cairo_cached_surface.h', 'scoped_gobject.h', ], }], ['OS=="win"', { 'sources': [ 'gdi_util.cc', 'gdi_util.h', 'icon_util.cc', 'icon_util.h', ], # TODO(jschuh): C4267: http://crbug.com/167187 size_t -> int # C4324 is structure was padded due to __declspec(align()), which is # uninteresting. 'msvs_disabled_warnings': [ 4267, 4324 ], }], ['OS=="android"', { 'sources!': [ 'animation/throb_animation.cc', 'display_observer.cc', 'path.cc', 'selection_model.cc', ], 'dependencies': [ 'gfx_jni_headers', ], 'link_settings': { 'libraries': [ '-landroid', '-ljnigraphics', ], }, }], ['OS=="android" and android_webview_build==0', { 'dependencies': [ '<(DEPTH)/base/base.gyp:base_java', ], }], ['OS=="android" or OS=="ios"', { 'sources!': [ 'render_text.cc', 'render_text.h', 'text_utils_skia.cc', ], }], ['use_pango==1', { 'dependencies': [ '<(DEPTH)/build/linux/system.gyp:pangocairo', ], }], ['ozone_platform_dri==1', { 'dependencies': [ '<(DEPTH)/build/linux/system.gyp:dridrm', ], }], ], 'target_conditions': [ # Need 'target_conditions' to override default filename_rules to include # the file on iOS. ['OS == "ios"', { 'sources/': [ ['include', '^scoped_cg_context_save_gstate_mac\\.h$'], ], }], ], } ], 'conditions': [ ['OS=="android"' , { 'targets': [ { 'target_name': 'gfx_jni_headers', 'type': 'none', 'direct_dependent_settings': { 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/ui/gfx', ], }, 'sources': [ '../android/java/src/org/chromium/ui/gfx/BitmapHelper.java', '../android/java/src/org/chromium/ui/gfx/DeviceDisplayInfo.java', ], 'variables': { 'jni_gen_package': 'ui/gfx', 'jni_generator_ptr_type': 'long', }, 'includes': [ '../../build/jni_generator.gypi' ], }, ], }], ], }
{'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'gfx', 'type': '<(component)', 'dependencies': ['<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/base.gyp:base_i18n', '<(DEPTH)/base/base.gyp:base_static', '<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '<(DEPTH)/net/net.gyp:net', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', '<(DEPTH)/third_party/libpng/libpng.gyp:libpng', '<(DEPTH)/third_party/zlib/zlib.gyp:zlib', '<(DEPTH)/url/url.gyp:url_lib'], 'export_dependent_settings': ['<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc'], 'defines': ['GFX_IMPLEMENTATION'], 'sources': ['android/device_display_info.cc', 'android/device_display_info.h', 'android/gfx_jni_registrar.cc', 'android/gfx_jni_registrar.h', 'android/java_bitmap.cc', 'android/java_bitmap.h', 'android/shared_device_display_info.cc', 'android/shared_device_display_info.h', 'animation/animation.cc', 'animation/animation.h', 'animation/animation_container.cc', 'animation/animation_container.h', 'animation/animation_container_element.h', 'animation/animation_container_observer.h', 'animation/animation_delegate.h', 'animation/linear_animation.cc', 'animation/linear_animation.h', 'animation/multi_animation.cc', 'animation/multi_animation.h', 'animation/slide_animation.cc', 'animation/slide_animation.h', 'animation/throb_animation.cc', 'animation/throb_animation.h', 'animation/tween.cc', 'animation/tween.h', 'blit.cc', 'blit.h', 'box_f.cc', 'box_f.h', 'break_list.h', 'canvas.cc', 'canvas.h', 'canvas_android.cc', 'canvas_paint_gtk.cc', 'canvas_paint_gtk.h', 'canvas_paint_mac.h', 'canvas_paint_mac.mm', 'canvas_paint_win.cc', 'canvas_paint_win.h', 'canvas_skia.cc', 'canvas_skia_paint.h', 'codec/jpeg_codec.cc', 'codec/jpeg_codec.h', 'codec/png_codec.cc', 'codec/png_codec.h', 'color_analysis.cc', 'color_analysis.h', 'color_profile.cc', 'color_profile.h', 'color_profile_mac.cc', 'color_profile_win.cc', 'color_utils.cc', 'color_utils.h', 'display.cc', 'display.h', 'display_observer.cc', 'display_observer.h', 'favicon_size.cc', 'favicon_size.h', 'frame_time.h', 'font.cc', 'font.h', 'font_fallback_win.cc', 'font_fallback_win.h', 'font_list.cc', 'font_list.h', 'font_render_params_android.cc', 'font_render_params_linux.cc', 'font_render_params_linux.h', 'font_smoothing_win.cc', 'font_smoothing_win.h', 'gfx_export.h', 'gfx_paths.cc', 'gfx_paths.h', 'gpu_memory_buffer.cc', 'gpu_memory_buffer.h', 'image/canvas_image_source.cc', 'image/canvas_image_source.h', 'image/image.cc', 'image/image.h', 'image/image_family.cc', 'image/image_family.h', 'image/image_ios.mm', 'image/image_mac.mm', 'image/image_png_rep.cc', 'image/image_png_rep.h', 'image/image_skia.cc', 'image/image_skia.h', 'image/image_skia_operations.cc', 'image/image_skia_operations.h', 'image/image_skia_rep.cc', 'image/image_skia_rep.h', 'image/image_skia_source.h', 'image/image_skia_util_ios.h', 'image/image_skia_util_ios.mm', 'image/image_skia_util_mac.h', 'image/image_skia_util_mac.mm', 'image/image_util.cc', 'image/image_util.h', 'image/image_util_ios.mm', 'insets.cc', 'insets.h', 'insets_base.h', 'insets_f.cc', 'insets_f.h', 'interpolated_transform.cc', 'interpolated_transform.h', 'mac/scoped_ns_disable_screen_updates.h', 'matrix3_f.cc', 'matrix3_f.h', 'native_widget_types.h', 'ozone/dri/dri_skbitmap.cc', 'ozone/dri/dri_skbitmap.h', 'ozone/dri/dri_surface.cc', 'ozone/dri/dri_surface.h', 'ozone/dri/dri_surface_factory.cc', 'ozone/dri/dri_surface_factory.h', 'ozone/dri/dri_wrapper.cc', 'ozone/dri/dri_wrapper.h', 'ozone/dri/hardware_display_controller.cc', 'ozone/dri/hardware_display_controller.h', 'ozone/impl/file_surface_factory.cc', 'ozone/impl/file_surface_factory.h', 'ozone/surface_factory_ozone.cc', 'ozone/surface_factory_ozone.h', 'pango_util.cc', 'pango_util.h', 'path.cc', 'path.h', 'path_aura.cc', 'path_gtk.cc', 'path_win.cc', 'path_win.h', 'path_x11.cc', 'path_x11.h', 'platform_font.h', 'platform_font_android.cc', 'platform_font_ios.h', 'platform_font_ios.mm', 'platform_font_mac.h', 'platform_font_mac.mm', 'platform_font_ozone.cc', 'platform_font_pango.cc', 'platform_font_pango.h', 'platform_font_win.cc', 'platform_font_win.h', 'point.cc', 'point.h', 'point3_f.cc', 'point3_f.h', 'point_base.h', 'point_conversions.cc', 'point_conversions.h', 'point_f.cc', 'point_f.h', 'quad_f.cc', 'quad_f.h', 'range/range.cc', 'range/range.h', 'range/range_mac.mm', 'range/range_win.cc', 'rect.cc', 'rect.h', 'rect_base.h', 'rect_base_impl.h', 'rect_conversions.cc', 'rect_conversions.h', 'rect_f.cc', 'rect_f.h', 'render_text.cc', 'render_text.h', 'render_text_mac.cc', 'render_text_mac.h', 'render_text_ozone.cc', 'render_text_pango.cc', 'render_text_pango.h', 'render_text_win.cc', 'render_text_win.h', 'safe_integer_conversions.h', 'scoped_canvas.h', 'scoped_cg_context_save_gstate_mac.h', 'scoped_ns_graphics_context_save_gstate_mac.h', 'scoped_ns_graphics_context_save_gstate_mac.mm', 'scoped_ui_graphics_push_context_ios.h', 'scoped_ui_graphics_push_context_ios.mm', 'screen.cc', 'screen.h', 'screen_android.cc', 'screen_aura.cc', 'screen_gtk.cc', 'screen_ios.mm', 'screen_mac.mm', 'screen_win.cc', 'screen_win.h', 'scrollbar_size.cc', 'scrollbar_size.h', 'selection_model.cc', 'selection_model.h', 'sequential_id_generator.cc', 'sequential_id_generator.h', 'shadow_value.cc', 'shadow_value.h', 'size.cc', 'size.h', 'size_base.h', 'size_conversions.cc', 'size_conversions.h', 'size_f.cc', 'size_f.h', 'skbitmap_operations.cc', 'skbitmap_operations.h', 'skia_util.cc', 'skia_util.h', 'skia_utils_gtk.cc', 'skia_utils_gtk.h', 'switches.cc', 'switches.h', 'sys_color_change_listener.cc', 'sys_color_change_listener.h', 'text_constants.h', 'text_elider.cc', 'text_elider.h', 'text_utils.cc', 'text_utils.h', 'text_utils_android.cc', 'text_utils_ios.mm', 'text_utils_skia.cc', 'transform.cc', 'transform.h', 'transform_util.cc', 'transform_util.h', 'utf16_indexing.cc', 'utf16_indexing.h', 'vector2d.cc', 'vector2d.h', 'vector2d_conversions.cc', 'vector2d_conversions.h', 'vector2d_f.cc', 'vector2d_f.h', 'vector3d_f.cc', 'vector3d_f.h', 'win/dpi.cc', 'win/dpi.h', 'win/hwnd_util.cc', 'win/hwnd_util.h', 'win/scoped_set_map_mode.h', 'win/singleton_hwnd.cc', 'win/singleton_hwnd.h', 'win/window_impl.cc', 'win/window_impl.h', 'x/x11_atom_cache.cc', 'x/x11_atom_cache.h', 'x/x11_types.cc', 'x/x11_types.h'], 'conditions': [['OS=="ios"', {'sources/': [['exclude', '^codec/jpeg_codec\\.cc$']]}, {'dependencies': ['<(libjpeg_gyp_path):libjpeg']}], ['use_canvas_skia==1', {'sources!': ['canvas_android.cc']}, {'sources!': ['canvas_skia.cc']}], ['toolkit_uses_gtk == 1', {'dependencies': ['<(DEPTH)/build/linux/system.gyp:gtk'], 'sources': ['gtk_native_view_id_manager.cc', 'gtk_native_view_id_manager.h', 'gtk_preserve_window.cc', 'gtk_preserve_window.h', 'gdk_compat.h', 'gtk_compat.h', 'gtk_util.cc', 'gtk_util.h', 'image/cairo_cached_surface.cc', 'image/cairo_cached_surface.h', 'scoped_gobject.h']}], ['OS=="win"', {'sources': ['gdi_util.cc', 'gdi_util.h', 'icon_util.cc', 'icon_util.h'], 'msvs_disabled_warnings': [4267, 4324]}], ['OS=="android"', {'sources!': ['animation/throb_animation.cc', 'display_observer.cc', 'path.cc', 'selection_model.cc'], 'dependencies': ['gfx_jni_headers'], 'link_settings': {'libraries': ['-landroid', '-ljnigraphics']}}], ['OS=="android" and android_webview_build==0', {'dependencies': ['<(DEPTH)/base/base.gyp:base_java']}], ['OS=="android" or OS=="ios"', {'sources!': ['render_text.cc', 'render_text.h', 'text_utils_skia.cc']}], ['use_pango==1', {'dependencies': ['<(DEPTH)/build/linux/system.gyp:pangocairo']}], ['ozone_platform_dri==1', {'dependencies': ['<(DEPTH)/build/linux/system.gyp:dridrm']}]], 'target_conditions': [['OS == "ios"', {'sources/': [['include', '^scoped_cg_context_save_gstate_mac\\.h$']]}]]}], 'conditions': [['OS=="android"', {'targets': [{'target_name': 'gfx_jni_headers', 'type': 'none', 'direct_dependent_settings': {'include_dirs': ['<(SHARED_INTERMEDIATE_DIR)/ui/gfx']}, 'sources': ['../android/java/src/org/chromium/ui/gfx/BitmapHelper.java', '../android/java/src/org/chromium/ui/gfx/DeviceDisplayInfo.java'], 'variables': {'jni_gen_package': 'ui/gfx', 'jni_generator_ptr_type': 'long'}, 'includes': ['../../build/jni_generator.gypi']}]}]]}
""" 113 / 113 test cases passed. Runtime: 92 ms Memory Usage: 16.4 MB """ class Solution: def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: m, n = len(heights), len(heights[0]) def dfs(used, x, y): used[x][y] = True for xx, yy in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]: if 0 <= xx < m and 0 <= yy < n and not used[xx][yy] and heights[xx][yy] >= heights[x][y]: dfs(used, xx, yy) pacific_used = [[False] * n for _ in range(m)] atlantic_used = [[False] * n for _ in range(m)] for i in range(m): dfs(pacific_used, i, 0) dfs(atlantic_used, i, n - 1) for i in range(n): dfs(pacific_used, 0, i) dfs(atlantic_used, m - 1, i) ans = [] for i in range(m): for j in range(n): if pacific_used[i][j] and atlantic_used[i][j]: ans.append([i, j]) return ans
""" 113 / 113 test cases passed. Runtime: 92 ms Memory Usage: 16.4 MB """ class Solution: def pacific_atlantic(self, heights: List[List[int]]) -> List[List[int]]: (m, n) = (len(heights), len(heights[0])) def dfs(used, x, y): used[x][y] = True for (xx, yy) in [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]: if 0 <= xx < m and 0 <= yy < n and (not used[xx][yy]) and (heights[xx][yy] >= heights[x][y]): dfs(used, xx, yy) pacific_used = [[False] * n for _ in range(m)] atlantic_used = [[False] * n for _ in range(m)] for i in range(m): dfs(pacific_used, i, 0) dfs(atlantic_used, i, n - 1) for i in range(n): dfs(pacific_used, 0, i) dfs(atlantic_used, m - 1, i) ans = [] for i in range(m): for j in range(n): if pacific_used[i][j] and atlantic_used[i][j]: ans.append([i, j]) return ans
__all__ = ( 'LIST', 'GET', 'CREATE', 'UPDATE', 'REPLACE', 'DELETE', 'ALL', 'get_http_methods' ) LIST = 'list' GET = 'get' CREATE = 'create' REPLACE = 'replace' UPDATE = 'update' DELETE = 'delete' ALL = (LIST, GET, CREATE, UPDATE, REPLACE, DELETE) _http_methods = { LIST: ('get',), GET: ('get',), CREATE: ('post',), REPLACE: ('put',), UPDATE: ('patch',), DELETE: ('delete',) } def get_http_methods(method): return _http_methods[method]
__all__ = ('LIST', 'GET', 'CREATE', 'UPDATE', 'REPLACE', 'DELETE', 'ALL', 'get_http_methods') list = 'list' get = 'get' create = 'create' replace = 'replace' update = 'update' delete = 'delete' all = (LIST, GET, CREATE, UPDATE, REPLACE, DELETE) _http_methods = {LIST: ('get',), GET: ('get',), CREATE: ('post',), REPLACE: ('put',), UPDATE: ('patch',), DELETE: ('delete',)} def get_http_methods(method): return _http_methods[method]
# -*- coding: utf-8 -*- """ Created on 2017/11/18 @author: MG """
""" Created on 2017/11/18 @author: MG """
""" Rackspace Cloud Backup API Test Suite """
""" Rackspace Cloud Backup API Test Suite """
#!/usr/bin/env python3 if __name__ == '__main__': # Python can represent integers. Here are a couple of ways to create an integer variable. Notice the truncation, # rather than rounding, in the assignment of d. a = 5 b = int() c = int(4) d = int(3.84) print(a, b, c, d) # Integers have the usual math operations. Note that division will return a float, but others will preserve the # integer type. The type() function can tell you the type of a variable. You should try to avoid using this # function in your code. print('\ndivision') a = 10 b = 10 / 5 print(b, type(b)) # We can force integer division with //. Note that this will truncate results. print('\nInteger division') a = 10 b = 10 // 5 print(b, type(b)) a = 10 b = 10 // 3 print(b, type(b)) # We can also calculate the remainder n = 10 m = 3 div = n // m rem = n % m print('\n{0} = {1} * {2} + {3}'.format(n, div, m, rem))
if __name__ == '__main__': a = 5 b = int() c = int(4) d = int(3.84) print(a, b, c, d) print('\ndivision') a = 10 b = 10 / 5 print(b, type(b)) print('\nInteger division') a = 10 b = 10 // 5 print(b, type(b)) a = 10 b = 10 // 3 print(b, type(b)) n = 10 m = 3 div = n // m rem = n % m print('\n{0} = {1} * {2} + {3}'.format(n, div, m, rem))
def test(): obj = { 'xxx1': 1, 'xxx2': 2, 'xxx3': 4, 'xxx4': 4, 'foo': 123 } i = 0 while i < 1e7: obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 i += 1 test()
def test(): obj = {'xxx1': 1, 'xxx2': 2, 'xxx3': 4, 'xxx4': 4, 'foo': 123} i = 0 while i < 10000000.0: obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 i += 1 test()
#!/usr/local/bin/python # -*- coding: utf-8 -*- """ """ __author__ = 'joscha' __date__ = '03.08.12'
""" """ __author__ = 'joscha' __date__ = '03.08.12'
counter_name = 'I0_PIN' Size = wx.Size(1007, 726) logfile = '/net/helix/data/anfinrud_1502/Logfiles/I0_PIN-2.log' average_count = 1 max_value = 11 min_value = 0 start_fraction = 0.401 reject_outliers = False outlier_cutoff = 2.5 show_statistics = True time_window = 172800
counter_name = 'I0_PIN' size = wx.Size(1007, 726) logfile = '/net/helix/data/anfinrud_1502/Logfiles/I0_PIN-2.log' average_count = 1 max_value = 11 min_value = 0 start_fraction = 0.401 reject_outliers = False outlier_cutoff = 2.5 show_statistics = True time_window = 172800
print("I will now count my chickens:") print ("Hens",25+30/6) print ("Roosters",100-25*3%4) print("How I will count the eggs:") print(3+2+1-5+4%2-1/4+6) print("Is it true that 3+2<5-7?") print(3+2<5-7) print("What is 3+2?", 3+2) print("What is 5-7?", 5-7) print("Oh,that's why it's false") print("How about some more.") print("Is it greater?",5>-2) print("Is it greater or equal?",5>=-2) print("Is it less or equal?",5<=-2)
print('I will now count my chickens:') print('Hens', 25 + 30 / 6) print('Roosters', 100 - 25 * 3 % 4) print('How I will count the eggs:') print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print('Is it true that 3+2<5-7?') print(3 + 2 < 5 - 7) print('What is 3+2?', 3 + 2) print('What is 5-7?', 5 - 7) print("Oh,that's why it's false") print('How about some more.') print('Is it greater?', 5 > -2) print('Is it greater or equal?', 5 >= -2) print('Is it less or equal?', 5 <= -2)
#! /usr/bin/env python """ Learning Series: Network Programmability Basics Module: Programming Fundamentals Lesson: Python Part 2 Author: Hank Preston <hapresto@cisco.com> common_vars.py Illustrate the following concepts: - Code reuse imported into other examples """ shapes = ["square", "triangle", "circle"] books = [ { "title": "War and Peace", "shelf": 3, "available": True }, { "title": "Hamlet", "shelf": 1, "available": False }, { "title": "Harold and the Purple Crayon", "shelf": 2, "available": True } ] colors = ["blue", "green", "red"]
""" Learning Series: Network Programmability Basics Module: Programming Fundamentals Lesson: Python Part 2 Author: Hank Preston <hapresto@cisco.com> common_vars.py Illustrate the following concepts: - Code reuse imported into other examples """ shapes = ['square', 'triangle', 'circle'] books = [{'title': 'War and Peace', 'shelf': 3, 'available': True}, {'title': 'Hamlet', 'shelf': 1, 'available': False}, {'title': 'Harold and the Purple Crayon', 'shelf': 2, 'available': True}] colors = ['blue', 'green', 'red']
# -*- coding: utf-8 -*- """ Created on Wed May 27 18:48:24 2020 @author: Christopher Cheng """ class Stack(object): def __init__ (self): self.stack = [] def get_stack_elements(self): return self.stack.copy() def add_one(self, item): self.stack.append(item) def add_many(self,item,n): # item is still a single string, n times for i in range (n): self.stack.append(item) def remove_one(self): self.stack.pop() def remove_many(self,n): for i in range(n): self.stack.pop() def size(self): return len(self.stack) def prettyprint(self): for thing in self.stack[::-1]: print("|_", thing,"_|") def add_list(self, L): for e in L: self.stack.append(e) def __str__ (self): ret = "" for thing in self.stack[::-1]: ret += ("|_" + str(thing) + "_|\n") return ret class Circle (object): def __init__(self): self.radius = 0 def change_radius(self, radius): self.radius = radius def get_radius (self): return self.radius def __str__(self): return "circle: " + str(self.radius) circles = Stack() one_circle = Circle() one_circle.change_radius(1) circles.add_one(one_circle) two_circle = Circle() two_circle.change_radius(2) circles.add_one(two_circle) print(circles)
""" Created on Wed May 27 18:48:24 2020 @author: Christopher Cheng """ class Stack(object): def __init__(self): self.stack = [] def get_stack_elements(self): return self.stack.copy() def add_one(self, item): self.stack.append(item) def add_many(self, item, n): for i in range(n): self.stack.append(item) def remove_one(self): self.stack.pop() def remove_many(self, n): for i in range(n): self.stack.pop() def size(self): return len(self.stack) def prettyprint(self): for thing in self.stack[::-1]: print('|_', thing, '_|') def add_list(self, L): for e in L: self.stack.append(e) def __str__(self): ret = '' for thing in self.stack[::-1]: ret += '|_' + str(thing) + '_|\n' return ret class Circle(object): def __init__(self): self.radius = 0 def change_radius(self, radius): self.radius = radius def get_radius(self): return self.radius def __str__(self): return 'circle: ' + str(self.radius) circles = stack() one_circle = circle() one_circle.change_radius(1) circles.add_one(one_circle) two_circle = circle() two_circle.change_radius(2) circles.add_one(two_circle) print(circles)
def wordPower(word): num = dict(zip(string.ascii_lowercase, range(1,27))) return sum([num[ch] for ch in word])
def word_power(word): num = dict(zip(string.ascii_lowercase, range(1, 27))) return sum([num[ch] for ch in word])
""" Profile ../profile-datasets-py/div83/027.py file automaticaly created by prof_gen.py script """ self["ID"] = "../profile-datasets-py/div83/027.py" self["Q"] = numpy.array([ 1.51831800e+00, 2.02599600e+00, 2.94787100e+00, 3.99669400e+00, 4.71653800e+00, 4.89106600e+00, 5.14399400e+00, 5.67274800e+00, 6.02338400e+00, 6.09836300e+00, 6.08376300e+00, 6.01126400e+00, 5.91866500e+00, 5.77584700e+00, 5.59481900e+00, 5.41637100e+00, 5.26750200e+00, 5.10689400e+00, 4.98576500e+00, 4.90039600e+00, 4.80689700e+00, 4.63989800e+00, 4.46443000e+00, 4.30135100e+00, 4.16606300e+00, 4.06766300e+00, 4.01361400e+00, 3.95640400e+00, 3.87825500e+00, 3.79394600e+00, 3.73623600e+00, 3.72919600e+00, 3.74067600e+00, 3.78187600e+00, 3.81900500e+00, 3.85233500e+00, 3.88512500e+00, 3.91148500e+00, 3.92466500e+00, 3.92849500e+00, 3.93905400e+00, 3.97355400e+00, 4.02951400e+00, 4.05710400e+00, 4.04558400e+00, 4.02228400e+00, 4.01040400e+00, 4.00572400e+00, 4.00641400e+00, 4.08608300e+00, 4.44130000e+00, 5.00126500e+00, 5.73600700e+00, 6.83860300e+00, 8.34002000e+00, 9.95999100e+00, 1.13537700e+01, 1.24435500e+01, 1.36048100e+01, 1.55239600e+01, 1.77784800e+01, 1.93991200e+01, 2.00516000e+01, 1.97941100e+01, 1.89638400e+01, 1.84148600e+01, 1.82331700e+01, 1.84861600e+01, 2.02668900e+01, 3.24805400e+01, 6.31028200e+01, 1.09865900e+02, 1.71694500e+02, 2.41407700e+02, 3.05073900e+02, 3.60772800e+02, 4.04902000e+02, 4.16543400e+02, 4.04623200e+02, 3.59892400e+02, 3.06567000e+02, 3.03443900e+02, 4.25764600e+02, 8.75110500e+02, 1.60701300e+03, 2.52645100e+03, 3.50894400e+03, 4.39830900e+03, 5.05090900e+03, 5.40195000e+03, 5.54486300e+03, 5.86218200e+03, 6.10752900e+03, 6.83105600e+03, 6.63557500e+03, 6.44820100e+03, 6.26853800e+03, 6.09616900e+03, 5.93072700e+03, 5.77187200e+03, 5.61926500e+03]) self["P"] = numpy.array([ 5.00000000e-03, 1.61000000e-02, 3.84000000e-02, 7.69000000e-02, 1.37000000e-01, 2.24400000e-01, 3.45400000e-01, 5.06400000e-01, 7.14000000e-01, 9.75300000e-01, 1.29720000e+00, 1.68720000e+00, 2.15260000e+00, 2.70090000e+00, 3.33980000e+00, 4.07700000e+00, 4.92040000e+00, 5.87760000e+00, 6.95670000e+00, 8.16550000e+00, 9.51190000e+00, 1.10038000e+01, 1.26492000e+01, 1.44559000e+01, 1.64318000e+01, 1.85847000e+01, 2.09224000e+01, 2.34526000e+01, 2.61829000e+01, 2.91210000e+01, 3.22744000e+01, 3.56505000e+01, 3.92566000e+01, 4.31001000e+01, 4.71882000e+01, 5.15278000e+01, 5.61260000e+01, 6.09895000e+01, 6.61253000e+01, 7.15398000e+01, 7.72396000e+01, 8.32310000e+01, 8.95204000e+01, 9.61138000e+01, 1.03017000e+02, 1.10237000e+02, 1.17778000e+02, 1.25646000e+02, 1.33846000e+02, 1.42385000e+02, 1.51266000e+02, 1.60496000e+02, 1.70078000e+02, 1.80018000e+02, 1.90320000e+02, 2.00989000e+02, 2.12028000e+02, 2.23442000e+02, 2.35234000e+02, 2.47408000e+02, 2.59969000e+02, 2.72919000e+02, 2.86262000e+02, 3.00000000e+02, 3.14137000e+02, 3.28675000e+02, 3.43618000e+02, 3.58966000e+02, 3.74724000e+02, 3.90893000e+02, 4.07474000e+02, 4.24470000e+02, 4.41882000e+02, 4.59712000e+02, 4.77961000e+02, 4.96630000e+02, 5.15720000e+02, 5.35232000e+02, 5.55167000e+02, 5.75525000e+02, 5.96306000e+02, 6.17511000e+02, 6.39140000e+02, 6.61192000e+02, 6.83667000e+02, 7.06565000e+02, 7.29886000e+02, 7.53628000e+02, 7.77790000e+02, 8.02371000e+02, 8.27371000e+02, 8.52788000e+02, 8.78620000e+02, 9.04866000e+02, 9.31524000e+02, 9.58591000e+02, 9.86067000e+02, 1.01395000e+03, 1.04223000e+03, 1.07092000e+03, 1.10000000e+03]) self["CO2"] = numpy.array([ 375.9234, 375.9232, 375.9219, 375.9195, 375.9172, 375.9142, 375.9041, 375.8819, 375.8607, 375.8617, 375.8997, 375.9717, 376.0398, 376.0858, 376.1489, 376.212 , 376.224 , 376.2321, 376.2481, 376.2772, 376.3252, 376.3663, 376.4023, 376.4224, 376.4504, 376.4865, 376.5545, 376.6335, 376.7605, 376.8966, 377.0446, 377.2036, 377.3766, 377.5606, 377.7106, 377.8485, 378.0765, 378.4945, 378.9365, 379.6475, 380.4225, 381.0245, 381.4085, 381.8025, 381.8315, 381.8625, 381.8985, 381.9405, 381.9845, 382.0364, 382.0903, 382.5651, 383.1618, 383.8894, 384.7668, 385.5962, 386.1156, 386.6532, 386.7607, 386.854 , 386.8701, 386.8645, 386.8732, 386.8913, 386.9157, 386.9449, 386.9669, 386.9788, 386.9602, 386.9034, 386.8186, 386.7075, 386.6086, 386.5187, 386.4681, 386.4315, 386.4595, 386.5189, 386.6375, 386.8447, 387.1073, 387.3124, 387.433 , 387.3937, 387.2297, 386.9659, 386.6525, 386.3522, 386.1188, 385.9826, 385.9361, 385.8209, 385.7317, 385.4548, 385.5337, 385.6074, 385.6771, 385.744 , 385.8082, 385.8699, 385.9291]) self["CO"] = numpy.array([ 0.2205447 , 0.2185316 , 0.2145434 , 0.2078282 , 0.1977631 , 0.1839901 , 0.1511932 , 0.09891954, 0.0827345 , 0.05454007, 0.02926452, 0.01534331, 0.01021024, 0.00922827, 0.00895567, 0.00841368, 0.00791632, 0.0076217 , 0.00749041, 0.00745301, 0.00740799, 0.00741502, 0.00746624, 0.00760092, 0.00775626, 0.00793258, 0.0081303 , 0.00834271, 0.00844155, 0.00854593, 0.00861921, 0.00869836, 0.00895125, 0.009236 , 0.00956421, 0.00993273, 0.01050776, 0.01155325, 0.01277055, 0.01483604, 0.01745463, 0.02009092, 0.02248201, 0.0252159 , 0.0250677 , 0.0249136 , 0.0248554 , 0.0248671 , 0.0248747 , 0.0248604 , 0.02484549, 0.02830606, 0.03349511, 0.03954063, 0.04649641, 0.05393566, 0.05777834, 0.06203953, 0.06291754, 0.06367061, 0.06376177, 0.06365417, 0.06355173, 0.06345124, 0.063449 , 0.06353453, 0.06376724, 0.06416551, 0.06445159, 0.0646028 , 0.06451203, 0.06417925, 0.06369376, 0.06310236, 0.06261609, 0.06216137, 0.06196 , 0.06180874, 0.06178709, 0.06208905, 0.06263239, 0.06350083, 0.06423774, 0.06476787, 0.06481747, 0.06471838, 0.06458966, 0.06447546, 0.06438733, 0.06432344, 0.06428367, 0.06423741, 0.0641983 , 0.06589368, 0.07015209, 0.07475692, 0.0797395 , 0.08513432, 0.09097941, 0.09731644, 0.1041912 ]) self["T"] = numpy.array([ 189.265, 197.336, 211.688, 227.871, 242.446, 252.765, 259.432, 262.908, 263.411, 262.202, 261.422, 259.368, 255.095, 250.075, 244.792, 239.205, 235.817, 231.46 , 227.966, 225.935, 225.115, 222.382, 219.723, 218.152, 217.875, 218.211, 218.288, 218.294, 217.949, 217.202, 216.158, 214.964, 215.259, 215.053, 215.409, 216.081, 216.441, 216.152, 215.427, 215.082, 216.198, 217.247, 217.006, 216.373, 216.342, 217.088, 218.419, 219.839, 220.797, 220.946, 221.423, 222.504, 223.822, 225.134, 226.221, 226.93 , 227.275, 227.405, 227.434, 227.346, 227.212, 227.246, 227.566, 228.2 , 229.083, 230.094, 231.117, 232.121, 233.086, 234.01 , 235.064, 236.351, 237.928, 239.892, 242.039, 244.306, 246.651, 249.025, 251.415, 253.802, 256.16 , 258.448, 260.591, 262.445, 264.071, 265.349, 266.233, 266.969, 267.78 , 268.72 , 269.42 , 270.502, 271.421, 273.317, 273.317, 273.317, 273.317, 273.317, 273.317, 273.317, 273.317]) self["N2O"] = numpy.array([ 0.00161 , 0.00187 , 0.00205999, 0.00220999, 0.00233999, 0.00235999, 0.00157999, 0.00186999, 0.00519997, 0.00870995, 0.00838995, 0.00955994, 0.01208993, 0.01432992, 0.0171399 , 0.02172988, 0.02788985, 0.03756981, 0.04630977, 0.05168975, 0.05680973, 0.05922973, 0.06028973, 0.06131974, 0.07010971, 0.07957968, 0.08867964, 0.09929961, 0.1101496 , 0.1206295 , 0.1301795 , 0.1371795 , 0.1439595 , 0.1505294 , 0.1651494 , 0.1848693 , 0.2034792 , 0.2285391 , 0.252299 , 0.2748389 , 0.2840589 , 0.2926288 , 0.3004188 , 0.3072488 , 0.3129187 , 0.3172487 , 0.3200187 , 0.3209987 , 0.3209987 , 0.3209987 , 0.3209986 , 0.3209984 , 0.3209982 , 0.3209978 , 0.3209973 , 0.3209968 , 0.3209964 , 0.320996 , 0.3209956 , 0.320995 , 0.3209943 , 0.3209938 , 0.3209936 , 0.3209936 , 0.3209939 , 0.3209941 , 0.3209941 , 0.3209941 , 0.3209935 , 0.3209896 , 0.3209797 , 0.3209647 , 0.3209449 , 0.3209225 , 0.3209021 , 0.3208842 , 0.32087 , 0.3208663 , 0.3208701 , 0.3208845 , 0.3209016 , 0.3209026 , 0.3208633 , 0.3207191 , 0.3204841 , 0.320189 , 0.3198736 , 0.3195881 , 0.3193787 , 0.319266 , 0.3192201 , 0.3191182 , 0.3190395 , 0.3188072 , 0.31887 , 0.3189301 , 0.3189878 , 0.3190431 , 0.3190962 , 0.3191472 , 0.3191962 ]) self["O3"] = numpy.array([ 0.1903137 , 0.2192386 , 0.3077081 , 0.5440408 , 0.8590299 , 1.170854 , 1.499102 , 1.864289 , 2.273556 , 2.805293 , 3.409769 , 4.028786 , 4.806182 , 5.619898 , 6.411164 , 7.147361 , 7.51202 , 7.648961 , 7.644362 , 7.556123 , 7.446574 , 7.281136 , 6.952659 , 6.604492 , 6.296854 , 6.008776 , 5.751387 , 5.520268 , 5.311749 , 5.111921 , 4.890092 , 4.593293 , 4.298724 , 3.882905 , 3.380027 , 2.799559 , 2.288161 , 2.031152 , 2.018272 , 2.047542 , 1.969722 , 1.685453 , 1.220825 , 0.9176053 , 0.8929574 , 0.9542592 , 1.004996 , 1.034796 , 1.031726 , 1.019046 , 0.8797071 , 0.6484178 , 0.4105526 , 0.2529783 , 0.1943934 , 0.201197 , 0.2459162 , 0.322179 , 0.3977806 , 0.4292413 , 0.4255834 , 0.3930204 , 0.3461121 , 0.2989281 , 0.2606191 , 0.2321107 , 0.2069452 , 0.1838146 , 0.1618567 , 0.1410414 , 0.1225313 , 0.1061913 , 0.09214328, 0.08133816, 0.07293074, 0.06636085, 0.06143102, 0.05859298, 0.05740586, 0.05732126, 0.05783027, 0.05809797, 0.05651443, 0.05019414, 0.0404447 , 0.03280082, 0.02944741, 0.02902179, 0.02945348, 0.02918976, 0.02836743, 0.02750451, 0.02608958, 0.02225294, 0.02225732, 0.02226152, 0.02226555, 0.02226941, 0.02227312, 0.02227668, 0.02228009]) self["CH4"] = numpy.array([ 0.1059488, 0.1201298, 0.1306706, 0.1417254, 0.1691352, 0.209023 , 0.2345078, 0.2578465, 0.2845033, 0.328699 , 0.3987896, 0.4800421, 0.5668716, 0.6510682, 0.7280449, 0.7954147, 0.8518465, 0.8903115, 0.9281374, 0.9731752, 1.016085 , 1.071595 , 1.131985 , 1.189835 , 1.247015 , 1.302185 , 1.355285 , 1.400504 , 1.442154 , 1.464494 , 1.488464 , 1.514124 , 1.541544 , 1.560774 , 1.579304 , 1.596804 , 1.612894 , 1.627174 , 1.638294 , 1.650024 , 1.662373 , 1.675353 , 1.688973 , 1.722213 , 1.729283 , 1.736683 , 1.741733 , 1.745103 , 1.749093 , 1.755483 , 1.762122 , 1.770021 , 1.77847 , 1.785498 , 1.790785 , 1.795642 , 1.79793 , 1.800308 , 1.800506 , 1.800632 , 1.800498 , 1.800295 , 1.800414 , 1.800704 , 1.800856 , 1.800867 , 1.800517 , 1.799787 , 1.798434 , 1.796372 , 1.794017 , 1.791393 , 1.789133 , 1.787118 , 1.785875 , 1.784886 , 1.784827 , 1.785476 , 1.788046 , 1.791395 , 1.795229 , 1.798224 , 1.800263 , 1.801052 , 1.800931 , 1.80036 , 1.799234 , 1.797877 , 1.796739 , 1.796035 , 1.795827 , 1.795294 , 1.79488 , 1.793604 , 1.793966 , 1.794315 , 1.794639 , 1.794951 , 1.795249 , 1.795536 , 1.795812 ]) self["CTP"] = 500.0 self["CFRACTION"] = 0.0 self["IDG"] = 0 self["ISH"] = 0 self["ELEVATION"] = 0.0 self["S2M"]["T"] = 273.317 self["S2M"]["Q"] = 5619.26541873 self["S2M"]["O"] = 0.022280094739 self["S2M"]["P"] = 905.85559 self["S2M"]["U"] = 0.0 self["S2M"]["V"] = 0.0 self["S2M"]["WFETC"] = 100000.0 self["SKIN"]["SURFTYPE"] = 0 self["SKIN"]["WATERTYPE"] = 1 self["SKIN"]["T"] = 273.317 self["SKIN"]["SALINITY"] = 35.0 self["SKIN"]["FOAM_FRACTION"] = 0.0 self["SKIN"]["FASTEM"] = numpy.array([ 3. , 5. , 15. , 0.1, 0.3]) self["ZENANGLE"] = 0.0 self["AZANGLE"] = 0.0 self["SUNZENANGLE"] = 0.0 self["SUNAZANGLE"] = 0.0 self["LATITUDE"] = 45.309 self["GAS_UNITS"] = 2 self["BE"] = 0.0 self["COSBK"] = 0.0 self["DATE"] = numpy.array([2007, 4, 1]) self["TIME"] = numpy.array([0, 0, 0])
""" Profile ../profile-datasets-py/div83/027.py file automaticaly created by prof_gen.py script """ self['ID'] = '../profile-datasets-py/div83/027.py' self['Q'] = numpy.array([1.518318, 2.025996, 2.947871, 3.996694, 4.716538, 4.891066, 5.143994, 5.672748, 6.023384, 6.098363, 6.083763, 6.011264, 5.918665, 5.775847, 5.594819, 5.416371, 5.267502, 5.106894, 4.985765, 4.900396, 4.806897, 4.639898, 4.46443, 4.301351, 4.166063, 4.067663, 4.013614, 3.956404, 3.878255, 3.793946, 3.736236, 3.729196, 3.740676, 3.781876, 3.819005, 3.852335, 3.885125, 3.911485, 3.924665, 3.928495, 3.939054, 3.973554, 4.029514, 4.057104, 4.045584, 4.022284, 4.010404, 4.005724, 4.006414, 4.086083, 4.4413, 5.001265, 5.736007, 6.838603, 8.34002, 9.959991, 11.35377, 12.44355, 13.60481, 15.52396, 17.77848, 19.39912, 20.0516, 19.79411, 18.96384, 18.41486, 18.23317, 18.48616, 20.26689, 32.48054, 63.10282, 109.8659, 171.6945, 241.4077, 305.0739, 360.7728, 404.902, 416.5434, 404.6232, 359.8924, 306.567, 303.4439, 425.7646, 875.1105, 1607.013, 2526.451, 3508.944, 4398.309, 5050.909, 5401.95, 5544.863, 5862.182, 6107.529, 6831.056, 6635.575, 6448.201, 6268.538, 6096.169, 5930.727, 5771.872, 5619.265]) self['P'] = numpy.array([0.005, 0.0161, 0.0384, 0.0769, 0.137, 0.2244, 0.3454, 0.5064, 0.714, 0.9753, 1.2972, 1.6872, 2.1526, 2.7009, 3.3398, 4.077, 4.9204, 5.8776, 6.9567, 8.1655, 9.5119, 11.0038, 12.6492, 14.4559, 16.4318, 18.5847, 20.9224, 23.4526, 26.1829, 29.121, 32.2744, 35.6505, 39.2566, 43.1001, 47.1882, 51.5278, 56.126, 60.9895, 66.1253, 71.5398, 77.2396, 83.231, 89.5204, 96.1138, 103.017, 110.237, 117.778, 125.646, 133.846, 142.385, 151.266, 160.496, 170.078, 180.018, 190.32, 200.989, 212.028, 223.442, 235.234, 247.408, 259.969, 272.919, 286.262, 300.0, 314.137, 328.675, 343.618, 358.966, 374.724, 390.893, 407.474, 424.47, 441.882, 459.712, 477.961, 496.63, 515.72, 535.232, 555.167, 575.525, 596.306, 617.511, 639.14, 661.192, 683.667, 706.565, 729.886, 753.628, 777.79, 802.371, 827.371, 852.788, 878.62, 904.866, 931.524, 958.591, 986.067, 1013.95, 1042.23, 1070.92, 1100.0]) self['CO2'] = numpy.array([375.9234, 375.9232, 375.9219, 375.9195, 375.9172, 375.9142, 375.9041, 375.8819, 375.8607, 375.8617, 375.8997, 375.9717, 376.0398, 376.0858, 376.1489, 376.212, 376.224, 376.2321, 376.2481, 376.2772, 376.3252, 376.3663, 376.4023, 376.4224, 376.4504, 376.4865, 376.5545, 376.6335, 376.7605, 376.8966, 377.0446, 377.2036, 377.3766, 377.5606, 377.7106, 377.8485, 378.0765, 378.4945, 378.9365, 379.6475, 380.4225, 381.0245, 381.4085, 381.8025, 381.8315, 381.8625, 381.8985, 381.9405, 381.9845, 382.0364, 382.0903, 382.5651, 383.1618, 383.8894, 384.7668, 385.5962, 386.1156, 386.6532, 386.7607, 386.854, 386.8701, 386.8645, 386.8732, 386.8913, 386.9157, 386.9449, 386.9669, 386.9788, 386.9602, 386.9034, 386.8186, 386.7075, 386.6086, 386.5187, 386.4681, 386.4315, 386.4595, 386.5189, 386.6375, 386.8447, 387.1073, 387.3124, 387.433, 387.3937, 387.2297, 386.9659, 386.6525, 386.3522, 386.1188, 385.9826, 385.9361, 385.8209, 385.7317, 385.4548, 385.5337, 385.6074, 385.6771, 385.744, 385.8082, 385.8699, 385.9291]) self['CO'] = numpy.array([0.2205447, 0.2185316, 0.2145434, 0.2078282, 0.1977631, 0.1839901, 0.1511932, 0.09891954, 0.0827345, 0.05454007, 0.02926452, 0.01534331, 0.01021024, 0.00922827, 0.00895567, 0.00841368, 0.00791632, 0.0076217, 0.00749041, 0.00745301, 0.00740799, 0.00741502, 0.00746624, 0.00760092, 0.00775626, 0.00793258, 0.0081303, 0.00834271, 0.00844155, 0.00854593, 0.00861921, 0.00869836, 0.00895125, 0.009236, 0.00956421, 0.00993273, 0.01050776, 0.01155325, 0.01277055, 0.01483604, 0.01745463, 0.02009092, 0.02248201, 0.0252159, 0.0250677, 0.0249136, 0.0248554, 0.0248671, 0.0248747, 0.0248604, 0.02484549, 0.02830606, 0.03349511, 0.03954063, 0.04649641, 0.05393566, 0.05777834, 0.06203953, 0.06291754, 0.06367061, 0.06376177, 0.06365417, 0.06355173, 0.06345124, 0.063449, 0.06353453, 0.06376724, 0.06416551, 0.06445159, 0.0646028, 0.06451203, 0.06417925, 0.06369376, 0.06310236, 0.06261609, 0.06216137, 0.06196, 0.06180874, 0.06178709, 0.06208905, 0.06263239, 0.06350083, 0.06423774, 0.06476787, 0.06481747, 0.06471838, 0.06458966, 0.06447546, 0.06438733, 0.06432344, 0.06428367, 0.06423741, 0.0641983, 0.06589368, 0.07015209, 0.07475692, 0.0797395, 0.08513432, 0.09097941, 0.09731644, 0.1041912]) self['T'] = numpy.array([189.265, 197.336, 211.688, 227.871, 242.446, 252.765, 259.432, 262.908, 263.411, 262.202, 261.422, 259.368, 255.095, 250.075, 244.792, 239.205, 235.817, 231.46, 227.966, 225.935, 225.115, 222.382, 219.723, 218.152, 217.875, 218.211, 218.288, 218.294, 217.949, 217.202, 216.158, 214.964, 215.259, 215.053, 215.409, 216.081, 216.441, 216.152, 215.427, 215.082, 216.198, 217.247, 217.006, 216.373, 216.342, 217.088, 218.419, 219.839, 220.797, 220.946, 221.423, 222.504, 223.822, 225.134, 226.221, 226.93, 227.275, 227.405, 227.434, 227.346, 227.212, 227.246, 227.566, 228.2, 229.083, 230.094, 231.117, 232.121, 233.086, 234.01, 235.064, 236.351, 237.928, 239.892, 242.039, 244.306, 246.651, 249.025, 251.415, 253.802, 256.16, 258.448, 260.591, 262.445, 264.071, 265.349, 266.233, 266.969, 267.78, 268.72, 269.42, 270.502, 271.421, 273.317, 273.317, 273.317, 273.317, 273.317, 273.317, 273.317, 273.317]) self['N2O'] = numpy.array([0.00161, 0.00187, 0.00205999, 0.00220999, 0.00233999, 0.00235999, 0.00157999, 0.00186999, 0.00519997, 0.00870995, 0.00838995, 0.00955994, 0.01208993, 0.01432992, 0.0171399, 0.02172988, 0.02788985, 0.03756981, 0.04630977, 0.05168975, 0.05680973, 0.05922973, 0.06028973, 0.06131974, 0.07010971, 0.07957968, 0.08867964, 0.09929961, 0.1101496, 0.1206295, 0.1301795, 0.1371795, 0.1439595, 0.1505294, 0.1651494, 0.1848693, 0.2034792, 0.2285391, 0.252299, 0.2748389, 0.2840589, 0.2926288, 0.3004188, 0.3072488, 0.3129187, 0.3172487, 0.3200187, 0.3209987, 0.3209987, 0.3209987, 0.3209986, 0.3209984, 0.3209982, 0.3209978, 0.3209973, 0.3209968, 0.3209964, 0.320996, 0.3209956, 0.320995, 0.3209943, 0.3209938, 0.3209936, 0.3209936, 0.3209939, 0.3209941, 0.3209941, 0.3209941, 0.3209935, 0.3209896, 0.3209797, 0.3209647, 0.3209449, 0.3209225, 0.3209021, 0.3208842, 0.32087, 0.3208663, 0.3208701, 0.3208845, 0.3209016, 0.3209026, 0.3208633, 0.3207191, 0.3204841, 0.320189, 0.3198736, 0.3195881, 0.3193787, 0.319266, 0.3192201, 0.3191182, 0.3190395, 0.3188072, 0.31887, 0.3189301, 0.3189878, 0.3190431, 0.3190962, 0.3191472, 0.3191962]) self['O3'] = numpy.array([0.1903137, 0.2192386, 0.3077081, 0.5440408, 0.8590299, 1.170854, 1.499102, 1.864289, 2.273556, 2.805293, 3.409769, 4.028786, 4.806182, 5.619898, 6.411164, 7.147361, 7.51202, 7.648961, 7.644362, 7.556123, 7.446574, 7.281136, 6.952659, 6.604492, 6.296854, 6.008776, 5.751387, 5.520268, 5.311749, 5.111921, 4.890092, 4.593293, 4.298724, 3.882905, 3.380027, 2.799559, 2.288161, 2.031152, 2.018272, 2.047542, 1.969722, 1.685453, 1.220825, 0.9176053, 0.8929574, 0.9542592, 1.004996, 1.034796, 1.031726, 1.019046, 0.8797071, 0.6484178, 0.4105526, 0.2529783, 0.1943934, 0.201197, 0.2459162, 0.322179, 0.3977806, 0.4292413, 0.4255834, 0.3930204, 0.3461121, 0.2989281, 0.2606191, 0.2321107, 0.2069452, 0.1838146, 0.1618567, 0.1410414, 0.1225313, 0.1061913, 0.09214328, 0.08133816, 0.07293074, 0.06636085, 0.06143102, 0.05859298, 0.05740586, 0.05732126, 0.05783027, 0.05809797, 0.05651443, 0.05019414, 0.0404447, 0.03280082, 0.02944741, 0.02902179, 0.02945348, 0.02918976, 0.02836743, 0.02750451, 0.02608958, 0.02225294, 0.02225732, 0.02226152, 0.02226555, 0.02226941, 0.02227312, 0.02227668, 0.02228009]) self['CH4'] = numpy.array([0.1059488, 0.1201298, 0.1306706, 0.1417254, 0.1691352, 0.209023, 0.2345078, 0.2578465, 0.2845033, 0.328699, 0.3987896, 0.4800421, 0.5668716, 0.6510682, 0.7280449, 0.7954147, 0.8518465, 0.8903115, 0.9281374, 0.9731752, 1.016085, 1.071595, 1.131985, 1.189835, 1.247015, 1.302185, 1.355285, 1.400504, 1.442154, 1.464494, 1.488464, 1.514124, 1.541544, 1.560774, 1.579304, 1.596804, 1.612894, 1.627174, 1.638294, 1.650024, 1.662373, 1.675353, 1.688973, 1.722213, 1.729283, 1.736683, 1.741733, 1.745103, 1.749093, 1.755483, 1.762122, 1.770021, 1.77847, 1.785498, 1.790785, 1.795642, 1.79793, 1.800308, 1.800506, 1.800632, 1.800498, 1.800295, 1.800414, 1.800704, 1.800856, 1.800867, 1.800517, 1.799787, 1.798434, 1.796372, 1.794017, 1.791393, 1.789133, 1.787118, 1.785875, 1.784886, 1.784827, 1.785476, 1.788046, 1.791395, 1.795229, 1.798224, 1.800263, 1.801052, 1.800931, 1.80036, 1.799234, 1.797877, 1.796739, 1.796035, 1.795827, 1.795294, 1.79488, 1.793604, 1.793966, 1.794315, 1.794639, 1.794951, 1.795249, 1.795536, 1.795812]) self['CTP'] = 500.0 self['CFRACTION'] = 0.0 self['IDG'] = 0 self['ISH'] = 0 self['ELEVATION'] = 0.0 self['S2M']['T'] = 273.317 self['S2M']['Q'] = 5619.26541873 self['S2M']['O'] = 0.022280094739 self['S2M']['P'] = 905.85559 self['S2M']['U'] = 0.0 self['S2M']['V'] = 0.0 self['S2M']['WFETC'] = 100000.0 self['SKIN']['SURFTYPE'] = 0 self['SKIN']['WATERTYPE'] = 1 self['SKIN']['T'] = 273.317 self['SKIN']['SALINITY'] = 35.0 self['SKIN']['FOAM_FRACTION'] = 0.0 self['SKIN']['FASTEM'] = numpy.array([3.0, 5.0, 15.0, 0.1, 0.3]) self['ZENANGLE'] = 0.0 self['AZANGLE'] = 0.0 self['SUNZENANGLE'] = 0.0 self['SUNAZANGLE'] = 0.0 self['LATITUDE'] = 45.309 self['GAS_UNITS'] = 2 self['BE'] = 0.0 self['COSBK'] = 0.0 self['DATE'] = numpy.array([2007, 4, 1]) self['TIME'] = numpy.array([0, 0, 0])
s = input().strip() res = [c for c in set(s.lower()) if c.isalpha()] if len(res) == 26: print("pangram") else: print("not pangram")
s = input().strip() res = [c for c in set(s.lower()) if c.isalpha()] if len(res) == 26: print('pangram') else: print('not pangram')
class DataStream: async def create_private_listen_key(self) -> dict: """**Create a ListenKey (USER_STREAM)** Notes: ``POST /fapi/v1/listenKey`` See Also: https://binance-docs.github.io/apidocs/futures/en/#start-user-data-stream-user_stream """ return await self._fetch( 'POST', 'create_private_listen_key', '/fapi/v1/listenKey' ) async def update_private_listen_key(self) -> dict: """**Ping/Keep-alive a ListenKey (USER_STREAM)** Notes: ``PUT /fapi/v1/listenKey`` See Also: https://binance-docs.github.io/apidocs/futures/en/#keepalive-user-data-stream-user_stream """ return await self._fetch( 'PUT', 'update_private_listen_key', '/fapi/v1/listenKey' ) async def delete_private_listen_key(self) -> dict: """**Close a ListenKey (USER_STREAM)** Notes: ``DELETE /fapi/v1/listenKey`` See Also: https://binance-docs.github.io/apidocs/futures/en/#close-user-data-stream-user_stream """ return await self._fetch( 'DELETE', 'delete_private_listen_key', '/fapi/v1/listenKey' )
class Datastream: async def create_private_listen_key(self) -> dict: """**Create a ListenKey (USER_STREAM)** Notes: ``POST /fapi/v1/listenKey`` See Also: https://binance-docs.github.io/apidocs/futures/en/#start-user-data-stream-user_stream """ return await self._fetch('POST', 'create_private_listen_key', '/fapi/v1/listenKey') async def update_private_listen_key(self) -> dict: """**Ping/Keep-alive a ListenKey (USER_STREAM)** Notes: ``PUT /fapi/v1/listenKey`` See Also: https://binance-docs.github.io/apidocs/futures/en/#keepalive-user-data-stream-user_stream """ return await self._fetch('PUT', 'update_private_listen_key', '/fapi/v1/listenKey') async def delete_private_listen_key(self) -> dict: """**Close a ListenKey (USER_STREAM)** Notes: ``DELETE /fapi/v1/listenKey`` See Also: https://binance-docs.github.io/apidocs/futures/en/#close-user-data-stream-user_stream """ return await self._fetch('DELETE', 'delete_private_listen_key', '/fapi/v1/listenKey')
x = input("Enter sentence: ") count={"Uppercase":0, "Lowercase":0} for i in x: if i.isupper(): count["Uppercase"]+=1 elif i.islower(): count["Lowercase"]+=1 else: pass print ("There is:", count["Uppercase"], "uppercases.") print ("There is:", count["Lowercase"], "lowercases.")
x = input('Enter sentence: ') count = {'Uppercase': 0, 'Lowercase': 0} for i in x: if i.isupper(): count['Uppercase'] += 1 elif i.islower(): count['Lowercase'] += 1 else: pass print('There is:', count['Uppercase'], 'uppercases.') print('There is:', count['Lowercase'], 'lowercases.')
input = """ f(X,1) :- a(X,Y), g(A,X),g(B,X), not f(1,X). a(X,Y) :- g(X,0),g(Y,0). g(x1,0). g(x2,0). """ output = """ f(X,1) :- a(X,Y), g(A,X),g(B,X), not f(1,X). a(X,Y) :- g(X,0),g(Y,0). g(x1,0). g(x2,0). """
input = '\nf(X,1) :- a(X,Y),\n g(A,X),g(B,X),\n not f(1,X).\n\na(X,Y) :- g(X,0),g(Y,0).\n\ng(x1,0).\ng(x2,0).\n\n' output = '\nf(X,1) :- a(X,Y),\n g(A,X),g(B,X),\n not f(1,X).\n\na(X,Y) :- g(X,0),g(Y,0).\n\ng(x1,0).\ng(x2,0).\n\n'
file = open("13") sum = 0 for numbers in file: #print(numbers.rstrip()) numbers = int(numbers) sum += numbers; print(sum) sum = str(sum) print(sum[:10])
file = open('13') sum = 0 for numbers in file: numbers = int(numbers) sum += numbers print(sum) sum = str(sum) print(sum[:10])
variable1 = "variable original" def variable_global(): global variable1 variable1 = "variable global modificada" print(variable1) #variable original variable_global() print(variable1) #variable global modificada
variable1 = 'variable original' def variable_global(): global variable1 variable1 = 'variable global modificada' print(variable1) variable_global() print(variable1)
TIMEOUT=100 def GenerateWriteCommand(i2cAddress, ID, writeLocation, data): i = 0 TIMEOUT = 100 command = bytearray(len(data)+15) while (i < 4): command[i] = 255 i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 2 command[8] = writeLocation command[9] = len(data) command[(10 + len(data))] = 255 i = 0 while (i < len(data)): command[(10 + i)] = data[i] i += 1 i = 0 while (i < 4): command[(11 + i) + len(data)] = 254 i += 1 return command def GenerateReadCommand(i2cAddress, ID, readLocation, numToRead): command = bytearray(16) i = 0 TIMEOUT = 100 while (i < 4): command[i] = 0xFF i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 0x01 command[8] = readLocation command[9] = numToRead command[10] = 0xFF i = 0 while (i < 4): command[(11 + i)] = 0xFE i += 1 return command def GenerateToggleCommand(i2cAddress, ID, writeLocation, data): i = 0 command = bytearray(16 + 15) while (i < 4): command[i] = 255 i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 3 command[8] = data command[9] = 16 command[(10 + 16)] = 255 i = 0 while (i < 16): command[(10 + i)] = 7 i += 1 i = 0 while (i < 4): command[((11 + i) + 16)] = 254 i += 1 return command
timeout = 100 def generate_write_command(i2cAddress, ID, writeLocation, data): i = 0 timeout = 100 command = bytearray(len(data) + 15) while i < 4: command[i] = 255 i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 2 command[8] = writeLocation command[9] = len(data) command[10 + len(data)] = 255 i = 0 while i < len(data): command[10 + i] = data[i] i += 1 i = 0 while i < 4: command[11 + i + len(data)] = 254 i += 1 return command def generate_read_command(i2cAddress, ID, readLocation, numToRead): command = bytearray(16) i = 0 timeout = 100 while i < 4: command[i] = 255 i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 1 command[8] = readLocation command[9] = numToRead command[10] = 255 i = 0 while i < 4: command[11 + i] = 254 i += 1 return command def generate_toggle_command(i2cAddress, ID, writeLocation, data): i = 0 command = bytearray(16 + 15) while i < 4: command[i] = 255 i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 3 command[8] = data command[9] = 16 command[10 + 16] = 255 i = 0 while i < 16: command[10 + i] = 7 i += 1 i = 0 while i < 4: command[11 + i + 16] = 254 i += 1 return command
class AveragingBucketUpkeep: def __init__(self): self.numer = 0.0 self.denom = 0 def add_cost(self, cost): self.numer += cost self.denom += 1 return self.numer / self.denom def rem_cost(self, cost): self.numer -= cost self.denom -= 1 if self.denom == 0: return 0 return self.numer / self.denom
class Averagingbucketupkeep: def __init__(self): self.numer = 0.0 self.denom = 0 def add_cost(self, cost): self.numer += cost self.denom += 1 return self.numer / self.denom def rem_cost(self, cost): self.numer -= cost self.denom -= 1 if self.denom == 0: return 0 return self.numer / self.denom
__version__ = "2.18" def version(): """Returns the version number of the installed workflows package.""" return __version__ class Error(Exception): """Common class for exceptions deliberately raised by workflows package.""" class Disconnected(Error): """Indicates the connection could not be established or has been lost."""
__version__ = '2.18' def version(): """Returns the version number of the installed workflows package.""" return __version__ class Error(Exception): """Common class for exceptions deliberately raised by workflows package.""" class Disconnected(Error): """Indicates the connection could not be established or has been lost."""
sqlqueries = { 'WeatherForecast':"select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr, to_char(f.forecasted_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day, f.zipcode zip, min(f.temp_avg) low, max(f.temp_avg) high, max(f.wind_speed) wind, max(f.humidity) humidity from forecast f where to_char(forecast_timestamp, 'YYYY-MM-DD HH24') = (select max(to_char(forecast_timestamp, 'YYYY-MM-DD HH24')) from forecast) group by to_char(f.forecasted_timestamp, 'YY'), to_char(f.forecasted_timestamp, 'MON'), to_char(f.forecasted_timestamp, 'DD'), f.zipcode;", 'WeatherActDesc':"select concat ('FY', to_char(o.observation_timestamp, 'YY')) Fiscal_yr, to_char(o.observation_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(o.observation_timestamp, 'DD')) Fiscal_day, o.zipcode zip, o.weather_description descripion from observations o group by to_char(o.observation_timestamp, 'YY'), to_char(o.observation_timestamp, 'MON'), to_char(o.observation_timestamp, 'DD'), o.zipcode, o.weather_description order by fiscal_yr, fiscal_mth, fiscal_day, zip;", 'WeatherActual':"select concat ('FY', to_char(o.observation_timestamp, 'YY')) Fiscal_yr, to_char(o.observation_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(o.observation_timestamp, 'DD')) Fiscal_day, o.zipcode zip, min(o.temp_avg) low, max(o.temp_avg) high, max(o.wind_speed) wind, max(o.humidity) humidity from observations o group by to_char(o.observation_timestamp, 'YY'), to_char(o.observation_timestamp, 'MON') , to_char(o.observation_timestamp, 'DD') , o.zipcode order by fiscal_yr, fiscal_mth, fiscal_day, zip;", 'WeatherDescription':"select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr , to_char(f.forecasted_timestamp, 'MON') Fiscal_mth , concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day , f.zipcode zip , f.weather_description descripion from forecast f where to_char(forecast_timestamp, 'YYYY-MM-DD HH24') = (select max(to_char(forecast_timestamp, 'YYYY-MM-DD HH24')) from forecast) group by to_char(forecasted_timestamp, 'YY') , to_char(f.forecasted_timestamp, 'MON') , to_char(f.forecasted_timestamp, 'DD') , f.zipcode , f.weather_description;" }
sqlqueries = {'WeatherForecast': "select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr, to_char(f.forecasted_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day, f.zipcode zip, min(f.temp_avg) low, max(f.temp_avg) high, max(f.wind_speed) wind, max(f.humidity) humidity from forecast f where to_char(forecast_timestamp, 'YYYY-MM-DD HH24') = (select max(to_char(forecast_timestamp, 'YYYY-MM-DD HH24')) from forecast) group by to_char(f.forecasted_timestamp, 'YY'), to_char(f.forecasted_timestamp, 'MON'), to_char(f.forecasted_timestamp, 'DD'), f.zipcode;", 'WeatherActDesc': "select concat ('FY', to_char(o.observation_timestamp, 'YY')) Fiscal_yr, to_char(o.observation_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(o.observation_timestamp, 'DD')) Fiscal_day, o.zipcode zip, o.weather_description descripion from observations o group by to_char(o.observation_timestamp, 'YY'), to_char(o.observation_timestamp, 'MON'), to_char(o.observation_timestamp, 'DD'), o.zipcode, o.weather_description order by fiscal_yr, fiscal_mth, fiscal_day, zip;", 'WeatherActual': "select concat ('FY', to_char(o.observation_timestamp, 'YY')) Fiscal_yr, to_char(o.observation_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(o.observation_timestamp, 'DD')) Fiscal_day, o.zipcode zip, min(o.temp_avg) low, max(o.temp_avg) high, max(o.wind_speed) wind, max(o.humidity) humidity from observations o group by to_char(o.observation_timestamp, 'YY'), to_char(o.observation_timestamp, 'MON') , to_char(o.observation_timestamp, 'DD') , o.zipcode order by fiscal_yr, fiscal_mth, fiscal_day, zip;", 'WeatherDescription': "select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr , to_char(f.forecasted_timestamp, 'MON') Fiscal_mth , concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day , f.zipcode zip , f.weather_description descripion from forecast f where to_char(forecast_timestamp, 'YYYY-MM-DD HH24') = (select max(to_char(forecast_timestamp, 'YYYY-MM-DD HH24')) from forecast) group by to_char(forecasted_timestamp, 'YY') , to_char(f.forecasted_timestamp, 'MON') , to_char(f.forecasted_timestamp, 'DD') , f.zipcode , f.weather_description;"}
mock_dbcli_config = { 'exports_from': { 'lpass': { 'pull_lastpass_from': "{{ lastpass_entry }}", }, 'lpass_user_and_pass_only': { 'pull_lastpass_username_password_from': "{{ lastpass_entry }}", }, 'my-json-script': { 'json_script': [ 'some-custom-json-script' ] }, 'invalid-method': { }, }, 'dbs': { 'baz': { 'exports_from': 'my-json-script', }, 'bing': { 'exports_from': 'invalid-method', }, 'bazzle': { 'exports_from': 'lpass', 'lastpass_entry': 'lpass entry name' }, 'bazzle-bing': { 'exports_from': 'lpass', 'lastpass_entry': 'different lpass entry name' }, 'frazzle': { 'exports_from': 'lpass', 'lastpass_entry': 'lpass entry name' }, 'frink': { 'exports_from': 'lpass_user_and_pass_only', 'lastpass_entry': 'lpass entry name', 'jinja_context_name': 'standard', 'exports': { 'some_additional': 'export', 'a_numbered_export': 123 }, }, 'gaggle': { 'jinja_context_name': [ 'env', 'base64', ], 'exports': { 'type': 'bigquery', 'protocol': 'bigquery', 'bq_account': 'bq_itest', 'bq_service_account_json': "{{ env('ITEST_BIGQUERY_SERVICE_ACCOUNT_JSON_BASE64') | b64decode }}", 'bq_default_project_id': 'bluelabs-tools-dev', 'bq_default_dataset_id': 'bq_itest', }, }, }, 'orgs': { 'myorg': { 'full_name': 'MyOrg', }, }, }
mock_dbcli_config = {'exports_from': {'lpass': {'pull_lastpass_from': '{{ lastpass_entry }}'}, 'lpass_user_and_pass_only': {'pull_lastpass_username_password_from': '{{ lastpass_entry }}'}, 'my-json-script': {'json_script': ['some-custom-json-script']}, 'invalid-method': {}}, 'dbs': {'baz': {'exports_from': 'my-json-script'}, 'bing': {'exports_from': 'invalid-method'}, 'bazzle': {'exports_from': 'lpass', 'lastpass_entry': 'lpass entry name'}, 'bazzle-bing': {'exports_from': 'lpass', 'lastpass_entry': 'different lpass entry name'}, 'frazzle': {'exports_from': 'lpass', 'lastpass_entry': 'lpass entry name'}, 'frink': {'exports_from': 'lpass_user_and_pass_only', 'lastpass_entry': 'lpass entry name', 'jinja_context_name': 'standard', 'exports': {'some_additional': 'export', 'a_numbered_export': 123}}, 'gaggle': {'jinja_context_name': ['env', 'base64'], 'exports': {'type': 'bigquery', 'protocol': 'bigquery', 'bq_account': 'bq_itest', 'bq_service_account_json': "{{ env('ITEST_BIGQUERY_SERVICE_ACCOUNT_JSON_BASE64') | b64decode }}", 'bq_default_project_id': 'bluelabs-tools-dev', 'bq_default_dataset_id': 'bq_itest'}}}, 'orgs': {'myorg': {'full_name': 'MyOrg'}}}
# Time: O(n) # Space: O(1) class Solution(object): def minDistance(self, height, width, tree, squirrel, nuts): """ :type height: int :type width: int :type tree: List[int] :type squirrel: List[int] :type nuts: List[List[int]] :rtype: int """ def distance(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) result = 0 d = float("inf") for nut in nuts: result += (distance(nut, tree) * 2) d = min(d, distance(nut, squirrel) - distance(nut, tree)) return result + d
class Solution(object): def min_distance(self, height, width, tree, squirrel, nuts): """ :type height: int :type width: int :type tree: List[int] :type squirrel: List[int] :type nuts: List[List[int]] :rtype: int """ def distance(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) result = 0 d = float('inf') for nut in nuts: result += distance(nut, tree) * 2 d = min(d, distance(nut, squirrel) - distance(nut, tree)) return result + d
# Copyright 2000-2004 Michael Hudson mwh@python.net # # All Rights Reserved # # # Permission to use, copy, modify, and distribute this software and # its documentation for any purpose is hereby granted without fee, # provided that the above copyright notice appear in all copies and # that both that copyright notice and this permission notice appear in # supporting documentation. # # THE AUTHOR MICHAEL HUDSON DISCLAIMS ALL WARRANTIES WITH REGARD TO # THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, # INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. class Event: """An Event. `evt' is 'key' or somesuch.""" def __init__(self, evt, data, raw=''): self.evt = evt self.data = data self.raw = raw def __repr__(self): return 'Event(%r, %r)'%(self.evt, self.data) class Console: """Attributes: screen, height, width, """ def refresh(self, screen, xy): pass def prepare(self): pass def restore(self): pass def move_cursor(self, x, y): pass def set_cursor_vis(self, vis): pass def getheightwidth(self): """Return (height, width) where height and width are the height and width of the terminal window in characters.""" pass def get_event(self, block=1): """Return an Event instance. Returns None if |block| is false and there is no event pending, otherwise waits for the completion of an event.""" pass def beep(self): pass def clear(self): """Wipe the screen""" pass def finish(self): """Move the cursor to the end of the display and otherwise get ready for end. XXX could be merged with restore? Hmm.""" pass def flushoutput(self): """Flush all output to the screen (assuming there's some buffering going on somewhere).""" pass def forgetinput(self): """Forget all pending, but not yet processed input.""" pass def getpending(self): """Return the characters that have been typed but not yet processed.""" pass def wait(self): """Wait for an event.""" pass
class Event: """An Event. `evt' is 'key' or somesuch.""" def __init__(self, evt, data, raw=''): self.evt = evt self.data = data self.raw = raw def __repr__(self): return 'Event(%r, %r)' % (self.evt, self.data) class Console: """Attributes: screen, height, width, """ def refresh(self, screen, xy): pass def prepare(self): pass def restore(self): pass def move_cursor(self, x, y): pass def set_cursor_vis(self, vis): pass def getheightwidth(self): """Return (height, width) where height and width are the height and width of the terminal window in characters.""" pass def get_event(self, block=1): """Return an Event instance. Returns None if |block| is false and there is no event pending, otherwise waits for the completion of an event.""" pass def beep(self): pass def clear(self): """Wipe the screen""" pass def finish(self): """Move the cursor to the end of the display and otherwise get ready for end. XXX could be merged with restore? Hmm.""" pass def flushoutput(self): """Flush all output to the screen (assuming there's some buffering going on somewhere).""" pass def forgetinput(self): """Forget all pending, but not yet processed input.""" pass def getpending(self): """Return the characters that have been typed but not yet processed.""" pass def wait(self): """Wait for an event.""" pass
with open('./8/input_a.txt', 'r') as f: input = [[a.strip().split(' | ')[0].split(' '), a.strip().split(' | ')[1].split(' ')] for a in f] num = sum([sum([1 if len(a) in {2,3,4,7} else 0 for a in o[1]]) for o in input ]) print(f'Part A: Number of 1,4,7 or 8s in output - {num}') def getoutput(i): nums = ['0','1','2','3','4','5','6','7','8','9'] nums[1] = [a for a in i[0] if len(a) == 2][0] nums[4] = [a for a in i[0] if len(a) == 4][0] nums[7] = [a for a in i[0] if len(a) == 3][0] nums[8] = [a for a in i[0] if len(a) == 7][0] nums[9] = [a for a in i[0] if len(a) == 6 and set(nums[4]).issubset(set(a))][0] nums[0] = [a for a in i[0] if len(a) == 6 and set(nums[1]).issubset(set(a)) and a not in nums][0] nums[6] = [a for a in i[0] if len(a) == 6 and a not in nums][0] nums[3] = [a for a in i[0] if len(a) == 5 and set(nums[1]).issubset(set(a))][0] nums[5] = [a for a in i[0] if len(a) == 5 and (set(nums[4]) - set(nums[1])).issubset(set(a)) and a not in nums][0] nums[2] = [a for a in i[0] if len(a) == 5 and a not in nums][0] return int(''.join([str(nums.index([n for n in nums if set(n) == set(a)][0])) for a in i[1]])) print(f'Part B: total output sum value - {sum([getoutput(a) for a in input])}')
with open('./8/input_a.txt', 'r') as f: input = [[a.strip().split(' | ')[0].split(' '), a.strip().split(' | ')[1].split(' ')] for a in f] num = sum([sum([1 if len(a) in {2, 3, 4, 7} else 0 for a in o[1]]) for o in input]) print(f'Part A: Number of 1,4,7 or 8s in output - {num}') def getoutput(i): nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] nums[1] = [a for a in i[0] if len(a) == 2][0] nums[4] = [a for a in i[0] if len(a) == 4][0] nums[7] = [a for a in i[0] if len(a) == 3][0] nums[8] = [a for a in i[0] if len(a) == 7][0] nums[9] = [a for a in i[0] if len(a) == 6 and set(nums[4]).issubset(set(a))][0] nums[0] = [a for a in i[0] if len(a) == 6 and set(nums[1]).issubset(set(a)) and (a not in nums)][0] nums[6] = [a for a in i[0] if len(a) == 6 and a not in nums][0] nums[3] = [a for a in i[0] if len(a) == 5 and set(nums[1]).issubset(set(a))][0] nums[5] = [a for a in i[0] if len(a) == 5 and (set(nums[4]) - set(nums[1])).issubset(set(a)) and (a not in nums)][0] nums[2] = [a for a in i[0] if len(a) == 5 and a not in nums][0] return int(''.join([str(nums.index([n for n in nums if set(n) == set(a)][0])) for a in i[1]])) print(f'Part B: total output sum value - {sum([getoutput(a) for a in input])}')
class Node: def __init__(self, data): self.data = data self.next = None def sumLinkedListNodes(list1, list2): value1, value2 = "", "" head1, head2 = list1, list2 while head1: value1 += str(head1.data) head1 = head1.next while head2: value2 += str(head2.data) head2 = head2.next total = str(int(value1) + int(value2)) totalList = list(total) list3 = {"head": Node(int(totalList[0]))} current = list3["head"] for i in range(1, len(totalList)): current.next = Node(int(totalList[i])) current = current.next return list3 list1 = Node(5) list1.next = Node(6) list1.next.next = Node(3) list2 = Node(8) list2.next = Node(4) list2.next.next = Node(2) sumLinkedListNodes(list1, list2)
class Node: def __init__(self, data): self.data = data self.next = None def sum_linked_list_nodes(list1, list2): (value1, value2) = ('', '') (head1, head2) = (list1, list2) while head1: value1 += str(head1.data) head1 = head1.next while head2: value2 += str(head2.data) head2 = head2.next total = str(int(value1) + int(value2)) total_list = list(total) list3 = {'head': node(int(totalList[0]))} current = list3['head'] for i in range(1, len(totalList)): current.next = node(int(totalList[i])) current = current.next return list3 list1 = node(5) list1.next = node(6) list1.next.next = node(3) list2 = node(8) list2.next = node(4) list2.next.next = node(2) sum_linked_list_nodes(list1, list2)
class Stack: def __init__(self): self.array = [] self.top = -1 self.max = 100 def isEmpty(self): if(self.top == -1): return True else: return False def isFull(self): if(self.top == self.max -1): return True else: return False def push(self, data): if(self.isFull()): print("Stack Overflow") return else: self.top += 1 self.array.append(data) def pop(self): if(self.isEmpty()): print("Stack Underflow") return else: self.top -= 1 return(self.array.pop()) class SpecialStack(Stack): def __init__(self): super().__init__() self.Min = Stack() def push(self, x): if(self.isEmpty): super().push(x) self.Min.push(x) else: super().push(x) y = self.Min.pop() self.Min.push(y) if(x <= y): self.Min.push(x) else: self.Min.push(y) def pop(self): x = super().pop() self.Min.pop() return x def getMin(self): x = self.Min.pop() self.Min.push(x) return x if __name__ == "__main__": s = SpecialStack() s.push(10) s.push(20) s.push(30) print(s.getMin()) s.push(5) print(s.getMin())
class Stack: def __init__(self): self.array = [] self.top = -1 self.max = 100 def is_empty(self): if self.top == -1: return True else: return False def is_full(self): if self.top == self.max - 1: return True else: return False def push(self, data): if self.isFull(): print('Stack Overflow') return else: self.top += 1 self.array.append(data) def pop(self): if self.isEmpty(): print('Stack Underflow') return else: self.top -= 1 return self.array.pop() class Specialstack(Stack): def __init__(self): super().__init__() self.Min = stack() def push(self, x): if self.isEmpty: super().push(x) self.Min.push(x) else: super().push(x) y = self.Min.pop() self.Min.push(y) if x <= y: self.Min.push(x) else: self.Min.push(y) def pop(self): x = super().pop() self.Min.pop() return x def get_min(self): x = self.Min.pop() self.Min.push(x) return x if __name__ == '__main__': s = special_stack() s.push(10) s.push(20) s.push(30) print(s.getMin()) s.push(5) print(s.getMin())
#---------------------------------------------------------------------- # Basis Set Exchange # Version v0.8.13 # https://www.basissetexchange.org #---------------------------------------------------------------------- # Basis set: STO-3G # Description: STO-3G Minimal Basis (3 functions/AO) # Role: orbital # Version: 1 (Data from Gaussian09) #---------------------------------------------------------------------- # BASIS "ao basis" PRINT # #BASIS SET: (3s) -> [1s] # H S # 0.3425250914E+01 0.1543289673E+00 # 0.6239137298E+00 0.5353281423E+00 # 0.1688554040E+00 0.4446345422E+00 # END A_LIST = [3.425250914 , 0.6239137298, 0.1688554040] D_LIST = [0.1543289673, 0.5353281423, 0.4446345422]
a_list = [3.425250914, 0.6239137298, 0.168855404] d_list = [0.1543289673, 0.5353281423, 0.4446345422]
{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "001887f2", "metadata": {}, "outputs": [], "source": [ "# import os modules to create path across operating system to load csv file\n", "import os\n", "# module for reading csv files\n", "import csv" ] }, { "cell_type": "code", "execution_count": null, "id": "77c0f7d8", "metadata": {}, "outputs": [], "source": [ "# read csv data and load to budgetDB\n", "csvpath = os.path.join(\"Resources\",\"budget_data.csv\")" ] }, { "cell_type": "code", "execution_count": null, "id": "b2da0e1e", "metadata": {}, "outputs": [], "source": [ "# creat a txt file to hold the analysis\n", "outputfile = os.path.join(\"Analysis\",\"budget_analysis.txt\")" ] }, { "cell_type": "code", "execution_count": null, "id": "f3c0fd89", "metadata": {}, "outputs": [], "source": [ "# set var and initialize to zero\n", "totalMonths = 0 \n", "totalBudget = 0" ] }, { "cell_type": "code", "execution_count": null, "id": "4f807576", "metadata": {}, "outputs": [], "source": [ "# set list to store all of the monthly changes\n", "monthChange = [] \n", "months = []" ] }, { "cell_type": "code", "execution_count": null, "id": "ad264653", "metadata": {}, "outputs": [], "source": [ "# use csvreader object to import the csv library with csvreader object\n", "with open(csvpath, newline = \"\") as csvfile:\n", "# # create a csv reader object\n", " csvreader = csv.reader(csvfile, delimiter=\",\")\n", " \n", " # skip the first row since it has all of the column information\n", " #next(csvreader)\n", " \n", "#header: date, profit/losses\n", "print(csvreader)" ] }, { "cell_type": "code", "execution_count": null, "id": "27fc81c1", "metadata": {}, "outputs": [], "source": [ "for p in csvreader:\n", " print(\"date: \" + p[0])\n", " print(\"profit: \" + p[1])" ] }, { "cell_type": "code", "execution_count": null, "id": "83749f03", "metadata": {}, "outputs": [], "source": [ "# read the header row\n", "header = next(csvreader)\n", "print(f\"csv header:{header}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "3b441a20", "metadata": {}, "outputs": [], "source": [ "# move to the next row (first row)\n", "firstRow = next(csvreader)\n", "totalMonths = (len(f\"[csvfile.index(months)][csvfile]\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "a815e200", "metadata": {}, "outputs": [], "source": [ "output = (\n", " f\"Financial Anaylsis \\n\"\n", " f\"------------------------- \\n\"\n", " f\"Total Months: {totalMonths} \\n\")\n", "print(output)" ] }, { "cell_type": "code", "execution_count": null, "id": "6bf35c14", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" } }, "nbformat": 4, "nbformat_minor": 5 }
{'cells': [{'cell_type': 'code', 'execution_count': null, 'id': '001887f2', 'metadata': {}, 'outputs': [], 'source': ['# import os modules to create path across operating system to load csv file\n', 'import os\n', '# module for reading csv files\n', 'import csv']}, {'cell_type': 'code', 'execution_count': null, 'id': '77c0f7d8', 'metadata': {}, 'outputs': [], 'source': ['# read csv data and load to budgetDB\n', 'csvpath = os.path.join("Resources","budget_data.csv")']}, {'cell_type': 'code', 'execution_count': null, 'id': 'b2da0e1e', 'metadata': {}, 'outputs': [], 'source': ['# creat a txt file to hold the analysis\n', 'outputfile = os.path.join("Analysis","budget_analysis.txt")']}, {'cell_type': 'code', 'execution_count': null, 'id': 'f3c0fd89', 'metadata': {}, 'outputs': [], 'source': ['# set var and initialize to zero\n', 'totalMonths = 0 \n', 'totalBudget = 0']}, {'cell_type': 'code', 'execution_count': null, 'id': '4f807576', 'metadata': {}, 'outputs': [], 'source': ['# set list to store all of the monthly changes\n', 'monthChange = [] \n', 'months = []']}, {'cell_type': 'code', 'execution_count': null, 'id': 'ad264653', 'metadata': {}, 'outputs': [], 'source': ['# use csvreader object to import the csv library with csvreader object\n', 'with open(csvpath, newline = "") as csvfile:\n', '# # create a csv reader object\n', ' csvreader = csv.reader(csvfile, delimiter=",")\n', ' \n', ' # skip the first row since it has all of the column information\n', ' #next(csvreader)\n', ' \n', '#header: date, profit/losses\n', 'print(csvreader)']}, {'cell_type': 'code', 'execution_count': null, 'id': '27fc81c1', 'metadata': {}, 'outputs': [], 'source': ['for p in csvreader:\n', ' print("date: " + p[0])\n', ' print("profit: " + p[1])']}, {'cell_type': 'code', 'execution_count': null, 'id': '83749f03', 'metadata': {}, 'outputs': [], 'source': ['# read the header row\n', 'header = next(csvreader)\n', 'print(f"csv header:{header}")']}, {'cell_type': 'code', 'execution_count': null, 'id': '3b441a20', 'metadata': {}, 'outputs': [], 'source': ['# move to the next row (first row)\n', 'firstRow = next(csvreader)\n', 'totalMonths = (len(f"[csvfile.index(months)][csvfile]"))']}, {'cell_type': 'code', 'execution_count': null, 'id': 'a815e200', 'metadata': {}, 'outputs': [], 'source': ['output = (\n', ' f"Financial Anaylsis \\n"\n', ' f"------------------------- \\n"\n', ' f"Total Months: {totalMonths} \\n")\n', 'print(output)']}, {'cell_type': 'code', 'execution_count': null, 'id': '6bf35c14', 'metadata': {}, 'outputs': [], 'source': []}], 'metadata': {'kernelspec': {'display_name': 'Python 3', 'language': 'python', 'name': 'python3'}, 'language_info': {'codemirror_mode': {'name': 'ipython', 'version': 3}, 'file_extension': '.py', 'mimetype': 'text/x-python', 'name': 'python', 'nbconvert_exporter': 'python', 'pygments_lexer': 'ipython3', 'version': '3.8.8'}}, 'nbformat': 4, 'nbformat_minor': 5}
class Solution: """ @param A : an integer array @return : a integer """ def singleNumber(self, A): # write your code here return reduce(lambda x, y: x ^ y, A) if A != [] else 0
class Solution: """ @param A : an integer array @return : a integer """ def single_number(self, A): return reduce(lambda x, y: x ^ y, A) if A != [] else 0
# Copyright 2018 Luddite Labs Inc. # # 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. """ Block Quotes ------------ Line blocks are groups of lines beginning with vertical bar ("|") prefixes. Each vertical bar prefix indicates a new line, so line breaks are preserved. Initial indents are also significant, resulting in a nested structure. Inline markup is supported. Continuation lines are wrapped portions of long lines; they begin with a space in place of the vertical bar. The left edge of a continuation line must be indented, but need not be aligned with the left edge of the text above it. A line block ends with a blank line. Syntax diagram: +------------------------------+ | (current level of | | indentation) | +------------------------------+ +---------------------------+ | block quote | | (body elements)+ | | | | -- attribution text | | (optional) | +---------------------------+ http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#block-quotes """ class BlockQuoteMixin: def visit_block_quote(self, node): self.open_block(indent=self.options['indent'], top_margin=1, bottom_margin=1) def depart_block_quote(self, node): self.close_block() def visit_attribution(self, node): self.block.add_text(u'-- ') def depart_attribution(self, node): pass
""" Block Quotes ------------ Line blocks are groups of lines beginning with vertical bar ("|") prefixes. Each vertical bar prefix indicates a new line, so line breaks are preserved. Initial indents are also significant, resulting in a nested structure. Inline markup is supported. Continuation lines are wrapped portions of long lines; they begin with a space in place of the vertical bar. The left edge of a continuation line must be indented, but need not be aligned with the left edge of the text above it. A line block ends with a blank line. Syntax diagram: +------------------------------+ | (current level of | | indentation) | +------------------------------+ +---------------------------+ | block quote | | (body elements)+ | | | | -- attribution text | | (optional) | +---------------------------+ http://docutils.sourceforge.net/docs/ref/rst/restructuredtext.html#block-quotes """ class Blockquotemixin: def visit_block_quote(self, node): self.open_block(indent=self.options['indent'], top_margin=1, bottom_margin=1) def depart_block_quote(self, node): self.close_block() def visit_attribution(self, node): self.block.add_text(u'-- ') def depart_attribution(self, node): pass
# https://www.beecrowd.com.br/judge/en/problems/view/1017 car_efficiency = 12 # Km/L time = int(input()) average_speed = int(input()) liters = (time * average_speed) / car_efficiency print(f"{liters:.3f}")
car_efficiency = 12 time = int(input()) average_speed = int(input()) liters = time * average_speed / car_efficiency print(f'{liters:.3f}')
preference_list_of_user=[] def give(def_list): Def=def_list global preference_list_of_user preference_list_of_user=Def return Def def give_to_model(): return preference_list_of_user
preference_list_of_user = [] def give(def_list): def = def_list global preference_list_of_user preference_list_of_user = Def return Def def give_to_model(): return preference_list_of_user
def is_leap(year): leap = False # Write your logic here # The year can be evenly divided by 4, is a leap year, unless: # The year can be evenly divided by 100, it is NOT a leap year, unless: # The year is also evenly divisible by 400. Then it is a leap year. leap = (year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)) return leap year = int(input()) print(is_leap(year))
def is_leap(year): leap = False leap = year % 4 == 0 and (year % 400 == 0 or year % 100 != 0) return leap year = int(input()) print(is_leap(year))
# Set random number generator np.random.seed(2020) # Initialize step_end, n, t_range, v and i step_end = int(t_max / dt) n = 50 t_range = np.linspace(0, t_max, num=step_end) v_n = el * np.ones([n, step_end]) i = i_mean * (1 + 0.1 * (t_max / dt)**(0.5) * (2 * np.random.random([n, step_end]) - 1)) # Loop for step_end - 1 steps for step in range(1, step_end): # Compute v_n v_n[:, step] = v_n[:, step - 1] + (dt / tau) * (el - v_n[:, step - 1] + r * i[:, step]) # Plot figure with plt.xkcd(): plt.figure() plt.title('Multiple realizations of $V_m$') plt.xlabel('time (s)') plt.ylabel('$V_m$ (V)') plt.plot(t_range, v_n.T, 'k', alpha=0.3) plt.show()
np.random.seed(2020) step_end = int(t_max / dt) n = 50 t_range = np.linspace(0, t_max, num=step_end) v_n = el * np.ones([n, step_end]) i = i_mean * (1 + 0.1 * (t_max / dt) ** 0.5 * (2 * np.random.random([n, step_end]) - 1)) for step in range(1, step_end): v_n[:, step] = v_n[:, step - 1] + dt / tau * (el - v_n[:, step - 1] + r * i[:, step]) with plt.xkcd(): plt.figure() plt.title('Multiple realizations of $V_m$') plt.xlabel('time (s)') plt.ylabel('$V_m$ (V)') plt.plot(t_range, v_n.T, 'k', alpha=0.3) plt.show()
# ------------------------------ # 78. Subsets # # Description: # Given a set of distinct integers, nums, return all possible subsets (the power set). # Note: The solution set must not contain duplicate subsets. # # For example, # If nums = [1,2,3], a solution is: # [ # [3], # [1], # [2], # [1,2,3], # [1,3], # [2,3], # [1,2], # [] # ] # # Version: 1.0 # 01/20/18 by Jianfa # ------------------------------ class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums: return [[]] result = [] for i in range(len(nums) + 1): result += self.combine(nums, i) return result def combine(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[List[int]] """ res = [] currlist = [] self.backtrack(nums, k, currlist, 0, res) return res def backtrack(self, nums, k, currlist, start, res): if len(currlist) == k: temp = [x for x in currlist] res.append(temp) elif len(nums) - start + len(currlist) < k: return else: for i in range(start, len(nums)): currlist.append(nums[i]) self.backtrack(nums, k, currlist, i+1, res) currlist.pop() # Used for testing if __name__ == "__main__": test = Solution() nums = [1,3,5] test.subsets(nums) # ------------------------------ # Summary: # Borrow the combine idea from 77.py. The major difference is here a number list is provided. # The number list may include discontinuous integers. So the parameter "start" here means index # rather than number itself.
class Solution(object): def subsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ if not nums: return [[]] result = [] for i in range(len(nums) + 1): result += self.combine(nums, i) return result def combine(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[List[int]] """ res = [] currlist = [] self.backtrack(nums, k, currlist, 0, res) return res def backtrack(self, nums, k, currlist, start, res): if len(currlist) == k: temp = [x for x in currlist] res.append(temp) elif len(nums) - start + len(currlist) < k: return else: for i in range(start, len(nums)): currlist.append(nums[i]) self.backtrack(nums, k, currlist, i + 1, res) currlist.pop() if __name__ == '__main__': test = solution() nums = [1, 3, 5] test.subsets(nums)
class CompressedFastq( CompressedArchive ): """ Class describing an compressed fastq file This class can be sublass'ed to implement archive filetypes that will not be unpacked by upload.py. """ file_ext = "fq.gz" def set_peek( self, dataset, is_multi_byte=False ): if not dataset.dataset.purged: dataset.peek = "Compressed fastq file" dataset.blurb = nice_size( dataset.get_size() ) else: dataset.peek = 'file does not exist' dataset.blurb = 'file purged from disk' def display_peek( self, dataset ): try: return dataset.peek except: return "Compressed fastq file (%s)" % ( nice_size( dataset.get_size() ) ) Binary.register_unsniffable_binary_ext("fq.gz")
class Compressedfastq(CompressedArchive): """ Class describing an compressed fastq file This class can be sublass'ed to implement archive filetypes that will not be unpacked by upload.py. """ file_ext = 'fq.gz' def set_peek(self, dataset, is_multi_byte=False): if not dataset.dataset.purged: dataset.peek = 'Compressed fastq file' dataset.blurb = nice_size(dataset.get_size()) else: dataset.peek = 'file does not exist' dataset.blurb = 'file purged from disk' def display_peek(self, dataset): try: return dataset.peek except: return 'Compressed fastq file (%s)' % nice_size(dataset.get_size()) Binary.register_unsniffable_binary_ext('fq.gz')
# Copyright 2017 Google Inc. 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. """Module containing the InsertableString class.""" class InsertableString(object): """Class that accumulates insert and replace operations for a string and later performs them all at once so that positions in the original string can be used in all of the operations. """ def __init__(self, input_string): self.input_string = input_string self.to_insert = [] def insert_at(self, pos, s): """Add an insert operation at given position.""" self.to_insert.append((pos, pos, s)) def replace_range(self, start, end, s): """Add a replace operation for given range. Assume that all replace_range operations are disjoint, otherwise undefined behavior. """ self.to_insert.append((start, end, s)) def apply_insertions(self): """Return a string obtained by performing all accumulated operations.""" to_insert = reversed(sorted(self.to_insert)) result = self.input_string for start, end, s in to_insert: result = result[:start] + s + result[end:] return result
"""Module containing the InsertableString class.""" class Insertablestring(object): """Class that accumulates insert and replace operations for a string and later performs them all at once so that positions in the original string can be used in all of the operations. """ def __init__(self, input_string): self.input_string = input_string self.to_insert = [] def insert_at(self, pos, s): """Add an insert operation at given position.""" self.to_insert.append((pos, pos, s)) def replace_range(self, start, end, s): """Add a replace operation for given range. Assume that all replace_range operations are disjoint, otherwise undefined behavior. """ self.to_insert.append((start, end, s)) def apply_insertions(self): """Return a string obtained by performing all accumulated operations.""" to_insert = reversed(sorted(self.to_insert)) result = self.input_string for (start, end, s) in to_insert: result = result[:start] + s + result[end:] return result
class PaginatorOptions: def __init__( self, page_number: int, page_size: int, sort_column: str = None, sort_descending: bool = None ): self.sort_column = sort_column self.sort_descending = sort_descending self.page_number = page_number self.page_size = page_size assert (page_number is not None and page_size) \ or (page_number is not None and not page_size), \ 'Specify both page_number and page_size' if not sort_column: self.sort_column = 'id' self.sort_descending = True __all__ = ['PaginatorOptions']
class Paginatoroptions: def __init__(self, page_number: int, page_size: int, sort_column: str=None, sort_descending: bool=None): self.sort_column = sort_column self.sort_descending = sort_descending self.page_number = page_number self.page_size = page_size assert page_number is not None and page_size or (page_number is not None and (not page_size)), 'Specify both page_number and page_size' if not sort_column: self.sort_column = 'id' self.sort_descending = True __all__ = ['PaginatorOptions']
property_setter = { "dt": "Property Setter", "filters": [ ["name", "in", [ 'Purchase Order-read_only_onload', 'Purchase Order-default_print_format', 'Purchase Invoice-naming_series-options', 'Purchase Invoice-naming_series-default', 'Delivery Note-naming_series-options', 'Delivery Note-naming_series-default', 'Sales Order-naming_series-options', 'Sales Order-naming_series-default', 'Purchase Receipt-naming_series-options', 'Purchase Receipt-naming_series-default', 'Production Order-naming_series-options', 'Production Order-naming_series-default', 'Stock Entry-naming_series-options', 'Stock Entry-naming_series-default', 'Purchase Order-naming_series-options', 'Purchase Order-naming_series-default', 'Sales Invoice-naming_series-options', 'Sales Invoice-naming_series-default', 'Purchase Invoice-read_only_onload', 'Stock Reconciliation-read_only_onload', 'Delivery Note-read_only_onload', 'Stock Entry-read_only_onload', 'Sales Invoice-po_no-read_only', 'Sales Invoice-read_only_onload', 'Purchase Receipt Item-read_only_onload', 'Custom Field-fieldname-width', 'Custom Field-dt-width', 'Sales Invoice Item-read_only_onload', 'Sales Invoice Item-warehouse-default', 'Sales Order-po_no-read_only', 'Sales Order-read_only_onload', 'Item-read_only_onload', 'User-read_only_onload', 'User-sort_field', 'Asset Maintenance Task-periodicity-options', 'Asset Maintenance Task-read_only_onload', 'Asset-read_only_onload', 'Sales Invoice Item-customer_item_code-print_hide', 'Sales Invoice Item-customer_item_code-hidden', 'Sales Order Item-read_only_onload', 'BOM-with_operations-default', 'BOM-read_only_onload', 'Stock Entry-default_print_format', 'Purchase Receipt-read_only_onload', 'Production Order-skip_transfer-default', 'Production Order-skip_transfer-read_only', 'Production Order-use_multi_level_bom-default', 'Production Order-use_multi_level_bom-read_only', 'Production Order-read_only_onload', 'Purchase Order Item-amount-precision', 'Purchase Order Item-read_only_onload', 'Purchase Order Item-rate-precision', 'Stock Entry-use_multi_level_bom-default', 'Stock Entry-use_multi_level_bom-read_only', 'Stock Entry-from_bom-read_only', 'Stock Entry-from_bom-default', 'Stock Entry Detail-barcode-read_only', 'Stock Entry Detail-read_only_onload', 'Stock Entry-to_warehouse-read_only', 'Stock Entry-from_warehouse-read_only', 'Stock Entry-remarks-reqd', 'Purchase Receipt-in_words-print_hide', 'Purchase Receipt-in_words-hidden', 'Purchase Invoice-in_words-print_hide', 'Purchase Invoice-in_words-hidden', 'Purchase Order-in_words-print_hide', 'Purchase Order-in_words-hidden', 'Supplier Quotation-in_words-print_hide', 'Supplier Quotation-in_words-hidden', 'Delivery Note-in_words-print_hide', 'Delivery Note-in_words-hidden', 'Sales Invoice-in_words-print_hide', 'Sales Invoice-in_words-hidden', 'Sales Order-in_words-print_hide', 'Sales Order-in_words-hidden', 'Quotation-in_words-print_hide', 'Quotation-in_words-hidden', 'Purchase Order-rounded_total-print_hide', 'Purchase Order-rounded_total-hidden', 'Purchase Order-base_rounded_total-print_hide', 'Purchase Order-base_rounded_total-hidden', 'Supplier Quotation-rounded_total-print_hide', 'Supplier Quotation-rounded_total-hidden', 'Supplier Quotation-base_rounded_total-print_hide', 'Supplier Quotation-base_rounded_total-hidden', 'Delivery Note-rounded_total-print_hide', 'Delivery Note-rounded_total-hidden', 'Delivery Note-base_rounded_total-print_hide', 'Delivery Note-base_rounded_total-hidden', 'Sales Invoice-rounded_total-print_hide', 'Sales Invoice-rounded_total-hidden', 'Sales Invoice-base_rounded_total-print_hide', 'Sales Invoice-base_rounded_total-hidden', 'Sales Order-rounded_total-print_hide', 'Sales Order-rounded_total-hidden', 'Sales Order-base_rounded_total-print_hide', 'Sales Order-base_rounded_total-hidden', 'Quotation-rounded_total-print_hide', 'Quotation-rounded_total-hidden', 'Quotation-base_rounded_total-print_hide', 'Quotation-base_rounded_total-hidden', 'Dropbox Settings-dropbox_setup_via_site_config-hidden', 'Dropbox Settings-read_only_onload', 'Dropbox Settings-dropbox_access_token-hidden', 'Activity Log-subject-width', 'Employee-employee_number-hidden', 'Employee-employee_number-reqd', 'Employee-naming_series-reqd', 'Employee-naming_series-hidden', 'Supplier-naming_series-hidden', 'Supplier-naming_series-reqd', 'Delivery Note-tax_id-print_hide', 'Delivery Note-tax_id-hidden', 'Sales Invoice-tax_id-print_hide', 'Sales Invoice-tax_id-hidden', 'Sales Order-tax_id-print_hide', 'Sales Order-tax_id-hidden', 'Customer-naming_series-hidden', 'Customer-naming_series-reqd', 'Stock Entry Detail-barcode-hidden', 'Stock Reconciliation Item-barcode-hidden', 'Item-barcode-hidden', 'Delivery Note Item-barcode-hidden', 'Sales Invoice Item-barcode-hidden', 'Purchase Receipt Item-barcode-hidden', 'Item-item_code-reqd', 'Item-item_code-hidden', 'Item-naming_series-hidden', 'Item-naming_series-reqd', 'Item-manufacturing-collapsible_depends_on', 'Purchase Invoice-payment_schedule-print_hide', 'Purchase Invoice-due_date-print_hide', 'Purchase Order-payment_schedule-print_hide', 'Purchase Order-due_date-print_hide', 'Sales Invoice-payment_schedule-print_hide', 'Sales Invoice-due_date-print_hide', 'Sales Order-payment_schedule-print_hide', 'Sales Order-due_date-print_hide', 'Journal Entry Account-sort_order', 'Journal Entry Account-account_currency-print_hide', 'Sales Invoice-taxes_and_charges-reqd', 'Sales Taxes and Charges-sort_order', 'Sales Invoice Item-customer_item_code-label', 'Sales Invoice-default_print_format', 'Purchase Taxes and Charges Template-sort_order', 'Serial No-company-in_standard_filter', 'Serial No-amc_expiry_date-in_standard_filter', 'Serial No-warranty_expiry_date-in_standard_filter', 'Serial No-maintenance_status-in_standard_filter', 'Serial No-customer_name-in_standard_filter', 'Serial No-customer_name-bold', 'Serial No-customer-in_standard_filter', 'Serial No-delivery_document_no-in_standard_filter', 'Serial No-delivery_document_type-in_standard_filter', 'Serial No-supplier_name-bold', 'Serial No-supplier_name-in_standard_filter', 'Serial No-supplier-in_standard_filter', 'Serial No-purchase_date-in_standard_filter', 'Serial No-description-in_standard_filter', 'Delivery Note-section_break1-hidden', 'Delivery Note-sales_team_section_break-hidden', 'Delivery Note-project-hidden', 'Delivery Note-taxes-hidden', 'Delivery Note-taxes_and_charges-hidden', 'Delivery Note-taxes_section-hidden', 'Delivery Note-posting_time-print_hide', 'Delivery Note-posting_time-description', 'Delivery Note Item-warehouse-default', 'Item-income_account-default', 'Item-income_account-depends_on', 'Purchase Receipt-remarks-reqd', 'Purchase Receipt-taxes-hidden', 'Purchase Receipt-taxes_and_charges-hidden', 'Purchase Receipt Item-base_rate-fieldtype', 'Purchase Receipt Item-amount-in_list_view', 'Purchase Receipt Item-rate-fieldtype', 'Purchase Receipt Item-base_price_list_rate-fieldtype', 'Purchase Receipt Item-price_list_rate-fieldtype', 'Purchase Receipt Item-qty-in_list_view', 'Stock Entry-title_field', 'Stock Entry-search_fields', 'Stock Entry-project-hidden', 'Stock Entry-supplier-in_list_view', 'Stock Entry-from_warehouse-in_list_view', 'Stock Entry-to_warehouse-in_list_view', 'Stock Entry-purpose-default', 'ToDo-sort_order', 'Currency Exchange-sort_order', 'Company-abbr-in_list_view', 'Stock Reconciliation-expense_account-in_standard_filter', 'Stock Reconciliation-expense_account-depends_on', 'Sales Order-taxes-hidden', 'Warehouse-sort_order', 'Address-fax-hidden', 'Address-fax-read_only', 'Address-phone-hidden', 'Address-email_id-hidden', 'Address-city-reqd', 'BOM Operation-sort_order', 'BOM Item-scrap-read_only', 'BOM-operations_section-read_only', 'BOM-operations-read_only', 'BOM-rm_cost_as_per-reqd', 'Journal Entry-pay_to_recd_from-allow_on_submit', 'Journal Entry-remark-in_global_search', 'Journal Entry-total_amount-bold', 'Journal Entry-total_amount-print_hide', 'Journal Entry-total_amount-in_list_view', 'Journal Entry-total_credit-print_hide', 'Journal Entry-total_debit-print_hide', 'Journal Entry-total_debit-in_list_view', 'Journal Entry-user_remark-print_hide', 'Stock Entry-to_warehouse-hidden', 'Purchase Order Item-rate-fieldtype', 'Journal Entry Account-exchange_rate-print_hide', 'Sales Invoice Item-item_code-label', 'BOM-rm_cost_as_per-options', 'Purchase Order Item-price_list_rate-fieldtype', 'Reconciliation-expense_account-read_only', 'Customer-tax_id-read_only', 'Purchase Order Item-amount-fieldtype', 'Stock Entry-project-hidden' ] ] ] }
property_setter = {'dt': 'Property Setter', 'filters': [['name', 'in', ['Purchase Order-read_only_onload', 'Purchase Order-default_print_format', 'Purchase Invoice-naming_series-options', 'Purchase Invoice-naming_series-default', 'Delivery Note-naming_series-options', 'Delivery Note-naming_series-default', 'Sales Order-naming_series-options', 'Sales Order-naming_series-default', 'Purchase Receipt-naming_series-options', 'Purchase Receipt-naming_series-default', 'Production Order-naming_series-options', 'Production Order-naming_series-default', 'Stock Entry-naming_series-options', 'Stock Entry-naming_series-default', 'Purchase Order-naming_series-options', 'Purchase Order-naming_series-default', 'Sales Invoice-naming_series-options', 'Sales Invoice-naming_series-default', 'Purchase Invoice-read_only_onload', 'Stock Reconciliation-read_only_onload', 'Delivery Note-read_only_onload', 'Stock Entry-read_only_onload', 'Sales Invoice-po_no-read_only', 'Sales Invoice-read_only_onload', 'Purchase Receipt Item-read_only_onload', 'Custom Field-fieldname-width', 'Custom Field-dt-width', 'Sales Invoice Item-read_only_onload', 'Sales Invoice Item-warehouse-default', 'Sales Order-po_no-read_only', 'Sales Order-read_only_onload', 'Item-read_only_onload', 'User-read_only_onload', 'User-sort_field', 'Asset Maintenance Task-periodicity-options', 'Asset Maintenance Task-read_only_onload', 'Asset-read_only_onload', 'Sales Invoice Item-customer_item_code-print_hide', 'Sales Invoice Item-customer_item_code-hidden', 'Sales Order Item-read_only_onload', 'BOM-with_operations-default', 'BOM-read_only_onload', 'Stock Entry-default_print_format', 'Purchase Receipt-read_only_onload', 'Production Order-skip_transfer-default', 'Production Order-skip_transfer-read_only', 'Production Order-use_multi_level_bom-default', 'Production Order-use_multi_level_bom-read_only', 'Production Order-read_only_onload', 'Purchase Order Item-amount-precision', 'Purchase Order Item-read_only_onload', 'Purchase Order Item-rate-precision', 'Stock Entry-use_multi_level_bom-default', 'Stock Entry-use_multi_level_bom-read_only', 'Stock Entry-from_bom-read_only', 'Stock Entry-from_bom-default', 'Stock Entry Detail-barcode-read_only', 'Stock Entry Detail-read_only_onload', 'Stock Entry-to_warehouse-read_only', 'Stock Entry-from_warehouse-read_only', 'Stock Entry-remarks-reqd', 'Purchase Receipt-in_words-print_hide', 'Purchase Receipt-in_words-hidden', 'Purchase Invoice-in_words-print_hide', 'Purchase Invoice-in_words-hidden', 'Purchase Order-in_words-print_hide', 'Purchase Order-in_words-hidden', 'Supplier Quotation-in_words-print_hide', 'Supplier Quotation-in_words-hidden', 'Delivery Note-in_words-print_hide', 'Delivery Note-in_words-hidden', 'Sales Invoice-in_words-print_hide', 'Sales Invoice-in_words-hidden', 'Sales Order-in_words-print_hide', 'Sales Order-in_words-hidden', 'Quotation-in_words-print_hide', 'Quotation-in_words-hidden', 'Purchase Order-rounded_total-print_hide', 'Purchase Order-rounded_total-hidden', 'Purchase Order-base_rounded_total-print_hide', 'Purchase Order-base_rounded_total-hidden', 'Supplier Quotation-rounded_total-print_hide', 'Supplier Quotation-rounded_total-hidden', 'Supplier Quotation-base_rounded_total-print_hide', 'Supplier Quotation-base_rounded_total-hidden', 'Delivery Note-rounded_total-print_hide', 'Delivery Note-rounded_total-hidden', 'Delivery Note-base_rounded_total-print_hide', 'Delivery Note-base_rounded_total-hidden', 'Sales Invoice-rounded_total-print_hide', 'Sales Invoice-rounded_total-hidden', 'Sales Invoice-base_rounded_total-print_hide', 'Sales Invoice-base_rounded_total-hidden', 'Sales Order-rounded_total-print_hide', 'Sales Order-rounded_total-hidden', 'Sales Order-base_rounded_total-print_hide', 'Sales Order-base_rounded_total-hidden', 'Quotation-rounded_total-print_hide', 'Quotation-rounded_total-hidden', 'Quotation-base_rounded_total-print_hide', 'Quotation-base_rounded_total-hidden', 'Dropbox Settings-dropbox_setup_via_site_config-hidden', 'Dropbox Settings-read_only_onload', 'Dropbox Settings-dropbox_access_token-hidden', 'Activity Log-subject-width', 'Employee-employee_number-hidden', 'Employee-employee_number-reqd', 'Employee-naming_series-reqd', 'Employee-naming_series-hidden', 'Supplier-naming_series-hidden', 'Supplier-naming_series-reqd', 'Delivery Note-tax_id-print_hide', 'Delivery Note-tax_id-hidden', 'Sales Invoice-tax_id-print_hide', 'Sales Invoice-tax_id-hidden', 'Sales Order-tax_id-print_hide', 'Sales Order-tax_id-hidden', 'Customer-naming_series-hidden', 'Customer-naming_series-reqd', 'Stock Entry Detail-barcode-hidden', 'Stock Reconciliation Item-barcode-hidden', 'Item-barcode-hidden', 'Delivery Note Item-barcode-hidden', 'Sales Invoice Item-barcode-hidden', 'Purchase Receipt Item-barcode-hidden', 'Item-item_code-reqd', 'Item-item_code-hidden', 'Item-naming_series-hidden', 'Item-naming_series-reqd', 'Item-manufacturing-collapsible_depends_on', 'Purchase Invoice-payment_schedule-print_hide', 'Purchase Invoice-due_date-print_hide', 'Purchase Order-payment_schedule-print_hide', 'Purchase Order-due_date-print_hide', 'Sales Invoice-payment_schedule-print_hide', 'Sales Invoice-due_date-print_hide', 'Sales Order-payment_schedule-print_hide', 'Sales Order-due_date-print_hide', 'Journal Entry Account-sort_order', 'Journal Entry Account-account_currency-print_hide', 'Sales Invoice-taxes_and_charges-reqd', 'Sales Taxes and Charges-sort_order', 'Sales Invoice Item-customer_item_code-label', 'Sales Invoice-default_print_format', 'Purchase Taxes and Charges Template-sort_order', 'Serial No-company-in_standard_filter', 'Serial No-amc_expiry_date-in_standard_filter', 'Serial No-warranty_expiry_date-in_standard_filter', 'Serial No-maintenance_status-in_standard_filter', 'Serial No-customer_name-in_standard_filter', 'Serial No-customer_name-bold', 'Serial No-customer-in_standard_filter', 'Serial No-delivery_document_no-in_standard_filter', 'Serial No-delivery_document_type-in_standard_filter', 'Serial No-supplier_name-bold', 'Serial No-supplier_name-in_standard_filter', 'Serial No-supplier-in_standard_filter', 'Serial No-purchase_date-in_standard_filter', 'Serial No-description-in_standard_filter', 'Delivery Note-section_break1-hidden', 'Delivery Note-sales_team_section_break-hidden', 'Delivery Note-project-hidden', 'Delivery Note-taxes-hidden', 'Delivery Note-taxes_and_charges-hidden', 'Delivery Note-taxes_section-hidden', 'Delivery Note-posting_time-print_hide', 'Delivery Note-posting_time-description', 'Delivery Note Item-warehouse-default', 'Item-income_account-default', 'Item-income_account-depends_on', 'Purchase Receipt-remarks-reqd', 'Purchase Receipt-taxes-hidden', 'Purchase Receipt-taxes_and_charges-hidden', 'Purchase Receipt Item-base_rate-fieldtype', 'Purchase Receipt Item-amount-in_list_view', 'Purchase Receipt Item-rate-fieldtype', 'Purchase Receipt Item-base_price_list_rate-fieldtype', 'Purchase Receipt Item-price_list_rate-fieldtype', 'Purchase Receipt Item-qty-in_list_view', 'Stock Entry-title_field', 'Stock Entry-search_fields', 'Stock Entry-project-hidden', 'Stock Entry-supplier-in_list_view', 'Stock Entry-from_warehouse-in_list_view', 'Stock Entry-to_warehouse-in_list_view', 'Stock Entry-purpose-default', 'ToDo-sort_order', 'Currency Exchange-sort_order', 'Company-abbr-in_list_view', 'Stock Reconciliation-expense_account-in_standard_filter', 'Stock Reconciliation-expense_account-depends_on', 'Sales Order-taxes-hidden', 'Warehouse-sort_order', 'Address-fax-hidden', 'Address-fax-read_only', 'Address-phone-hidden', 'Address-email_id-hidden', 'Address-city-reqd', 'BOM Operation-sort_order', 'BOM Item-scrap-read_only', 'BOM-operations_section-read_only', 'BOM-operations-read_only', 'BOM-rm_cost_as_per-reqd', 'Journal Entry-pay_to_recd_from-allow_on_submit', 'Journal Entry-remark-in_global_search', 'Journal Entry-total_amount-bold', 'Journal Entry-total_amount-print_hide', 'Journal Entry-total_amount-in_list_view', 'Journal Entry-total_credit-print_hide', 'Journal Entry-total_debit-print_hide', 'Journal Entry-total_debit-in_list_view', 'Journal Entry-user_remark-print_hide', 'Stock Entry-to_warehouse-hidden', 'Purchase Order Item-rate-fieldtype', 'Journal Entry Account-exchange_rate-print_hide', 'Sales Invoice Item-item_code-label', 'BOM-rm_cost_as_per-options', 'Purchase Order Item-price_list_rate-fieldtype', 'Reconciliation-expense_account-read_only', 'Customer-tax_id-read_only', 'Purchase Order Item-amount-fieldtype', 'Stock Entry-project-hidden']]]}
""" First class definition""" class Cat: pass class RaceCar: pass cat1 = Cat() cat2 = Cat() cat3 = Cat()
""" First class definition""" class Cat: pass class Racecar: pass cat1 = cat() cat2 = cat() cat3 = cat()
# We can transition on native options using this # //command_line_option:<option-name> syntax _BUILD_SETTING = "//command_line_option:test_arg" def _test_arg_transition_impl(settings, attr): _ignore = (settings, attr) return {_BUILD_SETTING: ["new arg"]} _test_arg_transition = transition( implementation = _test_arg_transition_impl, inputs = [], outputs = [_BUILD_SETTING], ) def _test_transition_rule_impl(ctx): # We need to copy the executable because starlark doesn't allow # providing an executable not created by the rule executable_src = ctx.executable.actual_test executable_dst = ctx.actions.declare_file(ctx.label.name) ctx.actions.run_shell( tools = [executable_src], outputs = [executable_dst], command = "cp %s %s" % (executable_src.path, executable_dst.path), ) runfiles = ctx.attr.actual_test[0][DefaultInfo].default_runfiles return [DefaultInfo(runfiles = runfiles, executable = executable_dst)] transition_rule_test = rule( implementation = _test_transition_rule_impl, attrs = { "actual_test": attr.label(cfg = _test_arg_transition, executable = True), "_allowlist_function_transition": attr.label( default = "@bazel_tools//tools/allowlists/function_transition_allowlist", ), }, test = True, ) def test_arg_cc_test(name, **kwargs): cc_test_name = name + "_native_test" transition_rule_test( name = name, actual_test = ":%s" % cc_test_name, ) native.cc_test(name = cc_test_name, **kwargs)
_build_setting = '//command_line_option:test_arg' def _test_arg_transition_impl(settings, attr): _ignore = (settings, attr) return {_BUILD_SETTING: ['new arg']} _test_arg_transition = transition(implementation=_test_arg_transition_impl, inputs=[], outputs=[_BUILD_SETTING]) def _test_transition_rule_impl(ctx): executable_src = ctx.executable.actual_test executable_dst = ctx.actions.declare_file(ctx.label.name) ctx.actions.run_shell(tools=[executable_src], outputs=[executable_dst], command='cp %s %s' % (executable_src.path, executable_dst.path)) runfiles = ctx.attr.actual_test[0][DefaultInfo].default_runfiles return [default_info(runfiles=runfiles, executable=executable_dst)] transition_rule_test = rule(implementation=_test_transition_rule_impl, attrs={'actual_test': attr.label(cfg=_test_arg_transition, executable=True), '_allowlist_function_transition': attr.label(default='@bazel_tools//tools/allowlists/function_transition_allowlist')}, test=True) def test_arg_cc_test(name, **kwargs): cc_test_name = name + '_native_test' transition_rule_test(name=name, actual_test=':%s' % cc_test_name) native.cc_test(name=cc_test_name, **kwargs)
balance = 700 papers=[100, 50, 10, 5,4,3,2,1] def withdraw(balance, request): if balance < request : print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print ('your balance >>', balance) orgnal_request = request while request > 0: for i in papers: while request >= i: print('give', i) request-=i balance -= orgnal_request return balance def withdraw1(balance, request): give = 0 if balance < request : print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print ('your balance >>', balance) balance -= request while request > 0: if request >= 100: give = 100 elif request >= 50: give = 50 elif request >= 10: give = 10 elif request >= 5: give = 5 else : give = request print('give',give) request -= give return balance balance = withdraw(balance, 777) balance = withdraw(balance, 276) balance = withdraw1(balance, 276) balance = withdraw(balance, 34) balance = withdraw1(balance, 5) balance = withdraw1(balance, 500)
balance = 700 papers = [100, 50, 10, 5, 4, 3, 2, 1] def withdraw(balance, request): if balance < request: print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print('your balance >>', balance) orgnal_request = request while request > 0: for i in papers: while request >= i: print('give', i) request -= i balance -= orgnal_request return balance def withdraw1(balance, request): give = 0 if balance < request: print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print('your balance >>', balance) balance -= request while request > 0: if request >= 100: give = 100 elif request >= 50: give = 50 elif request >= 10: give = 10 elif request >= 5: give = 5 else: give = request print('give', give) request -= give return balance balance = withdraw(balance, 777) balance = withdraw(balance, 276) balance = withdraw1(balance, 276) balance = withdraw(balance, 34) balance = withdraw1(balance, 5) balance = withdraw1(balance, 500)
"""Top-level package for Feature Flag Server SDK.""" __author__ = """Enver Bisevac""" __email__ = "enver@bisevac.com" __version__ = "0.1.0"
"""Top-level package for Feature Flag Server SDK.""" __author__ = 'Enver Bisevac' __email__ = 'enver@bisevac.com' __version__ = '0.1.0'
arr_1 = ["1","2","3","4","5","6","7"] arr_2 = [] for n in arr_1: arr_2.insert(0,n) print(arr_2)
arr_1 = ['1', '2', '3', '4', '5', '6', '7'] arr_2 = [] for n in arr_1: arr_2.insert(0, n) print(arr_2)
"""Top-level package for z2z Metadata analysis.""" __author__ = """Isthmus // Mitchell P. Krawiec-Thayer""" __email__ = 'project_z2z_metadata@mitchellpkt.com' __version__ = '0.0.1'
"""Top-level package for z2z Metadata analysis.""" __author__ = 'Isthmus // Mitchell P. Krawiec-Thayer' __email__ = 'project_z2z_metadata@mitchellpkt.com' __version__ = '0.0.1'
class Player(object): """Player class Attributes: name (str): Player name """ def __init__(self, name): """Initialize player Args: name (str): Player name """ self.name = name def place_troops(self, board, n_troops): """Place troops on territories Args: board (Gameboard): The gameboard n_troops (int): Number of new troops to deploy Returns: (dict(str, int)): Dictionary of territories with number of troops to be deployed """ raise NotImplementedError('place_troops not implemented') def do_attack(self, board): """Decide whether or not to continue attacking Args: board (Gameboard): The gameboard Returns: (bool): Whether or not to continue attacking """ raise NotImplementedError('do_attack not implemented') def attack(self, board): """Attack phase Args: board (Gameboard): The gameboard Returns: (str, str): from_territory, to_territory """ raise NotImplementedError('attack not implemented') def do_move_troops(self, board): """Decide whether or not to move troops Args: board (Gameboard): The gameboard Returns: (bool): Whether or not to move troops """ raise NotImplementedError('do_move_troops not implemented') def move_troops(self, board): """Troop movement phase Args: board (Gameboard): The gameboard Returns: (str, str, int): from_territory, to_territory, n_troops """ raise NotImplementedError('move_troops not implemented')
class Player(object): """Player class Attributes: name (str): Player name """ def __init__(self, name): """Initialize player Args: name (str): Player name """ self.name = name def place_troops(self, board, n_troops): """Place troops on territories Args: board (Gameboard): The gameboard n_troops (int): Number of new troops to deploy Returns: (dict(str, int)): Dictionary of territories with number of troops to be deployed """ raise not_implemented_error('place_troops not implemented') def do_attack(self, board): """Decide whether or not to continue attacking Args: board (Gameboard): The gameboard Returns: (bool): Whether or not to continue attacking """ raise not_implemented_error('do_attack not implemented') def attack(self, board): """Attack phase Args: board (Gameboard): The gameboard Returns: (str, str): from_territory, to_territory """ raise not_implemented_error('attack not implemented') def do_move_troops(self, board): """Decide whether or not to move troops Args: board (Gameboard): The gameboard Returns: (bool): Whether or not to move troops """ raise not_implemented_error('do_move_troops not implemented') def move_troops(self, board): """Troop movement phase Args: board (Gameboard): The gameboard Returns: (str, str, int): from_territory, to_territory, n_troops """ raise not_implemented_error('move_troops not implemented')
n=int(input("Nhap vao mot so:")) d=dict() for i in range(1, n+1): d[i]=i*i print(d)
n = int(input('Nhap vao mot so:')) d = dict() for i in range(1, n + 1): d[i] = i * i print(d)
#!/usr/bin/env python # Copyright 2008-2010 Isaac Gouy # Copyright (c) 2013, 2014, Regents of the University of California # Copyright (c) 2017, 2018, Oracle and/or its affiliates. # All rights reserved. # # Revised BSD license # # This is a specific instance of the Open Source Initiative (OSI) BSD license # template http://www.opensource.org/licenses/bsd-license.php # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # Neither the name of "The Computer Language Benchmarks Game" nor the name of # "The Computer Language Shootout Benchmarks" nor the name "nanobench" nor the # name "bencher" nor the names of its contributors may be used to endorse or # promote products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #runas solve() #unittest.skip recursive generator #pythran export solve() # 01/08/14 modified for benchmarking by Wei Zhang COINS = [1, 2, 5, 10, 20, 50, 100, 200] # test def _sum(iterable): sum = None for i in iterable: if sum is None: sum = i else: sum += i return sum def balance(pattern): return _sum(COINS[x]*pattern[x] for x in range(0, len(pattern))) def gen(pattern, coinnum, num): coin = COINS[coinnum] for p in range(0, num//coin + 1): newpat = pattern[:coinnum] + (p,) bal = balance(newpat) if bal > num: return elif bal == num: yield newpat elif coinnum < len(COINS)-1: for pat in gen(newpat, coinnum+1, num): yield pat def solve(total): ''' In England the currency is made up of pound, P, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, P1 (100p) and P2 (200p). It is possible to make P2 in the following way: 1 P1 + 1 50p + 2 20p + 1 5p + 1 2p + 3 1p How many different ways can P2 be made using any number of coins? ''' return _sum(1 for pat in gen((), 0, total)) def measure(num): result = solve(num) print('total number of different ways: ', result) def __benchmark__(num=200): measure(num)
coins = [1, 2, 5, 10, 20, 50, 100, 200] def _sum(iterable): sum = None for i in iterable: if sum is None: sum = i else: sum += i return sum def balance(pattern): return _sum((COINS[x] * pattern[x] for x in range(0, len(pattern)))) def gen(pattern, coinnum, num): coin = COINS[coinnum] for p in range(0, num // coin + 1): newpat = pattern[:coinnum] + (p,) bal = balance(newpat) if bal > num: return elif bal == num: yield newpat elif coinnum < len(COINS) - 1: for pat in gen(newpat, coinnum + 1, num): yield pat def solve(total): """ In England the currency is made up of pound, P, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, P1 (100p) and P2 (200p). It is possible to make P2 in the following way: 1 P1 + 1 50p + 2 20p + 1 5p + 1 2p + 3 1p How many different ways can P2 be made using any number of coins? """ return _sum((1 for pat in gen((), 0, total))) def measure(num): result = solve(num) print('total number of different ways: ', result) def __benchmark__(num=200): measure(num)
# Problem: Student Attendance Record I # Difficulty: Easy # Category: String # Leetcode 551: https://leetcode.com/problems/student-attendance-record-i/#/description # Description: """ You are given a string representing an attendance record for a student. The record only contains the following three characters: 'A' : Absent. 'L' : Late. 'P' : Present. A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). You need to return whether the student could be rewarded according to his attendance record. Example 1: Input: "PPALLP" Output: True Example 2: Input: "PPALLL" Output: False """ class Solution(object): def check_record(self, s): absent = True late = True abscn = 0 i = 0 while i < len(s) and absent and late: if abscn > 1: absent = False if s[i] == 'A': abscn += 1 if s[i] == 'L' and i + 3 <= len(s) and set(s[i:i+3]) == {'L'}: late = False i += 1 if abscn > 1: absent = False return absent and late obj = Solution() s1 = 'PPALLP' s2 = 'PPALLL' s3 = 'ALLLPPPLLPL' s4 = 'AA' print(obj.check_record(s1)) print(obj.check_record(s2)) print(obj.check_record(s3)) print(obj.check_record(s4))
""" You are given a string representing an attendance record for a student. The record only contains the following three characters: 'A' : Absent. 'L' : Late. 'P' : Present. A student could be rewarded if his attendance record doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late). You need to return whether the student could be rewarded according to his attendance record. Example 1: Input: "PPALLP" Output: True Example 2: Input: "PPALLL" Output: False """ class Solution(object): def check_record(self, s): absent = True late = True abscn = 0 i = 0 while i < len(s) and absent and late: if abscn > 1: absent = False if s[i] == 'A': abscn += 1 if s[i] == 'L' and i + 3 <= len(s) and (set(s[i:i + 3]) == {'L'}): late = False i += 1 if abscn > 1: absent = False return absent and late obj = solution() s1 = 'PPALLP' s2 = 'PPALLL' s3 = 'ALLLPPPLLPL' s4 = 'AA' print(obj.check_record(s1)) print(obj.check_record(s2)) print(obj.check_record(s3)) print(obj.check_record(s4))
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: missingdata.py # # Tests: missing data # # Programmer: Brad Whitlock # Date: Thu Jan 19 09:49:15 PST 2012 # # Modifications: # # ---------------------------------------------------------------------------- def SetTheView(): v = GetView2D() v.viewportCoords = (0.02, 0.98, 0.25, 1) SetView2D(v) def test0(datapath): TestSection("Missing data") OpenDatabase(pjoin(datapath,"earth.nc")) AddPlot("Pseudocolor", "height") DrawPlots() SetTheView() Test("missingdata_0_00") ChangeActivePlotsVar("carbon_particulates") Test("missingdata_0_01") ChangeActivePlotsVar("seatemp") Test("missingdata_0_02") ChangeActivePlotsVar("population") Test("missingdata_0_03") # Pick on higher zone numbers to make sure pick works. PickByNode(domain=0, element=833621) TestText("missingdata_0_04", GetPickOutput()) DeleteAllPlots() def test1(datapath): TestSection("Expressions and missing data") OpenDatabase(pjoin(datapath,"earth.nc")) DefineScalarExpression("meaningless", "carbon_particulates + seatemp") AddPlot("Pseudocolor", "meaningless") DrawPlots() SetTheView() Test("missingdata_1_00") DeleteAllPlots() DefineVectorExpression("color", "color(red,green,blue)") AddPlot("Truecolor", "color") DrawPlots() ResetView() SetTheView() Test("missingdata_1_01") DefineVectorExpression("color2", "color(population*0.364,green,blue)") ChangeActivePlotsVar("color2") v1 = GetView2D() v1.viewportCoords = (0.02, 0.98, 0.02, 0.98) v1.windowCoords = (259.439, 513.299, 288.93, 540) #25.466) SetView2D(v1) Test("missingdata_1_02") def main(): datapath = data_path("netcdf_test_data") test0(datapath) test1(datapath) main() Exit()
def set_the_view(): v = get_view2_d() v.viewportCoords = (0.02, 0.98, 0.25, 1) set_view2_d(v) def test0(datapath): test_section('Missing data') open_database(pjoin(datapath, 'earth.nc')) add_plot('Pseudocolor', 'height') draw_plots() set_the_view() test('missingdata_0_00') change_active_plots_var('carbon_particulates') test('missingdata_0_01') change_active_plots_var('seatemp') test('missingdata_0_02') change_active_plots_var('population') test('missingdata_0_03') pick_by_node(domain=0, element=833621) test_text('missingdata_0_04', get_pick_output()) delete_all_plots() def test1(datapath): test_section('Expressions and missing data') open_database(pjoin(datapath, 'earth.nc')) define_scalar_expression('meaningless', 'carbon_particulates + seatemp') add_plot('Pseudocolor', 'meaningless') draw_plots() set_the_view() test('missingdata_1_00') delete_all_plots() define_vector_expression('color', 'color(red,green,blue)') add_plot('Truecolor', 'color') draw_plots() reset_view() set_the_view() test('missingdata_1_01') define_vector_expression('color2', 'color(population*0.364,green,blue)') change_active_plots_var('color2') v1 = get_view2_d() v1.viewportCoords = (0.02, 0.98, 0.02, 0.98) v1.windowCoords = (259.439, 513.299, 288.93, 540) set_view2_d(v1) test('missingdata_1_02') def main(): datapath = data_path('netcdf_test_data') test0(datapath) test1(datapath) main() exit()
class SerialNumber: def __init__(self, serialNumber): if not (len(serialNumber) == 6): raise ValueError('Serial Number must be 6 digits long') self._serialNumber = serialNumber def __str__(self): return 'S/N: {}'.format(self._serialNumber) def __repr__(self): return 'SerialNumber: {}'.format(self._serialNumber) def getSerialNumber(self): return self._serialNumber def containsVowel(self): VOWELS = ['a', 'e', 'i', 'o', 'u'] for character in self._serialNumber: if character in VOWELS: return True return False def lastDigitOdd(self): try: lastDigitValue = int(self._serialNumber[-1]) except ValueError: return False return lastDigitValue % 2 == 1 def lastDigitEven(self): try: lastDigitValue = int(self._serialNumber[-1]) except ValueError: return False return lastDigitValue % 2 == 0
class Serialnumber: def __init__(self, serialNumber): if not len(serialNumber) == 6: raise value_error('Serial Number must be 6 digits long') self._serialNumber = serialNumber def __str__(self): return 'S/N: {}'.format(self._serialNumber) def __repr__(self): return 'SerialNumber: {}'.format(self._serialNumber) def get_serial_number(self): return self._serialNumber def contains_vowel(self): vowels = ['a', 'e', 'i', 'o', 'u'] for character in self._serialNumber: if character in VOWELS: return True return False def last_digit_odd(self): try: last_digit_value = int(self._serialNumber[-1]) except ValueError: return False return lastDigitValue % 2 == 1 def last_digit_even(self): try: last_digit_value = int(self._serialNumber[-1]) except ValueError: return False return lastDigitValue % 2 == 0
# # BitBake Graphical GTK User Interface # # Copyright (C) 2012 Intel Corporation # # Authored by Shane Wang <shane.wang@intel.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program 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 this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. class HobColors: WHITE = "#ffffff" PALE_GREEN = "#aaffaa" ORANGE = "#eb8e68" PALE_RED = "#ffaaaa" GRAY = "#aaaaaa" LIGHT_GRAY = "#dddddd" SLIGHT_DARK = "#5f5f5f" DARK = "#3c3b37" BLACK = "#000000" PALE_BLUE = "#53b8ff" DEEP_RED = "#aa3e3e" KHAKI = "#fff68f" OK = WHITE RUNNING = PALE_GREEN WARNING = ORANGE ERROR = PALE_RED
class Hobcolors: white = '#ffffff' pale_green = '#aaffaa' orange = '#eb8e68' pale_red = '#ffaaaa' gray = '#aaaaaa' light_gray = '#dddddd' slight_dark = '#5f5f5f' dark = '#3c3b37' black = '#000000' pale_blue = '#53b8ff' deep_red = '#aa3e3e' khaki = '#fff68f' ok = WHITE running = PALE_GREEN warning = ORANGE error = PALE_RED
'''input 4 8 3 4 5 6 7 8 3 8 2 3 4 7 8 2 9 100 2 3 4 5 6 7 8 9 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem B if __name__ == '__main__': a, b, k = list(map(int, input().split())) if (b - a + 1) <= 2 * k: for i in range(a, b + 1): print(i) else: for j in range(a, a + k): print(j) for j in range(b - k + 1, b + 1): print(j)
"""input 4 8 3 4 5 6 7 8 3 8 2 3 4 7 8 2 9 100 2 3 4 5 6 7 8 9 """ if __name__ == '__main__': (a, b, k) = list(map(int, input().split())) if b - a + 1 <= 2 * k: for i in range(a, b + 1): print(i) else: for j in range(a, a + k): print(j) for j in range(b - k + 1, b + 1): print(j)
class Authenticator(object): def authenticate(self, credentials): raise NotImplementedError()
class Authenticator(object): def authenticate(self, credentials): raise not_implemented_error()
class Node(): def __init__(self, id: int, value = None, right: 'Node' = None, left: 'Node' = None): self.id = id self.value = value self.right = right self.left = left self.parent: 'Node' = None def add(self, node: 'Node'): if not node: raise ValueError('node value invalid') if node.id == self.id: raise ValueError('The id sent is alredy on the tree') if node.id > self.id: if not self.right: node.parent = self self.right = node else: self.right.add(node) if node.id < self.id: if not self.left: node.parent = self self.left = node else: self.left.add(node) def get_size(self): size_l = self.left.get_size() if self.left else 0 size_r = self.right.get_size() if self.right else 0 return 1 + size_l + size_r def get_height(self): h_l = self.left.get_height() if self.left else 0 h_r = self.right.get_height() if self.right else 0 if h_r > h_l: return 1 + h_r return 1 + h_l def get_node(self, id: int): if self.id == id: return self if id > self.id: if self.right: return self.right.get_node(id) if id < self.id: if self.left: return self.left.get_node(id) return None def get_min_node(self): if not self.left: return self return self.left.get_min_node() def get_max_node(self): if not self.right: return self return self.right.get_max_node() def get_sorted_list(self, max_size: int=None, ascending: bool=True): if max_size == None: return self.__get_list(ascending) return self.__get_list_by_size(max_size, ascending) def __get_list(self, ascending: bool): list_e = self.left.__get_list(ascending) if self.left else [] list_d = self.right.__get_list(ascending) if self.right else [] if ascending: return list_e + [self.id] + list_d return list_d + [self.id] + list_e def __get_list_by_size(self, max_size: int, ascending: bool): if ascending: st = 'left' fi = 'right' else: st = 'right' fi = 'left' list_st = self[st].__get_list_by_size(max_size=max_size, ascending=ascending) if self[st] else [] if max_size <= len(list_st): return list_st elif max_size <= len(list_st) + 1: return list_st + [self.id] else: curr_size = len(list_st) + 1 list_fi = self[fi].__get_list_by_size(max_size=max_size-curr_size, ascending=ascending) if self[fi] else [] return list_st + [self.id] + list_fi def __getitem__(self, name): return getattr(self, name) def __setitem__(self, name, value): return setattr(self, name, value) def __str__(self): str_e = self.left.__str__() if self.left else None str_d = self.right.__str__() if self.right else None if not (str_e or str_d): return f'[({self.id})]' return f'[({self.id}) {str_e}, {str_d}]'
class Node: def __init__(self, id: int, value=None, right: 'Node'=None, left: 'Node'=None): self.id = id self.value = value self.right = right self.left = left self.parent: 'Node' = None def add(self, node: 'Node'): if not node: raise value_error('node value invalid') if node.id == self.id: raise value_error('The id sent is alredy on the tree') if node.id > self.id: if not self.right: node.parent = self self.right = node else: self.right.add(node) if node.id < self.id: if not self.left: node.parent = self self.left = node else: self.left.add(node) def get_size(self): size_l = self.left.get_size() if self.left else 0 size_r = self.right.get_size() if self.right else 0 return 1 + size_l + size_r def get_height(self): h_l = self.left.get_height() if self.left else 0 h_r = self.right.get_height() if self.right else 0 if h_r > h_l: return 1 + h_r return 1 + h_l def get_node(self, id: int): if self.id == id: return self if id > self.id: if self.right: return self.right.get_node(id) if id < self.id: if self.left: return self.left.get_node(id) return None def get_min_node(self): if not self.left: return self return self.left.get_min_node() def get_max_node(self): if not self.right: return self return self.right.get_max_node() def get_sorted_list(self, max_size: int=None, ascending: bool=True): if max_size == None: return self.__get_list(ascending) return self.__get_list_by_size(max_size, ascending) def __get_list(self, ascending: bool): list_e = self.left.__get_list(ascending) if self.left else [] list_d = self.right.__get_list(ascending) if self.right else [] if ascending: return list_e + [self.id] + list_d return list_d + [self.id] + list_e def __get_list_by_size(self, max_size: int, ascending: bool): if ascending: st = 'left' fi = 'right' else: st = 'right' fi = 'left' list_st = self[st].__get_list_by_size(max_size=max_size, ascending=ascending) if self[st] else [] if max_size <= len(list_st): return list_st elif max_size <= len(list_st) + 1: return list_st + [self.id] else: curr_size = len(list_st) + 1 list_fi = self[fi].__get_list_by_size(max_size=max_size - curr_size, ascending=ascending) if self[fi] else [] return list_st + [self.id] + list_fi def __getitem__(self, name): return getattr(self, name) def __setitem__(self, name, value): return setattr(self, name, value) def __str__(self): str_e = self.left.__str__() if self.left else None str_d = self.right.__str__() if self.right else None if not (str_e or str_d): return f'[({self.id})]' return f'[({self.id}) {str_e}, {str_d}]'