content
stringlengths
7
1.05M
""" Module: 'esp32' on esp32 1.11.0 """ # MCU: (sysname='esp32', nodename='esp32', release='1.11.0', version='v1.11-324-g40844fd27 on 2019-07-17', machine='ESP32 module with ESP32') # Stubber: 1.2.0 class ULP: '' RESERVE_MEM = 0 def load_binary(): pass def run(): pass def set_wakeup_period(): pass WAKEUP_ALL_LOW = None WAKEUP_ANY_HIGH = None def hall_sensor(): pass def raw_temperature(): pass def wake_on_ext0(): pass def wake_on_ext1(): pass def wake_on_touch(): pass
def isEscapePossible(self, blocked, source, target): blocked = set(map(tuple, blocked)) def dfs(x, y, target, seen): if ( not (0 <= x < 10 ** 6 and 0 <= y < 10 ** 6) or (x, y) in blocked or (x, y) in seen ): return False seen.add((x, y)) if len(seen) > 20000 or [x, y] == target: return True return ( dfs(x + 1, y, target, seen) or dfs(x - 1, y, target, seen) or dfs(x, y + 1, target, seen) or dfs(x, y - 1, target, seen) ) return dfs(source[0], source[1], target, set()) and dfs( target[0], target[1], source, set() )
# (c) Copyright IBM Corp. 2019. All Rights Reserved. """Class to handle manipulating the ServiceNow Records Data Table""" class ServiceNowRecordsDataTable(object): """Class that handles the sn_records_dt datatable""" def __init__(self, res_client, incident_id): self.res_client = res_client self.incident_id = incident_id self.api_name = "sn_records_dt" self.data = None self.rows = None self.get_data() def as_dict(self): """Returns this class object as a dictionary""" return self.__dict__ def get_data(self): """Gets that data and rows of the data table""" uri = "/incidents/{0}/table_data/{1}?handle_format=names".format(self.incident_id, self.api_name) try: self.data = self.res_client.get(uri) self.rows = self.data["rows"] except Exception as err: raise ValueError("Failed to get sn_records_dt Datatable", err) def get_row(self, cell_name, cell_value): """Returns the row if found. Returns None if no matching row found""" for row in self.rows: cells = row["cells"] if cells[cell_name] and cells[cell_name].get("value") and cells[cell_name].get("value") == cell_value: return row return None def get_sn_ref_id(self, res_id): """Returns the sn_ref_id that relates to the res_id""" row = self.get_row("sn_records_dt_res_id", res_id) if row is not None: cells = row["cells"] return str(cells["sn_records_dt_sn_ref_id"]["value"]) return None def add_row(self, time, name, res_type, res_id, sn_ref_id, res_status, snow_status, link): """Adds a new row to the data table and returns that row""" # Generate uri to POST datatable row uri = "/incidents/{0}/table_data/{1}/row_data?handle_format=names".format(self.incident_id, self.api_name) cells = [ ("sn_records_dt_time", time), ("sn_records_dt_name", name), ("sn_records_dt_type", res_type), ("sn_records_dt_res_id", res_id), ("sn_records_dt_sn_ref_id", sn_ref_id), ("sn_records_dt_res_status", res_status), ("sn_records_dt_snow_status", snow_status), ("sn_records_dt_links", link) ] formatted_cells = {} # Format the cells for cell in cells: formatted_cells[cell[0]] = {"value": cell[1]} formatted_cells = { "cells": formatted_cells } return self.res_client.post(uri, formatted_cells) def update_row(self, row, cells_to_update): """Updates the row with the given cells_to_update and returns the updated row""" # Generate uri to POST datatable row uri = "/incidents/{0}/table_data/{1}/row_data/{2}?handle_format=names".format(self.incident_id, self.api_name, row["id"]) def get_value(cell_name): """Gets the new or old value of the cell""" if cell_name in cells_to_update: return cells_to_update[cell_name] return row["cells"][cell_name]["value"] cells = [ ("sn_records_dt_time", get_value("sn_records_dt_time")), ("sn_records_dt_name", get_value("sn_records_dt_name")), ("sn_records_dt_type", get_value("sn_records_dt_type")), ("sn_records_dt_res_id", get_value("sn_records_dt_res_id")), ("sn_records_dt_sn_ref_id", get_value("sn_records_dt_sn_ref_id")), ("sn_records_dt_res_status", get_value("sn_records_dt_res_status")), ("sn_records_dt_snow_status", get_value("sn_records_dt_snow_status")), ("sn_records_dt_links", get_value("sn_records_dt_links")) ] formatted_cells = {} # Format the cells for cell in cells: formatted_cells[cell[0]] = {"value": cell[1]} formatted_cells = { "cells": formatted_cells } return self.res_client.put(uri, formatted_cells)
def compute(dna_string1: str, dna_string2: str) -> int: hamming_distance = 0 for index in range(0, len(dna_string1)): if dna_string1[index] is not dna_string2[index]: hamming_distance += 1 return hamming_distance
class Graph(): def __init__(self): self.numberOfNodes = 0 self.adjacentList = {} def __str__(self): return str(self.__dict__) def addVertex(self, node): self.adjacentList[node] = [] self.numberOfNodes += 1 def addEdge(self, nodeA, nodeB): self.adjacentList[nodeA].append(nodeB) self.adjacentList[nodeB].append(nodeA) def showConnections(self): for x in self.adjacentList: print(x, end='-->') for i in self.adjacentList[x]: print(i, end=' ') print() myGraph = Graph() myGraph.addVertex('0') myGraph.addVertex('1') myGraph.addVertex('2') myGraph.addVertex('3') myGraph.addEdge('1', '2') myGraph.addEdge('1', '3') myGraph.addEdge('2', '3') myGraph.addEdge('2', '0') print(myGraph) myGraph.showConnections()
""" # -*- coding: UTF-8 -*- # **********************************************************************************# # File: CONSTANT file. # Author: Myron # **********************************************************************************# """ AVAILABLE_DATA_FIELDS = [ 'cadd', 'cadw', 'cadm', 'cadq', 'scdh1', 'scdh2', 'scdh3', 'scdh4', 'scdd', 'scdw', 'scdm', 'scdq', 'tid', 'tiw', 'tim', 'tiq', 'adj_open_price', 'adj_close_price'] OUTPUT_FIELDS = ['M2B(n)', 'W2B(n)', 'D2B(n)', 'Z(n)', 'WZ(n)', 'T(n)', 'ZQ(n)'] MAX_THREADS = 5 MAX_SINGLE_FACTOR_PERIODS = 40 MAX_GLOBAL_PERIODS = 80 MAX_SYMBOLS_FRAGMENT = 200
nome = input('Nome: ') senha = input('Senha: ') while (senha == nome): print ('erro! Faça novamente.') nome = input('Nome: ') senha = input('Senha: ') print("Finish")
message = "zulkepretest make simpletes cpplest" translate = '' i = len(message) - 1 while i >= 0: translate = translate + message[i] i = i - 1 print("enc message is :"+ translate) print("message :"+ message)
#!python #coding: utf-8 #把字典转换成.属性的访问方式.如d['key'] -> d.key class DictObj: def __init__(self,d:dict): if not isinstance(d,(dict,)): self.__dict__['_dict'] = {} else: self.__dict__['_dict'] = d def __getattr__(self,item): try: return self._dict[item] except KeyError: raise AttributeError('Attribute {} Not Found'.format(item)) #不允许设置属性 def __setattr__(self,key,value): raise NotImplementedError('Attribute {} Not Implemented'.format(key)) d = {'a':1,'b':2} do = DictObj(d) print(do.a) do.a = 3
def whats_up_world(): print("What's up world?") if __name__ == "__main__": whats_up_world()
# list(map(int, input().split())) # int(input()) mod = 998244353 # 貰うDP # Pythonで普通に通った. # Aのような累積, のようなものを使って復元して高速化するケースはよくあるらしい. def main(N, S): dp = [0 if n != 0 else 1 for n in range(N)] # dp[i]はマスiに行く通り数. (答えはdp[-1]), dp[0] = 1 (最初にいる場所だから1通り) A = [0 if n != 0 else 1 for n in range(N)] # dp[i] = A[i] - A[i-1] (i >= 1), A[0] = dp[0] = 1 (i = 0) が成り立つような配列を考える. (累積を取っておく配列) for i in range(1, N): # 今いる点 (注目点) for l, r in S: # 選択行動範囲 (l: 始点, r: 終点) if i - l < 0: # 注目点が選択行動範囲の始点より手前の場合 → 注目点に来るために使用することはできない. break else: # 注目点に来るために使用することができる場合 if i - r <= 0: # lからrの間で,注目点に行くために使用できる点を逆算. そこに行くことができる = 選択行動範囲の値を選択することで注目点に達することができる通り数. dp[i] += A[i-l] else: dp[i] += A[i-l] - A[i-r-1] dp[i] %= mod A[i] = (A[i-1] + dp[i]) % mod print(dp[-1]) if __name__ == '__main__': N, K = list(map(int, input().split())) S = {tuple(map(int, input().split())) for k in range(K)} S = sorted(list(S), key = lambda x:x[0]) # 始点でsort (範囲の重複がないため) main(N, S) ''' # 配るDP # PyPyでもPythonでもTLE → ただのDPでは間に合わない?(最大O(N^2)だから?) def main(N, S): dp = [0 if n != 0 else 1 for n in range(N)] # 初期値 lst_S = sorted(list(S)) for i in range(N): if dp[i] == 0: # 計算時間削減のため, 時間さえ間に合えば不要かも. continue for j in lst_S: # このfor文内で同じものを足す機会が多い→これを削減? if i + j > N - 1: break else: dp[i+j] = (dp[i+j] + dp[i]) % mod print(dp[-1]) if __name__ == '__main__': N, K = list(map(int, input().split())) S = set() for k in range(K): L, R = map(int, input().split()) {S.add(i) for i in range(L, R+1)} main(N, S) '''
""" Faça um programa que leia um numero inteiro positivo N e imprima os numeros naturais de 0 ate N em ordem crescente. """ n = int(input('Digite um numero positivo: ')) print('Contagem ate o numero digitado:', end=' ') for i in range(0, n+1): print(f'{i}', end=' ')
# exception.py class InvalidSystemClock(Exception): """ 时钟回拨异常 """ pass
# -*- coding: utf-8 -*- featureInfo = dict() featureInfo['m21']=[ ['P22','Quality','Set to 0 if the key signature indicates that a recording is major, set to 1 if it indicates that it is minor and set to 0 if key signature is unknown. Music21 addition: if no key mode is found in the piece, analyze the piece to discover what mode it is most likely in.','1'], ['QL1','Unique Note Quarter Lengths','The number of unique note quarter lengths.','1'], ['QL2','Most Common Note Quarter Length','The value of the most common quarter length.','1'], ['QL3','Most Common Note Quarter Length Prevalence','Fraction of notes that have the most common quarter length.','1'], ['QL4','Range of Note Quarter Lengths','Difference between the longest and shortest quarter lengths.','1'], ['CS1','Unique Pitch Class Set Simultaneities','Number of unique pitch class simultaneities.','1'], ['CS2','Unique Set Class Simultaneities','Number of unique set class simultaneities.','1'], ['CS3','Most Common Pitch Class Set Simultaneity Prevalence','Fraction of all pitch class simultaneities that are the most common simultaneity.','1'], ['CS4','Most Common Set Class Simultaneity Prevalence','Fraction of all set class simultaneities that are the most common simultaneity.','1'], ['CS5','Major Triad Simultaneity Prevalence','Percentage of all simultaneities that are major triads.','1'], ['CS6','Minor Triad Simultaneity Prevalence','Percentage of all simultaneities that are minor triads.','1'], ['CS7','Dominant Seventh Simultaneity Prevalence','Percentage of all simultaneities that are dominant seventh.','1'], ['CS8','Diminished Triad Simultaneity Prevalence','Percentage of all simultaneities that are diminished triads.','1'], ['CS9','Triad Simultaneity Prevalence','Proportion of all simultaneities that form triads.','1'], ['CS10','Diminished Seventh Simultaneity Prevalence','Percentage of all simultaneities that are diminished seventh chords.','1'], ['CS11','Incorrectly Spelled Triad Prevalence','Percentage of all triads that are spelled incorrectly.','1'], ['MD1','Composer Popularity','Composer popularity today, as measured by the number of Google search results (log-10).','1'], ['MC1','Ends With Landini Melodic Contour','Boolean that indicates the presence of a Landini-like cadential figure in one or more parts.','1'], ['TX1','Language Feature','Languge of the lyrics of the piece given as a numeric value from text.LanguageDetector.mostLikelyLanguageNumeric().','1']] featureInfo['P']=[ ['P1','Most Common Pitch Prevalence','Fraction of Note Ons corresponding to the most common pitch.','1'], ['P2','Most Common Pitch Class Prevalence','Fraction of Note Ons corresponding to the most common pitch class.','1'], ['P3','Relative Strength of Top Pitches','The frequency of the 2nd most common pitch divided by the frequency of the most common pitch.','1'], ['P4','Relative Strength of Top Pitch Classes','The frequency of the 2nd most common pitch class divided by the frequency of the most common pitch class.','1'], ['P5','Interval Between Strongest Pitches','Absolute value of the difference between the pitches of the two most common MIDI pitches.','1'], ['P6','Interval Between Strongest Pitch Classes','Absolute value of the difference between the pitch classes of the two most common MIDI pitch classes.','1'], ['P7','Number of Common Pitches','Number of pitches that account individually for at least 9% of all notes.','1'], ['P8','Pitch Variety','Number of pitches used at least once.','1'], ['P9','Pitch Class Variety','Number of pitch classes used at least once.','1'], ['P10','Range','Difference between highest and lowest pitches.','1'], ['P11','Most Common Pitch','Bin label of the most common pitch divided by the number of possible pitches.','1'], ['P12','Primary Register','Average MIDI pitch.','1'], ['P13','Importance of Bass Register','Fraction of Note Ons between MIDI pitches 0 and 54.','1'], ['P14','Importance of Middle Register','Fraction of Note Ons between MIDI pitches 55 and 72.','1'], ['P15','Importance of High Register','Fraction of Note Ons between MIDI pitches 73 and 127.','1'], ['P16','Most Common Pitch Class','Bin label of the most common pitch class.','1'], ['P17','Dominant Spread','Largest number of consecutive pitch classes separated by perfect 5ths that accounted for at least 9% each of the notes.','1'], ['P18','Strong Tonal Centres','Number of peaks in the fifths pitch histogram that each account for at least 9% of all Note Ons.','1'], ['P19','Basic Pitch Histogram','A features array with bins corresponding to the values of the basic pitch histogram.','128'], ['P20','Pitch Class Distribution','A feature array with 12 entries where the first holds the frequency of the bin of the pitch class histogram with the highest frequency, and the following entries holding the successive bins of the histogram, wrapping around if necessary.','12'], ['P21','Fifths Pitch Histogram','A feature array with bins corresponding to the values of the 5ths pitch class histogram.','12'], ['P22','Quality','Set to 0 if the key signature indicates that a recording is major, set to 1 if it indicates that it is minor and set to 0 if key signature is unknown.','1'], ['P23','Glissando Prevalence','Number of Note Ons that have at least one MIDI Pitch Bend associated with them divided by total number of pitched Note Ons.','1'], ['P24','Average Range Of Glissandos','Average range of MIDI Pitch Bends, where "range" is defined as the greatest value of the absolute difference between 64 and the second data byte of all MIDI Pitch Bend messages falling between the Note On and Note Off messages of any note.','1'], ['P25','Vibrato Prevalence','Number of notes for which Pitch Bend messages change direction at least twice divided by total number of notes that have Pitch Bend messages associated with them.','1']] featureInfo['R']=[ ['R1','Strongest Rhythmic Pulse','Bin label of the beat bin with the highest frequency.','1'], ['R2','Second Strongest Rhythmic Pulse','Bin label of the beat bin of the peak with the second highest frequency.','1'], ['R3','Harmonicity of Two Strongest Rhythmic Pulses','The bin label of the higher (in terms of bin label) of the two beat bins of the peaks with the highest frequency divided by the bin label of the lower.','1'], ['R4','Strength of Strongest Rhythmic Pulse','Frequency of the beat bin with the highest frequency.','1'], ['R5','Strength of Second Strongest Rhythmic Pulse','Frequency of the beat bin of the peak with the second highest frequency.','1'], ['R6','Strength Ratio of Two Strongest Rhythmic Pulses','The frequency of the higher (in terms of frequency) of the two beat bins corresponding to the peaks with the highest frequency divided by the frequency of the lower.','1'], ['R7','Combined Strength of Two Strongest Rhythmic Pulses','The sum of the frequencies of the two beat bins of the peaks with the highest frequencies.','1'], ['R8','Number of Strong Pulses','Number of beat peaks with normalized frequencies over 0.1.','1'], ['R9','Number of Moderate Pulses','Number of beat peaks with normalized frequencies over 0.01.','1'], ['R10','Number of Relatively Strong Pulses','Number of beat peaks with frequencies at least 30% as high as the frequency of the bin with the highest frequency.','1'], ['R11','Rhythmic Looseness','Average width of beat histogram peaks (in beats per minute). Width is measured for all peaks with frequencies at least 30% as high as the highest peak, and is defined by the distance between the points on the peak in question that are 30% of the height of the peak.','1'], ['R12','Polyrhythms','Number of beat peaks with frequencies at least 30% of the highest frequency whose bin labels are not integer multiples or factors (using only multipliers of 1, 2, 3, 4, 6 and 8) (with an accepted error of +/- 3 bins) of the bin label of the peak with the highest frequency. This number is then divided by the total number of beat bins with frequencies over 30% of the highest frequency.','1'], ['R13','Rhythmic Variability','Standard deviation of the bin values (except the first 40 empty ones).','1'], ['R14','Beat Histogram','A feature array with entries corresponding to the frequency values of each of the bins of the beat histogram (except the first 40 empty ones).','161'], ['R15','Note Density','Average number of notes per second.','1'], ['R17','Average Note Duration','Average duration of notes in seconds.','1'], ['R18','Variability of Note Duration','Standard deviation of note durations in seconds.','1'], ['R19','Maximum Note Duration','Duration of the longest note (in seconds).','1'], ['R20','Minimum Note Duration','Duration of the shortest note (in seconds).','1'], ['R21','Staccato Incidence','Number of notes with durations of less than a 10th of a second divided by the total number of notes in the recording.','1'], ['R22','Average Time Between Attacks','Average time in seconds between Note On events (regardless of channel).','1'], ['R23','Variability of Time Between Attacks','Standard deviation of the times, in seconds, between Note On events (regardless of channel).','1'], ['R24','Average Time Between Attacks For Each Voice','Average of average times in seconds between Note On events on individual channels that contain at least one note.','1'], ['R25','Average Variability of Time Between Attacks For Each Voice','Average standard deviation, in seconds, of time between Note On events on individual channels that contain at least one note.','1'], ['R30','Initial Tempo','Tempo in beats per minute at the start of the recording.','1'], ['R31','Initial Time Signature','A feature array with two elements. The first is the numerator of the first occurring time signature and the second is the denominator of the first occurring time signature. Both are set to 0 if no time signature is present.','2'], ['R32','Compound Or Simple Meter','Set to 1 if the initial meter is compound (numerator of time signature is greater than or equal to 6 and is evenly divisible by 3) and to 0 if it is simple (if the above condition is not fulfilled).','1'], ['R33','Triple Meter','Set to 1 if numerator of initial time signature is 3, set to 0 otherwise.','1'], ['R34','Quintuple Meter','Set to 1 if numerator of initial time signature is 5, set to 0 otherwise.','1'], ['R35','Changes of Meter','Set to 1 if the time signature is changed one or more times during the recording','1']] featureInfo['M']=[ ['M1','Melodic Interval Histogram','A features array with bins corresponding to the values of the melodic interval histogram.','128'], ['M2','Average Melodic Interval','Average melodic interval (in semi-tones).','1'], ['M3','Most Common Melodic Interval','Melodic interval with the highest frequency.','1'], ['M4','Distance Between Most Common Melodic Intervals','Absolute value of the difference between the most common melodic interval and the second most common melodic interval.','1'], ['M5','Most Common Melodic Interval Prevalence','Fraction of melodic intervals that belong to the most common interval.','1'], ['M6','Relative Strength of Most Common Intervals','Fraction of melodic intervals that belong to the second most common interval divided by the fraction of melodic intervals belonging to the most common interval.','1'], ['M7','Number of Common Melodic Intervals','Number of melodic intervals that represent at least 9% of all melodic intervals.','1'], ['M8','Amount of Arpeggiation','Fraction of horizontal intervals that are repeated notes, minor thirds, major thirds, perfect fifths, minor sevenths, major sevenths, octaves, minor tenths or major tenths.','1'], ['M9','Repeated Notes','Fraction of notes that are repeated melodically.','1'], ['m10','Chromatic Motion','Fraction of melodic intervals corresponding to a semi-tone.','1'], ['M11','Stepwise Motion','Fraction of melodic intervals that corresponded to a minor or major second.','1'], ['M12','Melodic Thirds','Fraction of melodic intervals that are major or minor thirds.','1'], ['M13','Melodic Fifths','Fraction of melodic intervals that are perfect fifths.','1'], ['M14','Melodic Tritones','Fraction of melodic intervals that are tritones.','1'], ['M15','Melodic Octaves','Fraction of melodic intervals that are octaves.','1'], ['m17','Direction of Motion','Fraction of melodic intervals that are rising rather than falling.','1'], ['M18','Duration of Melodic Arcs','Average number of notes that separate melodic peaks and troughs in any channel.','1'], ['M19','Size of Melodic Arcs','Average melodic interval separating the top note of melodic peaks and the bottom note of melodic troughs.','1']] featureInfo['D']=[ ['D1','Overall Dynamic Range','The maximum loudness minus the minimum loudness value.','1'], ['D2','Variation of Dynamics','Standard deviation of loudness levels of all notes.','1'], ['D3','Variation of Dynamics In Each Voice','The average of the standard deviations of loudness levels within each channel that contains at least one note.','1'], ['D4','Average Note To Note Dynamics Change','Average change of loudness from one note to the next note in the same channel (in MIDI velocity units).','1']] featureInfo['T']=[ ['T1','Maximum Number of Independent Voices','Maximum number of different channels in which notes have sounded simultaneously. Here, Parts are treated as channels.','1'], ['T2','Average Number of Independent Voices','Average number of different channels in which notes have sounded simultaneously. Rests are not included in this calculation. Here, Parts are treated as voices','1'], ['T3','Variability of Number of Independent Voices','Standard deviation of number of different channels in which notes have sounded simultaneously. Rests are not included in this calculation.','1'], ['T4','Voice Equality - Number of Notes','Standard deviation of the total number of Note Ons in each channel that contains at least one note.','1'], ['T5','Voice Equality - Note Duration','Standard deviation of the total duration of notes in seconds in each channel that contains at least one note.','1'], ['T6','Voice Equality - Dynamics','Standard deviation of the average volume of notes in each channel that contains at least one note.','1'], ['T7','Voice Equality - Melodic Leaps','Standard deviation of the average melodic leap in MIDI pitches for each channel that contains at least one note.','1'], ['T8','Voice Equality - Range','Standard deviation of the differences between the highest and lowest pitches in each channel that contains at least one note.','1'], ['T9','Importance of Loudest Voice','Difference between the average loudness of the loudest channel and the average loudness of the other channels that contain at least one note.','1'], ['T10','Relative Range of Loudest Voice','Difference between the highest note and the lowest note played in the channel with the highest average loudness divided by the difference between the highest note and the lowest note overall in the piece.','1'], ['T12','Range of Highest Line','Difference between the highest note and the lowest note played in the channel with the highest average pitch divided by the difference between the highest note and the lowest note in the piece.','1'], ['T13','Relative Note Density of Highest Line','Number of Note Ons in the channel with the highest average pitch divided by the average number of Note Ons in all channels that contain at least one note.','1'], ['T15','Melodic Intervals in Lowest Line','Average melodic interval in semitones of the channel with the lowest average pitch divided by the average melodic interval of all channels that contain at least two notes.','1'], ['T20','Voice Separation','Average separation in semi-tones between the average pitches of consecutive channels (after sorting based/non average pitch) that contain at least one note.','1']]
class Animal: def __init__(self, age, name): self.age = age # public attribute self.name = name # public attribute def saluda(self, saludo='Hola', receptor = 'nuevo amigo'): print(saludo + " " + receptor) @staticmethod def add(a, b): if isinstance(a, int) and isinstance(b, int): return a + b elif isinstance(a, str) and isinstance(b, str): return " ".join((a, b)) else: raise TypeError def mostrarNombre(self): print(self.nombre) def mostrarEdad(self): print(self.edad)
""" Undefined-Complete-Key A key whose binding is Empty. """ class UndefinedCompleteKey( CompleteKey, ): pass
'''' Лекция 11.1 Магические методы класса !!! Почему так велется лекция, почему преподователь не гтовится заранее, а на средине лекции меняеются начальные условия и потом идут исправления по всему коду Как вот так... преподователь что то делает делает а потом говорит видимо не получается... ПОчему? ''' # Часть 1 - т.е для лекции 11.1 class Point2D(): # Часть 1 def __init__(self, x, y): self.coord = [x, y] def __str__(self): '''' ПРи вызове Print, выведет сторочное представлене, а не номер ячейки ''' return f'Point: ({self.coord[0]}, {self.coord[1]})' def __del__(self): '''' Метод для удаления параметров объекта ''' del self.coord def __getitem__(self, key): return self.coord[key] def __len__(self): '''' Вывкдкт длину, но не совсем корректно, т.к. для округления приенил str''' return int((self.coord[0]**2 + self.coord[1]**2)**0.5) def distance(self): '''' Аналог len''' return (self.coord[0]**2 + self.coord[1]**2)**0.5 # Часть 2--------------------------------------------- def __eq__(self, other): ''''Напишкем магич.метод котор будет работать при сравнении''' return (self.coord[0] == other.coord[0]) & (self.coord[1]== other.coord[1]) def __lt__(self, other): '''' метод сравнения, на уроке не не скажут,что этот метод подразузомивает, что левая част неравенства, должна быть меньше правой, в этом случае результат True. Есть противополождые методы ''' return (self.distance() < other.distance()) def __add__(self, other): '''' if isinstance(other) отвечает за тип объекта''' if isinstance(other, Point2D): # это мы дописыввем, что бы можно было выполнить point1+1 return Point2D(self.coord[0] + other.coord[0], self.coord[1] + other.coord[1]) if isinstance(other, int): return Point2D(self.coord[0] + other, self.coord[1] + other) def __float__(self): # Point2D -> float return self.distance() # Часть 3----------------------------------------------- def __getstate__(self): '''' Этот магич метод, при сериализации сохранит некоторую информацию об объекте ''' return self.coord def __setstate__(self, state): '''' Метод передаст состояние и объекта и после этого будет произведена сериализация ''' self.coord = state # Часть 4 -----Статические методы и методы класса------------ '''' Статический метод ''' @staticmethod # забронированно слово-декоратор def stat_method_ex(x, y): # это статическая функция данного класса if(x**2 + y**2)**0.5 > 1: return 1 return 0 ''' Метод класса ''' @classmethod def class_method_ex(cls): ''' Сделаем что бы возвращался лист из объектов класса ''' point_list = [] for i in range(10): point_list.append(cls(i, i + 1)) return point_list '''' Стат методы и методы класса исполбзуются реже, чем методы класса. На вход стат методу подаются некоторые парамтры и не подаются не объекты не классы Методы класса обычно используют для генерации каких то спец. объектов На вход подаётся сам класс''' if __name__ == '__main__': # point1 = Point2D(1,1) # print('Работа метода __str__: ',point1) # # del point1 # закоментил,т.к дальше print не будет работать # str1 = 'volvo' # list_test = [1,2,3,4] # print('Работа метода __len__ (в 3-ем Len):',len(str1), len(list_test), len(point1)) # print('Метод dictance:',point1.distance()) # # for item in str1: # print('Проэтирировали volvo:',item) # # for item in list_test: # print('Проэтирировали list_test:',item) # # print('Вычислим, находятся ли точки в диапазоне:\n',2 in point1, 1 in point1) # это мы тестим getitem # # for coord in point1: # print(coord) # Предыдущее закоментил, т.к. дальше Стат метод и метод класса list_ = Point2D.class_method_ex() ''' т.к. это метод класса, то он вызывается через класс точка и данный метод''' print(' не красиво, str здесь не работатет:',list_) '''' print(list_) - выведет некрасиво''' for i in range(10): '''' Запринтим каждый элемент листа''' print(list_[i]) print(Point2D.stat_method_ex(1, 2)) '''' Работаем со стат методом. У вектора (1, 2) расстояние > 1 поэтому должен вернуть 1 '''
class Filenames: class models: base = './res/models/player/' player = base + 'bicycle.obj' base = './res/models/oponents/' player = base + 'bicycle.obj' class textures: base = './res/textures/' floor_tile = base + 'floor.png' wall_tile = base + 'rim_wall_a.png' sky = base + 'sky.png'
#!/usr/bin/env python # -*- coding: utf-8 -*- class PodiumEventDevice(object): """ Object that represents a device at an event. **Attributes:** **eventdevice_id** (str): Unique id for device at this event **uri** (str): URI for this device at this event. **channels** (list): List of channels of data. Can be sensors or other sources of data. **name** (str): Name of device at event. Not always the same as the device name. **device_uri** (str): URI of the device **laps_uri** (str): URI of lap data. **avatar_url** (str): URI of the device avatar **user_avatar_url** (str): URL of the user avatar **event_title** (str): Title of the event """ def __init__( self, eventdevice_id, uri, channels, name, comp_number, device_uri, laps_uri, user_uri, event_uri, avatar_url, user_avatar_url, event_title, device_id, event_id, ): self.eventdevice_id = eventdevice_id self.uri = uri self.channels = channels self.name = name self.comp_number = comp_number self.device_uri = device_uri self.laps_uri = laps_uri self.user_uri = user_uri self.event_uri = event_uri self.avatar_url = avatar_url self.user_avatar_url = user_avatar_url self.event_title = event_title self.device_id = device_id self.event_id = event_id def get_eventdevice_from_json(json): """ Returns a PodiumEventDevice object from the json dict received from podium api. Args: json (dict): Dict of data from REST api Return: PodiumEvent: The PodiumEvent object for this data. """ return PodiumEventDevice( json["id"], json["URI"], json.get("channels", []), json.get("name", None), json.get("comp_number", None), json.get("device_uri", None), json.get("laps_uri", None), json.get("user_uri", None), json.get("event_uri", None), json.get("avatar_url", None), json.get("user_avatar_url", None), json.get("event_title", None), json.get("device_id", None), json.get("event_id", None), )
"""Exceptions for event processor.""" class EventProcessorError(BaseException): """General exception for the event-processor library.""" class FilterError(EventProcessorError): """Exception for failures related to filters.""" class InvocationError(EventProcessorError): """Exception for failures in invocation.""" class DependencyError(EventProcessorError): """Exceptions for failures while resolving dependencies.""" class NoValueError(EventProcessorError): """Exception for when a value is not present in a given context."""
class Recursion: def PalindromeCheck(self, strVal, i, j): if i>j: return True return self.PalindromeCheck(strVal, i + 1, j - 1) if strVal[i] == strVal[j] else False strVal = "q2eeeq" obj = Recursion() print(obj.PalindromeCheck(strVal, 0, len(strVal)-1))
# Identity vs. Equality # - is vs. == # - working with literals # - isinstance() a = 1 b = 1.0 c = "1" print(a == b) print(a is b) print(c == "1") print(c is "1") print(b == 1) print(b is 1) print(b == 1 and isinstance(b, int)) print(a == 1 and isinstance(a, int)) # d = 100000000000000000000000000000000 d = float(10) e = float(10) print(id(d)) print(id(e)) print(d == e) print(d is e) b = int(b) print(b) print(b == 1 and isinstance(b, int)) print(a) print(float(a)) print(str(a)) print(str(a) is c) print(str(a) == c)
# 54. Spiral Matrix # O(n) time | O(n) space class Solution: def spiralOrder(self, matrix: [[int]]) -> [int]: """ Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5] """ if len(matrix) == 0 or len(matrix[0]) == 0: return [] startRow = startColum = 0 endRow, endColum = len(matrix) - 1, len(matrix[0]) - 1 result = [] while startRow <= endRow and startColum <= endColum: for item in matrix[startRow][startColum : endColum + 1]: result.append(item) for row in range(startRow + 1, endRow + 1): result.append(matrix[row][endColum]) if startRow != endRow: for item in reversed(matrix[endRow][startColum : endColum]): result.append(item) if startColum != endColum: for row in reversed(range(startRow + 1, endRow)): result.append(matrix[row][startColum]) startRow += 1; startColum += 1 endRow -= 1; endColum -= 1 return result
age=input("How old ara you?") height=input("How tall are you?") weight=input("How much do you weigth?") print("So ,you're %r old , %r tall and %r heavy ." %(age,height,weight))
# my_nameという変数に「にんじゃわんこ」という文字列を代入してください my_name = "にんじゃわんこ" # my_nameを用いて、「私はにんじゃわんこです」となるように変数と文字列を連結して出力してください print ("私は" + my_name + "です")
class Room(): """ A room to give lectures in. """ def __init__(self, number, lectures, timeslots): """ Constructor """ self.number = number self._lectures = lectures self._timeslots = timeslots def can_be_used_for(self, lecture): """ Is the lecture be given in the room? """ return lecture in self._lectures def can_be_used_at(self, timeslot): """ Can the room be used at a certain timeslot? """ return timeslot in self._timeslots def __repr__(self): return '<Room No.{}>'.format(self.number) def __str__(self): return 'No.{}'.format(self.number) def __eq__(self, other): return self.number == other.number def __hash__(self): return hash(self.number)
def compute_bag_of_words(dataset,lang,domain_stopwords=[]): d = [] for index,row in dataset.iterrows(): text = row['title'] #texto do evento text2 = remove_stopwords(text, lang,domain_stopwords) text3 = stemming(text2, lang) d.append(text3) matrix = CountVectorizer(max_features=1000) X = matrix.fit_transform(d) count_vect_df = pd.DataFrame(X.todense(), columns=matrix.get_feature_names()) return count_vect_df bow = compute_bag_of_words(dataset,'portuguese') bow
def generator(): try: yield except RuntimeError as e: print(e) yield 'hello after first yield' g = generator() next(g) result = g.throw(RuntimeError, 'Broken') assert result == 'hello after first yield'
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Inception v3 stem, 7 x 7 is replaced by a stack of 3 x 3 convolutions. x = layers.Conv2D(32, (3, 3), strides=(2, 2), padding='same')(input) x = layers.Conv2D(32, (3, 3), strides=(1, 1), padding='same')(x) x = layers.Conv2D(64, (3, 3), strides=(1, 1), padding='same')(x) # max pooling layer x = layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x) # bottleneck convolution x = layers.Conv2D(80, (1, 1), strides=(1, 1), padding='same')(x) # next convolution layer x = layers.Conv2D(192, (3, 3), strides=(1, 1), padding='same')(x) # strided convolution - feature map reduction x = layers.Conv2D(256, (3, 3), strides=(2, 2), padding='same')(x)
favorite_fruits = ['apple', 'orange', 'pineapple'] if 'apple' in favorite_fruits: print("You really like apples!") if 'grapefruit' in favorite_fruits: print("You really like grapefruits!") else: print("Why don't you like grapefruits?") if 'orange' not in favorite_fruits: print("Why don't you like oranges?") if 'pineapple' in favorite_fruits: print("You really like pineapples!") if 'potato' in favorite_fruits: print("Do you really think potato is a fruit?")
expected_output = { "vrf": { "default": { "local_label": { 24: { "outgoing_label_or_vc": { "No Label": { "prefix_or_tunnel_id": { "10.23.120.0/24": { "outgoing_interface": { "GigabitEthernet2.120": { "next_hop": "10.12.120.2", "bytes_label_switched": 0, }, "GigabitEthernet3.120": { "next_hop": "10.13.120.3", "bytes_label_switched": 0, }, } } } } } }, 25: { "outgoing_label_or_vc": { "No Label": { "prefix_or_tunnel_id": { "10.23.120.0/24[V]": { "outgoing_interface": { "GigabitEthernet2.420": { "next_hop": "10.12.120.2", "bytes_label_switched": 0, }, "GigabitEthernet3.420": { "next_hop": "10.13.120.3", "bytes_label_switched": 0, }, } } } } } }, } } } }
#============================================================= # modules for HSPICE sim #============================================================= #============================================================= # varmap definition #------------------------------------------------------------- # This class is to make combinations of given variables # mostly used for testbench generation #------------------------------------------------------------- # Example: # varmap1=HSPICE_varmap.varmap(4) %%num of var=4 # varmap1.get_var('vdd',1.5,1.8,0.2) %%vdd=1.5:0.2:1.8 # varmap1.get_var('abc', ........ %%do this for 4 var # varmap1.cal_nbigcy() %%end of var input # varmap1.combinate %%returns variable comb 1 by 1 #============================================================= class varmap: def __init__(self): self.n_smlcycle=1 self.last=0 #self.smlcy=1 self.smlcy=0 self.vv=0 self.vf=1 self.nvar=0 def get_var(self,name,start,end,step): if self.nvar==0: self.map=[None] self.comblist=[None] self.flag=[None] else: self.map.append(None) self.comblist.append(None) self.flag.append(None) self.map[self.nvar]=list([name]) self.flag[self.nvar]=(name) self.comblist[self.nvar]=list([name]) self.nswp=int((end-start)//step+1) for i in range(1,self.nswp+1): self.map[self.nvar].append(start+step*(i-1)) self.nvar+=1 def add_val(self,flag,start,end,step): varidx=self.flag.index(flag) if start!=None: nval=int((end-start+step/10)//step+1) for i in range(1,nval+1): self.map[varidx].append(start+step*(i-1)) else: for i in range(1,step+1): self.map[varidx].append(end) def cal_nbigcy(self): self.bias=[1]*(len(self.map)) for j in range(1,len(self.map)+1): self.n_smlcycle=self.n_smlcycle*(len(self.map[j-1])-1) self.n_smlcycle=self.n_smlcycle*len(self.map) def increm(self,inc): #increment bias self.bias[inc]+=1 if self.bias[inc]>len(self.map[inc])-1: self.bias[inc]%len(self.map[inc])-1 def check_end(self,vf): #When this is called, it's already last stage of self.map[vf] self.bias[vf]=1 # if vf==0 and self.bias[0]==len(self.map[0])-1: # return 0 if self.bias[vf-1]==len(self.map[vf-1])-1: #if previous column is last element self.check_end(vf-1) else: self.bias[vf-1]+=1 return 1 def combinate(self): # print self.map[self.vv][self.bias[self.vv]] self.smlcy+=1 if self.vv==len(self.map)-1: #last variable for vprint in range(0,len(self.map)): #fill in the current pointer values self.comblist[vprint].append(self.map[vprint][self.bias[vprint]]) #print self.map[vprint][self.bias[vprint]] if self.bias[self.vv]==len(self.map[self.vv])-1: #last element if self.smlcy<self.n_smlcycle: self.check_end(self.vv) self.vv=(self.vv+1)%len(self.map) self.combinate() else: pass else: self.bias[self.vv]+=1 self.vv=(self.vv+1)%len(self.map) self.combinate() else: self.vv=(self.vv+1)%len(self.map) self.combinate() def find_comb(self,targetComb): #function that returns the index of certain combination if len(self.comblist)!=len(targetComb): print('the length of the list doesnt match') else: for i in range(1,len(self.comblist[0])): match=1 for j in range(len(self.comblist)): match=match*(self.comblist[j][i]==targetComb[j]) if match==1: return i #============================================================= # netmap #------------------------------------------------------------- # This class is used for replacing lines # detects @@ for line and @ for nets #------------------------------------------------------------- # Example: # netmap1.get_net('ab','NN',1,4,1) %flag MUST be 2 char # netmap2.get_net('bc','DD',2,5,1) %length of var must match # netmap2.get_net('bc','DD',None,5,9) repeat DD5 x9 # netmap2.get_net('bc','DD',None,None,None) write only DD # netmap2.get_net('bc','DD',None,5,None) write only DD for 5 times # !!caution: do get_var in order, except for lateral prints # which is using @W => varibales here, do get_var at last # for line in r_file.readlines(): # netmap1.printline(line,w_file) # printline string added #============================================================= class netmap: def __init__(self): self.nn=0 self.pvar=1 self.cnta=0 self.line_nvar=0 # index of last variable for this line self.nxtl_var=0 # index of variable of next line self.ci_at=-5 self.ci_and=-50 #try has been added to reduce unnecessary "add_val" usage: but it might produce a problem when the user didn't know this(thought that every get_net kicks old value out) def get_net(self,flag,netname,start,end,step): #if start==None: want to repeat without incrementation(usually for tab) (end)x(step) is the num of repetition try: #incase it's already in the netmap => same as add_val varidx=self.flag.index(flag) if start!=None: try: nval=abs(int((end-start+step/10)//step+1)) for i in range(1,nval+1): self.map[varidx].append(start+step*(i-1)) except: self.map[varidx].append(start) else: for i in range(1,step+1): self.map[varidx].append(end) except: #registering new net if self.nn==0: self.map=[None] self.flag=[None] self.name=[None] self.nnet=[None] self.stringOnly=[None] else: self.map.append(None) self.name.append(None) self.flag.append(None) self.nnet.append(None) self.stringOnly.append(None) if netname==None: self.name[self.nn]=0 else: self.name[self.nn]=1 self.map[self.nn]=list([netname]) self.flag[self.nn]=(flag) if start!=None and start!='d2o' and start!='d2oi': #normal n1 n2 n3 ... try: self.nnet[self.nn]=int((end-start+step/10)//step+1) for i in range(1,self.nnet[self.nn]+1): self.map[self.nn].append(start+step*(i-1)) except: self.map[self.nn].append(start) elif start=='d2o': #decimal to binary for i in range(0,end): if step-i>0: self.map[self.nn].append(1) else: self.map[self.nn].append(0) i+=1 elif start=='d2oi': #decimal to thermal inversed for i in range(0,end): if step-i>0: self.map[self.nn].append(0) else: self.map[self.nn].append(1) i+=1 elif start==None and end==None and step==None: #write only string self.stringOnly[self.nn]=1 self.map[self.nn].append(netname) #this is just to make len(self.map[])=2 to make it operate elif self.name[self.nn]!=None and start==None and end!=None and step==None: #repeatedely printing string (write name x end) for i in range(1,end+1): self.map[self.nn].append(netname) else: # start==None : repeat 'end' for 'step' times for i in range(1,step+1): self.map[self.nn].append(end) # self.map[self.nn]=[None]*step # for i in range(1,self.nnet[self.nn]+1): # self.map[self.nn][i]=None self.nn+=1 #print self.map def add_val(self,flag,netname,start,end,step): varidx=self.flag.index(flag) if start!=None: nval=int((end-start+step/10)//step+1) for i in range(1,nval+1): self.map[varidx].append(start+step*(i-1)) else: for i in range(1,step+1): self.map[varidx].append(end) def printline(self,line,wrfile): if line[0:2]=='@@': #print('self.ci_at=%d'%(self.ci_at)) self.nline=line[3:len(line)] self.clist=list(self.nline) #character list for iv in range (1,len(self.map[self.nxtl_var])): for ci in range(0,len(self.clist)): if (ci==self.ci_at+1 or ci==self.ci_at+2) and ci!=len(self.clist)-1: pass elif self.clist[ci]=='@': try: varidx=self.flag.index(self.clist[ci+1]+self.clist[ci+2]) #print self.cnta self.cnta+=1 self.line_nvar+=1 if self.stringOnly[varidx]==1: wrfile.write(self.map[varidx][0]) self.ci_at=ci else: #print ('flag=') #print (self.clist[ci+1]+self.clist[ci+2]) #print (self.map[varidx]) #print (self.pvar) if self.name[varidx]: wrfile.write(self.map[varidx][0]) if type(self.map[varidx][self.pvar])==str: wrfile.write('%s'%(self.map[varidx][self.pvar])) #modify here!!!! if type(self.map[varidx][self.pvar])==float: wrfile.write('%e'%(self.map[varidx][self.pvar])) #modify here!!!! #wrfile.write('%.2f'%(self.map[varidx][self.pvar])) #modify here!!!! elif type(self.map[varidx][self.pvar])==int: wrfile.write('%d'%(self.map[varidx][self.pvar])) #elif type(self.map[varidx][self.pvar])==str: # wrfile.write('%s'%(self.map[varidx][self.pvar])) self.ci_at=ci except: print("%s not in netmap!"%(self.clist[ci+1]+self.clist[ci+2])) wrfile.write(self.clist[ci]) elif ci==len(self.clist)-1: #end of the line if self.pvar==len(self.map[self.nxtl_var+self.line_nvar-1])-1: #last element self.pvar=1 self.nxtl_var=self.nxtl_var+self.line_nvar self.line_nvar=0 self.cnta=0 self.ci_at=-6 #print('printed all var for this line, %d'%(ci)) else: self.pvar+=1 self.line_nvar=self.cnta self.line_nvar=0 #print ('line_nvar= %d'%(self.line_nvar)) self.cnta=0 wrfile.write(self.clist[ci]) else: wrfile.write(self.clist[ci]) elif line[0:2]=='@W': #lateral writing #print('found word line') self.nline=line[3:len(line)] self.clist=list(self.nline) for ci in range(0,len(self.clist)): if (ci==self.ci_at+1 or ci==self.ci_at+2): pass elif self.clist[ci]=='@': varidx=self.flag.index(self.clist[ci+1]+self.clist[ci+2]) for iv in range(1,len(self.map[varidx])): if self.name[varidx]: wrfile.write(self.map[varidx][0]) if type(self.map[varidx][iv])==int: wrfile.write('%d '%(self.map[varidx][iv])) #this is added for edit pin elif type(self.map[varidx][iv])==float: wrfile.write('%.1f '%(self.map[varidx][iv])) self.ci_at=ci else: wrfile.write(self.clist[ci]) self.ci_at=-5 elif line[0:2]=='@E': #lateral writing for edit pin #print('found word line') self.nline=line[3:len(line)] self.clist=list(self.nline) for ci in range(0,len(self.clist)): if (ci==self.ci_at+1 or ci==self.ci_at+2): pass elif self.clist[ci]=='@': varidx=self.flag.index(self.clist[ci+1]+self.clist[ci+2]) for iv in range(1,len(self.map[varidx])): if self.name[varidx]: wrfile.write(self.map[varidx][0]) if type(self.map[varidx][iv])==int: wrfile.write('%d] '%(self.map[varidx][iv])) #this is added for edit pin elif type(self.map[varidx][iv])==float: wrfile.write('%.1f '%(self.map[varidx][iv])) self.ci_at=ci else: wrfile.write(self.clist[ci]) self.ci_at=-5 elif line[0:2]=='@C': # cross lateral writing #print('found word line') self.nline=line[3:len(line)] self.clist=list(self.nline) for ci in range(0,len(self.clist)): if (ci==self.ci_at+1 or ci==self.ci_at+2 or ci==self.ci_and+1 or ci==self.ci_and+2 or ci==self.ci_and+3 or ci==self.ci_and+4): pass elif self.clist[ci]=='@': varidx=self.flag.index(self.clist[ci+1]+self.clist[ci+2]) for iv in range(1,len(self.map[varidx])): if self.name[varidx]: wrfile.write(self.map[varidx][0]) if type(self.map[varidx][iv])==int: wrfile.write('%d '%(self.map[varidx][iv])) #this is added for edit pin elif type(self.map[varidx][iv])==float: wrfile.write('%.1f '%(self.map[varidx][iv])) self.ci_at=ci elif self.clist[ci]=='&': varidx1=self.flag.index(self.clist[ci+1]+self.clist[ci+2]) varidx2=self.flag.index(self.clist[ci+3]+self.clist[ci+4]) for iv in range(1,len(self.map[varidx1])): if type(self.map[varidx1][iv])==int: wrfile.write('%d '%(self.map[varidx1][iv])) #this is added for edit pin elif type(self.map[varidx1][iv])==float: wrfile.write('%e '%(self.map[varidx1][iv])) if type(self.map[varidx2][iv])==int: wrfile.write('%d '%(self.map[varidx2][iv])) #this is added for edit pin elif type(self.map[varidx2][iv])==float: wrfile.write('%e '%(self.map[varidx2][iv])) self.ci_and=ci else: wrfile.write(self.clist[ci]) self.ci_at=-5 elif line[0:2]=='@S': self.nline=line[3:len(line)] self.clist=list(self.nline) for ci in range(0,len(self.clist)): if (ci==self.ci_at+1 or ci==self.ci_at+2): pass elif self.clist[ci]=='@': varidx=self.flag.index(self.clist[ci+1]+self.clist[ci+2]) wrfile.write(self.map[varidx][0]) self.ci_at=ci else: wrfile.write(self.clist[ci]) self.ci_at=-5 else: wrfile.write(line) #============================================================= # resmap #------------------------------------------------------------- # This class is used to deal with results # detects @@ for line and @ for nets #------------------------------------------------------------- # EXAMPLE: # netmap1=netmap(2) %input num_var # netmap1.get_var('ab','NN',1,4,1) %flag MUST be 2 char # netmap2.get_var('bc','DD',2,5,1) %length of var must match # for line in r_file.readlines(): # netmap1.printline(line,w_file) # self.tb[x][y][env[]] #============================================================= class resmap: def __init__(self,num_tb,num_words,index): #num_words includes index self.tb=[None]*num_tb self.tbi=[None]*num_tb self.vl=[None]*num_tb self.vlinit=[None]*num_tb self.svar=[None]*num_tb self.index=index self.nenv=0 self.num_words=num_words self.vr=[None]*(num_words+index) #one set of variables per plot self.vidx=[None]*(num_words+index) self.env=[None]*(num_words+index) # self.vl=[None]*(num_words+index) #one set of variables per plot for itb in range(0,len(self.tb)): # self.tb[itb].vr=[None]*(num_words+index) self.tbi[itb]=0 #index for counting vars within tb self.vl[itb]=[None]*(num_words+index) self.vlinit[itb]=[0]*(num_words+index) def get_var(self,ntb,var): self.vr[self.tbi[ntb]]=(var) # variable # self.vl[ntb][self.tbi[ntb]]=list([None]) self.tbi[ntb]+=1 if self.tbi[ntb]==len(self.vr): #???????? self.tbi[ntb]=0 def add(self,ntb,value): if self.vlinit[ntb][self.tbi[ntb]]==0: #initialization self.vl[ntb][self.tbi[ntb]]=[value] # value self.vlinit[ntb][self.tbi[ntb]]+=1 else: self.vl[ntb][self.tbi[ntb]].append(value) # value self.tbi[ntb]=(self.tbi[ntb]+1)%len(self.vr) def plot_env(self,ntb,start,step,xvar,xval): #setting plot environment: if ntb=='all': x axis is in terms of testbench if ntb=='all': self.nenv+=1 self.xaxis=[None]*len(self.tb) for i in range(0,len(self.tb)): self.xaxis[i]=start+i*step self.vidx[self.nenv]=self.vr.index(xvar) #print self.vl[0][self.vidx[self.nenv]] self.env[self.nenv]=[i for (i,x) in enumerate(self.vl[0][self.vidx[self.nenv]]) if x=='%s'%(xval)] else: self.nenv+=1 self.xaxis=[None] #one output self.xaxis=[start] self.vidx[self.nenv]=self.vr.index(xvar) self.env[self.nenv]=[i for (i,x) in enumerate(self.vl[0][self.vidx[self.nenv]]) if x=='%s'%(xval)] def rst_env(self): self.vidx[self.nenv]=None self.env[self.nenv]=0 self.nenv=0 #print self.vl[0][self.vidx[self.nenv]] def plot_y(self,yvar): self.yidx=self.vr.index(yvar) #print ('yidx=%d'%(self.yidx)) #print self.vl[0][self.yidx][self.env[self.nenv][0]] self.yaxis=[None]*len(self.xaxis) for xx in range(0,len(self.xaxis)): self.yaxis[xx]=self.vl[xx][self.yidx][self.env[self.nenv][0]] #plt.plot(self.xaxis,self.yaxis) #plt.ylabel(self.vr[self.yidx]) def sort(self,var): varidx=self.vr.index(var) for k in range(len(self.vl)): #all testbenches self.svar[k]={} #define dict for i in range(len(self.vl[0][0])): #all values self.svar[k][self.vl[k][varidx][i]]=[] for j in range(len(self.vr)): #all variables if j!=varidx: self.svar[k][self.vl[k][varidx][i]].append(self.vl[k][j][i]) #============================================================= # sort #------------------------------------------------------------- # This function sorts 2D-list according to given index value # outputs the sorted 2D-list #------------------------------------------------------------- # EXAMPLE: #============================================================= def sort_via(list_ind,list_vic,index,i): index=int(index) i=int(i) if len(list_ind)!=len(list_vic): print('lengths of two lists dont match') else: #print('%d th'%(i)) t_ind=0 t_vic=0 if i<len(list_ind)-1 and i>=0: if list_ind[i][index]>list_ind[i+1][index]: #print list_ind #print list_vic #print('switch %d from %d and %d'%(i,len(list_ind),len(list_vic))) t_ind=list_ind[i] t_vic=list_vic[i] list_ind[i]=list_ind[i+1] list_vic[i]=list_vic[i+1] list_ind[i+1]=t_ind list_vic[i+1]=t_vic i=i-1 sort_via(list_ind,list_vic,index,i) else: #print('pass %d'%(i)) i+=1 sort_via(list_ind,list_vic,index,i) elif i<0: i+=1 sort_via(list_ind,list_vic,index,i) elif i==len(list_ind)-1: #print('came to last') #print list_ind #print list_vic return list_ind, list_vic #============================================================= # sort 1D #------------------------------------------------------------- # This function sorts 1D-list according to given index value # outputs the sorted 1D-list #------------------------------------------------------------- # EXAMPLE: # a=[3,2,1], b=[1,2,3] # a,b=sort_via_1d(a,b,0) # print a => [1,2,3] # print b => [3,2,1] #============================================================= def sort_via_1d(list_ind,list_vic,i): i=int(i) if len(list_ind)!=len(list_vic): print('lengths of two lists dont match') else: #print('%d th'%(i)) t_ind=0 t_vic=0 if i<len(list_ind)-1 and i>=0: if list_ind[i]>list_ind[i+1]: #print list_ind #print list_vic #print('switch %d from %d and %d'%(i,len(list_ind),len(list_vic))) t_ind=list_ind[i] t_vic=list_vic[i] list_ind[i]=list_ind[i+1] list_vic[i]=list_vic[i+1] list_ind[i+1]=t_ind list_vic[i+1]=t_vic i=i-1 sort_via_1d(list_ind,list_vic,i) else: #print('pass %d'%(i)) i+=1 sort_via_1d(list_ind,list_vic,i) elif i<0: i+=1 sort_via_1d(list_ind,list_vic,i) elif i==len(list_ind)-1: #print('came to last') #print list_ind #print list_vic return list_ind, list_vic def sort_via_1d_mult(list_ind,*list_vics): i=int(0) for list_vic in list_vics: list_ind_temp=list(list_ind) sort_via_1d(list_ind_temp,list_vic,0) sort_via_1d(list_ind,list_ind,0) #============================================================= # mM #------------------------------------------------------------- # This function picks min, Max, of 1-D list # outputs min, Max, step #------------------------------------------------------------- # EXAMPLE: #============================================================= def mM(inp_list): min_item=0 max_item=0 step_item=0 reg_item=0 err_step=0 cnt=0 for item in inp_list: if cnt==0: min_item=item max_item=item else: if min_item>item: min_item=item if max_item<item: max_item=item #if cnt>1 and step_item!=abs(item-reg_item): # print('step is not uniform') # err_step=1 # print reg_item-item #else: # step_item=abs(item-reg_item) reg_item=item cnt+=1 if err_step==0: return min_item,max_item # else: # print('step error')
"""This module holds string constants to be used in conjunction with API calls to MapRoulette.""" # Query string parameters QUERY_PARAMETER_Q = "q" QUERY_PARAMETER_PARENT_IDENTIFIER = "parentId" QUERY_PARAMETER_LIMIT = "limit" QUERY_PARAMETER_PAGE = "page" QUERY_PARAMETER_ONLY_ENABLED = "onlyEnabled" # Common URIs URI_FIND = "s/find" URI_PROJECT_GET_BY_NAME = "/projectByName" URI_PROJECT_POST = "/project" URI_CHILDREN = "/children" URL_CHALLENGE = "/challenge" URI_CHALLENGES = "/challenges" URI_TASK = "/task" URI_TASKS = "/tasks" # Flags FLAG_IMMEDIATE_DELETE = "immediate"
""" set:是一个非常有用的数据结构,它与列表的行为类似,区别在于set不能包含重复的值。 """ some_list = ["a", "b", "c", "d", "b", "m", "n", "n"] duplicates = [] for value in some_list: if some_list.count(value) > 1: if value not in duplicates: duplicates.append(value) print(duplicates) set_duplicates = set([x for x in some_list if some_list.count(x) > 1]) print(set_duplicates) """ 交集 """ valid = {"yellow", "red", "blue", "green", "black"} input_set = {"red", "brown"} print(input_set.intersection(valid)) """ 差集:相当于用一个集合减去另一个集合的数据。 """ print(input_set.difference(valid))
print("Programa que imprime a tabuada") numero = 5 while numero <= 255: print("\n\n\n") for n in range(1, 11): resultado = numero * n print(numero, "X", n, "=", resultado) numero = numero + 1 print("Fim do programa")
# faça um programa que que o usuario pode digitar vários valores numericos e cadastre-os em uma lista. # Caso o numero já estiver lá dentro ele não sera adicionado # No final serão exibidos em ordem crescente valores = [] conti = cont = 0 while True: conti += 1 num = int(input('Digite um valor: ')) if num not in valores: valores.append(num) print('Valor adicionado com sucesso!') else: print('Valor duplicado! Valor não adicionado!') continuar = ' ' while continuar not in 'SN': continuar = str(input('Deseja continuar :[S/N] ')).upper().strip() if continuar == 'N': break valores.sort() print(f'Voce digitou {cont} valores: {valores}')
""" quest-0 t - number of tests c - number of packages k - capacity w - package weight """ t = int(input()) for i in range(t): task_input = input().split() task_input = [float(variable) for variable in task_input] c, k, w = task_input[0], task_input[1], task_input[2], if c * w <= k: print("yes") else: print("no")
# This sample tests the special-case handle of the multi-parameter # form of the built-in "type" call. # pyright: strict X1 = type("X1", (object,), {}) X2 = type("X2", (object,), {}) class A(X1): ... class B(X2, A): ... # This should generate an error because the first arg is not a string. X3 = type(34, (object,)) # This should generate an error because the second arg is not a tuple of class types. X4 = type("X4", 34) # This should generate an error because the second arg is not a tuple of class types. X5 = type("X5", (3,))
# Copyright (c) 2014 Brocade Communications Systems, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # # Authors: # Varma Bhupatiraju (vbhupati@#brocade.com) # Shiv Haris (sharis@brocade.com) """NOS NETCONF XML Configuration Command Templates. Interface Configuration Commands """ # Create VLAN (vlan_id) CREATE_VLAN_INTERFACE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <interface-vlan xmlns="urn:brocade.com:mgmt:brocade-interface"> <interface> <vlan> <name>{vlan_id}</name> </vlan> </interface> </interface-vlan> </config> """ # Delete VLAN (vlan_id) DELETE_VLAN_INTERFACE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <interface-vlan xmlns="urn:brocade.com:mgmt:brocade-interface"> <interface> <vlan operation="delete"> <name>{vlan_id}</name> </vlan> </interface> </interface-vlan> </config> """ # # AMPP Life-cycle Management Configuration Commands # # Create AMPP port-profile (port_profile_name) CREATE_PORT_PROFILE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile"> <name>{name}</name> </port-profile> </config> """ # Create VLAN sub-profile for port-profile (port_profile_name) CREATE_VLAN_PROFILE_FOR_PORT_PROFILE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile"> <name>{name}</name> <vlan-profile/> </port-profile> </config> """ # Configure L2 mode for VLAN sub-profile (port_profile_name) CONFIGURE_L2_MODE_FOR_VLAN_PROFILE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile"> <name>{name}</name> <vlan-profile> <switchport/> </vlan-profile> </port-profile> </config> """ # Configure trunk mode for VLAN sub-profile (port_profile_name) CONFIGURE_TRUNK_MODE_FOR_VLAN_PROFILE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile"> <name>{name}</name> <vlan-profile> <switchport> <mode> <vlan-mode>trunk</vlan-mode> </mode> </switchport> </vlan-profile> </port-profile> </config> """ # Configure allowed VLANs for VLAN sub-profile # (port_profile_name, allowed_vlan, native_vlan) CONFIGURE_ALLOWED_VLANS_FOR_VLAN_PROFILE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile"> <name>{name}</name> <vlan-profile> <switchport> <trunk> <allowed> <vlan> <add>{vlan_id}</add> </vlan> </allowed> </trunk> </switchport> </vlan-profile> </port-profile> </config> """ # Delete port-profile (port_profile_name) DELETE_PORT_PROFILE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile" operation="delete"> <name>{name}</name> </port-profile> </config> """ # Activate port-profile (port_profile_name) ACTIVATE_PORT_PROFILE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <port-profile-global xmlns="urn:brocade.com:mgmt:brocade-port-profile"> <port-profile> <name>{name}</name> <activate/> </port-profile> </port-profile-global> </config> """ # Deactivate port-profile (port_profile_name) DEACTIVATE_PORT_PROFILE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <port-profile-global xmlns="urn:brocade.com:mgmt:brocade-port-profile"> <port-profile> <name>{name}</name> <activate xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" nc:operation="delete" /> </port-profile> </port-profile-global> </config> """ # Associate MAC address to port-profile (port_profile_name, mac_address) ASSOCIATE_MAC_TO_PORT_PROFILE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <port-profile-global xmlns="urn:brocade.com:mgmt:brocade-port-profile"> <port-profile> <name>{name}</name> <static> <mac-address>{mac_address}</mac-address> </static> </port-profile> </port-profile-global> </config> """ # Dissociate MAC address from port-profile (port_profile_name, mac_address) DISSOCIATE_MAC_FROM_PORT_PROFILE = """ <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0"> <port-profile-global xmlns="urn:brocade.com:mgmt:brocade-port-profile"> <port-profile> <name>{name}</name> <static xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" nc:operation="delete"> <mac-address>{mac_address}</mac-address> </static> </port-profile> </port-profile-global> </config> """ # # Constants # # Port profile naming convention for Neutron networks OS_PORT_PROFILE_NAME = "openstack-profile-{id}" # Port profile filter expressions PORT_PROFILE_XPATH_FILTER = "/port-profile" PORT_PROFILE_NAME_XPATH_FILTER = "/port-profile[name='{name}']"
#!/usr/bin/env python3 # Python 3.5.3 (default, Jan 19 2017, 14:11:04) # [GCC 6.3.0 20170118] on linux def fibo(n): W = [1, 1] for i in range(n): W.append(W[i] + W[i+1]) return(W) def inpt(): n = int(input("steps: ")) print(fibo(n)) inpt()
'''Find the area of the largest rectangle inside histogram''' def pop_stack(current_max, pos, stack): '''Remove item from stack and return area and start position''' start, height = stack.pop() return max(current_max, height * (pos - start)), start def largest_rectangle(hist): '''Find area of largest rectangle inside histogram''' current_max = 0 stack = [] i = -1 for i, height in enumerate(hist): if not stack or height > stack[-1][1]: stack.append((i, height)) elif height < stack[-1][1]: while stack and height < stack[-1][1]: current_max, start = pop_stack(current_max, i, stack) stack.append((start, height)) while stack: current_max = pop_stack(current_max, i+1, stack)[0] return current_max def main(): '''Main function for testing''' print(largest_rectangle([1, 3, 5, 3, 0, 2, 3, 3, 1, 0, 3, 6])) print(largest_rectangle([1, 3, 5, 3, 2, 2, 3, 3, 1, 0, 3, 6])) print(largest_rectangle([1, 2, 3, 1, 1])) if __name__ == '__main__': main()
""" Provides a series of solutions to the challenge provided at the following link: https://therenegadecoder.com/code/how-to-iterate-over-multiple-lists-at-the-same-time-in-python/#challenge """ def next_pokemon_1(pokemon, levels, fainted): best_level = -1 best_choice = pokemon[0] for curr_pokemon, level, has_fainted in zip(pokemon, levels, fainted): if not has_fainted and level > best_level: best_level = level best_choice = curr_pokemon return best_choice
""" Eliminate Odd Numbers within a List Published by Sri in Python Create a function that takes a list of numbers and returns only the even values. Examples [1, 2, 3, 4, 5, 6, 7, 8] ➞ [2, 4, 6, 8] [43, 65, 23, 89, 53, 9, 6] ➞ [6] [718, 991, 449, 644, 380, 440] ➞ [718, 644, 380, 440] """ def noOdds(lst): return [i for i in lst if i%2 == 0] ________________________________________________________________________________________________________________________ """ Find the Smallest Number in a List Published by Sri in Python Create a function that takes a list of numbers and returns the smallest number in the list. Examples [34, 15, 88, 2] ➞ 2 [34, -345, -1, 100] ➞ -345 [-76, 1.345, 1, 0] ➞ -76 [0.4356, 0.8795, 0.5435, -0.9999] ➞ -0.9999 [7, 7, 7] ➞ 7 """ def findSmallestNum(lst): return min(lst) ________________________________________________________________________________________________________________________ """ Is the Number Even or Odd? Published by Matt in Python Create a function that takes a number as an argument and returns "even" for even numbers and "odd" for odd numbers. Examples 3 ➞ "odd" 146 ➞ "even" 19 ➞ "odd" """ def isEvenOrOdd(num): answer = "even" if num%2 == 0 else "odd" return answer
print('*'*16) print('Sequência de Fibonacci') print('*'*16) n = int(input('Quantos elementos você quer mostrar? ')) t1 = 0 t2 = 1 if n == 0: exit() elif n == 1: print(t1) elif n == 2: print(t1, ' ► ', t2) else: print(t1, '►', t2, '► ', end='') cont = 3 while cont <= n: t3 = t1 + t2 print(t3, '► ' if cont < n else '', end='') t1 = t2 t2 = t3 cont += 1
# MIT License # ----------- # Copyright (c) 2021 Sorn Zupanic Maksumic (https://www.usn.no) # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. class Vector2: def __init__(self, x, y): self.x = x self.y = y def magnitude(self): return pow(self.x * self.x + self.y * self.y, 0.5) def __sub__(self, other): return Vector2(self.x - other.x, self.y - other.y) def dot(self, other): return self.x * other.x + self.y * other.y
pd = int(input()) num = pd while True : rev = 0 temp = num + 1 while temp>0 : rem = temp%10; rev = rev*10 + rem temp = temp//10 if rev == num+1 : print(num+1) break num += 1
DAL_VIEW_PY = """# generated by appcreator from django.db.models import Q from dal import autocomplete from . models import * {% for x in data %} class {{ x.model_name }}AC(autocomplete.Select2QuerySetView): def get_queryset(self): qs = {{ x.model_name }}.objects.all() if self.q: qs = qs.filter( Q(legacy_id__icontains=self.q) | Q({{ x.model_representation }}__icontains=self.q) ) return qs {% endfor %} """ DAL_URLS_PY = """# generated by appcreator from django.conf.urls import url from . import dal_views app_name = '{{ app_name }}' urlpatterns = [ {%- for x in data %} url( r'^{{ x.model_name|lower }}-autocomplete/$', dal_views.{{ x.model_name}}AC.as_view(), name='{{ x.model_name|lower }}-autocomplete' ), {%- endfor %} ] """ APP_PY = """ from django.apps import AppConfig class {{ app_name|title }}Config(AppConfig): name = '{{ app_name }}' """ ADMIN_PY = """# generated by appcreator from django.contrib import admin from . models import ( {%- for x in data %} {{ x.model_name }}{{ "," if not loop.last }} {%- endfor %} ) {%- for x in data %} admin.site.register({{ x.model_name }}) {%- endfor %} """ URLS_PY = """# generated by appcreator from django.conf.urls import url from . import views app_name = '{{ app_name }}' urlpatterns = [ {%- for x in data %} url( r'^{{ x.model_name|lower }}/$', views.{{ x.model_name}}ListView.as_view(), name='{{ x.model_name|lower }}_browse' ), url( r'^{{ x.model_name|lower }}/detail/(?P<pk>[0-9]+)$', views.{{ x.model_name}}DetailView.as_view(), name='{{ x.model_name|lower }}_detail' ), url( r'^{{ x.model_name|lower }}/create/$', views.{{ x.model_name}}Create.as_view(), name='{{ x.model_name|lower }}_create' ), url( r'^{{ x.model_name|lower }}/edit/(?P<pk>[0-9]+)$', views.{{ x.model_name}}Update.as_view(), name='{{ x.model_name|lower }}_edit' ), url( r'^{{ x.model_name|lower }}/delete/(?P<pk>[0-9]+)$', views.{{ x.model_name}}Delete.as_view(), name='{{ x.model_name|lower }}_delete'), {%- endfor %} ] """ FILTERS_PY = """# generated by appcreator import django_filters from django import forms from dal import autocomplete from vocabs.filters import generous_concept_filter from vocabs.models import SkosConcept from . models import ( {%- for x in data %} {{ x.model_name }}{{ "," if not loop.last }} {%- endfor %} ) {% for x in data %} class {{ x.model_name }}ListFilter(django_filters.FilterSet): legacy_id = django_filters.CharFilter( lookup_expr='icontains', help_text={{ x.model_name}}._meta.get_field('legacy_id').help_text, label={{ x.model_name}}._meta.get_field('legacy_id').verbose_name ) {%- for y in x.model_fields %} {%- if y.field_type == 'CharField' %} {{y.field_name}} = django_filters.CharFilter( lookup_expr='icontains', help_text={{ x.model_name}}._meta.get_field('{{y.field_name}}').help_text, label={{ x.model_name}}._meta.get_field('{{y.field_name}}').verbose_name ) {%- endif %} {%- if y.field_type == 'TextField' %} {{y.field_name}} = django_filters.CharFilter( lookup_expr='icontains', help_text={{ x.model_name}}._meta.get_field('{{y.field_name}}').help_text, label={{ x.model_name}}._meta.get_field('{{y.field_name}}').verbose_name ) {%- endif %} {%- if y.related_class == 'SkosConcept' %} {{y.field_name}} = django_filters.ModelMultipleChoiceFilter( queryset=SkosConcept.objects.filter( collection__name="{{y.field_name}}" ), help_text={{x.model_name}}._meta.get_field('{{y.field_name}}').help_text, label={{x.model_name}}._meta.get_field('{{y.field_name}}').verbose_name, method=generous_concept_filter, widget=autocomplete.Select2Multiple( url="/vocabs-ac/specific-concept-ac/{{y.field_name}}", attrs={ 'data-placeholder': 'Autocomplete ...', 'data-minimum-input-length': 2, }, ) ) {%- elif y.field_type == 'ManyToManyField' %} {{y.field_name}} = django_filters.ModelMultipleChoiceFilter( queryset={{y.related_class}}.objects.all(), help_text={{x.model_name}}._meta.get_field('{{y.field_name}}').help_text, label={{x.model_name}}._meta.get_field('{{y.field_name}}').verbose_name, widget=autocomplete.Select2Multiple( url="{{ app_name }}-ac:{{y.related_class|lower}}-autocomplete", ) ) {%- elif y.field_type == 'ForeignKey' %} {{y.field_name}} = django_filters.ModelMultipleChoiceFilter( queryset={{y.related_class}}.objects.all(), help_text={{x.model_name}}._meta.get_field('{{y.field_name}}').help_text, label={{x.model_name}}._meta.get_field('{{y.field_name}}').verbose_name, widget=autocomplete.Select2Multiple( url="{{ app_name }}-ac:{{y.related_class|lower}}-autocomplete", ) ) {%- endif %} {%- endfor %} class Meta: model = {{ x.model_name }} fields = [ 'id', 'legacy_id', {% for y in x.model_fields %} {%- if y.field_type == 'DateRangeField' or y.field_type == 'MultiPolygonField'%} {%- else %}'{{ y.field_name }}', {%- endif %} {% endfor %}] {% endfor %} """ FORMS_PY = """# generated by appcreator from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit, Layout, Fieldset, Div, MultiField, HTML from crispy_forms.bootstrap import Accordion, AccordionGroup from vocabs.models import SkosConcept from . models import ( {%- for x in data %} {{ x.model_name }}{{ "," if not loop.last }} {%- endfor %} ) {% for x in data %} class {{ x.model_name }}FilterFormHelper(FormHelper): def __init__(self, *args, **kwargs): super({{ x.model_name }}FilterFormHelper, self).__init__(*args, **kwargs) self.helper = FormHelper() self.form_class = 'genericFilterForm' self.form_method = 'GET' self.helper.form_tag = False self.add_input(Submit('Filter', 'Search')) self.layout = Layout( Fieldset( 'Basic search options', 'id', css_id="basic_search_fields" ), Accordion( AccordionGroup( 'Advanced search', {% for y in x.model_fields %} {% if y.field_type == 'DateRangeField' or y.field_type == 'id' or y.field_type == 'MultiPolygonField' %} {% else %}'{{ y.field_name }}', {%- endif %} {%- endfor %} css_id="more" ), AccordionGroup( 'admin', 'legacy_id', css_id="admin_search" ), ) ) class {{ x.model_name }}Form(forms.ModelForm): {%- for y in x.model_fields %} {%- if y.related_class == 'SkosConcept' and y.field_type == 'ForeignKey'%} {{y.field_name}} = forms.ModelChoiceField( required=False, label="{{y.field_verbose_name}}", queryset=SkosConcept.objects.filter(collection__name="{{y.field_name}}") ) {%- elif y.related_class == 'SkosConcept' and y.field_type == 'ManyToManyField'%} {{y.field_name}} = forms.ModelMultipleChoiceField( required=False, label="{{y.field_verbose_name}}", queryset=SkosConcept.objects.filter(collection__name="{{y.field_name}}") ) {%- endif -%} {% endfor %} class Meta: model = {{ x.model_name }} fields = "__all__" def __init__(self, *args, **kwargs): super({{ x.model_name }}Form, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_tag = True self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-md-3' self.helper.field_class = 'col-md-9' self.helper.add_input(Submit('submit', 'save'),) {% endfor %} """ TABLES_PY = """# generated by appcreator import django_tables2 as tables from django_tables2.utils import A from browsing.browsing_utils import MergeColumn from . models import ( {%- for x in data %} {{ x.model_name }}{{ "," if not loop.last }} {%- endfor %} ) {% for x in data %} class {{ x.model_name }}Table(tables.Table): id = tables.LinkColumn(verbose_name='ID') merge = MergeColumn(verbose_name='keep | remove', accessor='pk') {%- for y in x.model_fields %} {%- if y.field_type == 'ManyToManyField' %} {{ y.field_name }} = tables.columns.ManyToManyColumn() {%- endif %} {%- endfor %} class Meta: model = {{ x.model_name }} sequence = ('id',) attrs = {"class": "table table-responsive table-hover"} {% endfor %} """ VIEWS_PY = """# generated by appcreator from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from django.urls import reverse, reverse_lazy from django.views.generic.detail import DetailView from django.views.generic.edit import DeleteView from . filters import * from . forms import * from . tables import * from . models import ( {%- for x in data %} {{ x.model_name }}{{ "," if not loop.last }} {%- endfor %} ) from browsing.browsing_utils import ( GenericListView, BaseCreateView, BaseUpdateView, BaseDetailView ) {% for x in data %} class {{ x.model_name }}ListView(GenericListView): model = {{ x.model_name }} filter_class = {{ x.model_name }}ListFilter formhelper_class = {{ x.model_name }}FilterFormHelper table_class = {{ x.model_name }}Table init_columns = [ 'id', {%- if x.model_representation != 'nan' %} '{{ x.model_representation }}', {%- endif %} ] enable_merge = True class {{ x.model_name }}DetailView(BaseDetailView): model = {{ x.model_name }} template_name = 'browsing/generic_detail.html' class {{ x.model_name }}Create(BaseCreateView): model = {{ x.model_name }} form_class = {{ x.model_name }}Form @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super({{ x.model_name }}Create, self).dispatch(*args, **kwargs) class {{ x.model_name }}Update(BaseUpdateView): model = {{ x.model_name }} form_class = {{ x.model_name }}Form @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super({{ x.model_name }}Update, self).dispatch(*args, **kwargs) class {{ x.model_name }}Delete(DeleteView): model = {{ x.model_name }} template_name = 'webpage/confirm_delete.html' success_url = reverse_lazy('{{ app_name }}:{{ x.model_name|lower }}_browse') @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super({{ x.model_name }}Delete, self).dispatch(*args, **kwargs) {% endfor %} """ MODELS_PY = """# generated by appcreator from django.contrib.gis.db import models from django.urls import reverse from browsing.browsing_utils import model_to_dict def set_extra(self, **kwargs): self.extra = kwargs return self models.Field.set_extra = set_extra class IdProvider(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) legacy_id = models.CharField( blank=True, null=True, max_length=250, ) class Meta: abstract = True {% for x in data %} class {{ x.model_name }}(IdProvider): {% if x.model_helptext %}### {{ x.model_helptext }} ###{% endif %} legacy_id = models.CharField( max_length=300, blank=True, verbose_name="Legacy ID" ) {%- for y in x.model_fields %} {%- if y.field_type == 'DateRangeField' %} {{ y.field_name }} = {{ y.field_type}}( {%- else %} {{ y.field_name }} = models.{{ y.field_type}}( {%- endif %} {%- if y.field_name == 'id' %} primary_key=True, {%- endif %} {%- if y.field_type == 'DecimalField' %} max_digits=19, decimal_places=10, {%- endif %} {%- if y.field_type == 'BooleanField' %} default=False, {%- endif %} {%- if y.field_type == 'CharField' %} blank=True, null=True, {%- if y.choices %} choices={{ y.choices }}, {%- endif %} max_length=250, {%- elif y.field_type == 'TextField' %} blank=True, null=True, {%- elif y.field_type == 'ForeignKey' %} {%- if y.related_class == 'SkosConcept' %} {{ y.related_class }}, {%- else %} "{{ y.related_class }}", {%- endif %} related_name='{{ y.related_name }}', on_delete=models.SET_NULL, {%- if y.field_name != 'id' %} null=True, blank=True, {%- endif %} {%- elif y.field_type == 'ManyToManyField' %} {%- if y.related_class == 'SkosConcept' %} {{ y.related_class }}, {%- else %} "{{ y.related_class }}", {%- endif %} {%- if y.through %} through='{{ y.through }}', {%- endif %} related_name='{{ y.related_name }}', blank=True, {%- else %} {%- if y.field_name != 'id' %} blank=True, null=True, {%- endif %} {%- endif %} verbose_name="{{ y.field_verbose_name }}", help_text="{{ y.field_helptext }}", ).set_extra( is_public={{ y.field_public }}, {%- if y.value_from %} data_lookup="{{ y.value_from }}", {%- endif %} {%- if y.arche_prop %} arche_prop="{{ y.arche_prop }}", {%- endif %} {%- if y.arche_prop_str_template %} arche_prop_str_template="{{ y.arche_prop_str_template }}", {%- endif %} ) {%- endfor %} orig_data_csv = models.TextField( blank=True, null=True, verbose_name="The original data" ).set_extra( is_public=True ) class Meta: {% if x.model_order == 'nan' %} ordering = [ 'id', ] {%- else %} ordering = [ '{{ x.model_order }}', ] {%- endif %} verbose_name = "{{ x.model_verbose_name }}" {% if x.model_representation == 'nan' %} def __str__(self): return "{}".format(self.id) {%- else %} def __str__(self): if self.{{ x.model_representation }}: return "{}".format(self.{{ x.model_representation }}) else: return "{}".format(self.legacy_id) {%- endif %} def field_dict(self): return model_to_dict(self) @classmethod def get_listview_url(self): return reverse('{{ app_name }}:{{ x.model_name|lower }}_browse') {% if x.source_table %} @classmethod def get_source_table(self): return "{{ x.source_table }}" {% else %} @classmethod def get_source_table(self): return None {% endif %} {% if x.natural_primary_key %} @classmethod def get_natural_primary_key(self): return "{{ x.natural_primary_key }}" {% else %} @classmethod def get_natural_primary_key(self): return None {% endif %} @classmethod def get_createview_url(self): return reverse('{{ app_name }}:{{ x.model_name|lower }}_create') def get_absolute_url(self): return reverse('{{ app_name }}:{{ x.model_name|lower }}_detail', kwargs={'pk': self.id}) def get_absolute_url(self): return reverse('{{ app_name }}:{{ x.model_name|lower }}_detail', kwargs={'pk': self.id}) def get_delete_url(self): return reverse('{{ app_name }}:{{ x.model_name|lower }}_delete', kwargs={'pk': self.id}) def get_edit_url(self): return reverse('{{ app_name }}:{{ x.model_name|lower }}_edit', kwargs={'pk': self.id}) def get_next(self): next = self.__class__.objects.filter(id__gt=self.id) if next: return reverse( '{{ app_name }}:{{ x.model_name|lower }}_detail', kwargs={'pk': next.first().id} ) return False def get_prev(self): prev = self.__class__.objects.filter(id__lt=self.id).order_by('-id') if prev: return reverse( '{{ app_name }}:{{ x.model_name|lower }}_detail', kwargs={'pk': prev.first().id} ) return False {% endfor %} """
""" https://adventofcode.com/2018/day/14 """ def readFile(): with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f: return f.read() def part1(vals): border = int(vals) scores = [3, 7] elf1 = 0 elf2 = 1 i = 2 while i < border + 10: new = scores[elf1] + scores[elf2] if new > 9: scores.append(new // 10) scores.append(new % 10) i += 2 else: scores.append(new) i += 1 elf1 = (elf1 + 1 + scores[elf1]) % i elf2 = (elf2 + 1 + scores[elf2]) % i return "".join([str(i) for i in scores[border:border + 10]]) def part2(vals): size = len(vals) comp = [int(c) for c in vals] scores = [3, 7] elf1 = 0 elf2 = 1 i = 2 while True: new = scores[elf1] + scores[elf2] if new > 9: scores.append(new // 10) scores.append(new % 10) i += 2 if scores[-(size + 1):-1] == comp: return i - (size + 1) else: scores.append(new) i += 1 if scores[-size:] == comp: return i - size elf1 = (elf1 + 1 + scores[elf1]) % i elf2 = (elf2 + 1 + scores[elf2]) % i if __name__ == "__main__": vals = readFile() print(f"Part 1: {part1(vals)}") print(f"Part 2: {part2(vals)}")
n=int(input()) count=n sumnum=0 if n==0: print("No Data") else: while count>0: num=float(input()) sumnum+=num count-=1 print(sumnum/n)
__config_version__ = 1 GLOBALS = { 'serializer': '{{major}}.{{minor}}.{{patch}}{{status if status}}', } FILES = [{ 'path': 'README.rst', 'serializer': '{{major}}.{{minor}}.{{patch}}'}, 'docs/conf.py', 'setup.py', 'src/oemof/tabular/__init__.py'] VERSION = ['major', 'minor', 'patch', {'name': 'status', 'type': 'value_list', 'allowed_values': ['', 'dev']}]
#!/bin/python3 """What is the first Fibonacci number to contain N digits""" #https://www.hackerrank.com/contests/projecteuler/challenges/euler025/problem #First line T number of test cases, then T lines of N values #Constraints: 1 <= T <= 5000; 2 <= N <= 5000 #fibNums = [1,1] fibIndex = [1] #fibIndex[n-1] has the index of the first fibonacci number with at least n digits def generateFibonacciIndexes(): """if the last number in fibNums isnt long enough, keep appending new ones until it is""" """Return True if we had to add numbers (so our answer is the last one)""" appended = False a = 1 b = 1 index = 3 length = 1 while length < 5001: c = a + b if len(str(c)) > length: fibIndex.append(index) length += 1 a = b b = c index += 1 def main(): generateFibonacciIndexes() t = int(input()) for a0 in range(t): n = int(input()) print(fibIndex[n-1]) if __name__ == "__main__": main()
__version__ = '0.1.2' NAME = 'atlasreader' MAINTAINER = 'Michael Notter' EMAIL = 'michaelnotter@hotmail.com' VERSION = __version__ LICENSE = 'MIT' DESCRIPTION = ('A toolbox for generating cluster reports from statistical ' 'maps') LONG_DESCRIPTION = ('') URL = 'http://github.com/miykael/{name}'.format(name=NAME) DOWNLOAD_URL = ('https://github.com/miykael/{name}/archive/{ver}.tar.gz' .format(name=NAME, ver=__version__)) INSTALL_REQUIRES = [ 'matplotlib', 'nibabel', 'nilearn', 'numpy', 'pandas', 'scipy', 'scikit-image', 'scikit-learn' ] TESTS_REQUIRE = [ 'pytest', 'pytest-cov' ] PACKAGE_DATA = { 'atlasreader': [ 'data/*', 'data/atlases/*', 'data/templates/*' ], 'atlasreader.tests': [ 'data/*' ] }
# -*- coding: utf-8 -*- class BaseError(Exception): """Base Error in project """ pass
def apply_mode(module, mode): if mode == 'initialize' and 'reset_parameters' in dir(module): module.reset_parameters() for param in module.parameters(): if mode == 'freeze': param.requires_grad = False elif mode in ['fine-tune', 'initialize']: param.requires_grad = True
reactions_irreversible = [ # FIXME Automatic irreversible for: Cl- {"CaCl2": -1, "Ca++": 1, "Cl-": 2, "type": "irrev", "id_db": -1}, {"NaCl": -1, "Na+": 1, "Cl-": 1, "type": "irrev", "id_db": -1}, {"KCl": -1, "K+": 1, "Cl-": 1, "type": "irrev", "id_db": -1}, {"KOH": -1, "K+": 1, "OH-": 1, "type": "irrev", "id_db": -1}, {"MgCl2": -1, "Mg++": 1, "Cl-": 2, "type": "irrev", "id_db": -1}, {"K2SO4": -1, "K+": 2, "SO4--": 1, "type": "irrev", "id_db": -1}, {"BaCl2": -1, "Ba++": 1, "Cl-": 2, "type": "irrev", "id_db": -1}, {"NaHSO4": -1, "Na+": 1, "HSO4-": 1, "type": "irrev", "id_db": -1}, {"Na2SO4": -1, "Na+": 2, "HSO4-": 1, "type": "irrev", "id_db": -1}, {"H2SO4": -1, "H+": 2, "SO4-": 1, "type": "irrev", "id_db": -1}, {"Al2(SO4)3": -1, "Al+++": 2, "SO4--": 3, "type": "irrev", "id_db": -1}, ]
class FirstOrderFilter: # first order filter def __init__(self, x0, rc, dt, initialized=True): self.x = x0 self.dt = dt self.update_alpha(rc) self.initialized = initialized def update_alpha(self, rc): self.alpha = self.dt / (rc + self.dt) def update(self, x): if self.initialized: self.x = (1. - self.alpha) * self.x + self.alpha * x else: self.initialized = True self.x = x return self.x
# Move to the treasure room and defeat all the ogres. while True: hero.moveUp(4) hero.moveRight(4) hero.moveDown(3) hero.moveLeft() enemy = hero.findNearestEnemy() hero.attack(enemy) hero.attack(enemy) enemy2 = hero.findNearestEnemy() hero.attack(enemy2) hero.attack(enemy2) enemy3 = hero.findNearestEnemy() hero.attack(enemy3) hero.attack(enemy3) hero.moveLeft() enemy4 = hero.findNearestEnemy() hero.attack(enemy4) hero.attack(enemy4)
# Copyright 2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------------------------ class SimpleBlock: """Use a simpler data structure to save memory in the event the graph gets large and to simplify operations on blocks.""" def __init__(self, num, ident, previous): self.num = num self.ident = ident self.previous = previous @classmethod def from_block_dict(cls, block_dict): return cls( int(block_dict['header']['block_num']), block_dict['header_signature'], block_dict['header']['previous_block_id'], ) def __str__(self): return "(NUM:{}, ID:{}, P:{})".format( self.num, self.ident[:8], self.previous[:8]) class ForkGraphNode: """Represents a node on the fork graph. `siblings` is a dictionary whose keys are all the block ids that have the same parent and whose values are all the peers that have that particular block id.""" def __init__(self, num, previous): self.siblings = {} self.num = num self.previous = previous def add_sibling(self, peer_id, block): assert block.num == self.num assert block.previous == self.previous if block.ident not in self.siblings: self.siblings[block.ident] = [] self.siblings[block.ident].append(peer_id) class ForkGraph: """Represents a directed graph of blocks from multiple peers. Blocks are stored under their previous block's id and each node may have multiple children. An AssertionError is raised if two blocks are added with the same previous block id but different block numbers. The earliest block is stored in `root`. This implementation does not ensure that all nodes are connected to the root. """ def __init__(self): self._graph = {} self._root_node = None self._root_block = None @property def root(self): return self._root_block def add_block(self, peer_id, block): if block.previous not in self._graph: self._graph[block.previous] = \ ForkGraphNode(block.num, block.previous) self._graph[block.previous].add_sibling(peer_id, block) if self._root_node is None or self._root_node.num > block.num: self._root_node = self._graph[block.previous] self._root_block = block def walk(self, head=None): """Do a breadth-first walk of the graph, yielding on each node, starting at `head`.""" head = head or self._root_node queue = [] queue.insert(0, head) while queue: node = queue.pop() yield node.num, node.previous, node.siblings for child in node.siblings: if child in self._graph: queue.insert(0, self._graph[child])
class Solution: def numUniqueEmails(self, emails): """ :type emails: List[str] :rtype: int """ res = [] for email in emails: at_index = email.find("@") temp = email[:at_index].replace(".","") + email[at_index:] at_index = temp.find("@") plus_index = temp.find("+") if plus_index != -1: temp = temp[:plus_index], temp[at_index:] res.append(temp) return len(set(res))
class SqlAlchemyMediaException(Exception): """ The base class for all exceptions """ pass class MaximumLengthIsReachedError(SqlAlchemyMediaException): """ Indicates the maximum allowed file limit is reached. """ def __init__(self, max_length: int): super().__init__( 'Cannot store files larger than: %d bytes' % max_length ) class ContextError(SqlAlchemyMediaException): """ Exception related to :class:`.StoreManager`. """ class DefaultStoreError(SqlAlchemyMediaException): """ Raised when no default store is registered. .. seealso:: :meth:`.StoreManager.register`. """ def __init__(self): super(DefaultStoreError, self).__init__( 'Default store is not defined.' ) class AnalyzeError(SqlAlchemyMediaException): """ Raised when :class:`.Analyzer` can not analyze the file-like object. """ class ValidationError(SqlAlchemyMediaException): """ Raised when :class:`.Validator` can not validate the file-like object. """ class ContentTypeValidationError(ValidationError): """ Raised by :meth:`.Validator.validate` when the content type is missing or invalid. :param content_type: The invalid content type if any. """ def __init__(self, content_type=None, valid_content_types=None): if content_type is None: message = 'Content type is not provided.' else: message = 'Content type is not supported %s.' % content_type if valid_content_types: message += 'Valid options are: %s' % ', '.join(valid_content_types) super().__init__(message) class DescriptorError(SqlAlchemyMediaException): """ A sub-class instance of this exception may raised when an error has occurred in :class:`.BaseDescriptor` and it's subtypes. """ class DescriptorOperationError(DescriptorError): """ Raised when a subclass of :class:`.BaseDescriptor` is abused. """ class OptionalPackageRequirementError(SqlAlchemyMediaException): """ Raised when an optional package is missing. The constructor is trying to search for package name in requirements-optional.txt and find the requirement and it's version criteria to inform the user. :param package_name: The name of the missing package. """ __optional_packages__ = [ 'python-magic >= 0.4.12', 'requests-aws4auth >= 0.9', 'requests-aliyun >= 0.2.5' ] def __init__(self, package_name: str): # Searching for package name in requirements-optional.txt packages = [l for l in self.__optional_packages__ if package_name in l] if not len(packages): raise ValueError('Cannot find the package: %s.' % package_name) super().__init__( 'The following packages are missing.' f'in order please install them: {", ".join(packages)}') class ThumbnailIsNotAvailableError(SqlAlchemyMediaException): """ Raised when requested thumbnail is not available(generated) yet. """ class DimensionValidationError(ValidationError): """ Raises when ``width`` or ``height`` of the media is not meet the limitations. """ class AspectRatioValidationError(ValidationError): """ Raises when the image aspect ratio is not valid. """ class S3Error(SqlAlchemyMediaException): """ Raises when the image upload or delete to s3. """ class OS2Error(SqlAlchemyMediaException): """ Raises when the image upload or delete to os2. """ class SSHError(SqlAlchemyMediaException): """ Raises when the ssh command is failed. """
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) CloudZero, Inc. All rights reserved. # Licensed under the MIT License. See LICENSE file in the project root for full license information. """ `cloudzero-awstools` tests package. """
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # ------------------------------------------------------------ # File: const.py # Created Date: 2020/6/24 # Created Time: 0:13 # Author: Hypdncy # Author Mail: hypdncy@outlook.com # Copyright (c) 2020 Hypdncy # ------------------------------------------------------------ # .::::. # .::::::::. # ::::::::::: # ..:::::::::::' # '::::::::::::' # .:::::::::: # '::::::::::::::.. # ..::::::::::::. # ``:::::::::::::::: # ::::``:::::::::' .:::. # ::::' ':::::' .::::::::. # .::::' :::: .:::::::'::::. # .:::' ::::: .:::::::::' ':::::. # .::' :::::.:::::::::' ':::::. # .::' ::::::::::::::' ``::::. # ...::: ::::::::::::' ``::. # ````':. ':::::::::' ::::.. # '.:::::' ':'````.. # ------------------------------------------------------------ company_name = "懂王" systems_file = "./data/systems.csv" json_loops_error = "./logs/loops_error.json" json_loops_global = "./logs/loops_global.json" template_loops_file = "./template/主机扫描报告模板-202104.docx" translate_status = True translate_asyncios = 4 translate_baidu_url = "http://api.fanyi.baidu.com/api/trans/vip/translate" translate_baidu_appid = "XXXXXX" translate_baidu_secret = "XXXXXX" translate_youdao_url = "https://openapi.youdao.com/api" translate_youdao_appkey = "xxxxxxxx" translate_youdao_appsecret = "xxxxxxxx" translate_order = { "name_en": "name_cn", "describe_en": "describe_cn", "solution_en": "solution_cn", } table_host_ips = ["序号", "测试对象", "对象名称"] vuln_db_file = "./cnf/vuln.db" vuln_db_info = { "sqlite_code": "utf-8", "vuln_table": "vuln", "order": { "plugin_id": 0, "name_en": 1, "name_cn": 2, "risk_cn": 3, # 字段废弃 "describe_cn": 4, "solution_cn": 5, "cve": 6 } } vuln_info = { "name_en": "", "name_cn": "", "risk_en": "", "risk_cn": "", "describe_en": "", "describe_cn": "", "solution_en": "", "solution_cn": "", "cve": "" } nessus_csv_dir = "./data/nessus/" nessus_csv_order = { "plugin_id": 0, "name_en": 7, "risk_en": 3, "describe_en": 9, "solution_en": 10, "cve": 1, "host": 4, "protocol": 5, "port": 6, } risk_scores = { "Critical": 4, "High": 3, "Medium": 2, "Low": 1, } risk_en2cn = { "Critical": "紧急", "High": "高危", "Medium": "中危", "Low": "低危", } risk_range_en = ["Critical", "High", "Medium", "Low"] risk_loops_conclusion = { "safe": "暂未发现有效漏洞。", "unsafe": "共发现安全漏洞种类{risk_count}个,其中紧急漏洞{risk_urgent}个、高危漏洞{risk_high}个、中危漏洞{risk_medium}个、低危漏洞{risk_low}个。存在的安全隐患主要包括{risk_includes}等安全漏洞,可能将导致{risk_harms}等严重危害。" } risk_hosts_conclusion = { "safe": "暂未发现有效漏洞。", "unsafe": "共发现安全漏洞主机{risk_count}个,其中紧急主机{risk_urgent}个、高危主机{risk_high}个、中危主机{risk_medium}个、低危主机{risk_low}个。存在的安全隐患主要包括{risk_includes}等安全漏洞,可能将导致{risk_harms}等严重危害。" }
# SPDX-FileCopyrightText: 2021 Carter Nelson for Adafruit Industries # # SPDX-License-Identifier: MIT # This file is where you keep secret settings, passwords, and tokens! # If you put them in the code you risk committing that info or sharing it secrets = { # tuples of name, sekret key, color 'totp_keys' : [("Github", "JBSWY3DPEHPK3PXP", 0x8732A8), ("Discord", "JBSWY3DPEHPK3PXQ", 0x32A89E), ("Slack", "JBSWY5DZEHPK3PXR", 0xFC861E), ("Basecamp", "JBSWY6DZEHPK3PXS", 0x55C24C), ("Gmail", "JBSWY7DZEHPK3PXT", 0x3029FF), None, None, # must have 12 entires None, # set None for unused keys None, ("Hello Kitty", "JBSWY7DZEHPK3PXU", 0xED164F), None, None, ] }
# Do not edit this file directly. # It was auto-generated by: code/programs/reflexivity/reflexive_refresh load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") def python3(): http_archive( name = "python3", build_file = "//bazel/deps/python3:build.BUILD", sha256 = "36592ee2910b399c68bf0ddad1625f2c6a359ab9a8253d676d44531500e475d4", strip_prefix = "python3-7f755fe87d217177603a27d9dcc2fedc979f0f1a", urls = [ "https://github.com/Unilang/python3/archive/7f755fe87d217177603a27d9dcc2fedc979f0f1a.tar.gz", ], patch_cmds = [ "sed -i '/HAVE_CRYPT_H/d' usr/include/x86_64-linux-gnu/python3.6m/pyconfig.h", ], )
# Python program that uses classes and objects to represent realworld entities class Book(): # A class is a custom datatype template or blueprint title="" # Attribute author="" pages=0 book1 = Book() # An object is an instance of a class book2 = Book() book1.title = "Harry Potter" # The objects attribute values can be directly modified book1.author = "JK Rowling" book1.pages = 500 book2.title = "Lord of the Rings" book2.author = "Tolkien" book2.pages = 700 print("\nTitle:\t", book1.title,"\nAuthor:\t",book1.author,"\nPages:\t",book1.pages) # Prints the attribute values of the first book object print("\nTitle:\t", book2.title,"\nAuthor:\t",book2.author,"\nPages:\t",book2.pages) # Prints the attribute values of the second book object
note = """ I do not own the pictures, I simply provide for you a connection from your Discord server to Gelbooru using both legal and free APIs. I am not responsible in any way for the content that GelBot will send to the chat. Keep in mind YOU are the one who type the tags. """ help = """ The usage of GelBot is simple. Here's only one command that you need to get pictures. !pic is what you need. Syntax: !pic [optional rating] tag/tag with a space/tag/tag Type !gelexamples to get better grasp of the command. Type !gelratings if you don't know how to use ratings. Please type !gelnote and read my disclaimer. """ examples = """ Some examples of !pic usage: !pic rs lucy heartfilia !pic lucy heartfilia/cat ears/long hair !pic aqua (konosuba) !pic rs misaka mikoto/animal ears/sweater !pic rq kitchen """ ratings = """ We've got 3 ratings available: rs - rating safe - mostly SFW content, rq - rating questionable - mostly NSFW, well questionable content, re - rating explicit - definitely unquestionable NSFW content. For both rating questionable and explicit NSFW channel is required. If you don't specify any, GelBot will look only within rating safe. """
# INSERTION OF NODE AT END , BEGGINING AND AT GIVEN POS VALUE class linkedListNode: def __init__(self, value, nextNode=None): self.value = value self.nextNode = nextNode class linkedList: def __init__(self, head=None): self.head = head def printList(self): currentNode = self.head while currentNode is not None: print(currentNode.value, "->", end="") currentNode = currentNode.nextNode print("None") def insertAtEnd(self, value): node = linkedListNode(value) if(self.head is None): self.head = node return currentNode = self.head while True: if(currentNode.nextNode is None): currentNode.nextNode = node break currentNode = currentNode.nextNode def insertAtBeginning(self, value): node = linkedListNode(value) if(self.head is None): self.head = node return node.nextNode = self.head self.head = node def insertAtPos(self, value, prev_value): node = linkedListNode(value) if(self.head is None): self.head = node return currentNode = self.head prevNode = self.head while currentNode.value is not prev_value: if(currentNode.nextNode is None): print("Node not found") break prevNode = currentNode currentNode = currentNode.nextNode prevNode.nextNode = node node.nextNode = currentNode if __name__ == '__main__': nodeCreation = linkedList() nodeCreation.insertAtEnd("3") nodeCreation.printList() nodeCreation.insertAtEnd("5") nodeCreation.printList() nodeCreation.insertAtEnd("9") nodeCreation.printList() nodeCreation.insertAtBeginning("1") nodeCreation.printList() nodeCreation.insertAtPos("7", "9") nodeCreation.printList() nodeCreation.insertAtPos("7", "8") nodeCreation.printList()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' @Author: Adam @Date: 2020-04-13 16:48:59 @LastEditTime: 2020-04-17 16:07:33 @LastEditors: Please set LastEditors @Description: In User Settings Edit @FilePath: /LearnPython/python3_senior.py ''' # 高级特征 # ---------------------------------------- start ---------------------------------------- ''' print('-----------高级特征-----------') # 比如构造一个1, 3, 5, 7, ..., 99的列表,可以通过循环实现: L = [] n = 1 while n <= 99: L.append(n) n = n + 2 print(L) ''' # 切片 ''' print('-----------切片-----------') L= ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] # 取前3个元素,应该怎么做? # 笨办法 print([L[0], L[1], L[2]]) # 之所以是笨办法是因为扩展一下,取前N个元素就没辙了。 # 取前N个元素,也就是索引为0-(N-1)的元素,可以用循环: r = [] n = 4 for i in range(n): r.append(L[i]) print(r) # 对这种经常取指定索引范围的操作,用循环十分繁琐,因此,Python提供了切片(Slice)操作符,能大大简化这种操作。 # 对应上面的问题,取前3个元素,用一行代码就可以完成切片 print(L[0:3]) # L[0:3]表示,从索引0开始取,直到索引3为止,但不包括索引3。即索引0,1,2,正好是3个元素。 # 如果第一个索引是0,还可以省略: print(L[:3]) print(L[1:3]) print(L[-2:]) # 记住倒数第一个元素的索引是-1。 # 切片操作十分有用。我们先创建一个0-99的数列: L = list(range(100)) print(L) print(L[:10]) print(L[-10:]) print(L[10:20]) # 前10个数,每两个取一个: print(L[:10:2]) # 所有数,每5个取一个: print(L[::5]) L1 = L[:] print(L1) # tuple也是一种list,唯一区别是tuple不可变。因此,tuple也可以用切片操作,只是操作的结果仍是tuple: print((0, 1, 2, 3, 4, 5)[:3]) # 字符串'xxx'也可以看成是一种list,每个元素就是一个字符。因此,字符串也可以用切片操作,只是操作结果仍是字符串: S = 'ABCDEFG' print(S[:3]) print(S[::2]) # 在很多编程语言中,针对字符串提供了很多各种截取函数(例如,substring),其实目的就是对字符串切片。Python没有针对字符串的截取函数,只需要切片一个操作就可以完成,非常简单。 # 练习 # 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法: def trim(s): # 去除首空格 while s[:1] == ' ': s = s[1:] while s[-1:] == ' ': s = s[:-1] return s # 法2 def trim(s): for i in range(len(s)): if s[:1] == ' ': # 这个处理比较巧妙,不是每次用s[0] s = s[1:] if s[-1:] == ' ': # 这个处理比较巧妙,不是每次用s[-1] s = s[:-1] return s # 递归实现 # def trim(s): # if s[:1] == ' ': # return trim(s[1:]) # elif s[-1:] == ' ': # return trim(s[:-1]) # else: # return s print(trim(' hello ')) # 测试: if trim('hello ') != 'hello': print('测试失败!') elif trim(' hello') != 'hello': print('测试失败!') elif trim(' hello ') != 'hello': print('测试失败!') elif trim(' hello world ') != 'hello world': print('测试失败!') elif trim('') != '': print('测试失败!') elif trim(' ') != '': print('测试失败!') else: print('测试成功!') ''' # ---------------------------------------- end ---------------------------------------- # 迭代 # ---------------------------------------- start ---------------------------------------- ''' print('-----------迭代-----------') # 如果给定一个list或tuple,我们可以通过for循环来遍历这个list或tuple,这种遍历我们称为迭代(Iteration)。 # 在Python中,迭代是通过for ... in来完成的,而很多语言比如C语言,迭代list是通过下标完成的,比如Java代码: d = {'a': 1, 'b': 2, 'c': 3} for key in d: print(key) # 默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values(),如果要同时迭代key和value,可以用for k, v in d.items()。 for value in d.values(): print(value) for key, value in d.items(): print(key, ':', value) # 由于字符串也是可迭代对象,因此,也可以作用于for循环: for ch in 'ABCDEFG': print(ch) # 所以,当我们使用for循环时,只要作用于一个可迭代对象,for循环就可以正常运行,而我们不太关心该对象究竟是list还是其他数据类型。 # 那么,如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断: from collections import Iterable print(isinstance('abc', Iterable)) print(isinstance([1, 2, 3], Iterable)) print(isinstance(123, Iterable)) # 最后一个小问题,如果要对list实现类似Java那样的下标循环怎么办?Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身: for i, value in enumerate(['A', 'B', 'C']): print(i, value) # 上面的for循环里,同时引用了两个变量,在Python里是很常见的,比如下面的代码: for x, y in [(1, 1), (2, 4), (3, 9)]: print(x, y) # 练习 # 请使用迭代查找一个list中最小和最大值,并返回一个tuple: def findMinAndMax(L): "寻找列表中的最大值和最小值,空列表返回None,不用list.sort,不用max、min" if len(L) == 0 or not isinstance(L, list): return (None, None) min = L[0] max = L[0] try: for i in L: if min > i: min = i elif max < i: max = i except TypeError: print(r"can't compare different types") return (None, None) else: return (min, max) # 测试 if findMinAndMax([]) != (None, None): print('测试失败!') elif findMinAndMax([7]) != (7, 7): print('测试失败!') elif findMinAndMax([7, 1]) != (1, 7): print('测试失败!') elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9): print('测试失败!') else: print('测试成功!') print(findMinAndMax('abc')) print(findMinAndMax(['a','b',1])) # ---------------------------------------- end ---------------------------------------- ''' # 列表生成式 # ---------------------------------------- start ---------------------------------------- ''' print('-----------列表生成式-----------') # 列表生成式即List Comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。 L = list(range(1, 11)) print(L) # 但如果要生成[1x1, 2x2, 3x3, ..., 10x10]怎么做?方法一是循环: L = [] for x in range(1, 11): L.append(x ** 2) print(L) # 但是循环太繁琐,而列表生成式则可以用一行语句代替循环生成上面的list: L = [x ** 2 for x in range(1, 11)] print(L) # 写列表生成式时,把要生成的元素x * x放到前面,后面跟for循环,就可以把list创建出来,十分有用,多写几次,很快就可以熟悉这种语法。 # for循环后面还可以加上if判断,这样我们就可以筛选出仅偶数的平方: L = [x ** 2 for x in range(1, 11) if x % 2 == 0] print(L) # 还可以使用两层循环,可以生成全排列: L = [m + n for m in 'ABC' for n in 'XYZ'] print(L) # 三层和三层以上的循环就很少用到了。 # 运用列表生成式,可以写出非常简洁的代码。例如,列出当前目录下的所有文件和目录名,可以通过一行代码实现 import os L = [d for d in os.listdir('.')] print(L) # for循环其实可以同时使用两个甚至多个变量,比如dict的items()可以同时迭代key和value: d = {'x': 'A', 'y': 'B', 'z': 'C'} for k, v in d.items(): print(k, '=', v) # 因此,列表生成式也可以使用两个变量来生成list: L = [k + '=' + v for k, v in d.items()] print(L) # 最后把一个list中所有的字符串变成小写: L = ['HELLO', 'WORLD', 'IBM', 'Apple'] L1 = [s.lower() for s in L] print(L1) # if ... else # 使用列表生成式的时候,有些童鞋经常搞不清楚if...else的用法。 # 例如,以下代码正常输出偶数: L = [x for x in range(1, 11) if x % 2 == 0] print(L) # 但是,我们不能在最后的if加上else: # L = [x for x in range(1, 11) if x % 2 == 0 else 0] # 这是因为跟在for后面的if是一个筛选条件,不能带else,否则如何筛选? # 另一些童鞋发现把if写在for前面必须加else,否则报错: # L = [x if x % 2 == 0 for x in range(1, 11)] # 这是因为for前面的部分是一个表达式,它必须根据x计算出一个结果。因此,考察表达式:x if x % 2 == 0,它无法根据x计算出结果,因为缺少else,必须加上else: L = [x if x % 2 == 0 else -x for x in range(1, 11)] print(L) # 上述for前面的表达式x if x % 2 == 0 else -x才能根据x计算出确定的结果。 # 可见,在一个列表生成式中,for前面的if ... else是表达式,而for后面的if是过滤条件,不能带else。 # 练习 # 如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错: L = ['Hello', 'World', 18, 'Apple', None] # L1 = [s.lower() for s in L] print(L) L2 = [s.lower() for s in L if isinstance(s, str)] # 测试: print(L2) if L2 == ['hello', 'world', 'apple']: print('测试通过!') else: print('测试失败!') ''' # ---------------------------------------- end ---------------------------------------- # 生成器 # ---------------------------------------- start ---------------------------------------- print('-----------生成器-----------') # 通过列表生成式,我们可以直接创建一个列表。但是,受到内存限制,列表容量肯定是有限的。而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。 # 所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省大量的空间。在Python中,这种一边循环一边计算的机制,称为生成器:generator。 # 要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator: L = [x ** 2 for x in range(10)] print(L) g = (x ** 2 for x in range(10)) # print(g) # 创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator。 # 我们可以直接打印出list的每一个元素,但我们怎么打印出generator的每一个元素呢? # 如果要一个一个打印出来,可以通过next()函数获得generator的下一个返回值: # print(next(g), next(g), next(g), next(g), next(g), next(g), next(g), next(g), next(g), next(g)) # print(next(g), next(g), next(g), next(g), next(g), next(g), next(g), next(g), next(g), next(g)) # 我们讲过,generator保存的是算法,每次调用next(g),就计算出g的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。 # 当然,上面这种不断调用next(g)实在是太变态了,正确的方法是使用for循环,因为generator也是可迭代对象: for n in g: print(n) # 所以,我们创建了一个generator后,基本上永远不会调用next(),而是通过for循环来迭代它,并且不需要关心StopIteration的错误。 # generator非常强大。如果推算的算法比较复杂,用类似列表生成式的for循环无法实现的时候,还可以用函数来实现。 # 比如,著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到: # 1, 1, 2, 3, 5, 8, 13, 21, 34, ... # 斐波拉契数列用列表生成式写不出来,但是,用函数把它打印出来却很容易: def fib(max): n, a, b = 0, 0 , 1 while n < max: print(b) a, b = b, a + b n = n + 1 return 'done' print(fib(6)) print(fib(9)) # 仔细观察,可以看出,fib函数实际上是定义了斐波拉契数列的推算规则,可以从第一个元素开始,推算出后续任意的元素,这种逻辑其实非常类似generator。 # 也就是说,上面的函数和generator仅一步之遥。要把fib函数变成generator,只需要把print(b)改为yield b就可以了: def fib(max): n, a , b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'DONE' # 这里,最难理解的就是generator和函数的执行流程不一样。函数是顺序执行,遇到return语句或者最后一行函数语句就返回。而变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。 # 举个简单的例子,定义一个generator,依次返回数字1,3,5: def odd(): print('step1') yield 1 print('step2') yield 2 print('step3') yield 3 o = odd() next(o) next(o) next(o) # next(o) # 可以看到,odd不是普通函数,而是generator,在执行过程中,遇到yield就中断,下次又继续执行。执行3次yield后,已经没有yield可以执行了,所以,第4次调用next(o)就报错。 # 回到fib的例子,我们在循环过程中不断调用yield,就会不断中断。当然要给循环设置一个条件来退出循环,不然就会产生一个无限数列出来。 # 同样的,把函数改成generator后,我们基本上从来不会用next()来获取下一个返回值,而是直接使用for循环来迭代: for n in fib(9): print(n) # 但是用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中: g = fib(9) while True: try: x = next(g) print('g', x) except StopIteration as e: print('Generator return value:', e.value) break # 练习 # 杨辉三角定义如下: # 1 # / \ # 1 1 # / \ / \ # 1 2 1 # / \ / \ / \ # 1 3 3 1 # / \ / \ / \ / \ # 1 4 6 4 1 # / \ / \ / \ / \ / \ # 1 5 10 10 5 1 # 把每一行看做一个list,试写一个generator,不断输出下一行的list: # 解题思路 ## 杨辉三角形 # 假设行号以1开始,每行的元素数即为行号; # 每行的头尾都是1; # 每行中间的数都是正上方的数及正上方左边的数的和。 ## 题干 # 使用 results ,在 for 循环中,将 triangles() 生成器的元素逐行读出; # n 作为计数器,当 n 累加到10后,停止读出生成器的元素; # 使用 for 循环将 results (list)打印出来; # 与正确答案做比对 def triangles(): m = [1] while True: yield m m = [1] + [m[x] + m[x+1] for x in range(len(m)-1)] + [1] # 期待输出: # [1] # [1, 1] # [1, 2, 1] # [1, 3, 3, 1] # [1, 4, 6, 4, 1] # [1, 5, 10, 10, 5, 1] # [1, 6, 15, 20, 15, 6, 1] # [1, 7, 21, 35, 35, 21, 7, 1] # [1, 8, 28, 56, 70, 56, 28, 8, 1] # [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] n = 0 results = [] for t in triangles(): results.append(t) n = n + 1 if n == 10: break for t in results: print(t) if results == [ [1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], [1, 5, 10, 10, 5, 1], [1, 6, 15, 20, 15, 6, 1], [1, 7, 21, 35, 35, 21, 7, 1], [1, 8, 28, 56, 70, 56, 28, 8, 1], [1, 9, 36, 84, 126, 126, 84, 36, 9, 1] ]: print('测试通过!') else: print('测试失败!') # ---------------------------------------- end ---------------------------------------- print('-----------End-----------')
# -*- coding: utf-8 -*- # This file is generated from NI-FAKE API metadata version 1.2.0d9 functions = { 'Abort': { 'codegen_method': 'public', 'documentation': { 'description': 'Aborts a previously initiated thingie.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' } ], 'returns': 'ViStatus' }, 'AcceptListOfDurationsInSeconds': { 'codegen_method': 'public', 'documentation': { 'description': 'Accepts list of floats or hightime.timedelta instances representing time delays.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Count of input values.' }, 'name': 'count', 'type': 'ViInt32' }, { 'direction': 'in', 'documentation': { 'description': 'A collection of time delay values.' }, 'name': 'delays', 'python_api_converter_name': 'convert_timedeltas_to_seconds_real64', 'size': { 'mechanism': 'len', 'value': 'count' }, 'type': 'ViReal64[]', 'type_in_documentation': 'hightime.timedelta, datetime.timedelta, or float in seconds' } ], 'returns': 'ViStatus' }, 'AcceptViSessionArray': { 'codegen_method': 'public', 'parameters': [ { 'direction': 'in', 'name': 'sessionCount', 'type': 'ViUInt32' }, { 'direction': 'in', 'name': 'sessionArray', 'type': 'ViSession[]', 'size': { 'mechanism': 'passed-in', 'value': 'sessionCount' } } ], 'returns': 'ViStatus' }, 'AcceptViUInt32Array': { 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'arrayLen', 'type': 'ViInt32' }, { 'direction': 'in', 'name': 'uInt32Array', 'type': 'ViUInt32[]', 'size': { 'mechanism': 'len', 'value': 'arrayLen' } } ], 'returns': 'ViStatus' }, 'BoolArrayOutputFunction': { 'codegen_method': 'public', 'documentation': { 'description': 'This function returns an array of booleans.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session. You obtain the **vi** parameter from niFake_InitWithOptions.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Number of elements in the array.' }, 'name': 'numberOfElements', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Contains an array of booleans' }, 'name': 'anArray', 'size': { 'mechanism': 'passed-in', 'value': 'numberOfElements' }, 'type': 'ViBoolean[]' } ], 'returns': 'ViStatus' }, 'BoolArrayInputFunction': { 'codegen_method': 'public', 'documentation': { 'description': 'This function accepts an array of booleans.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session. You obtain the **vi** parameter from niFake_InitWithOptions.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Number of elements in the array.' }, 'name': 'numberOfElements', 'type': 'ViInt32' }, { 'direction': 'in', 'documentation': { 'description': 'Input boolean array' }, 'name': 'anArray', 'size': { 'mechanism': 'passed-in', 'value': 'numberOfElements' }, 'type': 'ViBoolean[]' } ], 'returns': 'ViStatus' }, 'CommandWithReservedParam': { 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'include_in_proto': False, 'name': 'reserved', 'pointer': True, 'hardcoded_value': "nullptr", 'type': 'ViBoolean' } ], 'returns': 'ViStatus' }, 'CreateConfigurationList': { 'parameters': [ { 'direction': 'in', 'name': 'numberOfListAttributes', 'type': 'ViInt32' }, { 'direction': 'in', 'name': 'listAttributeIds', 'size': { 'mechanism': 'len', 'value': 'numberOfListAttributes' }, 'type': 'ViAttr[]' } ], 'returns': 'ViStatus' }, 'DoubleAllTheNums': { 'documentation': { 'description': 'Test for buffer with converter' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session. You obtain the **vi** parameter from niFake_InitWithOptions.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Number of elements in the number array' }, 'name': 'numberCount', 'type': 'ViInt32' }, { 'direction': 'in', 'documentation': { 'description': 'numbers is an array of numbers we want to double.' }, 'name': 'numbers', 'python_api_converter_name': 'convert_double_each_element', 'size': { 'mechanism': 'len', 'value': 'numberCount' }, 'type': 'ViReal64[]' } ], 'returns': 'ViStatus' }, 'EnumArrayOutputFunction': { 'codegen_method': 'public', 'documentation': { 'description': 'This function returns an array of enums, stored as 16 bit integers under the hood.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session. You obtain the **vi** parameter from niFake_InitWithOptions.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Number of elements in the array.' }, 'name': 'numberOfElements', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Contains an array of enums, stored as 16 bit integers under the hood ' }, 'enum': 'Turtle', 'name': 'anArray', 'size': { 'mechanism': 'passed-in', 'value': 'numberOfElements' }, 'type': 'ViInt16[]' } ], 'returns': 'ViStatus' }, 'EnumInputFunctionWithDefaults': { 'codegen_method': 'public', 'documentation': { 'description': 'This function takes one parameter other than the session, which happens to be an enum and has a default value.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session. You obtain the **vi** parameter from niFake_InitWithOptions.' }, 'name': 'vi', 'type': 'ViSession' }, { 'default_value': 'Turtle.LEONARDO', 'direction': 'in', 'documentation': { 'description': 'Indicates a ninja turtle', 'table_body': [ [ '0', 'Leonardo' ], [ '1', 'Donatello' ], [ '2', 'Raphael' ], [ '3', 'Mich elangelo' ] ] }, 'enum': 'Turtle', 'name': 'aTurtle', 'type': 'ViInt16' } ], 'returns': 'ViStatus' }, 'ExportAttributeConfigurationBuffer': { 'documentation': { 'description': 'Export configuration buffer.' }, 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'sizeInBytes', 'type': 'ViInt32' }, { 'direction': 'out', 'name': 'configuration', 'python_api_converter_name': 'convert_to_bytes', 'size': { 'mechanism': 'ivi-dance', 'value': 'sizeInBytes' }, 'type': 'ViInt8[]', 'type_in_documentation': 'bytes', 'use_array': True } ], 'returns': 'ViStatus' }, 'FetchWaveform': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns waveform data.' }, 'method_templates': [ { 'documentation_filename': 'default_method', 'method_python_name_suffix': '', 'session_filename': 'default_method' }, { 'documentation_filename': 'numpy_method', 'method_python_name_suffix': '_into', 'session_filename': 'numpy_read_method' } ], 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Number of samples to return' }, 'name': 'numberOfSamples', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Samples fetched from the device. Array should be numberOfSamples big.' }, 'name': 'waveformData', 'numpy': True, 'size': { 'mechanism': 'passed-in', 'value': 'numberOfSamples' }, 'type': 'ViReal64[]', 'use_array': True }, { 'direction': 'out', 'documentation': { 'description': 'Number of samples actually fetched.' }, 'name': 'actualNumberOfSamples', 'type': 'ViInt32', 'use_in_python_api': False } ], 'returns': 'ViStatus' }, 'GetABoolean': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns a boolean.', 'note': 'This function rules!' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Contains a boolean.' }, 'name': 'aBoolean', 'type': 'ViBoolean' } ], 'returns': 'ViStatus' }, 'GetANumber': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns a number.', 'note': 'This function rules!' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Contains a number.' }, 'name': 'aNumber', 'type': 'ViInt16' } ], 'returns': 'ViStatus' }, 'GetAStringOfFixedMaximumSize': { 'codegen_method': 'public', 'documentation': { 'description': 'Illustrates returning a string of fixed size.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'String comes back here. Buffer must be 256 big.' }, 'name': 'aString', 'size': { 'mechanism': 'fixed', 'value': 256 }, 'type': 'ViChar[]' } ], 'returns': 'ViStatus' }, 'GetAStringUsingCustomCode': { 'codegen_method': 'no', 'documentation': { 'description': 'Returns a number and a string.', 'note': 'This function rules!' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Contains a number.' }, 'name': 'aNumber', 'type': 'ViInt16' }, { 'direction': 'out', 'documentation': { 'description': 'Contains a string of length aNumber.' }, 'name': 'aString', 'size': { 'mechanism': 'custom-code', 'value': 'a_number' }, 'type': 'ViChar[]' } ], 'returns': 'ViStatus' }, 'GetBitfieldAsEnumArray': { 'parameters': [ { 'bitfield_as_enum_array': 'Bitfield', 'direction': 'out', 'name': 'flags', 'type': 'ViInt64', } ], 'returns': 'ViStatus' }, 'GetAnIviDanceString': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns a string using the IVI dance.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Number of bytes in aString You can IVI-dance with this.' }, 'name': 'bufferSize', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Returns the string.' }, 'name': 'aString', 'size': { 'mechanism': 'ivi-dance', 'value': 'bufferSize' }, 'type': 'ViChar[]' } ], 'returns': 'ViStatus' }, 'GetAnIviDanceWithATwistArray': { 'parameters': [ { 'name': 'vi', 'direction': 'in', 'type': 'ViSession' }, { 'name': 'aString', 'direction': 'in', 'type': 'ViConstString' }, { 'name': 'bufferSize', 'direction': 'in', 'type': 'ViInt32' }, { 'name': 'arrayOut', 'direction': 'out', 'type': 'ViInt32[]', 'size': { 'mechanism': 'ivi-dance-with-a-twist', 'value': 'bufferSize', 'value_twist': 'actualSize' } }, { 'name': 'actualSize', 'direction': 'out', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'GetAnIviDanceWithATwistArrayOfCustomType': { 'parameters': [ { 'name': 'vi', 'direction': 'in', 'type': 'ViSession' }, { 'name': 'bufferSize', 'direction': 'in', 'type': 'ViInt32' }, { 'name': 'arrayOut', 'direction': 'out', 'type': 'struct CustomStruct[]', 'grpc_type': 'repeated FakeCustomStruct', 'size': { 'mechanism': 'ivi-dance-with-a-twist', 'value': 'bufferSize', 'value_twist': 'actualSize' } }, { 'name': 'actualSize', 'direction': 'out', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'GetAnIviDanceWithATwistArrayWithInputArray': { 'parameters': [ { 'direction': 'in', 'name': 'dataIn', 'size': { 'mechanism': 'len', 'value': 'arraySizeIn' }, 'type': 'ViInt32[]' }, { 'direction': 'in', 'name': 'arraySizeIn', 'type': 'ViInt32' }, { 'name': 'bufferSize', 'direction': 'in', 'type': 'ViInt32' }, { 'name': 'arrayOut', 'direction': 'out', 'type': 'ViInt32[]', 'size': { 'mechanism': 'ivi-dance-with-a-twist', 'value': 'bufferSize', 'value_twist': 'actualSize' } }, { 'name': 'actualSize', 'direction': 'out', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'GetAnIviDanceWithATwistByteArray': { 'parameters': [ { 'name': 'bufferSize', 'direction': 'in', 'type': 'ViInt32' }, { 'name': 'arrayOut', 'direction': 'out', 'size': { 'mechanism': 'ivi-dance-with-a-twist', 'value': 'bufferSize', 'value_twist': 'actualSize' }, 'type': 'ViInt8[]' }, { 'name': 'actualSize', 'direction': 'out', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'GetAnIviDanceWithATwistString': { 'parameters': [ { 'name': 'bufferSize', 'direction': 'in', 'type': 'ViInt32' }, { 'name': 'arrayOut', 'direction': 'out', 'size': { 'mechanism': 'ivi-dance-with-a-twist', 'value': 'bufferSize', 'value_twist': 'actualSize' }, 'type': 'ViChar[]' }, { 'name': 'actualSize', 'direction': 'out', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'GetAnIviDanceWithATwistStringStrlenBug': { 'parameters': [ { 'name': 'bufferSize', 'direction': 'in', 'type': 'ViInt32' }, { 'name': 'stringOut', 'direction': 'out', 'size': { 'mechanism': 'ivi-dance-with-a-twist', 'value': 'bufferSize', 'value_twist': 'actualSize', 'tags': ['strlen-bug'] }, 'type': 'ViChar[]' }, { 'name': 'actualSize', 'direction': 'out', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'GetArrayForCustomCodeCustomType': { 'codegen_method': 'no', 'documentation': { 'description': 'This function returns an array for use in custom-code size mechanism.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'include_in_proto': False, 'direction': 'in', 'documentation': { 'description': 'Number of elements in the array.' }, 'name': 'numberOfElements', 'size': { 'mechanism': 'custom-code', 'value': '', }, 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Array of custom type using custom-code size mechanism' }, 'name': 'arrayOut', 'size': { 'mechanism': 'custom-code', 'value': '' }, 'type': 'struct CustomStruct[]', 'grpc_type': 'repeated FakeCustomStruct' } ], 'returns': 'ViStatus' }, 'GetArrayForCustomCodeDouble': { 'codegen_method': 'no', 'documentation': { 'description': 'This function returns an array for use in custom-code size mechanism.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'include_in_proto': False, 'direction': 'in', 'documentation': { 'description': 'Number of elements in the array.' }, 'name': 'numberOfElements', 'size': { 'mechanism': 'custom-code', 'value': '', }, 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Array of double using custom-code size mechanism' }, 'name': 'arrayOut', 'size': { 'mechanism': 'custom-code', 'value': 'number_of_elements' }, 'type': 'ViReal64[]' } ], 'returns': 'ViStatus' }, 'GetArraySizeForCustomCode': { 'codegen_method': 'public', 'documentation': { 'description': 'This function returns the size of the array for use in custom-code size mechanism.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Size of array' }, 'name': 'sizeOut', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'GetArrayUsingIviDance': { 'codegen_method': 'public', 'documentation': { 'description': 'This function returns an array of float whose size is determined with the IVI dance.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Specifies the size of the buffer for copyint arrayOut onto.' }, 'name': 'arraySize', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'The array returned by this function' }, 'name': 'arrayOut', 'size': { 'mechanism': 'ivi-dance', 'value': 'arraySize' }, 'type': 'ViReal64[]' } ], 'returns': 'ViStatus' }, 'GetArrayViUInt8WithEnum': { 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'arrayLen', 'type': 'ViInt32' }, { 'direction': 'out', 'name': 'uInt8EnumArray', 'enum': 'Color', 'type': 'ViUInt8[]', 'size': { 'mechanism': 'passed-in', 'value': 'arrayLen' } } ], 'returns': 'ViStatus' }, 'GetAttributeViBoolean': { 'codegen_method': 'public', 'documentation': { 'description': 'Queries the value of a ViBoolean attribute.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the ID of an attribute.' }, 'name': 'attributeId', 'type': 'ViAttr' }, { 'direction': 'out', 'documentation': { 'description': 'Returns the value of the attribute.' }, 'name': 'attributeValue', 'type': 'ViBoolean' } ], 'returns': 'ViStatus' }, 'GetAttributeViInt32': { 'codegen_method': 'public', 'documentation': { 'description': 'Queries the value of a ViInt32 attribute.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the ID of an attribute.' }, 'name': 'attributeId', 'type': 'ViAttr' }, { 'direction': 'out', 'documentation': { 'description': 'Returns the value of the attribute.' }, 'name': 'attributeValue', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'GetAttributeViInt64': { 'codegen_method': 'public', 'documentation': { 'description': 'Queries the value of a ViInt64 attribute.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the ID of an attribute.' }, 'name': 'attributeId', 'type': 'ViAttr' }, { 'direction': 'out', 'documentation': { 'description': 'Returns the value of the attribute.' }, 'name': 'attributeValue', 'type': 'ViInt64' } ], 'returns': 'ViStatus' }, 'GetAttributeViReal64': { 'codegen_method': 'public', 'documentation': { 'description': 'Queries the value of a ViReal attribute.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the ID of an attribute.' }, 'name': 'attributeId', 'type': 'ViAttr' }, { 'direction': 'out', 'documentation': { 'description': 'Returns the value of the attribute.' }, 'name': 'attributeValue', 'type': 'ViReal64' } ], 'returns': 'ViStatus' }, 'GetAttributeViSession': { 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'attributeId', 'type': 'ViInt32' }, { 'direction': 'out', 'name': 'sessionOut', 'type': 'ViSession' } ], 'returns': 'ViStatus' }, 'GetAttributeViString': { 'codegen_method': 'public', 'documentation': { 'description': 'Queries the value of a ViBoolean attribute.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the ID of an attribute.' }, 'name': 'attributeId', 'type': 'ViAttr' }, { 'direction': 'in', 'documentation': { 'description': 'Number of bytes in attributeValue. You can IVI-dance with this.' }, 'name': 'bufferSize', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Returns the value of the attribute.' }, 'name': 'attributeValue', 'size': { 'mechanism': 'ivi-dance', 'value': 'bufferSize' }, 'type': 'ViChar[]' } ], 'returns': 'ViStatus' }, 'GetCalDateAndTime': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns the date and time of the last calibration performed.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Specifies the type of calibration performed (external or self-calibration).' }, 'name': 'calType', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Indicates the **month** of the last calibration.' }, 'name': 'month', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Indicates the **day** of the last calibration.' }, 'name': 'day', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Indicates the **year** of the last calibration.' }, 'name': 'year', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Indicates the **hour** of the last calibration.' }, 'name': 'hour', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Indicates the **minute** of the last calibration.' }, 'name': 'minute', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'GetCalInterval': { 'documentation': { 'description': 'Returns the recommended maximum interval, in **months**, between external calibrations.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Specifies the recommended maximum interval, in **months**, between external calibrations.' }, 'name': 'months', 'python_api_converter_name': 'convert_month_to_timedelta', 'type': 'ViInt32', 'type_in_documentation': 'hightime.timedelta' } ], 'returns': 'ViStatus' }, 'GetCustomType': { 'documentation': { 'description': 'This function returns a custom type.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Set using custom type' }, 'name': 'cs', 'type': 'struct CustomStruct', 'grpc_type': 'FakeCustomStruct' } ], 'returns': 'ViStatus' }, 'GetCustomTypeArray': { 'codegen_method': 'public', 'documentation': { 'description': 'This function returns a custom type.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Number of elements in the array.' }, 'name': 'numberOfElements', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Get using custom type' }, 'name': 'cs', 'size': { 'mechanism': 'passed-in', 'value': 'numberOfElements' }, 'type': 'struct CustomStruct[]', 'grpc_type': 'repeated FakeCustomStruct' } ], 'returns': 'ViStatus' }, 'GetEnumValue': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns an enum value', 'note': 'Splinter is not supported.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'This is an amount.', 'note': 'The amount will be between -2^31 and (2^31-1)' }, 'name': 'aQuantity', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Indicates a ninja turtle', 'table_body': [ [ '0', 'Leonardo' ], [ '1', 'Donatello' ], [ '2', 'Raphael' ], [ '3', 'Mich elangelo' ] ] }, 'enum': 'Turtle', 'name': 'aTurtle', 'type': 'ViInt16' } ], 'returns': 'ViStatus' }, 'GetError': { 'codegen_method': 'private', 'documentation': { 'description': 'Returns the error information associated with the session.' }, 'is_error_handling': True, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Returns errorCode for the session. If you pass 0 for bufferSize, you can pass VI_NULL for this.' }, 'name': 'errorCode', 'type': 'ViStatus' }, { 'direction': 'in', 'documentation': { 'description': 'Number of bytes in description buffer.' }, 'name': 'bufferSize', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'At least bufferSize big, string comes out here.' }, 'name': 'description', 'size': { 'mechanism': 'ivi-dance', 'value': 'bufferSize' }, 'type': 'ViChar[]' } ], 'returns': 'ViStatus', 'use_session_lock': False }, 'GetViUInt8': { 'codegen_method': 'public', 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'name': 'aUint8Number', 'type': 'ViUInt8' } ], 'returns': 'ViStatus' }, 'GetViInt32Array': { 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'arrayLen', 'type': 'ViInt32' }, { 'direction': 'out', 'name': 'int32Array', 'type': 'ViInt32[]', 'size': { 'mechanism': 'passed-in', 'value': 'arrayLen' } } ], 'returns': 'ViStatus' }, 'GetViUInt32Array': { 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'arrayLen', 'type': 'ViInt32' }, { 'direction': 'out', 'name': 'uInt32Array', 'type': 'ViUInt32[]', 'size': { 'mechanism': 'passed-in', 'value': 'arrayLen' } } ], 'returns': 'ViStatus' }, 'ImportAttributeConfigurationBuffer': { 'documentation': { 'description': 'Import configuration buffer.' }, 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'sizeInBytes', 'type': 'ViInt32' }, { 'direction': 'in', 'name': 'configuration', 'python_api_converter_name': 'convert_to_bytes', 'size': { 'mechanism': 'len', 'value': 'sizeInBytes' }, 'type': 'ViInt8[]', 'type_in_documentation': 'bytes' } ], 'returns': 'ViStatus' }, 'InitWithOptions': { 'codegen_method': 'public', 'init_method': True, 'documentation': { 'description': 'Creates a new IVI instrument driver session.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'caution': 'This is just some string.', 'description': 'Contains the **resource_name** of the device to initialize.' }, 'name': 'resourceName', 'type': 'ViString' }, { 'default_value': False, 'direction': 'in', 'documentation': { 'description': 'NI-FAKE is probably not needed.', 'table_body': [ [ 'VI_TRUE (default)', '1', 'Perform ID Query' ], [ 'VI_FALSE', '0', 'Skip ID Query' ] ] }, 'name': 'idQuery', 'type': 'ViBoolean', 'use_in_python_api': False }, { 'default_value': False, 'direction': 'in', 'documentation': { 'description': 'Specifies whether to reset', 'table_body': [ [ 'VI_TRUE (default)', '1', 'Reset Device' ], [ 'VI_FALSE', '0', "Don't Reset" ] ] }, 'name': 'resetDevice', 'type': 'ViBoolean' }, { 'direction': 'in', 'documentation': { 'description': 'Some options' }, 'name': 'optionString', 'python_api_converter_name': 'convert_init_with_options_dictionary', 'type': 'ViConstString', 'type_in_documentation': 'dict' }, { 'direction': 'out', 'documentation': { 'description': 'Returns a ViSession handle that you use.' }, 'name': 'vi', 'type': 'ViSession' } ], 'returns': 'ViStatus', 'use_session_lock': False }, 'Initiate': { 'codegen_method': 'private', 'documentation': { 'description': 'Initiates a thingie.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' } ], 'returns': 'ViStatus' }, 'InitExtCal': { 'codegen_method': 'public', 'init_method' : True, 'custom_close' : 'CloseExtCal(id, 0)', 'parameters': [ { 'name': 'resourceName', 'direction': 'in', 'type': 'ViRsrc' }, { 'name': 'calibrationPassword', 'direction': 'in', 'type': 'ViString' }, { 'name': 'vi', 'direction': 'out', 'type': 'ViSession' } ], 'returns': 'ViStatus' }, 'InitWithVarArgs': { 'codegen_method': 'public', 'init_method': True, 'parameters': [ { 'name': 'resourceName', 'direction': 'in', 'type': 'ViRsrc' }, { 'name': 'vi', 'direction': 'out', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'stringArg', 'type': 'ViConstString', 'include_in_proto': False, 'repeating_argument': True, }, { 'direction': 'in', 'include_in_proto': False, 'enum': 'Turtle', 'name': 'turtle', 'repeating_argument': True, 'type': 'ViInt16' }, { 'direction': 'in', 'grpc_type': 'repeated StringAndTurtle', 'is_compound_type': True, 'max_length': 3, 'name': 'nameAndTurtle', 'repeated_var_args': True }, ], 'returns': 'ViStatus', }, 'LockSession': { 'codegen_method': 'no', 'documentation': { 'description': 'Lock.' }, 'method_templates': [ { 'documentation_filename': 'lock', 'method_python_name_suffix': '', 'session_filename': 'lock' } ], 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Optional' }, 'name': 'callerHasLock', 'type': 'ViBoolean' } ], 'python_name': 'lock', 'render_in_session_base': True, 'returns': 'ViStatus', 'use_session_lock': False }, 'MultipleArrayTypes': { 'codegen_method': 'public', 'documentation': { 'description': 'Receives and returns multiple types of arrays.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Size of the array that will be returned.' }, 'name': 'outputArraySize', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Array that will be returned.', 'note': 'The size must be at least outputArraySize.' }, 'name': 'outputArray', 'size': { 'mechanism': 'passed-in', 'value': 'outputArraySize' }, 'type': 'ViReal64[]' }, { 'direction': 'out', 'documentation': { 'description': 'An array of doubles with fixed size.' }, 'name': 'outputArrayOfFixedLength', 'size': { 'mechanism': 'fixed', 'value': 3 }, 'type': 'ViReal64[]' }, { 'direction': 'in', 'documentation': { 'description': 'Size of inputArrayOfFloats and inputArrayOfIntegers' }, 'name': 'inputArraySizes', 'type': 'ViInt32' }, { 'direction': 'in', 'documentation': { 'description': 'Array of floats' }, 'name': 'inputArrayOfFloats', 'size': { 'mechanism': 'len', 'value': 'inputArraySizes' }, 'type': 'ViReal64[]' }, { 'default_value': None, 'direction': 'in', 'documentation': { 'description': 'Array of integers. Optional. If passed in then size must match that of inputArrayOfFloats.' }, 'name': 'inputArrayOfIntegers', 'size': { 'mechanism': 'len', 'value': 'inputArraySizes' }, 'type': 'ViInt16[]' } ], 'returns': 'ViStatus' }, 'MultipleArraysSameSize': { 'documentation': { 'description': 'Function to test multiple arrays that use the same size' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Array 1 of same size.' }, 'name': 'values1', 'size': { 'mechanism': 'len', 'value': 'size' }, 'type': 'ViReal64[]' }, { 'direction': 'in', 'documentation': { 'description': 'Array 2 of same size.' }, 'name': 'values2', 'size': { 'mechanism': 'len', 'value': 'size' }, 'type': 'ViReal64[]' }, { 'direction': 'in', 'documentation': { 'description': 'Array 3 of same size.' }, 'name': 'values3', 'size': { 'mechanism': 'len', 'value': 'size' }, 'type': 'ViReal64[]' }, { 'direction': 'in', 'documentation': { 'description': 'Array 4 of same size.' }, 'name': 'values4', 'size': { 'mechanism': 'len', 'value': 'size' }, 'type': 'ViReal64[]' }, { 'direction': 'in', 'documentation': { 'description': 'Size for all arrays' }, 'name': 'size', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'MultipleArraysSameSizeWithOptional': { 'documentation': { 'description': 'Function to test multiple arrays that use the same size' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Array 1 of same size.' }, 'name': 'values1', 'size': { 'mechanism': 'len', 'tags': [ 'optional' ], 'value': 'size' }, 'type': 'ViReal64[]' }, { 'direction': 'in', 'documentation': { 'description': 'Array 2 of same size.' }, 'name': 'values2', 'size': { 'mechanism': 'len', 'tags': [ 'optional' ], 'value': 'size' }, 'type': 'ViReal64[]' }, { 'direction': 'in', 'documentation': { 'description': 'Array 3 of same size.' }, 'name': 'values3', 'size': { 'mechanism': 'len', 'tags': [ 'optional' ], 'value': 'size' }, 'type': 'ViReal64[]' }, { 'direction': 'in', 'documentation': { 'description': 'Array 4 of same size.' }, 'name': 'values4', 'size': { 'mechanism': 'len', 'tags': [ 'optional' ], 'value': 'size' }, 'type': 'ViReal64[]' }, { 'direction': 'in', 'documentation': { 'description': 'Size for all arrays' }, 'name': 'size', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'OneInputFunction': { 'codegen_method': 'public', 'documentation': { 'description': 'This function takes one parameter other than the session.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session. You obtain the **vi** parameter from niFake_InitWithOptions.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Contains a number' }, 'name': 'aNumber', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'ParametersAreMultipleTypes': { 'codegen_method': 'public', 'documentation': { 'description': 'Has parameters of multiple types.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Contains a boolean.' }, 'name': 'aBoolean', 'type': 'ViBoolean' }, { 'direction': 'in', 'documentation': { 'description': 'Contains a 32-bit integer.' }, 'name': 'anInt32', 'type': 'ViInt32' }, { 'direction': 'in', 'documentation': { 'description': 'Contains a 64-bit integer.' }, 'name': 'anInt64', 'type': 'ViInt64' }, { 'direction': 'in', 'documentation': { 'description': 'Indicates a ninja turtle', 'table_body': [ [ '0', 'Leonardo' ], [ '1', 'Donatello' ], [ '2', 'Raphael' ], [ '3', 'Mich elangelo' ] ] }, 'enum': 'Turtle', 'name': 'anIntEnum', 'type': 'ViInt16' }, { 'direction': 'in', 'documentation': { 'description': 'The measured value.' }, 'name': 'aFloat', 'type': 'ViReal64' }, { 'direction': 'in', 'documentation': { 'description': 'A float enum.' }, 'enum': 'FloatEnum', 'name': 'aFloatEnum', 'type': 'ViReal64' }, { 'direction': 'in', 'documentation': { 'description': 'Number of bytes allocated for aString' }, 'name': 'stringSize', 'type': 'ViInt32' }, { 'direction': 'in', 'documentation': { 'description': 'An IVI dance string.' }, 'name': 'aString', 'size': { 'mechanism': 'len', 'value': 'stringSize' }, 'type': 'ViConstString' } ], 'returns': 'ViStatus' }, 'PoorlyNamedSimpleFunction': { 'codegen_method': 'public', 'documentation': { 'description': 'This function takes no parameters other than the session.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session. You obtain the **vi** parameter from niFake_InitWithOptions.' }, 'name': 'vi', 'type': 'ViSession' } ], 'python_name': 'simple_function', 'returns': 'ViStatus' }, 'Read': { 'codegen_method': 'public', 'documentation': { 'description': 'Acquires a single measurement and returns the measured value.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Specifies the **maximum_time** allowed in seconds.' }, 'name': 'maximumTime', 'python_api_converter_name': 'convert_timedelta_to_seconds_real64', 'type': 'ViReal64', 'type_in_documentation': 'hightime.timedelta' }, { 'direction': 'out', 'documentation': { 'description': 'The measured value.' }, 'name': 'reading', 'type': 'ViReal64' } ], 'returns': 'ViStatus' }, 'ReadDataWithInOutIviTwist': { 'parameters': [ { 'direction': 'out', 'name': 'data', 'size': { 'mechanism': 'ivi-dance-with-a-twist', 'value': 'bufferSize', 'value_twist': 'bufferSize' }, 'type': 'ViInt32[]' }, { 'name': 'bufferSize', 'direction': 'out', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'ReadFromChannel': { 'codegen_method': 'public', 'documentation': { 'description': 'Acquires a single measurement and returns the measured value.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Specifies the **maximum_time** allowed in milliseconds.' }, 'name': 'maximumTime', 'python_api_converter_name': 'convert_timedelta_to_milliseconds_int32', 'type': 'ViInt32', 'type_in_documentation': 'hightime.timedelta' }, { 'direction': 'out', 'documentation': { 'description': 'The measured value.' }, 'name': 'reading', 'type': 'ViReal64' } ], 'returns': 'ViStatus' }, 'ReturnANumberAndAString': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns a number and a string.', 'note': 'This function rules!' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Contains a number.' }, 'name': 'aNumber', 'type': 'ViInt16' }, { 'direction': 'out', 'documentation': { 'description': 'Contains a string. Buffer must be 256 bytes or larger.' }, 'name': 'aString', 'size': { 'mechanism': 'fixed', 'value': 256 }, 'type': 'ViChar[]' } ], 'returns': 'ViStatus' }, 'ReturnDurationInSeconds': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns a hightime.timedelta instance.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Duration in seconds.' }, 'name': 'timedelta', 'python_api_converter_name': 'convert_seconds_real64_to_timedelta', 'type': 'ViReal64', 'type_in_documentation': 'hightime.timedelta' } ], 'returns': 'ViStatus' }, 'ReturnListOfDurationsInSeconds': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns a list of hightime.timedelta instances.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Number of elements in output.' }, 'name': 'numberOfElements', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Contains a list of hightime.timedelta instances.' }, 'name': 'timedeltas', 'python_api_converter_name': 'convert_seconds_real64_to_timedeltas', 'size': { 'mechanism': 'passed-in', 'value': 'numberOfElements' }, 'type': 'ViReal64[]', 'type_in_documentation': 'hightime.timedelta' } ], 'returns': 'ViStatus' }, 'ReturnMultipleTypes': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns multiple types.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Contains a boolean.' }, 'name': 'aBoolean', 'type': 'ViBoolean' }, { 'direction': 'out', 'documentation': { 'description': 'Contains a 32-bit integer.' }, 'name': 'anInt32', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'Contains a 64-bit integer.' }, 'name': 'anInt64', 'type': 'ViInt64' }, { 'direction': 'out', 'documentation': { 'description': 'Indicates a ninja turtle', 'table_body': [ [ '0', 'Leonardo' ], [ '1', 'Donatello' ], [ '2', 'Raphael' ], [ '3', 'Mich elangelo' ] ] }, 'enum': 'Turtle', 'name': 'anIntEnum', 'type': 'ViInt16' }, { 'direction': 'out', 'documentation': { 'description': 'The measured value.' }, 'name': 'aFloat', 'type': 'ViReal64' }, { 'direction': 'out', 'documentation': { 'description': 'A float enum.' }, 'enum': 'FloatEnum', 'name': 'aFloatEnum', 'type': 'ViReal64' }, { 'direction': 'in', 'documentation': { 'description': 'Number of measurements to acquire.' }, 'name': 'arraySize', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'An array of measurement values.', 'note': 'The size must be at least arraySize.' }, 'name': 'anArray', 'size': { 'mechanism': 'passed-in', 'value': 'arraySize' }, 'type': 'ViReal64[]' }, { 'direction': 'in', 'documentation': { 'description': 'Number of bytes allocated for aString' }, 'name': 'stringSize', 'type': 'ViInt32' }, { 'direction': 'out', 'documentation': { 'description': 'An IVI dance string.' }, 'name': 'aString', 'size': { 'mechanism': 'ivi-dance', 'value': 'stringSize' }, 'type': 'ViChar[]' } ], 'returns': 'ViStatus' }, 'SetAttributeViBoolean': { 'codegen_method': 'private', 'documentation': { 'description': 'This function sets the value of a ViBoolean attribute.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the ID of an attribute.' }, 'name': 'attributeId', 'type': 'ViAttr' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the value that you want to set the attribute to.' }, 'name': 'attributeValue', 'type': 'ViBoolean' } ], 'returns': 'ViStatus' }, 'SetAttributeViInt32': { 'codegen_method': 'private', 'documentation': { 'description': 'This function sets the value of a ViInt32 attribute.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the ID of an attribute.' }, 'name': 'attributeId', 'type': 'ViAttr' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the value that you want to set the attribute to.' }, 'name': 'attributeValue', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'SetAttributeViInt64': { 'codegen_method': 'private', 'documentation': { 'description': 'This function sets the value of a ViInt64 attribute.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the ID of an attribute.' }, 'name': 'attributeId', 'type': 'ViAttr' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the value that you want to set the attribute to.' }, 'name': 'attributeValue', 'type': 'ViInt64' } ], 'returns': 'ViStatus' }, 'SetAttributeViReal64': { 'codegen_method': 'private', 'documentation': { 'description': 'This function sets the value of a ViReal64 attribute.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the ID of an attribute.' }, 'name': 'attributeId', 'type': 'ViAttr' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the value that you want to set the attribute to.' }, 'name': 'attributeValue', 'type': 'ViReal64' } ], 'returns': 'ViStatus' }, 'SetAttributeViString': { 'codegen_method': 'private', 'documentation': { 'description': 'This function sets the value of a ViString attribute.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'This is the channel(s) that this function will apply to.' }, 'name': 'channelName', 'type': 'ViConstString' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the ID of an attribute.' }, 'name': 'attributeId', 'type': 'ViAttr' }, { 'direction': 'in', 'documentation': { 'description': 'Pass the value that you want to set the attribute to.' }, 'name': 'attributeValue', 'type': 'ViConstString' } ], 'returns': 'ViStatus' }, 'SetCustomType': { 'documentation': { 'description': 'This function takes a custom type.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Set using custom type' }, 'name': 'cs', 'type': 'struct CustomStruct', 'grpc_type': 'FakeCustomStruct' } ], 'returns': 'ViStatus' }, 'SetCustomTypeArray': { 'documentation': { 'description': 'This function takes an array of custom types.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Number of elements in the array.' }, 'name': 'numberOfElements', 'type': 'ViInt32' }, { 'direction': 'in', 'documentation': { 'description': 'Set using custom type' }, 'name': 'cs', 'size': { 'mechanism': 'len', 'value': 'numberOfElements' }, 'type': 'struct CustomStruct[]', 'grpc_type': 'repeated FakeCustomStruct' } ], 'returns': 'ViStatus' }, 'StringValuedEnumInputFunctionWithDefaults': { 'codegen_method': 'public', 'documentation': { 'description': 'This function takes one parameter other than the session, which happens to be a string-valued enum and has a default value.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session. You obtain the **vi**' }, 'name': 'vi', 'type': 'ViSession' }, { 'default_value': 'MobileOSNames.ANDROID', 'direction': 'in', 'documentation': { 'description': 'Indicates a Mobile OS', 'table_body': [ [ 'ANDROID', 'Android' ], [ 'IOS', 'iOS' ], [ 'NONE', 'None' ] ] }, 'enum': 'MobileOSNames', 'name': 'aMobileOSName', 'type': 'ViConstString' } ], 'returns': 'ViStatus' }, 'TwoInputFunction': { 'codegen_method': 'public', 'documentation': { 'description': 'This function takes two parameters other than the session.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session. You obtain the **vi** parameter from niFake_InitWithOptions.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'Contains a number' }, 'name': 'aNumber', 'type': 'ViReal64' }, { 'direction': 'in', 'documentation': { 'description': 'Contains a string' }, 'name': 'aString', 'type': 'ViString' } ], 'returns': 'ViStatus' }, 'UnlockSession': { 'codegen_method': 'no', 'documentation': { 'description': 'Unlock' }, 'method_templates': [ { 'documentation_filename': 'unlock', 'method_python_name_suffix': '', 'session_filename': 'unlock' } ], 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Optional' }, 'name': 'callerHasLock', 'type': 'ViBoolean' } ], 'python_name': 'unlock', 'render_in_session_base': True, 'returns': 'ViStatus', 'use_session_lock': False }, 'Use64BitNumber': { 'codegen_method': 'public', 'documentation': { 'description': 'Returns a number and a string.', 'note': 'This function rules!' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'A big number on its way in.' }, 'name': 'input', 'type': 'ViInt64' }, { 'direction': 'out', 'documentation': { 'description': 'A big number on its way out.' }, 'name': 'output', 'type': 'ViInt64' } ], 'returns': 'ViStatus' }, 'WriteWaveform': { 'codegen_method': 'public', 'documentation': { 'description': 'Writes waveform to the driver' }, 'method_templates': [ { 'documentation_filename': 'default_method', 'method_python_name_suffix': '', 'session_filename': 'default_method' }, { 'documentation_filename': 'numpy_method', 'method_python_name_suffix': '_numpy', 'session_filename': 'numpy_write_method' } ], 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'How many samples the waveform contains.' }, 'name': 'numberOfSamples', 'type': 'ViInt32' }, { 'direction': 'in', 'documentation': { 'description': 'Waveform data.' }, 'name': 'waveform', 'numpy': True, 'size': { 'mechanism': 'len', 'value': 'numberOfSamples' }, 'type': 'ViReal64[]', 'use_array': True } ], 'returns': 'ViStatus' }, 'close': { 'codegen_method': 'public', 'documentation': { 'description': 'Closes the specified session and deallocates resources that it reserved.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' } ], 'python_name': '_close', 'returns': 'ViStatus', 'use_session_lock': False }, 'CloseExtCal': { 'codegen_method': 'public', 'custom_close_method': True, 'parameters': [ { 'name': 'vi', 'direction': 'in', 'type': 'ViSession' }, { 'name': 'action', 'direction': 'in', 'type': 'ViInt32' } ], 'returns': 'ViStatus' }, 'error_message': { 'codegen_method': 'private', 'documentation': { 'description': 'Takes the errorCode returned by a functiona and returns it as a user-readable string.' }, 'is_error_handling': True, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'documentation': { 'description': 'The errorCode returned from the instrument.' }, 'name': 'errorCode', 'type': 'ViStatus' }, { 'direction': 'out', 'documentation': { 'description': 'The error information formatted into a string.' }, 'name': 'errorMessage', 'size': { 'mechanism': 'fixed', 'value': 256 }, 'type': 'ViChar[]' } ], 'returns': 'ViStatus', 'use_session_lock': False }, 'self_test': { 'codegen_method': 'private', 'documentation': { 'description': 'Performs a self-test.' }, 'parameters': [ { 'direction': 'in', 'documentation': { 'description': 'Identifies a particular instrument session. You obtain the **vi** parameter from niFake_InitWithOptions.' }, 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'out', 'documentation': { 'description': 'Contains the value returned from the instrument self-test. Zero indicates success.' }, 'name': 'selfTestResult', 'type': 'ViInt16' }, { 'direction': 'out', 'documentation': { 'description': 'This parameter contains the string returned from the instrument self-test. The array must contain at least 256 elements.' }, 'name': 'selfTestMessage', 'size': { 'mechanism': 'fixed', 'value': 256 }, 'type': 'ViChar[]' } ], 'returns': 'ViStatus' }, 'ViUInt8ArrayInputFunction': { 'codegen_method': 'public', 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'numberOfElements', 'type': 'ViInt32' }, { 'direction': 'in', 'name': 'anArray', 'size': { 'mechanism': 'passed-in', 'value': 'numberOfElements' }, 'type': 'ViUInt8[]' } ], 'returns': 'ViStatus' }, 'ViUInt8ArrayOutputFunction': { 'codegen_method': 'public', 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'numberOfElements', 'type': 'ViInt32' }, { 'direction': 'out', 'name': 'anArray', 'size': { 'mechanism': 'passed-in', 'value': 'numberOfElements' }, 'type': 'ViUInt8[]' } ], 'returns': 'ViStatus' }, 'ViInt16ArrayInputFunction': { 'codegen_method': 'public', 'parameters': [ { 'direction': 'in', 'name': 'vi', 'type': 'ViSession' }, { 'direction': 'in', 'name': 'numberOfElements', 'type': 'ViInt32' }, { 'direction': 'in', 'name': 'anArray', 'size': { 'mechanism': 'len', 'value': 'numberOfElements' }, 'type': 'ViInt16[]' } ], 'returns': 'ViStatus' } }
word = "Python" assert "Python" == word[:2] + word[2:] assert "Python" == word[:4] + word[4:] assert "Py" == word[:2] assert "on" == word[4:] assert "on" == word[-2:] assert "Py" == word[:-4] # assert "Py" == word[::2] assert "Pto" == word[::2] assert "yhn" == word[1::2] assert "Pt" == word[:4:2] assert "yh" == word[1:4:2]
a=input() a=a.lower() if(a==a[::-1]): print("String is a PALINDROME") else: print("String NOT a PALINDROME")
class BaseFilter: """The base class to define unified interface.""" def hard_judge(self, infer_result=None): """predict function, and it must be implemented by different methods class. :param infer_result: prediction result :return: `True` means hard sample, `False` means not a hard sample. """ raise NotImplementedError class ThresholdFilter(BaseFilter): def __init__(self, threshold=0.5): self.threshold = threshold def hard_judge(self, infer_result=None): """ :param infer_result: [N, 6], (x0, y0, x1, y1, score, class) :return: `True` means hard sample, `False` means not a hard sample. """ if not infer_result: return True image_score = 0 for bbox in infer_result: image_score += bbox[4] average_score = image_score / (len(infer_result) or 1) return average_score < self.threshold
# GIS4WRF (https://doi.org/10.5281/zenodo.1288569) # Copyright (c) 2018 D. Meyer and M. Riechert. Licensed under MIT. geo_datasets = { "topo_10m": ("USGS GTOPO DEM", 0.16666667), "topo_5m": ("USGS GTOPO DEM", 0.08333333), "topo_2m": ("USGS GTOPO DEM", 0.03333333), "topo_30s": ("USGS GTOPO DEM", 0.00833333), "topo_gmted2010_30s": ("USGS GMTED2010 DEM", 0.03333333), "lake_depth": ("Lake Depth", 0.03333333), "landuse_10m": ("24-category USGS land use", 0.16666667), "landuse_5m": ("24-category USGS land use", 0.08333333), "landuse_2m": ("24-category USGS land use", 0.03333333), "landuse_30s": ("24-category USGS land use", 0.00833333), "landuse_30s_with_lakes": ("25-category USGS landuse", 0.00833333), "modis_landuse_20class_30s": ("Noah-modified 20-category IGBP-MODIS landuse", 0.00833333), "modis_landuse_20class_30s_with_lakes": ("New Noah-modified 21-category IGBP-MODIS landuse", 0.00833333), "modis_landuse_20class_15s": ("Noah-modified 20-category IGBP-MODIS landuse", 0.004166667), "modis_landuse_21class_30s": ("Noah-modified 21-category IGBP-MODIS landuse", 0.00833333), "nlcd2006_ll_30s": ("National Land Cover Database 2006", 0.00833333), "nlcd2006_ll_9s": ("National Land Cover Database 2006", 0.0025), "nlcd2011_imp_ll_9s": ("National Land Cover Database 2011 -- imperviousness percent", 0.0025), "nlcd2011_can_ll_9s": ("National Land Cover Database 2011 -- canopy percent", 0.0025), "nlcd2011_ll_9s": ("National Land Cover Database 2011", 0.0025), "ssib_landuse_10m": ("12-category Simplified Simple Biosphere Model (SSiB) land use", 0.1666667), "ssib_landuse_5m": ("12-category Simplified Simple Biosphere Model (SSiB) land use", 0.08333333), "NUDAPT44_1km": ("National Urban Database (NUDAPT) for 44 US cities", 0.0025), "crop": ("Monthly green fraction", 'various'), "greenfrac": ("Monthly green fraction", 0.144), "greenfrac_fpar_modis": ("MODIS Monthly Leaf Area Index/FPAR", 0.00833333), "sandfrac_5m": ("Sand fraction", 0.08333333), "soiltemp_1deg": ("Soil temperature", 1.0), "lai_modis_10m": ("MODIS Leaf Area Index", 0.16666667), "lai_modis_30s": ("MODIS Leaf Area Index", 0.00833333), "bnu_soiltype_bot": ("16-category bottom-layer soil type", 0.00833333), "bnu_soiltype_top": ("16-category top-layer soil type", 0.00833333), "clayfrac_5m": ("Clay Fraction", 0.08333333), "soiltype_bot_10m": ("Bottom-layer soil type", 0.16666667), "soiltype_bot_5m": ("Bottom-layer soil type", 0.08333333), "soiltype_bot_2m": ("Bottom-layer soil type", 0.03333333), "soiltype_bot_30s": ("Bottom-layer soil type", 0.00833333), "soiltype_top_10m": ("Top-layer soil type", 0.16666667), "soiltype_top_5m": ("Top-layer soil type", 0.08333333), "soiltype_top_2m": ("Top-layer soil type", 0.03333333), "soiltype_top_30s": ("Top-layer soil type", 0.00833333), "albedo_ncep": ("NCEP Monthly surface albedo", 0.144), "maxsnowalb": ("Maximum snow albedo", 1.0), "groundwater": ("Groundwater data", 0.00833333), "islope": ("14-category slope index", 1.0), "orogwd_2deg": ("Subgrid orography information for gravity wave drag option", 2.0), "orogwd_1deg": ("Subgrid orography information for gravity wave drag option", 1.0), "orogwd_30m": ("Subgrid orography information for gravity wave drag option", 0.5), "orogwd_20m": ("Subgrid orography information for gravity wave drag option", 0.3333333), "orogwd_10m": ("Subgrid orography information for gravity wave drag option", 0.16666667), "varsso_10m": ("Variance of subgrid-scale orography", 0.16666667), "varsso_5m": ("Variance of subgrid-scale orography", 0.08333333), "varsso_2m": ("Variance of subgrid-scale orography", 0.03333333), "varsso": ("Variance of subgrid-scale orography", 0.00833333), "albedo_modis": ("Monthly MODIS surface albedo", 0.05), "greenfrac_fpar_modis_5m": ("MODIS FPAR, subsampled by NCAR/MMM 2018-05-23 from 30-arc-second", 0.00833333), "maxsnowalb_modis": ("MODIS maximum snow albedo", 0.05), "modis_landuse_20class_5m_with_lakes": ("Noah-modified 21-category IGBP-MODIS landuse, subsampled by NCAR/MMM 2018-05-23 from 30-arc-second", 0.00833333), "topo_gmted2010_5m": ("GMTED2010 5-arc-minute topography height, subsampled by NCAR/MMM 2018-05-23 from 30-arc-second", 0.0833333), "erod": ("EROD", 0.25), "soilgrids": ("soilgrids", 0.00833333), "urbfrac_nlcd2011": ("Urban fraction derived from 30 m NLCD 2011 (22 = 50%, 23 = 90%, 24 = 95%)", 30.0), # FIXME: this is in Albers proj with unit metres # TODO: add `updated_Iceland_LU.tar.gz`` } # Lowest resolution of each mandatory field (WRF 4.0). # See http://www2.mmm.ucar.edu/wrf/users/download/get_sources_wps_geog.html. geo_datasets_mandatory_lores = [ "albedo_modis", "greenfrac_fpar_modis", "greenfrac_fpar_modis_5m", "lai_modis_10m", "maxsnowalb_modis", "modis_landuse_20class_5m_with_lakes", "orogwd_1deg", "soiltemp_1deg", "soiltype_bot_5m", "soiltype_top_5m", "topo_gmted2010_5m" ] # Highest resolution of each mandatory field (WRF 4.0). # See http://www2.mmm.ucar.edu/wrf/users/download/get_sources_wps_geog.html. geo_datasets_mandatory_hires = [ "albedo_modis", "greenfrac_fpar_modis", "lai_modis_10m", "lai_modis_30s", "maxsnowalb_modis", "modis_landuse_20class_30s_with_lakes", "orogwd_2deg", "orogwd_1deg", "orogwd_30m", "orogwd_20m", "orogwd_10m", "soiltemp_1deg", "soiltype_bot_30s", "soiltype_top_30s", "topo_gmted2010_30s", "varsso", "varsso_10m", "varsso_5m", "varsso_2m" ] met_datasets = { "ds083.0" : "NCEP FNL Operational Model Global Tropospheric Analyses, April 1997 through June 2007", "ds083.2" : "NCEP FNL Operational Model Global Tropospheric Analyses, continuing from July 1999", "ds083.3" : "NCEP GDAS/FNL 0.25 Degree Global Tropospheric Analyses and Forecast Grids", "ds084.1" : "NCEP GFS 0.25 Degree Global Forecast Grids Historical Archive" } met_datasets_vtables = { "ds083.0" : "Vtable.GFS", "ds083.2" : "Vtable.GFS", "ds083.3" : "Vtable.GFS", "ds084.1" : "Vtable.GFS" }
class Solution: def minRemoveToMakeValid(self, s: str) -> str: # step 1: 1st pass, traverse the string from left to right lcounter = 0 rcounter = 0 marker = 0 toremove1 = [] for i,char in enumerate(s): if char == '(': lcounter += 1 elif char == ')': rcounter += 1 if rcounter > lcounter: toremove1.append(i) lcounter = 0 rcounter = 0 marker = i + 1 # print(lcounter, rcounter, toremove1) # step 2: toremove2 = [] if lcounter > rcounter: # 2nd pass, traverse the string from right to left lcounter = 0 rcounter = 0 for j in range(len(s)-1, marker-1, -1): if s[j] == '(': lcounter += 1 elif s[j] == ')': rcounter += 1 if rcounter < lcounter: toremove2.append(j) lcounter = 0 rcounter = 0 # print(lcounter, rcounter, toremove1, toremove2) # step 3: remove the redundant parentheses s2 = [char for char in s] # print(s2) # print(len(s2)) # print(toremove1) # print(toremove2) if toremove2!=[]: for idx in toremove2: s2.pop(idx) if toremove1!=[]: toremove1.reverse() for idx in toremove1: s2.pop(idx) return ''.join(s2)
a = int(input()) b = int(input()) r = a * b while True: if b == 0: break print(a * (b % 10)) b //= 10 print(r)
""" This program displays 'Hello World' on the console by Bailey Nichols dated 1-29-2021 """ print('Hello World')
class ReportGenerator(object): u""" Top-level class that needs to be subclassed to provide a report generator. """ filename_template = 'report-%s-to-%s.csv' mimetype = 'text/csv' code = '' description = '<insert report description>' def __init__(self, **kwargs): if 'start_date' in kwargs and 'end_date' in kwargs: self.start_date = kwargs['start_date'] self.end_date = kwargs['end_date'] def generate(self, response): pass def filename(self): u""" Returns the filename for this report """ return self.filename_template % (self.start_date, self.end_date) def is_available_to(self, user): u""" Checks whether this report is available to this user """ return user.is_staff
# Copyright 2014 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. load("@io_bazel_rules_go//go/private:mode.bzl", "NORMAL_MODE", ) load("@io_bazel_rules_go//go/private:providers.bzl", "get_library", "get_searchpath", ) load("@io_bazel_rules_go//go/private:actions/action.bzl", "action_with_go_env", "bootstrap_action", ) def emit_compile(ctx, go_toolchain, sources = None, importpath = "", golibs = [], mode = NORMAL_MODE, out_lib = None, gc_goopts = []): """See go/toolchains.rst#compile for full documentation.""" if sources == None: fail("sources is a required parameter") if out_lib == None: fail("out_lib is a required parameter") # Add in any mode specific behaviours if mode.race: gc_goopts = gc_goopts + ("-race",) if mode.msan: gc_goopts = gc_goopts + ("-msan",) gc_goopts = [ctx.expand_make_variables("gc_goopts", f, {}) for f in gc_goopts] inputs = sources + [go_toolchain.data.package_list] go_sources = [s.path for s in sources if not s.basename.startswith("_cgo")] cgo_sources = [s.path for s in sources if s.basename.startswith("_cgo")] args = ["-package_list", go_toolchain.data.package_list.path] for src in go_sources: args += ["-src", src] for golib in golibs: inputs += [get_library(golib, mode)] args += ["-dep", golib.importpath] args += ["-I", get_searchpath(golib,mode)] args += ["-o", out_lib.path, "-trimpath", ".", "-I", "."] args += ["--"] if importpath: args += ["-p", importpath] args.extend(gc_goopts) args.extend(go_toolchain.flags.compile) if ctx.attr._go_toolchain_flags.compilation_mode == "debug": args.extend(["-N", "-l"]) args.extend(cgo_sources) action_with_go_env(ctx, go_toolchain, mode, inputs = list(inputs), outputs = [out_lib], mnemonic = "GoCompile", executable = go_toolchain.tools.compile, arguments = args, ) def bootstrap_compile(ctx, go_toolchain, sources = None, importpath = "", golibs = [], mode = NORMAL_MODE, out_lib = None, gc_goopts = []): """See go/toolchains.rst#compile for full documentation.""" if sources == None: fail("sources is a required parameter") if out_lib == None: fail("out_lib is a required parameter") if golibs: fail("compile does not accept deps in bootstrap mode") args = ["tool", "compile", "-o", out_lib.path] + list(gc_goopts) + [s.path for s in sources] bootstrap_action(ctx, go_toolchain, inputs = sources, outputs = [out_lib], mnemonic = "GoCompile", arguments = args, )
# Interface for the data source used in queries. # Currently only includes query capabilities. class Source: def __init__(self): None def isQueryable(self): return False # Check if the source will support the execution of an expression, # given that clauses have already been pushed into it. def supports(self,clauses,expr,visible_vars): return False # Database source for all relational database sources. Currently there is # no common functionality across different RDBMS sources class RDBMSTable(Source): def isQueryable(self): return True
# me - this DAT # par - the Par object that has changed # val - the current value # prev - the previous value # # Make sure the corresponding toggle is enabled in the Parameter Execute DAT. def onValueChange(par, prev): if par.name == 'Heartbeatrole': parent().Role_setup(par) else: pass return def onPulse(par): return def onExpressionChange(par, val, prev): return def onExportChange(par, val, prev): return def onEnableChange(par, val, prev): return def onModeChange(par, val, prev): return
# -*- coding:utf-8; -*- class Solution: """ 解题思路:递归 """ def invertTree(self, root): if not root: return root.left, root.right = self.invertTree(root.right), self.invertTree(root.left) return root
def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 fn1 = 0 fn2 = 1 for i in range(1, n): tmp = fn2 fn2 = fn1 + fn2 fn1 = tmp return fn2 if __name__ == '__main__': print(fibonacci(100))
# -*- coding: utf-8 -*- # Settings_Export: control which project settings are exposed to templates # See: https://github.com/jakubroztocil/django-settings-export SETTINGS_EXPORT = [ "SITE_NAME", "DEBUG", "ENV" ] # Settings can be accessed in templates via `{{ '{{' }} settings.<KEY> {{ '}}' }}`.
# Dataset information LABELS = [ 'Atelectasis', 'Cardiomegaly', 'Effusion', 'Infiltration', 'Mass', 'Nodule', 'Pneumonia', 'Pneumothorax', 'Consolidation', 'Edema', 'Emphysema', 'Fibrosis', 'Pleural_Thickening', 'Hernia' ] USE_COLUMNS = ['Image Index', 'Finding Labels', 'Patient ID'] N_CLASSES = len(LABELS) # Preprocessing # - default arguments RANDOM_SEED = 42 DATASET_IMAGE_SIZE = 256 TRAIN_VAL_TEST_RATIO = (.7, .1, .2) # - input filenames and directories IMAGE_DIR = './data/original_data/images/' META_DATA_DIR = './data/original_data/meta_data/' META_FILENAME = 'Data_Entry_2017_v2020.csv' # - output filenames and directories LABELS_DIR = './data/labels/' DATASET_DIR = './data/datasets/' TRAIN_LABELS = 'train_labels.csv' VAL_LABELS = 'val_labels.csv' TEST_LABELS = 'test_labels.csv' # Training, validation and testing # - filenames and directories SAVE_DIR = './data/saved_models/' # - default arguments BATCH_SIZE = 8 NUM_WORKERS = 1 NUM_EPOCHS = 8 LEARNING_RATE = 0.001 SCHEDULER_FACTOR = 0.1 SCHEDULER_PATIENCE = 0 DATA_AUGMENTATION = False CENTER_CROP = DATA_AUGMENTATION DEBUG = False # Testing and debugging DEBUG_SIZES = {'train': 1280, 'val': 1280, 'test':1280}
#!/bin/python3 DISK_SIZE = 272 INIT_STATE = '00111101111101000' def fill_disk(state, max_size): if len(state) > max_size: return state[:max_size] temp_state = state state += '0' for i in range(1, len(temp_state)+1): state += str(abs(int(temp_state[-i])-1)) return fill_disk(state, max_size) def acquire_check_sum(state): if len(state) % 2 != 0: return state checkdict = {'11': '1', '00': '1', '10': '0', '01': '0'} i = 0 checksum = '' while i < len(state): checksum += checkdict[state[i:i+2]] i += 2 return acquire_check_sum(checksum) def day16(): disk = fill_disk(INIT_STATE, DISK_SIZE) checksum = acquire_check_sum(disk) print('Part 1: {}'.format(checksum)) disk = fill_disk(INIT_STATE, 35651584) checksum = acquire_check_sum(disk) print('Part 2: {}'.format(checksum)) if __name__ == '__main__': day16()
## Valid Phone Number Checker def num_only(): ''' returns the user inputed phone number in the form of only ten digits, and prints the string 'Thanks!' if the number is inputted in a correct format or prints the string 'Invalid number.' if the input is not in correct form num_only: None -> Str examples: >>> num_only() Enter a phone number:(519)888-4567 Thanks! '5198884567' >>> num_only() Enter a phone number:90512345678 Invalid number. ''' s = input("Enter a phone number:") if str.isdigit(s) == True and len(s) == 10: print('Thanks!') return(s) elif str.isdigit(s[:3]) == True and s[3:4] == "-" and \ str.isdigit(s[4:7]) == True and s[7:8] == "-" and \ str.isdigit(s[8:12]) == True and len(s) == 12: print('Thanks!') return(s[:3] + s[4:7] + s[8:12]) elif s[:1] == "(": if len(s) == 12 and str.isdigit(s[1:4]) == True and \ s[4:5] == ")" and str.isdigit(s[5:12]) == True: print('Thanks!') return(s[1:4] + s[5:12]) if len(s) == 13 and str.isdigit(s[1:4]) == True and \ s[4:5] == ")" and str.isdigit(s[5:8]) == True and \ s[8:9] == "-" and str.isdigit(s[9:13]) == True: print('Thanks!') return(s[1:4] + s[5:8] + s[9:13]) else: print('Invalid number.') else: print('Invalid number.')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jul 9 14:20:17 2019 @author: Sven Serneels, Ponalytics """ __name__ = "dicomo" __author__ = "Sven Serneels" __license__ = "MIT" __version__ = "1.0.2" __date__ = "2020-12-20"
envs_dict = { # "Standard" Mujoco Envs "halfcheetah": "gym.envs.mujoco.half_cheetah:HalfCheetahEnv", "ant": "gym.envs.mujoco.ant:AntEnv", "hopper": "gym.envs.mujoco.hopper:HopperEnv", "walker": "gym.envs.mujoco.walker2d:Walker2dEnv", "humanoid": "gym.envs.mujoco.humanoid:HumanoidEnv", "swimmer": "gym.envs.mujoco.swimmer:SwimmerEnv", "inverteddoublependulum": "gym.envs.mujoco.inverted_double_pendulum:InvertedDoublePendulum2dEnv", "invertedpendulum": "gym.envs.mujoco.inverted_pendulum:InvertedPendulum", # normal envs "lunarlandercont": "gym.envs.box2d.lunar_lander:LunarLanderContinuous", }
#!/usr/bin/env python # _*_ coding:utf-8 _*_ """ testlink.testlink """ class TestSuite(object): def __init__(self, name='', details='', testcase_list=None, sub_suites=None): """ TestSuite (TODO(devin): there is an infinite recursive reference problem with initializing an empty list) :param name: test suite name :param details: test suite detail infomation :param testcase_list: test case list :param sub_suites: sub test suite list """ self.name = name self.details = details self.testcase_list = testcase_list self.sub_suites = sub_suites def to_dict(self): data = { 'name': self.name, 'details': self.details, 'testcase_list': [], 'sub_suites': [] } if self.sub_suites: for suite in self.sub_suites: data['sub_suites'].append(suite.to_dict()) if self.testcase_list: for case in self.testcase_list: data['testcase_list'].append(case.to_dict()) return data class TestCase(object): def __init__(self, name='', version=1, summary='', preconditions='', execution_type=1, importance=2, estimated_exec_duration=3, status=7, steps=None): """ TestCase :param name: test case name :param version: test case version infomation :param summary: test case summary infomation :param preconditions: test case pre condition :param execution_type: manual or automate :param importance: high:1, middle:2, low:3 :param estimated_exec_duration: estimated execution duration :param status: draft:1, ready ro review:2, review in progress:3, rework:4, obsolete:5, future:6, final:7 :param steps: test case step list """ self.name = name self.version = version self.summary = summary self.preconditions = preconditions self.execution_type = execution_type self.importance = importance self.estimated_exec_duration = estimated_exec_duration self.status = status self.steps = steps def to_dict(self): data = { 'name': self.name, 'version': self.version, # TODO(devin): get version content 'summary': self.summary, 'preconditions': self.preconditions, 'execution_type': self.execution_type, 'importance': self.importance, 'estimated_exec_duration': self.estimated_exec_duration, # TODO(devin): get estimated content 'status': self.status, # TODO(devin): get status content 'steps': [] } if self.steps: for step in self.steps: data['steps'].append(step.to_dict()) return data class TestStep(object): def __init__(self, step_number=1, actions='', expectedresults='', execution_type=1): """ TestStep :param step_number: test step number :param actions: test step actions :param expectedresults: test step expected results :param execution_type: test step execution type """ self.step_number = step_number self.actions = actions self.expectedresults = expectedresults self.execution_type = execution_type # TODO(devin): get execution type content def to_dict(self): data = { 'step_number': self.step_number, 'actions': self.actions, 'expectedresults': self.expectedresults, 'execution_type': self.execution_type } return data
# This file MUST be configured in order for the code to run properly # Make sure you put all your input images into an 'assets' folder. # Each layer (or category) of images must be put in a folder of its own. # CONFIG is an array of objects where each object represents a layer # THESE LAYERS MUST BE ORDERED. # Each layer needs to specify the following # 1. id: A number representing a particular layer # 2. name: The name of the layer. Does not necessarily have to be the same as the directory name containing the layer images. # 3. directory: The folder inside assets that contain traits for the particular layer # 4. required: If the particular layer is required (True) or optional (False). The first layer must always be set to true. # 5. rarity_weights: Denotes the rarity distribution of traits. It can take on three types of values. # - None: This makes all the traits defined in the layer equally rare (or common) # - "random": Assigns rarity weights at random. # - array: An array of numbers where each number represents a weight. # If required is True, this array must be equal to the number of images in the layer directory. The first number is the weight of the first image (in alphabetical order) and so on... # If required is False, this array must be equal to one plus the number of images in the layer directory. The first number is the weight of having no image at all for this layer. The second number is the weight of the first image and so on... # Be sure to check out the tutorial in the README for more details. CONFIG = [ { 'id': 1, 'name': 'asset1', 'directory': 'asset1', 'required': True, 'rarity_weights': [20, 16, 17, 8, 18, 15, 9, 6], }, { 'id': 2, 'name': 'asset2', 'directory': 'asset2', 'required': True, 'rarity_weights': [8, 24, 16, 20, 13, 19, 6], }, { 'id': 3, 'name': 'asset3', 'directory': 'asset3', 'required': True, 'rarity_weights': [6, 25, 15, 12, 20, 9, 16, 7, 15, 19, 5], }, { 'id': 4, 'name': 'asset4', 'directory': 'asset4', 'required': False, 'rarity_weights': [100, 9, 30, 20, 19, 25, 22, 33, 19, 12, 14, 18, 7, 3, 10, 24], }, { 'id': 5, 'name': 'asset5', 'directory': 'asset5', 'required': True, 'rarity_weights': [19, 12, 6, 12, 20, 24, 9, 8], }, { 'id': 5, 'name': 'asset6', 'directory': 'asset6', 'required': False, 'rarity_weights': [100, 24, 19, 6, 14, 20, 24, 12, 16], }, ]
''' http://pythontutor.ru/lessons/for_loop/problems/factorial/ Факториалом числа n называется произведение 1 × 2 × ... × n. Обозначение: n!. По данному натуральному n вычислите значение n!. Пользоваться математической библиотекой math в этой задаче запрещено. ''' n = int(input()) f = 1 for i in range(1, n+1): f *= i print(f)
def setData(field, value, path): f = open(path, "r") lines = f.readlines() f.close() f = open(path, "w+") for line in lines: if (line.find(field) != -1): f.write(field + "=" + str(value) + "\n") else: f.write(line) f.close() return True def getData(path): f = open(path, "r") lines = f.readlines() f.close() data = {} for line in lines: parts = line.split("=") data[parts[0]] = parts[1].strip() return data def addData(field, value, path): f = open(path, "a") f.write(field + "=" + str(value) + "\n") f.close() return def deleteData(field, value, path): f = open(path, "r") lines = f.readlines() f.close() f = open(path, "w+") for line in lines: if (line.find(field) == -1): f.write(line) f.close() return True
class Event: def __init__(self): self.handlers = [] def call(self, *args, **kwargs): for h in self.handlers: h(*args, **kwargs) def __call__(self, *args, **kwargs): self.call(*args, **kwargs)
""" module for menus and ascii arts """ ascii_art = """ 8888888b. .d8888b. .d88888b. 888 888 Y88b d88P Y88b d88P" "Y88b 888 888 888 Y88b. 888 888 888 888 d88P 888 888 "Y888b. 888 888 888 8888888P" 888 888 "Y88b. 888 888 888 888 888 888 "888 888 Y8b 888 888 888 Y88b 888 Y88b d88P Y88b.Y8b88P 888 888 "Y88888 "Y8888P" "Y888888" 88888888 888 Y8b Y8b d88P "Y88P" """ menu = """ OPTIONS -a about Shows information about PySQL -c commands Display available commands -d def user Default User options -h help Display this help message -v version Display application version -u updates Check for PySQL updates -q quit Exit the program """ about = """ PySQL: Python - MySQL wrapper tool PySQL is a command line tool for making MySQL queries easier, made using Python See https://github.com/Devansh3712/PySQL for more information """ commands = """ COMMANDS ddl Displays Data Definition Language commands dml Displays Data Manipulation Language commands export Export table/database import Import database all Displays all available commands """ default_user = """ DEFAULT USER adduser Create a default user for PySQL login removeuser Remove the current default user """ data_definition_language = """ DDL COMMANDS showdb Display all databases in MySQL server usedb Use a database createdb DB_NAME Create a new database dropdb DB_NAME Delete a database showtb Display all tables in current db createtb TB_NAME, ARGS Create a new table in current db droptb TB_NAME Delete a table in current db trunctb TB_NAME Truncate a table in current db desctb TB_NAME Display structure of a table in current db altertb TB_NAME, ARGS Alter contents of table in current db """ data_manipulation_language = """ DML COMMANDS select TB_NAME, COLUMNS, ARGS Displays selected columns of a table insert -s TB_NAME, ARGS Insert a single row in a table -m TB_NAME, NUM, ARGS Insert `NUM` rows in a table -f TB_NAME, FILE_NAME Insert values in a table from CSV file update TB_NAME, COLUMNS, ARGS Updates values of columns in a table delete TB_NAME, COLUMN Deletes values of row in a table """ all_commands = """ ALL COMMANDS select TB_NAME, COLUMNS, ARGS Displays selected columns of a table insert -s TB_NAME, ARGS Insert a single row in a table -m TB_NAME, NUM, ARGS Insert `NUM` rows in a table -f TB_NAME, FILE_NAME Insert values in a table from CSV file update TB_NAME, COLUMNS, ARGS Updates values of columns in a table delete TB_NAME, COLUMN Deletes values of row in a table showdb Display all databases in MySQL server usedb Use a database createdb DB_NAME Create a new database dropdb DB_NAME Delete a database showtb Display all tables in current db createtb TB_NAME, ARGS Create a new table in current db droptb TB_NAME Delete a table in current db trunctb TB_NAME Truncate a table in current db desctb TB_NAME Display structure of a table in current db altertb TB_NAME, ARGS Alter contents of table in current db exportdb DB_NAME, PATH Export db as `.sql` file to path exporttb -json TB_NAME, PATH Export table as `.txt` file to path -csv TB_NAME, PATH Export table as `.csv` file to path -sql TB_NAME, PATH Export table schema as `.sql` file to path exportall -json PATH Export all tables in db as `.txt` file to path -csv PATH Export all tables in db as `.csv` file to path -sql PATH Export all tables schema in db as `.sql` file to path importdb DB_NAME, PATH Import `.sql` file into input database importtb DB_NAME, PATH Import `.sql` table schema into input table """ export = """ EXPORT exportdb DB_NAME, PATH Export db as `.sql` file to path exporttb -json TB_NAME, PATH Export table as `.txt` file to path -csv TB_NAME, PATH Export table as `.csv` file to path -sql TB_NAME, PATH Export table schema as `.sql` file to path exportall -json PATH Export all tables in db as `.txt` file to path -csv PATH Export all tables in db as `.csv` file to path -sql PATH Export all tables schema in db as `.sql` file to path """ import_ = """ IMPORT importdb DB_NAME, PATH Import `.sql` file into input database importtb DB_NAME, PATH Import `.sql` table schema into input table """ """ PySQL Devansh Singh, 2021 """
class ExampleJob: def __init__(self, id): self.id = id self.retry_count = 10 self.retry_pause_sec = 10 def run(self, runtime): pass
#! /usr/bin/env python __author__ = 'Tser' __email__ = '807447312@qq.com' __project__ = 'jicaiauto' __script__ = '__version__.py' __create_time__ = '2020/7/15 23:21' VERSION = (0, 0, 2, 0) __version__ = '.'.join(map(str, VERSION))
_base_ = './pascal_voc12.py' # dataset settings data = dict( samples_per_gpu=2, train=dict( ann_dir=['SegmentationClass', 'SegmentationClassAug'], split=[ 'ImageSets/Segmentation/train.txt', 'ImageSets/Segmentation/aug.txt' ]))
""" Staircase """ def staircase(n): i = 1 while (n + 1) - i: blanks = " " * (n-i) pattern = "#" * i print(blanks+pattern) i += 1 if __name__ == "__main__": staircase(4)
# Copyright 2018 Contributors to Hyperledger Sawtooth # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ----------------------------------------------------------------------------- USER_SEARCH_ALL = "(objectClass=person)" USER_SEARCH_BY_DN = "(&(objectClass=person)(distinguishedName={}))" USER_SEARCH_AFTER_DATE = "(&(objectClass=person)(whenChanged>=%s))" GROUP_SEARCH_ALL = "(objectClass=group)" GROUP_SEARCH_BY_DN = "(&(objectClass=group)(distinguishedName={}))" GROUP_SEARCH_AFTER_DATE = "(&(objectClass=group)(whenChanged>=%s))"
class StatusWirelessStaRemoteUnms: status: int timestamp: str def __init__(self, data): self.status = data.get("status") self.timestamp = data.get("timestamp")