content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Right click functions and operators def dump(obj, text): print('-'*40, text, '-'*40) for attr in dir(obj): if hasattr( obj, attr ): print( "obj.%s = %s" % (attr, getattr(obj, attr))) def split_path(str): """Splits a data path into rna + id. This is the core of creating controls for properties. """ # First split the last part of the dot-chain rna, path = str.rsplit('.',1) # If the last part contains a '][', it's a custom property for a collection item if '][' in path: # path is 'somecol["itemkey"]["property"]' path, rem = path.rsplit('[', 1) # path is 'somecol["itemkey"]' ; rem is '"property"]' rna = rna + '.' + path # rna is 'rna.path.to.somecol["itemkey"]' path = '[' + rem # path is '["property"]' # If the last part only contains a single '[', # it's an indexed value elif '[' in path: # path is 'someprop[n]' path, rem = path.rsplit('[', 1) # path is 'someprop' ; rem is ignored return rna, path
def dump(obj, text): print('-' * 40, text, '-' * 40) for attr in dir(obj): if hasattr(obj, attr): print('obj.%s = %s' % (attr, getattr(obj, attr))) def split_path(str): """Splits a data path into rna + id. This is the core of creating controls for properties. """ (rna, path) = str.rsplit('.', 1) if '][' in path: (path, rem) = path.rsplit('[', 1) rna = rna + '.' + path path = '[' + rem elif '[' in path: (path, rem) = path.rsplit('[', 1) return (rna, path)
# alternative characters T = input() lst = [] results = [] if T >= 1 and T <= 10: for i in range(T): lst.append(raw_input()) lst = filter(lambda x: len(x) >= 1 and len(x) <= 10**5, lst) for cst in lst: delct = 0 for j in range(len(cst)-1): if cst[j] == cst[j+1]: delct += 1 results.append(delct) for v in results: print(v)
t = input() lst = [] results = [] if T >= 1 and T <= 10: for i in range(T): lst.append(raw_input()) lst = filter(lambda x: len(x) >= 1 and len(x) <= 10 ** 5, lst) for cst in lst: delct = 0 for j in range(len(cst) - 1): if cst[j] == cst[j + 1]: delct += 1 results.append(delct) for v in results: print(v)
a = int(input()) c = int(input()) s = True for b in range(a - 1): if int(input()) >= c: s = False if s: print("YES") else: print("NO")
a = int(input()) c = int(input()) s = True for b in range(a - 1): if int(input()) >= c: s = False if s: print('YES') else: print('NO')
n, m = map(int, input().split()) shops = [tuple(map(int, input().split())) for _ in range(n)] shops.sort(key=lambda x: x[0]) ans = 0 for a, b in shops: if m <= b: ans += a * m break else: ans += a * b m -= b print(ans)
(n, m) = map(int, input().split()) shops = [tuple(map(int, input().split())) for _ in range(n)] shops.sort(key=lambda x: x[0]) ans = 0 for (a, b) in shops: if m <= b: ans += a * m break else: ans += a * b m -= b print(ans)
''' Power of Two Solution Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 20 = 1 Example 2: Input: 16 Output: true Explanation: 24 = 16 Example 3: Input: 218 Output: false''' n = int(input()) if n <= 0 : print('false') while n%2 == 0: n = n/2 print(n==1)
""" Power of Two Solution Given an integer, write a function to determine if it is a power of two. Example 1: Input: 1 Output: true Explanation: 20 = 1 Example 2: Input: 16 Output: true Explanation: 24 = 16 Example 3: Input: 218 Output: false""" n = int(input()) if n <= 0: print('false') while n % 2 == 0: n = n / 2 print(n == 1)
# Copyright 2017 Lawrence Kesteloot # # 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. # Defines the various low-level model structures. These mirror the database tables. # Represents a photo that was taken. Multiple files on disk (PhotoFile) can represent # this photo. class Photo(object): def __init__(self, id, hash_back, rotation, rating, date, display_date, label): self.id = id # SHA-1 of the last 1 kB of the file. self.hash_back = hash_back # In degrees. self.rotation = rotation # 1 to 5, where 1 means "I'd be okay deleting this file", 2 means "I don't want # to show this on this slide show program", 3 is the default, 4 means "This is # a great photo", and 5 means "On my deathbed I want a photo album with this photo." self.rating = rating # Unix date when the photo was taken. Defaults to the date of the file. self.date = date # Date as displayed to the user. Usually a friendly version of "date" but might # be more vague, like "Summer 1975". self.display_date = display_date # Label to display. Defaults to a cleaned up version of the pathname, but could be # edited by the user. self.label = label # In-memory use only, not stored in database. Refers to the preferred photo file to # show for this photo. self.pathname = None # Represents a photo file on disk. Multiple of these (including minor changes in the header) # might represent the same Photo. class PhotoFile(object): def __init__(self, pathname, hash_all, hash_back): # Pathname relative to the root of the photo tree. self.pathname = pathname # SHA-1 of the entire file. self.hash_all = hash_all # SHA-1 of the last 1 kB of the file. self.hash_back = hash_back # Represents an email that was sent to a person about a photo. class Email(object): def __init__(self, id, pathname, person_id, sent_at, photo_id): self.id = id self.person_id = person_id self.sent_at = sent_at self.photo_id = photo_id
class Photo(object): def __init__(self, id, hash_back, rotation, rating, date, display_date, label): self.id = id self.hash_back = hash_back self.rotation = rotation self.rating = rating self.date = date self.display_date = display_date self.label = label self.pathname = None class Photofile(object): def __init__(self, pathname, hash_all, hash_back): self.pathname = pathname self.hash_all = hash_all self.hash_back = hash_back class Email(object): def __init__(self, id, pathname, person_id, sent_at, photo_id): self.id = id self.person_id = person_id self.sent_at = sent_at self.photo_id = photo_id
# eerste negen cijfers van ISBN-10 code inlezen en omzetten naar integers x1 = int(input()) x2 = int(input()) x3 = int(input()) x4 = int(input()) x5 = int(input()) x6 = int(input()) x7 = int(input()) x8 = int(input()) x9 = int(input()) # controlecijfer berekenen x10 = (x1 + 2 * x2 + 3 * x3 + 4 * x4 + 5 * x5 + 6 * x6 + 7 * x7 + 8 * x8 + 9 * x9) % 11 # controlecijfer uitschrijven print(x10)
x1 = int(input()) x2 = int(input()) x3 = int(input()) x4 = int(input()) x5 = int(input()) x6 = int(input()) x7 = int(input()) x8 = int(input()) x9 = int(input()) x10 = (x1 + 2 * x2 + 3 * x3 + 4 * x4 + 5 * x5 + 6 * x6 + 7 * x7 + 8 * x8 + 9 * x9) % 11 print(x10)
def get_attr_or_callable(obj, name): target = getattr(obj, name) if callable(target): return target() return target
def get_attr_or_callable(obj, name): target = getattr(obj, name) if callable(target): return target() return target
SAMPLE_NRTM_V3 = """ % NRTM v3 contains serials per object. % Another comment %START Version: 3 TEST 11012700-11012701 ADD 11012700 person: NRTM test address: NowhereLand source: TEST DEL 11012701 inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ # NRTM v1 has no serials per object SAMPLE_NRTM_V1 = """%START Version: 1 TEST 11012700-11012701 ADD person: NRTM test address: NowhereLand source: TEST DEL inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ SAMPLE_NRTM_V1_TOO_MANY_ITEMS = """ % The serial range is one item, but there are two items in here. %START Version: 1 TEST 11012700-11012700 FILTERED ADD person: NRTM test address: NowhereLand source: TEST DEL inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ SAMPLE_NRTM_INVALID_VERSION = """%START Version: 99 TEST 11012700-11012700""" SAMPLE_NRTM_V3_SERIAL_GAP = """ # NRTM v3 serials are allowed to have gaps per https://github.com/irrdnet/irrd/issues/85 %START Version: 3 TEST 11012699-11012703 ADD 11012700 person: NRTM test address: NowhereLand source: TEST DEL 11012701 inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ SAMPLE_NRTM_V3_SERIAL_OUT_OF_ORDER = """ # NRTM v3 serials can have gaps, but must always increase. %START Version: 3 TEST 11012699-11012703 ADD 11012701 person: NRTM test address: NowhereLand source: TEST DEL 11012701 inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ SAMPLE_NRTM_V3_INVALID_MULTIPLE_START_LINES = """ %START Version: 3 TEST 11012700-11012700 %START Version: 3 ARIN 11012700-11012700 ADD 11012701 person: NRTM test address: NowhereLand source: TEST %END TEST """ SAMPLE_NRTM_INVALID_NO_START_LINE = """ ADD 11012701 person: NRTM test address: NowhereLand source: TEST DEL 11012700 inetnum: 192.0.2.0 - 192.0.2.255 source: TEST %END TEST """ SAMPLE_NRTM_V3_NO_END = """%START Version: 3 TEST 11012700-11012701"""
sample_nrtm_v3 = '\n% NRTM v3 contains serials per object.\n\n% Another comment\n\n%START Version: 3 TEST 11012700-11012701\n\nADD 11012700\n\nperson: NRTM test\naddress: NowhereLand\nsource: TEST\n\nDEL 11012701\n\ninetnum: 192.0.2.0 - 192.0.2.255\nsource: TEST\n\n%END TEST\n' sample_nrtm_v1 = '%START Version: 1 TEST 11012700-11012701\n\nADD\n\nperson: NRTM test\naddress: NowhereLand\nsource: TEST\n\nDEL\n\ninetnum: 192.0.2.0 - 192.0.2.255\nsource: TEST\n\n%END TEST\n' sample_nrtm_v1_too_many_items = '\n% The serial range is one item, but there are two items in here.\n\n%START Version: 1 TEST 11012700-11012700 FILTERED\n\nADD\n\nperson: NRTM test\naddress: NowhereLand\nsource: TEST\n\nDEL\n\ninetnum: 192.0.2.0 - 192.0.2.255\nsource: TEST\n\n%END TEST\n' sample_nrtm_invalid_version = '%START Version: 99 TEST 11012700-11012700' sample_nrtm_v3_serial_gap = '\n# NRTM v3 serials are allowed to have gaps per https://github.com/irrdnet/irrd/issues/85\n\n%START Version: 3 TEST 11012699-11012703\n\nADD 11012700\n\nperson: NRTM test\naddress: NowhereLand\nsource: TEST\n\n\nDEL 11012701\n\ninetnum: 192.0.2.0 - 192.0.2.255\nsource: TEST\n\n%END TEST\n' sample_nrtm_v3_serial_out_of_order = '\n# NRTM v3 serials can have gaps, but must always increase.\n\n%START Version: 3 TEST 11012699-11012703\n\nADD 11012701\n\nperson: NRTM test\naddress: NowhereLand\nsource: TEST\n\nDEL 11012701\n\ninetnum: 192.0.2.0 - 192.0.2.255\nsource: TEST\n\n%END TEST\n' sample_nrtm_v3_invalid_multiple_start_lines = '\n%START Version: 3 TEST 11012700-11012700\n\n%START Version: 3 ARIN 11012700-11012700\n\nADD 11012701\n\nperson: NRTM test\naddress: NowhereLand\nsource: TEST\n\n%END TEST\n' sample_nrtm_invalid_no_start_line = '\nADD 11012701\n\nperson: NRTM test\naddress: NowhereLand\nsource: TEST\n\nDEL 11012700\n\ninetnum: 192.0.2.0 - 192.0.2.255\nsource: TEST\n\n%END TEST\n' sample_nrtm_v3_no_end = '%START Version: 3 TEST 11012700-11012701'
class Packager: """ Packager class. This class is used to generate the required XML to send back to the client. """ def __init__(self): self.xml_version = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" self.begin_root = "<kevlar>" self.end_root = "</kevlar>" def generate_account(self, username: str, password: str, database: str, hmac: str, initialization_vector: str): """ Generate account document by using the upload-able data. :param username: The account username. :param password: The account password. :param database: The account database. :param hmac: The authentication hmac of the database. :param initialization_vector: The initialization vector for that account. :return: The xml document. """ document = self.xml_version + self.begin_root document += f"<username>{username}</username>" document += f"<password>{password}</password>" document += f"<database>{database}</database>" document += f"<hmac>{hmac}</hmac>" document += f"<iv>{initialization_vector}</iv>" return document + self.end_root def generate_status(self, status: str): """ Generate the status document by using the status generated by the server. :param status: The status to include. :return: The xml document. """ document = self.xml_version + self.begin_root document += f"<status>{status}</status>" return document + self.end_root
class Packager: """ Packager class. This class is used to generate the required XML to send back to the client. """ def __init__(self): self.xml_version = '<?xml version="1.0" encoding="UTF-8"?>' self.begin_root = '<kevlar>' self.end_root = '</kevlar>' def generate_account(self, username: str, password: str, database: str, hmac: str, initialization_vector: str): """ Generate account document by using the upload-able data. :param username: The account username. :param password: The account password. :param database: The account database. :param hmac: The authentication hmac of the database. :param initialization_vector: The initialization vector for that account. :return: The xml document. """ document = self.xml_version + self.begin_root document += f'<username>{username}</username>' document += f'<password>{password}</password>' document += f'<database>{database}</database>' document += f'<hmac>{hmac}</hmac>' document += f'<iv>{initialization_vector}</iv>' return document + self.end_root def generate_status(self, status: str): """ Generate the status document by using the status generated by the server. :param status: The status to include. :return: The xml document. """ document = self.xml_version + self.begin_root document += f'<status>{status}</status>' return document + self.end_root
# These are the "Tableau 20" colors as RGB. tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] # Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts. for i in range(len(tableau20)): r, g, b = tableau20[i] tableau20[i] = (r / 255., g / 255., b / 255.)
tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120), (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150), (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148), (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199), (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)] for i in range(len(tableau20)): (r, g, b) = tableau20[i] tableau20[i] = (r / 255.0, g / 255.0, b / 255.0)
"""Utility functions for RtMidi backend. These are in a separate file so they can be tested without the `python-rtmidi` package. """ def expand_alsa_port_name(port_names, name): """Expand ALSA port name. RtMidi/ALSA includes client name and client:port number in the port name, for example: TiMidity:TiMidity port 0 128:0 This allows you to specify only port name or client:port name when opening a port. It will compare the name to each name in port_names (typically returned from get_*_names()) and try these three variants in turn: TiMidity:TiMidity port 0 128:0 TiMidity:TiMidity port 0 TiMidity port 0 It returns the first match. If no match is found it returns the passed name so the caller can deal with it. """ if name is None: return None for port_name in port_names: if name == port_name: return name # Try without client and port number (for example 128:0). without_numbers = port_name.rsplit(None, 1)[0] if name == without_numbers: return port_name if ':' in without_numbers: without_client = without_numbers.split(':', 1)[1] if name == without_client: return port_name else: # Let caller deal with it. return name
"""Utility functions for RtMidi backend. These are in a separate file so they can be tested without the `python-rtmidi` package. """ def expand_alsa_port_name(port_names, name): """Expand ALSA port name. RtMidi/ALSA includes client name and client:port number in the port name, for example: TiMidity:TiMidity port 0 128:0 This allows you to specify only port name or client:port name when opening a port. It will compare the name to each name in port_names (typically returned from get_*_names()) and try these three variants in turn: TiMidity:TiMidity port 0 128:0 TiMidity:TiMidity port 0 TiMidity port 0 It returns the first match. If no match is found it returns the passed name so the caller can deal with it. """ if name is None: return None for port_name in port_names: if name == port_name: return name without_numbers = port_name.rsplit(None, 1)[0] if name == without_numbers: return port_name if ':' in without_numbers: without_client = without_numbers.split(':', 1)[1] if name == without_client: return port_name else: return name
# -*- coding: utf-8 -*- # Which templates don't you want to generate? (You can use regular expressions here!) # Use strings (with single or double quotes), and separate each template/regex in a line terminated with a comma. IGNORE_JINJA_TEMPLATES = [ '.*base.jinja', '.*tests/.*' ] # Do you have any additional variables to the templates? Put 'em here! (use dictionary ('key': value) format) EXTRA_VARIABLES = { 'test_type': 'Array', 'name': 'float', 'dim': 3, 'type': 'float', 'suffix': 'f', 'extends': '[3]' } OUTPUT_OPTIONS = { 'extension': '3_arr.cpp', # Including leading '.', example '.html' 'remove_double_extension': False }
ignore_jinja_templates = ['.*base.jinja', '.*tests/.*'] extra_variables = {'test_type': 'Array', 'name': 'float', 'dim': 3, 'type': 'float', 'suffix': 'f', 'extends': '[3]'} output_options = {'extension': '3_arr.cpp', 'remove_double_extension': False}
class Solution(object): # def removeDuplicates(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # ls = len(nums) # if ls <= 1: # return ls # last = nums[0] # pos = 1 # for t in nums[1:]: # if t == last: # continue # else: # nums[pos] = t # pos += 1 # last = t # return pos # https://leetcode.com/articles/remove-duplicates-sorted-array/ def removeDuplicates(self, nums): if len(nums) == 0: return 0 left = 0 for i in range(1, len(nums)): if nums[left] == nums[i]: continue else: left += 1 nums[left] = nums[i] return left + 1
class Solution(object): def remove_duplicates(self, nums): if len(nums) == 0: return 0 left = 0 for i in range(1, len(nums)): if nums[left] == nums[i]: continue else: left += 1 nums[left] = nums[i] return left + 1
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: results = [] def dfs (elements, start: int, k: int): if k == 0: results.append(elements[:]) for i in range (start, n+1): elements.append(i) dfs (elements, i+1, k-1) elements.pop() dfs ([], 1, k) return results
class Solution: def combine(self, n: int, k: int) -> List[List[int]]: results = [] def dfs(elements, start: int, k: int): if k == 0: results.append(elements[:]) for i in range(start, n + 1): elements.append(i) dfs(elements, i + 1, k - 1) elements.pop() dfs([], 1, k) return results
load( "@build_bazel_rules_apple//apple:providers.bzl", "AppleBundleInfo", "AppleResourceInfo", "IosFrameworkBundleInfo", ) load( "@build_bazel_rules_apple//apple/internal:resources.bzl", "resources", ) load( "//rules:providers.bzl", "AvoidDepsInfo", ) load( "@build_bazel_rules_apple//apple/internal/providers:embeddable_info.bzl", "AppleEmbeddableInfo", "embeddable_info", ) load( "//rules/internal:objc_provider_utils.bzl", "objc_provider_utils", ) def _framework_middleman(ctx): resource_providers = [] objc_providers = [] dynamic_framework_providers = [] apple_embeddable_infos = [] cc_providers = [] def _collect_providers(lib_dep): if AppleEmbeddableInfo in lib_dep: apple_embeddable_infos.append(lib_dep[AppleEmbeddableInfo]) # Most of these providers will be passed into `deps` of apple rules. # Don't feed them twice. There are several assumptions rules_apple on # this if IosFrameworkBundleInfo in lib_dep: if CcInfo in lib_dep: cc_providers.append(lib_dep[CcInfo]) if AppleResourceInfo in lib_dep: resource_providers.append(lib_dep[AppleResourceInfo]) if apple_common.Objc in lib_dep: objc_providers.append(lib_dep[apple_common.Objc]) if apple_common.AppleDynamicFramework in lib_dep: dynamic_framework_providers.append(lib_dep[apple_common.AppleDynamicFramework]) for dep in ctx.attr.framework_deps: _collect_providers(dep) # Loop AvoidDepsInfo here as well if AvoidDepsInfo in dep: for lib_dep in dep[AvoidDepsInfo].libraries: _collect_providers(lib_dep) # Here we only need to loop a subset of the keys objc_provider_fields = objc_provider_utils.merge_objc_providers_dict(providers = objc_providers, merge_keys = [ "dynamic_framework_file", ]) # Add the frameworks to the linker command dynamic_framework_provider = objc_provider_utils.merge_dynamic_framework_providers(ctx, dynamic_framework_providers) objc_provider_fields["dynamic_framework_file"] = depset( transitive = [dynamic_framework_provider.framework_files, objc_provider_fields.get("dynamic_framework_file", depset([]))], ) objc_provider = apple_common.new_objc_provider(**objc_provider_fields) cc_info_provider = cc_common.merge_cc_infos(direct_cc_infos = [], cc_infos = cc_providers) providers = [ dynamic_framework_provider, cc_info_provider, objc_provider, IosFrameworkBundleInfo(), AppleBundleInfo( archive = None, archive_root = None, binary = None, # These arguments are unused - however, put them here incase that # somehow changes to make it easier to debug bundle_id = "com.bazel_build_rules_ios.unused", bundle_name = "bazel_build_rules_ios_unused", ), ] embed_info_provider = embeddable_info.merge_providers(apple_embeddable_infos) if embed_info_provider: providers.append(embed_info_provider) if len(resource_providers) > 0: resource_provider = resources.merge_providers( default_owner = str(ctx.label), providers = resource_providers, ) providers.append(resource_provider) return providers framework_middleman = rule( implementation = _framework_middleman, attrs = { "framework_deps": attr.label_list( cfg = apple_common.multi_arch_split, mandatory = True, doc = """Deps that may contain frameworks """, ), "platform_type": attr.string( mandatory = False, doc = """Internal - currently rules_ios uses the dict `platforms` """, ), "minimum_os_version": attr.string( mandatory = False, doc = """Internal - currently rules_ios the dict `platforms` """, ), }, doc = """ This is a volatile internal rule to make frameworks work with rules_apples bundling logic Longer term, we will likely get rid of this and call partial like apple_framework directly so consider it an implementation detail """, ) def _dedupe_key(key, avoid_libraries, objc_provider_fields, check_name = False): updated_library = [] exisiting_library = objc_provider_fields.get(key, depset([])) for f in exisiting_library.to_list(): check_key = (f.basename if check_name else f) if check_key in avoid_libraries: continue updated_library.append(f) objc_provider_fields[key] = depset(updated_library) def _dep_middleman(ctx): objc_providers = [] cc_providers = [] avoid_libraries = {} def _collect_providers(lib_dep): if apple_common.Objc in lib_dep: objc_providers.append(lib_dep[apple_common.Objc]) def _process_avoid_deps(avoid_dep_libs): for dep in avoid_dep_libs: if apple_common.Objc in dep: for lib in dep[apple_common.Objc].library.to_list(): avoid_libraries[lib] = True for lib in dep[apple_common.Objc].force_load_library.to_list(): avoid_libraries[lib] = True for lib in dep[apple_common.Objc].imported_library.to_list(): avoid_libraries[lib.basename] = True for lib in dep[apple_common.Objc].static_framework_file.to_list(): avoid_libraries[lib.basename] = True for dep in ctx.attr.deps: _collect_providers(dep) # Loop AvoidDepsInfo here as well if AvoidDepsInfo in dep: _process_avoid_deps(dep[AvoidDepsInfo].libraries) for lib_dep in dep[AvoidDepsInfo].libraries: _collect_providers(lib_dep) # Pull AvoidDeps from test deps for dep in (ctx.attr.test_deps if ctx.attr.test_deps else []): if AvoidDepsInfo in dep: _process_avoid_deps(dep[AvoidDepsInfo].libraries) # Merge the entire provider here objc_provider_fields = objc_provider_utils.merge_objc_providers_dict(providers = objc_providers, merge_keys = [ "force_load_library", "imported_library", "library", "link_inputs", "linkopt", "sdk_dylib", "sdk_framework", "source", "static_framework_file", "weak_sdk_framework", ]) # Ensure to strip out static link inputs _dedupe_key("library", avoid_libraries, objc_provider_fields) _dedupe_key("force_load_library", avoid_libraries, objc_provider_fields) _dedupe_key("imported_library", avoid_libraries, objc_provider_fields, check_name = True) _dedupe_key("static_framework_file", avoid_libraries, objc_provider_fields, check_name = True) objc_provider = apple_common.new_objc_provider(**objc_provider_fields) cc_info_provider = cc_common.merge_cc_infos(direct_cc_infos = [], cc_infos = cc_providers) providers = [ cc_info_provider, objc_provider, ] return providers dep_middleman = rule( implementation = _dep_middleman, attrs = { "deps": attr.label_list( cfg = apple_common.multi_arch_split, mandatory = True, doc = """Deps that may contain frameworks """, ), "test_deps": attr.label_list( cfg = apple_common.multi_arch_split, allow_empty = True, ), "platform_type": attr.string( mandatory = False, doc = """Internal - currently rules_ios uses the dict `platforms` """, ), "minimum_os_version": attr.string( mandatory = False, doc = """Internal - currently rules_ios the dict `platforms` """, ), }, doc = """ This is a volatile internal rule to make frameworks work with rules_apples bundling logic Longer term, we will likely get rid of this and call partial like apple_framework directly so consider it an implementation detail """, )
load('@build_bazel_rules_apple//apple:providers.bzl', 'AppleBundleInfo', 'AppleResourceInfo', 'IosFrameworkBundleInfo') load('@build_bazel_rules_apple//apple/internal:resources.bzl', 'resources') load('//rules:providers.bzl', 'AvoidDepsInfo') load('@build_bazel_rules_apple//apple/internal/providers:embeddable_info.bzl', 'AppleEmbeddableInfo', 'embeddable_info') load('//rules/internal:objc_provider_utils.bzl', 'objc_provider_utils') def _framework_middleman(ctx): resource_providers = [] objc_providers = [] dynamic_framework_providers = [] apple_embeddable_infos = [] cc_providers = [] def _collect_providers(lib_dep): if AppleEmbeddableInfo in lib_dep: apple_embeddable_infos.append(lib_dep[AppleEmbeddableInfo]) if IosFrameworkBundleInfo in lib_dep: if CcInfo in lib_dep: cc_providers.append(lib_dep[CcInfo]) if AppleResourceInfo in lib_dep: resource_providers.append(lib_dep[AppleResourceInfo]) if apple_common.Objc in lib_dep: objc_providers.append(lib_dep[apple_common.Objc]) if apple_common.AppleDynamicFramework in lib_dep: dynamic_framework_providers.append(lib_dep[apple_common.AppleDynamicFramework]) for dep in ctx.attr.framework_deps: _collect_providers(dep) if AvoidDepsInfo in dep: for lib_dep in dep[AvoidDepsInfo].libraries: _collect_providers(lib_dep) objc_provider_fields = objc_provider_utils.merge_objc_providers_dict(providers=objc_providers, merge_keys=['dynamic_framework_file']) dynamic_framework_provider = objc_provider_utils.merge_dynamic_framework_providers(ctx, dynamic_framework_providers) objc_provider_fields['dynamic_framework_file'] = depset(transitive=[dynamic_framework_provider.framework_files, objc_provider_fields.get('dynamic_framework_file', depset([]))]) objc_provider = apple_common.new_objc_provider(**objc_provider_fields) cc_info_provider = cc_common.merge_cc_infos(direct_cc_infos=[], cc_infos=cc_providers) providers = [dynamic_framework_provider, cc_info_provider, objc_provider, ios_framework_bundle_info(), apple_bundle_info(archive=None, archive_root=None, binary=None, bundle_id='com.bazel_build_rules_ios.unused', bundle_name='bazel_build_rules_ios_unused')] embed_info_provider = embeddable_info.merge_providers(apple_embeddable_infos) if embed_info_provider: providers.append(embed_info_provider) if len(resource_providers) > 0: resource_provider = resources.merge_providers(default_owner=str(ctx.label), providers=resource_providers) providers.append(resource_provider) return providers framework_middleman = rule(implementation=_framework_middleman, attrs={'framework_deps': attr.label_list(cfg=apple_common.multi_arch_split, mandatory=True, doc='Deps that may contain frameworks\n'), 'platform_type': attr.string(mandatory=False, doc='Internal - currently rules_ios uses the dict `platforms`\n'), 'minimum_os_version': attr.string(mandatory=False, doc='Internal - currently rules_ios the dict `platforms`\n')}, doc='\n This is a volatile internal rule to make frameworks work with\n rules_apples bundling logic\n\n Longer term, we will likely get rid of this and call partial like\n apple_framework directly so consider it an implementation detail\n ') def _dedupe_key(key, avoid_libraries, objc_provider_fields, check_name=False): updated_library = [] exisiting_library = objc_provider_fields.get(key, depset([])) for f in exisiting_library.to_list(): check_key = f.basename if check_name else f if check_key in avoid_libraries: continue updated_library.append(f) objc_provider_fields[key] = depset(updated_library) def _dep_middleman(ctx): objc_providers = [] cc_providers = [] avoid_libraries = {} def _collect_providers(lib_dep): if apple_common.Objc in lib_dep: objc_providers.append(lib_dep[apple_common.Objc]) def _process_avoid_deps(avoid_dep_libs): for dep in avoid_dep_libs: if apple_common.Objc in dep: for lib in dep[apple_common.Objc].library.to_list(): avoid_libraries[lib] = True for lib in dep[apple_common.Objc].force_load_library.to_list(): avoid_libraries[lib] = True for lib in dep[apple_common.Objc].imported_library.to_list(): avoid_libraries[lib.basename] = True for lib in dep[apple_common.Objc].static_framework_file.to_list(): avoid_libraries[lib.basename] = True for dep in ctx.attr.deps: _collect_providers(dep) if AvoidDepsInfo in dep: _process_avoid_deps(dep[AvoidDepsInfo].libraries) for lib_dep in dep[AvoidDepsInfo].libraries: _collect_providers(lib_dep) for dep in ctx.attr.test_deps if ctx.attr.test_deps else []: if AvoidDepsInfo in dep: _process_avoid_deps(dep[AvoidDepsInfo].libraries) objc_provider_fields = objc_provider_utils.merge_objc_providers_dict(providers=objc_providers, merge_keys=['force_load_library', 'imported_library', 'library', 'link_inputs', 'linkopt', 'sdk_dylib', 'sdk_framework', 'source', 'static_framework_file', 'weak_sdk_framework']) _dedupe_key('library', avoid_libraries, objc_provider_fields) _dedupe_key('force_load_library', avoid_libraries, objc_provider_fields) _dedupe_key('imported_library', avoid_libraries, objc_provider_fields, check_name=True) _dedupe_key('static_framework_file', avoid_libraries, objc_provider_fields, check_name=True) objc_provider = apple_common.new_objc_provider(**objc_provider_fields) cc_info_provider = cc_common.merge_cc_infos(direct_cc_infos=[], cc_infos=cc_providers) providers = [cc_info_provider, objc_provider] return providers dep_middleman = rule(implementation=_dep_middleman, attrs={'deps': attr.label_list(cfg=apple_common.multi_arch_split, mandatory=True, doc='Deps that may contain frameworks\n'), 'test_deps': attr.label_list(cfg=apple_common.multi_arch_split, allow_empty=True), 'platform_type': attr.string(mandatory=False, doc='Internal - currently rules_ios uses the dict `platforms`\n'), 'minimum_os_version': attr.string(mandatory=False, doc='Internal - currently rules_ios the dict `platforms`\n')}, doc='\n This is a volatile internal rule to make frameworks work with\n rules_apples bundling logic\n\n Longer term, we will likely get rid of this and call partial like\n apple_framework directly so consider it an implementation detail\n ')
text = 'Writing to a file which\n' fileis = open('hello.txt', 'w') fileis.write(text) fileis.close()
text = 'Writing to a file which\n' fileis = open('hello.txt', 'w') fileis.write(text) fileis.close()
def gcd(p, q): pTrue = isinstance(p,int) qTrue = isinstance(q,int) if pTrue and qTrue: if q == 0: return p r = p%q return gcd(q,r) else: print("Error!") return 0
def gcd(p, q): p_true = isinstance(p, int) q_true = isinstance(q, int) if pTrue and qTrue: if q == 0: return p r = p % q return gcd(q, r) else: print('Error!') return 0
# -*- coding: utf-8 -*- keywords = { "abbrev", "abs", "abstime", "abstimeeq", "abstimege", "abstimegt", "abstimein", "abstimele", "abstimelt", "abstimene", "abstimeout", "abstimerecv", "abstimesend", "aclcontains", "aclinsert", "aclitemeq", "aclitemin", "aclitemout", "aclremove", "acos", "add_months", "aes128", "aes256", "age", "all", "alloc_rowid", "allowoverwrite", "alt_to_iso", "alt_to_koi8r", "alt_to_mic", "alt_to_win1251", "analyse", "analyze", "and", "any", "any_in", "any_out", "anyarray_in", "anyarray_out", "anyarray_recv", "anyarray_send", "anyelement_in", "anyelement_out", "area", "areajoinsel", "areasel", "array", "array_append", "array_cat", "array_coerce", "array_dims", "array_eq", "array_ge", "array_gt", "array_in", "array_le", "array_length_coerce", "array_lower", "array_lt", "array_ne", "array_out", "array_prepend", "array_recv", "array_send", "array_type_length_coerce", "array_upper", "as", "asc", "ascii", "ascii_to_mic", "asin", "atan", "atan2", "authorization", "avg", "az64", "backup", "between", "big5_to_euc_tw", "big5_to_mic", "binary", "bit", "bit_and", "bit_in", "bit_length", "bit_or", "bit_out", "bit_recv", "bit_send", "bitand", "bitcat", "bitcmp", "biteq", "bitge", "bitgt", "bitle", "bitlt", "bitne", "bitnot", "bitor", "bitxor", "blanksasnull", "bool", "bool_and", "bool_or", "booleq", "boolge", "boolgt", "boolin", "boolle", "boollt", "boolne", "boolout", "boolrecv", "boolsend", "both", "box", "box_above", "box_add", "box_below", "box_center", "box_contain", "box_contained", "box_distance", "box_div", "box_eq", "box_ge", "box_gt", "box_in", "box_intersect", "box_le", "box_lt", "box_mul", "box_out", "box_overlap", "box_recv", "box_same", "box_send", "box_sub", "bpchar", "bpchar_pattern_eq", "bpchar_pattern_ge", "bpchar_pattern_gt", "bpchar_pattern_le", "bpchar_pattern_lt", "bpchar_pattern_ne", "bpcharcmp", "bpchareq", "bpcharge", "bpchargt", "bpcharle", "bpcharlike", "bpcharlt", "bpcharne", "bpcharnlike", "bpcharout", "bpcharrecv", "bpcharregexeq", "bpcharregexne", "bpcharsend", "broadcast", "btabstimecmp", "btarraycmp", "btbeginscan", "btboolcmp", "btbpchar_pattern_cmp", "btbuild", "btbulkdelete", "btcharcmp", "btcostestimate", "btendscan", "btgettuple", "btinsert", "btint24cmp", "btint28cmp", "btint2cmp", "btint42cmp", "btint48cmp", "btint4cmp", "btint82cmp", "btint84cmp", "btint8cmp", "btmarkpos", "btname_pattern_cmp", "btnamecmp", "btoidcmp", "btoidvectorcmp", "btreltimecmp", "btrescan", "btrestrpos", "bttext_pattern_cmp", "bttextcmp", "bttintervalcmp", "btvacuumcleanup", "byteacat", "byteacmp", "byteaeq", "byteage", "byteagt", "byteain", "byteale", "bytealike", "bytealt", "byteane", "byteanlike", "byteaout", "bytearecv", "byteasend", "bytedict", "bzip2", "card_check", "case", "cash_cmp", "cash_div_int2", "cash_div_int4", "cash_eq", "cash_ge", "cash_gt", "cash_in", "cash_le", "cash_lt", "cash_mi", "cash_mul_int2", "cash_mul_int4", "cash_ne", "cash_out", "cash_pl", "cash_recv", "cash_send", "cash_words", "cashlarger", "cashsmaller", "cast", "cbrt", "ceil", "ceiling", "center", "char", "char_length", "character_length", "chareq", "charge", "chargt", "charle", "charlt", "charne", "charout", "charrecv", "charsend", "check", "checksum", "chr", "cideq", "cidin", "cidout", "cidr", "cidr_in", "cidr_out", "cidr_recv", "cidr_send", "cidrecv", "cidsend", "circle", "circle_above", "circle_add_pt", "circle_below", "circle_center", "circle_contain", "circle_contain_pt", "circle_contained", "circle_distance", "circle_div_pt", "circle_eq", "circle_ge", "circle_gt", "circle_in", "circle_le", "circle_lt", "circle_mul_pt", "circle_ne", "circle_out", "circle_overlap", "circle_recv", "circle_same", "circle_send", "circle_sub_pt", "close_lb", "close_ls", "close_lseg", "close_pb", "close_pl", "close_ps", "close_sb", "close_sl", "collate", "column", "concat", "constraint", "contains", "contjoinsel", "contsel", "convert", "convert_timezone", "convert_using", "cos", "cot", "count", "crc32", "create", "credentials", "cross", "cume_dist", "current_database", "current_date", "current_schema", "current_schemas", "current_setting", "current_time", "current_timestamp", "current_user", "current_user_id", "currtid", "currtid2", "currval", "cvtile_sf", "date", "date_add", "date_cmp", "date_cmp_timestamp", "date_cmp_timestamptz", "date_eq", "date_eq_timestamp", "date_eq_timestamptz", "date_ge", "date_ge_timestamp", "date_ge_timestamptz", "date_gt", "date_gt_timestamp", "date_gt_timestamptz", "date_in", "date_larger", "date_le", "date_le_timestamp", "date_le_timestamptz", "date_lt", "date_lt_timestamp", "date_lt_timestamptz", "date_mi", "date_mi_interval", "date_mii", "date_ne", "date_ne_timestamp", "date_ne_timestamptz", "date_out", "date_part", "date_part_year", "date_pl_interval", "date_pli", "date_recv", "date_send", "date_smaller", "date_trunc", "datetime_pl", "datetimetz_pl", "dcbrt", "default", "deferrable", "deflate", "defrag", "degrees", "delete_xid_column", "delta", "delta32k", "dense_rank", "desc", "dexp", "diagonal", "diameter", "disable", "dist_cpoly", "dist_lb", "dist_pb", "dist_pc", "dist_pl", "dist_ppath", "dist_ps", "dist_sb", "dist_sl", "distinct", "dlog1", "dlog10", "do", "dpow", "dround", "dsqrt", "dtrunc", "else", "emptyasnull", "enable", "encode", "encrypt ", "encryption", "end", "eqjoinsel", "eqsel", "erf", "euc_cn_to_mic", "euc_jp_to_mic", "euc_jp_to_sjis", "euc_kr_to_mic", "euc_tw_to_big5", "euc_tw_to_mic", "every", "except", "exp", "explicit", "false", "for", "foreign", "freeze", "from", "full", "geometry_analyze", "geometry_in", "geometry_out", "geometry_recv", "geometry_send", "geometrytype", "get_bit", "get_byte", "getdatabaseencoding", "getdate", "gistbeginscan", "gistbuild", "gistbulkdelete", "gistcostestimate", "gistendscan", "gistgettuple", "gistinsert", "gistmarkpos", "gistrescan", "gistrestrpos", "globaldict256", "globaldict64k", "grant", "group", "gzip", "hash_aclitem", "hashbeginscan", "hashbpchar", "hashbuild", "hashbulkdelete", "hashchar", "hashcostestimate", "hashendscan", "hashgettuple", "hashinet", "hashinsert", "hashint2", "hashint2vector", "hashint4", "hashint8", "hashmacaddr", "hashmarkpos", "hashname", "hashoid", "hashoidvector", "hashrescan", "hashrestrpos", "hashtext", "hashvarlena", "haversine_distance_km", "haversine_distance_km2", "having", "height", "hll_cardinality_16", "hll_cardinality_32", "host", "hostmask", "iclikejoinsel", "iclikesel", "icnlikejoinsel", "icnlikesel", "icregexeqjoinsel", "icregexeqsel", "icregexnejoinsel", "icregexnesel", "identity", "ignore", "ilike", "in", "inet", "inet_client_addr", "inet_client_port", "inet_in", "inet_out", "inet_recv", "inet_send", "inet_server_addr", "inet_server_port", "initcap", "initially", "inner", "int2", "int24div", "int24eq", "int24ge", "int24gt", "int24le", "int24lt", "int24mi", "int24mod", "int24mul", "int24ne", "int24pl", "int28div", "int28eq", "int28ge", "int28gt", "int28le", "int28lt", "int28mi", "int28mul", "int28ne", "int28pl", "int2_accum", "int2_avg_accum", "int2_mul_cash", "int2_sum", "int2abs", "int2and", "int2div", "int2eq", "int2ge", "int2gt", "int2in", "int2larger", "int2le", "int2lt", "int2mi", "int2mod", "int2mul", "int2ne", "int2not", "int2or", "int2out", "int2pl", "int2recv", "int2send", "int2shl", "int2shr", "int2smaller", "int2um", "int2up", "int2vectoreq", "int2vectorout", "int2vectorrecv", "int2vectorsend", "int2xor", "int4", "int42div", "int42eq", "int42ge", "int42gt", "int42le", "int42lt", "int42mi", "int42mod", "int42mul", "int42ne", "int42pl", "int48div", "int48eq", "int48ge", "int48gt", "int48le", "int48lt", "int48mi", "int48mul", "int48ne", "int48pl", "int4_accum", "int4_avg_accum", "int4_mul_cash", "int4_sum", "int4abs", "int4and", "int4div", "int4eq", "int4ge", "int4gt", "int4in", "int4inc", "int4larger", "int4le", "int4lt", "int4mi", "int4mod", "int4mul", "int4ne", "int4not", "int4or", "int4out", "int4pl", "int4recv", "int4send", "int4shl", "int4shr", "int4smaller", "int4um", "int4up", "int4xor", "int8", "int82div", "int82eq", "int82ge", "int82gt", "int82le", "int82lt", "int82mi", "int82mul", "int82ne", "int82pl", "int84div", "int84eq", "int84ge", "int84gt", "int84le", "int84lt", "int84mi", "int84mul", "int84ne", "int84pl", "int8_accum", "int8_avg", "int8_avg_accum", "int8_pl_timestamp", "int8_pl_timestamptz", "int8_sum", "int8abs", "int8and", "int8div", "int8eq", "int8ge", "int8gt", "int8in", "int8inc", "int8larger", "int8le", "int8lt", "int8mi", "int8mod", "int8mul", "int8ne", "int8not", "int8or", "int8out", "int8pl", "int8recv", "int8send", "int8shl", "int8shr", "int8smaller", "int8um", "int8up", "int8xor", "integer_pl_date", "inter_lb", "inter_sb", "inter_sl", "internal_in", "internal_out", "intersect", "interval", "interval_accum", "interval_avg", "interval_cmp", "interval_div", "interval_eq", "interval_ge", "interval_gt", "interval_hash", "interval_in", "interval_larger", "interval_le", "interval_lt", "interval_mi", "interval_mul", "interval_ne", "interval_out", "interval_pl", "interval_pl_date", "interval_pl_time", "interval_pl_timestamp", "interval_pl_timestamptz", "interval_pl_timetz", "interval_recv", "interval_send", "interval_smaller", "interval_um", "intinterval", "into", "ip_aton", "ip_masking", "ip_ntoa", "is", "is_ssl_connection", "is_valid_json", "is_valid_json_array", "isclosed", "isnottrue", "isnull", "iso_to_alt", "iso_to_koi8r", "iso_to_mic", "iso_to_win1251", "isopen", "isparallel", "isperp", "istrue", "isvertical", "join", "json_array_length", "json_extract_array_element_text", "json_extract_path_text", "koi8r_to_alt", "koi8r_to_iso", "koi8r_to_mic", "koi8r_to_win1251", "lag", "language", "language_handler_in", "language_handler_out", "last_day", "last_value", "latin1_to_mic", "latin2_to_mic", "latin2_to_win1250", "latin3_to_mic", "latin4_to_mic", "lead", "leading", "left", "len", "length", "like", "like_escape", "likejoinsel", "likesel", "limit", "line", "line_distance", "line_eq", "line_in", "line_interpt", "line_intersect", "line_out", "line_parallel", "line_perp", "line_recv", "line_send", "line_vertical", "listagg", "listaggdistinct", "ln", "lo_close", "lo_creat", "lo_export", "lo_import", "lo_lseek", "lo_open", "lo_tell", "lo_unlink", "localtime", "localtimestamp", "log", "logistic", "loread", "lower", "lpad", "lseg", "lseg_center", "lseg_distance", "lseg_eq", "lseg_ge", "lseg_gt", "lseg_in", "lseg_interpt", "lseg_intersect", "lseg_le", "lseg_length", "lseg_lt", "lseg_ne", "lseg_out", "lseg_parallel", "lseg_perp", "lseg_recv", "lseg_send", "lseg_vertical", "lun", "luns", "lzo", "lzop", "macaddr", "macaddr_cmp", "macaddr_eq", "macaddr_ge", "macaddr_gt", "macaddr_in", "macaddr_le", "macaddr_lt", "macaddr_ne", "macaddr_out", "macaddr_recv", "macaddr_send", "makeaclitem", "masklen", "max", "md5", "median", "mic_to_alt", "mic_to_ascii", "mic_to_big5", "mic_to_euc_cn", "mic_to_euc_jp", "mic_to_euc_kr", "mic_to_euc_tw", "mic_to_iso", "mic_to_koi8r", "mic_to_latin1", "mic_to_latin2", "mic_to_latin3", "mic_to_latin4", "mic_to_sjis", "mic_to_win1250", "mic_to_win1251", "min", "minus", "mktinterval", "mod", "months_between", "mos_score", "mostly13", "mostly32", "mostly8", "mul_d_interval", "name", "name_pattern_eq", "name_pattern_ge", "name_pattern_gt", "name_pattern_le", "name_pattern_lt", "name_pattern_ne", "nameeq", "namege", "namegt", "nameiclike", "nameicnlike", "nameicregexeq", "nameicregexne", "namein", "namele", "namelike", "namelt", "namene", "namenlike", "nameout", "namerecv", "nameregexeq", "nameregexne", "namesend", "natural", "neqjoinsel", "neqsel", "netmask", "network", "network_cmp", "network_eq", "network_ge", "network_gt", "network_le", "network_lt", "network_ne", "network_sub", "network_subeq", "network_sup", "network_supeq", "new", "next_day", "nextval", "nlikejoinsel", "nlikesel", "node_num", "nonnullvalue", "not", "notlike", "notnull", "now", "npoints", "nth_value", "ntile", "null", "nulls", "nullvalue", "nvl2", "octet_length", "off", "offline", "offset", "oid", "oideq", "oidge", "oidgt", "oidin", "oidlarger", "oidle", "oidlt", "oidne", "oidout", "oidrecv", "oidsend", "oidsmaller", "oidvectoreq", "oidvectorge", "oidvectorgt", "oidvectorle", "oidvectorlt", "oidvectorne", "oidvectorout", "oidvectorrecv", "oidvectorsend", "oidvectortypes", "old", "on", "on_pb", "on_pl", "on_ppath", "on_ps", "on_sb", "on_sl", "only", "opaque_in", "opaque_out", "open", "or", "order", "outer", "overlaps", "parallel", "partition", "path", "path_add", "path_add_pt", "path_center", "path_contain_pt", "path_distance", "path_div_pt", "path_in", "path_inter", "path_length", "path_mul_pt", "path_n_eq", "path_n_ge", "path_n_gt", "path_n_le", "path_n_lt", "path_npoints", "path_out", "path_recv", "path_send", "path_sub_pt", "pclose", "percent", "percent_rank", "percentile_cont", "percentile_disc", "permissions", "pg_backend_pid", "pg_cancel_backend", "pg_char_to_encoding", "pg_client_encoding", "pg_conversion_is_visible", "pg_decode", "pg_encoding_to_char", "pg_get_cols", "pg_get_constraintdef", "pg_get_current_groups", "pg_get_expr", "pg_get_external_columns", "pg_get_external_tables", "pg_get_indexdef", "pg_get_late_binding_view_cols", "pg_get_ruledef", "pg_get_userbyid", "pg_get_viewdef", "pg_last_copy_count", "pg_last_copy_id", "pg_last_query_id", "pg_last_unload_count", "pg_last_unload_id", "pg_lock_status", "pg_opclass_is_visible", "pg_operator_is_visible", "pg_postmaster_start_time", "pg_show_all_settings", "pg_sleep", "pg_start_backup", "pg_stat_get_backend_activity", "pg_stat_get_backend_activity_start", "pg_stat_get_backend_dbid", "pg_stat_get_backend_idset", "pg_stat_get_backend_pid", "pg_stat_get_blocks_hit", "pg_stat_get_db_blocks_hit", "pg_stat_get_db_numbackends", "pg_stat_get_db_xact_commit", "pg_stat_get_db_xact_rollback", "pg_stat_get_numscans", "pg_stat_get_tuples_deleted", "pg_stat_get_tuples_inserted", "pg_stat_get_tuples_returned", "pg_stat_get_tuples_updated", "pg_stat_reset", "pg_stop_backup", "pg_table_is_visible", "pg_tablespace_databases", "pg_terminate_backend", "pg_timezone_abbrevs", "pg_timezone_names", "pg_type_is_visible", "pgdate_part", "pi", "placing", "plpython_call_handler", "plpython_compiler", "point", "point_above", "point_add", "point_below", "point_distance", "point_div", "point_eq", "point_in", "point_mul", "point_ne", "point_out", "point_recv", "point_send", "point_sub", "point_vert", "poly_center", "poly_contain", "poly_contain_pt", "poly_contained", "poly_distance", "poly_in", "poly_npoints", "poly_out", "poly_overlap", "poly_recv", "poly_same", "poly_send", "polygon", "popen", "position", "positionjoinsel", "positionsel", "pow", "power", "primary", "pt_contained_circle", "pt_contained_poly", "qsummary", "quote_ident", "quote_literal", "radians", "radius", "random", "rank", "rankx", "ratio_to_report", "raw", "readratio", "record_in", "record_out", "record_recv", "record_send", "recover", "references", "regclassin", "regclassout", "regclassrecv", "regclasssend", "regexeqjoinsel", "regexeqsel", "regexnejoinsel", "regexnesel", "regexp_count", "regexp_instr", "regexp_replace", "regexp_substr", "regoperatorout", "regoperatorrecv", "regoperatorsend", "regoperout", "regoperrecv", "regopersend", "regprocedurein", "regprocedureout", "regprocedurerecv", "regproceduresend", "regprocin", "regprocout", "regprocrecv", "regprocsend", "regtypein", "regtypeout", "regtyperecv", "regtypesend", "rejectlog", "reltime", "reltimeeq", "reltimege", "reltimegt", "reltimein", "reltimele", "reltimelt", "reltimene", "reltimeout", "reltimerecv", "reltimesend", "relu", "remaining_vacrows", "repeat", "replace", "replicate", "resort", "respect", "restore", "return_approx_percentile", "reverse", "right", "round", "row_number", "rownumber", "rpad", "rt_box_inter", "rt_box_size", "rt_box_union", "rt_poly_inter", "rt_poly_size", "rt_poly_union", "rtbeginscan", "rtbuild", "rtbulkdelete", "rtcostestimate", "rtendscan", "rtgettuple", "rtinsert", "rtmarkpos", "rtrescan", "rtrestrpos", "scalargtjoinsel", "scalargtsel", "scalarltjoinsel", "scalarltsel", "select", "session_user", "set_bit", "set_byte", "set_masklen", "setval", "sig_bucket_3g", "sig_bucket_lte", "sig_score_3g", "sig_score_lte", "sigmoid", "sign", "similar", "similar_escape", "sin", "sjis_to_euc_jp", "sjis_to_mic", "slice_num", "slope", "smgreq", "smgrne", "smgrout", "snapshot ", "some", "sort_avail_mem", "sortbytes", "split_part", "sqrt", "ssl_version", "st_asbinary", "st_asewkb", "st_asewkt", "st_astext", "st_azimuth", "st_contains", "st_dimension", "st_disjoint", "st_distance", "st_dwithin", "st_equals", "st_geometrytype", "st_intersects", "st_isclosed", "st_iscollection", "st_isempty", "st_makeline", "st_makepoint", "st_makepolygon", "st_npoints", "st_numpoints", "st_point", "st_polygon", "st_within", "st_x", "st_xmax", "st_xmin", "st_y", "st_ymax", "st_ymin", "stddev", "stddev_pop", "strpos", "strtol", "substr", "sum", "sysdate", "system", "table", "tablebytes", "tag", "tan", "tdes", "text", "text255", "text32k", "text_ge", "text_gt", "text_larger", "text_le", "text_lt", "text_pattern_eq", "text_pattern_ge", "text_pattern_gt", "text_pattern_le", "text_pattern_lt", "text_pattern_ne", "text_smaller", "textcat", "texteq", "texticlike", "texticnlike", "texticregexeq", "texticregexne", "textin", "textlen", "textlike", "textne", "textnlike", "textout", "textrecv", "textregexeq", "textregexne", "textsend", "then", "tideq", "tidin", "tidout", "tidrecv", "tidsend", "time", "time_cmp", "time_eq", "time_ge", "time_gt", "time_in", "time_larger", "time_le", "time_lt", "time_mi_interval", "time_mi_time", "time_ne", "time_out", "time_pl_interval", "time_recv", "time_send", "time_smaller", "timedate_pl", "timemi", "timenow", "timepl", "timestamp", "timestamp_cmp", "timestamp_cmp_date", "timestamp_cmp_timestamptz", "timestamp_eq", "timestamp_eq_date", "timestamp_eq_timestamptz", "timestamp_ge", "timestamp_ge_date", "timestamp_ge_timestamptz", "timestamp_gt", "timestamp_gt_date", "timestamp_gt_timestamptz", "timestamp_in", "timestamp_larger", "timestamp_le", "timestamp_le_date", "timestamp_le_timestamptz", "timestamp_lt", "timestamp_lt_date", "timestamp_lt_timestamptz", "timestamp_mi", "timestamp_mi_int8", "timestamp_mi_interval", "timestamp_ne", "timestamp_ne_date", "timestamp_ne_timestamptz", "timestamp_out", "timestamp_pl_int8", "timestamp_pl_interval", "timestamp_recv", "timestamp_send", "timestamp_smaller", "timestamptz", "timestamptz_cmp", "timestamptz_cmp_date", "timestamptz_cmp_timestamp", "timestamptz_eq", "timestamptz_eq_date", "timestamptz_eq_timestamp", "timestamptz_ge", "timestamptz_ge_date", "timestamptz_ge_timestamp", "timestamptz_gt", "timestamptz_gt_date", "timestamptz_gt_timestamp", "timestamptz_in", "timestamptz_larger", "timestamptz_le", "timestamptz_le_date", "timestamptz_le_timestamp", "timestamptz_lt", "timestamptz_lt_date", "timestamptz_lt_timestamp", "timestamptz_mi", "timestamptz_mi_int8", "timestamptz_mi_interval", "timestamptz_ne", "timestamptz_ne_date", "timestamptz_ne_timestamp", "timestamptz_out", "timestamptz_pl_int8", "timestamptz_pl_interval", "timestamptz_recv", "timestamptz_send", "timestamptz_smaller", "timetz", "timetz_cmp", "timetz_eq", "timetz_ge", "timetz_gt", "timetz_hash", "timetz_in", "timetz_larger", "timetz_le", "timetz_lt", "timetz_mi_interval", "timetz_ne", "timetz_out", "timetz_pl_interval", "timetz_recv", "timetz_send", "timetz_smaller", "timetzdate_pl", "timezone", "tinterval", "tintervalct", "tintervalend", "tintervaleq", "tintervalge", "tintervalgt", "tintervalin", "tintervalle", "tintervalleneq", "tintervallenge", "tintervallengt", "tintervallenle", "tintervallenlt", "tintervallenne", "tintervallt", "tintervalne", "tintervalout", "tintervalov", "tintervalrecv", "tintervalrel", "tintervalsame", "tintervalsend", "tintervalstart", "to", "to_ascii", "to_char", "to_date", "to_hex", "to_number", "to_timestamp", "tobpchar", "top", "total_num_deleted_vacrows", "total_num_deleted_vacrows_reclaimed", "trailing", "translate", "true", "trunc", "truncatecolumns", "union", "unique", "unknownin", "unknownout", "unknownrecv", "unknownsend", "upper", "user", "using", "vacstate_endrow", "vacstate_last_inserted_row", "var_pop", "varbit", "varbit_in", "varbit_out", "varbit_recv", "varbit_send", "varbitcmp", "varbiteq", "varbitge", "varbitgt", "varbitle", "varbitlt", "varbitne", "varchar", "varcharout", "varcharrecv", "varcharsend", "verbose", "version", "void_in", "void_out", "wallet", "when", "where", "width", "width_bucket", "win1250_to_latin2", "win1250_to_mic", "win1250_to_utf", "win1251_to_alt", "win1251_to_iso", "win1251_to_koi8r", "win1251_to_mic", "win1256_to_utf", "win874_to_utf", "with", "without", "xideq", "xideqint4", "xidin", "xidout", "xidrecv", "xidsend", }
keywords = {'abbrev', 'abs', 'abstime', 'abstimeeq', 'abstimege', 'abstimegt', 'abstimein', 'abstimele', 'abstimelt', 'abstimene', 'abstimeout', 'abstimerecv', 'abstimesend', 'aclcontains', 'aclinsert', 'aclitemeq', 'aclitemin', 'aclitemout', 'aclremove', 'acos', 'add_months', 'aes128', 'aes256', 'age', 'all', 'alloc_rowid', 'allowoverwrite', 'alt_to_iso', 'alt_to_koi8r', 'alt_to_mic', 'alt_to_win1251', 'analyse', 'analyze', 'and', 'any', 'any_in', 'any_out', 'anyarray_in', 'anyarray_out', 'anyarray_recv', 'anyarray_send', 'anyelement_in', 'anyelement_out', 'area', 'areajoinsel', 'areasel', 'array', 'array_append', 'array_cat', 'array_coerce', 'array_dims', 'array_eq', 'array_ge', 'array_gt', 'array_in', 'array_le', 'array_length_coerce', 'array_lower', 'array_lt', 'array_ne', 'array_out', 'array_prepend', 'array_recv', 'array_send', 'array_type_length_coerce', 'array_upper', 'as', 'asc', 'ascii', 'ascii_to_mic', 'asin', 'atan', 'atan2', 'authorization', 'avg', 'az64', 'backup', 'between', 'big5_to_euc_tw', 'big5_to_mic', 'binary', 'bit', 'bit_and', 'bit_in', 'bit_length', 'bit_or', 'bit_out', 'bit_recv', 'bit_send', 'bitand', 'bitcat', 'bitcmp', 'biteq', 'bitge', 'bitgt', 'bitle', 'bitlt', 'bitne', 'bitnot', 'bitor', 'bitxor', 'blanksasnull', 'bool', 'bool_and', 'bool_or', 'booleq', 'boolge', 'boolgt', 'boolin', 'boolle', 'boollt', 'boolne', 'boolout', 'boolrecv', 'boolsend', 'both', 'box', 'box_above', 'box_add', 'box_below', 'box_center', 'box_contain', 'box_contained', 'box_distance', 'box_div', 'box_eq', 'box_ge', 'box_gt', 'box_in', 'box_intersect', 'box_le', 'box_lt', 'box_mul', 'box_out', 'box_overlap', 'box_recv', 'box_same', 'box_send', 'box_sub', 'bpchar', 'bpchar_pattern_eq', 'bpchar_pattern_ge', 'bpchar_pattern_gt', 'bpchar_pattern_le', 'bpchar_pattern_lt', 'bpchar_pattern_ne', 'bpcharcmp', 'bpchareq', 'bpcharge', 'bpchargt', 'bpcharle', 'bpcharlike', 'bpcharlt', 'bpcharne', 'bpcharnlike', 'bpcharout', 'bpcharrecv', 'bpcharregexeq', 'bpcharregexne', 'bpcharsend', 'broadcast', 'btabstimecmp', 'btarraycmp', 'btbeginscan', 'btboolcmp', 'btbpchar_pattern_cmp', 'btbuild', 'btbulkdelete', 'btcharcmp', 'btcostestimate', 'btendscan', 'btgettuple', 'btinsert', 'btint24cmp', 'btint28cmp', 'btint2cmp', 'btint42cmp', 'btint48cmp', 'btint4cmp', 'btint82cmp', 'btint84cmp', 'btint8cmp', 'btmarkpos', 'btname_pattern_cmp', 'btnamecmp', 'btoidcmp', 'btoidvectorcmp', 'btreltimecmp', 'btrescan', 'btrestrpos', 'bttext_pattern_cmp', 'bttextcmp', 'bttintervalcmp', 'btvacuumcleanup', 'byteacat', 'byteacmp', 'byteaeq', 'byteage', 'byteagt', 'byteain', 'byteale', 'bytealike', 'bytealt', 'byteane', 'byteanlike', 'byteaout', 'bytearecv', 'byteasend', 'bytedict', 'bzip2', 'card_check', 'case', 'cash_cmp', 'cash_div_int2', 'cash_div_int4', 'cash_eq', 'cash_ge', 'cash_gt', 'cash_in', 'cash_le', 'cash_lt', 'cash_mi', 'cash_mul_int2', 'cash_mul_int4', 'cash_ne', 'cash_out', 'cash_pl', 'cash_recv', 'cash_send', 'cash_words', 'cashlarger', 'cashsmaller', 'cast', 'cbrt', 'ceil', 'ceiling', 'center', 'char', 'char_length', 'character_length', 'chareq', 'charge', 'chargt', 'charle', 'charlt', 'charne', 'charout', 'charrecv', 'charsend', 'check', 'checksum', 'chr', 'cideq', 'cidin', 'cidout', 'cidr', 'cidr_in', 'cidr_out', 'cidr_recv', 'cidr_send', 'cidrecv', 'cidsend', 'circle', 'circle_above', 'circle_add_pt', 'circle_below', 'circle_center', 'circle_contain', 'circle_contain_pt', 'circle_contained', 'circle_distance', 'circle_div_pt', 'circle_eq', 'circle_ge', 'circle_gt', 'circle_in', 'circle_le', 'circle_lt', 'circle_mul_pt', 'circle_ne', 'circle_out', 'circle_overlap', 'circle_recv', 'circle_same', 'circle_send', 'circle_sub_pt', 'close_lb', 'close_ls', 'close_lseg', 'close_pb', 'close_pl', 'close_ps', 'close_sb', 'close_sl', 'collate', 'column', 'concat', 'constraint', 'contains', 'contjoinsel', 'contsel', 'convert', 'convert_timezone', 'convert_using', 'cos', 'cot', 'count', 'crc32', 'create', 'credentials', 'cross', 'cume_dist', 'current_database', 'current_date', 'current_schema', 'current_schemas', 'current_setting', 'current_time', 'current_timestamp', 'current_user', 'current_user_id', 'currtid', 'currtid2', 'currval', 'cvtile_sf', 'date', 'date_add', 'date_cmp', 'date_cmp_timestamp', 'date_cmp_timestamptz', 'date_eq', 'date_eq_timestamp', 'date_eq_timestamptz', 'date_ge', 'date_ge_timestamp', 'date_ge_timestamptz', 'date_gt', 'date_gt_timestamp', 'date_gt_timestamptz', 'date_in', 'date_larger', 'date_le', 'date_le_timestamp', 'date_le_timestamptz', 'date_lt', 'date_lt_timestamp', 'date_lt_timestamptz', 'date_mi', 'date_mi_interval', 'date_mii', 'date_ne', 'date_ne_timestamp', 'date_ne_timestamptz', 'date_out', 'date_part', 'date_part_year', 'date_pl_interval', 'date_pli', 'date_recv', 'date_send', 'date_smaller', 'date_trunc', 'datetime_pl', 'datetimetz_pl', 'dcbrt', 'default', 'deferrable', 'deflate', 'defrag', 'degrees', 'delete_xid_column', 'delta', 'delta32k', 'dense_rank', 'desc', 'dexp', 'diagonal', 'diameter', 'disable', 'dist_cpoly', 'dist_lb', 'dist_pb', 'dist_pc', 'dist_pl', 'dist_ppath', 'dist_ps', 'dist_sb', 'dist_sl', 'distinct', 'dlog1', 'dlog10', 'do', 'dpow', 'dround', 'dsqrt', 'dtrunc', 'else', 'emptyasnull', 'enable', 'encode', 'encrypt ', 'encryption', 'end', 'eqjoinsel', 'eqsel', 'erf', 'euc_cn_to_mic', 'euc_jp_to_mic', 'euc_jp_to_sjis', 'euc_kr_to_mic', 'euc_tw_to_big5', 'euc_tw_to_mic', 'every', 'except', 'exp', 'explicit', 'false', 'for', 'foreign', 'freeze', 'from', 'full', 'geometry_analyze', 'geometry_in', 'geometry_out', 'geometry_recv', 'geometry_send', 'geometrytype', 'get_bit', 'get_byte', 'getdatabaseencoding', 'getdate', 'gistbeginscan', 'gistbuild', 'gistbulkdelete', 'gistcostestimate', 'gistendscan', 'gistgettuple', 'gistinsert', 'gistmarkpos', 'gistrescan', 'gistrestrpos', 'globaldict256', 'globaldict64k', 'grant', 'group', 'gzip', 'hash_aclitem', 'hashbeginscan', 'hashbpchar', 'hashbuild', 'hashbulkdelete', 'hashchar', 'hashcostestimate', 'hashendscan', 'hashgettuple', 'hashinet', 'hashinsert', 'hashint2', 'hashint2vector', 'hashint4', 'hashint8', 'hashmacaddr', 'hashmarkpos', 'hashname', 'hashoid', 'hashoidvector', 'hashrescan', 'hashrestrpos', 'hashtext', 'hashvarlena', 'haversine_distance_km', 'haversine_distance_km2', 'having', 'height', 'hll_cardinality_16', 'hll_cardinality_32', 'host', 'hostmask', 'iclikejoinsel', 'iclikesel', 'icnlikejoinsel', 'icnlikesel', 'icregexeqjoinsel', 'icregexeqsel', 'icregexnejoinsel', 'icregexnesel', 'identity', 'ignore', 'ilike', 'in', 'inet', 'inet_client_addr', 'inet_client_port', 'inet_in', 'inet_out', 'inet_recv', 'inet_send', 'inet_server_addr', 'inet_server_port', 'initcap', 'initially', 'inner', 'int2', 'int24div', 'int24eq', 'int24ge', 'int24gt', 'int24le', 'int24lt', 'int24mi', 'int24mod', 'int24mul', 'int24ne', 'int24pl', 'int28div', 'int28eq', 'int28ge', 'int28gt', 'int28le', 'int28lt', 'int28mi', 'int28mul', 'int28ne', 'int28pl', 'int2_accum', 'int2_avg_accum', 'int2_mul_cash', 'int2_sum', 'int2abs', 'int2and', 'int2div', 'int2eq', 'int2ge', 'int2gt', 'int2in', 'int2larger', 'int2le', 'int2lt', 'int2mi', 'int2mod', 'int2mul', 'int2ne', 'int2not', 'int2or', 'int2out', 'int2pl', 'int2recv', 'int2send', 'int2shl', 'int2shr', 'int2smaller', 'int2um', 'int2up', 'int2vectoreq', 'int2vectorout', 'int2vectorrecv', 'int2vectorsend', 'int2xor', 'int4', 'int42div', 'int42eq', 'int42ge', 'int42gt', 'int42le', 'int42lt', 'int42mi', 'int42mod', 'int42mul', 'int42ne', 'int42pl', 'int48div', 'int48eq', 'int48ge', 'int48gt', 'int48le', 'int48lt', 'int48mi', 'int48mul', 'int48ne', 'int48pl', 'int4_accum', 'int4_avg_accum', 'int4_mul_cash', 'int4_sum', 'int4abs', 'int4and', 'int4div', 'int4eq', 'int4ge', 'int4gt', 'int4in', 'int4inc', 'int4larger', 'int4le', 'int4lt', 'int4mi', 'int4mod', 'int4mul', 'int4ne', 'int4not', 'int4or', 'int4out', 'int4pl', 'int4recv', 'int4send', 'int4shl', 'int4shr', 'int4smaller', 'int4um', 'int4up', 'int4xor', 'int8', 'int82div', 'int82eq', 'int82ge', 'int82gt', 'int82le', 'int82lt', 'int82mi', 'int82mul', 'int82ne', 'int82pl', 'int84div', 'int84eq', 'int84ge', 'int84gt', 'int84le', 'int84lt', 'int84mi', 'int84mul', 'int84ne', 'int84pl', 'int8_accum', 'int8_avg', 'int8_avg_accum', 'int8_pl_timestamp', 'int8_pl_timestamptz', 'int8_sum', 'int8abs', 'int8and', 'int8div', 'int8eq', 'int8ge', 'int8gt', 'int8in', 'int8inc', 'int8larger', 'int8le', 'int8lt', 'int8mi', 'int8mod', 'int8mul', 'int8ne', 'int8not', 'int8or', 'int8out', 'int8pl', 'int8recv', 'int8send', 'int8shl', 'int8shr', 'int8smaller', 'int8um', 'int8up', 'int8xor', 'integer_pl_date', 'inter_lb', 'inter_sb', 'inter_sl', 'internal_in', 'internal_out', 'intersect', 'interval', 'interval_accum', 'interval_avg', 'interval_cmp', 'interval_div', 'interval_eq', 'interval_ge', 'interval_gt', 'interval_hash', 'interval_in', 'interval_larger', 'interval_le', 'interval_lt', 'interval_mi', 'interval_mul', 'interval_ne', 'interval_out', 'interval_pl', 'interval_pl_date', 'interval_pl_time', 'interval_pl_timestamp', 'interval_pl_timestamptz', 'interval_pl_timetz', 'interval_recv', 'interval_send', 'interval_smaller', 'interval_um', 'intinterval', 'into', 'ip_aton', 'ip_masking', 'ip_ntoa', 'is', 'is_ssl_connection', 'is_valid_json', 'is_valid_json_array', 'isclosed', 'isnottrue', 'isnull', 'iso_to_alt', 'iso_to_koi8r', 'iso_to_mic', 'iso_to_win1251', 'isopen', 'isparallel', 'isperp', 'istrue', 'isvertical', 'join', 'json_array_length', 'json_extract_array_element_text', 'json_extract_path_text', 'koi8r_to_alt', 'koi8r_to_iso', 'koi8r_to_mic', 'koi8r_to_win1251', 'lag', 'language', 'language_handler_in', 'language_handler_out', 'last_day', 'last_value', 'latin1_to_mic', 'latin2_to_mic', 'latin2_to_win1250', 'latin3_to_mic', 'latin4_to_mic', 'lead', 'leading', 'left', 'len', 'length', 'like', 'like_escape', 'likejoinsel', 'likesel', 'limit', 'line', 'line_distance', 'line_eq', 'line_in', 'line_interpt', 'line_intersect', 'line_out', 'line_parallel', 'line_perp', 'line_recv', 'line_send', 'line_vertical', 'listagg', 'listaggdistinct', 'ln', 'lo_close', 'lo_creat', 'lo_export', 'lo_import', 'lo_lseek', 'lo_open', 'lo_tell', 'lo_unlink', 'localtime', 'localtimestamp', 'log', 'logistic', 'loread', 'lower', 'lpad', 'lseg', 'lseg_center', 'lseg_distance', 'lseg_eq', 'lseg_ge', 'lseg_gt', 'lseg_in', 'lseg_interpt', 'lseg_intersect', 'lseg_le', 'lseg_length', 'lseg_lt', 'lseg_ne', 'lseg_out', 'lseg_parallel', 'lseg_perp', 'lseg_recv', 'lseg_send', 'lseg_vertical', 'lun', 'luns', 'lzo', 'lzop', 'macaddr', 'macaddr_cmp', 'macaddr_eq', 'macaddr_ge', 'macaddr_gt', 'macaddr_in', 'macaddr_le', 'macaddr_lt', 'macaddr_ne', 'macaddr_out', 'macaddr_recv', 'macaddr_send', 'makeaclitem', 'masklen', 'max', 'md5', 'median', 'mic_to_alt', 'mic_to_ascii', 'mic_to_big5', 'mic_to_euc_cn', 'mic_to_euc_jp', 'mic_to_euc_kr', 'mic_to_euc_tw', 'mic_to_iso', 'mic_to_koi8r', 'mic_to_latin1', 'mic_to_latin2', 'mic_to_latin3', 'mic_to_latin4', 'mic_to_sjis', 'mic_to_win1250', 'mic_to_win1251', 'min', 'minus', 'mktinterval', 'mod', 'months_between', 'mos_score', 'mostly13', 'mostly32', 'mostly8', 'mul_d_interval', 'name', 'name_pattern_eq', 'name_pattern_ge', 'name_pattern_gt', 'name_pattern_le', 'name_pattern_lt', 'name_pattern_ne', 'nameeq', 'namege', 'namegt', 'nameiclike', 'nameicnlike', 'nameicregexeq', 'nameicregexne', 'namein', 'namele', 'namelike', 'namelt', 'namene', 'namenlike', 'nameout', 'namerecv', 'nameregexeq', 'nameregexne', 'namesend', 'natural', 'neqjoinsel', 'neqsel', 'netmask', 'network', 'network_cmp', 'network_eq', 'network_ge', 'network_gt', 'network_le', 'network_lt', 'network_ne', 'network_sub', 'network_subeq', 'network_sup', 'network_supeq', 'new', 'next_day', 'nextval', 'nlikejoinsel', 'nlikesel', 'node_num', 'nonnullvalue', 'not', 'notlike', 'notnull', 'now', 'npoints', 'nth_value', 'ntile', 'null', 'nulls', 'nullvalue', 'nvl2', 'octet_length', 'off', 'offline', 'offset', 'oid', 'oideq', 'oidge', 'oidgt', 'oidin', 'oidlarger', 'oidle', 'oidlt', 'oidne', 'oidout', 'oidrecv', 'oidsend', 'oidsmaller', 'oidvectoreq', 'oidvectorge', 'oidvectorgt', 'oidvectorle', 'oidvectorlt', 'oidvectorne', 'oidvectorout', 'oidvectorrecv', 'oidvectorsend', 'oidvectortypes', 'old', 'on', 'on_pb', 'on_pl', 'on_ppath', 'on_ps', 'on_sb', 'on_sl', 'only', 'opaque_in', 'opaque_out', 'open', 'or', 'order', 'outer', 'overlaps', 'parallel', 'partition', 'path', 'path_add', 'path_add_pt', 'path_center', 'path_contain_pt', 'path_distance', 'path_div_pt', 'path_in', 'path_inter', 'path_length', 'path_mul_pt', 'path_n_eq', 'path_n_ge', 'path_n_gt', 'path_n_le', 'path_n_lt', 'path_npoints', 'path_out', 'path_recv', 'path_send', 'path_sub_pt', 'pclose', 'percent', 'percent_rank', 'percentile_cont', 'percentile_disc', 'permissions', 'pg_backend_pid', 'pg_cancel_backend', 'pg_char_to_encoding', 'pg_client_encoding', 'pg_conversion_is_visible', 'pg_decode', 'pg_encoding_to_char', 'pg_get_cols', 'pg_get_constraintdef', 'pg_get_current_groups', 'pg_get_expr', 'pg_get_external_columns', 'pg_get_external_tables', 'pg_get_indexdef', 'pg_get_late_binding_view_cols', 'pg_get_ruledef', 'pg_get_userbyid', 'pg_get_viewdef', 'pg_last_copy_count', 'pg_last_copy_id', 'pg_last_query_id', 'pg_last_unload_count', 'pg_last_unload_id', 'pg_lock_status', 'pg_opclass_is_visible', 'pg_operator_is_visible', 'pg_postmaster_start_time', 'pg_show_all_settings', 'pg_sleep', 'pg_start_backup', 'pg_stat_get_backend_activity', 'pg_stat_get_backend_activity_start', 'pg_stat_get_backend_dbid', 'pg_stat_get_backend_idset', 'pg_stat_get_backend_pid', 'pg_stat_get_blocks_hit', 'pg_stat_get_db_blocks_hit', 'pg_stat_get_db_numbackends', 'pg_stat_get_db_xact_commit', 'pg_stat_get_db_xact_rollback', 'pg_stat_get_numscans', 'pg_stat_get_tuples_deleted', 'pg_stat_get_tuples_inserted', 'pg_stat_get_tuples_returned', 'pg_stat_get_tuples_updated', 'pg_stat_reset', 'pg_stop_backup', 'pg_table_is_visible', 'pg_tablespace_databases', 'pg_terminate_backend', 'pg_timezone_abbrevs', 'pg_timezone_names', 'pg_type_is_visible', 'pgdate_part', 'pi', 'placing', 'plpython_call_handler', 'plpython_compiler', 'point', 'point_above', 'point_add', 'point_below', 'point_distance', 'point_div', 'point_eq', 'point_in', 'point_mul', 'point_ne', 'point_out', 'point_recv', 'point_send', 'point_sub', 'point_vert', 'poly_center', 'poly_contain', 'poly_contain_pt', 'poly_contained', 'poly_distance', 'poly_in', 'poly_npoints', 'poly_out', 'poly_overlap', 'poly_recv', 'poly_same', 'poly_send', 'polygon', 'popen', 'position', 'positionjoinsel', 'positionsel', 'pow', 'power', 'primary', 'pt_contained_circle', 'pt_contained_poly', 'qsummary', 'quote_ident', 'quote_literal', 'radians', 'radius', 'random', 'rank', 'rankx', 'ratio_to_report', 'raw', 'readratio', 'record_in', 'record_out', 'record_recv', 'record_send', 'recover', 'references', 'regclassin', 'regclassout', 'regclassrecv', 'regclasssend', 'regexeqjoinsel', 'regexeqsel', 'regexnejoinsel', 'regexnesel', 'regexp_count', 'regexp_instr', 'regexp_replace', 'regexp_substr', 'regoperatorout', 'regoperatorrecv', 'regoperatorsend', 'regoperout', 'regoperrecv', 'regopersend', 'regprocedurein', 'regprocedureout', 'regprocedurerecv', 'regproceduresend', 'regprocin', 'regprocout', 'regprocrecv', 'regprocsend', 'regtypein', 'regtypeout', 'regtyperecv', 'regtypesend', 'rejectlog', 'reltime', 'reltimeeq', 'reltimege', 'reltimegt', 'reltimein', 'reltimele', 'reltimelt', 'reltimene', 'reltimeout', 'reltimerecv', 'reltimesend', 'relu', 'remaining_vacrows', 'repeat', 'replace', 'replicate', 'resort', 'respect', 'restore', 'return_approx_percentile', 'reverse', 'right', 'round', 'row_number', 'rownumber', 'rpad', 'rt_box_inter', 'rt_box_size', 'rt_box_union', 'rt_poly_inter', 'rt_poly_size', 'rt_poly_union', 'rtbeginscan', 'rtbuild', 'rtbulkdelete', 'rtcostestimate', 'rtendscan', 'rtgettuple', 'rtinsert', 'rtmarkpos', 'rtrescan', 'rtrestrpos', 'scalargtjoinsel', 'scalargtsel', 'scalarltjoinsel', 'scalarltsel', 'select', 'session_user', 'set_bit', 'set_byte', 'set_masklen', 'setval', 'sig_bucket_3g', 'sig_bucket_lte', 'sig_score_3g', 'sig_score_lte', 'sigmoid', 'sign', 'similar', 'similar_escape', 'sin', 'sjis_to_euc_jp', 'sjis_to_mic', 'slice_num', 'slope', 'smgreq', 'smgrne', 'smgrout', 'snapshot ', 'some', 'sort_avail_mem', 'sortbytes', 'split_part', 'sqrt', 'ssl_version', 'st_asbinary', 'st_asewkb', 'st_asewkt', 'st_astext', 'st_azimuth', 'st_contains', 'st_dimension', 'st_disjoint', 'st_distance', 'st_dwithin', 'st_equals', 'st_geometrytype', 'st_intersects', 'st_isclosed', 'st_iscollection', 'st_isempty', 'st_makeline', 'st_makepoint', 'st_makepolygon', 'st_npoints', 'st_numpoints', 'st_point', 'st_polygon', 'st_within', 'st_x', 'st_xmax', 'st_xmin', 'st_y', 'st_ymax', 'st_ymin', 'stddev', 'stddev_pop', 'strpos', 'strtol', 'substr', 'sum', 'sysdate', 'system', 'table', 'tablebytes', 'tag', 'tan', 'tdes', 'text', 'text255', 'text32k', 'text_ge', 'text_gt', 'text_larger', 'text_le', 'text_lt', 'text_pattern_eq', 'text_pattern_ge', 'text_pattern_gt', 'text_pattern_le', 'text_pattern_lt', 'text_pattern_ne', 'text_smaller', 'textcat', 'texteq', 'texticlike', 'texticnlike', 'texticregexeq', 'texticregexne', 'textin', 'textlen', 'textlike', 'textne', 'textnlike', 'textout', 'textrecv', 'textregexeq', 'textregexne', 'textsend', 'then', 'tideq', 'tidin', 'tidout', 'tidrecv', 'tidsend', 'time', 'time_cmp', 'time_eq', 'time_ge', 'time_gt', 'time_in', 'time_larger', 'time_le', 'time_lt', 'time_mi_interval', 'time_mi_time', 'time_ne', 'time_out', 'time_pl_interval', 'time_recv', 'time_send', 'time_smaller', 'timedate_pl', 'timemi', 'timenow', 'timepl', 'timestamp', 'timestamp_cmp', 'timestamp_cmp_date', 'timestamp_cmp_timestamptz', 'timestamp_eq', 'timestamp_eq_date', 'timestamp_eq_timestamptz', 'timestamp_ge', 'timestamp_ge_date', 'timestamp_ge_timestamptz', 'timestamp_gt', 'timestamp_gt_date', 'timestamp_gt_timestamptz', 'timestamp_in', 'timestamp_larger', 'timestamp_le', 'timestamp_le_date', 'timestamp_le_timestamptz', 'timestamp_lt', 'timestamp_lt_date', 'timestamp_lt_timestamptz', 'timestamp_mi', 'timestamp_mi_int8', 'timestamp_mi_interval', 'timestamp_ne', 'timestamp_ne_date', 'timestamp_ne_timestamptz', 'timestamp_out', 'timestamp_pl_int8', 'timestamp_pl_interval', 'timestamp_recv', 'timestamp_send', 'timestamp_smaller', 'timestamptz', 'timestamptz_cmp', 'timestamptz_cmp_date', 'timestamptz_cmp_timestamp', 'timestamptz_eq', 'timestamptz_eq_date', 'timestamptz_eq_timestamp', 'timestamptz_ge', 'timestamptz_ge_date', 'timestamptz_ge_timestamp', 'timestamptz_gt', 'timestamptz_gt_date', 'timestamptz_gt_timestamp', 'timestamptz_in', 'timestamptz_larger', 'timestamptz_le', 'timestamptz_le_date', 'timestamptz_le_timestamp', 'timestamptz_lt', 'timestamptz_lt_date', 'timestamptz_lt_timestamp', 'timestamptz_mi', 'timestamptz_mi_int8', 'timestamptz_mi_interval', 'timestamptz_ne', 'timestamptz_ne_date', 'timestamptz_ne_timestamp', 'timestamptz_out', 'timestamptz_pl_int8', 'timestamptz_pl_interval', 'timestamptz_recv', 'timestamptz_send', 'timestamptz_smaller', 'timetz', 'timetz_cmp', 'timetz_eq', 'timetz_ge', 'timetz_gt', 'timetz_hash', 'timetz_in', 'timetz_larger', 'timetz_le', 'timetz_lt', 'timetz_mi_interval', 'timetz_ne', 'timetz_out', 'timetz_pl_interval', 'timetz_recv', 'timetz_send', 'timetz_smaller', 'timetzdate_pl', 'timezone', 'tinterval', 'tintervalct', 'tintervalend', 'tintervaleq', 'tintervalge', 'tintervalgt', 'tintervalin', 'tintervalle', 'tintervalleneq', 'tintervallenge', 'tintervallengt', 'tintervallenle', 'tintervallenlt', 'tintervallenne', 'tintervallt', 'tintervalne', 'tintervalout', 'tintervalov', 'tintervalrecv', 'tintervalrel', 'tintervalsame', 'tintervalsend', 'tintervalstart', 'to', 'to_ascii', 'to_char', 'to_date', 'to_hex', 'to_number', 'to_timestamp', 'tobpchar', 'top', 'total_num_deleted_vacrows', 'total_num_deleted_vacrows_reclaimed', 'trailing', 'translate', 'true', 'trunc', 'truncatecolumns', 'union', 'unique', 'unknownin', 'unknownout', 'unknownrecv', 'unknownsend', 'upper', 'user', 'using', 'vacstate_endrow', 'vacstate_last_inserted_row', 'var_pop', 'varbit', 'varbit_in', 'varbit_out', 'varbit_recv', 'varbit_send', 'varbitcmp', 'varbiteq', 'varbitge', 'varbitgt', 'varbitle', 'varbitlt', 'varbitne', 'varchar', 'varcharout', 'varcharrecv', 'varcharsend', 'verbose', 'version', 'void_in', 'void_out', 'wallet', 'when', 'where', 'width', 'width_bucket', 'win1250_to_latin2', 'win1250_to_mic', 'win1250_to_utf', 'win1251_to_alt', 'win1251_to_iso', 'win1251_to_koi8r', 'win1251_to_mic', 'win1256_to_utf', 'win874_to_utf', 'with', 'without', 'xideq', 'xideqint4', 'xidin', 'xidout', 'xidrecv', 'xidsend'}
# 231A - Team # http://codeforces.com/problemset/problem/231/A n = int(input()) c = 0 for i in range(n): arr = [x for x in input().split() if int(x) == 1] if len(arr) >= 2: c += 1 print(c)
n = int(input()) c = 0 for i in range(n): arr = [x for x in input().split() if int(x) == 1] if len(arr) >= 2: c += 1 print(c)
"""Base class for Node and LinkedLists""" class BaseLinkedList: def __init__(self): pass class BaseNode: def __init__(self, val=0, next_node=None): self._val = val self._next_node = next_node def __repr__(self): return f"Node({self.val, self._next_node})"
"""Base class for Node and LinkedLists""" class Baselinkedlist: def __init__(self): pass class Basenode: def __init__(self, val=0, next_node=None): self._val = val self._next_node = next_node def __repr__(self): return f'Node({(self.val, self._next_node)})'
description = 'XCCM' group = 'basic' includes = [ # 'source', # 'table', # 'detector', 'virtual_sample_motors', 'virtual_detector_motors', 'virtual_optic_motors', 'virtual_IOcard', 'optic_tool_switch', 'virtual_capillary_motors', 'capillary_selector' ]
description = 'XCCM' group = 'basic' includes = ['virtual_sample_motors', 'virtual_detector_motors', 'virtual_optic_motors', 'virtual_IOcard', 'optic_tool_switch', 'virtual_capillary_motors', 'capillary_selector']
""" https://www.hackerrank.com/challenges/binary-search-tree-insertion/problem """ # CODE PROVIDED BY TASK STARTS class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) def preOrder(root): if root is None: return print(root.info, end=" ") preOrder(root.left) preOrder(root.right) class BinarySearchTree: def __init__(self): self.root = None # CODE PROVIDED BY TASK ENDS """ Create tree.insert method """ def insert(self, val): if self.root is None: self.root = Node(val) else: self._insert(self.root, val) return self.root def _insert(self, root, val): if root is None: return if val < root.info: if root.left: self._insert(root.left, val) else: root.left = Node(val) if val > root.info: if root.right: self._insert(root.right, val) else: root.right = Node(val)
""" https://www.hackerrank.com/challenges/binary-search-tree-insertion/problem """ class Node: def __init__(self, info): self.info = info self.left = None self.right = None self.level = None def __str__(self): return str(self.info) def pre_order(root): if root is None: return print(root.info, end=' ') pre_order(root.left) pre_order(root.right) class Binarysearchtree: def __init__(self): self.root = None ' Create tree.insert method ' def insert(self, val): if self.root is None: self.root = node(val) else: self._insert(self.root, val) return self.root def _insert(self, root, val): if root is None: return if val < root.info: if root.left: self._insert(root.left, val) else: root.left = node(val) if val > root.info: if root.right: self._insert(root.right, val) else: root.right = node(val)
"""Triples are a way to define information about a platform/system. This module provides a way to convert a triple string into a well structured object to avoid constant string parsing in starlark code. Triples can be described at the following link: https://clang.llvm.org/docs/CrossCompilation.html#target-triple """ def triple(triple): """Constructs a struct containing each component of the provided triple Args: triple (str): A platform triple. eg: `x86_64-unknown-linux-gnu` Returns: struct: - arch (str): The triple's CPU architecture - vendor (str): The vendor of the system - system (str): The name of the system - abi (str, optional): The abi to use or None if abi does not apply. - triple (str): The original triple """ if triple == "wasm32-wasi": return struct( arch = "wasm32", system = "wasi", vendor = "wasi", abi = None, triple = triple, ) component_parts = triple.split("-") if len(component_parts) < 3: fail("Expected target triple to contain at least three sections separated by '-'") cpu_arch = component_parts[0] vendor = component_parts[1] system = component_parts[2] abi = None if system == "androideabi": system = "android" abi = "eabi" if len(component_parts) == 4: abi = component_parts[3] return struct( arch = cpu_arch, vendor = vendor, system = system, abi = abi, triple = triple, )
"""Triples are a way to define information about a platform/system. This module provides a way to convert a triple string into a well structured object to avoid constant string parsing in starlark code. Triples can be described at the following link: https://clang.llvm.org/docs/CrossCompilation.html#target-triple """ def triple(triple): """Constructs a struct containing each component of the provided triple Args: triple (str): A platform triple. eg: `x86_64-unknown-linux-gnu` Returns: struct: - arch (str): The triple's CPU architecture - vendor (str): The vendor of the system - system (str): The name of the system - abi (str, optional): The abi to use or None if abi does not apply. - triple (str): The original triple """ if triple == 'wasm32-wasi': return struct(arch='wasm32', system='wasi', vendor='wasi', abi=None, triple=triple) component_parts = triple.split('-') if len(component_parts) < 3: fail("Expected target triple to contain at least three sections separated by '-'") cpu_arch = component_parts[0] vendor = component_parts[1] system = component_parts[2] abi = None if system == 'androideabi': system = 'android' abi = 'eabi' if len(component_parts) == 4: abi = component_parts[3] return struct(arch=cpu_arch, vendor=vendor, system=system, abi=abi, triple=triple)
# -*- coding:utf-8 -*- """ Description: Script OP Code Usage: from AntShares.Core.Scripts.ScriptOp import ScriptOp """ class ScriptOp(object): # Constants OP_0 = 0x00 # An empty array of bytes is pushed onto the stack. (This is not a no-op: an item is added to the stack.) OP_FALSE = OP_0 OP_PUSHBYTES1 = 0x01 # 0x01-0x4B The next opcode bytes is data to be pushed onto the stack OP_PUSHBYTES75 = 0x4B OP_PUSHDATA1 = 0x4C # The next byte contains the number of bytes to be pushed onto the stack. OP_PUSHDATA2 = 0x4D # The next two bytes contain the number of bytes to be pushed onto the stack. OP_PUSHDATA4 = 0x4E # The next four bytes contain the number of bytes to be pushed onto the stack. OP_1NEGATE = 0x4F # The number -1 is pushed onto the stack. #OP_RESERVED = 0x50 # Transaction is invalid unless occuring in an unexecuted OP_IF branch OP_1 = 0x51 # The number 1 is pushed onto the stack. OP_TRUE = OP_1 OP_2 = 0x52 # The number 2 is pushed onto the stack. OP_3 = 0x53 # The number 3 is pushed onto the stack. OP_4 = 0x54 # The number 4 is pushed onto the stack. OP_5 = 0x55 # The number 5 is pushed onto the stack. OP_6 = 0x56 # The number 6 is pushed onto the stack. OP_7 = 0x57 # The number 7 is pushed onto the stack. OP_8 = 0x58 # The number 8 is pushed onto the stack. OP_9 = 0x59 # The number 9 is pushed onto the stack. OP_10 = 0x5A # The number 10 is pushed onto the stack. OP_11 = 0x5B # The number 11 is pushed onto the stack. OP_12 = 0x5C # The number 12 is pushed onto the stack. OP_13 = 0x5D # The number 13 is pushed onto the stack. OP_14 = 0x5E # The number 14 is pushed onto the stack. OP_15 = 0x5F # The number 15 is pushed onto the stack. OP_16 = 0x60 # The number 16 is pushed onto the stack. # Flow control OP_NOP = 0x61 # Does nothing. OP_JMP = 0x62 OP_JMPIF = 0x63 OP_JMPIFNOT = 0x64 OP_CALL = 0x65 OP_RET = 0x66 OP_APPCALL = 0x67 OP_SYSCALL = 0x68 OP_HALTIFNOT = 0x69 OP_HALT = 0x6A # Stack OP_TOALTSTACK = 0x6B # Puts the input onto the top of the alt stack. Removes it from the main stack. OP_FROMALTSTACK = 0x6C # Puts the input onto the top of the main stack. Removes it from the alt stack. OP_XDROP = 0x6D #OP_2DUP = 0x6E # Duplicates the top two stack items. #OP_3DUP = 0x6F # Duplicates the top three stack items. #OP_2OVER = 0x70 # Copies the pair of items two spaces back in the stack to the front. #OP_2ROT = 0x71 # The fifth and sixth items back are moved to the top of the stack. OP_XSWAP = 0x72 OP_XTUCK = 0x73 OP_DEPTH = 0x74 # Puts the number of stack items onto the stack. OP_DROP = 0x75 # Removes the top stack item. OP_DUP = 0x76 # Duplicates the top stack item. OP_NIP = 0x77 # Removes the second-to-top stack item. OP_OVER = 0x78 # Copies the second-to-top stack item to the top. OP_PICK = 0x79 # The item n back in the stack is copied to the top. OP_ROLL = 0x7A # The item n back in the stack is moved to the top. OP_ROT = 0x7B # The top three items on the stack are rotated to the left. OP_SWAP = 0x7C # The top two items on the stack are swapped. OP_TUCK = 0x7D # The item at the top of the stack is copied and inserted before the second-to-top item. # Splice OP_CAT = 0x7E # Concatenates two strings. OP_SUBSTR = 0x7F # Returns a section of a string. OP_LEFT = 0x80 # Keeps only characters left of the specified point in a string. OP_RIGHT = 0x81 # Keeps only characters right of the specified point in a string. OP_SIZE = 0x82 # Returns the length of the input string. # Bitwise logic OP_INVERT = 0x83 # Flips all of the bits in the input. OP_AND = 0x84 # Boolean and between each bit in the inputs. OP_OR = 0x85 # Boolean or between each bit in the inputs. OP_XOR = 0x86 # Boolean exclusive or between each bit in the inputs. OP_EQUAL = 0x87 # Returns 1 if the inputs are exactly equal 0 otherwise. #OP_EQUALVERIFY = 0x88 # Same as OP_EQUAL, but runs OP_VERIFY afterward. #OP_RESERVED1 = 0x89 # Transaction is invalid unless occuring in an unexecuted OP_IF branch #OP_RESERVED2 = 0x8A # Transaction is invalid unless occuring in an unexecuted OP_IF branch # Arithmetic # Note: Arithmetic inputs are limited to signed 32-bit integers, but may overflow their output. OP_1ADD = 0x8B # 1 is added to the input. OP_1SUB = 0x8C # 1 is subtracted from the input. OP_2MUL = 0x8D # The input is multiplied by 2. OP_2DIV = 0x8E # The input is divided by 2. OP_NEGATE = 0x8F # The sign of the input is flipped. OP_ABS = 0x90 # The input is made positive. OP_NOT = 0x91 # If the input is 0 or 1, it is flipped. Otherwise the output will be 0. OP_0NOTEQUAL = 0x92 # Returns 0 if the input is 0. 1 otherwise. OP_ADD = 0x93 # a is added to b. OP_SUB = 0x94 # b is subtracted from a. OP_MUL = 0x95 # a is multiplied by b. OP_DIV = 0x96 # a is divided by b. OP_MOD = 0x97 # Returns the remainder after dividing a by b. OP_LSHIFT = 0x98 # Shifts a left b bits, preserving sign. OP_RSHIFT = 0x99 # Shifts a right b bits, preserving sign. OP_BOOLAND = 0x9A # If both a and b are not 0, the output is 1. Otherwise 0. OP_BOOLOR = 0x9B # If a or b is not 0, the output is 1. Otherwise 0. OP_NUMEQUAL = 0x9C # Returns 1 if the numbers are equal, 0 otherwise. #OP_NUMEQUALVERIFY = 0x9D # Same as OP_NUMEQUAL, but runs OP_VERIFY afterward. OP_NUMNOTEQUAL = 0x9E # Returns 1 if the numbers are not equal, 0 otherwise. OP_LESSTHAN = 0x9F # Returns 1 if a is less than b, 0 otherwise. OP_GREATERTHAN = 0xA0 # Returns 1 if a is greater than b, 0 otherwise. OP_LESSTHANOREQUAL = 0xA1 # Returns 1 if a is less than or equal to b, 0 otherwise. OP_GREATERTHANOREQUAL = 0xA2 # Returns 1 if a is greater than or equal to b, 0 otherwise. OP_MIN = 0xA3 # Returns the smaller of a and b. OP_MAX = 0xA4 # Returns the larger of a and b. OP_WITHIN = 0xA5 # Returns 1 if x is within the specified range (left-inclusive), 0 otherwise. # Crypto #OP_RIPEMD160 = 0xA6 # The input is hashed using RIPEMD-160. OP_SHA1 = 0xA7 # The input is hashed using SHA-1. OP_SHA256 = 0xA8 # The input is hashed using SHA-256. OP_HASH160 = 0xA9 OP_HASH256 = 0xAA #OP_CODESEPARATOR = 0xAB # All of the signature checking words will only match signatures to the data after the most recently-executed OP_CODESEPARATOR. OP_CHECKSIG = 0xAC # The entire transaction's outputs, inputs, and script (from the most recently-executed OP_CODESEPARATOR to the end) are hashed. The signature used by OP_CHECKSIG must be a valid signature for this hash and public key. If it is, 1 is returned, 0 otherwise. #OP_CHECKSIGVERIFY = 0xAD # Same as OP_CHECKSIG, but OP_VERIFY is executed afterward. OP_CHECKMULTISIG = 0xAE # For each signature and public key pair, OP_CHECKSIG is executed. If more public keys than signatures are listed, some key/sig pairs can fail. All signatures need to match a public key. If all signatures are valid, 1 is returned, 0 otherwise. Due to a bug, one extra unused value is removed from the stack. #OP_CHECKMULTISIGVERIFY = 0xAF, # Same as OP_CHECKMULTISIG, but OP_VERIFY is executed afterward.
""" Description: Script OP Code Usage: from AntShares.Core.Scripts.ScriptOp import ScriptOp """ class Scriptop(object): op_0 = 0 op_false = OP_0 op_pushbytes1 = 1 op_pushbytes75 = 75 op_pushdata1 = 76 op_pushdata2 = 77 op_pushdata4 = 78 op_1_negate = 79 op_1 = 81 op_true = OP_1 op_2 = 82 op_3 = 83 op_4 = 84 op_5 = 85 op_6 = 86 op_7 = 87 op_8 = 88 op_9 = 89 op_10 = 90 op_11 = 91 op_12 = 92 op_13 = 93 op_14 = 94 op_15 = 95 op_16 = 96 op_nop = 97 op_jmp = 98 op_jmpif = 99 op_jmpifnot = 100 op_call = 101 op_ret = 102 op_appcall = 103 op_syscall = 104 op_haltifnot = 105 op_halt = 106 op_toaltstack = 107 op_fromaltstack = 108 op_xdrop = 109 op_xswap = 114 op_xtuck = 115 op_depth = 116 op_drop = 117 op_dup = 118 op_nip = 119 op_over = 120 op_pick = 121 op_roll = 122 op_rot = 123 op_swap = 124 op_tuck = 125 op_cat = 126 op_substr = 127 op_left = 128 op_right = 129 op_size = 130 op_invert = 131 op_and = 132 op_or = 133 op_xor = 134 op_equal = 135 op_1_add = 139 op_1_sub = 140 op_2_mul = 141 op_2_div = 142 op_negate = 143 op_abs = 144 op_not = 145 op_0_notequal = 146 op_add = 147 op_sub = 148 op_mul = 149 op_div = 150 op_mod = 151 op_lshift = 152 op_rshift = 153 op_booland = 154 op_boolor = 155 op_numequal = 156 op_numnotequal = 158 op_lessthan = 159 op_greaterthan = 160 op_lessthanorequal = 161 op_greaterthanorequal = 162 op_min = 163 op_max = 164 op_within = 165 op_sha1 = 167 op_sha256 = 168 op_hash160 = 169 op_hash256 = 170 op_checksig = 172 op_checkmultisig = 174
def triplewise(it): try: a, b = next(it), next(it) except StopIteration: return for c in it: yield a, b, c a, b = b, c def inc_count(values): last = None count = 0 for v in values: if last is not None and v > last: count += 1 last = v return count def main(): nums = [int(line) for line in open("input.txt").readlines()] sums = [sum(triple) for triple in triplewise(iter(nums))] print(inc_count(nums)) # part 1 print(inc_count(sums)) # part 2 if __name__ == "__main__": main()
def triplewise(it): try: (a, b) = (next(it), next(it)) except StopIteration: return for c in it: yield (a, b, c) (a, b) = (b, c) def inc_count(values): last = None count = 0 for v in values: if last is not None and v > last: count += 1 last = v return count def main(): nums = [int(line) for line in open('input.txt').readlines()] sums = [sum(triple) for triple in triplewise(iter(nums))] print(inc_count(nums)) print(inc_count(sums)) if __name__ == '__main__': main()
definitions = { "StringArray": { "type": "array", "items": { "type": "string", } }, "AudioEncoding": { "type": "string", "enum": ["LINEAR16", "ALAW", "MULAW", "LINEAR32F", "RAW_OPUS", "MPEG_AUDIO"] }, "VoiceActivityDetectionConfig": { "type": "object", "properties": { "min_speech_duration": {"type": "number"}, "max_speech_duration": {"type": "number"}, "silence_duration_threshold": {"type": "number"}, "silence_prob_threshold": {"type": "number"}, "aggressiveness": {"type": "number"}, } }, "SpeechContext": { "type": "object", "properties": { "phrases": {"$ref": "#definitions/StringArray"}, "words": {"$ref": "#definitions/StringArray"} } }, "InterimResultsConfig": { "type": "object", "properties": { "enable_interim_results": {"type": "boolean"}, "interval": {"type": "number"} } } } recognition_config_schema = { "type": "object", "definitions": definitions, "properties": { "encoding": {"$ref": "#/definitions/AudioEncoding"}, "sample_rate_hertz": {"type": "number"}, "language_code": {"type": "string"}, "max_alternatives": {"type": "number"}, "speech_contexts": { "type": "array", "items": { "$ref": "#/definitions/SpeechContext" } }, "enable_automatic_punctuation": {"type": "boolean"}, "enable_denormalization": {"type": "boolean"}, "enable_rescoring": {"type": "boolean"}, "model": {"type": "string"}, "num_channels": {"type": "number"}, "do_not_perform_vad": {"type": "boolean"}, "vad_config": {"$ref": "#/definitions/VoiceActivityDetectionConfig"}, "profanity_filter": {"type": "boolean"} }, "required": [ "sample_rate_hertz", "num_channels", "encoding", ], "additionalProperties": False } streaming_recognition_config_schema = { "type": "object", "definitions": definitions, "properties": { "config": recognition_config_schema, "single_utterance": {"type": "boolean"}, "interim_results_config": {"$ref": "#/definitions/InterimResultsConfig"} }, "additionalProperties": False } long_running_recognition_config_schema = { "type": "object", "definitions": definitions, "properties": { "config": recognition_config_schema, "group": {"type": "string"} }, "additionalProperties": False }
definitions = {'StringArray': {'type': 'array', 'items': {'type': 'string'}}, 'AudioEncoding': {'type': 'string', 'enum': ['LINEAR16', 'ALAW', 'MULAW', 'LINEAR32F', 'RAW_OPUS', 'MPEG_AUDIO']}, 'VoiceActivityDetectionConfig': {'type': 'object', 'properties': {'min_speech_duration': {'type': 'number'}, 'max_speech_duration': {'type': 'number'}, 'silence_duration_threshold': {'type': 'number'}, 'silence_prob_threshold': {'type': 'number'}, 'aggressiveness': {'type': 'number'}}}, 'SpeechContext': {'type': 'object', 'properties': {'phrases': {'$ref': '#definitions/StringArray'}, 'words': {'$ref': '#definitions/StringArray'}}}, 'InterimResultsConfig': {'type': 'object', 'properties': {'enable_interim_results': {'type': 'boolean'}, 'interval': {'type': 'number'}}}} recognition_config_schema = {'type': 'object', 'definitions': definitions, 'properties': {'encoding': {'$ref': '#/definitions/AudioEncoding'}, 'sample_rate_hertz': {'type': 'number'}, 'language_code': {'type': 'string'}, 'max_alternatives': {'type': 'number'}, 'speech_contexts': {'type': 'array', 'items': {'$ref': '#/definitions/SpeechContext'}}, 'enable_automatic_punctuation': {'type': 'boolean'}, 'enable_denormalization': {'type': 'boolean'}, 'enable_rescoring': {'type': 'boolean'}, 'model': {'type': 'string'}, 'num_channels': {'type': 'number'}, 'do_not_perform_vad': {'type': 'boolean'}, 'vad_config': {'$ref': '#/definitions/VoiceActivityDetectionConfig'}, 'profanity_filter': {'type': 'boolean'}}, 'required': ['sample_rate_hertz', 'num_channels', 'encoding'], 'additionalProperties': False} streaming_recognition_config_schema = {'type': 'object', 'definitions': definitions, 'properties': {'config': recognition_config_schema, 'single_utterance': {'type': 'boolean'}, 'interim_results_config': {'$ref': '#/definitions/InterimResultsConfig'}}, 'additionalProperties': False} long_running_recognition_config_schema = {'type': 'object', 'definitions': definitions, 'properties': {'config': recognition_config_schema, 'group': {'type': 'string'}}, 'additionalProperties': False}
""" 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
""" Module: 'esp32' on esp32 1.11.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() )
def is_escape_possible(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)
"""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 value_error('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""" 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 = {} 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""" 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 = {} 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
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()
class Graph: def __init__(self): self.numberOfNodes = 0 self.adjacentList = {} def __str__(self): return str(self.__dict__) def add_vertex(self, node): self.adjacentList[node] = [] self.numberOfNodes += 1 def add_edge(self, nodeA, nodeB): self.adjacentList[nodeA].append(nodeB) self.adjacentList[nodeB].append(nodeA) def show_connections(self): for x in self.adjacentList: print(x, end='-->') for i in self.adjacentList[x]: print(i, end=' ') print() my_graph = 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
""" # -*- 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
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)
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)
def whats_up_world(): print("What's up world?") if __name__ == "__main__": whats_up_world()
def whats_up_world(): print("What's up world?") if __name__ == '__main__': whats_up_world()
# -*- 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']]
feature_info = 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)
class Animal: def __init__(self, age, name): self.age = age self.name = name 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 mostrar_nombre(self): print(self.nombre) def mostrar_edad(self): print(self.edad)
""" Undefined-Complete-Key A key whose binding is Empty. """ class UndefinedCompleteKey( CompleteKey, ): pass
""" Undefined-Complete-Key A key whose binding is Empty. """ class Undefinedcompletekey(CompleteKey): pass
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'
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), )
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 podium_event_device(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."""
"""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))
class Recursion: def palindrome_check(self, strVal, i, j): if i > j: return True return self.PalindromeCheck(strVal, i + 1, j - 1) if strVal[i] == strVal[j] else False str_val = '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)
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 = 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
class Solution: def spiral_order(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 [] start_row = start_colum = 0 (end_row, end_colum) = (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]) start_row += 1 start_colum += 1 end_row -= 1 end_colum -= 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))
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))
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)
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 compute_bag_of_words(dataset, lang, domain_stopwords=[]): d = [] for (index, row) in dataset.iterrows(): text = row['title'] text2 = remove_stopwords(text, lang, domain_stopwords) text3 = stemming(text2, lang) d.append(text3) matrix = count_vectorizer(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'
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)
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) x = layers.MaxPooling2D((3, 3), strides=(2, 2), padding='same')(x) x = layers.Conv2D(80, (1, 1), strides=(1, 1), padding='same')(x) x = layers.Conv2D(192, (3, 3), strides=(1, 1), padding='same')(x) 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?")
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, }, } } } } } }, } } } }
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')
class Varmap: def __init__(self): self.n_smlcycle = 1 self.last = 0 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): 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): self.bias[vf] = 1 if self.bias[vf - 1] == len(self.map[vf - 1]) - 1: self.check_end(vf - 1) else: self.bias[vf - 1] += 1 return 1 def combinate(self): self.smlcy += 1 if self.vv == len(self.map) - 1: for vprint in range(0, len(self.map)): self.comblist[vprint].append(self.map[vprint][self.bias[vprint]]) if self.bias[self.vv] == len(self.map[self.vv]) - 1: 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): 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 class Netmap: def __init__(self): self.nn = 0 self.pvar = 1 self.cnta = 0 self.line_nvar = 0 self.nxtl_var = 0 self.ci_at = -5 self.ci_and = -50 def get_net(self, flag, netname, start, end, step): try: 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: 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'): 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': 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': 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): self.stringOnly[self.nn] = 1 self.map[self.nn].append(netname) elif self.name[self.nn] != None and start == None and (end != None) and (step == None): for i in range(1, end + 1): self.map[self.nn].append(netname) else: for i in range(1, step + 1): self.map[self.nn].append(end) self.nn += 1 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] == '@@': self.nline = line[3:len(line)] self.clist = list(self.nline) 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]) self.cnta += 1 self.line_nvar += 1 if self.stringOnly[varidx] == 1: wrfile.write(self.map[varidx][0]) self.ci_at = ci else: 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]) if type(self.map[varidx][self.pvar]) == float: wrfile.write('%e' % self.map[varidx][self.pvar]) elif type(self.map[varidx][self.pvar]) == int: wrfile.write('%d' % 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: if self.pvar == len(self.map[self.nxtl_var + self.line_nvar - 1]) - 1: self.pvar = 1 self.nxtl_var = self.nxtl_var + self.line_nvar self.line_nvar = 0 self.cnta = 0 self.ci_at = -6 else: self.pvar += 1 self.line_nvar = self.cnta self.line_nvar = 0 self.cnta = 0 wrfile.write(self.clist[ci]) else: wrfile.write(self.clist[ci]) elif line[0:2] == '@W': 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\t' % self.map[varidx][iv]) elif type(self.map[varidx][iv]) == float: wrfile.write('%.1f\t' % self.map[varidx][iv]) self.ci_at = ci else: wrfile.write(self.clist[ci]) self.ci_at = -5 elif line[0:2] == '@E': 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]) elif type(self.map[varidx][iv]) == float: wrfile.write('%.1f\t' % self.map[varidx][iv]) self.ci_at = ci else: wrfile.write(self.clist[ci]) self.ci_at = -5 elif line[0:2] == '@C': 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]) elif type(self.map[varidx][iv]) == float: wrfile.write('%.1f\t' % 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]) 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]) 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) class Resmap: def __init__(self, num_tb, num_words, 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) self.vidx = [None] * (num_words + index) self.env = [None] * (num_words + index) for itb in range(0, len(self.tb)): self.tbi[itb] = 0 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 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: self.vl[ntb][self.tbi[ntb]] = [value] self.vlinit[ntb][self.tbi[ntb]] += 1 else: self.vl[ntb][self.tbi[ntb]].append(value) self.tbi[ntb] = (self.tbi[ntb] + 1) % len(self.vr) def plot_env(self, ntb, start, step, xvar, xval): 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) 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] 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 def plot_y(self, yvar): self.yidx = self.vr.index(yvar) 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]] def sort(self, var): varidx = self.vr.index(var) for k in range(len(self.vl)): self.svar[k] = {} for i in range(len(self.vl[0][0])): self.svar[k][self.vl[k][varidx][i]] = [] for j in range(len(self.vr)): if j != varidx: self.svar[k][self.vl[k][varidx][i]].append(self.vl[k][j][i]) 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: 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]: 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: 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: return (list_ind, list_vic) 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: t_ind = 0 t_vic = 0 if i < len(list_ind) - 1 and i >= 0: if list_ind[i] > list_ind[i + 1]: 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: 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: 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) def m_m(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 reg_item = item cnt += 1 if err_step == 0: return (min_item, max_item)
"""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"
"""This module holds string constants to be used in conjunction with API calls to MapRoulette.""" query_parameter_q = 'q' query_parameter_parent_identifier = 'parentId' query_parameter_limit = 'limit' query_parameter_page = 'page' query_parameter_only_enabled = 'onlyEnabled' 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' flag_immediate_delete = 'immediate'
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")
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')
""" 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")
""" 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,))
x1 = type('X1', (object,), {}) x2 = type('X2', (object,), {}) class A(X1): ... class B(X2, A): ... x3 = type(34, (object,)) x4 = type('X4', 34) 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}']"
"""NOS NETCONF XML Configuration Command Templates. Interface Configuration Commands """ create_vlan_interface = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <interface-vlan xmlns="urn:brocade.com:mgmt:brocade-interface">\n <interface>\n <vlan>\n <name>{vlan_id}</name>\n </vlan>\n </interface>\n </interface-vlan>\n </config>\n' delete_vlan_interface = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <interface-vlan xmlns="urn:brocade.com:mgmt:brocade-interface">\n <interface>\n <vlan operation="delete">\n <name>{vlan_id}</name>\n </vlan>\n </interface>\n </interface-vlan>\n </config>\n' create_port_profile = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile">\n <name>{name}</name>\n </port-profile>\n </config>\n' create_vlan_profile_for_port_profile = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile">\n <name>{name}</name>\n <vlan-profile/>\n </port-profile>\n </config>\n' configure_l2_mode_for_vlan_profile = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile">\n <name>{name}</name>\n <vlan-profile>\n <switchport/>\n </vlan-profile>\n </port-profile>\n </config>\n' configure_trunk_mode_for_vlan_profile = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile">\n <name>{name}</name>\n <vlan-profile>\n <switchport>\n <mode>\n <vlan-mode>trunk</vlan-mode>\n </mode>\n </switchport>\n </vlan-profile>\n </port-profile>\n </config>\n' configure_allowed_vlans_for_vlan_profile = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <port-profile xmlns="urn:brocade.com:mgmt:brocade-port-profile">\n <name>{name}</name>\n <vlan-profile>\n <switchport>\n <trunk>\n <allowed>\n <vlan>\n <add>{vlan_id}</add>\n </vlan>\n </allowed>\n </trunk>\n </switchport>\n </vlan-profile>\n </port-profile>\n </config>\n' delete_port_profile = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <port-profile\nxmlns="urn:brocade.com:mgmt:brocade-port-profile" operation="delete">\n <name>{name}</name>\n </port-profile>\n </config>\n' activate_port_profile = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <port-profile-global xmlns="urn:brocade.com:mgmt:brocade-port-profile">\n <port-profile>\n <name>{name}</name>\n <activate/>\n </port-profile>\n </port-profile-global>\n </config>\n' deactivate_port_profile = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <port-profile-global xmlns="urn:brocade.com:mgmt:brocade-port-profile">\n <port-profile>\n <name>{name}</name>\n <activate\nxmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" nc:operation="delete" />\n </port-profile>\n </port-profile-global>\n </config>\n' associate_mac_to_port_profile = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <port-profile-global xmlns="urn:brocade.com:mgmt:brocade-port-profile">\n <port-profile>\n <name>{name}</name>\n <static>\n <mac-address>{mac_address}</mac-address>\n </static>\n </port-profile>\n </port-profile-global>\n </config>\n' dissociate_mac_from_port_profile = '\n <config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0">\n <port-profile-global xmlns="urn:brocade.com:mgmt:brocade-port-profile">\n <port-profile>\n <name>{name}</name>\n <static\nxmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" nc:operation="delete">\n <mac-address>{mac_address}</mac-address>\n </static>\n </port-profile>\n </port-profile-global>\n </config>\n' os_port_profile_name = 'openstack-profile-{id}' 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()
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()
"""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
""" 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
# 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
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
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 %} """
dal_view_py = '# generated by appcreator\nfrom django.db.models import Q\nfrom dal import autocomplete\nfrom . models import *\n\n{% for x in data %}\nclass {{ x.model_name }}AC(autocomplete.Select2QuerySetView):\n def get_queryset(self):\n qs = {{ x.model_name }}.objects.all()\n\n if self.q:\n qs = qs.filter(\n Q(legacy_id__icontains=self.q) |\n Q({{ x.model_representation }}__icontains=self.q)\n )\n return qs\n\n{% endfor %}\n' dal_urls_py = "# generated by appcreator\nfrom django.conf.urls import url\nfrom . import dal_views\n\napp_name = '{{ app_name }}'\nurlpatterns = [\n{%- for x in data %}\n url(\n r'^{{ x.model_name|lower }}-autocomplete/$',\n dal_views.{{ x.model_name}}AC.as_view(),\n name='{{ x.model_name|lower }}-autocomplete'\n ),\n{%- endfor %}\n]\n" app_py = "\nfrom django.apps import AppConfig\nclass {{ app_name|title }}Config(AppConfig):\n name = '{{ app_name }}'\n" admin_py = '# generated by appcreator\nfrom django.contrib import admin\nfrom . models import (\n{%- for x in data %}\n {{ x.model_name }}{{ "," if not loop.last }}\n{%- endfor %}\n)\n\n{%- for x in data %}\nadmin.site.register({{ x.model_name }})\n{%- endfor %}\n' urls_py = "# generated by appcreator\nfrom django.conf.urls import url\nfrom . import views\n\napp_name = '{{ app_name }}'\nurlpatterns = [\n{%- for x in data %}\n url(\n r'^{{ x.model_name|lower }}/$',\n views.{{ x.model_name}}ListView.as_view(),\n name='{{ x.model_name|lower }}_browse'\n ),\n url(\n r'^{{ x.model_name|lower }}/detail/(?P<pk>[0-9]+)$',\n views.{{ x.model_name}}DetailView.as_view(),\n name='{{ x.model_name|lower }}_detail'\n ),\n url(\n r'^{{ x.model_name|lower }}/create/$',\n views.{{ x.model_name}}Create.as_view(),\n name='{{ x.model_name|lower }}_create'\n ),\n url(\n r'^{{ x.model_name|lower }}/edit/(?P<pk>[0-9]+)$',\n views.{{ x.model_name}}Update.as_view(),\n name='{{ x.model_name|lower }}_edit'\n ),\n url(\n r'^{{ x.model_name|lower }}/delete/(?P<pk>[0-9]+)$',\n views.{{ x.model_name}}Delete.as_view(),\n name='{{ x.model_name|lower }}_delete'),\n{%- endfor %}\n]\n" filters_py = '# generated by appcreator\nimport django_filters\nfrom django import forms\n\nfrom dal import autocomplete\n\nfrom vocabs.filters import generous_concept_filter\nfrom vocabs.models import SkosConcept\nfrom . models import (\n{%- for x in data %}\n {{ x.model_name }}{{ "," if not loop.last }}\n{%- endfor %}\n)\n\n{% for x in data %}\nclass {{ x.model_name }}ListFilter(django_filters.FilterSet):\n legacy_id = django_filters.CharFilter(\n lookup_expr=\'icontains\',\n help_text={{ x.model_name}}._meta.get_field(\'legacy_id\').help_text,\n label={{ x.model_name}}._meta.get_field(\'legacy_id\').verbose_name\n )\n {%- for y in x.model_fields %}\n {%- if y.field_type == \'CharField\' %}\n {{y.field_name}} = django_filters.CharFilter(\n lookup_expr=\'icontains\',\n help_text={{ x.model_name}}._meta.get_field(\'{{y.field_name}}\').help_text,\n label={{ x.model_name}}._meta.get_field(\'{{y.field_name}}\').verbose_name\n )\n {%- endif %}\n {%- if y.field_type == \'TextField\' %}\n {{y.field_name}} = django_filters.CharFilter(\n lookup_expr=\'icontains\',\n help_text={{ x.model_name}}._meta.get_field(\'{{y.field_name}}\').help_text,\n label={{ x.model_name}}._meta.get_field(\'{{y.field_name}}\').verbose_name\n )\n {%- endif %}\n {%- if y.related_class == \'SkosConcept\' %}\n {{y.field_name}} = django_filters.ModelMultipleChoiceFilter(\n queryset=SkosConcept.objects.filter(\n collection__name="{{y.field_name}}"\n ),\n help_text={{x.model_name}}._meta.get_field(\'{{y.field_name}}\').help_text,\n label={{x.model_name}}._meta.get_field(\'{{y.field_name}}\').verbose_name,\n method=generous_concept_filter,\n widget=autocomplete.Select2Multiple(\n url="/vocabs-ac/specific-concept-ac/{{y.field_name}}",\n attrs={\n \'data-placeholder\': \'Autocomplete ...\',\n \'data-minimum-input-length\': 2,\n },\n )\n )\n {%- elif y.field_type == \'ManyToManyField\' %}\n {{y.field_name}} = django_filters.ModelMultipleChoiceFilter(\n queryset={{y.related_class}}.objects.all(),\n help_text={{x.model_name}}._meta.get_field(\'{{y.field_name}}\').help_text,\n label={{x.model_name}}._meta.get_field(\'{{y.field_name}}\').verbose_name,\n widget=autocomplete.Select2Multiple(\n url="{{ app_name }}-ac:{{y.related_class|lower}}-autocomplete",\n )\n )\n {%- elif y.field_type == \'ForeignKey\' %}\n {{y.field_name}} = django_filters.ModelMultipleChoiceFilter(\n queryset={{y.related_class}}.objects.all(),\n help_text={{x.model_name}}._meta.get_field(\'{{y.field_name}}\').help_text,\n label={{x.model_name}}._meta.get_field(\'{{y.field_name}}\').verbose_name,\n widget=autocomplete.Select2Multiple(\n url="{{ app_name }}-ac:{{y.related_class|lower}}-autocomplete",\n )\n )\n {%- endif %}\n {%- endfor %}\n\n class Meta:\n model = {{ x.model_name }}\n fields = [\n \'id\',\n \'legacy_id\',\n {% for y in x.model_fields %}\n {%- if y.field_type == \'DateRangeField\' or y.field_type == \'MultiPolygonField\'%}\n {%- else %}\'{{ y.field_name }}\',\n {%- endif %}\n {% endfor %}]\n\n{% endfor %}\n' forms_py = '# generated by appcreator\nfrom django import forms\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Submit, Layout, Fieldset, Div, MultiField, HTML\nfrom crispy_forms.bootstrap import Accordion, AccordionGroup\n\nfrom vocabs.models import SkosConcept\nfrom . models import (\n{%- for x in data %}\n {{ x.model_name }}{{ "," if not loop.last }}\n{%- endfor %}\n)\n\n{% for x in data %}\nclass {{ x.model_name }}FilterFormHelper(FormHelper):\n def __init__(self, *args, **kwargs):\n super({{ x.model_name }}FilterFormHelper, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.form_class = \'genericFilterForm\'\n self.form_method = \'GET\'\n self.helper.form_tag = False\n self.add_input(Submit(\'Filter\', \'Search\'))\n self.layout = Layout(\n Fieldset(\n \'Basic search options\',\n \'id\',\n css_id="basic_search_fields"\n ),\n Accordion(\n AccordionGroup(\n \'Advanced search\',\n {% for y in x.model_fields %}\n {% if y.field_type == \'DateRangeField\' or y.field_type == \'id\' or y.field_type == \'MultiPolygonField\' %}\n {% else %}\'{{ y.field_name }}\',\n {%- endif %}\n {%- endfor %}\n css_id="more"\n ),\n AccordionGroup(\n \'admin\',\n \'legacy_id\',\n css_id="admin_search"\n ),\n )\n )\n\n\nclass {{ x.model_name }}Form(forms.ModelForm):\n\n {%- for y in x.model_fields %}\n {%- if y.related_class == \'SkosConcept\' and y.field_type == \'ForeignKey\'%}\n {{y.field_name}} = forms.ModelChoiceField(\n required=False,\n label="{{y.field_verbose_name}}",\n queryset=SkosConcept.objects.filter(collection__name="{{y.field_name}}")\n )\n {%- elif y.related_class == \'SkosConcept\' and y.field_type == \'ManyToManyField\'%}\n {{y.field_name}} = forms.ModelMultipleChoiceField(\n required=False,\n label="{{y.field_verbose_name}}",\n queryset=SkosConcept.objects.filter(collection__name="{{y.field_name}}")\n )\n {%- endif -%}\n {% endfor %}\n\n class Meta:\n model = {{ x.model_name }}\n fields = "__all__"\n\n def __init__(self, *args, **kwargs):\n super({{ x.model_name }}Form, self).__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.form_tag = True\n self.helper.form_class = \'form-horizontal\'\n self.helper.label_class = \'col-md-3\'\n self.helper.field_class = \'col-md-9\'\n self.helper.add_input(Submit(\'submit\', \'save\'),)\n\n{% endfor %}\n' tables_py = '# generated by appcreator\nimport django_tables2 as tables\nfrom django_tables2.utils import A\n\nfrom browsing.browsing_utils import MergeColumn\nfrom . models import (\n{%- for x in data %}\n {{ x.model_name }}{{ "," if not loop.last }}\n{%- endfor %}\n)\n{% for x in data %}\n\nclass {{ x.model_name }}Table(tables.Table):\n\n id = tables.LinkColumn(verbose_name=\'ID\')\n merge = MergeColumn(verbose_name=\'keep | remove\', accessor=\'pk\')\n {%- for y in x.model_fields %}\n {%- if y.field_type == \'ManyToManyField\' %}\n {{ y.field_name }} = tables.columns.ManyToManyColumn()\n {%- endif %}\n {%- endfor %}\n\n class Meta:\n model = {{ x.model_name }}\n sequence = (\'id\',)\n attrs = {"class": "table table-responsive table-hover"}\n{% endfor %}\n' views_py = '# generated by appcreator\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.urls import reverse, reverse_lazy\nfrom django.views.generic.detail import DetailView\nfrom django.views.generic.edit import DeleteView\nfrom . filters import *\nfrom . forms import *\nfrom . tables import *\nfrom . models import (\n{%- for x in data %}\n {{ x.model_name }}{{ "," if not loop.last }}\n{%- endfor %}\n)\nfrom browsing.browsing_utils import (\n GenericListView, BaseCreateView, BaseUpdateView, BaseDetailView\n)\n\n{% for x in data %}\nclass {{ x.model_name }}ListView(GenericListView):\n\n model = {{ x.model_name }}\n filter_class = {{ x.model_name }}ListFilter\n formhelper_class = {{ x.model_name }}FilterFormHelper\n table_class = {{ x.model_name }}Table\n init_columns = [\n \'id\', {%- if x.model_representation != \'nan\' %} \'{{ x.model_representation }}\', {%- endif %}\n ]\n enable_merge = True\n\n\nclass {{ x.model_name }}DetailView(BaseDetailView):\n\n model = {{ x.model_name }}\n template_name = \'browsing/generic_detail.html\'\n\n\nclass {{ x.model_name }}Create(BaseCreateView):\n\n model = {{ x.model_name }}\n form_class = {{ x.model_name }}Form\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super({{ x.model_name }}Create, self).dispatch(*args, **kwargs)\n\n\nclass {{ x.model_name }}Update(BaseUpdateView):\n\n model = {{ x.model_name }}\n form_class = {{ x.model_name }}Form\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super({{ x.model_name }}Update, self).dispatch(*args, **kwargs)\n\n\nclass {{ x.model_name }}Delete(DeleteView):\n model = {{ x.model_name }}\n template_name = \'webpage/confirm_delete.html\'\n success_url = reverse_lazy(\'{{ app_name }}:{{ x.model_name|lower }}_browse\')\n\n @method_decorator(login_required)\n def dispatch(self, *args, **kwargs):\n return super({{ x.model_name }}Delete, self).dispatch(*args, **kwargs)\n\n{% endfor %}\n' models_py = '# generated by appcreator\n\nfrom django.contrib.gis.db import models\nfrom django.urls import reverse\n\n\nfrom browsing.browsing_utils import model_to_dict\n\n\ndef set_extra(self, **kwargs):\n self.extra = kwargs\n return self\n\n\nmodels.Field.set_extra = set_extra\n\n\nclass IdProvider(models.Model):\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n legacy_id = models.CharField(\n blank=True, null=True,\n max_length=250,\n )\n\n class Meta:\n abstract = True\n\n{% for x in data %}\nclass {{ x.model_name }}(IdProvider):\n {% if x.model_helptext %}### {{ x.model_helptext }} ###{% endif %}\n legacy_id = models.CharField(\n max_length=300, blank=True,\n verbose_name="Legacy ID"\n )\n {%- for y in x.model_fields %}\n {%- if y.field_type == \'DateRangeField\' %}\n {{ y.field_name }} = {{ y.field_type}}(\n {%- else %}\n {{ y.field_name }} = models.{{ y.field_type}}(\n {%- endif %}\n {%- if y.field_name == \'id\' %}\n primary_key=True,\n {%- endif %}\n {%- if y.field_type == \'DecimalField\' %}\n max_digits=19,\n decimal_places=10,\n {%- endif %}\n {%- if y.field_type == \'BooleanField\' %}\n default=False,\n {%- endif %}\n {%- if y.field_type == \'CharField\' %}\n blank=True, null=True,\n {%- if y.choices %}\n choices={{ y.choices }},\n {%- endif %}\n max_length=250,\n {%- elif y.field_type == \'TextField\' %}\n blank=True, null=True,\n {%- elif y.field_type == \'ForeignKey\' %}\n {%- if y.related_class == \'SkosConcept\' %}\n {{ y.related_class }},\n {%- else %}\n "{{ y.related_class }}",\n {%- endif %}\n related_name=\'{{ y.related_name }}\',\n on_delete=models.SET_NULL,\n {%- if y.field_name != \'id\' %}\n null=True,\n blank=True,\n {%- endif %}\n {%- elif y.field_type == \'ManyToManyField\' %}\n {%- if y.related_class == \'SkosConcept\' %}\n {{ y.related_class }},\n {%- else %}\n "{{ y.related_class }}",\n {%- endif %}\n {%- if y.through %}\n through=\'{{ y.through }}\',\n {%- endif %}\n related_name=\'{{ y.related_name }}\',\n blank=True,\n {%- else %}\n {%- if y.field_name != \'id\' %}\n blank=True, null=True,\n {%- endif %}\n {%- endif %}\n verbose_name="{{ y.field_verbose_name }}",\n help_text="{{ y.field_helptext }}",\n ).set_extra(\n is_public={{ y.field_public }},\n {%- if y.value_from %}\n data_lookup="{{ y.value_from }}",\n {%- endif %}\n {%- if y.arche_prop %}\n arche_prop="{{ y.arche_prop }}",\n {%- endif %}\n {%- if y.arche_prop_str_template %}\n arche_prop_str_template="{{ y.arche_prop_str_template }}",\n {%- endif %}\n )\n {%- endfor %}\n orig_data_csv = models.TextField(\n blank=True,\n null=True,\n verbose_name="The original data"\n ).set_extra(\n is_public=True\n )\n\n class Meta:\n {% if x.model_order == \'nan\' %}\n ordering = [\n \'id\',\n ]\n {%- else %}\n ordering = [\n \'{{ x.model_order }}\',\n ]\n {%- endif %}\n verbose_name = "{{ x.model_verbose_name }}"\n {% if x.model_representation == \'nan\' %}\n def __str__(self):\n return "{}".format(self.id)\n {%- else %}\n def __str__(self):\n if self.{{ x.model_representation }}:\n return "{}".format(self.{{ x.model_representation }})\n else:\n return "{}".format(self.legacy_id)\n {%- endif %}\n\n def field_dict(self):\n return model_to_dict(self)\n\n @classmethod\n def get_listview_url(self):\n return reverse(\'{{ app_name }}:{{ x.model_name|lower }}_browse\')\n {% if x.source_table %}\n @classmethod\n def get_source_table(self):\n return "{{ x.source_table }}"\n {% else %}\n @classmethod\n def get_source_table(self):\n return None\n {% endif %}\n {% if x.natural_primary_key %}\n @classmethod\n def get_natural_primary_key(self):\n return "{{ x.natural_primary_key }}"\n {% else %}\n @classmethod\n def get_natural_primary_key(self):\n return None\n {% endif %}\n @classmethod\n def get_createview_url(self):\n return reverse(\'{{ app_name }}:{{ x.model_name|lower }}_create\')\n\n def get_absolute_url(self):\n return reverse(\'{{ app_name }}:{{ x.model_name|lower }}_detail\', kwargs={\'pk\': self.id})\n\n def get_absolute_url(self):\n return reverse(\'{{ app_name }}:{{ x.model_name|lower }}_detail\', kwargs={\'pk\': self.id})\n\n def get_delete_url(self):\n return reverse(\'{{ app_name }}:{{ x.model_name|lower }}_delete\', kwargs={\'pk\': self.id})\n\n def get_edit_url(self):\n return reverse(\'{{ app_name }}:{{ x.model_name|lower }}_edit\', kwargs={\'pk\': self.id})\n\n def get_next(self):\n next = self.__class__.objects.filter(id__gt=self.id)\n if next:\n return reverse(\n \'{{ app_name }}:{{ x.model_name|lower }}_detail\',\n kwargs={\'pk\': next.first().id}\n )\n return False\n\n def get_prev(self):\n prev = self.__class__.objects.filter(id__lt=self.id).order_by(\'-id\')\n if prev:\n return reverse(\n \'{{ app_name }}:{{ x.model_name|lower }}_detail\',\n kwargs={\'pk\': prev.first().id}\n )\n return False\n\n{% endfor %}\n'
""" 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)}")
""" https://adventofcode.com/2018/day/14 """ def read_file(): 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 = read_file() 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)
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']}]
__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()
"""What is the first Fibonacci number to contain N digits""" fib_index = [1] def generate_fibonacci_indexes(): """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(): generate_fibonacci_indexes() 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/*' ] }
__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
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
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}, ]
reactions_irreversible = [{'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
class Firstorderfilter: 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.0 - 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)
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 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] = fork_graph_node(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 Solution: def num_unique_emails(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. """
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): packages = [l for l in self.__optional_packages__ if package_name in l] if not len(packages): raise value_error('Cannot find the package: %s.' % package_name) super().__init__(f"The following packages are missing.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. """
""" `cloudzero-awstools` tests package. """
# 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, ] }
secrets = {'totp_keys': [('Github', 'JBSWY3DPEHPK3PXP', 8860328), ('Discord', 'JBSWY3DPEHPK3PXQ', 3319966), ('Slack', 'JBSWY5DZEHPK3PXR', 16549406), ('Basecamp', 'JBSWY6DZEHPK3PXS', 5620300), ('Gmail', 'JBSWY7DZEHPK3PXT', 3156479), None, None, None, None, ('Hello Kitty', 'JBSWY7DZEHPK3PXU', 15537743), 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", ], )
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
class Book: title = '' author = '' pages = 0 book1 = book() book2 = book() book1.title = 'Harry Potter' 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) print('\nTitle:\t', book2.title, '\nAuthor:\t', book2.author, '\nPages:\t', book2.pages)
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. """
note = '\nI do not own the pictures, I simply provide for you a connection\nfrom your Discord server to Gelbooru using both legal and free APIs.\n\nI am not responsible in any way for the content that GelBot will send to\nthe chat. Keep in mind YOU are the one who type the tags.\n' help = "\nThe usage of GelBot is simple. Here's only one command that you need to\nget pictures. !pic is what you need. Syntax:\n\n!pic [optional rating] tag/tag with a space/tag/tag\n\nType !gelexamples to get better grasp of the command.\n\nType !gelratings if you don't know how to use ratings.\n\nPlease type !gelnote and read my disclaimer.\n" examples = '\nSome examples of !pic usage:\n!pic rs lucy heartfilia\n!pic lucy heartfilia/cat ears/long hair\n!pic aqua (konosuba)\n!pic rs misaka mikoto/animal ears/sweater\n!pic rq kitchen\n' ratings = "\nWe've got 3 ratings available:\nrs - rating safe - mostly SFW content,\nrq - rating questionable - mostly NSFW, well questionable content,\nre - rating explicit - definitely unquestionable NSFW content.\n\nFor both rating questionable and explicit NSFW channel is required.\n\nIf you don't specify any, GelBot will look only within rating safe.\n"
# 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()
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 print_list(self): current_node = self.head while currentNode is not None: print(currentNode.value, '->', end='') current_node = currentNode.nextNode print('None') def insert_at_end(self, value): node = linked_list_node(value) if self.head is None: self.head = node return current_node = self.head while True: if currentNode.nextNode is None: currentNode.nextNode = node break current_node = currentNode.nextNode def insert_at_beginning(self, value): node = linked_list_node(value) if self.head is None: self.head = node return node.nextNode = self.head self.head = node def insert_at_pos(self, value, prev_value): node = linked_list_node(value) if self.head is None: self.head = node return current_node = self.head prev_node = self.head while currentNode.value is not prev_value: if currentNode.nextNode is None: print('Node not found') break prev_node = currentNode current_node = currentNode.nextNode prevNode.nextNode = node node.nextNode = currentNode if __name__ == '__main__': node_creation = linked_list() 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()
# -*- 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' } }
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]
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 '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")
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
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" }
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)} 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'] 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)
class Solution: def min_remove_to_make_valid(self, s: str) -> str: 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 toremove2 = [] if lcounter > rcounter: 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 s2 = [char for char in s] 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)
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')
""" 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
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, )
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') 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
class Source: def __init__(self): None def is_queryable(self): return False def supports(self, clauses, expr, visible_vars): return False class Rdbmstable(Source): def is_queryable(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
def on_value_change(par, prev): if par.name == 'Heartbeatrole': parent().Role_setup(par) else: pass return def on_pulse(par): return def on_expression_change(par, val, prev): return def on_export_change(par, val, prev): return def on_enable_change(par, val, prev): return def on_mode_change(par, val, prev): return
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))
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> {{ '}}' }}`.
settings_export = ['SITE_NAME', 'DEBUG', 'ENV']
# 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}
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) random_seed = 42 dataset_image_size = 256 train_val_test_ratio = (0.7, 0.1, 0.2) image_dir = './data/original_data/images/' meta_data_dir = './data/original_data/meta_data/' meta_filename = 'Data_Entry_2017_v2020.csv' labels_dir = './data/labels/' dataset_dir = './data/datasets/' train_labels = 'train_labels.csv' val_labels = 'val_labels.csv' test_labels = 'test_labels.csv' save_dir = './data/saved_models/' 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 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()
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.')
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"
""" 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'