content
stringlengths
7
1.05M
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: if not matrix: return 0 row, col = len(matrix), len(matrix[0]) dp = [0] * col ret = 0 for i in range(row): for j in range(col): if matrix[i][j] == '1': dp[j] += 1 else: dp[j] = 0 left = [] right = [None] * col stack = [] for idx, val in enumerate(dp): while stack and val <= dp[stack[-1]]: stack.pop(); if not stack: left.append(-1) else: left.append(stack[-1]) stack.append(idx) stack = [] for idx, val in enumerate(dp[::-1]): cidx = col - idx - 1 while stack and val <= dp[stack[-1]]: stack.pop(); if not stack: right[cidx] = col else: right[cidx] = stack[-1] stack.append(cidx) for l, r, v in zip(left, right, dp): ret = max(ret, v * (r - l - 1)) return ret
database_name = "Health_Service" user_name = "postgres" password = "zhangheng" port = "5432"
""" Problem Set 5 - Problem 1 - Build the Shift Dictionary and Apply Shift The Message class contains methods that could be used to apply a cipher to a string, either to encrypt or to decrypt a message (since for Caesar codes this is the same action). In the next two questions, you will fill in the methods of the Message class found in ps6.py according to the specifications in the docstrings. In this problem, you will fill in two methods: 1. Fill in the build_shift_dict(self, shift) method of the Message class. Be sure that your dictionary includes both lower and upper case letters, but that the shifted character for a lower case letter and its uppercase version are lower and upper case instances of the same letter. What this means is that if the original letter is "a" and its shifted value is "c", the letter "A" should shift to the letter "C". 2. Fill in the apply_shift(self, shift) method of the Message class. You may find it easier to use build_shift_dict(self, shift). Remember that spaces and punctuation should not be changed by the cipher. """ class Message(object): ### DO NOT MODIFY THIS METHOD ### def __init__(self, text): ''' Initializes a Message object text (string): the message's text a Message object has two attributes: self.message_text (string, determined by input text) self.valid_words (list, determined using helper function load_words ''' self.message_text = text self.valid_words = load_words(WORDLIST_FILENAME) ### DO NOT MODIFY THIS METHOD ### def get_message_text(self): ''' Used to safely access self.message_text outside of the class Returns: self.message_text ''' return self.message_text ### DO NOT MODIFY THIS METHOD ### def get_valid_words(self): ''' Used to safely access a copy of self.valid_words outside of the class Returns: a COPY of self.valid_words ''' return self.valid_words[:] def build_shift_dict(self, shift): ''' Creates a dictionary that can be used to apply a cipher to a letter. The dictionary maps every uppercase and lowercase letter to a character shifted down the alphabet by the input shift. The dictionary should have 52 keys of all the uppercase letters and all the lowercase letters only. shift (integer): the amount by which to shift every letter of the alphabet. 0 <= shift < 26 Returns: a dictionary mapping a letter (string) to another letter (string). ''' self.dictionaryResult = {} lowerCase = string.ascii_lowercase upperCase = string.ascii_uppercase for letters in lowerCase: self.dictionaryResult.update({letters : lowerCase[((lowerCase.index(letters) + shift) % 26)]}) for letters in upperCase: self.dictionaryResult.update({letters : upperCase[((upperCase.index(letters) + shift) % 26)]}) return self.dictionaryResult def apply_shift(self, shift): ''' Applies the Caesar Cipher to self.message_text with the input shift. Creates a new string that is self.message_text shifted down the alphabet by some number of characters determined by the input shift shift (integer): the shift with which to encrypt the message. 0 <= shift < 26 Returns: the message text (string) in which every character is shifted down the alphabet by the input shift ''' shiftedResult = "" for letters in self.get_message_text(): if letters in self.build_shift_dict(shift): shiftedResult += self.build_shift_dict(shift).get(letters) else: shiftedResult += letters return shiftedResult
#Exercise 3.2: Rewrite your pay program using try and except so # that yourprogram handles non-numeric input gracefully by # printing a messageand exiting the program. The following # shows two executions of the program: # Enter Hours: 20 # Enter Rate: nine # Error, please enter numeric input # Enter Hours: forty # Error, please enter numeric input hrs = input("Enter Hours: ") try: h = float(hrs) rph = input("Enter Rate: ") try: r = float(rph) if h <= 40: pay = h * r else: overhours = h - 40 norm_pay = 40 * r over_pay = overhours * r * 1.5 pay = norm_pay + over_pay print(pay) except: print("Error, please enter numeric input") except: print("Error, please enter numeric input")
def find_pairs_with_given_difference(arr, k): diffs = {} for y in arr: diffs[y-k] = y result=[] i = 0 while i < len(diffs): try: if arr[i] in diffs: result.append([ diffs[arr[i]], arr[i] ]) except: pass i+=1 return result ''' Pairs with Specific Difference A naive approach is is to run two loops. The outer loop picks the first element (smaller element) and the inner loop looks up for the element picked by the outer loop plus k. While this solution is done in O(1) space complexity, its time complexity is O(N^2), which isn’t asymptotically optimal. We can use a hash map to improve the time complexity to O(N⋅log(N)) for the worst case and O(N) for the average case. We rely on the fact that if x - y = k then x - k = y. The first step is to traverse the array, and for each element arr[i], we add a key-value pair of (arr[i] - k, arr[i]) to a hash map. Once the map is populated, we traverse the array again, and check for each element if a match exists in the map. Both the first and second steps take O(N⋅log(N)) for the worst case and O(N) for the average case. So the overall time complexity is O(N) for the average case. Pseudocode: function findPairsWithGivenDifference(arr, k): # since we don't allow duplicates, no pair can satisfy x - 0 = y if k == 0: return [] map = {} answer = [] for (x in arr): map[x - k] = x for (y in arr): if y in map: answer.push([map[y], y]) return answer Time Complexity: a generic hash map insert/lookup takes O(N) in the worst case. However, since we’re storing numbers, we can use a hash map that is based on a Binary Search Tree, and reduces inserts and lookups to O(log(N)). For the average case these operations take O(1). The while loop is O(N) since we go through every element in the array. So the total time complexity is O(N⋅log(N)) + O(N⋅log(N)) = O(N·log(N)) for the worst case, and O(N) + O(N) = O(N) for the average case. Space Complexity: since the size of the output itself is O(N), the space complexity is O(N) as well. The map we added will only hold N elements, and won’t increase the space complexity. '''
_base_ = [ '../_base_/models/mask_rcnn_r50_fpn_icdar2021.py', '../_base_/datasets/icdar2021_instance_isolated.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] # data = dict( # samples_per_gpu=1, # workers_per_gpu=2) # optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
""" Define custom exceptions """ __all__ = ( 'Track17Exception', 'InvalidCarrierCode', 'DateProcessingError' ) class Track17Exception(Exception): def __init__(self, message: str, code: int = None): self.message = message self.code = code super().__init__() def __str__(self) -> str: if self.code: return f'{self.message} (Code: {self.code})' return self.message class InvalidCarrierCode(Track17Exception): pass class DateProcessingError(Track17Exception): pass
""" Ryan Kirkbride - Noodling around: https://www.youtube.com/watch?v=CXrkq7u69vU How to: - Run the statements line by line (alt+enter), go to the next one whenever you feel like - The "#### > run block <" blocks should be executed together (ctrl+enter) - If you want to fast-forward through the song, just execute the blocks together (ctrl+enter) from the beginning, so you don't have to go through every variation of each instrument - Enjoy ! :+1: """ Scale.default = Scale.minor Root.default = -4 Clock.bpm = 136 d1 >> play(P["x---o---"],) d1 >> play(P["x---o---"].layer("mirror"),pan=(-1,1),) d1 >> play(P["x--(-[--])o---"].layer("mirror"),pan=(-1,1),) d1 >> play(P["x--(-[--])o--(-=)"].layer("mirror"),pan=(-1,1),) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),) d2 >> play(PZip("Vs"," n "),sample=1,) d2 >> play(PZip("Vs"," n "),sample=2,) d2 >> play(PZip("Vs"," n "),sample=2,).every(3,"stutter") d2 >> play(PZip("Vs"," n "),sample=2,).every(3,"stutter",dur=1) d2 >> play(PZip("Vs"," n "),sample=2,hpf=var([0,4000],[28,4]),).every(3,"stutter",dur=1) b1 >> dirt(var([0,2,-1,3]),) b1 >> dirt(var([0,2,-1,3]),dur=PDur(3,8),) b1 >> dirt(var([0,2,-1,3]),dur=PDur(3,8),bits=4,) b1 >> dirt(var([0,2,-1,3]),dur=PDur(3,8),bits=4,lpf=80,) b1 >> dirt(var([0,2,-1,3]),dur=PDur(3,8),bits=4,lpf=80,fmod=(0,1),) k1 >> karp() k1 >> karp(oct=6,) k1 >> karp(dur=1/4,oct=6,) k1 >> karp(dur=1/4,oct=var([6,7]),) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1/2,) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32],) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32]*(1,2),) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32]*(1,2),delay=(0,1/8),) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32]*(1,2),delay=(0,1/8),lpf=linvar([400,5000],12),) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32]*(1,2),delay=(0,1/8),lpf=linvar([400,5000],12),pan=linvar([-1,1],8),) + var([0,-1,1,0]) k1 >> karp(dur=1/4,oct=var([6,7]),sus=1,rate=P[:32]*(1,2),delay=(0,1/8),lpf=linvar([400,5000],12),pan=linvar([-1,1],8),) + var([0,-1,1,-7]) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),).every(5,"stutter",4,pan=[-1,1]) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),).every(5,"stutter",4,pan=[-1,1],rate=4) p1 >> blip([0,4,7,9],) p1 >> blip([0,4,7,9],oct=6,) p1 >> blip([0,4,7,9],oct=6,sus=2,) p1 >> blip([0,4,7,9],oct=6,sus=2,dur=1/2,) p1 >> blip([var([0,-1,1,0]),4,7,9],oct=6,sus=2,dur=1/2,) p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=6,sus=2,dur=1/2,) p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=7,sus=2,dur=1/2,) p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=(6,7),sus=2,dur=1/2,) d3 >> play("[--]") p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=(6,7),sus=2,dur=PDur(5,8),) p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=(6,7),sus=2,dur=PDur(5,8),chop=4) p1 >> blip([var([0,-1,1,0]),4,[7,10],9],oct=(6),sus=2,dur=PDur(5,8),chop=4) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),).every(5,"stutter",0,pan=[-1,1],rate=4) k1.stop() d2.solo() Scale.default = "major" s1 >> swell((0,2,4,const(6)),dur=4,) s1 >> swell((0,2,4,const(6)),dur=4,) + var([0,1],8) s1 >> swell((0,2,4,const(6)),dur=4,) + var([0,-1],8) s1 >> swell((0,2,4,const(6)),dur=4,) + var([0,1],8) Scale.default = Pvar([Scale.major,Scale.minor],16) s1 >> swell((0,2,4,const(6)),dur=4,) + var([0,[1,-1]],8) s1.solo() b1 >> dirt(var([0,[1,-1]],8),dur=PDur(3,8),bits=4,lpf=80,fmod=(0,1),) b1 >> dirt(var([0,[1,-1]],8),dur=PDur(3,8),bits=0,lpf=80,fmod=(0,1),) b1 >> dirt(var([0,[1,-1]],8),dur=PDur(3,8),bits=0,lpf=0,fmod=(0,1),) b1 >> bass(var([0,[1,-1]],8),dur=PDur(3,8),bits=0,lpf=0,fmod=(0,1),) b1 >> bass(var([0,[1,-1]],8),dur=PDur(3,8),bits=0,lpf=0,fmod=(0,0),) b1 >> bass(var([0,[1,-1]],8),dur=PDur(3,8),bits=0,lpf=0,) + [0,4,const(7)] b1 >> bass(var([0,[1,-1]],8),dur=PDur(5,8),bits=0,lpf=0,) + [0,4,const(7)] b1 >> bass(var([0,[1,-1]],8),dur=PDur(5,12),bits=0,lpf=0,) + [0,4,const(7)] d2 >> play(PZip("Vs"," n "),sample=2,hpf=var([0,4000],[28,4]),).every(3,"stutter",dur=1) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),) k2 >> karp([0,7,6,4,2],) k2 >> karp([0,7,6,4,2],sus=2,) k2 >> karp([0,7,6,4,2],sus=2,dur=PDur(5,8),chop=4,) k2 >> karp([0,7,6,4,2],sus=2,dur=PDur(5,8),chop=4,oct=7,) k2 >> karp(P[var([0,1],8),7,6,4,2],sus=2,dur=PDur(5,8),chop=4,oct=7,) k2 >> karp(P[var([0,1],8),7,6,4,2].layer("mirror"),sus=2,dur=PDur(5,8),chop=4,oct=7,) k2 >> karp(P[var([0,1],8),7,6,4,2].layer("mirror"),sus=2,dur=PDur(5,8),chop=4,oct=7,delay=(0,0.25),) k2.solo() b1 >> bass(var([0,[1,-1]],8),dur=PDur(5,12),bits=0,lpf=0,) + [0,4,const(7)] d2 >> play(PZip("Vs"," D "),sample=0,hpf=var([0,4000],[28,4]),).every(3,"stutter",dur=1) d2 >> play(PZip("Vs"," D D"),dur=PDur(5,8),sample=0,hpf=var([0,4000],[28,4]),).every(3,"stutter",dur=1) d2 >> play(PZip("Vs"," i i"),dur=PDur(5,8),sample=0,hpf=var([0,4000],[28,4]),).every(3,"stutter",dur=1) s1 >> swell((0,2,4,const(6)),dur=4,) + var([0,[1,-1]],8) d3 >> play("[--]") d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),chop=32,) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),chop=32,bits=4,) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),chop=32,bits=4,slide=PStep(5,-1),) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sample=-1,rate=var([1,4],[28,4]),chop=8,bits=4,slide=PStep(5,-1),) d1 >> play(P["x--(-[--])o--o(-=)-"].layer("mirror"),pan=(-1,1),dur=PDur(5,8),sus=1,sample=-1,rate=var([1,4],[28,4]),chop=8,bits=4,slide=PStep(5,-1),) k2.solo() k2.solo(0) p1.stop() Group(k2, s1, d2, d3).only() Group(s1, d3).stop() nextBar(Clock.clear)
HASS_EVENT_RECEIVE = 'HASS_EVENT_RECEIVE' # hass.bus --> hauto.bus HASS_STATE_CHANGED = 'HASS_STATE_CHANGE' # aka hass.EVENT_STATE_CHANGED HASS_ENTITY_CREATE = 'HASS_ENTITY_CREATE' # hass entity is newly created HASS_ENTITY_CHANGE = 'HASS_ENTITY_CHANGE' # hass entity's state changes HASS_ENTITY_UPDATE = 'HASS_ENTITY_UPDATE' # hass entity's state is same, but attributes change HASS_ENTITY_REMOVE = 'HASS_ENTITY_REMOVE' # hass entity is removed
N, L = map(int, input().split()) amida = [] for _ in range(L+1): tmp = list(input()) amida.append(tmp) idx = amida[L].index('o') for i in reversed(range(L)): if idx != N*2-2 and amida[i][idx+1] == '-': idx += 2 elif idx != 0 and amida[i][idx-1] == '-': idx -= 2 print(idx//2+1)
# LSM6DSO 3D accelerometer and 3D gyroscope seneor micropython drive # ver: 1.0 # License: MIT # Author: shaoziyang (shaoziyang@micropython.org.cn) # v1.0 2019.7 LSM6DSO_CTRL1_XL = const(0x10) LSM6DSO_CTRL2_G = const(0x11) LSM6DSO_CTRL3_C = const(0x12) LSM6DSO_CTRL6_C = const(0x15) LSM6DSO_CTRL8_XL = const(0x17) LSM6DSO_STATUS = const(0x1E) LSM6DSO_OUT_TEMP_L = const(0x20) LSM6DSO_OUTX_L_G = const(0x22) LSM6DSO_OUTY_L_G = const(0x24) LSM6DSO_OUTZ_L_G = const(0x26) LSM6DSO_OUTX_L_A = const(0x28) LSM6DSO_OUTY_L_A = const(0x2A) LSM6DSO_OUTZ_L_A = const(0x2C) LSM6DSO_SCALEA = ('2g', '16g', '4g', '8g') LSM6DSO_SCALEG = ('250', '125', '500', '', '1000', '', '2000') class LSM6DSO(): def __init__(self, i2c, addr = 0x6B): self.i2c = i2c self.addr = addr self.tb = bytearray(1) self.rb = bytearray(1) self.oneshot = False self.irq_v = [[0, 0, 0], [0, 0, 0]] self._power = True self._power_a = 0x10 self._power_g = 0x10 # ODR_XL=1 FS_XL=0 self.setreg(LSM6DSO_CTRL1_XL, 0x10) # ODR_G=1 FS_125=1 self.setreg(LSM6DSO_CTRL2_G, 0x12) # BDU=1 IF_INC=1 self.setreg(LSM6DSO_CTRL3_C, 0x44) self.setreg(LSM6DSO_CTRL8_XL, 0) # scale=2G self._scale_a = 0 self._scale_g = 0 self._scale_a_c = 1 self._scale_g_c = 1 self.scale_a('2g') self.scale_g('125') def int16(self, d): return d if d < 0x8000 else d - 0x10000 def setreg(self, reg, dat): self.tb[0] = dat self.i2c.writeto_mem(self.addr, reg, self.tb) def getreg(self, reg): self.i2c.readfrom_mem_into(self.addr, reg, self.rb) return self.rb[0] def get2reg(self, reg): return self.getreg(reg) + self.getreg(reg+1) * 256 def r_w_reg(self, reg, dat, mask): self.getreg(reg) self.rb[0] = (self.rb[0] & mask) | dat self.setreg(reg, self.rb[0]) def ax_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTX_L_A)) def ay_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTY_L_A)) def az_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTZ_L_A)) def gx_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTX_L_G)) def gy_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTY_L_G)) def gz_raw(self): return self.int16(self.get2reg(LSM6DSO_OUTZ_L_G)) def mg(self, reg): return round(self.int16(self.get2reg(reg)) * 0.061 * self._scale_a_c) def mdps(self, reg): return round(self.int16(self.get2reg(reg)) * 4.375 * self._scale_g_c) def ax(self): return self.mg(LSM6DSO_OUTX_L_A) def ay(self): return self.mg(LSM6DSO_OUTY_L_A) def az(self): return self.mg(LSM6DSO_OUTZ_L_A) def gx(self): return self.mdps(LSM6DSO_OUTX_L_G) def gy(self): return self.mdps(LSM6DSO_OUTY_L_G) def gz(self): return self.mdps(LSM6DSO_OUTZ_L_G) def get_a(self): self.irq_v[0][0] = self.ax() self.irq_v[0][1] = self.ay() self.irq_v[0][2] = self.az() return self.irq_v[0] def get_g(self): self.irq_v[1][0] = self.gx() self.irq_v[1][1] = self.gy() self.irq_v[1][2] = self.gz() return self.irq_v[1] def get(self): self.get_a() self.get_g() return self.irq_v def get_a_raw(self): self.irq_v[0][0] = self.ax_raw() self.irq_v[0][1] = self.ay_raw() self.irq_v[0][2] = self.az_raw() return self.irq_v[0] def get_g(self): self.irq_v[1][0] = self.gx_raw() self.irq_v[1][1] = self.gy_raw() self.irq_v[1][2] = self.gz_raw() return self.irq_v[1] def get(self): self.get_a_raw() self.get_g_raw() return self.irq_v def temperature(self): try: return self.int16(self.get2reg(LSM6DSO_OUT_TEMP_L))/256 + 25 except MemoryError: return self.temperature_irq() def temperature_irq(self): self.getreg(LSM6DSO_OUT_TEMP_L+1) if self.rb[0] & 0x80: self.rb[0] -= 256 return self.rb[0] + 25 def scale_a(self, dat=None): if dat is None: return LSM6DSO_SCALEA[self._scale_a] else: if type(dat) is str: if not dat in LSM6DSO_SCALEA: return self._scale_a = LSM6DSO_SCALEA.index(dat) self._scale_a_c = int(dat.rstrip('g'))//2 else: return self.r_w_reg(LSM6DSO_CTRL1_XL, self._scale_a<<2, 0xF3) def scale_g(self, dat=None): if (dat is None) or (dat == ''): return LSM6DSO_SCALEG[self._scale_g] else: if type(dat) is str: if not dat in LSM6DSO_SCALEG: return self._scale_g = LSM6DSO_SCALEG.index(dat) self._scale_g_c = int(dat)//125 else: return self.r_w_reg(LSM6DSO_CTRL2_G, self._scale_g<<1, 0xF1) def power(self, on=None): if on is None: return self._power else: self._power = on if on: self.r_w_reg(LSM6DSO_CTRL1_XL, self._power_a, 0x0F) self.r_w_reg(LSM6DSO_CTRL2_G, self._power_g, 0x0F) else: self._power_a = self.getreg(LSM6DSO_CTRL1_XL) & 0xF0 self._power_g = self.getreg(LSM6DSO_CTRL2_G) & 0xF0 self.r_w_reg(LSM6DSO_CTRL1_XL, 0, 0x0F) self.r_w_reg(LSM6DSO_CTRL2_G, 0, 0x0F)
class Solution: def findPeakElement(self, nums: List[int]) -> int: l=0 r=len(nums)-1 while l<r: mid=l+(r-l)//2 if nums[mid]<nums[mid+1]: l=mid+1 else: r=mid return l
# Refers to `_RAND_INCREASING_TRANSFORMS` in pytorch-image-models rand_increasing_policies = [ dict(type='AutoContrast'), dict(type='Equalize'), dict(type='Invert'), dict(type='Rotate', magnitude_key='angle', magnitude_range=(0, 30)), dict(type='Posterize', magnitude_key='bits', magnitude_range=(4, 0)), dict(type='Solarize', magnitude_key='thr', magnitude_range=(256, 0)), dict(type='SolarizeAdd', magnitude_key='magnitude', magnitude_range=(0, 110)), dict(type='ColorTransform', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Contrast', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Brightness', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Sharpness', magnitude_key='magnitude', magnitude_range=(0, 0.9)), dict(type='Shear', magnitude_key='magnitude', magnitude_range=(0, 0.3), direction='horizontal'), dict(type='Shear', magnitude_key='magnitude', magnitude_range=(0, 0.3), direction='vertical'), dict(type='Translate', magnitude_key='magnitude', magnitude_range=(0, 0.45), direction='horizontal'), dict(type='Translate', magnitude_key='magnitude', magnitude_range=(0, 0.45), direction='vertical') ]
def tickets(people): twenty_fives = 0 fifties = 0 for p in people: if p == 25: twenty_fives += 1 if p == 50: if twenty_fives == 0: return 'NO' twenty_fives -= 1 fifties += 1 if p == 100: if fifties >= 1 and twenty_fives >= 1: twenty_fives -= 1 fifties -= 1 elif twenty_fives >= 3: twenty_fives -= 3 else: return 'NO' return 'YES'
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ # Disable DYNAMICBASE for these tests because it implies/doesn't imply # FIXED in certain cases so it complicates the test for FIXED. { 'target_name': 'test_fixed_default_exe', 'type': 'executable', 'msvs_settings': { 'VCLinkerTool': { 'RandomizedBaseAddress': '1', }, }, 'sources': ['hello.cc'], }, { 'target_name': 'test_fixed_default_dll', 'type': 'shared_library', 'msvs_settings': { 'VCLinkerTool': { 'RandomizedBaseAddress': '1', }, }, 'sources': ['hello.cc'], }, { 'target_name': 'test_fixed_no', 'type': 'executable', 'msvs_settings': { 'VCLinkerTool': { 'FixedBaseAddress': '1', 'RandomizedBaseAddress': '1', } }, 'sources': ['hello.cc'], }, { 'target_name': 'test_fixed_yes', 'type': 'executable', 'msvs_settings': { 'VCLinkerTool': { 'FixedBaseAddress': '2', 'RandomizedBaseAddress': '1', }, }, 'sources': ['hello.cc'], }, ] }
# Python program to Find Numbers divisible by Another number def main(): x=int(input("Enter the number")) y=int(input("Enter the limit value")) print("The Numbers divisible by",x,"is") for i in range(1,y+1): if i%x==0: print(i) if __name__=='__main__': main()
#给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。 # # 找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。 # # 示例: # # X X X X #X O O X #X X O X #X O X X # # # 运行你的函数后,矩阵变为: # # X X X X #X X X X #X X X X #X O X X # # # 解释: # # 被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。 # Related Topics 深度优先搜索 广度优先搜索 并查集 #leetcode submit region begin(Prohibit modification and deletion) class Solution: def solve(self, board: list) -> None: """ 深度优先搜索 """ if not board: return row = len(board) col = len(board[0]) if row < 3 or col < 3: return # DFS函数 def dfs(i, j): if i < 0 or j < 0 or i >= row or j >= col or board[i][j] != 'O': return board[i][j] = '#' dfs(i - 1, j) dfs(i + 1, j) dfs(i, j - 1) dfs(i, j + 1) for i in range(row): dfs(i, 0) dfs(i, col - 1) for i in range(col): dfs(0, i) dfs(row - 1, i) for i in range(0, row): for j in range(0, col): if board[i][j] == 'O': board[i][j] = 'X' if board[i][j] == '#': board[i][j] = 'O' #leetcode submit region end(Prohibit modification and deletion) if __name__ == '__main__': s = Solution() board = [ ["X", "X", "X", "X"], ["X", "O", "O", "X"], ["X", "X", "O", "X"], ["X", "O", "X", "X"], ] s.solve(board) for b in board: print(b)
class multi(): def insert(self,num): for i in range(1, 11): print(num, "X", i, "=", num * i) d=multi() d.insert(num=int(input('Enter the number')))
a = 67 b = 1006 c = 1002 """if (a>=b and a>=c): print(a) elif (b>=c and b>=a) : print(b) elif (b>=a and b>=b) : print(c)""" max=a if a>=b: if b>=c: max =a else: if a>=c: max =a else: max = c else: if a>=c: max =b else: if b>=c: max=a else: max=c print(max)
""" Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. """ class Solution(object): def isPalindrome(self, s): """ :type s: str :rtype: bool """ if len(s)<=1: return True chars=[] for i in range(len(s)): if s[i] >= 'a' and s[i] <= 'z' or s[i] >= '0' and s[i] <= '9' or s[i] >= 'A' and s[i] <= 'Z': chars.append(s[i].lower()) left,right=0,len(chars)-1 while left<=right: if chars[left]!=chars[right]: return False else: left,right=left+1,right-1 return True
for value in range(10): print(value) print('All Done!')
""""" Datos de Entrada N Enteros Positivos = n = int K Enteros Positivos = k = int Datos de Salida Siempre que k sea menor a n Cuando N = K """"" n=int(input("Escriba el primer digito ")) k=int(input("Escriba el primer digito ")) while True: n=0 if(k<n): n=n-1 print(n) elif(n==k): print(k) break # Datos de Salida
def shift_letter(char, shifts): if not isinstance(char, chr): raise ValueError('char should be typeof chr') if char == '' or char is None: raise ValueError('char should be typeof chr') if ord(char.upper()) < 65 or ord(char.upper()) > 90: raise ValueError('char should be only a-z Latin alphabet letters') char = char.upper() char = ord(char) + shifts char = char - 90 + 64 if char > 90 else char char = chr(char) return char def cesar(input_string, shifts=13): if isinstance(input_string, str) is False or input_string is '': raise ValueError( 'input_string should be type of str() and not empty or null') if isinstance(shifts, int) is False or shifts <= 0: raise ValueError( 'shifts should be type of int() and greater then zero') if shifts is True or shifts is False: raise ValueError('shifts cannot be boolean value') chars = list(input_string.upper()) encrypted_string = list() for char in chars: number_in_ascii = ord(char) if number_in_ascii < 65 or number_in_ascii > 90: raise ValueError('Input string should contain only a-z Latin alphabet letters' '(no special signs or numbers!) without white-spaces.') number_in_ascii += shifts if number_in_ascii > 90: number_in_ascii = (number_in_ascii - 90) + 65 char = chr(number_in_ascii) encrypted_string.append(char) return ''.join(encrypted_string) def fence(input_string, fence_height): if isinstance(input_string, str) is False or input_string is '': raise ValueError( 'input_string should be type of str() and not empty or null') if isinstance(fence_height, int) is False or fence_height < 2: raise ValueError('fence_height should be type of int greater then one') if isinstance(fence_height, bool): raise ValueError('fence_height cannot be typeof bool') fence_levels = list() i = 0 while i < fence_height: fence_levels.append(list()) i += 1 level = 0 go_down = True for sign in input_string: fence_levels[level].append(sign) if go_down: level += 1 else: level -= 1 if level == fence_height - 1: go_down = False if level == 0: go_down = True output_string = '' for lvl in fence_levels: for char in lvl: output_string += char return output_string def gaderypoluki(input_string, key): if isinstance(input_string, str) is False or input_string is '': raise ValueError( 'input_string should be type of str() and not empty or null') if isinstance(key, str) is False or key is '': raise ValueError('key should be type of str() and not empty or null') input_string = input_string.lower() key = key.lower() i = 2 while i < len(key): if key[i] is not '-': raise ValueError( "Wrong format of key value. Should be like: 'GA-DE-RY-PO-LU-KI'") i += 3 simplified_key = '' for char in key: if char is not '-': simplified_key += char output_string = '' for char in input_string: if char in simplified_key: index = simplified_key.index(char) if index % 2 is 0: index += 1 else: index -= 1 output_string += simplified_key[index] else: output_string += char return output_string def vignere_table(i_row, i_column): table = [[chr(num) for num in range(65, 91, 1)] for c in range(65, 91, 1)] if not isinstance(i_row, int) or not isinstance(i_column, int): raise ValueError('i_row nad i_column should be typeof int') if i_row > 25: raise IndexError('i_rowe is out of range it should be below 26') if i_column > 25: raise IndexError('i_column is out of range it should be below 26') row = 1 while row < len(table): column = 0 while column < len(table[row]): letter = table[row][column] table[row][column] = shift_letter(letter, row) column += 1 row += 1 return table[i_row][i_column] def vignere(input_string, key): if not isinstance(input_string, str): raise ValueError('Input string should be typeof str') if input_string is None or input_string is '': raise ValueError('Input string should be typeof str') input_string = input_string.upper() for c in input_string: if ord(c) < 65 or ord(c) > 90: if c is not ' ': raise ValueError( 'Input string should contain only a-z Latin alphabet letters') key = key.upper() correct_key = [] i = 0 for letter in input_string: if i == len(key): i = 0 if letter == ' ': correct_key.append(letter) else: correct_key.append(key[i]) i += 1 correct_key = ''.join(correct_key) column = 0 row = 0 alphabet = [chr(i) for i in range(65, 91, 1)] output_string = [] i = 0 while i < len(input_string): if input_string[i] == ' ': output_string.append(input_string[i]) else: column = alphabet.index(input_string[i]) row = alphabet.index(correct_key[i]) output_string.append(vignere_table(column, row)) i += 1 output_string = ''.join(output_string) return output_string
i = 1 while i < 20: print(i) i += 1 i = 1 while i < 100: print(i) i += 1 i = 50 while i < 60: print(i) i += 1 i = 5 while i < 60: print(i) i += 1 i = 1 while i < 6: print(i) if (i == 3): break i += 1 k = 1 while k < 20: print(k) if (k == 20 or k == 16): break k += 1 usr = "" while usr != "q": usr = input("Enter a city, or q t")
def count_words(message): #return len(message.split()) # words = [] count = 0 activeWord = False for c in message: if c.isspace(): activeWord = False else: if not activeWord: # words.append([]) count += 1 activeWord = True # words[-1].append(c) return count #len(words) def main(): message = "What is your name?" print(message) print(count_words(message)) message = " Howwdy doody? " print(message) print(count_words(message)) if __name__ == '__main__': main()
class BufferFullException(Exception): def __init__(self, msg): self.msg = msg class BufferEmptyException(Exception): def __init__(self, msg): self.msg = msg class CircularBuffer: def __init__(self, capacity): self.list_circulator = list() self.list_circulator.append(','.join(str(capacity))) def read(self): if self.list_circulator == None: return BufferEmptyException("Empty") else: for items in self.list_circulator: return items def write(self, data): pass def overwrite(self, data): pass def clear(self): pass
DOMAIN = "microsoft_todo" CONF_CLIENT_ID = "client_id" CONF_CLIENT_SECRET = "client_secret" AUTH_CALLBACK_PATH = "/api/microsoft-todo" AUTHORIZATION_BASE_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize" TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token" SCOPE = ["Tasks.ReadWrite"] AUTH_REQUEST_SCOPE = SCOPE + ["offline_access"] MS_TODO_AUTH_FILE = ".ms_todo_auth.json" ATTR_ACCESS_TOKEN = "access_token" ATTR_REFRESH_TOKEN = "refresh_token" SERVICE_NEW_TASK = "new_task" SUBJECT = "subject" LIST_CONF = "list_conf" LIST_NAME = "list_name" LIST_ID = "list_id" NOTE = "note" DUE_DATE = "due_date" REMINDER_DATE_TIME = "reminder_date_time" ALL_TASKS = "all_tasks"
input = """ c | d. a | b :- c. a :- b. b :- a. """ output = """ {d} {c, a, b} """
class HouseScheme: def __init__(self, rooms, area, bathroomAvailability): if (area < 0) or ((bathroomAvailability is not True) and (bathroomAvailability is not False)): raise ValueError("Invalid value") self.rooms = rooms self.area = area self.bathroomAvailability = bathroomAvailability class CountryHouse(HouseScheme): def __init__(self, rooms, area, bathroomAvailability, floors, landArea): HouseScheme.__init__(self, rooms, area, bathroomAvailability) self.floors = floors self.landArea = landArea def __str__(self): return "Country House: Количество жилых комнат {}, Жилая площадь {}, Совмещенный санузел {}, Количество этажей {}, Площадь участка {}.".format(self.rooms, self.area, self.bathroomAvailability, self.floors, self.landArea) def __eq__(self, other): return (self.area == other.area) and (self.landArea == other.landArea) and (abs(self.floors - other.floors) <= 1) class Apartment(HouseScheme): def __init__(self, rooms, area, bathroomAvailability, floor, side): HouseScheme.__init__(self, rooms, area, bathroomAvailability) self.floor = floor self.side = side if self.floor < 1 or self.floor > 15: raise ValueError("Invalid value") if self.side not in ["N", "S", "W", "E"]: raise ValueError("Invalid value") def __str__(self): return "Apartment: Количество жилых комнат {}, Жилая площадь {}, Совмещенный санузел {}, Этаж {}, Окна выходят на {}.".format(self.rooms, self.area, self.bathroomAvailability, self.floor, self.side) class CountryHouseList(list): def __init__(self, name): list.__init__(self) self.name = name def append(self, p_object): if isinstance(p_object, CountryHouse): list.append(self, p_object) else: raise TypeError("Invalid type {}".format(type(p_object))) def total_square(self): return sum([x.area for x in self]) class ApartmentList(list): def __init__(self, name): list.__init__(self) self.name = name def extend(self, iterable): filteredIterable = filter(lambda x: isinstance(x, Apartment), iterable) list.extend(self, filteredIterable) def floor_view(self, floors, directions): filteredApartmentList = filter(lambda x: (x.floor >= floors[0]) and (x.floor <= floors[1]) and (x.side in directions), self) for i in filteredApartmentList: print("{}: {}".format(i.side, i.floor))
def parse_response_from_json(r): response = '' try: response = r.json()['response'] except Exception as ex: response = str(ex) return response
# [Commerci Republic] Delfino Deleter 2 sm.setSpeakerID(9390256) # Leon Daniella sm.sendNext("I was so much faster than you! But you're the sidekick for a reason.") sm.sendNext("C'mon! We can't let them get their buddies. We have to finish this now! I'll be waiting for you at #m865020200#") # Canal 3 sm.sendNext("What are you waiting for, my loyal sidekick?") sm.setPlayerAsSpeaker() # Has to be Player Avatar sm.sendNext("Hold up. I have a really bad feeling about this...") sm.setSpeakerID(9390256) # Leon Daniella sm.sendNext("Don't feel bad. I'm here for you, pal.") sm.setPlayerAsSpeaker() # Has to be Player Avatar sm.sendNext("No, listen. These fishmen seem like they're barely even trying...") sm.setSpeakerID(9390256) # Leon Daniella sm.sendNext("That's only because I'm totally awesome. So they look weak in comparison.") sm.setPlayerAsSpeaker() # Has to be Player Avatar sm.sendNext("But...") sm.setSpeakerID(9390256) # Leon Daniella sm.sendNext("Let's go!") sm.completeQuest(parentID) sm.dispose()
ans=0 n=200 def f(n): fac=[0]*(n+10) fac[0]=1 for i in range(1,n+5): fac[i]=i*fac[i-1] return fac def c(n,m): return fac[n]//fac[n-m]//fac[m] def solve(i,asn,b,other): res=0 if i>b: if other>b+1: return 0 else: t=fac[b+1]//fac[b+1-other] for j in asn: if j: t//=fac[j] return t for j in range(b/i+1): asn[i]=j res+=solve(i+1,asn,b-i*j,other+j) asn[i]=0 return res; fac=f(n) assign = [0]*(n+10) #ans = solve(3,assign,n,0) ans=50 while solve(50,assign,ans,0)<1000000: ans+=1 print(ans)
a='ala ma kota' print(a) a=u'ala ma kota' print(a) a='ala'+'ma'+'kota' print(a) print(len(a)) if(a[:1]=='a'): print(a[-4]) else: print('No nie za brdzo') print('{0}, {1}, {2}'.format(*'abc')) a = 'Psa' print('%s ma %s' % (a,a))
distancia = int(input('Digite a distância de sua viagem: ')) if distancia > 200: print('O custo total de sua passagem é R${:.2f}'.format(0.45*distancia)) else: print('O custo total de sua passagem é R${:.2f}'.format(0.50 * distancia))
class ElectricMotor: """A class used to model an electric motor Assumptions: - linear magnetic circuit (not considering flux dispersions and metal saturation when high currents are applied) - only viscous friction is assumed to be present (not considering Coulomb frictions) - stator is assumed to have a single coil - rotor is assumed to have a single coil Source: - Zaccarian, L. "DC motors: dynamic model and control techniques". Available at: http://homepages.laas.fr/lzaccari/seminars/DCmotors.pdf """ def __init__(self, coil_turns, coil_size, magnetic_permea, solenoid_length, solenoid_area, stator_induc, stator_resist, rotor_induc, rotor_resist, rotor_inertia, viscous_friction, load_torque, stator_current, rotor_current, rotor_speed, rotor_position): self.N = [coil_turns] self.m = [magnetic_permea] self.l = [solenoid_length] self.A = [solenoid_area] self.d = [coil_size] self.K0 = self.m[-1]*self.A[-1]/self.l[-1] self.Kphi = self.l[-1]*self.d[-1]/self.A[-1] self.K = self.Kphi[-1]*self.K0[-1]*self.N[-1] self.Le = [stator_induc] self.Re = [stator_resist] self.Ke = 1/self.Re[-1] # stator gain self.te = self.Le[-1]/self.Re[-1] # stator time constant self.La = [rotor_induc] self.Ra = [rotor_resist] self.Ka = 1/self.Ra[-1] # rotor gain self.ta = self.La[-1]/self.Ra[-1] # rotor time constant self.J = [rotor_inertia] self.F = [viscous_friction] self.Km = 1/self.F[-1] # mechanical gain self.tm = self.J[-1]/self.F[-1] # mechanical time constant self.Tl = [load_torque] # load torque exerted on the motor # state variables self.ie = [stator_current] self.ia = [rotor_current] self.w = [rotor_speed] self.omega = [rotor_position]
scan_utility_version = '1.0.11' detect_jar = "/tmp/synopsys-detect.jar" # workflow_script = "/Users/mbrad/working/blackduck-scan-action/blackduck-rapid-scan-to-github.py" # detect_jar = "./synopsys-detect.jar" # workflow_script = "/Users/jcroall/PycharmProjects/blackduck-scan-action/blackduck-rapid-scan-to-github.py" debug = 0 # fix_pr = '' # upgrade_major = '' # comment_on_pr = '' # sarif = "blackduck-sarif.json" # incremental_results = False # upgrade_indirect = False # skip_detect = False bd = None args = None scm_provider = None pkg_files = ['pom.xml', 'package.json', 'npm-shrinkwrap.json', 'package-lock.json', 'Cargo.toml', 'Cargo.lock', 'conanfile.txt', 'environment.yml', 'pubspec.yml', 'pubspec.lock', 'gogradle.lock', 'Gopkg.lock', 'go.mod', 'vendor,json', 'vendor.conf', 'build.gradle', 'rebar.config', 'lerna.json', 'requirements.txt', 'Pipfile', 'Pipfile.lock', 'yarn.lock'] pkg_exts = ['.csproj', '.fsproj', '.vbproj', '.asaproj', '.dcproj', '.shproj', '.ccproj', '.sfproj', '.njsproj', '.vcxproj', '.vcproj', '.xproj', '.pyproj', '.hiveproj', '.pigproj', '.jsproj', '.usqlproj', '.deployproj', '.msbuildproj', '.sqlproj', '.dbproj', '.rproj', '.sln'] # baseline_comp_cache = None bdio_graph = None bdio_projects = None rapid_scan_data = None detected_package_files = None # comment_on_pr_comments = [] tool_rules = [] results = [] fix_pr_data = dict() rscan_items = [] comment_on_pr_header = "Synopsys Black Duck - Vulnerabilities Reported" github_token = '' github_repo = '' github_branch = '' github_ref = '' github_api_url = '' github_sha = '' def printdebug(dstring): if debug > 0: print(dstring)
""" 230. Kth Smallest Element in a BST """ # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: A = [] res = self.inorder(root, A) return A[k - 1] def inorder(self, root, A): currentNode = root if root: if currentNode.left: self.inorder(currentNode.left, A) print(currentNode.val) A.append(currentNode.val) if currentNode.right: self.inorder(currentNode.right, A) return A
def collateFunction(self, batch): """ Custom collate function to adjust a variable number of low-res images. Args: batch: list of imageset Returns: padded_lr_batch: tensor (B, min_L, W, H), low resolution images alpha_batch: tensor (B, min_L), low resolution indicator (0 if padded view, 1 otherwise) hr_batch: tensor (B, W, H), high resolution images hm_batch: tensor (B, W, H), high resolution status maps isn_batch: list of imageset names """ lr_batch = [] # batch of low-resolution views alpha_batch = [] # batch of indicators (0 if padded view, 1 if genuine view) hr_batch = [] # batch of high-resolution views hm_batch = [] # batch of high-resolution status maps isn_batch = [] # batch of site names train_batch = True for imageset in batch: lrs = imageset['lr'] L, H, W = lrs.shape lr_batch.append(lrs) alpha_batch.append(torch.ones(L)) hr = imageset['hr'] hr_batch.append(hr) hm_batch.append(imageset['hr_map']) isn_batch.append(imageset['name']) padded_lr_batch = lr_batch padded_lr_batch = torch.stack(padded_lr_batch, dim=0) alpha_batch = torch.stack(alpha_batch, dim=0) hr_batch = torch.stack(hr_batch, dim=0) hm_batch = torch.stack(hm_batch, dim=0) # isn_batch = torch.stack(isn_batch, dim=0) # for imageset in batch:# # lrs = imageset['lr'] # L, H, W = lrs.shape # if L >= self.min_L: # pad input to top_k # lr_batch.append(lrs[:self.min_L]) # alpha_batch.append(torch.ones(self.min_L)) # else: # pad = torch.zeros(self.min_L - L, H, W) # lr_batch.append(torch.cat([lrs, pad], dim=0)) # alpha_batch.append(torch.cat([torch.ones(L), torch.zeros(self.min_L - L)], dim=0)) # hr = imageset['hr'] # if train_batch and hr is not None: # hr_batch.append(hr) # else: # train_batch = False # hm_batch.append(imageset['hr_map']) # isn_batch.append(imageset['name']) # padded_lr_batch = torch.stack(lr_batch, dim=0) # alpha_batch = torch.stack(alpha_batch, dim=0) # if train_batch: # hr_batch = torch.stack(hr_batch, dim=0) # hm_batch = torch.stack(hm_batch, dim=0) return padded_lr_batch, alpha_batch, hr_batch, hm_batch, isn_batch
class Pagination(object): def __init__(self,totalCount,currentPage,perPageItemNum=10,maxPageNum=7): # 数据总个数 self.total_count = totalCount # 当前页 try: v = int(currentPage) if v <= 0: v = 1 self.current_page = v except Exception as e: self.current_page = 1 # 每页显示的行数 self.per_page_item_num = perPageItemNum # 最多显示页面 self.max_page_num = maxPageNum def start(self): return (self.current_page-1) * self.per_page_item_num def end(self): return self.current_page * self.per_page_item_num @property def num_pages(self): """ 总页数 :return: """ # 666 # 10 a,b = divmod(self.total_count,self.per_page_item_num) if b == 0: return a return a+1 def pager_num_range(self): # self.num_pages() # self.num_pages # 当前页 #self.current_page # 最多显示的页码数量 11 #self.per_pager_num # 总页数 # self.num_pages if self.num_pages < self.max_page_num: return range(1,self.num_pages+1) # 总页数特别多 5 part = int(self.max_page_num/2) if self.current_page <= part: return range(1,self.max_page_num+1) if (self.current_page + part) > self.num_pages: return range(self.num_pages-self.max_page_num+1,self.num_pages+1) return range(self.current_page-part,self.current_page+part+1) def page_str(self): page_list = [] first = "<li><a href='/index2.html?p=1'>首页</a></li>" page_list.append(first) if self.current_page == 1: prev = "<li><a href='#'>上一页</a></li>" else: prev = "<li><a href='/index2.html?p=%s'>上一页</a></li>" %(self.current_page-1,) page_list.append(prev) for i in self.pager_num_range(): if i == self.current_page: temp = "<li class='active'><a href='/index2.html?p=%s'>%s</a></li>" %(i,i) else: temp = "<li><a href='/index2.html?p=%s'>%s</a></li>" % (i, i) page_list.append(temp) if self.current_page == self.num_pages: nex = "<li><a href='#'>下一页</a></li>" else: nex = "<li><a href='/index2.html?p=%s'>下一页</a></li>" % (self.current_page + 1,) page_list.append(nex) last = "<li><a href='/index2.html?p=%s'>尾页</a></li>" %(self.num_pages,) page_list.append(last) return ''.join(page_list)
destination = input() current_money = 0 while destination != 'End': vacation_money = float(input()) while current_money < vacation_money: work_money = float(input()) current_money += work_money print(f'Going to {destination}!') current_money = 0 destination = input()
"""Internal exception classes.""" class UnsatisfiableConstraint(Exception): """Raise when a specified constraint cannot be satisfied.""" pass class UnsatisfiableType(UnsatisfiableConstraint): """Raised when a type constraint cannot be satisfied.""" pass class TreeConstructionError(Exception): """Raised when a tree cannot be successfully constructed.""" pass
class Book: def __init__(self, title, bookType): self.title = title self.bookType = bookType
XK_Aogonek = 0x1a1 XK_breve = 0x1a2 XK_Lstroke = 0x1a3 XK_Lcaron = 0x1a5 XK_Sacute = 0x1a6 XK_Scaron = 0x1a9 XK_Scedilla = 0x1aa XK_Tcaron = 0x1ab XK_Zacute = 0x1ac XK_Zcaron = 0x1ae XK_Zabovedot = 0x1af XK_aogonek = 0x1b1 XK_ogonek = 0x1b2 XK_lstroke = 0x1b3 XK_lcaron = 0x1b5 XK_sacute = 0x1b6 XK_caron = 0x1b7 XK_scaron = 0x1b9 XK_scedilla = 0x1ba XK_tcaron = 0x1bb XK_zacute = 0x1bc XK_doubleacute = 0x1bd XK_zcaron = 0x1be XK_zabovedot = 0x1bf XK_Racute = 0x1c0 XK_Abreve = 0x1c3 XK_Lacute = 0x1c5 XK_Cacute = 0x1c6 XK_Ccaron = 0x1c8 XK_Eogonek = 0x1ca XK_Ecaron = 0x1cc XK_Dcaron = 0x1cf XK_Dstroke = 0x1d0 XK_Nacute = 0x1d1 XK_Ncaron = 0x1d2 XK_Odoubleacute = 0x1d5 XK_Rcaron = 0x1d8 XK_Uring = 0x1d9 XK_Udoubleacute = 0x1db XK_Tcedilla = 0x1de XK_racute = 0x1e0 XK_abreve = 0x1e3 XK_lacute = 0x1e5 XK_cacute = 0x1e6 XK_ccaron = 0x1e8 XK_eogonek = 0x1ea XK_ecaron = 0x1ec XK_dcaron = 0x1ef XK_dstroke = 0x1f0 XK_nacute = 0x1f1 XK_ncaron = 0x1f2 XK_odoubleacute = 0x1f5 XK_udoubleacute = 0x1fb XK_rcaron = 0x1f8 XK_uring = 0x1f9 XK_tcedilla = 0x1fe XK_abovedot = 0x1ff
load( "//scala:scala.bzl", "scala_library", ) load( "//scala:scala_cross_version.bzl", _default_scala_version = "default_scala_version", _extract_major_version = "extract_major_version", _scala_mvn_artifact = "scala_mvn_artifact", ) load( "@io_bazel_rules_scala//scala:scala_maven_import_external.bzl", _scala_maven_import_external = "scala_maven_import_external", ) load( "//scala/private:common.bzl", "collect_jars", "create_java_provider", ) load( "//scala_proto/private:scala_proto_default_repositories.bzl", "scala_proto_default_repositories", ) load( "//scala_proto/private:scalapb_aspect.bzl", "scalapb_aspect", "ScalaPBInfo", "merge_scalapb_aspect_info", "ScalaPBAspectInfo", ) def scala_proto_repositories( scala_version = _default_scala_version(), maven_servers = ["http://central.maven.org/maven2"]): return scala_proto_default_repositories(scala_version, maven_servers) """Generate scalapb bindings for a set of proto_library targets. Example: scalapb_proto_library( name = "exampla_proto_scala", deps = ["//src/proto:example_service"] ) Args: name: A unique name for this rule deps: Proto library or java proto library (if with_java is True) targets that this rule depends on Outputs: A scala_library rule that includes the generated scalapb bindings, as well as any library dependencies needed to compile and use these. """ def _scalapb_proto_library_impl(ctx): aspect_info = merge_scalapb_aspect_info( [dep[ScalaPBAspectInfo] for dep in ctx.attr.deps], ) all_java = aspect_info.java_info return [ all_java, ScalaPBInfo(aspect_info = aspect_info), DefaultInfo(files = aspect_info.output_files), ] scalapb_proto_library = rule( implementation = _scalapb_proto_library_impl, attrs = { "deps": attr.label_list(aspects = [scalapb_aspect]) }, provides = [DefaultInfo, ScalaPBInfo, JavaInfo], )
# TimeTracker config # By Clok Much # # ver.1 # # 已废弃 class Default: track_time = 30 # 统计周期 int ,单位为 秒 ,指定时间为间隔,进行一次统计 graph_time = 5 # 绘图周期 int ,单位为 次 ,指定次数的统计时间后,进行一次数据输出和绘图 period = 8 # 将指定天数之前的数据视为过期数据,将之压缩并保存在 sub_dir output_dir = 'V:\\TimeTracker\\' # 统计结果输出的主目录 sub_dir = 'storage\\' # 过期数据储存目录 default_reminder_time = 0 # 默认提醒器时间 int ,单位为 分钟 ,当不配置提醒器时间时,使用此处的时间 app_color = "#999999" # 程序计时绘图的颜色 graph_font = 'Sarasa Fixed Slab SC' # 绘图使用的字体
def EDFB(U): if U>1: return False else: return True def SC_EDF(tasks): U=0 for itask in tasks: U+=(itask['execution']+itask['sslength'])/itask['period'] return EDFB(U)
""" Write a Python function that takes a number as an input from the user and computes its factorial. Written by Sudipto Ghosh for the University of Delhi """ def factorial(n): """ Calculates factorial of a number Arguments: n {integer} -- input Returns: factorial {integer} """ assert n >= 0, 'invalid number' if n == 0: return 1 else: return n * factorial(n - 1) def computeFactorial(): """ Takes Argumrnts from the user and computes its factorial """ n = int(input("Enter Number: ")) nFactorial = factorial(n) print("Factorial of", n, "is", nFactorial) def main(): computeFactorial() if __name__ == "__main__": main()
#Faça um programa que leia um número inteiro e diga se ele é ou não um número primo. num = int(input('Digite um número: ')) total = 0 for c in range(1, num + 1): if num % c == 0: total += 1 if total == 2: print(f'O numero {num} é primo') else: print(f'O número {num} não é primo')
#buffer = [0xB5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0xD0, 0x08, 0x00, 0x00, 0x80, 0x25, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x09, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x3B, 0x2C, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x3B, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x11, 0x02, 0x00, 0x08, 0x01] #buffer = [0xB5, 0x62, 0x06, 0x11, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x3E, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x3E, 0x24, 0x00, 0x00, 0x16, 0x16, 0x04, 0x00, 0x04, 0xff, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x05, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x08, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x24, 0x24, 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x09, 0x0C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x01, 0x08, 0x00, 0xF0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x09, 0x0C, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00] #buffer = [0xB5, 0x62, 0x06, 0x00, 0x14, 0x00, 0x01, 0x00, 0x00, 0x00, 0xD0, 0x08, 0x00, 0x00, 0x00, 0x4B, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00] buffer = [0xB5, 0x62, 0x05, 0x01, 0x02, 0x00, 0x06, 0x00] ca = 0 cb = 0 for x in range(2,len(buffer)): ca = 0xff & (ca + buffer[x]) cb = 0xff & (cb + ca) print(hex(ca)) print(hex(cb))
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param: head: The first node of linked list. @return: a tree node """ def sortedListToBST(self, head): # write your code here # base case if not head: return head if not head.next: return TreeNode(head.val) # find middle position of current Linked List slow, fast = head, head.next while fast.next and fast.next.next: slow = slow.next fast = fast.next.next # create TreeNode mid = slow.next slow.next = None root = TreeNode(mid.val) # recursive case root.left = self.sortedListToBST(head) root.right = self.sortedListToBST(mid.next) return root
ifXTable = '.1.3.6.1.2.1.31.1.1.1' ifName = ifXTable + '.1' ifInMulticastPkts = ifXTable + '.2' ifHCInOctets = ifXTable + '.6' ifHCInUcastPkts = ifXTable + '.7' ifHCInMulticastPkts = ifXTable + '.8' ifHCInBroadcastPkts = ifXTable + '.9' ifHCOutOctets = ifXTable + '.10' ifHCOutUcastPkts = ifXTable + '.11' ifHCOutMulticastPkts = ifXTable + '.12' ifHCOutBroadcastPkts = ifXTable + '.13' ifHighSpeed = ifXTable + '.15' ifAlias = ifXTable + '.18' ifx_table_oids = [ifHCInOctets, ifHCInUcastPkts, ifHCInMulticastPkts, ifHCInBroadcastPkts, ifHCOutOctets, ifHCOutUcastPkts, ifHCOutMulticastPkts, ifHCOutBroadcastPkts, ifHighSpeed, ]
# from django.views.generic.base import View # from rest_framework.views import APIView # from django.conf import settings #!/usr/bin/env python # def func(): # fun_list = [] # for i in range(4): # def foo(x, i=i): # return x*i # fun_list.append(foo) # return fun_list # # # for m in func(): # print(m(2)) class SingleTool(object): __instance = None def __new__(cls, *args, **kwargs): if not cls.__instance: cls.__instance = object.__new__(cls) return cls.__instance def addxnum(self,*args): my_sum = 0 for value in args: my_sum +=value return my_sum t1 = SingleTool() print(t1.addxnum(1,2,3)) print(t1) t2=SingleTool() print(t2) a = [(i-2, i-1, i) for i in range(1, 100) if i % 3 == 0] print(a) print([[x for x in range(1,100)][i:i+3] for i in range(0, 100, 3)])
# modifying a list in a function # Start with some designs that need to be printed. unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron'] completed_models = [] # Simulate printing each design, until none are left. # Move each design to completed_models after printing. while unprinted_designs: current_design = unprinted_designs.pop() print(f"Printing model: {current_design}") completed_models.append(current_design) # Display all completed models print("\nThe following models have been printed:") for completed_model in completed_models: print(completed_model)
def foo(): x = 1 def bar(): nonlocal x baz() print(x) def baz(): nonlocal x x = 2 bar() foo()
"""Constants for the onboarding component.""" DOMAIN = "onboarding" STEP_USER = "user" STEP_CORE_CONFIG = "core_config" STEP_INTEGRATION = "integration" STEP_ANALYTICS = "analytics" STEP_MOB_INTEGRATION = "mob_integration" STEPS = [ STEP_USER, STEP_CORE_CONFIG, STEP_ANALYTICS, STEP_INTEGRATION, STEP_MOB_INTEGRATION, ] DEFAULT_AREAS = ("living_room", "kitchen", "bedroom")
class MovieData: def __init__(self,movie_name,imdb_id,plot,review,facts_table,comments,spans,labels,chat,chat_id): self.movie_name=movie_name self.imdb_id=imdb_id self.plot=plot self.review=review self.facts_table=facts_table self.comments=comments self.spans=spans self.labels=labels self.chat=[] if(chat is not None): self.chat.append(Chat(chat_id,chat)) class Chat: def __init__(self,chat_id,chats): self.chat=[] if(len(chats)%2!=0): le=len(chats)-1 else: le=len(chats) self.chat_id=chat_id self.encoder_chat=[] self.decoder_chat=[] try: for i in range(0, le, 2): if(i>=2): self.encoder_chat.append("<SOS> "+chats[i-2]+" <EOS>"+" <SOS> "+chats[i-1]+" <EOS> "+chats[i]) else: self.encoder_chat.append(chats[i]) self.decoder_chat.append(chats[i + 1]) self.chat.append(self.encoder_chat) self.chat.append(self.decoder_chat) except: print("Error")
# when not using https CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False #SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_PROXY_SSL_HEADER = None #https://docs.djangoproject.com/en/3.0/ref/settings/#secure-proxy-ssl-header #A tuple representing a HTTP header/value combination that # signifies a request is secure. # This controls the behavior of the request object’s is_secure() method.
# Tests: # ifstmt ::= testexpr _ifstmts_jump # _ifstmts_jump ::= c_stmts_opt JUMP_FORWARD COME_FROM if True: b = False
class Solution: def checkEqualTree(self, root: Optional[TreeNode]) -> bool: if not root: return False seen = set() def dfs(root: Optional[TreeNode]) -> int: if not root: return 0 sum = root.val + dfs(root.left) + dfs(root.right) seen.add(sum) return sum sum = root.val + dfs(root.left) + dfs(root.right) return sum % 2 == 0 and sum // 2 in seen
#!/usr/bin/env python3 # Example: 3 Integer Printing (Recursion) # Print integers relative to various bases # i.e. printInteger(61,2) → 111101 # printInteger(61,10) → 61 def rec_printInteger(n, b): str = '0123456789ABCDEF' if n < b: return str[n] # base case else: return rec_printInteger(n // b, b) + str[n % b] # recursive call print(rec_printInteger(6005698765698767906445, 16))
# color references: # http://rebrickable.com/colors # http://www.bricklink.com/catalogColors.asp rebrickable_color_to_bricklink = { # Solid Colors 15: (1, 'White'), 503: (49, 'Very Light Gray'), 151: (99, 'Very Light Bluish Gray'), 71: (86, 'Light Bluish Gray'), 7: (9, 'Light Gray'), 8: (10, 'Dark Gray'), 72: (85, 'Dark Bluish Gray'), 0: (11, 'Black'), 320: (59, 'Dark Red'), 4: (5, 'Red'), 216: (27, 'Rust'), 12: (25, 'Salmon'), 100: (26, 'Light Salmon'), 335: (58, 'Sand Red'), 70: (88, 'Reddish Brown'), 6: (8, 'Brown'), 308: (120, 'Dark Brown'), 28: (69, 'Dark Tan'), 19: (2, 'Tan'), 78: (90, 'Light Flesh'), 92: (28, 'Flesh'), 84: (150, 'Medium Dark Flesh'), 86: (91, 'Dark Flesh'), 450: (106, 'Fabuland Brown'), 366: (29, 'Earth Orange'), 484: (68, 'Dark Orange'), 25: (4, 'Orange'), 462: (31, 'Medium Orange'), 191: (110, 'Bright Light Orange'), 125: (32, 'Light Orange'), 68: (96, 'Very Light Orange'), 14: (3, 'Yellow'), 226: (103, 'Bright Light Yellow'), 18: (33, 'Light Yellow'), 120: (35, 'Light Lime'), 158: (158, 'Yellowish Green'), 115: (76, 'Medium Lime'), 27: (34, 'Lime'), 326: (155, 'Olive Green'), 288: (80, 'Dark Green'), 2: (6, 'Green'), 10: (36, 'Bright Green'), 74: (37, 'Medium Green'), 17: (38, 'Light Green'), 378: (48, 'Sand Green'), 3: (39, 'Dark Turquoise'), 11: (40, 'Light Turquoise'), 118: (41, 'Aqua'), 323: (152, 'Light Aqua'), 272: (63, 'Dark Blue'), 1: (7, 'Blue'), 321: (153, 'Dark Azure'), 322: (156, 'Medium Azure'), 73: (42, 'Medium Blue'), 313: (72, 'Maersk Blue'), 212: (105, 'Bright Light Blue'), 9: (62, 'Light Blue'), 232: (87, 'Sky Blue'), 379: (55, 'Sand Blue'), 112: (97, 'Blue-Violet'), 23: (109, 'Dark Blue-Violet'), 110: (43, 'Violet'), 1001: (73, 'Medium Violet'), 20: (44, 'Light Violet'), 85: (89, 'Dark Purple'), 22: (24, 'Purple'), 69: (93, 'Light Purple'), 30: (157, 'Medium Lavender'), 31: (154, 'Lavender'), 373: (54, 'Sand Purple'), 26: (71, 'Magenta'), 5: (47, 'Dark Pink'), 351: (94, 'Medium Dark Pink'), 29: (104, 'Bright Pink'), 13: (23, 'Pink'), 77: (56, 'Light Pink'), # Transparent Colors 47: (12, 'Trans-Clear'), 40: (13, 'Trans-Black'), 36: (17, 'Trans-Red'), 57: (18, 'Trans-Neon Orange'), 182: (98, 'Trans-Orange'), 54: (121, 'Trans-Neon Yellow'), 46: (19, 'Trans-Yellow'), 42: (16, 'Trans-Neon Green'), 35: (108, 'Trans-Bright Green'), 34: (20, 'Trans-Green'), 33: (14, 'Trans-Dark Blue'), 143: (74, 'Trans-Medium Blue'), 41: (15, 'Trans-Light Blue'), 43: (113, 'Trans-Very Lt Blue'), 236: (114, 'Trans-Light Purple'), 52: (51, 'Trans-Purple'), 45: (50, 'Trans-Dark Pink'), 230: (107, 'Trans-Pink'), # Chrome Colors 334: (21, 'Chrome Gold'), 383: (22, 'Chrome Silver'), 60: (57, 'Chrome Antique Brass'), 64: (122, 'Chrome Black'), 61: (52, 'Chrome Blue'), 62: (64, 'Chrome Green'), 63: (82, 'Chrome Pink'), # Pearl Colors 183: (83, 'Pearl White'), 150: (119, 'Pearl Very Light Gray'), 135: (66, 'Pearl Light Gray'), 179: (95, 'Flat Silver'), 148: (77, 'Pearl Dark Gray'), 137: (78, 'Metal Blue'), 142: (61, 'Pearl Light Gold'), 297: (115, 'Pearl Gold'), 178: (81, 'Flat Dark Gold'), 134: (84, 'Copper'), # Metallic Colors 80: (67, 'Metallic Silver'), 81: (70, 'Metallic Green'), 82: (65, 'Metallic Gold'), # Milky Colors 79: (60, 'Milky White'), 1000: (159, 'Glow in Dark White'), 21: (46, 'Glow In Dark Opaque'), 294: (118, 'Glow In Dark Trans'), # Glitter Colors 117: (101, 'Glitter Trans-Clear'), 1002: (163, 'Glitter Trans-Neon Green'), 1003: (162, 'Glitter Trans-Light Blue'), 129: (102, 'Glitter Trans-Purple'), 114: (100, 'Glitter Trans-Dark Pink'), # Speckle Colors 132: (111, 'Speckle Black-Silver'), 133: (151, 'Speckle Black-Gold'), 75: (116, 'Speckle Black-Copper'), 76: (117, 'Speckle DBGray-Silver'), # missing: (160, 'Fabuland Orange'), (161, 'Dark Yellow'), Modulex Colors 9999: (-1, '(No Color)'), -1: (-1, 'Unknown'), 89: (-1, 'Royal Blue'), # part bb556 of set 2852725 }
""" Root-level catalog interface """ class ValidationError(Exception): pass class PrivateArchive(Exception): pass class EntityNotFound(Exception): pass class NoAccessToEntity(Exception): """ Used when the actual entity is not accessible, i.e. when a ref cannot dereference itself """ pass class AbstractQuery(object): """ Not-qute-abstract base class for executing queries Query implementation must provide: - origin (property) - _iface (generator: itype) - _tm (property) a TermManager """ _validated = None ''' Overridde these methods ''' @property def origin(self): return NotImplemented def make_ref(self, entity): raise NotImplementedError def _perform_query(self, itype, attrname, exc, *args, strict=False, **kwargs): raise NotImplementedError ''' Internal workings ''' ''' Can be overridden ''' def _grounded_query(self, origin): """ Pseudo-abstract method used to construct entity references from a query that is anchored to a metaresource. must be overriden by user-facing subclasses if resources beyond self are required to answer the queries (e.g. a catalog). :param origin: :return: """ return self """ Basic "Documentary" interface implementation From JIE submitted: - get(id) - properties(id) - get item(id, item) - get reference(id) - synonyms(id-or-string) provided but not spec'd: - validate - get_uuid """ def validate(self): if self._validated is None: try: self._perform_query('basic', 'validate', ValidationError) self._validated = True except ValidationError: self._validated = False return self._validated def get(self, eid, **kwargs): """ Basic entity retrieval-- should be supported by all implementations :param eid: :param kwargs: :return: """ return self._perform_query('basic', 'get', EntityNotFound, eid, **kwargs) def properties(self, external_ref, **kwargs): """ Get an entity's list of properties :param external_ref: :param kwargs: :return: """ return self._perform_query('basic', 'properties', EntityNotFound, external_ref, **kwargs) def get_item(self, external_ref, item): """ access an entity's dictionary items :param external_ref: :param item: :return: """ ''' if hasattr(external_ref, 'external_ref'): # debounce err_str = external_ref.external_ref else: err_str = external_ref ''' return self._perform_query('basic', 'get_item', EntityNotFound, external_ref, item) def get_uuid(self, external_ref): return self._perform_query('basic', 'get_uuid', EntityNotFound, external_ref) def get_reference(self, external_ref): return self._perform_query('basic', 'get_reference', EntityNotFound, external_ref) def synonyms(self, item, **kwargs): """ Return a list of synonyms for the object -- quantity, flowable, or compartment :param item: :return: list of strings """ return self._perform_query('basic', 'synonyms', EntityNotFound, item, **kwargs)
def get_gender(sex='unknown'): if sex == 'm': sex = 'male' elif sex == 'f': sex = 'female' print(sex) get_gender('m') get_gender('f') get_gender()
# 選択肢が書き換えられないようにlistではなくtupleを使う chose_from_two = ('A', 'B', 'C') answer = [] answer.append('A') answer.append('C') print(chose_from_two) # ('A', 'B', 'C') print(answer) # ['A', 'C']
palavras = ('programacao','nomes','legal','que bacana','yeaaah','astronomia') for i in palavras: print(f"Na palavra {i} há as vogais", end=' ') for j in i: if j.lower() in ('aeiou'): print (f"{j}", end=',') print("\n")
description = 'Example Sans2D Pixel Detector Setup with Instrument View' group = 'basic' sysconfig = dict( instrument = 'sans2d', ) devices = dict( sans2d = device('nicos_demo.mantid.devices.instrument.ViewableInstrument', description = 'instrument object', responsible = 'R. Esponsible <r.esponsible@stfc.ac.uk>', instrument = 'sans2d', website = 'http://www.nicos-controls.org', operators = ['ISIS developer team'], facility = 'ISIS demo instruments', idf = 'SANS2D_Definition.xml' ), sample = device('nicos_mlz.sans1.devices.sans1_sample.Sans1Sample', description = 'sample object', ), mot_z = device('nicos.devices.generic.VirtualMotor', description = 'front detector position in the tube', abslimits = (19.281, 23.281), curvalue = 23.281, precision = 3, speed = 1, unit = 'm', fmtstr = '%.3f', ), mot_x = device('nicos.devices.generic.VirtualMotor', description = 'horizontal offset of detector', abslimits = (1.0, 5.0), speed = 0.5, unit = 'm', curvalue = 1.1, ), mot_omega = device('nicos.devices.generic.VirtualMotor', description = 'tilt of detector', abslimits = (-40, 40), speed = 1.5, unit = 'deg', curvalue = 0, fmtstr = '%.1f', ), mantid_move_det = device('nicos_demo.mantid.devices.devices.MantidTranslationDevice', args = {'RelativePosition': False, 'ComponentName': 'front-detector'}, x = 'mot_x', z = 'mot_z', lowlevel = True, ), mantid_rot_det = device('nicos_demo.mantid.devices.devices.MantidRotationDevice', args = {'RelativeRotation': False, 'ComponentName': 'front-detector'}, y = 1, angle = 'mot_omega', lowlevel = True, ), ) startupcode = ''' printinfo("============================================================") printinfo("Welcome to the Sans 2D Instrument View demo setup.") printinfo("============================================================") '''
class Student: def __init__(self,name="",roll=2): print("para init called") self.name=name self.roll_no=roll def hello(self): print("Hello this is: ",self.name) print("Your roll no. is: ",self.roll_no)
description = 'pressure filter readout' group = 'lowlevel' devices = dict( # p_in_filter = device('nicos_mlz.sans1.devices.wut.WutValue', # hostname = 'sans1wut-p-diff-fak40.sans1.frm2', # port = '1', # description = 'pressure in front of filter', # fmtstr = '%.2F', # loglevel = 'info', # unit = 'bar', # ), # p_out_filter = device('nicos_mlz.sans1.devices.wut.WutValue', # hostname = 'sans1wut-p-diff-fak40.sans1.frm2', # port = '2', # description = 'pressure behind of filter', # fmtstr = '%.2F', # loglevel = 'info', # unit = 'bar', # ), # p_diff_filter = device('nicos_mlz.sans1.devices.wut.WutDiff', # description = 'pressure in front of filter minus pressure behind filter', # dev1 = 'p_in_filter', # dev2 = 'p_out_filter', # fmtstr = '%.2F', # loglevel = 'info', # unit = 'bar', # ), )
#Python doesn't support Generics #you can do it like this in java or C++ or #any other Object Oriented language which supports Generics class AdvancedArithmetic(object): def divisorSum(n): raise NotImplementedError class Calculator(AdvancedArithmetic): def divisorSum(self, n): divisor=[] for i in range(n): x = len([i for i in range(1,n+1) if n % i]) divisor.append(x) res = sum(divisor) return res n = int(input()) my_calculator = Calculator() s = my_calculator.divisorSum(n) print("I implemented: " + type(my_calculator).__bases__[0].__name__) print(s)
class Solution: def solve(self, nums, k): history = [nums[:]] seen = {tuple(nums)} before_cycle = [] cycle = [] while True: nums2 = [0]*8 for i in range(1,7): l = (nums[i-1] if i-1 >= 0 else 0) + (nums[i+1] if i+1 < 8 else 0) nums2[i] = 1 - l%2 nums = nums2 if tuple(nums) in seen: i = history.index(nums) before_cycle = history[:i] cycle = history[i:] break history.append(nums[:]) seen.add(tuple(nums)) return before_cycle[k] if k < len(before_cycle) else cycle[(k-len(before_cycle))%len(cycle)]
expected_output = { "Tunnel10": { "bandwidth": 100, "counters": { "in_abort": 0, "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "last_clear": "17:00:12", "out_broadcast_pkts": 0, "out_buffer_failure": 0, "out_buffers_swapped": 0, "out_collision": 0, "out_errors": 0, "out_interface_resets": 0, "out_multicast_pkts": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 }, }, "delay": 50000, "enabled": True, "encapsulations": { "encapsulation": "tunnel" }, "ipv4": { "1.1.1.3/24": { "ip": "1.1.1.3", "prefix_length": "24" }, }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mtu": 9980, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 0, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "tunnel_destination_ip": "1.1.10.11", "tunnel_protocol": "AURP", "tunnel_receive_bandwidth": 1000000, "tunnel_source_ip": "1.1.10.10", "tunnel_transmit_bandwidth": 10000000, "tunnel_transport_mtu": 1480, "tunnel_ttl": 255, "txload": "1/255", "type": "Tunnel" }, "Tunnel4": { "bandwidth": 100, "counters": { "in_abort": 0, "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "last_clear": "00:02:56", "out_broadcast_pkts": 0, "out_buffer_failure": 0, "out_buffers_swapped": 0, "out_collision": 0, "out_errors": 0, "out_interface_resets": 0, "out_multicast_pkts": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 }, }, "delay": 50000, "enabled": True, "encapsulations": { "encapsulation": "tunnel" }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mtu": 9976, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 0, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "tunnel_protocol": "GRE/IP", "tunnel_receive_bandwidth": 8000, "tunnel_source_ip": "192.168.1.100", "tunnel_transmit_bandwidth": 8000, "tunnel_transport_mtu": 1476, "tunnel_ttl": 255, "txload": "1/255", "type": "Tunnel" }, "Tunnel5": { "bandwidth": 100, "counters": { "in_abort": 0, "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "last_clear": "00:01:30", "out_broadcast_pkts": 0, "out_buffer_failure": 0, "out_buffers_swapped": 0, "out_collision": 0, "out_errors": 0, "out_interface_resets": 0, "out_multicast_pkts": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 }, }, "delay": 50000, "enabled": True, "encapsulations": { "encapsulation": "tunnel" }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mtu": 9976, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 0, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "tunnel_destination_ip": "7.7.7.8", "tunnel_protocol": "GRE/IP", "tunnel_receive_bandwidth": 8000, "tunnel_source_ip": "7.7.7.7", "tunnel_source_interface": 'Loopback100', "tunnel_transmit_bandwidth": 8000, "tunnel_transport_mtu": 1476, "tunnel_ttl": 255, "txload": "1/255", "type": "Tunnel" }, "Tunnel6": { "bandwidth": 100, "counters": { "in_abort": 0, "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "last_clear": "00:00:38", "out_broadcast_pkts": 0, "out_buffer_failure": 0, "out_buffers_swapped": 0, "out_collision": 0, "out_errors": 0, "out_interface_resets": 0, "out_multicast_pkts": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 }, }, "delay": 50000, "enabled": True, "encapsulations": { "encapsulation": "tunnel" }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mtu": 9976, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 0, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "tunnel_destination_ip": "1.2.3.4", "tunnel_protocol": "GRE/IP", "tunnel_receive_bandwidth": 8000, "tunnel_source_ip": "UNKNOWN", "tunnel_transmit_bandwidth": 8000, "tunnel_transport_mtu": 1476, "tunnel_ttl": 255, "txload": "1/255", "type": "Tunnel" }, "Tunnel7": { "bandwidth": 100, "counters": { "in_abort": 0, "in_broadcast_pkts": 0, "in_crc_errors": 0, "in_errors": 0, "in_frame": 0, "in_giants": 0, "in_ignored": 0, "in_multicast_pkts": 0, "in_no_buffer": 0, "in_octets": 0, "in_overrun": 0, "in_pkts": 0, "in_runts": 0, "in_throttles": 0, "last_clear": "00:00:45", "out_broadcast_pkts": 0, "out_buffer_failure": 0, "out_buffers_swapped": 0, "out_collision": 0, "out_errors": 0, "out_interface_resets": 0, "out_multicast_pkts": 0, "out_octets": 0, "out_pkts": 0, "out_underruns": 0, "out_unknown_protocl_drops": 0, "rate": { "in_rate": 0, "in_rate_pkts": 0, "load_interval": 300, "out_rate": 0, "out_rate_pkts": 0 }, }, "delay": 50000, "enabled": True, "encapsulations": { "encapsulation": "tunnel" }, "last_input": "never", "last_output": "never", "line_protocol": "down", "mtu": 9976, "oper_status": "down", "output_hang": "never", "port_channel": { "port_channel_member": False }, "queues": { "input_queue_drops": 0, "input_queue_flushes": 0, "input_queue_max": 375, "input_queue_size": 0, "output_queue_max": 0, "output_queue_size": 0, "queue_strategy": "fifo", "total_output_drop": 0 }, "reliability": "255/255", "rxload": "1/255", "tunnel_protocol": "GRE/IP", "tunnel_receive_bandwidth": 8000, "tunnel_source_ip": "9.45.21.231", "tunnel_source_interface": 'GigabitEthernet2', "tunnel_transmit_bandwidth": 8000, "tunnel_transport_mtu": 1476, "tunnel_ttl": 255, "txload": "1/255", "type": "Tunnel" } }
input = open('input.txt'); length = int(input.readline()); tokens = input.readline().split(' '); input.close(); output = open('output.txt' , 'w'); i = 0; while i < length: j = 0; while (int(tokens[i]) >= int(tokens[j])) & (j < i): j += 1; if j < i: shelf = tokens[i]; k = i; while k > j: tokens[k] = tokens[k - 1]; k -= 1; tokens[j] = shelf; output.write(str(j + 1) + ' '); else: output.write(str(i + 1) + ' '); i += 1; output.write('\n'); for element in tokens: output.write(element + ' '); output.close();
MSG_START = "Hello, {name}\!\n\nPlease, choose your language\." MSG_NOTIFY_EN = ( """Hello, {first_name}\!\n\n""" """As of {timestamp}, your order `{id}` has arrived to our base.\n""" """We are going to deliver it to your address _{address}_ no later than in 3 days.\n\n""" """*Product Details:*\n""" """Product: {product}\n""" """Model: {model}\n""" """Price: €{price:.2f}\n""" """Amount: {amount}\n""" """Weight: {weight:.3f} kg\n""" """ID: {id}""" ) MSG_NOTIFY_RU = ( """Здравствуйте, {first_name}\!\n\n""" """{timestamp} Ваш заказ `{id}` доставлен в наш центр.\n""" """Мы доставим его по Вашему адресу _{address}_ не позже, чем через 3 дня.\n\n""" """*Детали заказа:*\n""" """Товар: {product}\n""" """Модель: {model}\n""" """Цена: €{price:.2f}\n""" """Количество: {amount}\n""" """Вес: {weight:.3f} кг\n""" """ID: {id}""" )
#!/usr/bin/env python ''' Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. ''' """ Python Kerberos GSS APIs used by spnego_kerberos_auth.py. It is used as a place holder for kerberos.py which is not available. """ class KrbError(Exception): pass class GSSError(KrbError): pass def authGSSClientInit(service): pass def authGSSClientClean(context): pass def authGSSClientStep(context, challenge): pass def authGSSClientResponse(context): pass
expected_output = { "ospf-database-information": { "ospf-area-header": {"ospf-area": "192.168.76.0"}, "ospf-database": { "@heading": "Type ID Adv Rtr Seq Age Opt Cksum Len", "advertising-router": "192.168.219.235", "age": "1730", "checksum": "0x1b56", "lsa-id": "10.69.197.1", "lsa-length": "36", "lsa-type": "Network", "options": "0x22", "ospf-network-lsa": { "address-mask": "255.255.255.128", "attached-router": [ "192.168.219.235", "10.69.198.249", "192.168.219.236", ], "ospf-lsa-topology": { "ospf-lsa-topology-link": [ { "link-type-name": "Transit", "ospf-lsa-topology-link-metric": "0", "ospf-lsa-topology-link-node-id": "192.168.219.236", "ospf-lsa-topology-link-state": "Bidirectional", }, { "link-type-name": "Transit", "ospf-lsa-topology-link-metric": "0", "ospf-lsa-topology-link-node-id": "10.69.198.249", "ospf-lsa-topology-link-state": "Bidirectional", }, { "link-type-name": "Transit", "ospf-lsa-topology-link-metric": "0", "ospf-lsa-topology-link-node-id": "192.168.219.235", "ospf-lsa-topology-link-state": "Bidirectional", }, ], "ospf-topology-id": "default", "ospf-topology-name": "default", }, }, "our-entry": True, "sequence-number": "0x80000026", }, } }
# 1.Why carry is a&b: # If a and b are both 1 at the same digit, it creates one carry. # Because you can only use 0 and 1 in binary, if you add 1+1 together, it will roll that over to the next digit, and the value will be 0 at this digit. # if they are both 0 or only one is 1, it doesn't need to carry. # Use ^ operation between a and b to find the different bit # In my understanding, using ^ operator is kind of adding a and b together (a+b) but ignore the digit that a and b are both 1, # because we already took care of this in step1. class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ INFINITY = 0xffffffff while b & INFINITY != 0: carry = (a & b) << 1 a = a ^ b b = carry # for overflow condition like # -1 # 1 return (a & INFINITY) if b > INFINITY else a sol = Solution() output = sol.getSum(-1, 1) print('Res: ', output)
while True: h = int(input()) if h == 0: break arr = list() arr.append(h) while h != 1: if h%2 == 0: h = int((0.5)*h) arr.append(h) else: h = 3 * h + 1 arr.append(h) # print(arr) print(max(arr))
def read_input(): row, col = [int(x) for x in input().split()] arr = [list(input()) for _ in range(row)] return arr def print_output(obj): for i in obj: print(''.join(i)) def test_pos(obj, grid, row, col): for i in range(len(obj)): for j in range(len(obj[0])): if grid[row + i][col + j] != '.' and obj[i][j] != '.': return False return True def place_at_pos(obj, grid, row, col): arr = grid for i in range(len(obj)): for j in range(len(obj[0])): if obj[i][j] != '.': arr[row + i][col + j] = obj[i][j] return arr ob = read_input() gr = read_input() positions = [] for di in range(len(gr) - len(ob) + 1): for dj in range(len(gr[0]) - len(ob[0]) + 1): if test_pos(ob, gr, di, dj): positions.append((di, dj)) print(len(positions)) if len(positions) == 1: display = place_at_pos(ob, gr, positions[0][0], positions[0][1]) print_output(display)
# import pytest class TestSingletonMeta: def test___call__(self): # synced assert True class TestSingleton: pass
i = 0 result = 0 while i <= 100: if i % 2 == 0: result += i i += 1 print(result) j = 0 result2 = 0 while j <= 100: result2 += j j += 2 print(result2)
# test for PR#112 -- functions should not have __module__ attributes def f(): pass if hasattr(f, '__module__'): print('functions should not have __module__ attributes') # but make sure classes still do have __module__ attributes class F: pass if not hasattr(F, '__module__'): print('classes should still have __module__ attributes')
# kano00 # https://adventofcode.com/2021/day/10 def calc1(chunk_list): left_brankets = ["(", "[", "{", "<"] right_brankets = [")", "]", "}", ">"] scores = [3,57,1197,25137] res = 0 def calc_points(chunk): stack = [] for c in chunk: for i in range(4): if c == left_brankets[i]: stack.append(i) elif c== right_brankets[i]: if len(stack) == 0: print("error") return 0 else: # if corrupted if right_brankets[stack.pop()] != c: return scores[i] return 0 for chunk in chunk_list: res += calc_points(chunk) return res def calc2(chunk_list): left_brankets = ["(", "[", "{", "<"] right_brankets = [")", "]", "}", ">"] scores = [1, 2, 3, 4] res_options = [] def calc_remains(chunk): stack = [] for c in chunk: for i in range(4): if c == left_brankets[i]: stack.append(i) elif c== right_brankets[i]: if len(stack) == 0: print("error") return [] else: # if corrupted if right_brankets[stack.pop()] != c: return [] return stack def calc_points(remains): points = 0 while len(remains): p = remains.pop() points = points * 5 + scores[p] return points for chunk in chunk_list: remains = calc_remains(chunk) if remains: points = calc_points(remains) res_options.append(points) res_options.sort() res = res_options[len(res_options)//2] return res if __name__ == "__main__": chunk_list= [] i = input() while i: chunk_list.append(i) i = input() res = calc2(chunk_list) print(res)
def show_magicians(magician_names, great_magicians): """Transfer the lis of magician in the great list""" while magician_names: magician = magician_names.pop() great_magicians.append(magician) def make_great(great_magicians): """Print the new list of magicians""" for great_magician in great_magicians: print('The great ' + great_magician) magician_names = ['albus', 'harry potter', 'merlin'] great_magicians = [] show_magicians(magician_names[:], great_magicians) make_great(great_magicians) print(magician_names) print(great_magicians)
#!/usr/bin/python li = [1, 2, 3, 1, 4, 5] # wrong 1 for v in li: if v == 1 or v == 2: li.remove(v) # wrong 2 for idx, v in enumerate(li): if v == 1 or v == 2: del li[idx] # wrong 3 for idx, v in enumerate(li[:]): if v == 1 or v == 2: del li[idx] # not recommend for v in li[:]: if v == 1 or v == 2: li.remove(v) # recommend 1 li = list(filter(lambda x: x != 1 and x != 2, li)) # recommend 2 li = [x for x in li if x != 1 and x != 2]
def candidate_selection(wn, token, target_lemma, pos=None, gold_lexkeys=set(), debug=False): """ return candidate synsets of a token :param str token: the token :param str targe_lemma: a lemma :param str pos: supported: n, v, r, a. If None, candidate selection is limited by one pos :param str gold_lexkeys: {'congress%1:14:00::'} :rtype: tuple :return: (candidate_synsets, gold_in_candidates) """ if token.istitle(): candidate_synsets = wn.synsets(token, pos) if not candidate_synsets: candidate_synsets = wn.synsets(target_lemma, pos) else: candidate_synsets = wn.synsets(target_lemma, pos) return candidate_synsets def synset2identifier(synset, wn_version): """ return synset identifier of nltk.corpus.reader.wordnet.Synset instance :param nltk.corpus.reader.wordnet.Synset synset: a wordnet synset :param str wn_version: supported: '171 | 21 | 30' :rtype: str :return: eng-VERSION-OFFSET-POS (n | v | r | a) e.g. """ offset = str(synset.offset()) offset_8_char = offset.zfill(8) pos = synset.pos() if pos in {'j', 's'}: pos = 'a' identifier = 'eng-{wn_version}-{offset_8_char}-{pos}'.format_map(locals()) return identifier
""" Write a Python function to map two lists into a dictionary. list1 contains the keys, list2 contains the values. Input lists: list1 = [1,2,3,4,5] list2 = [6,7,8,9,10] Expected output: {1: 6, 2: 7, 3: 8, 4: 9, 5: 10} """ #Solution is: def map_lists(list1,list2): return (dict(zip(list1,list2)))
largest = None smallest = None numbers = list() while True: num = input('Enter a number: ') if num == "done": if numbers == []: max = '(no input)' min = '(no input)' else: max = max(numbers) min = min(numbers) break try: num = int(num) except: print('Invalid input') continue num = float(num) numbers.append(num) print('Maximum is', max) print('Minimum is', min)
# Iterable Data # - String # - List # - Set # - Dictionary for x in [3,5,2]: print(x) for x in "abc": print(x) for x in {"x":"123", "a":"456"}: print(x) ########## # max(iterable data) # sorted (iterable data) result=max([30, 20, 50, 10]) print(result) result2=sorted([30, 20, 50, 10]) print(result2)
print(population/area) # De indices worden gebruitk om te achterhalen welke elementen bij elkaar horen. # Strings kun je gewoon optellen! df1 = make_df(list('AB'), range(2)) # print(df1) df2 = make_df(list('ACB'), range(3)) # print(df2) print(df1+df2) # Alleen overeenkomstige kolommen zijn gebruikt, en de volgorde van deze kolommen is irrelevant. Zelfde geldt voor indices. print() df1 = make_df('AB', [1, 2]) df2 = make_df('AB', [3, 4]) print(pd.concat([df1, df2])) # default: ze worden onder elkaar gehangen print() print(pd.concat([df1, df2], axis=1)) # Nu wil concat ze naast elkaar hebben, maar indices van de rijen komen nergens overeen. print() df3 = make_df('AB', [1, 3]) print(pd.concat([df1, df3])) # Er ontstaan dubbele indices. Optie "verify_integrity=True" zou dat ondervangen. Probeer maar! print() koffiefile = os.path.join('data', 'csvoorbeeld.csv') koffie = pd.read_csv(koffiefile, ) # check de help voor alle opties! koffiemerken = pd.DataFrame({'Merk':['Palazzo', "G'woon", "L'Or", "Nescafe"], "Land":['Nederland', 'Nederland', 'Frankrijk', 'Duitsland']}) # merging zonder specificatie van merge-key resulteert in een merge op overeenkomstige kolommen. # Zonder het voorbeeld uit te werken: een outer join is altijd het grootst. Onderzoek hoe deze werkt! Hier is de outer join: koffie.merge(koffiemerken, how='outer')
class Solution(object): def XXX(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 return max (self.XXX(root.left)+1 , self.XXX(root.right)+1)
n = int(input()) dot = (2 ** n) + 1 result = dot * dot print(result)
var1 = "Hello " var2 = "World" # + Operator is used to combine strings var3 = var1 + var2 print(var3)
#x = 3 #x = x*x #print(x) #y = input('enter a number:') #print(y) #x = int(input('Enter an integer')) #if x%2 == 0: # print('Even') #else: # print('Odd') # if x%3 != 0: # print('And not divisible by 3') #Find the cube root of a perfect cube #x = int(input('Enter an integer')) #ans = 0 #while ans*ans*ans < abs(x): # ans = ans + 1 # print('current guess =', ans) #if ans*ans*ans != abs(x): # print(x, 'is not a perfect cube') #elif x < 0: # print('You entered a negative number') # ans = -ans #print('Cube root of ' + str(x) + ' is ' + str(ans)) for i in range(1,101): s = str(i) if i % 3 == 0 or i % 5 == 0: s = '' if i % 3 == 0: s = s + 'Fizz' if i % 5 == 0: s = s + 'Buzz' print(s)
class Order: def __init__(self, orderInfo): self.order_id = orderInfo[0] self.customer_id =int(orderInfo[1]) self.order_date = orderInfo[2] self.status = orderInfo[3] self.total_price = float(orderInfo[4]) self.comment = orderInfo[5]
# # PySNMP MIB module Unisphere-Data-Registry (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-Registry # Produced by pysmi-0.3.4 at Wed May 1 15:31:00 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Integer32, Gauge32, ObjectIdentity, iso, ModuleIdentity, NotificationType, Counter64, Bits, Counter32, Unsigned32, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Integer32", "Gauge32", "ObjectIdentity", "iso", "ModuleIdentity", "NotificationType", "Counter64", "Bits", "Counter32", "Unsigned32", "TimeTicks") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") usAdmin, = mibBuilder.importSymbols("Unisphere-SMI", "usAdmin") usDataAdmin = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2)) usDataAdmin.setRevisions(('2001-09-25 15:25', '2001-06-01 21:18',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: usDataAdmin.setRevisionsDescriptions(('Change the name of the MRX.', 'Initial version of this SNMP management information module.',)) if mibBuilder.loadTexts: usDataAdmin.setLastUpdated('200109251525Z') if mibBuilder.loadTexts: usDataAdmin.setOrganization('Unisphere Networks, Inc.') if mibBuilder.loadTexts: usDataAdmin.setContactInfo(' Unisphere Networks, Inc. Postal: 10 Technology Park Drive Westford, MA 01886 USA Tel: +1 978 589 5800 Email: mib@UnisphereNetworks.com') if mibBuilder.loadTexts: usDataAdmin.setDescription('Administratively assigned object identifiers for Unisphere Networks data communications products.') usDataRegistry = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 1)) if mibBuilder.loadTexts: usDataRegistry.setStatus('current') if mibBuilder.loadTexts: usDataRegistry.setDescription('The root for administratively assigned object identifiers for Unisphere Networks Data cross-product objects.') usdErxRegistry = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 4, 2, 2)) usdMrxRegistry = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 4, 2, 3)) usDataEntPhysicalType = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 4, 2, 1, 1)) usdPcmciaFlashCard = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 1, 1, 1)) if mibBuilder.loadTexts: usdPcmciaFlashCard.setStatus('current') if mibBuilder.loadTexts: usdPcmciaFlashCard.setDescription('The vendor type id for a standard PCMCIA flash card.') usd85MegT2FlashCard = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 1, 1, 1, 1)) if mibBuilder.loadTexts: usd85MegT2FlashCard.setStatus('current') if mibBuilder.loadTexts: usd85MegT2FlashCard.setDescription('The vendor type id for an 85 Megabyte Type II ATA PCMCIA flash card (Product Code: PCM-85).') usd220MegT2FlashCard = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 1, 1, 1, 2)) if mibBuilder.loadTexts: usd220MegT2FlashCard.setStatus('current') if mibBuilder.loadTexts: usd220MegT2FlashCard.setDescription('The vendor type id for a 220 Megabyte Type II ATA PCMCIA flash card (Product Code: FLASH-220M).') usdTraceRouteImplementationTypes = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 4, 2, 1, 2)) usdTraceRouteUsingIcmpProbe = ObjectIdentity((1, 3, 6, 1, 4, 1, 4874, 4, 2, 1, 2, 1)) if mibBuilder.loadTexts: usdTraceRouteUsingIcmpProbe.setStatus('current') if mibBuilder.loadTexts: usdTraceRouteUsingIcmpProbe.setDescription('Indicates that an implementation is using ICMP probes to perform the trace-route operation.') mibBuilder.exportSymbols("Unisphere-Data-Registry", usdMrxRegistry=usdMrxRegistry, usd220MegT2FlashCard=usd220MegT2FlashCard, usDataRegistry=usDataRegistry, usdPcmciaFlashCard=usdPcmciaFlashCard, usDataAdmin=usDataAdmin, usd85MegT2FlashCard=usd85MegT2FlashCard, PYSNMP_MODULE_ID=usDataAdmin, usdTraceRouteUsingIcmpProbe=usdTraceRouteUsingIcmpProbe, usDataEntPhysicalType=usDataEntPhysicalType, usdErxRegistry=usdErxRegistry, usdTraceRouteImplementationTypes=usdTraceRouteImplementationTypes)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon May 6 19:14:57 2019 @author: athreya """ #Python Programming #Print function: Prints the given text within single/double quotes print('Hi wecome to Python!') #Hi wecome to Python! print("Hello World") #Hello World #Strings: Text in Python is considered a specific type of data called a string. print("Hello World this is Manoj") #Hello World this is Manoj print('Here is the place where you can learn python') #Here is the place where you can learn python print("Hello" + "Python") #HelloPython #Multi-line Strings pond='''The old pond, A frog jumps in: Plop!''' #Variables: Deals with data that changes over time. todays_date = "May 06, 2019" print(todays_date) todays_date = "May 07, 2019" print(todays_date) #Arithmetic Operations add=3+2 sub=7-5 mul=5*5 div=7/3 mod=9%2 print(add,sub,mul,div,mod) #5 2 25 2.3333333333333335 1 a=5/3 b=float(5)/float(3) print(int(a)) #1 print(b) #1.6666666666667 #Numbers #Create a new variable called total_cost which is the product of how many #cucumbers you are going to buy and the cost per cucumber cucumbers=7 price_per_cucumber=3.25 total_cost=cucumbers*price_per_cucumber print(total_cost) #22.75 a=55 b=6 c=float(a/b) print(c) #9.1666666666666666666666 #Booleans #True or False value skill_completed = "Python Syntax" exercises_completed = 13 points_per_exercise = 5 point_total = 100 point_total += exercises_completed*points_per_exercise print("I got "+str(point_total)+" points!") #I got 165 points
RULE_TO_REMOVE = \ """ { "data-source-definition-name": "__RuleToRemove", "model-id": "__RuleToRemove", "model-description": "System DSD for marking rules to be removed.", "can-reflect-on-web": false, "fields": [ { "field-name": "rule_name", "type": "STRING", "use-as": "primary-key" } ] } """
# el binary searc solo sirve con una lista ordenada def run(): sequence = [1,2,3,4,5,6,7,8,9,10,11] print(binary_search(sequence,-5)) def binary_search(list,goal,start=None,end=None): if start is None: start = 0 if end is None: end = len(list)-1 midpoint = (start + end)//2 if end < start: return -1 elif list[midpoint] == goal: return midpoint elif list[midpoint] > goal: return binary_search(list,goal,start,midpoint-1) else: return binary_search(list,goal,midpoint+1,end) if __name__ == "__main__": run()
# Func11.py def calc(n,m): return [n+m, n-m, n*m, n/m] print(calc(20, 10)) a,b,c,d = calc(20,10) print(a,b,c,d) # + - * / def swap(n,m): return m, n x= 200 y= 100 x,y = swap(x,y) print(x,y) # 100, 200
""" DeskUnity """ class Event: TEST = "TEST" CONNECTION_TEST = "CONNECTION_TEST" MOVE_MOUSE = "MOVE_MOUSE" MOUSE_LEFT_DOWN = "MOUSE_LEFT_DOWN" MOUSE_LEFT_UP = "MOUSE_LEFT_UP" MOUSE_RIGHT_DOWN = "MOUSE_RIGHT_DOWN" MOUSE_RIGHT_UP = "MOUSE_RIGHT_UP" MOUSE_WHEEL = "MOUSE_WHEEL" KEY_UP = "KEY_UP" KEY_DOWN = "KEY_DOWN" CLIPBOARD = "CLIPBOARD" CHANGE_POSITION = "CHANGE_POSITION" SERVER_SHUT = "SERVER_SHUT" def __init__(self, name, value="", client=None, computer=None): self.name = name self.value = value self.client = client self.computer = computer