content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class FPyCompare: def __readFile(self, fileName): with open(fileName) as f: lines = f.read().splitlines() return lines def __writeFile(self, resultList, fileName): with open(fileName, "w") as outfile: outfile.write("\n".join(resultList)) print(fileName + " completed!") def initializeList(self): fileNameOne = input("First File Name: ") self.listOne = set(self.__readFile(fileNameOne)) fileNameTwo = input("Second File Name: ") self.listTwo = set(self.__readFile(fileNameTwo)) def interset(self, printResult=True): intersect = list(self.listOne.intersection(self.listTwo)) print(intersect) if printResult else self.__writeFile(intersect, "result_intersect.txt") def union(self, printResult=True): union = list(self.listOne.union(self.listTwo)) print(union) if printResult else self.__writeFile(union, "result_union.txt") def differenceListOne(self, printResult=True): subtract = list(self.listOne.difference(self.listTwo)) print(subtract) if printResult else self.__writeFile(subtract, "result_DifferenceOne.txt") def differenceListTwo(self, printResult=True): subtract = list(self.listTwo.difference(self.listOne)) print(subtract) if printResult else self.__writeFile(subtract, "result_DifferenceTwo.txt") fCompare = FPyCompare() fCompare.initializeList() fCompare.interset(False) fCompare.union(False) fCompare.differenceListOne(False) fCompare.differenceListTwo(False)
class Fpycompare: def __read_file(self, fileName): with open(fileName) as f: lines = f.read().splitlines() return lines def __write_file(self, resultList, fileName): with open(fileName, 'w') as outfile: outfile.write('\n'.join(resultList)) print(fileName + ' completed!') def initialize_list(self): file_name_one = input('First File Name: ') self.listOne = set(self.__readFile(fileNameOne)) file_name_two = input('Second File Name: ') self.listTwo = set(self.__readFile(fileNameTwo)) def interset(self, printResult=True): intersect = list(self.listOne.intersection(self.listTwo)) print(intersect) if printResult else self.__writeFile(intersect, 'result_intersect.txt') def union(self, printResult=True): union = list(self.listOne.union(self.listTwo)) print(union) if printResult else self.__writeFile(union, 'result_union.txt') def difference_list_one(self, printResult=True): subtract = list(self.listOne.difference(self.listTwo)) print(subtract) if printResult else self.__writeFile(subtract, 'result_DifferenceOne.txt') def difference_list_two(self, printResult=True): subtract = list(self.listTwo.difference(self.listOne)) print(subtract) if printResult else self.__writeFile(subtract, 'result_DifferenceTwo.txt') f_compare = f_py_compare() fCompare.initializeList() fCompare.interset(False) fCompare.union(False) fCompare.differenceListOne(False) fCompare.differenceListTwo(False)
print(() == ()) print(() > ()) print(() < ()) print(() == (1,)) print((1,) == ()) print(() > (1,)) print((1,) > ()) print(() < (1,)) print((1,) < ()) print(() >= (1,)) print((1,) >= ()) print(() <= (1,)) print((1,) <= ()) print((1,) == (1,)) print((1,) != (1,)) print((1,) == (2,)) print((1,) == (1, 0,)) print((1,) > (1,)) print((1,) > (2,)) print((2,) > (1,)) print((1, 0,) > (1,)) print((1, -1,) > (1,)) print((1,) > (1, 0,)) print((1,) > (1, -1,)) print((1,) < (1,)) print((2,) < (1,)) print((1,) < (2,)) print((1,) < (1, 0,)) print((1,) < (1, -1,)) print((1, 0,) < (1,)) print((1, -1,) < (1,)) print((1,) >= (1,)) print((1,) >= (2,)) print((2,) >= (1,)) print((1, 0,) >= (1,)) print((1, -1,) >= (1,)) print((1,) >= (1, 0,)) print((1,) >= (1, -1,)) print((1,) <= (1,)) print((2,) <= (1,)) print((1,) <= (2,)) print((1,) <= (1, 0,)) print((1,) <= (1, -1,)) print((1, 0,) <= (1,)) print((1, -1,) <= (1,)) print((10, 0) > (1, 1)) print((10, 0) < (1, 1)) print((0, 0, 10, 0) > (0, 0, 1, 1)) print((0, 0, 10, 0) < (0, 0, 1, 1))
print(() == ()) print(() > ()) print(() < ()) print(() == (1,)) print((1,) == ()) print(() > (1,)) print((1,) > ()) print(() < (1,)) print((1,) < ()) print(() >= (1,)) print((1,) >= ()) print(() <= (1,)) print((1,) <= ()) print((1,) == (1,)) print((1,) != (1,)) print((1,) == (2,)) print((1,) == (1, 0)) print((1,) > (1,)) print((1,) > (2,)) print((2,) > (1,)) print((1, 0) > (1,)) print((1, -1) > (1,)) print((1,) > (1, 0)) print((1,) > (1, -1)) print((1,) < (1,)) print((2,) < (1,)) print((1,) < (2,)) print((1,) < (1, 0)) print((1,) < (1, -1)) print((1, 0) < (1,)) print((1, -1) < (1,)) print((1,) >= (1,)) print((1,) >= (2,)) print((2,) >= (1,)) print((1, 0) >= (1,)) print((1, -1) >= (1,)) print((1,) >= (1, 0)) print((1,) >= (1, -1)) print((1,) <= (1,)) print((2,) <= (1,)) print((1,) <= (2,)) print((1,) <= (1, 0)) print((1,) <= (1, -1)) print((1, 0) <= (1,)) print((1, -1) <= (1,)) print((10, 0) > (1, 1)) print((10, 0) < (1, 1)) print((0, 0, 10, 0) > (0, 0, 1, 1)) print((0, 0, 10, 0) < (0, 0, 1, 1))
# Copyright 2012 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. { 'variables': { 'chromium_code': 1, }, 'targets': [ { 'target_name': 'timed_decomposer_lib', 'type': 'static_library', 'sources': [ 'timed_decomposer_app.cc', 'timed_decomposer_app.h', ], 'dependencies': [ '<(src)/syzygy/pe/pe.gyp:pe_lib', '<(src)/syzygy/common/common.gyp:syzygy_version', ], }, { 'target_name': 'timed_decomposer', 'type': 'executable', 'sources': [ 'timed_decomposer_main.cc', ], 'dependencies': [ 'timed_decomposer_lib', ], 'run_as': { 'action': [ '$(TargetPath)', '--image=$(OutDir)\\test_dll.dll', '--csv=$(OutDir)\\decomposition_times_for_test_dll.csv', '--iterations=20', ], }, }, ], }
{'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'timed_decomposer_lib', 'type': 'static_library', 'sources': ['timed_decomposer_app.cc', 'timed_decomposer_app.h'], 'dependencies': ['<(src)/syzygy/pe/pe.gyp:pe_lib', '<(src)/syzygy/common/common.gyp:syzygy_version']}, {'target_name': 'timed_decomposer', 'type': 'executable', 'sources': ['timed_decomposer_main.cc'], 'dependencies': ['timed_decomposer_lib'], 'run_as': {'action': ['$(TargetPath)', '--image=$(OutDir)\\test_dll.dll', '--csv=$(OutDir)\\decomposition_times_for_test_dll.csv', '--iterations=20']}}]}
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: dummy_head = sublist_head = ListNode(0,head) for _ in range(1,left): sublist_head=sublist_head.next #Reversal sublist_iter = sublist_head.next for _ in range(right-left): temp=sublist_iter.next print(sublist_head) sublist_iter.next , temp.next , sublist_head.next = temp.next , sublist_head.next , temp print(sublist_head) return dummy_head.next
class Solution: def reverse_between(self, head: ListNode, left: int, right: int) -> ListNode: dummy_head = sublist_head = list_node(0, head) for _ in range(1, left): sublist_head = sublist_head.next sublist_iter = sublist_head.next for _ in range(right - left): temp = sublist_iter.next print(sublist_head) (sublist_iter.next, temp.next, sublist_head.next) = (temp.next, sublist_head.next, temp) print(sublist_head) return dummy_head.next
# Height in cm --> feet and inches # (just for ya fookin 'muricans) cm = float(input("Enter height in cm: ")) inches = cm/2.54 ft = int(inches//12) inches = int(round(inches % 12)) print("Height is about {}'{}\".".format(ft, inches))
cm = float(input('Enter height in cm: ')) inches = cm / 2.54 ft = int(inches // 12) inches = int(round(inches % 12)) print('Height is about {}\'{}".'.format(ft, inches))
# writing to a file : # To write to a file you need to create file stream = open('output.txt', 'wt') print('\n Can I write to this file : ' + str(stream.writable())) stream.write('H') # write a single string ... stream.writelines(['ello',' ', 'Susan']) # write multiple strings stream.write('\n') # write a new line # You can pass for writelines a list of strings names = ['Alen', 'Chris', 'Sausan'] # Here is how to write to a file using a list, and then you can use a neat feature so you can separate them using whatever you want using join stream.writelines(','.join(names)) stream.writelines('\n'.join(names)) stream.close() # flush stream and close
stream = open('output.txt', 'wt') print('\n Can I write to this file : ' + str(stream.writable())) stream.write('H') stream.writelines(['ello', ' ', 'Susan']) stream.write('\n') names = ['Alen', 'Chris', 'Sausan'] stream.writelines(','.join(names)) stream.writelines('\n'.join(names)) stream.close()
an_int = 2 a_float = 2.1 print(an_int + 3) # prints 5 # Define the release and runtime integer variables below: release_year = 15 runtime = 20 # Define the rating_out_of_10 float variable below: rating_out_of_10 = 3.5
an_int = 2 a_float = 2.1 print(an_int + 3) release_year = 15 runtime = 20 rating_out_of_10 = 3.5
N = int(input()) s = [input() for _ in range(5)] a = [ '.###..#..###.###.#.#.###.###.###.###.###.', '.#.#.##....#...#.#.#.#...#.....#.#.#.#.#.', '.#.#..#..###.###.###.###.###...#.###.###.', '.#.#..#..#.....#...#...#.#.#...#.#.#...#.', '.###.###.###.###...#.###.###...#.###.###.' ] result = [] for i in range(N): t = [s[j][i * 4:(i + 1) * 4] for j in range(5)] for j in range(10): for k in range(5): if t[k] != a[k][j * 4:(j + 1) * 4]: break else: result.append(j) break print(''.join(str(i) for i in result))
n = int(input()) s = [input() for _ in range(5)] a = ['.###..#..###.###.#.#.###.###.###.###.###.', '.#.#.##....#...#.#.#.#...#.....#.#.#.#.#.', '.#.#..#..###.###.###.###.###...#.###.###.', '.#.#..#..#.....#...#...#.#.#...#.#.#...#.', '.###.###.###.###...#.###.###...#.###.###.'] result = [] for i in range(N): t = [s[j][i * 4:(i + 1) * 4] for j in range(5)] for j in range(10): for k in range(5): if t[k] != a[k][j * 4:(j + 1) * 4]: break else: result.append(j) break print(''.join((str(i) for i in result)))
# -*- coding: utf-8 -*- """ Created on Tue Sep 22 15:47:38 2020 @author: xyz """ a = 4 b = 5 c = 6 d = True e = False bool1 = (d + d) >= 2 and (not e) bool2 = (not e) and (6*d == 12/2) bool3 = (d or (e)) and (a > b) print(bool1, bool2, bool3)
""" Created on Tue Sep 22 15:47:38 2020 @author: xyz """ a = 4 b = 5 c = 6 d = True e = False bool1 = d + d >= 2 and (not e) bool2 = not e and 6 * d == 12 / 2 bool3 = (d or e) and a > b print(bool1, bool2, bool3)
# Numpy is imported; seed is set # Initialize all_walks (don't change this line) all_walks = [] # Simulate random walk 10 times for i in range(10) : # Code from before random_walk = [0] for x in range(100) : step = random_walk[-1] dice = np.random.randint(1,7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1,7) random_walk.append(step) # Append random_walk to all_walks all_walks.append(random_walk) # Print all_walks print(all_walks) # numpy and matplotlib imported, seed set. # initialize and populate all_walks all_walks = [] for i in range(10) : random_walk = [0] for x in range(100) : step = random_walk[-1] dice = np.random.randint(1,7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1,7) random_walk.append(step) all_walks.append(random_walk) # Convert all_walks to Numpy array: np_aw np_aw = np.array(all_walks) # Plot np_aw and show plt.plot(np_aw) plt.show() # Clear the figure plt.clf() # Transpose np_aw: np_aw_t np_aw_t = np.transpose(np_aw) # Plot np_aw_t and show plt.plot(np_aw_t) plt.show() # numpy and matplotlib imported, seed set # Simulate random walk 250 times all_walks = [] for i in range(250) : random_walk = [0] for x in range(100) : step = random_walk[-1] dice = np.random.randint(1,7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1,7) # Implement clumsiness if np.random.rand() <= 0.001 : step = 0 random_walk.append(step) all_walks.append(random_walk) # Create and plot np_aw_t np_aw_t = np.transpose(np.array(all_walks)) plt.plot(np_aw_t) plt.show() # numpy and matplotlib imported, seed set # Simulate random walk 500 times all_walks = [] for i in range(500) : random_walk = [0] for x in range(100) : step = random_walk[-1] dice = np.random.randint(1,7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1,7) if np.random.rand() <= 0.001 : step = 0 random_walk.append(step) all_walks.append(random_walk) # Create and plot np_aw_t np_aw_t = np.transpose(np.array(all_walks)) # Select last row from np_aw_t: ends ends = np_aw_t[-1,:] # Plot histogram of ends, display plot plt.hist(ends) plt.show()
all_walks = [] for i in range(10): random_walk = [0] for x in range(100): step = random_walk[-1] dice = np.random.randint(1, 7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1, 7) random_walk.append(step) all_walks.append(random_walk) print(all_walks) all_walks = [] for i in range(10): random_walk = [0] for x in range(100): step = random_walk[-1] dice = np.random.randint(1, 7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1, 7) random_walk.append(step) all_walks.append(random_walk) np_aw = np.array(all_walks) plt.plot(np_aw) plt.show() plt.clf() np_aw_t = np.transpose(np_aw) plt.plot(np_aw_t) plt.show() all_walks = [] for i in range(250): random_walk = [0] for x in range(100): step = random_walk[-1] dice = np.random.randint(1, 7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1, 7) if np.random.rand() <= 0.001: step = 0 random_walk.append(step) all_walks.append(random_walk) np_aw_t = np.transpose(np.array(all_walks)) plt.plot(np_aw_t) plt.show() all_walks = [] for i in range(500): random_walk = [0] for x in range(100): step = random_walk[-1] dice = np.random.randint(1, 7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1, 7) if np.random.rand() <= 0.001: step = 0 random_walk.append(step) all_walks.append(random_walk) np_aw_t = np.transpose(np.array(all_walks)) ends = np_aw_t[-1, :] plt.hist(ends) plt.show()
# A file to test if pyvm works from the command line. def it_works(): print("Success!") it_works()
def it_works(): print('Success!') it_works()
n = "Hello" # Your function here! def string_function(s): return s + 'world' print(string_function(n))
n = 'Hello' def string_function(s): return s + 'world' print(string_function(n))
#this software is a copyrighted product made by laba.not for resell. all right reserved.date-7th may 2018. one of the 1st software made by laba. print("Welcome to Personal dictionary by laba.\nThis ugliest software is made by most handsome man alive name laba.") print("\nThis software aims to make your process for learning new words easy. \nJust add a new word and a note describing it. Revice twice a day.") words = [] notes = [] def word_entry(word): w_entry = {"word": word} words.append(w_entry) def note_entry(note): n_entry = {"note": note} notes.append(n_entry) def inputf(): word_input = input("Enter the word you wanna add: ") note_input = input("Enter description note: ") word_entry(word_input) note_entry(note_input) save_file(word_input, note_input) def save_file(word, note): try: f = open("log.txt", "a") f.write(word + " - " + note + "\n") f.close() except Exception: print("uh oh! fucked up while saving \ntrying to unfuck...") def read_file(): try: f = open("log.txt", "r") print("\nWORD - NOTE\n") """generator function""" def read_lines(f): for line in f: yield line for entry in read_lines(f): print(entry) f.close() except Exception: ask = input("\nHey niggah, how are you doin? using this software for 1st time? \nDon't worry its easy to use. \nTo add a new word in your personal dictionary Type Y ;-D - ") if (ask == "Y"): inputf() print("see its easy!!") else: print("capital Y niggah ;-|") read_file() num = 1 while (num == 1): ask_again = input("Wanna add more word? type Y for yes, N for exit - ") if ask_again == "Y": inputf() continue elif ask_again == "y": print("fucking fuuuuuck... are you fuckin blind? or trying to break my software ? can't read a simple instruction? type CAPITAL Y.") else: break
print('Welcome to Personal dictionary by laba.\nThis ugliest software is made by most handsome man alive name laba.') print('\nThis software aims to make your process for learning new words easy. \nJust add a new word and a note describing it. Revice twice a day.') words = [] notes = [] def word_entry(word): w_entry = {'word': word} words.append(w_entry) def note_entry(note): n_entry = {'note': note} notes.append(n_entry) def inputf(): word_input = input('Enter the word you wanna add: ') note_input = input('Enter description note: ') word_entry(word_input) note_entry(note_input) save_file(word_input, note_input) def save_file(word, note): try: f = open('log.txt', 'a') f.write(word + ' - ' + note + '\n') f.close() except Exception: print('uh oh! fucked up while saving \ntrying to unfuck...') def read_file(): try: f = open('log.txt', 'r') print('\nWORD - NOTE\n') 'generator function' def read_lines(f): for line in f: yield line for entry in read_lines(f): print(entry) f.close() except Exception: ask = input("\nHey niggah, how are you doin? using this software for 1st time? \nDon't worry its easy to use. \nTo add a new word in your personal dictionary Type Y ;-D - ") if ask == 'Y': inputf() print('see its easy!!') else: print('capital Y niggah ;-|') read_file() num = 1 while num == 1: ask_again = input('Wanna add more word? type Y for yes, N for exit - ') if ask_again == 'Y': inputf() continue elif ask_again == 'y': print("fucking fuuuuuck... are you fuckin blind? or trying to break my software ? can't read a simple instruction? type CAPITAL Y.") else: break
# Final Exam, Problem 4 - 2 def longestRun(L): ''' Assumes L is a non-empty list Returns the length of the longest monotonically increasing ''' maxRun = 0 tempRun = 0 for i in range(len(L) - 1): if L[i + 1] >= L[i]: tempRun += 1 if tempRun > maxRun: maxRun = tempRun else: tempRun = 0 return maxRun + 1
def longest_run(L): """ Assumes L is a non-empty list Returns the length of the longest monotonically increasing """ max_run = 0 temp_run = 0 for i in range(len(L) - 1): if L[i + 1] >= L[i]: temp_run += 1 if tempRun > maxRun: max_run = tempRun else: temp_run = 0 return maxRun + 1
# # @lc app=leetcode id=415 lang=python3 # # [415] Add Strings # # https://leetcode.com/problems/add-strings/description/ # # algorithms # Easy (51.34%) # Likes: 2772 # Dislikes: 495 # Total Accepted: 421.8K # Total Submissions: 820.4K # Testcase Example: '"11"\n"123"' # # Given two non-negative integers, num1 and num2 represented as string, return # the sum of num1 and num2 as a string. # # You must solve the problem without using any built-in library for handling # large integers (such as BigInteger). You must also not convert the inputs to # integers directly. # # # Example 1: # # # Input: num1 = "11", num2 = "123" # Output: "134" # # # Example 2: # # # Input: num1 = "456", num2 = "77" # Output: "533" # # # Example 3: # # # Input: num1 = "0", num2 = "0" # Output: "0" # # # # Constraints: # # # 1 <= num1.length, num2.length <= 10^4 # num1 and num2 consist of only digits. # num1 and num2 don't have any leading zeros except for the zero itself. # # # # @lc code=start class Solution: def addStrings(self, num1: str, num2: str) -> str: ans = int(num1) + int(num2) return str(ans) # @lc code=end
class Solution: def add_strings(self, num1: str, num2: str) -> str: ans = int(num1) + int(num2) return str(ans)
def landscaper(f, generations): seen_states = {} states = [] state = f.readline().strip().split(' ')[-1] f.readline() rules = {} idx = 0 prev_sum = None for rule in f.readlines(): keys, _, res = rule.strip().split(' ') if res == '#': rules[keys] = True for i in range(0, generations): first_hash = state.index('#') if first_hash < 5: adds = 5 - first_hash state = '.' * adds + state idx -= adds last_hash = state.rindex('#') if last_hash > (len(state) - 5): state += '.' * (6 - abs(last_hash - len(state))) output = state[:2] for x in range(2, len(state) - 2): output += '#' if state[x-2:x+3] in rules else '.' output += state[len(state) - 2:] state = output k = state.strip('.') if k in seen_states: current = sum_state(state, idx) if prev_sum: diff = current - prev_sum return current + diff * (generations - seen_states[k][0] - 2) prev_sum = current seen_states[k] = (i, idx) states.append(state) return sum_state(state, idx) def sum_state(state, idx): s = 0 for i in range(0, len(state)): add = (i + idx) if state[i] == '#' else 0 s += add return s def test_landscaper(): assert landscaper(open('input/12.test'), 20) == 325 if __name__ == '__main__': print(landscaper(open('input/12'), 20)) print(landscaper(open('input/12'), 128)) print(landscaper(open('input/12'), 50_000_000_000))
def landscaper(f, generations): seen_states = {} states = [] state = f.readline().strip().split(' ')[-1] f.readline() rules = {} idx = 0 prev_sum = None for rule in f.readlines(): (keys, _, res) = rule.strip().split(' ') if res == '#': rules[keys] = True for i in range(0, generations): first_hash = state.index('#') if first_hash < 5: adds = 5 - first_hash state = '.' * adds + state idx -= adds last_hash = state.rindex('#') if last_hash > len(state) - 5: state += '.' * (6 - abs(last_hash - len(state))) output = state[:2] for x in range(2, len(state) - 2): output += '#' if state[x - 2:x + 3] in rules else '.' output += state[len(state) - 2:] state = output k = state.strip('.') if k in seen_states: current = sum_state(state, idx) if prev_sum: diff = current - prev_sum return current + diff * (generations - seen_states[k][0] - 2) prev_sum = current seen_states[k] = (i, idx) states.append(state) return sum_state(state, idx) def sum_state(state, idx): s = 0 for i in range(0, len(state)): add = i + idx if state[i] == '#' else 0 s += add return s def test_landscaper(): assert landscaper(open('input/12.test'), 20) == 325 if __name__ == '__main__': print(landscaper(open('input/12'), 20)) print(landscaper(open('input/12'), 128)) print(landscaper(open('input/12'), 50000000000))
# printing out a string print("lol") # printing out a space betwin them (\n) print("Hello\nWorld") # if you want to put a (") inside do this: print("Hello\"World\"") # if you want to put a (\) inside just type: print("Hello\World") # you can also print a variable like this; lol = "Hello World" print(lol) # you can also do something called cencatenation who is putting a string whit some text like this; lol = "Hello World" print(lol + " Hello World") # you can also use fonctions to change info or to know info about a sring. exemple of fonctions; lol = "Hello World" # puts every thing small or decapitelize print(lol.lower()) # capitelize everything print(lol.upper()) # boolean is it all cap. print(lol.isupper()) # 2 same time print(lol.upper().isupper()) # tells you lhe length print(len(lol)) # this fonction shows a letter of the string(0 for "H", 1 for "e" exetera). lol = "Hello World" print(lol[0]) print(lol[1]) # you can return the index (the position of a letter)by doing this: print(lol.index("d")) # you can also replace a word in your string like this: print(lol.replace("World", "dude"))
print('lol') print('Hello\nWorld') print('Hello"World"') print('Hello\\World') lol = 'Hello World' print(lol) lol = 'Hello World' print(lol + ' Hello World') lol = 'Hello World' print(lol.lower()) print(lol.upper()) print(lol.isupper()) print(lol.upper().isupper()) print(len(lol)) lol = 'Hello World' print(lol[0]) print(lol[1]) print(lol.index('d')) print(lol.replace('World', 'dude'))
def funcao(x = 1,y = 1): return 2*x+y print(funcao(2,3)) print(funcao(3,2)) print(funcao(1,2))
def funcao(x=1, y=1): return 2 * x + y print(funcao(2, 3)) print(funcao(3, 2)) print(funcao(1, 2))
''' author: Iuri Freire e-mail: iuricostafreire at gmail dot com local date : 2021-01-07 local time : 20:47 '''
""" author: Iuri Freire e-mail: iuricostafreire at gmail dot com local date : 2021-01-07 local time : 20:47 """
# -*- coding: utf-8 -*- """ snaplayer ~~~~~~~~ The very basics :copyright: (c) 2015 by Alejandro Ricoveri :license: MIT, see LICENSE for more details. """ PKG_URL = 'https://github.com/axltxl/snaplayer' __name__ = 'snaplayer' __author__ = 'Alejandro Ricoveri' __version__ = '0.1.1' __licence__ = 'MIT' __copyright__ = 'Copyright (c) Alejandro Ricoveri'
""" snaplayer ~~~~~~~~ The very basics :copyright: (c) 2015 by Alejandro Ricoveri :license: MIT, see LICENSE for more details. """ pkg_url = 'https://github.com/axltxl/snaplayer' __name__ = 'snaplayer' __author__ = 'Alejandro Ricoveri' __version__ = '0.1.1' __licence__ = 'MIT' __copyright__ = 'Copyright (c) Alejandro Ricoveri'
name = 'exit' usage = 'EXIT' description = 'Exits Diplomat.' def execute(query): return 'Exiting Diplomat.'
name = 'exit' usage = 'EXIT' description = 'Exits Diplomat.' def execute(query): return 'Exiting Diplomat.'
"""Args: param1 (int): byte as int value in binary Returns: True if input indicates a meta event, False if otherwise. """ def is_meta(n): # hex status byte 0xFF # dec value 255 dec_val = int(n, 2) if dec_val == 255: return True else: return False
"""Args: param1 (int): byte as int value in binary Returns: True if input indicates a meta event, False if otherwise. """ def is_meta(n): dec_val = int(n, 2) if dec_val == 255: return True else: return False
#!/usr/bin/env python """version of the sdk """ __version__ = "1.0.0"
"""version of the sdk """ __version__ = '1.0.0'
success = { "uuid": "8bf7e570-67cd-4670-a37c-0999fd07f9bf", "action": "EventsRouter", "result": { "success": True }, "tid": 1, "type": "rpc", "method": "detail" } fail = { "uuid": "8bf7e570-67cd-4670-a37c-0999fd07f9bf", "action": "EventsRouter", "result": { "msg": "ServiceResponseError: Not Found", "type": "exception", "success": False }, "tid": 1, "type": "rpc", "method": "detail" } events_query = { "uuid": "eadafce3-12ba-44ed-b1aa-e6ffdf6e98c6", "action": "EventsRouter", "result": { "totalCount": 50, "events": [ { "prodState": "Production", "firstTime": 1505865565.822, "facility": None, "eventClassKey": "csm.sessionFailed", "agent": "zenpython", "dedupid": "test.example.com|test-01|/Status|ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlugin|60|3", "Location": [ { "uid": "/zport/dmd/Locations/Moon Base Alpha", "name": "/Moon Base Alpha" } ], "ownerid": "zenoss", "eventClass": { "text": "/Status", "uid": "/zport/dmd/Events/Status" }, "id": "02420a11-0015-98b9-11e7-9d96ae351999", "DevicePriority": "Normal", "monitor": "localhost", "priority": None, "details": { "node": [ "test-01" ], "recvtime": [ "1508797427" ], "zenoss.device.location": [ "/Moon Base Alpha" ], "zenoss.device.priority": [ "3" ], "zenoss.device.device_class": [ "/Storage/NetApp/C-Mode" ], "seq-num": [ "647604" ], "source": [ "CsmMpAgentThread" ], "manager": [ "13a1a22ff067" ], "message-name": [ "csm.sessionFailed" ], "resolution": [ "If you can reach the storage failover (SFO) partner of the target appliance, initiate a storage failover (takeover) of any aggregates on the target appliance. Then perform a 'sendhome' operation on these aggregates after the target appliance is operational again. Examine the network between the initiating appliance and the target appliance for problems. " ], "eventClassMapping": [ "/Status/failureNoFrames" ], "time": [ "1508797427" ], "zenoss.device.production_state": [ "1000" ], "zenoss.device.ip_address": [ "1.2.3.4" ], "event": [ "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. " ] }, "DeviceClass": [ { "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode", "name": "/Storage/NetApp/C-Mode" } ], "eventKey": "ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlug", "evid": "02420a11-0015-98b9-11e7-9d96ae351999", "eventClassMapping": { "uuid": "1337d66f-d5fa-4c3b-8198-bcfedf83d040", "name": "failureNoFrames" }, "component": { "url": "/zport/dmd/goto?guid=08c40deb-1009-4634-a529-d66631391733", "text": "test-01", "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode/devices/test.example.com/systemnodes/test-01", "uuid": "08c40deb-1009-4634-a529-d66631391733" }, "clearid": None, "DeviceGroups": [], "eventGroup": None, "device": { "url": "/zport/dmd/goto?guid=02e21618-b30a-47bf-8591-471c70570932", "text": "test.example.com", "uuid": "02e21618-b30a-47bf-8591-471c70570932", "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode/devices/test.example.com" }, "message": "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. \nResolution: If you can reach the storage failover (SFO) partner of the target appliance, initiate a storage failover (takeover) of any aggregates on the target appliance. Then perform a 'sendhome' operation on these aggregates after the target appliance is operational again. Examine the network between the initiating appliance and the target appliance for problems. ", "severity": 3, "count": 66, "stateChange": 1507054918.83, "ntevid": None, "summary": "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. ", "eventState": "Acknowledged", "lastTime": 1508797479.194, "ipAddress": [ "1.2.3.4" ], "Systems": [] } ], "success": True, "asof": 1508797504.409547 }, "tid": 1, "type": "rpc", "method": "query" } events_query_evid = { "uuid": "eadafce3-12ba-44ed-b1aa-e6ffdf6e98c6", "action": "EventsRouter", "result": { "totalCount": 50, "events": [ { "evid": "02420a11-0015-98b9-11e7-9d96ae351999" } ], "success": True, "asof": 1508797504.409547 }, "tid": 1, "type": "rpc", "method": "query" } event_detail = { "uuid": "23f0bbd9-b6a3-46bb-909f-aa53891dfbf5", "action": "EventsRouter", "result": { "event": [ { "prodState": "Production", "firstTime": 1505865565.822, "device_uuid": "02e21618-b30a-47bf-8591-471c70570932", "eventClassKey": "smc.snapmir.unexpected.err", "agent": "zenpython", "dedupid": "test.example.com|test-01|/Status|ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlugin|60|3", "Location": [ { "uid": "/zport/dmd/Locations/Moon Base Alpha", "name": "/Moon Base Alpha" } ], "component_url": "/zport/dmd/goto?guid=08c40deb-1009-4634-a529-d66631391733", "ownerid": "zenoss", "eventClassMapping_url": "/zport/dmd/goto?guid=1337d66f-d5fa-4c3b-8198-bcfedf83d040", "eventClass": "/Status", "id": "02420a11-0015-98b9-11e7-9d96ae351999", "device_title": "test.example.com", "DevicePriority": "Normal", "log": [ [ "zenoss", 1507054918830, "state changed to Acknowledged" ] ], "facility": None, "eventClass_url": "/zport/dmd/Events/Status", "monitor": "localhost", "priority": None, "device_url": "/zport/dmd/goto?guid=02e21618-b30a-47bf-8591-471c70570932", "details": [ { "key": "event", "value": "smc.snapmir.unexpected.err: SnapMirror unexpected error 'Destination volume \"cg_name_wildcard\" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))'. Relationship UUID ' '. " }, { "key": "eventClassMapping", "value": "/Status/failureNoFrames" }, { "key": "manager", "value": "13a1a22ff067" }, { "key": "message-name", "value": "smc.snapmir.unexpected.err" }, { "key": "node", "value": "test-01" }, { "key": "recvtime", "value": "1508798161" }, { "key": "resolution", "value": "If the problem persists, contact NetApp technical support. " }, { "key": "seq-num", "value": "647654" }, { "key": "source", "value": "sm_logger_main" }, { "key": "time", "value": "1508798161" }, { "key": "zenoss.device.device_class", "value": "/Storage/NetApp/C-Mode" }, { "key": "zenoss.device.ip_address", "value": "1.2.3.4" }, { "key": "zenoss.device.location", "value": "/Moon Base Alpha" }, { "key": "zenoss.device.priority", "value": "3" }, { "key": "zenoss.device.production_state", "value": "1000" } ], "DeviceClass": [ { "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode", "name": "/Storage/NetApp/C-Mode" } ], "eventKey": "ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlug", "evid": "02420a11-0015-98b9-11e7-9d96ae351999", "eventClassMapping": "failureNoFrames", "component": "test-01", "clearid": None, "DeviceGroups": [], "eventGroup": None, "device": "test.example.com", "Systems": [], "component_title": "test-01", "severity": 3, "count": 66, "stateChange": 1507054918.83, "ntevid": None, "summary": "smc.snapmir.unexpected.err: SnapMirror unexpected error 'Destination volume \"cg_name_wildcard\" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))'. Relationship UUID ' '. ", "message": "smc.snapmir.unexpected.err: SnapMirror unexpected error 'Destination volume \"cg_name_wildcard\" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))'. Relationship UUID ' '. \nResolution: If the problem persists, contact NetApp technical support. ", "eventState": "Acknowledged", "lastTime": 1508798199.186, "ipAddress": [ "1.2.3.4" ], "component_uuid": "08c40deb-1009-4634-a529-d66631391733" } ], "success": True }, "tid": 1, "type": "rpc", "method": "detail" } events_config = { "uuid": "7f7109f2-1a6f-41f5-a12f-bbd95f280b9c", "action": "EventsRouter", "result": { "data": [ { "xtype": "eventageseverity", "defaultValue": 4, "id": "event_age_disable_severity", "value": 4, "name": "Don't Age This Severity and Above" }, { "defaultValue": False, "id": "event_age_severity_inclusive", "value": False, "xtype": "hidden" } ], "success": True }, "tid": 1, "type": "rpc", "method": "getConfig" } add_event_evid_query = { "uuid": "6700ab59-c559-42ec-959b-ebc33bc52257", "action": "EventsRouter", "result": { "totalCount": 1, "events": [ { "evid": "02420a11-000c-a561-11e7-ba9b510182b3", } ], "success": True, "asof": 1509056503.945677 }, "tid": 1, "type": "rpc", "method": "query" } add_event_detail = { "uuid": "c54074e8-af8b-4e40-a679-7dbe314709ed", "action": "EventsRouter", "result": { "event": [ { "prodState": None, "firstTime": 1509056189.91, "device_uuid": None, "eventClassKey": None, "agent": None, "dedupid": "Heart of Gold|Arthur Dent|/Status|3|Out of Tea", "Location": [], "component_url": None, "ownerid": None, "eventClassMapping_url": None, "eventClass": "/Status", "id": "02420a11-000c-a561-11e7-ba9b510182b3", "device_title": "Heart of Gold", "DevicePriority": None, "log": [ [ "zenoss", 1509057815980, "<p>Test log entry</p>" ] ], "facility": None, "eventClass_url": "/zport/dmd/Events/Status", "monitor": None, "priority": None, "device_url": None, "details": [], "DeviceClass": [], "eventKey": "", "evid": "02420a11-000c-a561-11e7-ba9b510182b3", "eventClassMapping": None, "component": "Arthur Dent", "clearid": None, "DeviceGroups": [], "eventGroup": None, "device": "Heart of Gold", "Systems": [], "component_title": "Arthur Dent", "severity": 3, "count": 1, "stateChange": 1509056189.91, "ntevid": None, "summary": "Out of Tea", "message": "Out of Tea", "eventState": "New", "lastTime": 1509056189.91, "ipAddress": "", "component_uuid": None } ], "success": True }, "tid": 1, "type": "rpc", "method": "detail" }
success = {'uuid': '8bf7e570-67cd-4670-a37c-0999fd07f9bf', 'action': 'EventsRouter', 'result': {'success': True}, 'tid': 1, 'type': 'rpc', 'method': 'detail'} fail = {'uuid': '8bf7e570-67cd-4670-a37c-0999fd07f9bf', 'action': 'EventsRouter', 'result': {'msg': 'ServiceResponseError: Not Found', 'type': 'exception', 'success': False}, 'tid': 1, 'type': 'rpc', 'method': 'detail'} events_query = {'uuid': 'eadafce3-12ba-44ed-b1aa-e6ffdf6e98c6', 'action': 'EventsRouter', 'result': {'totalCount': 50, 'events': [{'prodState': 'Production', 'firstTime': 1505865565.822, 'facility': None, 'eventClassKey': 'csm.sessionFailed', 'agent': 'zenpython', 'dedupid': 'test.example.com|test-01|/Status|ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlugin|60|3', 'Location': [{'uid': '/zport/dmd/Locations/Moon Base Alpha', 'name': '/Moon Base Alpha'}], 'ownerid': 'zenoss', 'eventClass': {'text': '/Status', 'uid': '/zport/dmd/Events/Status'}, 'id': '02420a11-0015-98b9-11e7-9d96ae351999', 'DevicePriority': 'Normal', 'monitor': 'localhost', 'priority': None, 'details': {'node': ['test-01'], 'recvtime': ['1508797427'], 'zenoss.device.location': ['/Moon Base Alpha'], 'zenoss.device.priority': ['3'], 'zenoss.device.device_class': ['/Storage/NetApp/C-Mode'], 'seq-num': ['647604'], 'source': ['CsmMpAgentThread'], 'manager': ['13a1a22ff067'], 'message-name': ['csm.sessionFailed'], 'resolution': ["If you can reach the storage failover (SFO) partner of the target appliance, initiate a storage failover (takeover) of any aggregates on the target appliance. Then perform a 'sendhome' operation on these aggregates after the target appliance is operational again. Examine the network between the initiating appliance and the target appliance for problems. "], 'eventClassMapping': ['/Status/failureNoFrames'], 'time': ['1508797427'], 'zenoss.device.production_state': ['1000'], 'zenoss.device.ip_address': ['1.2.3.4'], 'event': ['csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. ']}, 'DeviceClass': [{'uid': '/zport/dmd/Devices/Storage/NetApp/C-Mode', 'name': '/Storage/NetApp/C-Mode'}], 'eventKey': 'ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlug', 'evid': '02420a11-0015-98b9-11e7-9d96ae351999', 'eventClassMapping': {'uuid': '1337d66f-d5fa-4c3b-8198-bcfedf83d040', 'name': 'failureNoFrames'}, 'component': {'url': '/zport/dmd/goto?guid=08c40deb-1009-4634-a529-d66631391733', 'text': 'test-01', 'uid': '/zport/dmd/Devices/Storage/NetApp/C-Mode/devices/test.example.com/systemnodes/test-01', 'uuid': '08c40deb-1009-4634-a529-d66631391733'}, 'clearid': None, 'DeviceGroups': [], 'eventGroup': None, 'device': {'url': '/zport/dmd/goto?guid=02e21618-b30a-47bf-8591-471c70570932', 'text': 'test.example.com', 'uuid': '02e21618-b30a-47bf-8591-471c70570932', 'uid': '/zport/dmd/Devices/Storage/NetApp/C-Mode/devices/test.example.com'}, 'message': "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. \nResolution: If you can reach the storage failover (SFO) partner of the target appliance, initiate a storage failover (takeover) of any aggregates on the target appliance. Then perform a 'sendhome' operation on these aggregates after the target appliance is operational again. Examine the network between the initiating appliance and the target appliance for problems. ", 'severity': 3, 'count': 66, 'stateChange': 1507054918.83, 'ntevid': None, 'summary': 'csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. ', 'eventState': 'Acknowledged', 'lastTime': 1508797479.194, 'ipAddress': ['1.2.3.4'], 'Systems': []}], 'success': True, 'asof': 1508797504.409547}, 'tid': 1, 'type': 'rpc', 'method': 'query'} events_query_evid = {'uuid': 'eadafce3-12ba-44ed-b1aa-e6ffdf6e98c6', 'action': 'EventsRouter', 'result': {'totalCount': 50, 'events': [{'evid': '02420a11-0015-98b9-11e7-9d96ae351999'}], 'success': True, 'asof': 1508797504.409547}, 'tid': 1, 'type': 'rpc', 'method': 'query'} event_detail = {'uuid': '23f0bbd9-b6a3-46bb-909f-aa53891dfbf5', 'action': 'EventsRouter', 'result': {'event': [{'prodState': 'Production', 'firstTime': 1505865565.822, 'device_uuid': '02e21618-b30a-47bf-8591-471c70570932', 'eventClassKey': 'smc.snapmir.unexpected.err', 'agent': 'zenpython', 'dedupid': 'test.example.com|test-01|/Status|ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlugin|60|3', 'Location': [{'uid': '/zport/dmd/Locations/Moon Base Alpha', 'name': '/Moon Base Alpha'}], 'component_url': '/zport/dmd/goto?guid=08c40deb-1009-4634-a529-d66631391733', 'ownerid': 'zenoss', 'eventClassMapping_url': '/zport/dmd/goto?guid=1337d66f-d5fa-4c3b-8198-bcfedf83d040', 'eventClass': '/Status', 'id': '02420a11-0015-98b9-11e7-9d96ae351999', 'device_title': 'test.example.com', 'DevicePriority': 'Normal', 'log': [['zenoss', 1507054918830, 'state changed to Acknowledged']], 'facility': None, 'eventClass_url': '/zport/dmd/Events/Status', 'monitor': 'localhost', 'priority': None, 'device_url': '/zport/dmd/goto?guid=02e21618-b30a-47bf-8591-471c70570932', 'details': [{'key': 'event', 'value': 'smc.snapmir.unexpected.err: SnapMirror unexpected error \'Destination volume "cg_name_wildcard" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))\'. Relationship UUID \' \'. '}, {'key': 'eventClassMapping', 'value': '/Status/failureNoFrames'}, {'key': 'manager', 'value': '13a1a22ff067'}, {'key': 'message-name', 'value': 'smc.snapmir.unexpected.err'}, {'key': 'node', 'value': 'test-01'}, {'key': 'recvtime', 'value': '1508798161'}, {'key': 'resolution', 'value': 'If the problem persists, contact NetApp technical support. '}, {'key': 'seq-num', 'value': '647654'}, {'key': 'source', 'value': 'sm_logger_main'}, {'key': 'time', 'value': '1508798161'}, {'key': 'zenoss.device.device_class', 'value': '/Storage/NetApp/C-Mode'}, {'key': 'zenoss.device.ip_address', 'value': '1.2.3.4'}, {'key': 'zenoss.device.location', 'value': '/Moon Base Alpha'}, {'key': 'zenoss.device.priority', 'value': '3'}, {'key': 'zenoss.device.production_state', 'value': '1000'}], 'DeviceClass': [{'uid': '/zport/dmd/Devices/Storage/NetApp/C-Mode', 'name': '/Storage/NetApp/C-Mode'}], 'eventKey': 'ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlug', 'evid': '02420a11-0015-98b9-11e7-9d96ae351999', 'eventClassMapping': 'failureNoFrames', 'component': 'test-01', 'clearid': None, 'DeviceGroups': [], 'eventGroup': None, 'device': 'test.example.com', 'Systems': [], 'component_title': 'test-01', 'severity': 3, 'count': 66, 'stateChange': 1507054918.83, 'ntevid': None, 'summary': 'smc.snapmir.unexpected.err: SnapMirror unexpected error \'Destination volume "cg_name_wildcard" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))\'. Relationship UUID \' \'. ', 'message': 'smc.snapmir.unexpected.err: SnapMirror unexpected error \'Destination volume "cg_name_wildcard" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))\'. Relationship UUID \' \'. \nResolution: If the problem persists, contact NetApp technical support. ', 'eventState': 'Acknowledged', 'lastTime': 1508798199.186, 'ipAddress': ['1.2.3.4'], 'component_uuid': '08c40deb-1009-4634-a529-d66631391733'}], 'success': True}, 'tid': 1, 'type': 'rpc', 'method': 'detail'} events_config = {'uuid': '7f7109f2-1a6f-41f5-a12f-bbd95f280b9c', 'action': 'EventsRouter', 'result': {'data': [{'xtype': 'eventageseverity', 'defaultValue': 4, 'id': 'event_age_disable_severity', 'value': 4, 'name': "Don't Age This Severity and Above"}, {'defaultValue': False, 'id': 'event_age_severity_inclusive', 'value': False, 'xtype': 'hidden'}], 'success': True}, 'tid': 1, 'type': 'rpc', 'method': 'getConfig'} add_event_evid_query = {'uuid': '6700ab59-c559-42ec-959b-ebc33bc52257', 'action': 'EventsRouter', 'result': {'totalCount': 1, 'events': [{'evid': '02420a11-000c-a561-11e7-ba9b510182b3'}], 'success': True, 'asof': 1509056503.945677}, 'tid': 1, 'type': 'rpc', 'method': 'query'} add_event_detail = {'uuid': 'c54074e8-af8b-4e40-a679-7dbe314709ed', 'action': 'EventsRouter', 'result': {'event': [{'prodState': None, 'firstTime': 1509056189.91, 'device_uuid': None, 'eventClassKey': None, 'agent': None, 'dedupid': 'Heart of Gold|Arthur Dent|/Status|3|Out of Tea', 'Location': [], 'component_url': None, 'ownerid': None, 'eventClassMapping_url': None, 'eventClass': '/Status', 'id': '02420a11-000c-a561-11e7-ba9b510182b3', 'device_title': 'Heart of Gold', 'DevicePriority': None, 'log': [['zenoss', 1509057815980, '<p>Test log entry</p>']], 'facility': None, 'eventClass_url': '/zport/dmd/Events/Status', 'monitor': None, 'priority': None, 'device_url': None, 'details': [], 'DeviceClass': [], 'eventKey': '', 'evid': '02420a11-000c-a561-11e7-ba9b510182b3', 'eventClassMapping': None, 'component': 'Arthur Dent', 'clearid': None, 'DeviceGroups': [], 'eventGroup': None, 'device': 'Heart of Gold', 'Systems': [], 'component_title': 'Arthur Dent', 'severity': 3, 'count': 1, 'stateChange': 1509056189.91, 'ntevid': None, 'summary': 'Out of Tea', 'message': 'Out of Tea', 'eventState': 'New', 'lastTime': 1509056189.91, 'ipAddress': '', 'component_uuid': None}], 'success': True}, 'tid': 1, 'type': 'rpc', 'method': 'detail'}
settings = { # add provider-specific survey settings here # e.g. how to abbreviate questions }
settings = {}
# coding: utf-8 s = "The string ends in escape: " s += chr(27) # add an escape character at the end of $str print(repr(s))
s = 'The string ends in escape: ' s += chr(27) print(repr(s))
SERVICE_NAME = "org.bluez" AGENT_IFACE = SERVICE_NAME + '.Agent1' ADAPTER_IFACE = SERVICE_NAME + ".Adapter1" DEVICE_IFACE = SERVICE_NAME + ".Device1" PLAYER_IFACE = SERVICE_NAME + '.MediaPlayer1' TRANSPORT_IFACE = SERVICE_NAME + '.MediaTransport1' OBJECT_IFACE = "org.freedesktop.DBus.ObjectManager" PROPERTIES_IFACE = "org.freedesktop.DBus.Properties" INTROSPECT_IFACE = "org.freedesktop.DBus.Introspectable"
service_name = 'org.bluez' agent_iface = SERVICE_NAME + '.Agent1' adapter_iface = SERVICE_NAME + '.Adapter1' device_iface = SERVICE_NAME + '.Device1' player_iface = SERVICE_NAME + '.MediaPlayer1' transport_iface = SERVICE_NAME + '.MediaTransport1' object_iface = 'org.freedesktop.DBus.ObjectManager' properties_iface = 'org.freedesktop.DBus.Properties' introspect_iface = 'org.freedesktop.DBus.Introspectable'
class Cliente: def __init__(self, nome): self.__nome = nome @property def nome(self): return self.__nome.title() def get_nome(self): print('[INFO] Getting value...') print('[INFO] Name "{}" getted sucessfully'.format(self.__nome)) return self.__nome.title() @nome.setter def nome(self, value): print('[INFO] Setting new value...') self.__nome = value print('[INFO] New value: {}'.format(value)) if __name__ == '__main__': cliente = Cliente('thiago') cliente.nome cliente.nome = 'Thiago Kasper'
class Cliente: def __init__(self, nome): self.__nome = nome @property def nome(self): return self.__nome.title() def get_nome(self): print('[INFO] Getting value...') print('[INFO] Name "{}" getted sucessfully'.format(self.__nome)) return self.__nome.title() @nome.setter def nome(self, value): print('[INFO] Setting new value...') self.__nome = value print('[INFO] New value: {}'.format(value)) if __name__ == '__main__': cliente = cliente('thiago') cliente.nome cliente.nome = 'Thiago Kasper'
class ChartModel: def score_keywords(self, dep_keywords): #mock (@todo: update after integrating training a model) keyword_scores = [] for kw in dep_keywords: keyword_scores.append({ 'keyword': kw, 'score': 0.7 }) return keyword_scores
class Chartmodel: def score_keywords(self, dep_keywords): keyword_scores = [] for kw in dep_keywords: keyword_scores.append({'keyword': kw, 'score': 0.7}) return keyword_scores
def word_permutation(s): return word_permutation_helper(list(s)) def word_permutation_helper(input_list): if len(input_list) ==0: return '' ret = [] for i in range(len(input_list)): base = input_list[i] remainder = input_list[:i]+input_list[i+1:] out = word_permutation_helper(remainder) if isinstance(out,list): ret.extend([out[i]+base for i in range(len(out))]) continue else: out+=base ret.append(out) return ret
def word_permutation(s): return word_permutation_helper(list(s)) def word_permutation_helper(input_list): if len(input_list) == 0: return '' ret = [] for i in range(len(input_list)): base = input_list[i] remainder = input_list[:i] + input_list[i + 1:] out = word_permutation_helper(remainder) if isinstance(out, list): ret.extend([out[i] + base for i in range(len(out))]) continue else: out += base ret.append(out) return ret
def solution(participant, completion): answer = "" temp = 0 dic = {} for p in participant: dic[hash(p)] = p temp += hash(p) for c in completion: temp -= hash(c) return dic[temp]
def solution(participant, completion): answer = '' temp = 0 dic = {} for p in participant: dic[hash(p)] = p temp += hash(p) for c in completion: temp -= hash(c) return dic[temp]
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: mat = [[0] * n for _ in range(n)] left, top, right, bottom = 0, 0, n, n val = 1 while left < right and top < bottom: for i in range(left, right): mat[top][i] = val val += 1 top += 1 for i in range(top, bottom): mat[i][right - 1] = val val += 1 right -= 1 for i in range(right - 1, left - 1, -1): mat[bottom - 1][i] = val val += 1 bottom -= 1 for i in range(bottom - 1, top - 1, -1): mat[i][left] = val val += 1 left += 1 return mat
class Solution: def generate_matrix(self, n: int) -> List[List[int]]: mat = [[0] * n for _ in range(n)] (left, top, right, bottom) = (0, 0, n, n) val = 1 while left < right and top < bottom: for i in range(left, right): mat[top][i] = val val += 1 top += 1 for i in range(top, bottom): mat[i][right - 1] = val val += 1 right -= 1 for i in range(right - 1, left - 1, -1): mat[bottom - 1][i] = val val += 1 bottom -= 1 for i in range(bottom - 1, top - 1, -1): mat[i][left] = val val += 1 left += 1 return mat
# DROP TABLES songplay_table_drop = "DROP TABLE songplays" user_table_drop = "DROP TABLE users" song_table_drop = "DROP TABLE songs" artist_table_drop = "DROP TABLE artists" time_table_drop = "DROP TABLE time" # CREATE TABLES songplay_table_create = (""" CREATE TABLE IF NOT EXISTS songplays ( songplay_id SERIAL PRIMARY KEY, start_time timestamp NOT NULL REFERENCES time(start_time), user_id int NOT NULL REFERENCES users(user_id), level varchar, song_id varchar, artist_id varchar, session_id int, location varchar, user_agent varchar ); """) user_table_create = (""" CREATE TABLE IF NOT EXISTS users ( user_id int PRIMARY KEY, first_name varchar NOT NULL, last_name varchar NOT NULL, gender varchar, level varchar ); """) song_table_create = (""" CREATE TABLE IF NOT EXISTS songs ( song_id varchar PRIMARY KEY, title varchar NOT NULL, artist_id varchar NOT NULL REFERENCES artists(artist_id), year int, duration numeric(10,5) ); """) artist_table_create = (""" CREATE TABLE IF NOT EXISTS artists ( artist_id varchar PRIMARY KEY, name varchar NOT NULL, location varchar, latitude numeric, longitude numeric ); """) time_table_create = (""" CREATE TABLE IF NOT EXISTS time ( start_time timestamp PRIMARY KEY, hour int, day int, week int, month int, year int, weekday int ); """) # INSERT RECORDS songplay_table_insert = (""" INSERT INTO songplays(songplay_id,start_time,user_id,level,song_id,artist_id,session_id,location,user_agent) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT (songplay_id) DO NOTHING; """) user_table_insert = (""" INSERT INTO users(user_id,first_name,last_name,gender,level) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (user_id) DO UPDATE SET level=EXCLUDED.level; """) song_table_insert = (""" INSERT INTO songs(song_id,title,artist_id,year,duration) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (song_id) DO NOTHING; """) artist_table_insert = (""" INSERT INTO artists(artist_id,name,location,latitude,longitude) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (artist_id) DO NOTHING; """) time_table_insert = (""" INSERT INTO time(start_time,hour,day,week,month,year,weekday) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT (start_time) DO NOTHING; """) # FIND SONGS song_select = (""" SELECT song_id, artists.artist_id FROM songs JOIN artists ON songs.artist_id = artists.artist_id WHERE songs.title = %s AND artists.name = %s AND songs.duration = %s """) # QUERY LISTS create_table_queries = [time_table_create, artist_table_create, user_table_create, songplay_table_create, song_table_create, ] drop_table_queries = [songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
songplay_table_drop = 'DROP TABLE songplays' user_table_drop = 'DROP TABLE users' song_table_drop = 'DROP TABLE songs' artist_table_drop = 'DROP TABLE artists' time_table_drop = 'DROP TABLE time' songplay_table_create = '\nCREATE TABLE IF NOT EXISTS songplays (\n songplay_id SERIAL PRIMARY KEY, \n start_time timestamp NOT NULL REFERENCES time(start_time), \n user_id int NOT NULL REFERENCES users(user_id), \n level varchar, \n song_id varchar, \n artist_id varchar, \n session_id int, \n location varchar, \n user_agent varchar\n );\n' user_table_create = '\nCREATE TABLE IF NOT EXISTS users (\n user_id int PRIMARY KEY, \n first_name varchar NOT NULL, \n last_name varchar NOT NULL, \n gender varchar, \n level varchar\n );\n' song_table_create = '\nCREATE TABLE IF NOT EXISTS songs (\n song_id varchar PRIMARY KEY, \n title varchar NOT NULL, \n artist_id varchar NOT NULL REFERENCES artists(artist_id), \n year int, \n duration numeric(10,5)\n );\n' artist_table_create = '\nCREATE TABLE IF NOT EXISTS artists (\n artist_id varchar PRIMARY KEY, \n name varchar NOT NULL, \n location varchar, \n latitude numeric, \n longitude numeric\n );\n' time_table_create = '\nCREATE TABLE IF NOT EXISTS time (\n start_time timestamp PRIMARY KEY, \n hour int, \n day int, \n week int, \n month int, \n year int, \n weekday int\n );\n' songplay_table_insert = '\nINSERT INTO songplays(songplay_id,start_time,user_id,level,song_id,artist_id,session_id,location,user_agent)\nVALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)\nON CONFLICT (songplay_id) DO NOTHING;\n' user_table_insert = '\nINSERT INTO users(user_id,first_name,last_name,gender,level)\nVALUES (%s, %s, %s, %s, %s)\nON CONFLICT (user_id) DO UPDATE SET level=EXCLUDED.level;\n' song_table_insert = '\nINSERT INTO songs(song_id,title,artist_id,year,duration) \nVALUES (%s, %s, %s, %s, %s)\nON CONFLICT (song_id) DO NOTHING;\n' artist_table_insert = '\nINSERT INTO artists(artist_id,name,location,latitude,longitude)\nVALUES (%s, %s, %s, %s, %s)\nON CONFLICT (artist_id) DO NOTHING;\n' time_table_insert = '\nINSERT INTO time(start_time,hour,day,week,month,year,weekday) \nVALUES (%s, %s, %s, %s, %s, %s, %s)\nON CONFLICT (start_time) DO NOTHING;\n' song_select = '\nSELECT song_id, artists.artist_id\n FROM songs JOIN artists ON songs.artist_id = artists.artist_id\n WHERE songs.title = %s\n AND artists.name = %s\n AND songs.duration = %s\n' create_table_queries = [time_table_create, artist_table_create, user_table_create, songplay_table_create, song_table_create] drop_table_queries = [songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
class Solution(object): def findCircleNum(self, M): def dfs(node): visited.add(node) for person, is_friend in enumerate(M[node]): if is_friend and person not in visited: dfs(person) circle = 0 visited = set() for node in range(len(M)): if node not in visited: circle += 1 dfs(node) return circle
class Solution(object): def find_circle_num(self, M): def dfs(node): visited.add(node) for (person, is_friend) in enumerate(M[node]): if is_friend and person not in visited: dfs(person) circle = 0 visited = set() for node in range(len(M)): if node not in visited: circle += 1 dfs(node) return circle
a = [1,5,4,6,8,11,3,12] even = list(filter(lambda x: (x%2 == 0), a)) print(even) third = list(filter(lambda x: (x%3 == 0), a)) print(third) b = [[0,1,8],[7,2,2],[5,3,10],[1,4,5]] b.sort(key = lambda x: x[2]) print(b) b.sort(key = lambda x: x[0]+x[1]) print(b)
a = [1, 5, 4, 6, 8, 11, 3, 12] even = list(filter(lambda x: x % 2 == 0, a)) print(even) third = list(filter(lambda x: x % 3 == 0, a)) print(third) b = [[0, 1, 8], [7, 2, 2], [5, 3, 10], [1, 4, 5]] b.sort(key=lambda x: x[2]) print(b) b.sort(key=lambda x: x[0] + x[1]) print(b)
# -*- coding: utf-8 -*- """ Created on Wed Feb 5 11:02:42 2020 @author: Arthur """
""" Created on Wed Feb 5 11:02:42 2020 @author: Arthur """
def word(str): j=len(str)-1 for i in range(int(len(str)/2)): if str[i]!=str[j]: return False j=j-1 return True str=input("Enter the string :") ans=word(str) if(ans): print("string is palindrome") else: print("string is not palindrome")
def word(str): j = len(str) - 1 for i in range(int(len(str) / 2)): if str[i] != str[j]: return False j = j - 1 return True str = input('Enter the string :') ans = word(str) if ans: print('string is palindrome') else: print('string is not palindrome')
class RowMenuItem: def __init__(self, widget): # Item can have an optional id self.id = None # Item may specify a parent id (for rendering purposes, like display = 'with-parent,' perhaps) self.parent_id = None # If another item chooses to display with this item, then that other item (the with-parent item) # becomes a "friend" of this item (sharing focus and blur events) self.friend_ids = [] # The widget container within this RowMenuItem self.item = widget # I typically track visibility within the lowest level widgets (<label />, etc.). # For RowMenuItems, though, I'll permit this wrapper to also have a "visibility" setting, # separate from the standard "display" attribute of low-level widgets. self.visibility = "visible" # An item may be entirely hidden from view (no height, no rendering, nothing) # Primarily used for static dialogue panels, etc., to serve as a "hidden input" field # (i.e. key listener) self.hidden = False # An item might not be selectable by the user self.disabled = False # Perhaps the single item (within a group) has an individual border? self.individual_border = False # Shrinkwrap to rnder only necessary border width? self.shrinkwrap = False # Perhaps we'll render a glowing highlight behind the text of the active selection? self.glow = False # Occasionally we'll hard-code the height for a given item self.explicit_height = None # Sometimes a row menu item will have a tooltip (which is basically a simple GridMenuCell) self.tooltip = None # A RowMenuItem may have other special properties if they begin with a - self.additional_properties = {} def configure(self, options): if ( "id" in options ): self.id = options["id"] if ( "parent-id" in options ): self.parent_id = options["parent-id"] if ( "visibility" in options ): self.visibility = options["visibility"] if ( "hidden" in options ): self.hidden = options["hidden"] if ( "disabled" in options ): self.disabled = int( options["disabled"] ) if ( "individual-border" in options ): self.individual_border = int( options["individual-border"] ) if ( "shrinkwrap" in options ): self.shrinkwrap = int( options["shrinkwrap"] ) if ( "glow" in options ): self.glow = int( options["glow"] ) if ( "explicit-height" in options ): self.explicit_height = int( options["explicit-height"] ) # Check for special additional properties for key in options: # Must start with a - if ( key.startswith("-") ): # Save it self.additional_properties[key] = options[key] #print "..." #print options #print self.additional_properties #print 5/0 # For chaining return self # Get a special property def get_property(self, key): # Validate if (key in self.additional_properties): return self.additional_properties[key] else: return None def get_widget_container(self): return self.item # Event callbacks def while_awake(self): # Forward message self.get_widget().while_awake() def while_asleep(self): # Forward message self.get_widget().while_asleep() def on_blur(self): # Forward message self.get_widget().on_blur() def get_widget(self): return self.item # used in widget height calculations (e.g. overall RowMenu height) def get_box_height(self, text_renderer): # Hidden items have no height if (self.hidden): return 0 elif (self.explicit_height != None): return (self.explicit_height) else: #print "Advance, check box height for %s" % self.item return (self.item.get_box_height(text_renderer)) # Used to determine render region for backgrounds and the like def get_render_height(self, text_renderer): # Hidden items have no height if (self.hidden): return 0 elif (self.explicit_height != None): return self.explicit_height else: return self.item.get_render_height(text_renderer) def get_min_x(self, text_renderer): return self.item.get_min_x(text_renderer) def add_tooltip(self):#, width, align, delay, lifespan, margin_x = 20, margin_y = 0): self.tooltip = RowMenuTooltip()#RowMenuItemTooltip(width, align, delay = delay, lifespan = lifespan, margin_x = margin_x, margin_y = margin_y) return self.tooltip
class Rowmenuitem: def __init__(self, widget): self.id = None self.parent_id = None self.friend_ids = [] self.item = widget self.visibility = 'visible' self.hidden = False self.disabled = False self.individual_border = False self.shrinkwrap = False self.glow = False self.explicit_height = None self.tooltip = None self.additional_properties = {} def configure(self, options): if 'id' in options: self.id = options['id'] if 'parent-id' in options: self.parent_id = options['parent-id'] if 'visibility' in options: self.visibility = options['visibility'] if 'hidden' in options: self.hidden = options['hidden'] if 'disabled' in options: self.disabled = int(options['disabled']) if 'individual-border' in options: self.individual_border = int(options['individual-border']) if 'shrinkwrap' in options: self.shrinkwrap = int(options['shrinkwrap']) if 'glow' in options: self.glow = int(options['glow']) if 'explicit-height' in options: self.explicit_height = int(options['explicit-height']) for key in options: if key.startswith('-'): self.additional_properties[key] = options[key] return self def get_property(self, key): if key in self.additional_properties: return self.additional_properties[key] else: return None def get_widget_container(self): return self.item def while_awake(self): self.get_widget().while_awake() def while_asleep(self): self.get_widget().while_asleep() def on_blur(self): self.get_widget().on_blur() def get_widget(self): return self.item def get_box_height(self, text_renderer): if self.hidden: return 0 elif self.explicit_height != None: return self.explicit_height else: return self.item.get_box_height(text_renderer) def get_render_height(self, text_renderer): if self.hidden: return 0 elif self.explicit_height != None: return self.explicit_height else: return self.item.get_render_height(text_renderer) def get_min_x(self, text_renderer): return self.item.get_min_x(text_renderer) def add_tooltip(self): self.tooltip = row_menu_tooltip() return self.tooltip
nome = str(input('Digite seu nome completo: ')).strip() print(nome.upper()) print(nome.lower()) print(len(nome))
nome = str(input('Digite seu nome completo: ')).strip() print(nome.upper()) print(nome.lower()) print(len(nome))
#!/usr/bin/env python # encoding=utf-8 def test(): print('utils_gao, making for ml')
def test(): print('utils_gao, making for ml')
class Config(object): """This is the basic configuration class for BorgWeb.""" #: builtin web server configuration HOST = '127.0.0.1' # use 0.0.0.0 to bind to all interfaces PORT = 9087 # ports < 1024 need root DEBUG = True # if True, enable reloader and debugger LOG_FILE = 'prombot.log' # Telegram bot config TELEGRAM_BOT_USERNAME = "dwarferie_bot" TELEGRAM_BOT_TOKEN = "1110478838:AAGZVZaDmjUPffFTIxpgLVIKI5r7yg5h_8g" TELEGRAM_BOT_CHAT_ID = "-489291168"
class Config(object): """This is the basic configuration class for BorgWeb.""" host = '127.0.0.1' port = 9087 debug = True log_file = 'prombot.log' telegram_bot_username = 'dwarferie_bot' telegram_bot_token = '1110478838:AAGZVZaDmjUPffFTIxpgLVIKI5r7yg5h_8g' telegram_bot_chat_id = '-489291168'
def _gen_k8s_file(ctx): odir = ctx.actions.declare_directory("tmp") ctx.actions.run( inputs = [], outputs = [odir], arguments = [], progress_message = "Converting", env = { "CDK8S_OUTDIR": odir.path, }, executable = ctx.executable.tool, tools = [ctx.executable.tool], ) runfiles = ctx.runfiles( files = [odir, ctx.executable._concat], ) ctx.actions.run( inputs = [odir], outputs = [ctx.outputs.out], arguments = [odir.path, ctx.outputs.out.path], executable = ctx.executable._concat, tools = [ctx.executable._concat], ) gen_to_stdout = ctx.actions.declare_file(ctx.label.name + ".gen") ctx.actions.write( output = gen_to_stdout, content = "%s %s" % (ctx.executable._concat.short_path, odir.short_path), is_executable = True, ) # gen_to_file = ctx.actions.declare_file("gen_to_file") # ctx.actions.write( # output = gen_to_file, # content = (base_gen_cmd + "> %s") % (odir.path, ctx.outputs.out.path), # is_executable = True, # ) # ctx.actions.run( # inputs = [odir, gen_to_stdout], # executable = gen_to_file, # outputs = [ctx.outputs.out], # ) return [DefaultInfo( files = depset([ctx.outputs.out]), runfiles = runfiles, executable = gen_to_stdout, )] gen_k8s_file = rule( _gen_k8s_file, attrs = { "tool": attr.label( executable = True, allow_files = True, cfg = "exec", ), "_concat": attr.label( executable = True, allow_single_file = True, cfg = "exec", default = "//rules:concat.sh", ) }, executable = True, outputs = { "out": "%{name}.yaml", }, )
def _gen_k8s_file(ctx): odir = ctx.actions.declare_directory('tmp') ctx.actions.run(inputs=[], outputs=[odir], arguments=[], progress_message='Converting', env={'CDK8S_OUTDIR': odir.path}, executable=ctx.executable.tool, tools=[ctx.executable.tool]) runfiles = ctx.runfiles(files=[odir, ctx.executable._concat]) ctx.actions.run(inputs=[odir], outputs=[ctx.outputs.out], arguments=[odir.path, ctx.outputs.out.path], executable=ctx.executable._concat, tools=[ctx.executable._concat]) gen_to_stdout = ctx.actions.declare_file(ctx.label.name + '.gen') ctx.actions.write(output=gen_to_stdout, content='%s %s' % (ctx.executable._concat.short_path, odir.short_path), is_executable=True) return [default_info(files=depset([ctx.outputs.out]), runfiles=runfiles, executable=gen_to_stdout)] gen_k8s_file = rule(_gen_k8s_file, attrs={'tool': attr.label(executable=True, allow_files=True, cfg='exec'), '_concat': attr.label(executable=True, allow_single_file=True, cfg='exec', default='//rules:concat.sh')}, executable=True, outputs={'out': '%{name}.yaml'})
# # This file contains the Python code from Program 2.9 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm02_09.txt # def geometricSeriesSum(x, n): return (power(x, n + 1) - 1) / (x - 1)
def geometric_series_sum(x, n): return (power(x, n + 1) - 1) / (x - 1)
N, K = map(int, input().split()) a_list = list(map(int, input().split())) sum_list = [] for i in range(N): for j in range(i, N): sum_list.append(sum(a_list[i:j+1])) ans = 0 count = 0 tmp = [] for i in range(40, -1, -1): for s in sum_list: check_num = 1 << i logical_and = check_num & s if logical_and != 0: count += 1 if count >= K: ans += 1 << i tmp = [x for x in sum_list if (1 << i) & x != 0] sum_list = tmp[:] count = 0 print(ans)
(n, k) = map(int, input().split()) a_list = list(map(int, input().split())) sum_list = [] for i in range(N): for j in range(i, N): sum_list.append(sum(a_list[i:j + 1])) ans = 0 count = 0 tmp = [] for i in range(40, -1, -1): for s in sum_list: check_num = 1 << i logical_and = check_num & s if logical_and != 0: count += 1 if count >= K: ans += 1 << i tmp = [x for x in sum_list if 1 << i & x != 0] sum_list = tmp[:] count = 0 print(ans)
# Reads config/config.ini and performs sanity checks class Config(object): config = None def __init__(self, path='config/config.ini'): if not self.config: print("[WARNING] Loading placeholder config") # this has to be replaced by reading the actual .ini config file with open(path, 'r') as cfg: token = cfg.readline().rstrip() initial_channel = cfg.readline().rstrip() default_playlist = cfg.readline().rstrip() Config.config = { 'token': token, 'initial_channel': initial_channel, 'default_playlist': default_playlist } def __getattr__(self, name): return self.config[name] def __setattr__(self, name, value): print("[WARNING] Overriding config value") self.config[name] = value conf = Config()
class Config(object): config = None def __init__(self, path='config/config.ini'): if not self.config: print('[WARNING] Loading placeholder config') with open(path, 'r') as cfg: token = cfg.readline().rstrip() initial_channel = cfg.readline().rstrip() default_playlist = cfg.readline().rstrip() Config.config = {'token': token, 'initial_channel': initial_channel, 'default_playlist': default_playlist} def __getattr__(self, name): return self.config[name] def __setattr__(self, name, value): print('[WARNING] Overriding config value') self.config[name] = value conf = config()
''' Set data type lst = [varname, varname1, varname2] dictionary = { "key": "value", } ''' set = {"Item1", "Item2", "Item3"} print(set) # {'Item1', 'Item2', 'Item3'} # Sets do not care about the order # {'Item2', 'Item3', 'Item1'} # Sets do not care about the order s = {"Item1", "Item2", "Item2", "Item3"} print(s) # {'Item3', 'Item2', 'Item1'} ## Second item2 considered a duplicate s.add("item 4") print(s) #{'Item2', 'Item1', 'item 4', 'Item3'} s.remove("item 4") print(s) # {'Item1', 'Item2', 'Item3'}
""" Set data type lst = [varname, varname1, varname2] dictionary = { "key": "value", } """ set = {'Item1', 'Item2', 'Item3'} print(set) s = {'Item1', 'Item2', 'Item2', 'Item3'} print(s) s.add('item 4') print(s) s.remove('item 4') print(s)
""" gen123.py generate sequences from a base list, repeating each element one more time than the last. """ def gen123(m): #yield None n = 0 for item in m: n += 1 for i in range(n): yield item
""" gen123.py generate sequences from a base list, repeating each element one more time than the last. """ def gen123(m): n = 0 for item in m: n += 1 for i in range(n): yield item
class SlidingAverage: def __init__(self, window_size): self.index = 0 self.values = [0] * window_size def _previous(self): return self.values[(self.index + len(self.values) - 1) % len(self.values)] def update(self, value): self.values[self.index] = self._previous() + value self.index = (self.index + 1) % len(self.values) def get(self): return (self._previous() - self.values[self.index]) / (len(self.values) - 1)
class Slidingaverage: def __init__(self, window_size): self.index = 0 self.values = [0] * window_size def _previous(self): return self.values[(self.index + len(self.values) - 1) % len(self.values)] def update(self, value): self.values[self.index] = self._previous() + value self.index = (self.index + 1) % len(self.values) def get(self): return (self._previous() - self.values[self.index]) / (len(self.values) - 1)
palavras = ('Doidera', 'Calipso', 'Yoda', 'Axt', 'Jovirone', 'Matilda', 'Schwarzenneger', 'Mustefaga', 'Instinct', 'Kobayashi', 'Ludgero', 'Salcicha', 'Scooby', 'Turtle', 'Lily', 'Toast') for palavra in palavras: print(f'Na palavra {palavra.upper()} temos ', end='') for c in range(0, len(palavra)): if palavra[c] in 'AaEeIiOoUu': print(palavra[c].lower(), end=' ') print()
palavras = ('Doidera', 'Calipso', 'Yoda', 'Axt', 'Jovirone', 'Matilda', 'Schwarzenneger', 'Mustefaga', 'Instinct', 'Kobayashi', 'Ludgero', 'Salcicha', 'Scooby', 'Turtle', 'Lily', 'Toast') for palavra in palavras: print(f'Na palavra {palavra.upper()} temos ', end='') for c in range(0, len(palavra)): if palavra[c] in 'AaEeIiOoUu': print(palavra[c].lower(), end=' ') print()
def specificSummator(): counter = 0 for i in range(0, 10000): if (i % 7) == 0: counter += i elif (i % 9) == 0: counter += i return counter print(specificSummator())
def specific_summator(): counter = 0 for i in range(0, 10000): if i % 7 == 0: counter += i elif i % 9 == 0: counter += i return counter print(specific_summator())
# WAP to accept a file from user and print shortest and longest line from that file. def PrintShortestLongestLines(inputFile): line = inputFile.readline() maxLine = line minLine = line while line != "": line = inputFile.readline() if line == "\n" or line == "": continue if len(line) < len(minLine): minLine = line elif len(line) > len(maxLine): maxLine = line return minLine, maxLine def PrintShortestLongestLinesDict(inputFile): line = inputFile.readline() maxline = len(line) minline = len(line) resultDict = dict({ "MinLen": line, "MaxLen": line }) while line != '': line = inputFile.readline() if line == '\n' or line == '': continue if len(line) < minline: resultDict["MinLen"] = line elif len(line) > maxline: resultDict["MaxLen"] = line return resultDict def main(): inputFilePath = input("Please enter a filename to be read: ") fd = open(inputFilePath) if fd != None: # print(PrintShortestLongestLines(fd)) minLenLin, maxLenLine = PrintShortestLongestLines(fd) print("Min Length {}\nMax Length {}".format(minLenLin, maxLenLine)) else: print("File does not exist") if __name__ == "__main__": main()
def print_shortest_longest_lines(inputFile): line = inputFile.readline() max_line = line min_line = line while line != '': line = inputFile.readline() if line == '\n' or line == '': continue if len(line) < len(minLine): min_line = line elif len(line) > len(maxLine): max_line = line return (minLine, maxLine) def print_shortest_longest_lines_dict(inputFile): line = inputFile.readline() maxline = len(line) minline = len(line) result_dict = dict({'MinLen': line, 'MaxLen': line}) while line != '': line = inputFile.readline() if line == '\n' or line == '': continue if len(line) < minline: resultDict['MinLen'] = line elif len(line) > maxline: resultDict['MaxLen'] = line return resultDict def main(): input_file_path = input('Please enter a filename to be read: ') fd = open(inputFilePath) if fd != None: (min_len_lin, max_len_line) = print_shortest_longest_lines(fd) print('Min Length {}\nMax Length {}'.format(minLenLin, maxLenLine)) else: print('File does not exist') if __name__ == '__main__': main()
# Much of the code in this file was ported from ev3dev-lang-python so we # are including the license for ev3dev-lang-python. # ----------------------------------------------------------------------------- # Copyright (c) 2015 Ralph Hempel # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ----------------------------------------------------------------------------- CENTIMETER_MM = 10 DECIMETER_MM = 100 METER_MM = 1000 INCH_MM = 25.4 FOOT_MM = 304.8 YARD_MM = 914.4 STUD_MM = 8 class DistanceValue: """ A base class for ``Distance`` classes. Do not use this directly. Use one of: * :class:`DistanceMillimeters` * :class:`DistanceCentimeters` * :class:`DistanceDecimeters` * :class:`DistanceMeters` * :class:`DistanceInches` * :class:`DistanceFeet` * :class:`DistanceYards` * :class:`DistanceStuds`. """ # This allows us to sort lists of DistanceValue objects def __lt__(self, other): return self.mm < other.mm def __rmul__(self, other): return self.__mul__(other) class DistanceMillimeters(DistanceValue): """ Distance in millimeters Args: millimeters (int): the number of millimeters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceMillimeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 600 millimeters md.run_for_distance(DistanceMillimeters(600), MotorSpeedDPS(100)) """ def __init__(self, millimeters): self.millimeters = millimeters def __str__(self): return str(self.millimeters) + "mm" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceMillimeters(self.millimeters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.millimeters class DistanceCentimeters(DistanceValue): """ Distance in centimeters Args: centimeters (int): the number of centimeters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceCentimeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 60 centimeters md.run_for_distance(DistanceCentimeters(60), MotorSpeedDPS(100)) """ def __init__(self, centimeters): self.centimeters = centimeters def __str__(self): return str(self.centimeters) + "cm" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceCentimeters(self.centimeters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.centimeters * CENTIMETER_MM class DistanceDecimeters(DistanceValue): """ Distance in decimeters Args: decimeters (int): the number of decimeters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceDecimeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 6 decimeters md.run_for_distance(DistanceDecimeters(6), MotorSpeedDPS(100)) """ def __init__(self, decimeters): self.decimeters = decimeters def __str__(self): return str(self.decimeters) + "dm" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceDecimeters(self.decimeters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.decimeters * DECIMETER_MM class DistanceMeters(DistanceValue): """ Distance in meters Args: meters (int): the number of meters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceMeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 2 meters md.run_for_distance(DistanceMeters(2), MotorSpeedDPS(100)) """ def __init__(self, meters): self.meters = meters def __str__(self): return str(self.meters) + "m" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceMeters(self.meters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.meters * METER_MM class DistanceInches(DistanceValue): """ Distance in inches Args: inches (int): the number of inches Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceInches, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 6 inches md.run_for_distance(DistanceInches(6), MotorSpeedDPS(100)) """ def __init__(self, inches): self.inches = inches def __str__(self): return str(self.inches) + "in" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceInches(self.inches * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.inches * INCH_MM class DistanceFeet(DistanceValue): """ Distance in feet Args: feet (int): the number of feet Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceFeet, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 3 feet md.run_for_distance(DistanceFeet(3), MotorSpeedDPS(100)) """ def __init__(self, feet): self.feet = feet def __str__(self): return str(self.feet) + "ft" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceFeet(self.feet * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.feet * FOOT_MM class DistanceYards(DistanceValue): """ Distance in yards Args: yards (int): the number of yards Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceYards, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 2 yards md.run_for_distance(DistanceYards(2), MotorSpeedDPS(100)) """ def __init__(self, yards): self.yards = yards def __str__(self): return str(self.yards) + "yd" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceYards(self.yards * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.yards * YARD_MM class DistanceStuds(DistanceValue): """ Distance in studs Args: studs (int): the number of LEGO studs Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 2 studs md.run_for_distance(DistanceStuds(6), MotorSpeedDPS(100)) """ def __init__(self, studs): self.studs = studs def __str__(self): return str(self.studs) + "stud" def __mul__(self, other): if not isinstance(other, (float, int)): raise TypeError("{} can only be multiplied by an int or float".format(self)) return DistanceStuds(self.studs * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.studs * STUD_MM def distance_in_mm(distance): """ Args: distance (DistanceValue, int): the distance to convert to millimeters Returns: int: ``distance`` converted to millimeters Example: .. code:: python from spikedev.unit import DistanceFeet two_feet_in_mm = distance_in_mm(DistanceFeet(2)) """ if isinstance(distance, DistanceValue): return distance.mm # If distance is not a DistanceValue object, treat it as an int of mm elif isinstance(distance, (float, int)): return distance else: raise TypeError(type(distance))
centimeter_mm = 10 decimeter_mm = 100 meter_mm = 1000 inch_mm = 25.4 foot_mm = 304.8 yard_mm = 914.4 stud_mm = 8 class Distancevalue: """ A base class for ``Distance`` classes. Do not use this directly. Use one of: * :class:`DistanceMillimeters` * :class:`DistanceCentimeters` * :class:`DistanceDecimeters` * :class:`DistanceMeters` * :class:`DistanceInches` * :class:`DistanceFeet` * :class:`DistanceYards` * :class:`DistanceStuds`. """ def __lt__(self, other): return self.mm < other.mm def __rmul__(self, other): return self.__mul__(other) class Distancemillimeters(DistanceValue): """ Distance in millimeters Args: millimeters (int): the number of millimeters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceMillimeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 600 millimeters md.run_for_distance(DistanceMillimeters(600), MotorSpeedDPS(100)) """ def __init__(self, millimeters): self.millimeters = millimeters def __str__(self): return str(self.millimeters) + 'mm' def __mul__(self, other): if not isinstance(other, (float, int)): raise type_error('{} can only be multiplied by an int or float'.format(self)) return distance_millimeters(self.millimeters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.millimeters class Distancecentimeters(DistanceValue): """ Distance in centimeters Args: centimeters (int): the number of centimeters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceCentimeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 60 centimeters md.run_for_distance(DistanceCentimeters(60), MotorSpeedDPS(100)) """ def __init__(self, centimeters): self.centimeters = centimeters def __str__(self): return str(self.centimeters) + 'cm' def __mul__(self, other): if not isinstance(other, (float, int)): raise type_error('{} can only be multiplied by an int or float'.format(self)) return distance_centimeters(self.centimeters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.centimeters * CENTIMETER_MM class Distancedecimeters(DistanceValue): """ Distance in decimeters Args: decimeters (int): the number of decimeters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceDecimeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 6 decimeters md.run_for_distance(DistanceDecimeters(6), MotorSpeedDPS(100)) """ def __init__(self, decimeters): self.decimeters = decimeters def __str__(self): return str(self.decimeters) + 'dm' def __mul__(self, other): if not isinstance(other, (float, int)): raise type_error('{} can only be multiplied by an int or float'.format(self)) return distance_decimeters(self.decimeters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.decimeters * DECIMETER_MM class Distancemeters(DistanceValue): """ Distance in meters Args: meters (int): the number of meters Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceMeters, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 2 meters md.run_for_distance(DistanceMeters(2), MotorSpeedDPS(100)) """ def __init__(self, meters): self.meters = meters def __str__(self): return str(self.meters) + 'm' def __mul__(self, other): if not isinstance(other, (float, int)): raise type_error('{} can only be multiplied by an int or float'.format(self)) return distance_meters(self.meters * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.meters * METER_MM class Distanceinches(DistanceValue): """ Distance in inches Args: inches (int): the number of inches Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceInches, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 6 inches md.run_for_distance(DistanceInches(6), MotorSpeedDPS(100)) """ def __init__(self, inches): self.inches = inches def __str__(self): return str(self.inches) + 'in' def __mul__(self, other): if not isinstance(other, (float, int)): raise type_error('{} can only be multiplied by an int or float'.format(self)) return distance_inches(self.inches * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.inches * INCH_MM class Distancefeet(DistanceValue): """ Distance in feet Args: feet (int): the number of feet Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceFeet, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 3 feet md.run_for_distance(DistanceFeet(3), MotorSpeedDPS(100)) """ def __init__(self, feet): self.feet = feet def __str__(self): return str(self.feet) + 'ft' def __mul__(self, other): if not isinstance(other, (float, int)): raise type_error('{} can only be multiplied by an int or float'.format(self)) return distance_feet(self.feet * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.feet * FOOT_MM class Distanceyards(DistanceValue): """ Distance in yards Args: yards (int): the number of yards Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceYards, DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 2 yards md.run_for_distance(DistanceYards(2), MotorSpeedDPS(100)) """ def __init__(self, yards): self.yards = yards def __str__(self): return str(self.yards) + 'yd' def __mul__(self, other): if not isinstance(other, (float, int)): raise type_error('{} can only be multiplied by an int or float'.format(self)) return distance_yards(self.yards * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.yards * YARD_MM class Distancestuds(DistanceValue): """ Distance in studs Args: studs (int): the number of LEGO studs Example: .. code:: python import hub from spikedev.motor import MoveDifferential, MotorSpeedDPS from spikedev.unit import DistanceStuds from spikedev.wheel import SpikeWheel md = MoveDifferential(hub.port.E, hub.port.F, SpikeWheel, DistanceStuds(11)) # drive forward 2 studs md.run_for_distance(DistanceStuds(6), MotorSpeedDPS(100)) """ def __init__(self, studs): self.studs = studs def __str__(self): return str(self.studs) + 'stud' def __mul__(self, other): if not isinstance(other, (float, int)): raise type_error('{} can only be multiplied by an int or float'.format(self)) return distance_studs(self.studs * other) @property def mm(self): """ Returns: int: our distance in millimeters """ return self.studs * STUD_MM def distance_in_mm(distance): """ Args: distance (DistanceValue, int): the distance to convert to millimeters Returns: int: ``distance`` converted to millimeters Example: .. code:: python from spikedev.unit import DistanceFeet two_feet_in_mm = distance_in_mm(DistanceFeet(2)) """ if isinstance(distance, DistanceValue): return distance.mm elif isinstance(distance, (float, int)): return distance else: raise type_error(type(distance))
students = [] class Student: school_name = "Springfied Elementary" def __init__(self, name, student_id=332): self.name = name self.student_id = student_id students.append(self) def __str__(self): return "Student " + self.name def get_name_capitalize(self): return self.name.capitalize() def get_school_name(self): return self.school_name class HighSchoolStudent(Student): school_name = "Springfirld High School" def get_school_name(self): return "This is a high school student" def get_name_capitalize(self): original_value = super().get_name_capitalize() return original_value + "-HS" james = HighSchoolStudent("james") print(james.get_name_capitalize())
students = [] class Student: school_name = 'Springfied Elementary' def __init__(self, name, student_id=332): self.name = name self.student_id = student_id students.append(self) def __str__(self): return 'Student ' + self.name def get_name_capitalize(self): return self.name.capitalize() def get_school_name(self): return self.school_name class Highschoolstudent(Student): school_name = 'Springfirld High School' def get_school_name(self): return 'This is a high school student' def get_name_capitalize(self): original_value = super().get_name_capitalize() return original_value + '-HS' james = high_school_student('james') print(james.get_name_capitalize())
data_A = [1,2,3,6,7,8,9] data_B = [1,2,7,8] count = 0 for number1 in data_A: for number2 in data_B: if number1 == number2: print('{} is also appeared in {}'.format(number1,number2)) count += 1 else: pass print('There are only {} matching numbers between Data A and Data B.'.format(count))
data_a = [1, 2, 3, 6, 7, 8, 9] data_b = [1, 2, 7, 8] count = 0 for number1 in data_A: for number2 in data_B: if number1 == number2: print('{} is also appeared in {}'.format(number1, number2)) count += 1 else: pass print('There are only {} matching numbers between Data A and Data B.'.format(count))
class Solution(object): def rotate(self, matrix): """ :type m: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ m = matrix side = len(m) max_i = side - 1 for i in range(side // 2): y = i for j in range(max_i - i * 2): x = i + j m[y][x], m[x][max_i - y], m[max_i - y][max_i - x], m[max_i - x][y] = \ m[max_i - x][y], m[y][x], m[x][max_i - y], m[max_i - y][max_i - x]
class Solution(object): def rotate(self, matrix): """ :type m: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ m = matrix side = len(m) max_i = side - 1 for i in range(side // 2): y = i for j in range(max_i - i * 2): x = i + j (m[y][x], m[x][max_i - y], m[max_i - y][max_i - x], m[max_i - x][y]) = (m[max_i - x][y], m[y][x], m[x][max_i - y], m[max_i - y][max_i - x])
# Publised to Explorer in private.py # Also used in measurement.py TEST_GROUPS = { "websites": ["web_connectivity"], "im": ["facebook_messenger", "signal", "telegram", "whatsapp"], "middlebox": ["http_invalid_request_line", "http_header_field_manipulation"], "performance": ["ndt", "dash"], "circumvention": [ "bridge_reachability", "meek_fronted_requests_test", "vanilla_tor", "tcp_connect", "psiphon", "tor", "torsf", "riseupvpn", ], "legacy": [ "http_requests", "dns_consistency", "http_host", "multi_protocol_traceroute", ], "experimental": [ "urlgetter", "dnscheck", ], } TEST_NAMES = [] for v in TEST_GROUPS.values(): assert isinstance(v, list) TEST_NAMES.extend(v) def get_test_group_case(): """ Returns a postgres CASE statement to return the test_group based on the value of test_name. """ c = "CASE\n" for tg_name, tests in TEST_GROUPS.items(): c += "WHEN test_name = ANY('{{{}}}') THEN '{}'\n".format( ",".join(tests), tg_name ) c += "ELSE 'unknown'\n" c += "END\n" return c
test_groups = {'websites': ['web_connectivity'], 'im': ['facebook_messenger', 'signal', 'telegram', 'whatsapp'], 'middlebox': ['http_invalid_request_line', 'http_header_field_manipulation'], 'performance': ['ndt', 'dash'], 'circumvention': ['bridge_reachability', 'meek_fronted_requests_test', 'vanilla_tor', 'tcp_connect', 'psiphon', 'tor', 'torsf', 'riseupvpn'], 'legacy': ['http_requests', 'dns_consistency', 'http_host', 'multi_protocol_traceroute'], 'experimental': ['urlgetter', 'dnscheck']} test_names = [] for v in TEST_GROUPS.values(): assert isinstance(v, list) TEST_NAMES.extend(v) def get_test_group_case(): """ Returns a postgres CASE statement to return the test_group based on the value of test_name. """ c = 'CASE\n' for (tg_name, tests) in TEST_GROUPS.items(): c += "WHEN test_name = ANY('{{{}}}') THEN '{}'\n".format(','.join(tests), tg_name) c += "ELSE 'unknown'\n" c += 'END\n' return c
# -*- coding: utf-8 -*- class VertexNotReachableException(Exception): """ Exception for vertex distance and path """ pass
class Vertexnotreachableexception(Exception): """ Exception for vertex distance and path """ pass
class Node: def __init__(self, value): self.value = value self.l = None self.r = None class BinaryTree: def __init__(self): self.root = None def draw(self): '''Prints a preorder traversal of the tree''' self._draw(self.root) print() def _draw(self, node): print("(", end="") if node != None: print(str(node.value) + ", ", end="") self._draw(node.l) print(", ", end="") self._draw(node.r) print(")", end="") def invert(self): self.root = self._invert(self.root) def _invert(self, node): # find lowest point where nodes can be swapped # swap nodes if node: node.l = self._invert(node.l) node.r = self._invert(node.r) temp = node.l node.l = node.r node.r = temp return node def add(self, vals): for val in vals: if self.root == None: self.root = Node(val) else: self._add(self.root, val) def _add(self, node, val): if val < node.value: if node.l == None: node.l = Node(val) else: self._add(node.l, val) else: if node.r == None: node.r = Node(val) else: self._add(node.r, val) def main(): t = BinaryTree() t.add([4, 2, 7, 1, 3, 6, 9, 11]) t.draw() t.invert() t.draw() if __name__ == "__main__": main()
class Node: def __init__(self, value): self.value = value self.l = None self.r = None class Binarytree: def __init__(self): self.root = None def draw(self): """Prints a preorder traversal of the tree""" self._draw(self.root) print() def _draw(self, node): print('(', end='') if node != None: print(str(node.value) + ', ', end='') self._draw(node.l) print(', ', end='') self._draw(node.r) print(')', end='') def invert(self): self.root = self._invert(self.root) def _invert(self, node): if node: node.l = self._invert(node.l) node.r = self._invert(node.r) temp = node.l node.l = node.r node.r = temp return node def add(self, vals): for val in vals: if self.root == None: self.root = node(val) else: self._add(self.root, val) def _add(self, node, val): if val < node.value: if node.l == None: node.l = node(val) else: self._add(node.l, val) elif node.r == None: node.r = node(val) else: self._add(node.r, val) def main(): t = binary_tree() t.add([4, 2, 7, 1, 3, 6, 9, 11]) t.draw() t.invert() t.draw() if __name__ == '__main__': main()
# 1, 2, 3, 4, 5, 6, 7, 8, 9 # 0, 1, 1, -1, -1, 2, 2, -2, -2 # 0, 0, 1, 1, -1, -1, 2, 2, -2, -2 def seq(n): a = (n - 1) // 2 b = (n + 1) // 4 if a % 2 == 0: return -b else: return b n = int(input()) x = seq(n + 1) y = seq(n) print(x, y)
def seq(n): a = (n - 1) // 2 b = (n + 1) // 4 if a % 2 == 0: return -b else: return b n = int(input()) x = seq(n + 1) y = seq(n) print(x, y)
W = [] S = str(input('')) for i in S: if i not in W: W.append(i) if len(W) % 2 == 0: print('CHAT WITH HER!') else: print('IGNORE HIM!')
w = [] s = str(input('')) for i in S: if i not in W: W.append(i) if len(W) % 2 == 0: print('CHAT WITH HER!') else: print('IGNORE HIM!')
worldLists = { "desk": { "sets": ["desk"], "assume": ["des", "de"], }, "laptop": { "sets": ["laptop"], "assume": ["lapto", "lapt", "lap", "la"], }, "wall": { "sets": ["wall"], "assume": ["wal", "wa"] }, "sign": { "sets": ["sign"], "assume": ["sig", "si"], }, "door": { "sets": ["door"], "assume": ["doo", "do"], }, "chair": { "sets": ["chair"], "assume": ["chai", "cha", "ch",] }, "window": { "sets": ["window"], "assume": ["windo", "wind", "win", "wi"] }, "floor": { "sets": ["floor"], "assume": ["floo", "flo", "fl"] }, }
world_lists = {'desk': {'sets': ['desk'], 'assume': ['des', 'de']}, 'laptop': {'sets': ['laptop'], 'assume': ['lapto', 'lapt', 'lap', 'la']}, 'wall': {'sets': ['wall'], 'assume': ['wal', 'wa']}, 'sign': {'sets': ['sign'], 'assume': ['sig', 'si']}, 'door': {'sets': ['door'], 'assume': ['doo', 'do']}, 'chair': {'sets': ['chair'], 'assume': ['chai', 'cha', 'ch']}, 'window': {'sets': ['window'], 'assume': ['windo', 'wind', 'win', 'wi']}, 'floor': {'sets': ['floor'], 'assume': ['floo', 'flo', 'fl']}}
# Prova Mundo 02 # Rascunhos da Prova do Mundo 2 #Nota: 90% n = ' nilseia'.upper().strip()[0] print(n) for c in range(0, 10): print(c)
n = ' nilseia'.upper().strip()[0] print(n) for c in range(0, 10): print(c)
dnas = [ ['hY?9', 56, 25, 8.21, 47, 21, -2.56, {'ott_len': 43, 'ott_percent': 196, 'ott_bw': 124, 'tps_qty_index': 215}], ['st7M', 67, 43, 17.72, 55, 29, 5.52, {'ott_len': 49, 'ott_percent': 299, 'ott_bw': 84, 'tps_qty_index': 468}], ]
dnas = [['hY?9', 56, 25, 8.21, 47, 21, -2.56, {'ott_len': 43, 'ott_percent': 196, 'ott_bw': 124, 'tps_qty_index': 215}], ['st7M', 67, 43, 17.72, 55, 29, 5.52, {'ott_len': 49, 'ott_percent': 299, 'ott_bw': 84, 'tps_qty_index': 468}]]
# This program contains a tuple stores the months of the year and # another tuple from it with just summer months # and prints out the summer months ine at a time. month = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December") summer = month[4:7] for month in summer: print(month)
month = ('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December') summer = month[4:7] for month in summer: print(month)
default_players = { 'hungergames': [ ("Marvel", True), ("Glimmer", False), ("Cato", True), ("Clove", False), ("Foxface", False), ("Jason", True), ("Rue", False), ("Thresh", True), ("Peeta", True), ("Katniss", False) ], 'melee': [ ("Dr. Mario", True), ("Mario", True), ("Luigi", True), ("Bowser", True), ("Peach", False), ("Yoshi", True), ("Donkey Kong", True), ("Captain Falcon", True), ("Ganondorf", True), ("Falco", True), ("Fox", True), ("Ness", True), ("Nana", False), ("Popo", True), ("Kirby", True), ("Samus", False), ("Zelda", False), ("Link", True), ("Young Link", True), ("Pichu", None), ("Pikachu", None), ("Jigglypuff", None), ("Mewtwo", True), ("Mr. Game & Watch", True), ("Marth", True), ("Roy", True) ] }
default_players = {'hungergames': [('Marvel', True), ('Glimmer', False), ('Cato', True), ('Clove', False), ('Foxface', False), ('Jason', True), ('Rue', False), ('Thresh', True), ('Peeta', True), ('Katniss', False)], 'melee': [('Dr. Mario', True), ('Mario', True), ('Luigi', True), ('Bowser', True), ('Peach', False), ('Yoshi', True), ('Donkey Kong', True), ('Captain Falcon', True), ('Ganondorf', True), ('Falco', True), ('Fox', True), ('Ness', True), ('Nana', False), ('Popo', True), ('Kirby', True), ('Samus', False), ('Zelda', False), ('Link', True), ('Young Link', True), ('Pichu', None), ('Pikachu', None), ('Jigglypuff', None), ('Mewtwo', True), ('Mr. Game & Watch', True), ('Marth', True), ('Roy', True)]}
def main(): N, M = map(int,input().split()) for i in range(1,N,2): print(("." + "|.."*int((i-1)/2) + "|" + "..|"*int((i-1)/2) + ".").center(M,'-')) print("WELCOME".center(M,"-")) for i in range(N-2,-1,-2): print(("." + "|.."*int((i-1)/2) + "|" + "..|"*int((i-1)/2) + ".").center(M,'-')) if __name__=='__main__': main()
def main(): (n, m) = map(int, input().split()) for i in range(1, N, 2): print(('.' + '|..' * int((i - 1) / 2) + '|' + '..|' * int((i - 1) / 2) + '.').center(M, '-')) print('WELCOME'.center(M, '-')) for i in range(N - 2, -1, -2): print(('.' + '|..' * int((i - 1) / 2) + '|' + '..|' * int((i - 1) / 2) + '.').center(M, '-')) if __name__ == '__main__': main()
""" Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" Example 3: Input: s = "a" Output: "a" Example 4: Input: s = "ac" Output: "a" Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters. """ def longestPalindrome(s: str) -> str: """ Time: O(n^2) Space: O(1) """ n = len(s) res = s[0] for i in range(1, n): left = i - 1 mid = i while s[left] == s[mid] and left >= 0 and mid < n: left -= 1 mid += 1 res = max(res, s[left + 1:mid], key=len) left = i - 1 right = i + 1 while left >= 0 and right < n and s[left] == s[right]: left -= 1 right += 1 res = max(res, s[left + 1:right], key=len) return res if __name__ == '__main__': # Test 1 s = "babad" print(longestPalindrome(s)) # Test 2 s = "cbbd" print(longestPalindrome(s)) # Test 3 s = "a" print(longestPalindrome(s)) # Test 4 s = "ac" print(longestPalindrome(s))
""" Given a string s, return the longest palindromic substring in s. Example 1: Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer. Example 2: Input: s = "cbbd" Output: "bb" Example 3: Input: s = "a" Output: "a" Example 4: Input: s = "ac" Output: "a" Constraints: 1 <= s.length <= 1000 s consist of only digits and English letters. """ def longest_palindrome(s: str) -> str: """ Time: O(n^2) Space: O(1) """ n = len(s) res = s[0] for i in range(1, n): left = i - 1 mid = i while s[left] == s[mid] and left >= 0 and (mid < n): left -= 1 mid += 1 res = max(res, s[left + 1:mid], key=len) left = i - 1 right = i + 1 while left >= 0 and right < n and (s[left] == s[right]): left -= 1 right += 1 res = max(res, s[left + 1:right], key=len) return res if __name__ == '__main__': s = 'babad' print(longest_palindrome(s)) s = 'cbbd' print(longest_palindrome(s)) s = 'a' print(longest_palindrome(s)) s = 'ac' print(longest_palindrome(s))
#!/usr/bin/env python3 tls_cnt = 0 ssl_cnt = 0 with open("input.txt",'r') as f: for line in f: bracket = 0 tls_flag = 0 ABAs = [[],[]] for i in range(len(line)-2): if line[i] == '[': bracket = 1 elif line[i] == ']': bracket = 0 else: if line[i] == line[i+2] and line[i+1] not in "]": ABAs[bracket].append(line[i:i+3]) if i < len(line)-3 and line[i:i+2] == line[i+3:i+1:-1] and line[i] != line[i+1]: if not bracket and tls_flag != 2: tls_flag = 1 else: tls_flag = 2 else: # for exited normally if tls_flag == 1: tls_cnt += 1 ABAs[0] = map(lambda s: s[1:]+s[1], ABAs[0]) if len(set(ABAs[0]).intersection(ABAs[1])) > 0: ssl_cnt += 1 print("TLS: {}".format(tls_cnt)) print("SSL: {}".format(ssl_cnt))
tls_cnt = 0 ssl_cnt = 0 with open('input.txt', 'r') as f: for line in f: bracket = 0 tls_flag = 0 ab_as = [[], []] for i in range(len(line) - 2): if line[i] == '[': bracket = 1 elif line[i] == ']': bracket = 0 else: if line[i] == line[i + 2] and line[i + 1] not in ']': ABAs[bracket].append(line[i:i + 3]) if i < len(line) - 3 and line[i:i + 2] == line[i + 3:i + 1:-1] and (line[i] != line[i + 1]): if not bracket and tls_flag != 2: tls_flag = 1 else: tls_flag = 2 else: if tls_flag == 1: tls_cnt += 1 ABAs[0] = map(lambda s: s[1:] + s[1], ABAs[0]) if len(set(ABAs[0]).intersection(ABAs[1])) > 0: ssl_cnt += 1 print('TLS: {}'.format(tls_cnt)) print('SSL: {}'.format(ssl_cnt))
"""This module defines Ubuntu Bionic dependencies.""" load("@rules_deb_packages//:deb_packages.bzl", "deb_packages") def ubuntu_bionic_amd64(): deb_packages( name = "ubuntu_bionic_amd64", arch = "amd64", packages = { "base-files": "pool/main/b/base-files/base-files_10.1ubuntu2.11_amd64.deb", "bash": "pool/main/b/bash/bash_4.4.18-2ubuntu1.2_amd64.deb", "ca-certificates": "pool/main/c/ca-certificates/ca-certificates_20210119~18.04.2_all.deb", "coreutils": "pool/main/c/coreutils/coreutils_8.28-1ubuntu1_amd64.deb", "dash": "pool/main/d/dash/dash_0.5.8-2.10_amd64.deb", "fontconfig-config": "pool/main/f/fontconfig/fontconfig-config_2.12.6-0ubuntu2_all.deb", "fonts-dejavu-core": "pool/main/f/fonts-dejavu/fonts-dejavu-core_2.37-1_all.deb", "gzip": "pool/main/g/gzip/gzip_1.6-5ubuntu1.1_amd64.deb", "less": "pool/main/l/less/less_487-0.1_amd64.deb", "libacl1": "pool/main/a/acl/libacl1_2.2.52-3build1_amd64.deb", "libaio1": "pool/main/liba/libaio/libaio1_0.3.110-5ubuntu0.1_amd64.deb", "libattr1": "pool/main/a/attr/libattr1_2.4.47-2build1_amd64.deb", "libbz2-1.0": "pool/main/b/bzip2/libbz2-1.0_1.0.6-8.1ubuntu0.2_amd64.deb", "libc-bin": "pool/main/g/glibc/libc-bin_2.27-3ubuntu1.4_amd64.deb", "libc6": "pool/main/g/glibc/libc6_2.27-3ubuntu1.4_amd64.deb", "libdb5.3": "pool/main/d/db5.3/libdb5.3_5.3.28-13.1ubuntu1.1_amd64.deb", "libexpat1": "pool/main/e/expat/libexpat1_2.2.5-3ubuntu0.2_amd64.deb", "libffi6": "pool/main/libf/libffi/libffi6_3.2.1-8_amd64.deb", "libfontconfig1": "pool/main/f/fontconfig/libfontconfig1_2.12.6-0ubuntu2_amd64.deb", "libfreetype6": "pool/main/f/freetype/libfreetype6_2.8.1-2ubuntu2.1_amd64.deb", "libgcc1": "pool/main/g/gcc-8/libgcc1_8.4.0-1ubuntu1~18.04_amd64.deb", "libgcrypt20": "pool/main/libg/libgcrypt20/libgcrypt20_1.8.1-4ubuntu1.3_amd64.deb", "libgomp1": "pool/main/g/gcc-8/libgomp1_8.4.0-1ubuntu1~18.04_amd64.deb", "libgpg-error0": "pool/main/libg/libgpg-error/libgpg-error0_1.27-6_amd64.deb", "libjpeg-turbo8": "pool/main/libj/libjpeg-turbo/libjpeg-turbo8_1.5.2-0ubuntu5.18.04.4_amd64.deb", "liblcms2-2": "pool/main/l/lcms2/liblcms2-2_2.9-1ubuntu0.1_amd64.deb", "liblz4-1": "pool/main/l/lz4/liblz4-1_0.0~r131-2ubuntu3.1_amd64.deb", "liblzma5": "pool/main/x/xz-utils/liblzma5_5.2.2-1.3_amd64.deb", "libmpdec2": "pool/main/m/mpdecimal/libmpdec2_2.4.2-1ubuntu1_amd64.deb", "libncurses5": "pool/main/n/ncurses/libncurses5_6.1-1ubuntu1.18.04_amd64.deb", "libncursesw5": "pool/main/n/ncurses/libncursesw5_6.1-1ubuntu1.18.04_amd64.deb", "libpcre2-8-0": "pool/universe/p/pcre2/libpcre2-8-0_10.31-2_amd64.deb", "libpmem1": "pool/universe/p/pmdk/libpmem1_1.4.1-0ubuntu1~18.04.1_amd64.deb", "libpng16-16": "pool/main/libp/libpng1.6/libpng16-16_1.6.34-1ubuntu0.18.04.2_amd64.deb", "libpython3.6-minimal": "pool/main/p/python3.6/libpython3.6-minimal_3.6.9-1~18.04ubuntu1.6_amd64.deb", "libpython3.6-stdlib": "pool/main/p/python3.6/libpython3.6-stdlib_3.6.9-1~18.04ubuntu1.6_amd64.deb", "libreadline5": "pool/main/r/readline5/libreadline5_5.2+dfsg-3build1_amd64.deb", "libreadline7": "pool/main/r/readline/libreadline7_7.0-3_amd64.deb", "libselinux1": "pool/main/libs/libselinux/libselinux1_2.7-2build2_amd64.deb", "libsqlite3-0": "pool/main/s/sqlite3/libsqlite3-0_3.22.0-1ubuntu0.4_amd64.deb", "libssl1.1": "pool/main/o/openssl/libssl1.1_1.1.1-1ubuntu2.1~18.04.14_amd64.deb", "libstdc++6": "pool/main/g/gcc-8/libstdc++6_8.4.0-1ubuntu1~18.04_amd64.deb", "libsystemd0": "pool/main/s/systemd/libsystemd0_237-3ubuntu10.53_amd64.deb", "libtinfo5": "pool/main/n/ncurses/libtinfo5_6.1-1ubuntu1.18.04_amd64.deb", "libuuid1": "pool/main/u/util-linux/libuuid1_2.31.1-0.4ubuntu3.7_amd64.deb", "mime-support": "pool/main/m/mime-support/mime-support_3.60ubuntu1_all.deb", "ncurses-bin": "pool/main/n/ncurses/ncurses-bin_6.1-1ubuntu1.18.04_amd64.deb", "netbase": "pool/main/n/netbase/netbase_5.4_all.deb", "openssl": "pool/main/o/openssl/openssl_1.1.1-1ubuntu2.1~18.04.14_amd64.deb", "python3-distutils": "pool/main/p/python3-stdlib-extensions/python3-distutils_3.6.9-1~18.04_all.deb", "python3.6-minimal": "pool/main/p/python3.6/python3.6-minimal_3.6.9-1~18.04ubuntu1.6_amd64.deb", "readline-common": "pool/main/r/readline/readline-common_7.0-3_all.deb", "tar": "pool/main/t/tar/tar_1.29b-2ubuntu0.2_amd64.deb", "tzdata": "pool/main/t/tzdata/tzdata_2021e-0ubuntu0.18.04_all.deb", "zlib1g": "pool/main/z/zlib/zlib1g_1.2.11.dfsg-0ubuntu2_amd64.deb", }, packages_sha256 = { "base-files": "b103b55f80cc703af636cb111d80b733c71ba4c39a138ebe8926356d88173142", "bash": "4f95ed6e11435fccaa9731eaeb7688fed8cc1fd8a25d44640e2f7a25f871ae08", "ca-certificates": "911c7e57ad1ef49958f28dcc27bb19e0103465486cc7766023a68e78344b8c10", "coreutils": "24541a48e25dfb17c98ce77dda61800e6cd68d74c25725753613fbcc00f2418f", "dash": "51fe28b98b8e023325ae8868f29807cdb53f6f2eac943723b5e6bd47cde0cb2c", "fontconfig-config": "ba4dbb3b4c173c1d97b6112d736da25d2dc7fab0c7408eb3cb49207f43dd5630", "fonts-dejavu-core": "f2b3f7f51e23e0493e8e642c82003fe75cf42bc95fda545cc96b725a69adb515", "gzip": "46286e914cad985cfe8cb3f196b7fce48146d3b329d45673b6ad62e8ced034cb", "less": "00d9c5e56b81c95a14e3fd148ff464acaf3fe757d3e4b4d1e54990b28c54eb57", "libacl1": "adbe1a5b37daf02f7bbd645c3a0baf63f6607e207567574c609493c32d5d57a5", "libaio1": "01d780036ab15752b939637daa200517bafbd62ff73f91be5f94e77f42f7a7b0", "libattr1": "91ef5319ee1f0173a6c5d16ba364e79c90f74b94b5d7daed1a2674a92f4f9c78", "libbz2-1.0": "897850ec11aab3280ce2755eb552995a5aa9b16a70453934828c6418591ea87b", "libc-bin": "438aa7dc40dfa7c5ab51c1e726d63414bd5dad44954c8cbb75d6c3d73bbc0efe", "libc6": "46d39b8965f35457ce5db62662832c095fd7e01e72093da99ae025eb8e12bbe5", "libdb5.3": "abb7f569252604af9b123cd6c73195cbd54d7b7664479a85fd5fd12fe8ba3b5d", "libexpat1": "d700a358e8139b5f31c96a3caef452d62388c05f7cf4d6e4f448a06c2c2da122", "libffi6": "fa26945b0aadfc72ec623c68be9cc59235a7fe42e2388f7015fd131f4fb06dc9", "libfontconfig1": "647bb8f09e751a39d488b0260db6015ce1118c56114cc771dd5bf907180f0c80", "libfreetype6": "7f4afc6a8e7023ed51f15caf4d082e44e0f3926161afaeb7c4bb6326955255bd", "libgcc1": "116dadf4ceaba7150eb46a6598dd3defa62b1b2a6578fb494f4c932878634994", "libgcrypt20": "079025d334873844bba2aae474fe78f3eff3e04673302c91e4167916fd03efd2", "libgomp1": "2fb511a931d0510d22313fad065c951e04431d75d4e6160e1d80d29e88748c8a", "libgpg-error0": "afcf8629c4de6946d73661126ae4e0a28f9718c8720900201d46fd963e0b5ccf", "libjpeg-turbo8": "57f9879f3a23128ba3e9c348eb250b83996fa9ef16de947ab8eff74100f898da", "liblcms2-2": "a08e5e734bcb5a827772e326dad7c0411bbac9399f0f635edfa6b1f09ad80bdb", "liblz4-1": "deed1dc6d2c5b492b136fe23b0c6563f9fe9a9a016bd0c93abdb253cc97cfe67", "liblzma5": "92704fce1ad9af92d59052705d2e0e258789a1718afeca9c0fb0a0d37112b27a", "libmpdec2": "2962dbb81413ad47fee589bb6663589e38b84d80b4d55d8019f0b305025c5eb6", "libncurses5": "928109886a9c8a1a1504e5460632ba49cc0854176a90c16dcd95eb7ebd8d240d", "libncursesw5": "d1a7a32fe88181d6f5adf7c52cb981359aa35b01bdbbf7218ddc240a4fdabd87", "libpcre2-8-0": "37898dba2cc2cf5b87b47b1efb6cb2fda65f3a556f237bd3c30d5c2a8aa48fdd", "libpmem1": "25d3bf2e7c76d8588967e411667f3c2a6d442f6bb4c0bcdb8fa018891e782e06", "libpng16-16": "4d484ba67be62e7bb450ff41c88d06e65d564f9180daccc4a2640760493804bc", "libpython3.6-minimal": "ba0ae4d8a896e433124f462ceffc41009cfddae1e7006f49200d9776f7f21495", "libpython3.6-stdlib": "6b8b2dbb1e838808ae362de266b79ade1d7a78bdfd5be91031583df211f53bf2", "libreadline5": "dd851f543f3061d07c31fd44917865c3173ae9018ae331716787fbfcf1988bec", "libreadline7": "8706403267e95615f1b70db31ff16709361982728b308466346e01c20a743dd5", "libselinux1": "6b6c70f809e8b13f0b1f27006e125abb3a8c3195f5c888dce0df1a5d3f211c0d", "libsqlite3-0": "cde7a26502ecfeede865ce054763f4b6d3aa151bd8dcc5696e2725cfda5ceb07", "libssl1.1": "edeeb202b67936376e8fe483d7bc8d769a456eba2d100b272bb195b6e6d38cb3", "libstdc++6": "4dbd1ffa20011329608f584ff329a10507cfa78c3f76fa34e6f479f9680b64f4", "libsystemd0": "12ba25ece07fed5dae27e33daf701786d0b2589df141d751a25a99f136d8c9e2", "libtinfo5": "bb4d4d80720149692ea0d5bca1a5dac57737afe447810ce69dd4a95107121da5", "libuuid1": "c04350aa8dc1bd73712716f9826b0f02fa10b77058c990a406445020970c2eaa", "mime-support": "98e05aa03538c5f182ed14cbb59cfe64b30592d77e602abd2442a9f1c72532b3", "ncurses-bin": "336af3c372b6a7d083e6c6053670781369d8ae713fd098c9dab8fc5432458015", "netbase": "cbda1c8035cd1fe0b1fb09b456892c0bb868657bfe02da82f0b16207d391145e", "openssl": "c938fa9fb3a00e89a868e95c0faa76adafa0a53f1de122f22ccdfb4e4a074986", "python3-distutils": "f836b1e22923fa175c1968b9dbd916ae5639c9250e21bcfb88f9df2dc289f65c", "python3.6-minimal": "e30011c605816ab1d371c9f096caabaff8dabf87850207fd146aa05845b912c9", "readline-common": "84cb3642c82114496d2fc17011db13655bd661cf4641098c03c168ddde367908", "tar": "6bdbb90c9c073f8e8f92da231a2e553410ce397489f2f1f77d1ae8ddbd0c7bc4", "tzdata": "8ff68141a56b3fe97588a4e8ee02de7dfdacf2abbd4c23ed9ea793ba181ee479", "zlib1g": "2e6dafb986ee8ebbc4e1c344fab090a41710cab878fc9cd89336cdd1740518c5", }, sources = [ "http://us.archive.ubuntu.com/ubuntu bionic main universe", "http://us.archive.ubuntu.com/ubuntu bionic-updates main universe", "http://us.archive.ubuntu.com/ubuntu bionic-backports main universe", "http://security.ubuntu.com/ubuntu bionic-security main universe", ], urls = [ "http://us.archive.ubuntu.com/ubuntu/$(package_path)", "http://security.ubuntu.com/ubuntu/$(package_path)", "https://launchpad.net/ubuntu/+archive/primary/+files/$(package_file)", # Needed in case of superseded archive no more available on the mirrors ], )
"""This module defines Ubuntu Bionic dependencies.""" load('@rules_deb_packages//:deb_packages.bzl', 'deb_packages') def ubuntu_bionic_amd64(): deb_packages(name='ubuntu_bionic_amd64', arch='amd64', packages={'base-files': 'pool/main/b/base-files/base-files_10.1ubuntu2.11_amd64.deb', 'bash': 'pool/main/b/bash/bash_4.4.18-2ubuntu1.2_amd64.deb', 'ca-certificates': 'pool/main/c/ca-certificates/ca-certificates_20210119~18.04.2_all.deb', 'coreutils': 'pool/main/c/coreutils/coreutils_8.28-1ubuntu1_amd64.deb', 'dash': 'pool/main/d/dash/dash_0.5.8-2.10_amd64.deb', 'fontconfig-config': 'pool/main/f/fontconfig/fontconfig-config_2.12.6-0ubuntu2_all.deb', 'fonts-dejavu-core': 'pool/main/f/fonts-dejavu/fonts-dejavu-core_2.37-1_all.deb', 'gzip': 'pool/main/g/gzip/gzip_1.6-5ubuntu1.1_amd64.deb', 'less': 'pool/main/l/less/less_487-0.1_amd64.deb', 'libacl1': 'pool/main/a/acl/libacl1_2.2.52-3build1_amd64.deb', 'libaio1': 'pool/main/liba/libaio/libaio1_0.3.110-5ubuntu0.1_amd64.deb', 'libattr1': 'pool/main/a/attr/libattr1_2.4.47-2build1_amd64.deb', 'libbz2-1.0': 'pool/main/b/bzip2/libbz2-1.0_1.0.6-8.1ubuntu0.2_amd64.deb', 'libc-bin': 'pool/main/g/glibc/libc-bin_2.27-3ubuntu1.4_amd64.deb', 'libc6': 'pool/main/g/glibc/libc6_2.27-3ubuntu1.4_amd64.deb', 'libdb5.3': 'pool/main/d/db5.3/libdb5.3_5.3.28-13.1ubuntu1.1_amd64.deb', 'libexpat1': 'pool/main/e/expat/libexpat1_2.2.5-3ubuntu0.2_amd64.deb', 'libffi6': 'pool/main/libf/libffi/libffi6_3.2.1-8_amd64.deb', 'libfontconfig1': 'pool/main/f/fontconfig/libfontconfig1_2.12.6-0ubuntu2_amd64.deb', 'libfreetype6': 'pool/main/f/freetype/libfreetype6_2.8.1-2ubuntu2.1_amd64.deb', 'libgcc1': 'pool/main/g/gcc-8/libgcc1_8.4.0-1ubuntu1~18.04_amd64.deb', 'libgcrypt20': 'pool/main/libg/libgcrypt20/libgcrypt20_1.8.1-4ubuntu1.3_amd64.deb', 'libgomp1': 'pool/main/g/gcc-8/libgomp1_8.4.0-1ubuntu1~18.04_amd64.deb', 'libgpg-error0': 'pool/main/libg/libgpg-error/libgpg-error0_1.27-6_amd64.deb', 'libjpeg-turbo8': 'pool/main/libj/libjpeg-turbo/libjpeg-turbo8_1.5.2-0ubuntu5.18.04.4_amd64.deb', 'liblcms2-2': 'pool/main/l/lcms2/liblcms2-2_2.9-1ubuntu0.1_amd64.deb', 'liblz4-1': 'pool/main/l/lz4/liblz4-1_0.0~r131-2ubuntu3.1_amd64.deb', 'liblzma5': 'pool/main/x/xz-utils/liblzma5_5.2.2-1.3_amd64.deb', 'libmpdec2': 'pool/main/m/mpdecimal/libmpdec2_2.4.2-1ubuntu1_amd64.deb', 'libncurses5': 'pool/main/n/ncurses/libncurses5_6.1-1ubuntu1.18.04_amd64.deb', 'libncursesw5': 'pool/main/n/ncurses/libncursesw5_6.1-1ubuntu1.18.04_amd64.deb', 'libpcre2-8-0': 'pool/universe/p/pcre2/libpcre2-8-0_10.31-2_amd64.deb', 'libpmem1': 'pool/universe/p/pmdk/libpmem1_1.4.1-0ubuntu1~18.04.1_amd64.deb', 'libpng16-16': 'pool/main/libp/libpng1.6/libpng16-16_1.6.34-1ubuntu0.18.04.2_amd64.deb', 'libpython3.6-minimal': 'pool/main/p/python3.6/libpython3.6-minimal_3.6.9-1~18.04ubuntu1.6_amd64.deb', 'libpython3.6-stdlib': 'pool/main/p/python3.6/libpython3.6-stdlib_3.6.9-1~18.04ubuntu1.6_amd64.deb', 'libreadline5': 'pool/main/r/readline5/libreadline5_5.2+dfsg-3build1_amd64.deb', 'libreadline7': 'pool/main/r/readline/libreadline7_7.0-3_amd64.deb', 'libselinux1': 'pool/main/libs/libselinux/libselinux1_2.7-2build2_amd64.deb', 'libsqlite3-0': 'pool/main/s/sqlite3/libsqlite3-0_3.22.0-1ubuntu0.4_amd64.deb', 'libssl1.1': 'pool/main/o/openssl/libssl1.1_1.1.1-1ubuntu2.1~18.04.14_amd64.deb', 'libstdc++6': 'pool/main/g/gcc-8/libstdc++6_8.4.0-1ubuntu1~18.04_amd64.deb', 'libsystemd0': 'pool/main/s/systemd/libsystemd0_237-3ubuntu10.53_amd64.deb', 'libtinfo5': 'pool/main/n/ncurses/libtinfo5_6.1-1ubuntu1.18.04_amd64.deb', 'libuuid1': 'pool/main/u/util-linux/libuuid1_2.31.1-0.4ubuntu3.7_amd64.deb', 'mime-support': 'pool/main/m/mime-support/mime-support_3.60ubuntu1_all.deb', 'ncurses-bin': 'pool/main/n/ncurses/ncurses-bin_6.1-1ubuntu1.18.04_amd64.deb', 'netbase': 'pool/main/n/netbase/netbase_5.4_all.deb', 'openssl': 'pool/main/o/openssl/openssl_1.1.1-1ubuntu2.1~18.04.14_amd64.deb', 'python3-distutils': 'pool/main/p/python3-stdlib-extensions/python3-distutils_3.6.9-1~18.04_all.deb', 'python3.6-minimal': 'pool/main/p/python3.6/python3.6-minimal_3.6.9-1~18.04ubuntu1.6_amd64.deb', 'readline-common': 'pool/main/r/readline/readline-common_7.0-3_all.deb', 'tar': 'pool/main/t/tar/tar_1.29b-2ubuntu0.2_amd64.deb', 'tzdata': 'pool/main/t/tzdata/tzdata_2021e-0ubuntu0.18.04_all.deb', 'zlib1g': 'pool/main/z/zlib/zlib1g_1.2.11.dfsg-0ubuntu2_amd64.deb'}, packages_sha256={'base-files': 'b103b55f80cc703af636cb111d80b733c71ba4c39a138ebe8926356d88173142', 'bash': '4f95ed6e11435fccaa9731eaeb7688fed8cc1fd8a25d44640e2f7a25f871ae08', 'ca-certificates': '911c7e57ad1ef49958f28dcc27bb19e0103465486cc7766023a68e78344b8c10', 'coreutils': '24541a48e25dfb17c98ce77dda61800e6cd68d74c25725753613fbcc00f2418f', 'dash': '51fe28b98b8e023325ae8868f29807cdb53f6f2eac943723b5e6bd47cde0cb2c', 'fontconfig-config': 'ba4dbb3b4c173c1d97b6112d736da25d2dc7fab0c7408eb3cb49207f43dd5630', 'fonts-dejavu-core': 'f2b3f7f51e23e0493e8e642c82003fe75cf42bc95fda545cc96b725a69adb515', 'gzip': '46286e914cad985cfe8cb3f196b7fce48146d3b329d45673b6ad62e8ced034cb', 'less': '00d9c5e56b81c95a14e3fd148ff464acaf3fe757d3e4b4d1e54990b28c54eb57', 'libacl1': 'adbe1a5b37daf02f7bbd645c3a0baf63f6607e207567574c609493c32d5d57a5', 'libaio1': '01d780036ab15752b939637daa200517bafbd62ff73f91be5f94e77f42f7a7b0', 'libattr1': '91ef5319ee1f0173a6c5d16ba364e79c90f74b94b5d7daed1a2674a92f4f9c78', 'libbz2-1.0': '897850ec11aab3280ce2755eb552995a5aa9b16a70453934828c6418591ea87b', 'libc-bin': '438aa7dc40dfa7c5ab51c1e726d63414bd5dad44954c8cbb75d6c3d73bbc0efe', 'libc6': '46d39b8965f35457ce5db62662832c095fd7e01e72093da99ae025eb8e12bbe5', 'libdb5.3': 'abb7f569252604af9b123cd6c73195cbd54d7b7664479a85fd5fd12fe8ba3b5d', 'libexpat1': 'd700a358e8139b5f31c96a3caef452d62388c05f7cf4d6e4f448a06c2c2da122', 'libffi6': 'fa26945b0aadfc72ec623c68be9cc59235a7fe42e2388f7015fd131f4fb06dc9', 'libfontconfig1': '647bb8f09e751a39d488b0260db6015ce1118c56114cc771dd5bf907180f0c80', 'libfreetype6': '7f4afc6a8e7023ed51f15caf4d082e44e0f3926161afaeb7c4bb6326955255bd', 'libgcc1': '116dadf4ceaba7150eb46a6598dd3defa62b1b2a6578fb494f4c932878634994', 'libgcrypt20': '079025d334873844bba2aae474fe78f3eff3e04673302c91e4167916fd03efd2', 'libgomp1': '2fb511a931d0510d22313fad065c951e04431d75d4e6160e1d80d29e88748c8a', 'libgpg-error0': 'afcf8629c4de6946d73661126ae4e0a28f9718c8720900201d46fd963e0b5ccf', 'libjpeg-turbo8': '57f9879f3a23128ba3e9c348eb250b83996fa9ef16de947ab8eff74100f898da', 'liblcms2-2': 'a08e5e734bcb5a827772e326dad7c0411bbac9399f0f635edfa6b1f09ad80bdb', 'liblz4-1': 'deed1dc6d2c5b492b136fe23b0c6563f9fe9a9a016bd0c93abdb253cc97cfe67', 'liblzma5': '92704fce1ad9af92d59052705d2e0e258789a1718afeca9c0fb0a0d37112b27a', 'libmpdec2': '2962dbb81413ad47fee589bb6663589e38b84d80b4d55d8019f0b305025c5eb6', 'libncurses5': '928109886a9c8a1a1504e5460632ba49cc0854176a90c16dcd95eb7ebd8d240d', 'libncursesw5': 'd1a7a32fe88181d6f5adf7c52cb981359aa35b01bdbbf7218ddc240a4fdabd87', 'libpcre2-8-0': '37898dba2cc2cf5b87b47b1efb6cb2fda65f3a556f237bd3c30d5c2a8aa48fdd', 'libpmem1': '25d3bf2e7c76d8588967e411667f3c2a6d442f6bb4c0bcdb8fa018891e782e06', 'libpng16-16': '4d484ba67be62e7bb450ff41c88d06e65d564f9180daccc4a2640760493804bc', 'libpython3.6-minimal': 'ba0ae4d8a896e433124f462ceffc41009cfddae1e7006f49200d9776f7f21495', 'libpython3.6-stdlib': '6b8b2dbb1e838808ae362de266b79ade1d7a78bdfd5be91031583df211f53bf2', 'libreadline5': 'dd851f543f3061d07c31fd44917865c3173ae9018ae331716787fbfcf1988bec', 'libreadline7': '8706403267e95615f1b70db31ff16709361982728b308466346e01c20a743dd5', 'libselinux1': '6b6c70f809e8b13f0b1f27006e125abb3a8c3195f5c888dce0df1a5d3f211c0d', 'libsqlite3-0': 'cde7a26502ecfeede865ce054763f4b6d3aa151bd8dcc5696e2725cfda5ceb07', 'libssl1.1': 'edeeb202b67936376e8fe483d7bc8d769a456eba2d100b272bb195b6e6d38cb3', 'libstdc++6': '4dbd1ffa20011329608f584ff329a10507cfa78c3f76fa34e6f479f9680b64f4', 'libsystemd0': '12ba25ece07fed5dae27e33daf701786d0b2589df141d751a25a99f136d8c9e2', 'libtinfo5': 'bb4d4d80720149692ea0d5bca1a5dac57737afe447810ce69dd4a95107121da5', 'libuuid1': 'c04350aa8dc1bd73712716f9826b0f02fa10b77058c990a406445020970c2eaa', 'mime-support': '98e05aa03538c5f182ed14cbb59cfe64b30592d77e602abd2442a9f1c72532b3', 'ncurses-bin': '336af3c372b6a7d083e6c6053670781369d8ae713fd098c9dab8fc5432458015', 'netbase': 'cbda1c8035cd1fe0b1fb09b456892c0bb868657bfe02da82f0b16207d391145e', 'openssl': 'c938fa9fb3a00e89a868e95c0faa76adafa0a53f1de122f22ccdfb4e4a074986', 'python3-distutils': 'f836b1e22923fa175c1968b9dbd916ae5639c9250e21bcfb88f9df2dc289f65c', 'python3.6-minimal': 'e30011c605816ab1d371c9f096caabaff8dabf87850207fd146aa05845b912c9', 'readline-common': '84cb3642c82114496d2fc17011db13655bd661cf4641098c03c168ddde367908', 'tar': '6bdbb90c9c073f8e8f92da231a2e553410ce397489f2f1f77d1ae8ddbd0c7bc4', 'tzdata': '8ff68141a56b3fe97588a4e8ee02de7dfdacf2abbd4c23ed9ea793ba181ee479', 'zlib1g': '2e6dafb986ee8ebbc4e1c344fab090a41710cab878fc9cd89336cdd1740518c5'}, sources=['http://us.archive.ubuntu.com/ubuntu bionic main universe', 'http://us.archive.ubuntu.com/ubuntu bionic-updates main universe', 'http://us.archive.ubuntu.com/ubuntu bionic-backports main universe', 'http://security.ubuntu.com/ubuntu bionic-security main universe'], urls=['http://us.archive.ubuntu.com/ubuntu/$(package_path)', 'http://security.ubuntu.com/ubuntu/$(package_path)', 'https://launchpad.net/ubuntu/+archive/primary/+files/$(package_file)'])
# Configuration file for the Sphinx documentation builder. project = 'wwt_api_client' author = 'Peter K. G. Williams' copyright = '2019 ' + author release = '0.1.0dev0' extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'sphinx_automodapi.automodapi', 'sphinx_automodapi.smart_resolver', 'numpydoc', ] master_doc = 'index' templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] numpydoc_class_members_toctree = False html_theme = 'alabaster' html_static_path = ['_static'] html_logo = 'images/logo.png'
project = 'wwt_api_client' author = 'Peter K. G. Williams' copyright = '2019 ' + author release = '0.1.0dev0' extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode', 'sphinx_automodapi.automodapi', 'sphinx_automodapi.smart_resolver', 'numpydoc'] master_doc = 'index' templates_path = ['_templates'] exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] numpydoc_class_members_toctree = False html_theme = 'alabaster' html_static_path = ['_static'] html_logo = 'images/logo.png'
class ConfigException(Exception): pass class AuthException(Exception): pass class AuthEngineFailedException(AuthException): pass class UnauthorizedAccountException(AuthException): pass class LockedUserException(UnauthorizedAccountException): pass class InvalidAuthEngineException(AuthException): pass class UserNotFoundException(AuthException): pass class NeedsOTPException(AuthException): pass class InvalidCredentialsException(AuthException): pass
class Configexception(Exception): pass class Authexception(Exception): pass class Authenginefailedexception(AuthException): pass class Unauthorizedaccountexception(AuthException): pass class Lockeduserexception(UnauthorizedAccountException): pass class Invalidauthengineexception(AuthException): pass class Usernotfoundexception(AuthException): pass class Needsotpexception(AuthException): pass class Invalidcredentialsexception(AuthException): pass
def tick(nums): """ Simulate one tick of passage of time nums is a list of timer counts of all fish """ # Iterate over a copy of nums as it will be modified within the loop for i, j in enumerate(nums[:]): if j == 0: nums[i] = 6 nums.append(8) else: nums[i] -= 1 return nums def part1(): nums = list(map(int, open("in.txt").read().strip().split(","))) for i in range(80): nums = tick(nums) print(len(nums)) part1()
def tick(nums): """ Simulate one tick of passage of time nums is a list of timer counts of all fish """ for (i, j) in enumerate(nums[:]): if j == 0: nums[i] = 6 nums.append(8) else: nums[i] -= 1 return nums def part1(): nums = list(map(int, open('in.txt').read().strip().split(','))) for i in range(80): nums = tick(nums) print(len(nums)) part1()
""" Copyright 2020 Tianshu AI Platform. 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. ============================================================= """ class FeatureHook(): def __init__(self, module): self.module = module self.feat_in = None self.feat_out = None self.register() def register(self): self._hook = self.module.register_forward_hook(self.hook_fn_forward) def remove(self): self._hook.remove() def hook_fn_forward(self, module, fea_in, fea_out): self.feat_in = fea_in[0] self.feat_out = fea_out
""" Copyright 2020 Tianshu AI Platform. 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. ============================================================= """ class Featurehook: def __init__(self, module): self.module = module self.feat_in = None self.feat_out = None self.register() def register(self): self._hook = self.module.register_forward_hook(self.hook_fn_forward) def remove(self): self._hook.remove() def hook_fn_forward(self, module, fea_in, fea_out): self.feat_in = fea_in[0] self.feat_out = fea_out
class Metadata: name: str def __init__(self, name: str): self.name = name def to_dict(self) -> dict: return { 'name': self.name, } class ConfigMap: metadata: Metadata data: dict apiVersion: str = 'v1' kind: str = 'ConfigMap' def __init__( self, metadata: Metadata, data: dict, apiVersion: str = 'v1', kind: str = 'ConfigMap', ): self.metadata = metadata self.data = data self.apiVersion = apiVersion self.kind = kind def to_dict(self) -> dict: return { 'metadata': self.metadata.to_dict(), 'data': self.data, 'apiVersion': self.apiVersion, 'kind': self.kind, } configMap = ConfigMap( metadata=Metadata(name='the-map'), data={'altGreeting': 'Good Morning!', 'enableRisky': 'false'}, )
class Metadata: name: str def __init__(self, name: str): self.name = name def to_dict(self) -> dict: return {'name': self.name} class Configmap: metadata: Metadata data: dict api_version: str = 'v1' kind: str = 'ConfigMap' def __init__(self, metadata: Metadata, data: dict, apiVersion: str='v1', kind: str='ConfigMap'): self.metadata = metadata self.data = data self.apiVersion = apiVersion self.kind = kind def to_dict(self) -> dict: return {'metadata': self.metadata.to_dict(), 'data': self.data, 'apiVersion': self.apiVersion, 'kind': self.kind} config_map = config_map(metadata=metadata(name='the-map'), data={'altGreeting': 'Good Morning!', 'enableRisky': 'false'})
# Creating a class # Method 1 # class teddy: # quantity = 200 # print(teddy.quantity) # Method 2 class teddy: quantity = 200 quality = 90 obteddy = teddy() print(obteddy.quality) print(obteddy.quantity)
class Teddy: quantity = 200 quality = 90 obteddy = teddy() print(obteddy.quality) print(obteddy.quantity)
# -*- coding: utf-8 -*- """ Created on Tue Oct 9 20:09:13 2018 @author: JinJheng """ a=input() b=input() c=input() d=input() print('|%10s %10s|' %(a,b)) print('|%10s %10s|' %(c,d)) print('|%-10s %-10s|' %(a,b)) print('|%-10s %-10s|' %(c,d))
""" Created on Tue Oct 9 20:09:13 2018 @author: JinJheng """ a = input() b = input() c = input() d = input() print('|%10s %10s|' % (a, b)) print('|%10s %10s|' % (c, d)) print('|%-10s %-10s|' % (a, b)) print('|%-10s %-10s|' % (c, d))
num = 10 num = 20 num = 30 num = 40 num = 50 num = 66 num = 60 num = 70
num = 10 num = 20 num = 30 num = 40 num = 50 num = 66 num = 60 num = 70
def create_HMM(switch_prob=0.1, noise_level=1e-1, startprob=[1.0, 0.0]): """Create an HMM with binary state variable and 1D Gaussian measurements The probability to switch to the other state is `switch_prob`. Two measurement models have mean 1.0 and -1.0 respectively. `noise_level` specifies the standard deviation of the measurement models. Args: switch_prob (float): probability to jump to the other state noise_level (float): standard deviation of measurement models. Same for two components Returns: model (GaussianHMM instance): the described HMM """ n_components = 2 startprob_vec = np.asarray(startprob) # STEP 1: Transition probabilities transmat_mat = np.array([[1. - switch_prob, switch_prob], [switch_prob, 1. - switch_prob]]) # # np.array([[...], [...]]) # STEP 2: Measurement probabilities # Mean measurements for each state means_vec = np.array([-1.0, 1.0]) # Noise for each state vars_vec = np.ones(2) * noise_level * noise_level # Initialize model model = GaussianHMM1D( startprob = startprob_vec, transmat = transmat_mat, means = means_vec, vars = vars_vec, n_components = n_components ) return model def sample(model, T): """Generate samples from the given HMM Args: model (GaussianHMM1D): the HMM with Gaussian measurement T (int): number of time steps to sample Returns: M (numpy vector): the series of measurements S (numpy vector): the series of latent states """ # Initialize S and M S = np.zeros((T,),dtype=int) M = np.zeros((T,)) # Calculate initial state S[0] = np.random.choice([0,1],p=model.startprob) # Latent state at time `t` depends on `t-1` and the corresponding transition probabilities to other states for t in range(1,T): # STEP 3: Get vector of probabilities for all possible `S[t]` given a particular `S[t-1]` transition_vector = model.transmat[S[t-1],:] # Calculate latent state at time `t` S[t] = np.random.choice([0,1],p=transition_vector) # Calculate measurements conditioned on the latent states # Since measurements are independent of each other given the latent states, we could calculate them as a batch means = model.means[S] scales = np.sqrt(model.vars[S]) M = np.random.normal(loc=means, scale=scales, size=(T,)) return M, S # Set random seed np.random.seed(101) # Set parameters of HMM T = 100 switch_prob = 0.1 noise_level = 2.0 # Create HMM model = create_HMM(switch_prob=switch_prob, noise_level=noise_level) # Sample from HMM M, S = sample(model,T) assert M.shape==(T,) assert S.shape==(T,) # Print values print(M[:5]) print(S[:5])
def create_hmm(switch_prob=0.1, noise_level=0.1, startprob=[1.0, 0.0]): """Create an HMM with binary state variable and 1D Gaussian measurements The probability to switch to the other state is `switch_prob`. Two measurement models have mean 1.0 and -1.0 respectively. `noise_level` specifies the standard deviation of the measurement models. Args: switch_prob (float): probability to jump to the other state noise_level (float): standard deviation of measurement models. Same for two components Returns: model (GaussianHMM instance): the described HMM """ n_components = 2 startprob_vec = np.asarray(startprob) transmat_mat = np.array([[1.0 - switch_prob, switch_prob], [switch_prob, 1.0 - switch_prob]]) means_vec = np.array([-1.0, 1.0]) vars_vec = np.ones(2) * noise_level * noise_level model = gaussian_hmm1_d(startprob=startprob_vec, transmat=transmat_mat, means=means_vec, vars=vars_vec, n_components=n_components) return model def sample(model, T): """Generate samples from the given HMM Args: model (GaussianHMM1D): the HMM with Gaussian measurement T (int): number of time steps to sample Returns: M (numpy vector): the series of measurements S (numpy vector): the series of latent states """ s = np.zeros((T,), dtype=int) m = np.zeros((T,)) S[0] = np.random.choice([0, 1], p=model.startprob) for t in range(1, T): transition_vector = model.transmat[S[t - 1], :] S[t] = np.random.choice([0, 1], p=transition_vector) means = model.means[S] scales = np.sqrt(model.vars[S]) m = np.random.normal(loc=means, scale=scales, size=(T,)) return (M, S) np.random.seed(101) t = 100 switch_prob = 0.1 noise_level = 2.0 model = create_hmm(switch_prob=switch_prob, noise_level=noise_level) (m, s) = sample(model, T) assert M.shape == (T,) assert S.shape == (T,) print(M[:5]) print(S[:5])
#!/usr/bin/env python3 def find_distance(matrix, key): """Find the distance of the nearest key for each cell """ if not matrix or not matrix[0]: return matrix rows, cols = len(matrix), len(matrix[0]) delta = [(-1, 0), (1, 0), (0, -1), (0, 1)] def shortest(matrix, row, col, key): q = [(row, col, 0)] while q: r, c, d = q.pop(0) if matrix[r][c] == key: return d else: for i, j in delta: nr, nc = r+i, c+j if 0 <= nr < rows and 0 <= nc < cols: q.append((nr, nc, d+1)) result = [[0] * cols for _ in range(rows)] for r in range(rows): for c in range(cols): result[r][c] = shortest(matrix, r, c, key) return result if __name__ == '__main__': matrix = [input().split() for _ in range(int(input()))] print(find_distance(matrix, '0'))
def find_distance(matrix, key): """Find the distance of the nearest key for each cell """ if not matrix or not matrix[0]: return matrix (rows, cols) = (len(matrix), len(matrix[0])) delta = [(-1, 0), (1, 0), (0, -1), (0, 1)] def shortest(matrix, row, col, key): q = [(row, col, 0)] while q: (r, c, d) = q.pop(0) if matrix[r][c] == key: return d else: for (i, j) in delta: (nr, nc) = (r + i, c + j) if 0 <= nr < rows and 0 <= nc < cols: q.append((nr, nc, d + 1)) result = [[0] * cols for _ in range(rows)] for r in range(rows): for c in range(cols): result[r][c] = shortest(matrix, r, c, key) return result if __name__ == '__main__': matrix = [input().split() for _ in range(int(input()))] print(find_distance(matrix, '0'))
""" Utilities for the :class:`~django_mri.analysis.interfaces.fmriprep.fmriprep.FmriPrep` interface. """ #: Command line template to format for execution. COMMAND = "singularity run -e {security_options} -B {bids_parent}:/work,{destination_parent}:/output,{freesurfer_license}:/fs_license {singularity_image_root}/fmriprep-{version}.simg /work/{bids_name} /output/{destination_name} {analysis_level} --fs-license-file /fs_license" # noqa: E501 #: Default FreeSurfer home directory. FREESURFER_HOME: str = "/usr/local/freesurfer" #: "Flags" indicate parameters that are specified without any arguments, i.e. #: they are a switch for some binary configuration. FLAGS = ( "skip_bids_validation", "low-mem", "anat-only", "boilerplate_only", "md-only-boilerplate", "error-on-aroma-warnings", "longitudinal", "force-bbr", "force-no-bbr", "medial-surface-nan", "use-aroma", "return-all-components", "skull-strip-fixed-seed", "fmap-bspline", "fmap-no-demean", "use-syn-sdc", "force-syn", "no-submm-recon", "fs-no-reconall", "clean-workdir", "resource-monitor", "reports-only", "write-graph", "stop-on-first-crash", "notrack", "sloppy", ) #: Dictionary of expeected outputs by key. OUTPUTS = { # Anatomicals "native_T1w": ["fmriprep", "anat", "desc-preproc_T1w.nii.gz"], "native_brain_mask": ["fmriprep", "anat", "desc-brain_mask.nii.gz"], "native_parcellation": ["fmriprep", "anat", "*dseg.nii.gz"], "native_csf": ["fmriprep", "anat", "label-CSF_probseg.nii.gz"], "native_gm": ["fmriprep", "anat", "label-GM_probseg.nii.gz"], "native_wm": ["fmriprep", "anat", "label-WM_probseg.nii.gz"], "standard_T1w": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_desc-preproc_T1w.nii.gz", ], "standard_brain_mask": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz", ], "standard_parcellation": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_dseg.nii.gz", ], "standard_csf": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_label-CSF_probseg.nii.gz", ], "standard_gm": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_label-GM_probseg.nii.gz", ], "standard_wm": [ "fmriprep", "anat", "space-MNI152NLin2009cAsym_label-WM_probseg.nii.gz", ], "native_to_mni_transform": [ "fmriprep", "anat", "from-T1w_to-MNI152NLin2009cAsym_mode-image_xfm.h5", ], "mni_to_native_transform": [ "fmriprep", "anat", "from-MNI152NLin2009cAsym_to-T1w_mode-image_xfm.h5", ], "native_to_fsnative_transform": [ "fmriprep", "anat", "from-T1w_to-fsnative_mode-image_xfm.txt", ], "fsnative_to_native_transform": [ "fmriprep", "anat", "from-fsnative_to-T1w_mode-image_xfm.txt", ], "smoothwm": ["fmriprep", "anat", "hemi-*_smoothwm.surf.gii"], "pial": ["fmriprep", "anat", "hemi-*_pial.surf.gii"], "midthickness": ["fmriprep", "anat", "hemi-*_midthickness.surf.gii"], "inflated": ["fmriprep", "anat", "hemi-*_inflated.surf.gii"], # Functionals "native_boldref": ["fmriprep", "func", "*space-T1w_desc-boldref.nii.gz"], "native_func_brain_mask": [ "fmriprep", "func", "*space-T1w_desc-brain_mask.nii.gz", ], "native_preproc_bold": [ "fmriprep", "func", "*space-T1w_desc-preproc_bold.nii.gz", ], "native_aparc_bold": [ "fmriprep", "func", "*space-T1w_desc-aparcaseg_dseg.nii.gz", ], "native_aseg_bold": [ "fmriprep", "func", "*space-T1w_desc-aseg_dseg.nii.gz", ], "standard_boldref": [ "fmriprep", "func", "*space-MNI152NLin2009cAsym_desc-boldref.nii.gz", ], "standard_func_brain_mask": [ "fmriprep", "func", "*space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz", ], "standard_preproc_bold": [ "fmriprep", "func", "*space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz", ], "standard_aparc_bold": [ "fmriprep", "func", "*space-MNI152NLin2009cAsym_desc-aparcaseg_dseg.nii.gz", ], "standard_aseg_bold": [ "fmriprep", "func", "*space-MNI152NLin2009cAsym_desc-aseg_dseg.nii.gz", ], "confounds_tsv": ["fmriprep", "func", "*desc-confound_timeseries.tsv"], "confounds_json": ["fmriprep", "func", "*desc-confound_timeseries.json"], "freesurfer_T1": ["freesurfer", "mri", "T1.mgz"], "freesurfer_rawavg": ["freesurfer", "mri", "rawavg.mgz"], "freesurfer_orig": ["freesurfer", "mri", "orig.mgz"], "freesurfer_nu": ["freesurfer", "mri", "nu.mgz"], "freesurfer_norm": ["freesurfer", "mri", "norm.mgz"], "freesurfer_aseg": ["freesurfer", "mri", "aseg.mgz"], "freesurfer_aseg_stats": ["freesurfer", "stats", "aseg.stats"], "freesurfer_brain": ["freesurfer", "mri", "brain.mgz"], "freesurfer_brainmask": ["freesurfer", "mri", "brainmask.mgz"], "freesurfer_filled": ["freesurfer", "mri", "filled.mgz"], "freesurfer_wm": ["freesurfer", "mri", "wm.mgz"], "freesurfer_wmparc": ["freesurfer", "mri", "wmparc.mgz"], "freesurfer_wmparc_stats": ["freesurfer", "stats", "wmparc.stats"], "freesurfer_BA_stats": ["freesurfer", "stats", ".BA_exvivo*.stats"], # TODO: Finish outputs dictionary. }
""" Utilities for the :class:`~django_mri.analysis.interfaces.fmriprep.fmriprep.FmriPrep` interface. """ command = 'singularity run -e {security_options} -B {bids_parent}:/work,{destination_parent}:/output,{freesurfer_license}:/fs_license {singularity_image_root}/fmriprep-{version}.simg /work/{bids_name} /output/{destination_name} {analysis_level} --fs-license-file /fs_license' freesurfer_home: str = '/usr/local/freesurfer' flags = ('skip_bids_validation', 'low-mem', 'anat-only', 'boilerplate_only', 'md-only-boilerplate', 'error-on-aroma-warnings', 'longitudinal', 'force-bbr', 'force-no-bbr', 'medial-surface-nan', 'use-aroma', 'return-all-components', 'skull-strip-fixed-seed', 'fmap-bspline', 'fmap-no-demean', 'use-syn-sdc', 'force-syn', 'no-submm-recon', 'fs-no-reconall', 'clean-workdir', 'resource-monitor', 'reports-only', 'write-graph', 'stop-on-first-crash', 'notrack', 'sloppy') outputs = {'native_T1w': ['fmriprep', 'anat', 'desc-preproc_T1w.nii.gz'], 'native_brain_mask': ['fmriprep', 'anat', 'desc-brain_mask.nii.gz'], 'native_parcellation': ['fmriprep', 'anat', '*dseg.nii.gz'], 'native_csf': ['fmriprep', 'anat', 'label-CSF_probseg.nii.gz'], 'native_gm': ['fmriprep', 'anat', 'label-GM_probseg.nii.gz'], 'native_wm': ['fmriprep', 'anat', 'label-WM_probseg.nii.gz'], 'standard_T1w': ['fmriprep', 'anat', 'space-MNI152NLin2009cAsym_desc-preproc_T1w.nii.gz'], 'standard_brain_mask': ['fmriprep', 'anat', 'space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz'], 'standard_parcellation': ['fmriprep', 'anat', 'space-MNI152NLin2009cAsym_dseg.nii.gz'], 'standard_csf': ['fmriprep', 'anat', 'space-MNI152NLin2009cAsym_label-CSF_probseg.nii.gz'], 'standard_gm': ['fmriprep', 'anat', 'space-MNI152NLin2009cAsym_label-GM_probseg.nii.gz'], 'standard_wm': ['fmriprep', 'anat', 'space-MNI152NLin2009cAsym_label-WM_probseg.nii.gz'], 'native_to_mni_transform': ['fmriprep', 'anat', 'from-T1w_to-MNI152NLin2009cAsym_mode-image_xfm.h5'], 'mni_to_native_transform': ['fmriprep', 'anat', 'from-MNI152NLin2009cAsym_to-T1w_mode-image_xfm.h5'], 'native_to_fsnative_transform': ['fmriprep', 'anat', 'from-T1w_to-fsnative_mode-image_xfm.txt'], 'fsnative_to_native_transform': ['fmriprep', 'anat', 'from-fsnative_to-T1w_mode-image_xfm.txt'], 'smoothwm': ['fmriprep', 'anat', 'hemi-*_smoothwm.surf.gii'], 'pial': ['fmriprep', 'anat', 'hemi-*_pial.surf.gii'], 'midthickness': ['fmriprep', 'anat', 'hemi-*_midthickness.surf.gii'], 'inflated': ['fmriprep', 'anat', 'hemi-*_inflated.surf.gii'], 'native_boldref': ['fmriprep', 'func', '*space-T1w_desc-boldref.nii.gz'], 'native_func_brain_mask': ['fmriprep', 'func', '*space-T1w_desc-brain_mask.nii.gz'], 'native_preproc_bold': ['fmriprep', 'func', '*space-T1w_desc-preproc_bold.nii.gz'], 'native_aparc_bold': ['fmriprep', 'func', '*space-T1w_desc-aparcaseg_dseg.nii.gz'], 'native_aseg_bold': ['fmriprep', 'func', '*space-T1w_desc-aseg_dseg.nii.gz'], 'standard_boldref': ['fmriprep', 'func', '*space-MNI152NLin2009cAsym_desc-boldref.nii.gz'], 'standard_func_brain_mask': ['fmriprep', 'func', '*space-MNI152NLin2009cAsym_desc-brain_mask.nii.gz'], 'standard_preproc_bold': ['fmriprep', 'func', '*space-MNI152NLin2009cAsym_desc-preproc_bold.nii.gz'], 'standard_aparc_bold': ['fmriprep', 'func', '*space-MNI152NLin2009cAsym_desc-aparcaseg_dseg.nii.gz'], 'standard_aseg_bold': ['fmriprep', 'func', '*space-MNI152NLin2009cAsym_desc-aseg_dseg.nii.gz'], 'confounds_tsv': ['fmriprep', 'func', '*desc-confound_timeseries.tsv'], 'confounds_json': ['fmriprep', 'func', '*desc-confound_timeseries.json'], 'freesurfer_T1': ['freesurfer', 'mri', 'T1.mgz'], 'freesurfer_rawavg': ['freesurfer', 'mri', 'rawavg.mgz'], 'freesurfer_orig': ['freesurfer', 'mri', 'orig.mgz'], 'freesurfer_nu': ['freesurfer', 'mri', 'nu.mgz'], 'freesurfer_norm': ['freesurfer', 'mri', 'norm.mgz'], 'freesurfer_aseg': ['freesurfer', 'mri', 'aseg.mgz'], 'freesurfer_aseg_stats': ['freesurfer', 'stats', 'aseg.stats'], 'freesurfer_brain': ['freesurfer', 'mri', 'brain.mgz'], 'freesurfer_brainmask': ['freesurfer', 'mri', 'brainmask.mgz'], 'freesurfer_filled': ['freesurfer', 'mri', 'filled.mgz'], 'freesurfer_wm': ['freesurfer', 'mri', 'wm.mgz'], 'freesurfer_wmparc': ['freesurfer', 'mri', 'wmparc.mgz'], 'freesurfer_wmparc_stats': ['freesurfer', 'stats', 'wmparc.stats'], 'freesurfer_BA_stats': ['freesurfer', 'stats', '.BA_exvivo*.stats']}
val = open('val.txt', encoding='UTF-8') out = open('out.txt', encoding='UTF-8') t = val.readline() a = out.readline() sum = 0 right = 0 while t and a: error = [] t = t.strip() a = a.strip() for i in range(len(t)): sum += 1 if t[i] == a[i]: right += 1 else: error.append(a[i]) print(t) print(a) print("wrong with {}", format(error)) t = val.readline() a = out.readline() print("right={}".format(right)) print("sum={}".format(sum)) print(right / sum)
val = open('val.txt', encoding='UTF-8') out = open('out.txt', encoding='UTF-8') t = val.readline() a = out.readline() sum = 0 right = 0 while t and a: error = [] t = t.strip() a = a.strip() for i in range(len(t)): sum += 1 if t[i] == a[i]: right += 1 else: error.append(a[i]) print(t) print(a) print('wrong with {}', format(error)) t = val.readline() a = out.readline() print('right={}'.format(right)) print('sum={}'.format(sum)) print(right / sum)
#!/usr/bin/env python3 @app.route('/api/v1/weight', methods=['GET']) def weight_v1(): conn = None try: params = config() conn = psycopg2.connect(**params) cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor) cur.execute("""SELECT * FROM weights WHERE child_id={};""".format(request.args['child_id'])) ans = cur.fetchall() if (len(ans) == 0): return jsonify({'code':204, 'name':'No content', 'key':''}) ans1 = [] for row in ans: ans1.append(dict(row)) return jsonify(ans1) except (Exception, psycopg2.DatabaseError) as error: return str(error) finally: if conn is not None: conn.close()
@app.route('/api/v1/weight', methods=['GET']) def weight_v1(): conn = None try: params = config() conn = psycopg2.connect(**params) cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor) cur.execute('SELECT * FROM weights WHERE child_id={};'.format(request.args['child_id'])) ans = cur.fetchall() if len(ans) == 0: return jsonify({'code': 204, 'name': 'No content', 'key': ''}) ans1 = [] for row in ans: ans1.append(dict(row)) return jsonify(ans1) except (Exception, psycopg2.DatabaseError) as error: return str(error) finally: if conn is not None: conn.close()
URL_FANTOIR = ( "https://www.collectivites-locales.gouv.fr/competences/la-mise-disposition-gratuite-du-fichier-des-" "voies-et-des-lieux-dits-fantoir" ) URL_DOCUMENTATION = "https://docs.3liz.org/QgisCadastrePlugin/"
url_fantoir = 'https://www.collectivites-locales.gouv.fr/competences/la-mise-disposition-gratuite-du-fichier-des-voies-et-des-lieux-dits-fantoir' url_documentation = 'https://docs.3liz.org/QgisCadastrePlugin/'
class JavascriptDebugRenderer: def __init__(self, debugger): self.debugger = debugger def render(self, meta=None): data = {} if meta is None: meta = [] for name, collector in self.debugger.collectors.items(): data.update({collector.name: collector.collect()}) return """ <div class="fixed inset-x bottom-0 h-72 bg-white border border-top border-gray-300 w-full overflow-auto" x-data="bar"> <nav class="relative z-0 flex divide-x divide-gray-300 bg-gray-100" aria-label="Tabs"> <template x-for="tab in tabs"> <!-- Current: "text-gray-900", Default: "text-gray-500 hover:text-gray-700" --> <!-- class="text-gray-500 hover:text-gray-700 group relative min-w-0 flex-1 overflow-hidden bg-white py-4 px-4 text-sm font-medium text-center hover:bg-gray-50 focus:z-10"> --> <a x-on:click="setTab(tab)" class="text-gray-700 cursor-pointer max-w-min group relative min-w-0 flex-1 overflow-hidden py-1 px-3 text-sm font-base text-center hover:bg-gray-50 focus:z-10" > <span x-text="tab"></span> <!-- <span aria-hidden="true" class="bg-red-500 absolute inset-x-0 bottom-0 h-0.5"></span> --> <span aria-hidden="true" class="absolute inset-x-0 bottom-0 h-0.5" :class="currentTab == tab ? 'bg-red-500' : 'bg-transparent'" ></span> </a> </template> </nav> <!-- content --> <div> <!-- TODO later: it will be html --> <template x-for="(object, index) in currentContent"> <div> <span x-html="object.html"></span> </div> </template> </div> </div> <script> document.addEventListener('alpine:init', () => { Alpine.data('bar', function () { return { rawData: {}, tabs: [], content: [], currentTab: this.$persist("python"), currentContent: "", init() { // TODO: Load JSON debugbar payload of last request this.getRequestData() }, async getRequestData(id = null) { //this.rawData = await (await fetch(`/_debugbar/${id}/`)).json(); this.rawData = await (await fetch("/_debugbar/")).json() this.tabs = this.rawData.collectors this.content = this.rawData.data this.currentContent = this.getTabContent(this.currentTab) }, setTab(tab) { this.currentTab = tab this.currentContent = this.getTabContent(tab) }, getTabContent(tab) { return this.content[tab].data } } }) }) </script> """
class Javascriptdebugrenderer: def __init__(self, debugger): self.debugger = debugger def render(self, meta=None): data = {} if meta is None: meta = [] for (name, collector) in self.debugger.collectors.items(): data.update({collector.name: collector.collect()}) return '\n <div class="fixed inset-x bottom-0 h-72 bg-white border border-top border-gray-300 w-full overflow-auto" x-data="bar">\n <nav class="relative z-0 flex divide-x divide-gray-300 bg-gray-100" aria-label="Tabs">\n <template x-for="tab in tabs">\n <!-- Current: "text-gray-900", Default: "text-gray-500 hover:text-gray-700" -->\n <!-- class="text-gray-500 hover:text-gray-700 group relative min-w-0 flex-1 overflow-hidden bg-white py-4 px-4 text-sm font-medium text-center hover:bg-gray-50 focus:z-10"> -->\n <a\n x-on:click="setTab(tab)"\n class="text-gray-700 cursor-pointer max-w-min group relative min-w-0 flex-1 overflow-hidden py-1 px-3 text-sm font-base text-center hover:bg-gray-50 focus:z-10"\n >\n <span x-text="tab"></span>\n <!-- <span aria-hidden="true" class="bg-red-500 absolute inset-x-0 bottom-0 h-0.5"></span> -->\n <span aria-hidden="true"\n class="absolute inset-x-0 bottom-0 h-0.5"\n :class="currentTab == tab ? \'bg-red-500\' : \'bg-transparent\'"\n ></span>\n </a>\n </template>\n </nav>\n <!-- content -->\n <div>\n <!-- TODO later: it will be html -->\n <template x-for="(object, index) in currentContent">\n <div>\n <span x-html="object.html"></span>\n </div>\n </template>\n </div>\n </div>\n\n <script>\n document.addEventListener(\'alpine:init\', () => {\n Alpine.data(\'bar\', function () {\n return {\n rawData: {},\n tabs: [],\n content: [],\n currentTab: this.$persist("python"),\n currentContent: "",\n init() {\n // TODO: Load JSON debugbar payload of last request\n this.getRequestData()\n },\n async getRequestData(id = null) {\n //this.rawData = await (await fetch(`/_debugbar/${id}/`)).json();\n this.rawData = await (await fetch("/_debugbar/")).json()\n this.tabs = this.rawData.collectors\n this.content = this.rawData.data\n\n this.currentContent = this.getTabContent(this.currentTab)\n },\n setTab(tab) {\n this.currentTab = tab\n this.currentContent = this.getTabContent(tab)\n },\n getTabContent(tab) {\n return this.content[tab].data\n }\n }\n })\n })\n </script>\n '
n = int(input('digite um numero: ')) if n%2 == 0: print('PAR') else: print('IMPAR')
n = int(input('digite um numero: ')) if n % 2 == 0: print('PAR') else: print('IMPAR')
ir_licenses = { 'names': { 'P': 'Pro', 'A': 'Class A', 'B': 'Class B', 'C': 'Class C', 'D': 'Class D', 'R': 'Rookie' }, 'bg_colors': { 'P': '#000000', 'A': '#0153DB', 'B': '#00C702', 'C': '#FEEC04', 'D': '#FC8A27', 'R': '#FC0706' }, 'colors': { 'P': '#FFFFFF', 'A': '#FFFFFF', 'B': '#FFFFFF', 'C': '#000000', 'D': '#000000', 'R': '#FFFFFF' } } content = { 'bg_colors': { 'owned': '#1E9E1E', 'missing': '#40474C', 'twitter': '#1DA1F2', 'github': '#333000', 'paypal': '#003087' }, 'colors': { 'normal': 'black', 'alt': '#DDDDDD', 'owned': 'black', 'missing': '#DDDDDD', 'twitter': '#FFFFFF', 'github': '#FAFAFA', 'paypal': '#009CDE' } }
ir_licenses = {'names': {'P': 'Pro', 'A': 'Class A', 'B': 'Class B', 'C': 'Class C', 'D': 'Class D', 'R': 'Rookie'}, 'bg_colors': {'P': '#000000', 'A': '#0153DB', 'B': '#00C702', 'C': '#FEEC04', 'D': '#FC8A27', 'R': '#FC0706'}, 'colors': {'P': '#FFFFFF', 'A': '#FFFFFF', 'B': '#FFFFFF', 'C': '#000000', 'D': '#000000', 'R': '#FFFFFF'}} content = {'bg_colors': {'owned': '#1E9E1E', 'missing': '#40474C', 'twitter': '#1DA1F2', 'github': '#333000', 'paypal': '#003087'}, 'colors': {'normal': 'black', 'alt': '#DDDDDD', 'owned': 'black', 'missing': '#DDDDDD', 'twitter': '#FFFFFF', 'github': '#FAFAFA', 'paypal': '#009CDE'}}
pkg_dnf = { 'nfs-utils': {}, 'libnfsidmap': {}, } svc_systemd = { 'nfs-server': { 'needs': ['pkg_dnf:nfs-utils'], }, 'rpcbind': { 'needs': ['pkg_dnf:nfs-utils'], }, 'rpc-statd': { 'needs': ['pkg_dnf:nfs-utils'], }, 'nfs-idmapd': { 'needs': ['pkg_dnf:nfs-utils'], }, } files = {} actions = { 'nfs_export': { 'command': 'exportfs -a', 'triggered': True, 'needs': ['pkg_dnf:nfs-utils'], }, } for export in node.metadata['nfs-server']['exports']: files['/etc/exports.d/{}'.format(export['alias'])] = { 'source': 'template', 'mode': '0644', 'content_type': 'mako', 'context': { 'export': export, }, 'needs': ['pkg_dnf:nfs-utils'], 'triggers': ['action:nfs_export', 'svc_systemd:nfs-server:restart', 'svc_systemd:rpcbind:restart'], } if node.has_bundle('firewalld'): if node.metadata.get('nfs-server', {}).get('firewalld_permitted_zones'): for zone in node.metadata.get('nfs-server', {}).get('firewalld_permitted_zones'): actions['firewalld_add_nfs_zone_{}'.format(zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=nfs'.format(zone), 'unless': 'firewall-cmd --zone={} --list-services | grep nfs'.format(zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_mountd_zone_{}'.format(zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=mountd'.format(zone), 'unless': 'firewall-cmd --zone={} --list-services | grep mountd'.format(zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_rpc-bind_zone_{}'.format(zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=rpc-bind'.format(zone), 'unless': 'firewall-cmd --zone={} --list-services | grep rpc-bind'.format(zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } elif node.metadata.get('firewalld', {}).get('default_zone'): default_zone = node.metadata.get('firewalld', {}).get('default_zone') actions['firewalld_add_nfs_zone_{}'.format(default_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=nfs'.format(default_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep nfs'.format(default_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_mountd_zone_{}'.format(default_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=mountd'.format(default_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep mountd'.format(default_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_rpc-bind_zone_{}'.format(default_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=rpc-bind'.format(default_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep rpc-bind'.format(default_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } elif node.metadata.get('firewalld', {}).get('custom_zones', False): for interface in node.metadata['interfaces']: custom_zone = node.metadata.get('interfaces', {}).get(interface).get('firewalld_zone') actions['firewalld_add_nfs_zone_{}'.format(custom_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=nfs'.format(custom_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep nfs'.format(custom_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_mountd_zone_{}'.format(custom_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=mountd'.format(custom_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep mountd'.format(custom_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_rpc-bind_zone_{}'.format(custom_zone)] = { 'command': 'firewall-cmd --permanent --zone={} --add-service=rpc-bind'.format(custom_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep rpc-bind'.format(custom_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } else: actions['firewalld_add_nfs'] = { 'command': 'firewall-cmd --permanent --add-service=nfs', 'unless': 'firewall-cmd --list-services | grep nfs', 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_mountd'] = { 'command': 'firewall-cmd --permanent --add-service=mountd', 'unless': 'firewall-cmd --list-services | grep mountd', 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], } actions['firewalld_add_rpc-bind'] = { 'command': 'firewall-cmd --permanent --add-service=rpc-bind', 'unless': 'firewall-cmd --list-services | grep rpc-bind', 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload'], }
pkg_dnf = {'nfs-utils': {}, 'libnfsidmap': {}} svc_systemd = {'nfs-server': {'needs': ['pkg_dnf:nfs-utils']}, 'rpcbind': {'needs': ['pkg_dnf:nfs-utils']}, 'rpc-statd': {'needs': ['pkg_dnf:nfs-utils']}, 'nfs-idmapd': {'needs': ['pkg_dnf:nfs-utils']}} files = {} actions = {'nfs_export': {'command': 'exportfs -a', 'triggered': True, 'needs': ['pkg_dnf:nfs-utils']}} for export in node.metadata['nfs-server']['exports']: files['/etc/exports.d/{}'.format(export['alias'])] = {'source': 'template', 'mode': '0644', 'content_type': 'mako', 'context': {'export': export}, 'needs': ['pkg_dnf:nfs-utils'], 'triggers': ['action:nfs_export', 'svc_systemd:nfs-server:restart', 'svc_systemd:rpcbind:restart']} if node.has_bundle('firewalld'): if node.metadata.get('nfs-server', {}).get('firewalld_permitted_zones'): for zone in node.metadata.get('nfs-server', {}).get('firewalld_permitted_zones'): actions['firewalld_add_nfs_zone_{}'.format(zone)] = {'command': 'firewall-cmd --permanent --zone={} --add-service=nfs'.format(zone), 'unless': 'firewall-cmd --zone={} --list-services | grep nfs'.format(zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} actions['firewalld_add_mountd_zone_{}'.format(zone)] = {'command': 'firewall-cmd --permanent --zone={} --add-service=mountd'.format(zone), 'unless': 'firewall-cmd --zone={} --list-services | grep mountd'.format(zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} actions['firewalld_add_rpc-bind_zone_{}'.format(zone)] = {'command': 'firewall-cmd --permanent --zone={} --add-service=rpc-bind'.format(zone), 'unless': 'firewall-cmd --zone={} --list-services | grep rpc-bind'.format(zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} elif node.metadata.get('firewalld', {}).get('default_zone'): default_zone = node.metadata.get('firewalld', {}).get('default_zone') actions['firewalld_add_nfs_zone_{}'.format(default_zone)] = {'command': 'firewall-cmd --permanent --zone={} --add-service=nfs'.format(default_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep nfs'.format(default_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} actions['firewalld_add_mountd_zone_{}'.format(default_zone)] = {'command': 'firewall-cmd --permanent --zone={} --add-service=mountd'.format(default_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep mountd'.format(default_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} actions['firewalld_add_rpc-bind_zone_{}'.format(default_zone)] = {'command': 'firewall-cmd --permanent --zone={} --add-service=rpc-bind'.format(default_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep rpc-bind'.format(default_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} elif node.metadata.get('firewalld', {}).get('custom_zones', False): for interface in node.metadata['interfaces']: custom_zone = node.metadata.get('interfaces', {}).get(interface).get('firewalld_zone') actions['firewalld_add_nfs_zone_{}'.format(custom_zone)] = {'command': 'firewall-cmd --permanent --zone={} --add-service=nfs'.format(custom_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep nfs'.format(custom_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} actions['firewalld_add_mountd_zone_{}'.format(custom_zone)] = {'command': 'firewall-cmd --permanent --zone={} --add-service=mountd'.format(custom_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep mountd'.format(custom_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} actions['firewalld_add_rpc-bind_zone_{}'.format(custom_zone)] = {'command': 'firewall-cmd --permanent --zone={} --add-service=rpc-bind'.format(custom_zone), 'unless': 'firewall-cmd --zone={} --list-services | grep rpc-bind'.format(custom_zone), 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} else: actions['firewalld_add_nfs'] = {'command': 'firewall-cmd --permanent --add-service=nfs', 'unless': 'firewall-cmd --list-services | grep nfs', 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} actions['firewalld_add_mountd'] = {'command': 'firewall-cmd --permanent --add-service=mountd', 'unless': 'firewall-cmd --list-services | grep mountd', 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']} actions['firewalld_add_rpc-bind'] = {'command': 'firewall-cmd --permanent --add-service=rpc-bind', 'unless': 'firewall-cmd --list-services | grep rpc-bind', 'cascade_skip': False, 'needs': ['pkg_dnf:firewalld'], 'triggers': ['action:firewalld_reload']}
class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ m, q, n = len(A), len(B), len(B[0]) # C = [[0] * n] * m C = [[0] * n for _ in range(m)] for i in range(m): for k in range(q): if A[i][k]: for j in range(n): if B[k][j]: C[i][j] += A[i][k] * B[k][j] return C
class Solution(object): def multiply(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: List[List[int]] """ (m, q, n) = (len(A), len(B), len(B[0])) c = [[0] * n for _ in range(m)] for i in range(m): for k in range(q): if A[i][k]: for j in range(n): if B[k][j]: C[i][j] += A[i][k] * B[k][j] return C
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here n, q = map(int, input().strip().split()) a = list(map(int, input().strip().split())) for _ in range(q): x, y = map(int, input().strip().split()) if x == y: print(0) else: ans = n - 1 matched_idx = init_idx = None for i in range(n): if a[i] == x or a[i] == y: if matched_idx is None: matched_idx = init_idx = i else: if a[i] != a[matched_idx]: ans = min(ans, (i - matched_idx) // 2) matched_idx = i if a[init_idx] != a[matched_idx]: ans = min(ans, (init_idx - (matched_idx - n)) // 2) print(ans)
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ (n, q) = map(int, input().strip().split()) a = list(map(int, input().strip().split())) for _ in range(q): (x, y) = map(int, input().strip().split()) if x == y: print(0) else: ans = n - 1 matched_idx = init_idx = None for i in range(n): if a[i] == x or a[i] == y: if matched_idx is None: matched_idx = init_idx = i else: if a[i] != a[matched_idx]: ans = min(ans, (i - matched_idx) // 2) matched_idx = i if a[init_idx] != a[matched_idx]: ans = min(ans, (init_idx - (matched_idx - n)) // 2) print(ans)
# FIXME need to figure generation of bytecode class Scenario: STAGES = [ {"name": "install", "path": "build/{version}/cast_to_short-{version}.cap",}, { "name": "send", "comment": "READMEM APDU", "payload": "0xA0 0xB0 0x01 0x00 0x00", "optional": False, }, ]
class Scenario: stages = [{'name': 'install', 'path': 'build/{version}/cast_to_short-{version}.cap'}, {'name': 'send', 'comment': 'READMEM APDU', 'payload': '0xA0 0xB0 0x01 0x00\t0x00', 'optional': False}]
class SalesforceRouter(object): """ A router to control all database operations on models in the salesforce application. """ def db_for_read(self, model, **hints): """ Attempts to read salesforce models go to salesforce. """ if model._meta.app_label == 'salesforce': return 'salesforce' return None def db_for_write(self, model, **hints): """ Attempts to write salesforce models go to salesforce. """ if model._meta.app_label == 'salesforce': return 'salesforce' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the salesforce app is involved. """ if obj1._meta.app_label == 'salesforce' or \ obj2._meta.app_label == 'salesforce': return True return None def allow_migrate(self, db, model): """ Make sure the salesforce app only appears in the 'salesforce' database. """ if db == 'salesforce': return False elif model._meta.app_label == 'salesforce': return False return None
class Salesforcerouter(object): """ A router to control all database operations on models in the salesforce application. """ def db_for_read(self, model, **hints): """ Attempts to read salesforce models go to salesforce. """ if model._meta.app_label == 'salesforce': return 'salesforce' return None def db_for_write(self, model, **hints): """ Attempts to write salesforce models go to salesforce. """ if model._meta.app_label == 'salesforce': return 'salesforce' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the salesforce app is involved. """ if obj1._meta.app_label == 'salesforce' or obj2._meta.app_label == 'salesforce': return True return None def allow_migrate(self, db, model): """ Make sure the salesforce app only appears in the 'salesforce' database. """ if db == 'salesforce': return False elif model._meta.app_label == 'salesforce': return False return None
class Solution: def calPoints(self, ops: List[str]) -> int: arr = [] for op in ops: #print(arr) if op.isdigit() or op[0] == '-': arr.append(int(op)) elif op == 'C' and arr: arr.pop() elif op == 'D' and arr: arr.append(arr[-1] * 2) elif len(arr) >= 2: arr.append(arr[-1] + arr[-2]) #print(arr) return sum(arr)
class Solution: def cal_points(self, ops: List[str]) -> int: arr = [] for op in ops: if op.isdigit() or op[0] == '-': arr.append(int(op)) elif op == 'C' and arr: arr.pop() elif op == 'D' and arr: arr.append(arr[-1] * 2) elif len(arr) >= 2: arr.append(arr[-1] + arr[-2]) return sum(arr)
# 153. Find Minimum in Rotated Sorted Array class Solution(object): global find_min_helper def find_min_helper(nums,left,right): # base case: if left >= right, return the first element if left >= right: return nums[0] # get middle element mid = (left+right)/2 # check if mid < right and mid element > mid+1 if mid < right and nums[mid] > nums[mid+1]: # return mid+1 element return nums[mid+1] # check if mid > left and mid element < mid-1 element if mid > left and nums[mid] < nums[mid-1]: return nums[mid] # check if mid < right and mid element < mid+1 if nums[mid] < nums[right]: # return function(nums,mid+1,right) return find_min_helper(nums,left,mid-1) # return function(nums,left, mid) return find_min_helper(nums,mid+1,right) def findMin(self, nums): # if nums length is 1, return first element if len(nums) == 1: return nums[0] if len(nums) == 2: return min(nums) # return the helper function (log n) binary search return find_min_helper(nums,0,len(nums)-1)
class Solution(object): global find_min_helper def find_min_helper(nums, left, right): if left >= right: return nums[0] mid = (left + right) / 2 if mid < right and nums[mid] > nums[mid + 1]: return nums[mid + 1] if mid > left and nums[mid] < nums[mid - 1]: return nums[mid] if nums[mid] < nums[right]: return find_min_helper(nums, left, mid - 1) return find_min_helper(nums, mid + 1, right) def find_min(self, nums): if len(nums) == 1: return nums[0] if len(nums) == 2: return min(nums) return find_min_helper(nums, 0, len(nums) - 1)
# Configuration file for ipython. #------------------------------------------------------------------------------ # InteractiveShellApp(Configurable) configuration #------------------------------------------------------------------------------ ## lines of code to run at IPython startup. c.InteractiveShellApp.exec_lines = ['%load_ext autoreload', '%autoreload 2'] ## A list of dotted module names of IPython extensions to load. c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%load_ext autoreload', '%autoreload 2'] c.InteractiveShellApp.extensions = ['autoreload']
#!/usr/bin/env python3 size_of_grp = 5 inp_list = "1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2".split() set_l = set(inp_list) cap_room = "" for element in set_l: inp_list.remove(element) if not element in inp_list: cap_room = element break print(int(cap_room))
size_of_grp = 5 inp_list = '1 2 3 6 5 4 4 2 5 3 6 1 6 5 3 2 4 1 2 5 1 4 3 6 8 4 3 1 5 6 2'.split() set_l = set(inp_list) cap_room = '' for element in set_l: inp_list.remove(element) if not element in inp_list: cap_room = element break print(int(cap_room))
class InferErr(Exception): def __init__(self, e): self.code = 1 self.message = "Inference Error" super().__init__(self.message, str(e)) def MiB(val): return val * 1 << 20 def GiB(val): return val * 1 << 30 class HostDeviceMem(object): def __init__(self, host_mem, device_mem): self.host = host_mem self.device = device_mem def __str__(self): return "Host:\n" + str(self.host) + "\nDevice:\n" + str(self.device) def __repr__(self): return self.__str__()
class Infererr(Exception): def __init__(self, e): self.code = 1 self.message = 'Inference Error' super().__init__(self.message, str(e)) def mi_b(val): return val * 1 << 20 def gi_b(val): return val * 1 << 30 class Hostdevicemem(object): def __init__(self, host_mem, device_mem): self.host = host_mem self.device = device_mem def __str__(self): return 'Host:\n' + str(self.host) + '\nDevice:\n' + str(self.device) def __repr__(self): return self.__str__()
GPU_ID = 0 BATCH_SIZE = 64 VAL_BATCH_SIZE = 100 NUM_OUTPUT_UNITS = 3000 # This is the answer vocabulary size MAX_WORDS_IN_QUESTION = 15 MAX_WORDS_IN_EXP = 36 MAX_ITERATIONS = 50000 PRINT_INTERVAL = 100 # what data to use for training TRAIN_DATA_SPLITS = 'train' # what data to use for the vocabulary QUESTION_VOCAB_SPACE = 'train' ANSWER_VOCAB_SPACE = 'train' EXP_VOCAB_SPACE = 'train' # VQA pretrained model VQA_PRETRAINED = 'PATH_TO_PRETRAINED_VQA_MODEL.caffemodel' # location of the data VQA_PREFIX = './VQA-X' DATA_PATHS = { 'train': { 'ques_file': VQA_PREFIX + '/Questions/v2_OpenEnded_mscoco_train2014_questions.json', 'ans_file': VQA_PREFIX + '/Annotations/v2_mscoco_train2014_annotations.json', 'exp_file': VQA_PREFIX + '/Annotations/train_exp_anno.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/train2014/COCO_train2014_' }, 'val': { 'ques_file': VQA_PREFIX + '/Questions/v2_OpenEnded_mscoco_val2014_questions.json', 'ans_file': VQA_PREFIX + '/Annotations/v2_mscoco_val2014_annotations.json', 'exp_file': VQA_PREFIX + '/Annotations/val_exp_anno.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/val2014/COCO_val2014_' }, 'test-dev': { 'ques_file': VQA_PREFIX + '/Questions/OpenEnded_mscoco_test-dev2015_questions.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/test2015/COCO_test2015_' }, 'test': { 'ques_file': VQA_PREFIX + '/Questions/OpenEnded_mscoco_test2015_questions.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/test2015/COCO_test2015_' } }
gpu_id = 0 batch_size = 64 val_batch_size = 100 num_output_units = 3000 max_words_in_question = 15 max_words_in_exp = 36 max_iterations = 50000 print_interval = 100 train_data_splits = 'train' question_vocab_space = 'train' answer_vocab_space = 'train' exp_vocab_space = 'train' vqa_pretrained = 'PATH_TO_PRETRAINED_VQA_MODEL.caffemodel' vqa_prefix = './VQA-X' data_paths = {'train': {'ques_file': VQA_PREFIX + '/Questions/v2_OpenEnded_mscoco_train2014_questions.json', 'ans_file': VQA_PREFIX + '/Annotations/v2_mscoco_train2014_annotations.json', 'exp_file': VQA_PREFIX + '/Annotations/train_exp_anno.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/train2014/COCO_train2014_'}, 'val': {'ques_file': VQA_PREFIX + '/Questions/v2_OpenEnded_mscoco_val2014_questions.json', 'ans_file': VQA_PREFIX + '/Annotations/v2_mscoco_val2014_annotations.json', 'exp_file': VQA_PREFIX + '/Annotations/val_exp_anno.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/val2014/COCO_val2014_'}, 'test-dev': {'ques_file': VQA_PREFIX + '/Questions/OpenEnded_mscoco_test-dev2015_questions.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/test2015/COCO_test2015_'}, 'test': {'ques_file': VQA_PREFIX + '/Questions/OpenEnded_mscoco_test2015_questions.json', 'features_prefix': VQA_PREFIX + '/Features/resnet_res5c_bgrms_large/test2015/COCO_test2015_'}}
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ def largest_prime_factor(): i = 2 lst = [] number = 600851475143 while i != number: if number % i == 0: lst.append(i) number /= i i = 2 else: i += 1 lst.append(i) return lst[-1] if __name__ == '__main__': print(largest_prime_factor())
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ def largest_prime_factor(): i = 2 lst = [] number = 600851475143 while i != number: if number % i == 0: lst.append(i) number /= i i = 2 else: i += 1 lst.append(i) return lst[-1] if __name__ == '__main__': print(largest_prime_factor())
state_dict = {} aug_dict = {} oneof_dict = {} def clear_dict(state): skey = 'session' if skey not in list(state_dict.keys()) or state != state_dict[skey]: state_dict.clear() state_dict.update({'session': state}) aug_dict.clear()
state_dict = {} aug_dict = {} oneof_dict = {} def clear_dict(state): skey = 'session' if skey not in list(state_dict.keys()) or state != state_dict[skey]: state_dict.clear() state_dict.update({'session': state}) aug_dict.clear()
def reduce_to_one_dividing_by_one_or_pm_one(n): """ Given n this function computes the minimum number of operations 1. Divide by 2 when even 2. Add or subtract 1 when odd to reduce n to 1. The n input is supposed to be a string containing the decimal representation of the actual number. Original problem statement: Fuel Injection Perfection ========================= Commander Lambda has asked for your help to refine the automatic quantum antimatter fuel injection system for her LAMBCHOP doomsday device. It's a great chance for you to get a closer look at the LAMBCHOP - and maybe sneak in a bit of sabotage while you're at it - so you took the job gladly. Quantum antimatter fuel comes in small pellets, which is convenient since the many moving parts of the LAMBCHOP each need to be fed fuel one pellet at a time. However, minions dump pellets in bulk into the fuel intake. You need to figure out the most efficient way to sort and shift the pellets down to a single pellet at a time. The fuel control mechanisms have three operations: 1) Add one fuel pellet 2) Remove one fuel pellet 3) Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets) Write a function called solution(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits. For example: solution(4) returns 2: 4 -> 2 -> 1 solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1 Languages ========= To provide a Python solution, edit solution.py To provide a Java solution, edit Solution.java Test cases ========== Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here. -- Python cases -- Input: solution.solution('15') Output: 5 Input: solution.solution('4') Output: 2 -- Java cases -- Input: Solution.solution('4') Output: 2 Input: Solution.solution('15') Output: 5 """ count = 0 while not n == 1: if not n & 1: # Divisible by 2, then divide. n //= 2 else: if (n == 3) or (n_minus_1 % 4 == 1): # Subtracting 1 will give two # divisions by 2 afterwards. # The case n = 3 gives only one zero but # that one division by 2 finishes it. n -= 1 else: # Adding 1 will create at least # two divisions by 2. n += 1 count += 1 return count
def reduce_to_one_dividing_by_one_or_pm_one(n): """ Given n this function computes the minimum number of operations 1. Divide by 2 when even 2. Add or subtract 1 when odd to reduce n to 1. The n input is supposed to be a string containing the decimal representation of the actual number. Original problem statement: Fuel Injection Perfection ========================= Commander Lambda has asked for your help to refine the automatic quantum antimatter fuel injection system for her LAMBCHOP doomsday device. It's a great chance for you to get a closer look at the LAMBCHOP - and maybe sneak in a bit of sabotage while you're at it - so you took the job gladly. Quantum antimatter fuel comes in small pellets, which is convenient since the many moving parts of the LAMBCHOP each need to be fed fuel one pellet at a time. However, minions dump pellets in bulk into the fuel intake. You need to figure out the most efficient way to sort and shift the pellets down to a single pellet at a time. The fuel control mechanisms have three operations: 1) Add one fuel pellet 2) Remove one fuel pellet 3) Divide the entire group of fuel pellets by 2 (due to the destructive energy released when a quantum antimatter pellet is cut in half, the safety controls will only allow this to happen if there is an even number of pellets) Write a function called solution(n) which takes a positive integer as a string and returns the minimum number of operations needed to transform the number of pellets to 1. The fuel intake control panel can only display a number up to 309 digits long, so there won't ever be more pellets than you can express in that many digits. For example: solution(4) returns 2: 4 -> 2 -> 1 solution(15) returns 5: 15 -> 16 -> 8 -> 4 -> 2 -> 1 Languages ========= To provide a Python solution, edit solution.py To provide a Java solution, edit Solution.java Test cases ========== Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here. -- Python cases -- Input: solution.solution('15') Output: 5 Input: solution.solution('4') Output: 2 -- Java cases -- Input: Solution.solution('4') Output: 2 Input: Solution.solution('15') Output: 5 """ count = 0 while not n == 1: if not n & 1: n //= 2 elif n == 3 or n_minus_1 % 4 == 1: n -= 1 else: n += 1 count += 1 return count