content
stringlengths
7
1.05M
# # PySNMP MIB module RBN-TC (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBN-TC # Produced by pysmi-0.3.4 at Wed May 1 14:52:26 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint") rbnModules, = mibBuilder.importSymbols("RBN-SMI", "rbnModules") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, ObjectIdentity, Counter32, MibIdentifier, TimeTicks, Gauge32, ModuleIdentity, Unsigned32, iso, IpAddress, Bits, Integer32, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "ObjectIdentity", "Counter32", "MibIdentifier", "TimeTicks", "Gauge32", "ModuleIdentity", "Unsigned32", "iso", "IpAddress", "Bits", "Integer32", "NotificationType") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") rbnTC = ModuleIdentity((1, 3, 6, 1, 4, 1, 2352, 5, 2)) rbnTC.setRevisions(('2009-10-20 17:00', '2004-06-19 17:00', '2003-03-17 17:00', '2002-11-11 00:00', '2002-06-26 00:00', '2000-07-14 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: rbnTC.setRevisionsDescriptions(('Added new textual convention: RbnUnsigned64 for read-write capable 64 bit integer value.', 'Added new textual convention: RbnPortMediumType. Correct warnings given by smilint.', 'Added new textual convention: RbnVidOrUntagged.', 'Moved definitions of RbnSlot and RbnPort from RBN-PVC-MIB. Updated range on RbnSlot and RbnPort.', 'Updated CONTACT-INFO. Added new textual conventions: RbnKBytes and RbnPercentage.', 'Initial version.',)) if mibBuilder.loadTexts: rbnTC.setLastUpdated('200910201700Z') if mibBuilder.loadTexts: rbnTC.setOrganization('Redback Networks, Inc.') if mibBuilder.loadTexts: rbnTC.setContactInfo(' RedBack Networks, Inc. Postal: 300 Holger Way San Jose, CA 95134-1362 USA Phone: +1 408 750 5000 Fax: +1 408 750 5599 E-mail: [email protected] ') if mibBuilder.loadTexts: rbnTC.setDescription('Defines common textual conventions used in Redback mib modules.') class RbnCircuitHandle(TextualConvention, OctetString): description = 'A unique identifier for individual circuits. The string is composed of the following: Octet 1 slot 2 port 3-8 circuit identifier slots/ports are numbered 0..n. The SMS CLI also numbers slots/ports 0..n but SE CLI numbers slots/ports 1..n. For example: When the SE CLI refers to slot/port 1/2, this maps to to the RbnCircuitHandle slot/port 0/1 ' status = 'current' displayHint = '1d:1d:2x-2x-2x' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8) fixedLength = 8 class RbnKBytes(TextualConvention, Integer32): description = 'Storage size, expressed in units of 1024 bytes.' status = 'current' displayHint = 'd' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 2147483647) class RbnPercentage(TextualConvention, Integer32): description = 'This Textual Convention describes an object that stores a whole integer percentage value.' status = 'current' displayHint = 'd%' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 100) class RbnSlot(TextualConvention, Unsigned32): description = "The chassis slot number. This is the physical slot number as reported in the CLI command 'show hardware' on SMS and the CLI command 'show port' on SE." status = 'current' displayHint = 'd' subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(0, 255) class RbnPort(TextualConvention, Unsigned32): description = "The chassis port number. This is the physical port number as reported in the CLI command 'show hardware' on SMS and the CLI command 'show port' on SE." status = 'current' displayHint = 'd' subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(0, 255) class RbnVidOrUntagged(TextualConvention, Integer32): description = 'The twelve-bit VLAN Identifer (VID) used to uniquely identify the VLAN to which the frame belongs. The VID is encoded as an unsigned binary number. An untagged frame does not carry any identification of the VLAN to which it belongs and is designated with a value of 4096.' status = 'current' displayHint = 'd' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 4096) class RbnPortMediumType(TextualConvention, Integer32): description = 'Medium type of NAS port.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 11, 12, 13, 14)) namedValues = NamedValues(("unknown", 0), ("dsl", 11), ("cable", 12), ("wireless", 13), ("satellite", 14)) class RbnUnsigned64(TextualConvention, OctetString): description = 'Unsigned 64 bit integer value is represented as an OCTET STRING. This allows an unsigned integer value in the range 0..18446744073709551615. The octets are ordered with the first octet containing the highest ordered bits of the integer and the 8th octet containing the lowest ordered bits, corresponding to network byte order.' status = 'current' displayHint = '8d' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8) fixedLength = 8 mibBuilder.exportSymbols("RBN-TC", RbnSlot=RbnSlot, RbnVidOrUntagged=RbnVidOrUntagged, RbnPercentage=RbnPercentage, RbnCircuitHandle=RbnCircuitHandle, PYSNMP_MODULE_ID=rbnTC, rbnTC=rbnTC, RbnPortMediumType=RbnPortMediumType, RbnKBytes=RbnKBytes, RbnUnsigned64=RbnUnsigned64, RbnPort=RbnPort)
# Write a program that reads a floating­point number and prints “zero” if the number # is zero. Otherwise, print “positive” or “negative”. Add “small” if the absolute value # of the number is less than 1, or “large” if it exceeds 1,000,000. userInput = float(input("Enter a floating-point number: ")) if userInput == 0: print("It's zero") elif userInput > 0: print("It's positive") else: print("It's negative") if userInput < 1: print("and small") elif userInput > 1000000: print("and large")
def quicksort(ar:list): """ Sort a list with quicksort algorithm. The quicksort algorithm splits a list into two parts and recursively sorts those parts by making swaps based on the elements value in relation to the pivot value. It is an O(n log(n)) sort. Args: ar: list to sort. Returns: The input list sorted. """ def sort(ar, lo, hi): # if the two ends haven't swapped if lo < hi: # find the partition partition_index = partition(ar, lo, hi) # sort both sides sort(ar, lo, partition_index - 1) sort(ar, partition_index + 1, hi) def partition(ar, lo, hi): # basic partition by using the high value as a pivot pivot = ar[hi] # the value being examined i = lo for j in range(lo, hi): # if ar[j] <= pivot: ar[i], ar[j] = ar[j], ar[i] i += 1 # swap the pivot into place ar[i], ar[hi] = ar[hi], ar[i] return i sort(ar, 0, len(ar)-1) return ar
imports="" loader=""" //handle := C.MemoryLoadLibrary(unsafe.Pointer(&full_payload[0]),(C.size_t)(len(full_payload))) handle := C.MemoryLoadLibraryEx(unsafe.Pointer(&full_payload[0]), (C.size_t)(len(full_payload)), (*[0]byte)(C.MemoryDefaultLoadLibrary), // loadLibrary func ptr (*[0]byte)(C.MemoryDefaultGetProcAddress), // getProcAddress func ptr (*[0]byte)(C.MemoryDefaultFreeLibrary), // freeLibrary func ptr unsafe.Pointer(nil), // void *userdata (we're not passing any data to the dll or exe) ) if handle == nil { fmt.Println("MemoryLoadLibrary failed") os.Exit(1) } //output := C.MemoryCallEntryPoint(handle) _ = C.MemoryCallEntryPoint(handle) //fmt.Println(output) C.MemoryFreeLibrary(handle) """
# Copyright (C) 2019 SignalFx, Inc. All rights reserved. name = 'signalfx_serverless_gcf' version = '0.0.1' user_agent = 'signalfx_serverless/' + version packages = ['signalfx_gcf', 'signalfx_gcf.serverless']
print("Hello! I am a script in python"); def Hi(firstName, lastName): print("Hello " + firstName + " " + lastName)
class GN3: def __init__(self): self.name = 'GN3' def __str__(self): return self.name
# Specialization: Google IT Automation with Python # Course 01: Crash Course with Python # Week 2 Module Part 1 Exercise 02 # Student: Shawn Solomon # Learning Platform: Coursera.org # Practice writing some expressions and conversions yourself. # In this scenario, we have a directory with 5 files in it. Each file has a different size: 2048, 4357, 97658, 125, and 8. # Fill in the blanks to calculate the average file size by having Python add all the values for you, and then set the files variable to the number of files. # Finally, output a message saying "The average size is: " followed by the resulting number. Remember to use the str() function to convert the number into a string. # total = 2048 + ___ + ___ + ___ + ___ # files = ___ # average = total / files # print("___" + str(___)) total = 2048 + 4357 + 97658 + 125 + 8 files = 5 average = total / files print("The average size is: " + str(average))
''' Author: your name Date: 2021-01-29 16:15:21 LastEditTime: 2021-03-18 18:51:14 LastEditors: Please set LastEditors # Description: In User Settings Edit FilePath: \IOe:\代码练习\每日一刷\题源分类\LeetCode\LeetCode日刷\python\92.反转链表-ii.py ''' # # @lc app=leetcode.cn id=92 lang=python3 # # [92] 反转链表 II # # https://leetcode-cn.com/problems/reverse-linked-list-ii/description/ # # algorithms # Medium (50.41%) # Likes: 403 # Dislikes: 0 # Total Accepted: 56.6K # Total Submissions: 112.3K # Testcase Example: '[1,2,3,4,5]\n2\n4' # # 反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。 # # 说明: # 1 ≤ m ≤ n ≤ 链表长度。 # # 示例: # # 输入: 1->2->3->4->5->NULL, m = 2, n = 4 # 输出: 1->4->3->2->5->NULL # # # @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: if not head: return None count = 1 dummy = ListNode(0) dummy.next = head pre = dummy while count < m: pre = pre.next count += 1 cur = pre.next tail = cur p1 = pre pre = None while count <= n: nex = cur.next cur.next = pre pre = cur cur = nex count += 1 p1.next = pre tail.next = cur return dummy.next # @lc code=end # def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: # if not head: # return None # prev,cur = None,head # while m > 1: # prev = cur # cur = cur.next # m,n = m-1,n-1 # tail,con = cur,prev # while n: # third = cur.next # cur.next = prev # prev = cur # cur = third # n -= 1 # if con: # con.next = prev # else: # head = prev # tail.next = cur # return head # def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode: # if not head: # return None # count = 1 # dummy = ListNode(0) # dummy.next = head # pre = dummy # while count < m: # pre = pre.next # count += 1 # cur = pre.next # tail = cur # while cur and count <= n: # nex = cur.next # cur.next = pre.next # pre.next = cur # tail.next = nex # cur = nex # count += 1 # return dummy.next
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of xy-cli. # https://github.com/exiahuang/xy-cli # Licensed under the Apache License 2.0: # http://www.opensource.org/licenses/Apache-2.0 # Copyright (c) 2020, exiahuang <[email protected]> __version__ = '0.8' # NOQA __desc__ = 'xy command tools'
class Stack: def __init__(self) -> None: self.elements = [] def push(self, element): self.elements.append(element) def size(self): return len(self.elements) def pop(self): result = self.elements[self.size()-1] self.elements = self.elements[:self.size()-1] return result def peek(self): result = self.elements[self.size()-1] return result
# Lets attempt to draw two points and have them move also pos_1 = 0 velo_1 = 1 pos_2 = 9 velo_2 = -1 line = 10*[' '] # The code is beginning to be clustered and hard to read for i in range(10): line[pos_1] = '*' line[pos_2] = '*' print("".join(line)) line[pos_1] = ' ' line[pos_2] = ' ' pos_1 += velo_1 pos_2 += velo_2 # Note that if we used the pos now to index the line, we would get errors or wrong behavior print(pos_1, pos_2) print("".join(line)) # This is going to become extremely problematic if we try to go beyond this # If we wanted to add more points or dimensions, the code will quickly degrade`
a = int(input("Enter a -: ")) b = int(input("Enter b -: ")) print("A, B se bada ya barabar h bhai") if a >= b else print( "B, A se bada h bhai")
# A postgres database url # postgresql://[user[:password]@][netloc][:port][/dbname] DATABASE_URL="" # Your discord bot token TOKEN=""
API_TOKEN = '5218149935:AAH8qNCC69ToT29CbWppROwM4lefow9WS7k' # токен от вашего бота в телеграме (взять тут t.me/botfather) number = '79049966033' # номер киви кошелька QIWI_SEC_TOKEN = 'eyJ2ZXJzaW9uIjoiUDJQIiwiZGF0YSI6eyJwYXlpbl9tZXJjaGFudF9zaXRlX3VpZCI6InY3NWU4MS0wMCIsInVzZXJfaWQiOiI3OTA0OTk2NjAzMyIsInNlY3JldCI6Ijk4M2U0ZWQ5MzRjYjIyOTkxNjJkOWMyZjQ4YjBjNzA3ZmU1NWViYzcxYzNjNDY1YjkyMTFmOTVlMzUzOWM1ZWYifX0=' # секретный ключ p2p https://p2p.qiwi.com admin = 1066406624 # id админа, узнать тут t.me/userinfobot admin_name = 'Azq' # username админа, без @
# brute force def find_max_subarray_1(arr): max_sub = float('-inf ') start, end = 0, 0 for i in range(0, len(arr)): sum_of_sub = 0 for j in range(i, len(arr)): sum_of_sub += arr[j] if max_sub < sum_of_sub: max_sub = sum_of_sub start = i end = j return arr[start:end+1] # divide and conquer, 左闭右闭 def find_max_subarray_2(arr, start, end): if start == end: return arr[start] mid = (start + end) // 2 l_max = find_max_subarray_2(arr, start, mid) r_max = find_max_subarray_2(arr, mid + 1, end) cross_max = find_max_cross_subarray(arr, start, end) return max(l_max, r_max, cross_max) def find_max_cross_subarray(arr, start, end): mid = (start + end) // 2 l_sum, l_max = 0, float('-inf') for i in range(mid, start - 1, -1): l_sum += arr[i] if l_max < l_sum: l_max = l_sum r_sum, r_max = 0, float('-inf') for i in range(mid + 1, end + 1): r_sum += arr[i] if r_max < r_sum: r_max = r_sum return l_max + r_max # Dynamic programing def find_max_subarray_3(arr): # cur_max denote the current max subarray ending at index i # glb_max denote the global max subarray among all possible subarray cur_max = glb_max = float('-inf') for i in range(0, len(arr)): # the cur_max(i) is either ith element itself or previous max plus ith max. cur_max = max(arr[i], cur_max + arr[i]) if cur_max > glb_max: glb_max = cur_max return glb_max # reference: # 1. https://www.youtube.com/watch?v=86CQq3pKSUw # 2. https://www.geeksforgeeks.org/maximum-subarray-sum-using-divide-and-conquer-algorithm/ test = [-2, 1, -3, 4, -1, 2, 1, -5, 4] test = [2, 3, 4, 5, 7] print(find_max_subarray_2(test, 0, len(test) - 1)) print(find_max_subarray_3(test))
class Server(object): def __init__(self, crt_name, deploy_full_chain=False, **kwargs): r"""Default server implementation describing interface of a server This is an abstract class, so each specialized method must be overridden in parent class. :param crt_name: name of certificate on server (without any extension like .crt) :type crt_name: str :param deploy_full_chain: if True, deploy server certificate with full chain of trust in crt file else, simply deploy server certificate in crt file :type deploy_full_chain: bool """ self.crt_name = crt_name self.deploy_full_chain = deploy_full_chain def get_description(self): """Get description of this server :return: server description :rtype: str """ raise NotImplementedError("Must be overridden in parent class") def deploy_cert(self, key, cert, **kwargs): r"""Deploy input certificate on server :param key: path to local private key :type key: pathlib.Path :param cert: path to local public certificate :type cert: pathlib.Path :raise exception.DeployCertificateError: if unexpected error occurred during deployment on server """ raise NotImplementedError("Must be overridden in parent class") def create_acme_challenge(self, token, key_authorization): """Create token on server with specified value :param token: challenge key :param key_authorization: challenge value """ raise NotImplementedError("Must be overridden in parent class") def delete_acme_challenge(self, token): """Delete challenge created on server :param token: challenge key to delete from server :type token: str """ raise NotImplementedError("Must be overridden in parent class") def get_certificate_information(self): """Retrieve certificate information from server. Must be implemented for each type of server. :return: SSL certificate information :rtype: autossl.ssl.SslCertificate :raise autossl.exception.CertificateNotFound: if certificate does not exist yet on server """ raise NotImplementedError("Must be overridden in parent class") def is_same(self, common_name=None, sans=None, exact_match=False): """Check if current certificate deployed on server is covering all specified domains :param common_name: Common name :type common_name: str :param sans: list of Subject Alternate Names :type sans: list :param exact_match: if True, certificate must exactly match input domains if False, input domain will also match wilcard certificate and additional domains in certificate will be ignored :type exact_match: bool :return: True is certificate is already covering all domains """ return self.get_certificate_information().is_same(common_name, sans, exact_match) def is_expired(self, expiration_delay=0): """Check for expiration of specified certificate :param expiration_delay: Number of days before real expiration we consider a renewal needed :type expiration_delay: int :return: True is certificate is going to expire in less than expiration_delay days :rtype: bool """ return self.get_certificate_information().is_expired(expiration_delay)
def gcd(a,b): return gcd(b,a%b) if b>0 else a a,b,c=map(int,input().split()) if a*b//gcd(a,b) <=c: print("yes") else: print("no")
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def search_paths(self, root, sum, path, paths): if not(root): return sum -= root.val if sum < 0: return path.append(root.val) if sum == 0: paths.append(path[:]) self.search_paths(root.left, sum, path, paths) self.search_paths(root.right, sum, path, paths) path.pop() def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] Assumptions: root to leaf paths (root has to be included) return list of all the possible paths. Path is a list of integers that sum up to sum. Approach #1: DFS search_paths(root, sum, path, paths) if root == null, return sum -= root.val if sum < 0, return path.append(root.val) if sum == 0, paths.append(path) path.pop() return search_paths(root.left, sum, path, paths) search_paths(root.right, sum, path, paths) path.pop() """ path = [] paths = [] self.search_paths(root, sum, path, paths) return paths # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def search_paths(self, root, sum, path, paths): if not(root): return path.append(root.val) if not(root.left) and not(root.right) and sum == root.val: paths.append(path[:]) if root.left: self.search_paths(root.left, sum-root.val, path, paths) if root.right: self.search_paths(root.right, sum-root.val, path, paths) path.pop() def pathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] Assumptions: root to leaf paths (root has to be included) return list of all the possible paths. Path is a list of integers that sum up to sum. Approach #1: DFS search_paths(root, sum, path, paths) if root == null, return sum -= root.val if sum < 0, return path.append(root.val) if sum == 0, paths.append(path) path.pop() return search_paths(root.left, sum, path, paths) search_paths(root.right, sum, path, paths) path.pop() """ path = [] paths = [] self.search_paths(root, sum, path, paths) return paths
load("@io_bazel_rules_go//go:def.bzl", "go_context", "go_rule") load("@bazel_skylib//lib:shell.bzl", "shell") def _go_vendor(ctx): go = go_context(ctx) out = ctx.actions.declare_file(ctx.label.name + ".sh") substitutions = { "@@GO@@": shell.quote(go.go.path), "@@GAZELLE@@": shell.quote(ctx.executable._gazelle.short_path), } ctx.actions.expand_template( template = ctx.file._template, output = out, substitutions = substitutions, is_executable = True, ) runfiles = ctx.runfiles(files = [go.go, ctx.executable._gazelle]) return [ DefaultInfo( runfiles = runfiles, executable = out, ), ] go_vendor = go_rule( implementation = _go_vendor, executable = True, attrs = { "_template": attr.label( default = "//build/rules/go:vendor.bash", allow_single_file = True, ), "_gazelle": attr.label( default = "@bazel_gazelle//cmd/gazelle", executable = True, cfg = "host", ), }, )
# ------------------------------ # 137. Single Number II # # Description: # Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one. # Note: # Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? # Example 1: # Input: [2,2,3,2] # Output: 3 # # Example 2: # Input: [0,1,0,1,0,1,99] # Output: 99 # # Version: 1.0 # 08/20/18 by Jianfa # ------------------------------ class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ while nums: n = nums.pop(0) if n in nums: nums.remove(n) nums.remove(n) else: return n # Used for testing if __name__ == "__main__": test = Solution() # ------------------------------ # Summary: # Top voted solution: # public int singleNumber(int[] A) { # int ones = 0, twos = 0; # for(int i = 0; i < A.length; i++){ # ones = (ones ^ A[i]) & ~twos; # twos = (twos ^ A[i]) & ~ones; # } # return ones; # }
class InputPin: """ The Rosetta graph input pin """ # TODO: Should be able to find connected output pin - so traversal up the graph is possible. def __init__(self, pin_name, mime_type_map, filter): """ c'tor :param pin_name: The name of the pin for diagnostics, etc. :param mime_type_map: Maps a mime type to a handler. * maps everything. :param filter: A reference to the filter to which this pin belongs. """ self._pin_name = pin_name self._mime_type_map = mime_type_map self._filter = filter @property def pin_name(self): return self._pin_name def recv(self, mime_type, payload, metadata_dict): """ Receive a payload. Payload must be in either str or a binary sequence convertible to bytes format. :param mime_type: The mime_type of the payload being received :param payload: The payload to be received :param metadata_dict: A dictionary of metadata values to be passed down the filter chain :return: None """ disp_fun = self._mime_type_map.get(mime_type) if disp_fun is None: disp_fun = self._mime_type_map.get('*') if disp_fun is None: raise ValueError("Pin {0} could not find a dispatcher for {1}".format(self._pin_name, mime_type)) disp_fun(mime_type, payload, metadata_dict)
# # PySNMP MIB module CTRON-SFPS-COMMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-SFPS-COMMON-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:30:50 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection") sfpsSystemGenerics, sfpsDiagEventLog, sfpsAOPropertiesAPI, sfpsAOProperties = mibBuilder.importSymbols("CTRON-SFPS-INCLUDE-MIB", "sfpsSystemGenerics", "sfpsDiagEventLog", "sfpsAOPropertiesAPI", "sfpsAOProperties") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Integer32, TimeTicks, Counter32, Counter64, Gauge32, IpAddress, ObjectIdentity, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Unsigned32, iso, NotificationType, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "TimeTicks", "Counter32", "Counter64", "Gauge32", "IpAddress", "ObjectIdentity", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Unsigned32", "iso", "NotificationType", "Bits") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") class HexInteger(Integer32): pass sfpsGenericVersionTable = MibTable((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 3, 1), ) if mibBuilder.loadTexts: sfpsGenericVersionTable.setStatus('mandatory') if mibBuilder.loadTexts: sfpsGenericVersionTable.setDescription('Table describing the SFS generics and their versions that are contained within this image.') sfpsGenericVersionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 3, 1, 1), ).setIndexNames((0, "CTRON-SFPS-COMMON-MIB", "sfpsGenericVersionHash")) if mibBuilder.loadTexts: sfpsGenericVersionEntry.setStatus('mandatory') if mibBuilder.loadTexts: sfpsGenericVersionEntry.setDescription('An entry in the table instanced by the Generic name.') sfpsGenericVersionHash = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 3, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsGenericVersionHash.setStatus('mandatory') if mibBuilder.loadTexts: sfpsGenericVersionHash.setDescription('Hash of the name to make it a unique entry.') sfpsGenericVersionName = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 3, 1, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsGenericVersionName.setStatus('mandatory') if mibBuilder.loadTexts: sfpsGenericVersionName.setDescription('Name of the Generic.') sfpsGenericVersionVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 3, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsGenericVersionVersion.setStatus('mandatory') if mibBuilder.loadTexts: sfpsGenericVersionVersion.setDescription('Version stamp of the generic component.') sfpsGenericVersionMIBRev = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 3, 1, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsGenericVersionMIBRev.setStatus('mandatory') if mibBuilder.loadTexts: sfpsGenericVersionMIBRev.setDescription('MIB version of the generic component.') sfpsDiagLogConfigTable = MibTable((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1), ) if mibBuilder.loadTexts: sfpsDiagLogConfigTable.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigTable.setDescription('This table contains the informtion to configure an Event Logger object.') sfpsDiagLogConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1), ).setIndexNames((0, "CTRON-SFPS-COMMON-MIB", "sfpsDiagLogConfigInstance")) if mibBuilder.loadTexts: sfpsDiagLogConfigEntry.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigEntry.setDescription('Each entry contains configuration data.') sfpsDiagLogConfigInstance = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsDiagLogConfigInstance.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigInstance.setDescription('The instance of this Event Logger.') sfpsDiagLogConfigStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("enabled", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigStatus.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigStatus.setDescription('The status of this Event Logger object.') sfpsDiagLogConfigIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsDiagLogConfigIndex.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigIndex.setDescription('The current index in the circular buffer where events are being logged.') sfpsDiagLogConfigStart = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 4), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigStart.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigStart.setDescription('The starting index in the circular buffer to display.') sfpsDiagLogConfigStop = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 5), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigStop.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigStop.setDescription('The last index in the circular buffer to display.') sfpsDiagLogConfigLogIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 6), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigLogIndex.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigLogIndex.setDescription('The current index in the log buffer where we are looking.') sfpsDiagLogConfigFilterMatch = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 7), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigFilterMatch.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigFilterMatch.setDescription('The specified Event Id to log. A value of 0 will cause every event to be logged.') sfpsDiagLogConfigFilterStart = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 8), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigFilterStart.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigFilterStart.setDescription('The beginning range of Event Ids to log.') sfpsDiagLogConfigFilterStop = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 9), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigFilterStop.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigFilterStop.setDescription('The ending range of Event Ids to log.') sfpsDiagLogAccessPortControl = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 10), HexInteger()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogAccessPortControl.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogAccessPortControl.setDescription('Leaf to be used to set a port bit mask. This bit mask represents which ports shall be statically set to be an ACCESS port. Bit 0 corresponds to Port 1.') sfpsDiagLogCallIdleTime = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 11), Integer32().clone(60)).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogCallIdleTime.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogCallIdleTime.setDescription('Leaf to be used to set a debug variable. (in seconds)') sfpsDiagLogFilterAddTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 12), Integer32().clone(900)).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogFilterAddTimer.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogFilterAddTimer.setDescription('Leaf to be used to set how long a filter connection should be (Default : 900 seconds)') sfpsDiagLogRedirectorWakeup = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 13), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogRedirectorWakeup.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogRedirectorWakeup.setDescription('Leaf to be used to set how often the Redirector wakes up to service the queue (in seconds)') sfpsDiagLogRedirectorNumPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 14), Integer32().clone(64)).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogRedirectorNumPackets.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogRedirectorNumPackets.setDescription('Leaf to be used to set how many packets the Redirector reads off at a time.') sfpsDiagLogEndSystemTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 15), Integer32().clone(600)).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogEndSystemTimeout.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogEndSystemTimeout.setDescription('Leaf to be used to set a debug variable. (Default : 10 minutes) (in seconds)') sfpsDiagLogSwitchIdleInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 16), Integer32().clone(30)).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogSwitchIdleInterval.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogSwitchIdleInterval.setDescription('Leaf to be used to set a debug variable. (in seconds)') sfpsDiagLogInlnFltrAgeTime = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 17), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogInlnFltrAgeTime.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogInlnFltrAgeTime.setDescription('Leaf to be used to set the BAF age time (seconds).') sfpsDiagLogConfigDebug9 = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 18), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigDebug9.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigDebug9.setDescription('Leaf to be used to set a debug variable.') sfpsDiagLogSignalThrottle = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 19), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogSignalThrottle.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogSignalThrottle.setDescription('Leaf to be used to set the Signal Thottle knob. Throttling defaults to off. By setting it to 1,2,5, or 10 one can dictate the rate (signal/second) at which SFPS sends signals to the ACMS Signal Stack..') sfpsDiagLogConfigOther = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("string", 1), ("integer", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigOther.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigOther.setDescription('Dictates the format of the Event to be displayed (either Text or Integer values).') sfpsDiagLogConfigSoftReset = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 21), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigSoftReset.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigSoftReset.setDescription('') sfpsDiagLogConfigSFPSVlan = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 2, 6, 1, 1, 1, 22), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsDiagLogConfigSFPSVlan.setStatus('mandatory') if mibBuilder.loadTexts: sfpsDiagLogConfigSFPSVlan.setDescription('') sfpsAOPropertiesTable = MibTable((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1), ) if mibBuilder.loadTexts: sfpsAOPropertiesTable.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesTable.setDescription('') sfpsAOPropertiesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1, 1), ).setIndexNames((0, "CTRON-SFPS-COMMON-MIB", "sfpsAOPropertiesTag")) if mibBuilder.loadTexts: sfpsAOPropertiesEntry.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesEntry.setDescription('An entry in the table instanced by the tag.') sfpsAOPropertiesTag = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesTag.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesTag.setDescription('') sfpsAOPropertiesTagDescriptor = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1, 1, 2), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesTagDescriptor.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesTagDescriptor.setDescription('') sfpsAOPropertiesPrettyType = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1, 1, 3), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesPrettyType.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesPrettyType.setDescription('') sfpsAOPropertiesNumBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesNumBytes.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesNumBytes.setDescription('') sfpsAOPropertiesIsLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("false", 1), ("true", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesIsLimit.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesIsLimit.setDescription('') sfpsAOPropertiesIsMobile = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("false", 1), ("true", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesIsMobile.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesIsMobile.setDescription('') sfpsAOPropertiesIsSingle = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("false", 1), ("true", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesIsSingle.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesIsSingle.setDescription('') sfpsAOPropertiesNoBlock = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("false", 1), ("true", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesNoBlock.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesNoBlock.setDescription('') sfpsAOPropertiesNoDelta = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("false", 1), ("true", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesNoDelta.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesNoDelta.setDescription('') sfpsAOPropertiesAPITag = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 2, 1), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsAOPropertiesAPITag.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesAPITag.setDescription('') sfpsAOPropertiesAPITagString = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 2, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesAPITagString.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesAPITagString.setDescription('') sfpsAOPropertiesAPIPrettyType = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 2, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesAPIPrettyType.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesAPIPrettyType.setDescription('') sfpsAOPropertiesAPINumBytes = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 2, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: sfpsAOPropertiesAPINumBytes.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesAPINumBytes.setDescription('') sfpsAOPropertiesAPIIsLimit = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 2, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notSet", 1), ("false", 2), ("true", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsAOPropertiesAPIIsLimit.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesAPIIsLimit.setDescription('') sfpsAOPropertiesAPIIsMobile = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 2, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notSet", 1), ("false", 2), ("true", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsAOPropertiesAPIIsMobile.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesAPIIsMobile.setDescription('') sfpsAOPropertiesAPIIsSingle = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 2, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notSet", 1), ("false", 2), ("true", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsAOPropertiesAPIIsSingle.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesAPIIsSingle.setDescription('') sfpsAOPropertiesAPINoBlock = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 2, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notSet", 1), ("false", 2), ("true", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsAOPropertiesAPINoBlock.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesAPINoBlock.setDescription('') sfpsAOPropertiesAPINoDelta = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 2, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notSet", 1), ("false", 2), ("true", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsAOPropertiesAPINoDelta.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesAPINoDelta.setDescription('') sfpsAOPropertiesAPIAction = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 2, 4, 2, 1, 1, 5, 2, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("readProperties", 1), ("setProperties", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sfpsAOPropertiesAPIAction.setStatus('mandatory') if mibBuilder.loadTexts: sfpsAOPropertiesAPIAction.setDescription('') mibBuilder.exportSymbols("CTRON-SFPS-COMMON-MIB", sfpsDiagLogConfigDebug9=sfpsDiagLogConfigDebug9, sfpsDiagLogConfigOther=sfpsDiagLogConfigOther, sfpsGenericVersionVersion=sfpsGenericVersionVersion, sfpsDiagLogConfigStatus=sfpsDiagLogConfigStatus, sfpsDiagLogEndSystemTimeout=sfpsDiagLogEndSystemTimeout, sfpsAOPropertiesTable=sfpsAOPropertiesTable, sfpsDiagLogConfigIndex=sfpsDiagLogConfigIndex, sfpsAOPropertiesNoBlock=sfpsAOPropertiesNoBlock, sfpsAOPropertiesAPIAction=sfpsAOPropertiesAPIAction, sfpsDiagLogConfigSFPSVlan=sfpsDiagLogConfigSFPSVlan, sfpsDiagLogSwitchIdleInterval=sfpsDiagLogSwitchIdleInterval, sfpsAOPropertiesAPIPrettyType=sfpsAOPropertiesAPIPrettyType, sfpsDiagLogConfigFilterMatch=sfpsDiagLogConfigFilterMatch, sfpsGenericVersionEntry=sfpsGenericVersionEntry, sfpsAOPropertiesTag=sfpsAOPropertiesTag, HexInteger=HexInteger, sfpsDiagLogRedirectorNumPackets=sfpsDiagLogRedirectorNumPackets, sfpsDiagLogConfigFilterStop=sfpsDiagLogConfigFilterStop, sfpsAOPropertiesPrettyType=sfpsAOPropertiesPrettyType, sfpsDiagLogConfigLogIndex=sfpsDiagLogConfigLogIndex, sfpsAOPropertiesAPIIsLimit=sfpsAOPropertiesAPIIsLimit, sfpsAOPropertiesAPINumBytes=sfpsAOPropertiesAPINumBytes, sfpsDiagLogConfigInstance=sfpsDiagLogConfigInstance, sfpsAOPropertiesAPINoBlock=sfpsAOPropertiesAPINoBlock, sfpsAOPropertiesAPINoDelta=sfpsAOPropertiesAPINoDelta, sfpsAOPropertiesIsMobile=sfpsAOPropertiesIsMobile, sfpsDiagLogRedirectorWakeup=sfpsDiagLogRedirectorWakeup, sfpsAOPropertiesIsLimit=sfpsAOPropertiesIsLimit, sfpsDiagLogAccessPortControl=sfpsDiagLogAccessPortControl, sfpsAOPropertiesNoDelta=sfpsAOPropertiesNoDelta, sfpsAOPropertiesAPIIsSingle=sfpsAOPropertiesAPIIsSingle, sfpsDiagLogSignalThrottle=sfpsDiagLogSignalThrottle, sfpsAOPropertiesAPIIsMobile=sfpsAOPropertiesAPIIsMobile, sfpsGenericVersionHash=sfpsGenericVersionHash, sfpsDiagLogConfigTable=sfpsDiagLogConfigTable, sfpsAOPropertiesEntry=sfpsAOPropertiesEntry, sfpsDiagLogConfigEntry=sfpsDiagLogConfigEntry, sfpsGenericVersionName=sfpsGenericVersionName, sfpsDiagLogCallIdleTime=sfpsDiagLogCallIdleTime, sfpsGenericVersionTable=sfpsGenericVersionTable, sfpsDiagLogFilterAddTimer=sfpsDiagLogFilterAddTimer, sfpsDiagLogConfigStop=sfpsDiagLogConfigStop, sfpsAOPropertiesAPITagString=sfpsAOPropertiesAPITagString, sfpsAOPropertiesTagDescriptor=sfpsAOPropertiesTagDescriptor, sfpsDiagLogConfigFilterStart=sfpsDiagLogConfigFilterStart, sfpsDiagLogConfigStart=sfpsDiagLogConfigStart, sfpsGenericVersionMIBRev=sfpsGenericVersionMIBRev, sfpsAOPropertiesAPITag=sfpsAOPropertiesAPITag, sfpsDiagLogConfigSoftReset=sfpsDiagLogConfigSoftReset, sfpsAOPropertiesNumBytes=sfpsAOPropertiesNumBytes, sfpsDiagLogInlnFltrAgeTime=sfpsDiagLogInlnFltrAgeTime, sfpsAOPropertiesIsSingle=sfpsAOPropertiesIsSingle)
print("git UNT ") print("git lunes")
def metaLine2metaDict(metaLine): metaDict = {} fields = metaLine.split(';') for field in fields: fl = field.split('=') subfieldName = fl[0] fieldInfo = fl[1] metaDict[subfieldName] = fieldInfo return metaDict def getGeneInformationFromGFFline(line, field): result = False if not line.startswith('#'): ll = line.strip().split('\t') if len(ll) > 2 and ll[2] == 'gene': start = ll[3] end = ll[4] strand = ll[6] metaLine = ll[8] metaDict= metaLine2metaDict(metaLine) result = metaDict[field] return result
s=input('Enter Main String:') subs=input('Enter Substring to search:') if subs in s: print(subs, 'Is found in Main String') else: print(subs, 'is not found in Main String')
class Solution(object): def maxProduct(self, nums): """ :type nums: List[int] :rtype: int """ max_product = local_min = local_max = nums[0] for i in range(1, len(nums)): cur = nums[i] local_min, local_max = min(min(cur*local_min, cur*local_max), cur), max(max(cur*local_min, cur*local_max), cur) max_product = max(max_product, local_max) return max_product
# automatically generated by the FlatBuffers compiler, do not modify # namespace: FBS class FByteDataType(object): UINT8 = 0 FLOAT16 = 1 FLOAT32 = 2 PNG = 3 JPEG = 4 Other = 5
FILE_PATH = './Day4/input.txt' def parseData(recordData): record = {} for data in recordData: fieldPairs = data.split(' ') for fieldPair in fieldPairs: field, value = fieldPair.split(':') record[field] = value if field not in ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid', 'cid']: print('What no!!! {}'.format(field)) return record def readFile(path): f = open(path, 'r') records = [] recordData = [] for l in f: l = l.strip() if l == '': record = parseData(recordData) records.append(record) recordData = [] else: recordData.append(l) records.append(parseData(recordData)) return records def isPassportValid(record): requiredFields = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] for field in requiredFields: if not field in record: print('missingField: {}. {}'.format(field, record)) return False return True def checkPassports(): records = readFile(FILE_PATH) print('{} passports'.format(len(records))) count = 0 for rec in records: if isPassportValid(rec): count += 1 return count def validateBYR(byr): if not byr.isnumeric() or len(byr) != 4: return False byrNum = int(byr) return byrNum >= 1920 and byrNum <= 2002 def validateIYR(iyr): if not iyr.isnumeric() or len(iyr) != 4: return False iyrNum = int(iyr) return iyrNum >= 2010 and iyrNum <= 2020 def validateEYR(eyr): if not eyr.isnumeric() or len(eyr) != 4: return False eyrNum = int(eyr) return eyrNum >= 2020 and eyrNum <= 2030 def validateHeight(height): if len(height) < 4: return False if height[-2:] == 'cm': hVal = height[:-2] if hVal.isnumeric(): hNum = int(hVal) return hNum <= 193 and hNum >= 150 elif height[-2:] == 'in': hVal = height[:-2] if hVal.isnumeric(): hNum = int(hVal) return hNum <= 76 and hNum >= 59 return False def validateHCL(hcl): if len(hcl) != 7 or hcl[0] != '#': return False validChars = '1234567890abcdef' for i in range(1, len(hcl)): if hcl[i] not in validChars: return False return True def validateECL(ecl): validClr = set(['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']) return ecl in validClr def validatePID(pid): return len(pid) == 9 and pid.isnumeric() def validatePassport(passport): if not isPassportValid(passport): return False if not validateBYR(passport['byr']): return False if not validateIYR(passport['iyr']): return False if not validateEYR(passport['eyr']): return False if not validateHeight(passport['hgt']): return False if not validateHCL(passport['hcl']): return False if not validateECL(passport['ecl']): return False if not validatePID(passport['pid']): return False return True def validatePassports(): records = readFile(FILE_PATH) count = 0 for rec in records: if validatePassport(rec): count += 1 return count if __name__ == "__main__": # print(checkPassports()) print(validatePassports())
""" TASK1: Finding the Square Root of an Integer Find the square root of the integer without using any Python library. You have to find the floor value of the square root. For example if the given number is 16, then the answer would be 4. If the given number is 27, the answer would be 5 because sqrt(5) = 5.196 whose floor value is 5. The expected time complexity is O(log(n)) """ def sqrt_slower(number: int) -> int: """ Calculate the floored square root of a number Args: number(int): Number to find the floored squared root Returns: int: Floored Square Root """ print("->sqrt for number " + str(number)) if number == 0: return 0 if number is None or number < 0: return "Error" if number == 1: return 1 counter = 2 while True: square = counter * counter print("counter= " + str(counter) + ", square=" + str(square)) if square == number: return counter elif square < number: counter += 1 else: return counter - 1 # Newton's method def sqrt(number: int) -> int: if number == 0: return 0 if number is None or number < 0: return "Error" x = number y = (x + 1) // 2 while y < x: x = y y = (x + number // x) // 2 print("x=" + str(x) + ", y=" + str(y)) return x def test_sqrt(): print("case1----------------------------------------------------------------------------------") # case1 expected_result = 3 actual_result = sqrt(9) print("result= " + str(actual_result)) assert (expected_result == actual_result), "{}expected is {}, actual is {}".format("case1: ", expected_result, actual_result) print("\ncase2----------------------------------------------------------------------------------") # case2 expected_result = 0 actual_result = sqrt(0) print("result= " + str(actual_result)) assert (expected_result == actual_result), "{}expected is {}, actual is {}".format("case2: ", expected_result, actual_result) print("\ncase3----------------------------------------------------------------------------------") # case3 expected_result = 4 actual_result = sqrt(16) print("result= " + str(actual_result)) assert (expected_result == actual_result), "{}expected is {}, actual is {}".format("case3: ", expected_result, actual_result) print("\ncase4----------------------------------------------------------------------------------") # case4 expected_result = 1 actual_result = sqrt(1) print("result= " + str(actual_result)) assert (expected_result == actual_result), "{}expected is {}, actual is {}".format("case4: ", expected_result, actual_result) print("\ncase5----------------------------------------------------------------------------------") # case5 expected_result = 5 actual_result = sqrt(27) print("result= " + str(actual_result)) assert (expected_result == actual_result), "{}expected is {}, actual is {}".format("case5: ", expected_result, actual_result) print("\ncase6----------------------------------------------------------------------------------") # case6 expected_result = 5 actual_result = sqrt(34) print("result= " + str(actual_result)) assert (expected_result == actual_result), "{}expected is {}, actual is {}".format("case6: ", expected_result, actual_result) print("\ncase7----------------------------------------------------------------------------------") # case6 expected_result = 32 actual_result = sqrt(1024) print("result= " + str(actual_result)) assert (expected_result == actual_result), "{}expected is {}, actual is {}".format("case7: ", expected_result, actual_result) print("\ncase8----------------------------------------------------------------------------------") # case7 expected_result = "Error" actual_result = sqrt(None) print("result= " + str(actual_result)) assert (expected_result == actual_result), "{}expected is {}, actual is {}".format("case8: ", expected_result, actual_result) print("\ncase9----------------------------------------------------------------------------------") # case8 expected_result = "Error" actual_result = sqrt(-16) print("result= " + str(actual_result)) assert (expected_result == actual_result), "{}expected is {}, actual is {}".format("case9: ", expected_result, actual_result) test_sqrt()
#– O nome com todas as letras maiúsculas e minúsculas. #– Quantas letras ao todo (sem considerar espaços). #– Quantas letras tem o primeiro nome. """""essas três aspas duplas é uma maneira de fazer um comentario grande""" """ essa é a primeira maneira n =str(input('Digite o seu nome completo')) print(n.upper()) print(n.lower()) nome=n.split() print(f'O seu primeiro nome é {nome[0]} ') print(len(nome[0])) resp=''.join(nome) print(len(resp)) """
print(60*'=') print(' CAIXA ELETRONICO ') print(60*'=') total = int(input('Que valor deseja sacar ? R$ ')) cedula = 50 totalced = 0 while True: if total >= cedula: total-=cedula totalced+=1 print(total) else: if totalced>0: print(f'Total de {totalced} cedulas de R$ {cedula}') if cedula==50: cedula = 20 elif cedula==20: cedula = 10 elif cedula==10: cedula=1 totalced= 0 if total == 0: break print(60*'=') print(' VOLTE SEMPRE ')
class BaseRandomizer(): def __init__(self, projectName=None, seed=None, programMode=True) -> None: self.seed = seed if programMode: self.inputPath = f'projects/{projectName}/tmp/text/' else: self.inputPath = f'projects/{projectName}/text/'
""" This constant file was automatically generated by a quick script I wrote for the enum part and h2py for the constant part. It aims to help out remembering the enum values and constants, but probably as bugs... please refer to the actual documentation for the correct values (if something is not working) and feel free to correct the values and submit a pull request. """ class EWfmItem: WfmItem_MARKER1 = 1 WfmItem_MARKER2 = 2 WfmItem_DIGITAL0 = 3 WfmItem_DIGITAL1 = 4 WfmItem_DIGITAL2 = 5 WfmItem_DIGITAL3 = 6 WfmItem_DIGITAL4 = 7 WfmItem_DIGITAL5 = 8 WfmItem_DIGITAL6 = 9 WfmItem_DIGITAL7 = 10 WfmItem_DIGITAL8 = 11 WfmItem_DIGITAL9 = 12 WfmItem_DIGITAL10 = 13 WfmItem_DIGITAL11 = 14 WfmItem_DIGITAL12 = 15 WfmItem_DIGITAL13 = 16 class ELogicSignature: LogicSignature_0 = 1 LogicSignature_1 = 2 LogicSignature_MIX = 3 class EStdWfmType: StdWfmType_SQUARE = 1 StdWfmType_TRIANGLE = 2 StdWfmType_RAMP = 3 StdWfmType_GAUSSIAN_NOISE = 4 class EPointDrawInterpolationType: PointDrawInterpolationType_SPLINE = 1 class EDualWfmMathType: MATH_SUB = 1 class EMarkDensity: MARK_DENSITY_1_4 = 1 MARK_DENSITY_1_2 = 2 MARK_DENSITY_3_4 = 3 class ESeqItem: ITEM_WFM_CH2 = 1 ITEM_WFM_CH3 = 2 ITEM_WFM_CH4 = 3 ITEM_WAIT = 4 ITEM_LOOP = 5 ITEM_JUMP_TO = 6 ITEM_GO_TO = 7 class ECalDiagType: CAL_DIAG_TYPE_YIG = 1 CAL_DIAG_TYPE_CLOCKPOWER = 2 CAL_DIAG_TYPE_IPC = 3 CAL_DIAG_TYPE_DTIMING = 4 CAL_DIAG_TYPE_ANALOG = 5 CAL_DIAG_TYPE_MARKER = 6 CAL_DIAG_TYPE_MDELAY = 7 CAL_DIAG_TYPE_MCPOINT = 8 CAL_DIAG_TYPE_SKEW = 9 class EUserCalDiagType: USER_CALDIAG_TYPE_D_AWG_REGISTER = 1 USER_CALDIAG_TYPE_D_AWG_WFM_MEM_CH1 = 2 USER_CALDIAG_TYPE_D_AWG_WFM_MEM_CH2 = 3 USER_CALDIAG_TYPE_D_AWG_WFM_MEM_CH3 = 4 USER_CALDIAG_TYPE_D_AWG_WFM_MEM_CH4 = 5 USER_CALDIAG_TYPE_D_CLOCK_REGISTER = 6 USER_CALDIAG_TYPE_D_CLOCK_PLL = 7 USER_CALDIAG_TYPE_D_OUTPUT1_REGISTER = 8 USER_CALDIAG_TYPE_D_OUTPUT1_ANALOG = 9 USER_CALDIAG_TYPE_D_OUTPUT1_MARKER = 10 USER_CALDIAG_TYPE_D_OUTPUT2_REGISTER = 11 USER_CALDIAG_TYPE_D_OUTPUT2_ANALOG = 12 USER_CALDIAG_TYPE_D_OUTPUT2_MARKER = 13 USER_CALDIAG_TYPE_C_LEVEL_ANALOG_CH1 = 14 USER_CALDIAG_TYPE_C_LEVEL_MARKER_CH1 = 15 USER_CALDIAG_TYPE_C_LEVEL_ANALOG_CH2 = 16 USER_CALDIAG_TYPE_C_LEVEL_MARKER_CH2 = 17 USER_CALDIAG_TYPE_C_LEVEL_ANALOG_CH3 = 18 USER_CALDIAG_TYPE_C_LEVEL_MARKER_CH3 = 19 USER_CALDIAG_TYPE_C_LEVEL_ANALOG_CH4 = 20 USER_CALDIAG_TYPE_C_LEVEL_MARKER_CH4 = 21 USER_CALDIAG_TYPE_D_AWG_DTIMING = 22 USER_CALDIAG_TYPE_D_OUTPUT1_ANALOG_2 = 23 class EClockSource: ClockSource_INTERNAL = 1 ClockSource_EXTERNAL = 2 class EReferenceSource: ReferenceSource_INTERNAL = 1 ReferenceSource_EXTERNAL = 2 class EReferenceType: ReferenceType_Fixed = 1 ReferenceType_Variable = 2 class EReferenceClockFrequency: ReferenceClockFrequency_10MHZ = 1 ReferenceClockFrequency_20MHZ = 2 ReferenceClockFrequency_100MHZ = 3 class EDividerRate: DividerRate_DIV_1 = 1 DividerRate_DIV_2 = 2 DividerRate_DIV_4 = 3 DividerRate_DIV_8 = 4 DividerRate_DIV_16 = 5 DividerRate_DIV_32 = 6 DividerRate_DIV_64 = 7 DividerRate_DIV_128 = 8 DividerRate_DIV_256 = 9 class EExternalReferenceStatus: ExternalReferenceStatus_INPUT_OK = 1 ExternalReferenceStatus_INPUT_MISSING = 2 ExternalReferenceStatus_INPUT_OUT_OF_RANGE = 3 ExternalReferenceStatus_INPUT_UNSTABLE = 4 class EExternalOscillatorStatus: ExternalOscillatorStatus_INPUT_OK = 1 ExternalOscillatorStatus_INPUT_MISSING = 2 ExternalOscillatorStatus_INPUT_OUT_OF_RANGE = 3 ExternalOscillatorStatus_INPUT_UNSTABLE = 4 class ETriggerSource: TriggerSource_EXTERNAL = 1 TriggerSource_INTERNAL = 2 class ETriggerInputImpedance: TriggerInputImpedance_50OHM = 1 TriggerInputImpedance_1KOHM = 2 class ETriggerInputSlope: TriggerInputSlope_POL_POSITIVE = 1 TriggerInputSlope_POL_NEGATIVE = 2 class ETriggerInputPolarity: TriggerInputPolarity_POSITIVE = 1 TriggerInputPolarity_NEGATIVE = 2 class EEventInputImpedance: EventInputImpedance_50OHM = 1 EventInputImpedance_1KOHM = 2 class EEventInputPolarity: EventInputPolarity_POSITIVE = 1 EventInputPolarity_NEGATIVE = 2 class EJumpTiming: JumpTiming_SYNC = 1 JumpTiming_ASYNC = 2 class EAnalogInputMethod: AnalogInputMethod_IMAmplitudeOffset = 1 AnalogInputMethod_IMHighLow = 2 class EDacResolution: DacResolution_8 = 1 DacResolution_10 = 2 DacResolution_14 = 3 class EFilter: Filter_20MHZ = 1 Filter_50MHZ = 2 Filter_100MHZ = 3 Filter_200MHZ = 4 Filter_THROUGH = 5 class EMarkerInputMethod: MarkerInputMethod_IMAmplitudeOffset = 1 MarkerInputMethod_IMHighLow = 2 class EChannelCoupling: ChannelCoupling_Off = 1 ChannelCoupling_Pair = 2 ChannelCoupling_All = 3 class ERunMode: RunMode_CONTINUOUS = 1 RunMode_TRIGGERED = 2 RunMode_GATED = 3 RunMode_SEQUENCE = 4 class ESequencerState: SequencerState_STOPPED = 1 SequencerState_RUNNING = 2 SequencerState_WAIT_FOR_TRIGGER = 3 class ESequencerType: SequencerType_HW = 1 SequencerType_SW = 2 class EWaitValue: WaitValue_FIRST = 1 WaitValue_LAST = 2 class EJumpTargetType: JumpTargetType_OFF = 1 JumpTargetType_INDEX = 2 JumpTargetType_NEXT = 3 class EWaveformType: WaveformType_INTEGER = 1 WaveformType_REAL = 2 class EWfmDacResolution: WfmDacResolution_8 = 1 WfmDacResolution_10 = 2 WfmDacResolution_14 = 3 class EOverHeat: OverHeat_None = 1 OverHeat_Message = 2 OverHeat_Shutdown = 3 class EDigitalInputMethod: DigitalInputMethod_IMAmplitudeOffset = 1 DigitalInputMethod_IMHighLow = 2 class ENormalizationType: NormalizationType_NONE = 1 NormalizationType_FULL_SCALE = 2 NormalizationType_ZERO_REFERENCE = 3 class EPhaseDelayInputMethod: PhaseDelayInputMethod_PHASE = 1 PhaseDelayInputMethod_DELAY_IN_TIME = 2 class ETeklinkConnectionType: TeklinkConnectionType_NONE = 1 TeklinkConnectionType_HUB = 2 TeklinkConnectionType_INSTRUMENT = 3 class ETeklinkCpState: TeklinkCpState_NOTRUNNING = 1 TeklinkCpState_RUNNING = 2 TeklinkCpState_PENDING = 3 class EJumpMode: JumpMode_EVENT = 1 JumpMode_TABLE = 2 class Commands: CS_MAGIC = "MAGIC" CS_VERSION = "VERSION" CS_SAMPLING_RATE = "SAMPLING_RATE" CS_REPETITION_RATE = "REPETITION_RATE" CS_HOLD_REPETITION_RATE = "HOLD_REPETITION_RATE" CS_CLOCK_SOURCE = "CLOCK_SOURCE" CS_REFERENCE_SOURCE = "REFERENCE_SOURCE" CS_EXTERNAL_REFERENCE_TYPE = "EXTERNAL_REFERENCE_TYPE" CS_REFERENCE_CLOCK_FREQUENCY_SELECTION = "REFERENCE_CLOCK_FREQUENCY_SELECTION" CS_REFERENCE_MULTIPLIER_RATE = "REFERENCE_MULTIPLIER_RATE" CS_DIVIDER_RATE = "DIVIDER_RATE" CS_TRIGGER_SOURCE = "TRIGGER_SOURCE" CS_INTERNAL_TRIGGER_RATE = "INTERNAL_TRIGGER_RATE" CS_TRIGGER_INPUT_IMPEDANCE = "TRIGGER_INPUT_IMPEDANCE" CS_TRIGGER_INPUT_SLOPE = "TRIGGER_INPUT_SLOPE" CS_TRIGGER_INPUT_POLARITY = "TRIGGER_INPUT_POLARITY" CS_TRIGGER_INPUT_THRESHOLD = "TRIGGER_INPUT_THRESHOLD" CS_EVENT_INPUT_IMPEDANCE = "EVENT_INPUT_IMPEDANCE" CS_EVENT_INPUT_POLARITY = "EVENT_INPUT_POLARITY" CS_EVENT_INPUT_THRESHOLD = "EVENT_INPUT_THRESHOLD" CS_JUMP_TIMING = "JUMP_TIMING" CS_INTERLEAVE = "INTERLEAVE" CS_ZEROING = "ZEROING" CS_INTERLEAVE_ADJ_PHASE = "INTERLEAVE_ADJ_PHASE" CS_INTERLEAVE_ADJ_AMPLITUDE = "INTERLEAVE_ADJ_AMPLITUDE" CS_COUPLING = "COUPLING" CS_RUN_MODE = "RUN_MODE" CS_WAIT_VALUE = "WAIT_VALUE" CS_RUN_STATE = "RUN_STATE" CS_EVENT_JUMP_MODE = "EVENT_JUMP_MODE" CS_TABLE_JUMP_STROBE = "TABLE_JUMP_STROBE" CS_TABLE_JUMP_DEFINITION = "TABLE_JUMP_DEFINITION" CS_DAC_RESOLUTION_1 = "DAC_RESOLUTION_1" CS_OUTPUT_WAVEFORM_NAME_1 = "OUTPUT_WAVEFORM_NAME_1" CS_CHANNEL_STATE_1 = "CHANNEL_STATE_1" CS_ANALOG_DIRECT_OUTPUT_1 = "ANALOG_DIRECT_OUTPUT_1" CS_ANALOG_FILTER_1 = "ANALOG_FILTER_1" CS_ANALOG_METHOD_1 = "ANALOG_METHOD_1" CS_ANALOG_AMPLITUDE_1 = "ANALOG_AMPLITUDE_1" CS_ANALOG_OFFSET_1 = "ANALOG_OFFSET_1" CS_ANALOG_HIGH_1 = "ANALOG_HIGH_1" CS_ANALOG_LOW_1 = "ANALOG_LOW_1" CS_MARKER1_SKEW_1 = "MARKER1_SKEW_1" CS_MARKER1_METHOD_1 = "MARKER1_METHOD_1" CS_MARKER1_AMPLITUDE_1 = "MARKER1_AMPLITUDE_1" CS_MARKER1_OFFSET_1 = "MARKER1_OFFSET_1" CS_MARKER1_HIGH_1 = "MARKER1_HIGH_1" CS_MARKER1_LOW_1 = "MARKER1_LOW_1" CS_MARKER2_SKEW_1 = "MARKER2_SKEW_1" CS_MARKER2_METHOD_1 = "MARKER2_METHOD_1" CS_MARKER2_AMPLITUDE_1 = "MARKER2_AMPLITUDE_1" CS_MARKER2_OFFSET_1 = "MARKER2_OFFSET_1" CS_MARKER2_HIGH_1 = "MARKER2_HIGH_1" CS_MARKER2_LOW_1 = "MARKER2_LOW_1" CS_DIGITAL_METHOD_1 = "DIGITAL_METHOD_1" CS_DIGITAL_AMPLITUDE_1 = "DIGITAL_AMPLITUDE_1" CS_DIGITAL_OFFSET_1 = "DIGITAL_OFFSET_1" CS_DIGITAL_HIGH_1 = "DIGITAL_HIGH_1" CS_DIGITAL_LOW_1 = "DIGITAL_LOW_1" CS_EXTERNAL_ADD_1 = "EXTERNAL_ADD_1" CS_PHASE_DELAY_INPUT_METHOD_1 = "PHASE_DELAY_INPUT_METHOD_1" CS_PHASE_1 = "PHASE_1" CS_DELAY_IN_TIME_1 = "DELAY_IN_TIME_1" CS_DELAY_IN_POINTS_1 = "DELAY_IN_POINTS_1" CS_CHANNEL_SKEW_1 = "CHANNEL_SKEW_1" CS_DAC_RESOLUTION_2 = "DAC_RESOLUTION_2" CS_OUTPUT_WAVEFORM_NAME_2 = "OUTPUT_WAVEFORM_NAME_2" CS_CHANNEL_STATE_2 = "CHANNEL_STATE_2" CS_ANALOG_DIRECT_OUTPUT_2 = "ANALOG_DIRECT_OUTPUT_2" CS_ANALOG_FILTER_2 = "ANALOG_FILTER_2" CS_ANALOG_METHOD_2 = "ANALOG_METHOD_2" CS_ANALOG_AMPLITUDE_2 = "ANALOG_AMPLITUDE_2" CS_ANALOG_OFFSET_2 = "ANALOG_OFFSET_2" CS_ANALOG_HIGH_2 = "ANALOG_HIGH_2" CS_ANALOG_LOW_2 = "ANALOG_LOW_2" CS_MARKER1_SKEW_2 = "MARKER1_SKEW_2" CS_MARKER1_METHOD_2 = "MARKER1_METHOD_2" CS_MARKER1_AMPLITUDE_2 = "MARKER1_AMPLITUDE_2" CS_MARKER1_OFFSET_2 = "MARKER1_OFFSET_2" CS_MARKER1_HIGH_2 = "MARKER1_HIGH_2" CS_MARKER1_LOW_2 = "MARKER1_LOW_2" CS_MARKER2_SKEW_2 = "MARKER2_SKEW_2" CS_MARKER2_METHOD_2 = "MARKER2_METHOD_2" CS_MARKER2_AMPLITUDE_2 = "MARKER2_AMPLITUDE_2" CS_MARKER2_OFFSET_2 = "MARKER2_OFFSET_2" CS_MARKER2_HIGH_2 = "MARKER2_HIGH_2" CS_MARKER2_LOW_2 = "MARKER2_LOW_2" CS_DIGITAL_METHOD_2 = "DIGITAL_METHOD_2" CS_DIGITAL_AMPLITUDE_2 = "DIGITAL_AMPLITUDE_2" CS_DIGITAL_OFFSET_2 = "DIGITAL_OFFSET_2" CS_DIGITAL_HIGH_2 = "DIGITAL_HIGH_2" CS_DIGITAL_LOW_2 = "DIGITAL_LOW_2" CS_EXTERNAL_ADD_2 = "EXTERNAL_ADD_2" CS_PHASE_DELAY_INPUT_METHOD_2 = "PHASE_DELAY_INPUT_METHOD_2" CS_PHASE_2 = "PHASE_2" CS_DELAY_IN_TIME_2 = "DELAY_IN_TIME_2" CS_DELAY_IN_POINTS_2 = "DELAY_IN_POINTS_2" CS_CHANNEL_SKEW_2 = "CHANNEL_SKEW_2" CS_DAC_RESOLUTION_3 = "DAC_RESOLUTION_3" CS_OUTPUT_WAVEFORM_NAME_3 = "OUTPUT_WAVEFORM_NAME_3" CS_CHANNEL_STATE_3 = "CHANNEL_STATE_3" CS_ANALOG_DIRECT_OUTPUT_3 = "ANALOG_DIRECT_OUTPUT_3" CS_ANALOG_FILTER_3 = "ANALOG_FILTER_3" CS_ANALOG_METHOD_3 = "ANALOG_METHOD_3" CS_ANALOG_AMPLITUDE_3 = "ANALOG_AMPLITUDE_3" CS_ANALOG_OFFSET_3 = "ANALOG_OFFSET_3" CS_ANALOG_HIGH_3 = "ANALOG_HIGH_3" CS_ANALOG_LOW_3 = "ANALOG_LOW_3" CS_MARKER1_SKEW_3 = "MARKER1_SKEW_3" CS_MARKER1_METHOD_3 = "MARKER1_METHOD_3" CS_MARKER1_AMPLITUDE_3 = "MARKER1_AMPLITUDE_3" CS_MARKER1_OFFSET_3 = "MARKER1_OFFSET_3" CS_MARKER1_HIGH_3 = "MARKER1_HIGH_3" CS_MARKER1_LOW_3 = "MARKER1_LOW_3" CS_MARKER2_SKEW_3 = "MARKER2_SKEW_3" CS_MARKER2_METHOD_3 = "MARKER2_METHOD_3" CS_MARKER2_AMPLITUDE_3 = "MARKER2_AMPLITUDE_3" CS_MARKER2_OFFSET_3 = "MARKER2_OFFSET_3" CS_MARKER2_HIGH_3 = "MARKER2_HIGH_3" CS_MARKER2_LOW_3 = "MARKER2_LOW_3" CS_DIGITAL_METHOD_3 = "DIGITAL_METHOD_3" CS_DIGITAL_AMPLITUDE_3 = "DIGITAL_AMPLITUDE_3" CS_DIGITAL_OFFSET_3 = "DIGITAL_OFFSET_3" CS_DIGITAL_HIGH_3 = "DIGITAL_HIGH_3" CS_DIGITAL_LOW_3 = "DIGITAL_LOW_3" CS_EXTERNAL_ADD_3 = "EXTERNAL_ADD_3" CS_PHASE_DELAY_INPUT_METHOD_3 = "PHASE_DELAY_INPUT_METHOD_3" CS_PHASE_3 = "PHASE_3" CS_DELAY_IN_TIME_3 = "DELAY_IN_TIME_3" CS_DELAY_IN_POINTS_3 = "DELAY_IN_POINTS_3" CS_CHANNEL_SKEW_3 = "CHANNEL_SKEW_3" CS_DAC_RESOLUTION_4 = "DAC_RESOLUTION_4" CS_OUTPUT_WAVEFORM_NAME_4 = "OUTPUT_WAVEFORM_NAME_4" CS_CHANNEL_STATE_4 = "CHANNEL_STATE_4" CS_ANALOG_DIRECT_OUTPUT_4 = "ANALOG_DIRECT_OUTPUT_4" CS_ANALOG_FILTER_4 = "ANALOG_FILTER_4" CS_ANALOG_METHOD_4 = "ANALOG_METHOD_4" CS_ANALOG_AMPLITUDE_4 = "ANALOG_AMPLITUDE_4" CS_ANALOG_OFFSET_4 = "ANALOG_OFFSET_4" CS_ANALOG_HIGH_4 = "ANALOG_HIGH_4" CS_ANALOG_LOW_4 = "ANALOG_LOW_4" CS_MARKER1_SKEW_4 = "MARKER1_SKEW_4" CS_MARKER1_METHOD_4 = "MARKER1_METHOD_4" CS_MARKER1_AMPLITUDE_4 = "MARKER1_AMPLITUDE_4" CS_MARKER1_OFFSET_4 = "MARKER1_OFFSET_4" CS_MARKER1_HIGH_4 = "MARKER1_HIGH_4" CS_MARKER1_LOW_4 = "MARKER1_LOW_4" CS_MARKER2_SKEW_4 = "MARKER2_SKEW_4" CS_MARKER2_METHOD_4 = "MARKER2_METHOD_4" CS_MARKER2_AMPLITUDE_4 = "MARKER2_AMPLITUDE_4" CS_MARKER2_OFFSET_4 = "MARKER2_OFFSET_4" CS_MARKER2_HIGH_4 = "MARKER2_HIGH_4" CS_MARKER2_LOW_4 = "MARKER2_LOW_4" CS_DIGITAL_METHOD_4 = "DIGITAL_METHOD_4" CS_DIGITAL_AMPLITUDE_4 = "DIGITAL_AMPLITUDE_4" CS_DIGITAL_OFFSET_4 = "DIGITAL_OFFSET_4" CS_DIGITAL_HIGH_4 = "DIGITAL_HIGH_4" CS_DIGITAL_LOW_4 = "DIGITAL_LOW_4" CS_EXTERNAL_ADD_4 = "EXTERNAL_ADD_4" CS_PHASE_DELAY_INPUT_METHOD_4 = "PHASE_DELAY_INPUT_METHOD_4" CS_PHASE_4 = "PHASE_4" CS_DELAY_IN_TIME_4 = "DELAY_IN_TIME_4" CS_DELAY_IN_POINTS_4 = "DELAY_IN_POINTS_4" CS_CHANNEL_SKEW_4 = "CHANNEL_SKEW_4" CS_DAC_RESOLUTION_N = "DAC_RESOLUTION_" CS_OUTPUT_WAVEFORM_NAME_N = "OUTPUT_WAVEFORM_NAME_" CS_CHANNEL_STATE_N = "CHANNEL_STATE_" CS_ANALOG_DIRECT_OUTPUT_N = "ANALOG_DIRECT_OUTPUT_" CS_ANALOG_FILTER_N = "ANALOG_FILTER_" CS_ANALOG_METHOD_N = "ANALOG_METHOD_" CS_ANALOG_AMPLITUDE_N = "ANALOG_AMPLITUDE_" CS_ANALOG_OFFSET_N = "ANALOG_OFFSET_" CS_ANALOG_HIGH_N = "ANALOG_HIGH_" CS_ANALOG_LOW_N = "ANALOG_LOW_" CS_MARKER1_SKEW_N = "MARKER1_SKEW_" CS_MARKER1_METHOD_N = "MARKER1_METHOD_" CS_MARKER1_AMPLITUDE_N = "MARKER1_AMPLITUDE_" CS_MARKER1_OFFSET_N = "MARKER1_OFFSET_" CS_MARKER1_HIGH_N = "MARKER1_HIGH_" CS_MARKER1_LOW_N = "MARKER1_LOW_" CS_MARKER2_SKEW_N = "MARKER2_SKEW_" CS_MARKER2_METHOD_N = "MARKER2_METHOD_" CS_MARKER2_AMPLITUDE_N = "MARKER2_AMPLITUDE_" CS_MARKER2_OFFSET_N = "MARKER2_OFFSET_" CS_MARKER2_HIGH_N = "MARKER2_HIGH_" CS_MARKER2_LOW_N = "MARKER2_LOW_" CS_DIGITAL_METHOD_N = "DIGITAL_METHOD_" CS_DIGITAL_AMPLITUDE_N = "DIGITAL_AMPLITUDE_" CS_DIGITAL_OFFSET_N = "DIGITAL_OFFSET_" CS_DIGITAL_HIGH_N = "DIGITAL_HIGH_" CS_DIGITAL_LOW_N = "DIGITAL_LOW_" CS_EXTERNAL_ADD_N = "EXTERNAL_ADD_" CS_PHASE_DELAY_INPUT_METHOD_N = "PHASE_DELAY_INPUT_METHOD_" CS_PHASE_N = "PHASE_" CS_DELAY_IN_TIME_N = "DELAY_IN_TIME_" CS_DELAY_IN_POINTS_N = "DELAY_IN_POINTS_" CS_CHANNEL_SKEW_N = "CHANNEL_SKEW_" CS_DC_OUTPUT_LEVEL_1 = "DC_OUTPUT_LEVEL_1" CS_DC_OUTPUT_LEVEL_2 = "DC_OUTPUT_LEVEL_2" CS_DC_OUTPUT_LEVEL_3 = "DC_OUTPUT_LEVEL_3" CS_DC_OUTPUT_LEVEL_4 = "DC_OUTPUT_LEVEL_4" CS_DC_OUTPUT_LEVEL_N = "DC_OUTPUT_LEVEL_" CS_WAVEFORM_NAME_N = "WAVEFORM_NAME_" CS_WAVEFORM_TYPE_N = "WAVEFORM_TYPE_" CS_WAVEFORM_LENGTH_N = "WAVEFORM_LENGTH_" CS_WAVEFORM_TIMESTAMP_N = "WAVEFORM_TIMESTAMP_" CS_WAVEFORM_DATA_N = "WAVEFORM_DATA_" CS_SEQUENCE_WAIT_N = "SEQUENCE_WAIT_" CS_SEQUENCE_LOOP_N = "SEQUENCE_LOOP_" CS_SEQUENCE_JUMP_N = "SEQUENCE_JUMP_" CS_SEQUENCE_GOTO_N = "SEQUENCE_GOTO_" CS_SEQUENCE_WAVEFORM_NAME_CH_N_N = "SEQUENCE_WAVEFORM_NAME_CH_" CS_SEQUENCE_IS_SUBSEQUENCE_N = "SEQUENCE_IS_SUBSEQ_" CS_SEQUENCE_SUBSEQUENCE_NAME_N = "SEQUENCE_SUBSEQ_NAME_" CS_SUBSEQUENCE_NAME_O = "SUBSEQ_NAME_" CS_SUBSEQUENCE_TIMESTAMP_O = "SUBSEQ_TIMESTAMP_" CS_SUBSEQUENCE_LENGTH_O = "SUBSEQ_LENGTH_" CS_SUBSEQUENCE_LOOP_E_O_U = "SUBSEQ_LOOP_" CS_SUBSEQUENCE_WAVEFORM_NAME_CH_X_E_O_U = "SUBSEQ_WAVEFORM_NAME_CH_" SEQUENCE_JUMP_TARGET_TYPE_OFF = 0 SEQUENCE_JUMP_TARGET_TYPE_NEXT = -1
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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. # # NOTE: This class is auto generated by the jdcloud code generator program. class TagsSpec(object): def __init__(self, appCode, serviceCode, groupCode, resourceIds, tags, filter=None): """ :param appCode: 校验码。调用此API前需找云监控提供 :param serviceCode: 服务码 :param groupCode: 组id,全局唯一,建议用那个UUID :param resourceIds: 资源列表 :param tags: 进行打tag的数据以及操作 :param filter: (Optional) 更详细过滤条件 """ self.appCode = appCode self.serviceCode = serviceCode self.groupCode = groupCode self.resourceIds = resourceIds self.tags = tags self.filter = filter
def padlindromic_date1(date1): d,m,y = date1.split('/') return (d+y)[::-1] == y and (m+d) [::-1] == y def padlindromic_date2(date2): dd,mm,yyyy = date2.split('/') date11 = ''.join([dd,mm,yyyy]) date12 = ''.join([mm,dd,yyyy]) return date11 == date11[::-1] and date12 == date12[::-1] def padlindromic_date3(date3): d,m,y = date3.split('/') return d==m and d+m==y[::-1] pd1 = padlindromic_date1("02/02/2020"), padlindromic_date1("11/12/2019"), padlindromic_date1("11/12/2011") print(pd1) pd2 = padlindromic_date2("02/02/2020"), padlindromic_date2("11/12/2019"), padlindromic_date2("11/12/2011") print(pd2) pd3 = padlindromic_date3("02/02/2020"), padlindromic_date3("11/12/2019"), padlindromic_date3("11/12/2011") print(pd3)
sum = 0 for i in range(1,1000): if i%3==0 or i%5==0: sum += i print(sum)
class ORMBaseException(Exception): def __init__(self): self.message = "" super().__init__() def __str__(self): return self.message class FieldDoesNotExist(ORMBaseException): def __init__(self, field: str): self.message = f"This field '{field}' is not avaible"
r""" Global variables to the migration simulations and plot analysis. """ END_TIME = 13.2 # total simulation time in Gyr # Width of each annulus in kpc # This needs modified *only* if running the plotting scripts. ZONE_WIDTH = 0.1 MAX_SF_RADIUS = 15.5 # Radius in kpc beyond which the SFR = 0 # Stellar mass of Milky Way (Licquia & Newman 2015, ApJ, 806, 96) M_STAR_MW = 5.17e10 COLORMAP = "winter"
#Translation table for atomic numbers to element names and vice versa #Note that the NIST database provides data up to atomic number 92 (= Uranium) #Last column contains material densities ElementaryData = [ (0, "Void", "X", 0), (1, "Hydrogen", "H", 8.375E-05), (2, "Helium", "He", 1.663E-04), (3, "Lithium", "Li", 5.340E-01), (4, "Beryllium", "Be", 1.848E+00), (5, "Boron", "B", 2.370E+00), (6, "Carbon", "C", 1.700E+00), (7, "Nitrogen", "N", 1.165E-03), (8, "Oxygen", "O", 1.332E-03), (9, "Fluorine", "F", 1.580E-03), (10, "Neon", "Ne", 8.385E-04), (11, "Sodium", "Na", 9.710E-01), (12, "Magnesium", "Mg", 1.740E+00), (13, "Aluminium", "Al", 2.699E+00), (14, "Silicon", "Si", 2.330E+00), (15, "Phosphorus", "P", 2.200E+00), (16, "Sulfur", "S", 2.000E+00), (17, "Chlorine", "Cl", 2.995E-03), (18, "Argon", "Ar", 1.662E-03), (19, "Potassium", "K", 8.620E-01), (20, "Calcium", "Ca", 1.550E+00), (21, "Scandium", "Sc", 2.989E+00), (22, "Titanium", "Ti", 4.540E+00), (23, "Vanadium", "V", 6.110E+00), (24, "Chromium", "Cr", 7.180E+00), (25, "Manganese", "Mn", 7.440E+00), (26, "Iron", "Fe", 7.874E+00), (27, "Cobalt", "Co", 8.900E+00), (28, "Nickel", "Ni", 8.902E+00), (29, "Copper", "Cu", 8.960E+00), (30, "Zinc", "Zn", 7.133E+00), (31, "Gallium", "Ga", 5.904E+00), (32, "Germanium", "Ge", 5.323E+00), (33, "Arsenic", "As", 5.730E+00), (34, "Selenium", "Se", 4.500E+00), (35, "Bromine", "Br", 7.072E-03), (36, "Krypton", "Kr", 3.478E-03), (37, "Rubidium", "Rb", 1.532E+00), (38, "Strontium", "Sr", 2.540E+00), (39, "Yttrium", "Y", 4.469E+00), (40, "Zirconium", "Zr", 6.506E+00), (41, "Niobium", "Nb", 8.570E+00), (42, "Molybdenum", "Mo", 1.022E+01), (43, "Technetium", "Tc", 1.150E+01), (44, "Ruthenium", "Ru", 1.241E+01), (45, "Rhodium", "Rh", 1.241E+01), (46, "Palladium", "Pd", 1.202E+01), (47, "Silver", "Ag", 1.050E+01), (48, "Cadmium", "Cd", 8.650E+00), (49, "Indium", "In", 7.310E+00), (50, "Tin", "Sn", 7.310E+00), (51, "Antimony", "Sb", 6.691E+00), (52, "Tellurium", "Te", 6.240E+00), (53, "Iodine", "I", 4.930E+00), (54, "Xenon", "Xe", 5.485E-03), (55, "Cesium", "Cs", 1.873E+00), (56, "Barium", "Ba", 3.500E+00), (57, "Lanthanum", "La", 6.154E+00), (58, "Cerium", "Ce", 6.657E+00), (59, "Praseodymium", "Pr", 6.710E+00), (60, "Neodymium", "Nd", 6.900E+00), (61, "Promethium", "Pm", 7.220E+00), (62, "Samarium", "Sm", 7.460E+00), (63, "Europium", "Eu", 5.243E+00), (64, "Gadolinium", "Gd", 7.900E+00), (65, "Terbium", "Tb", 8.229E+00), (66, "Dysprosium", "Dy", 8.550E+00), (67, "Holmium", "Ho", 8.795E+00), (68, "Erbium", "Er", 9.066E+00), (69, "Thulium", "Tm", 9.321E+00), (70, "Ytterbium", "Yb", 6.730E+00), (71, "Lutetium", "Lu", 9.840E+00), (72, "Hafnium", "Hf", 1.331E+01), (73, "Tantalum", "Ta", 1.665E+01), (74, "Tungsten", "W", 1.930E+01), (75, "Rhenium", "Re", 2.102E+01), (76, "Osmium", "Os", 2.257E+01), (77, "Iridium", "Ir", 2.242E+01), (78, "Platinum", "Pt", 2.145E+01), (79, "Gold", "Au", 1.932E+01), (80, "Mercury", "Hg", 1.355E+01), (81, "Thallium", "Tl", 1.172E+01), (82, "Lead", "Pb", 1.135E+01), (83, "Bismuth", "Bi", 9.747E+00), (84, "Polonium", "Po", 9.320E+00), (85, "Astatine", "At", 1.000E+01), (86, "Radon", "Rn", 9.066E-03), (87, "Francium", "Fr", 1.000E+01), (88, "Radium", "Ra", 5.000E+00), (89, "Actinium", "Ac", 1.007E+01), (90, "Thorium", "Th", 1.172E+01), (91, "Protactinium", "Pa", 1.537E+01), (92, "Uranium", "U", 1.895E+01), (93, "Neptunium", "Np", 0), (94, "Plutonium", "Pu", 0), (95, "Americium", "Am", 0), (96, "Curium", "Cm", 0), (97, "Berkelium", "Bk", 0), (98, "Californium", "Cf", 0), (99, "Einsteinium", "Es", 0), (100,"Fermium", "Fm", 0), (101,"Mendelevium", "Md", 0), (102,"Nobelium", "No", 0), (103,"Lawrencium", "Lr", 0), (104,"Rutherfordium", "Rf", 0), (105,"Dubnium", "Db", 0), (106,"Seaborgium", "Sg", 0), (107,"Bohrium", "Bh", 0), (108,"Hassium", "Hs", 0), (109,"Meitnerium", "Mt", 0), (110,"Darmstadtium", "Ds", 0), (111,"Roentgenium" "Rg", 0), (112,"Ununbium", "Uub", 0), (113,"Ununtrium", "Uut", 0), (114,"Ununquadium", "Uuq", 0), (115,"Ununpentium", "Uup", 0), (116,"Ununhexium", "Uuh", 0), (117,"Ununseptium", "Uus", 0), (118,"Ununoctium", "Uuo", 0) ]
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. class Parameter(object): """This bean is used for building config entries.""" def __init__(self, config): self.name = config['name'] self.description = config.get('description', "No description") self.required = not config['is_optional'] self.default_value = config.get('default_value', None) self.initial_value = self.default_value self.param_type = config['config_type'] self.priority = int(config.get('priority', 2))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'Phoenix1327' a = 'ABC' b = a a = 'XYZ' print(b) # a --> 'ABC' # b --> a --> 'ABC'(i.e. b --> 'ABC') # a --> 'XYZ' #exercise n = 123 f = 456.789 s1 = 'Hello, world' s2 = 'Hello, \'Adam\'' s3 = r'Hello, "Bart"' s4 = r'''Hello, Lisa!''' print (n) print (f) print (s1) print (s2) print (s3) print (s4)
class URL(object): BASE_URL = 'https://uatapi.nimbbl.tech/api' ORDER_URL = "/orders" AUTHURL = "v2/generate-token"; ORDER_CREATE = "v2/create-order"; ORDER_GET = "v2/get-order"; ORDER_LIST = "orders/many?f=&pt=yes"; LIST_QUERYPARAM1 = "f"; LIST_QUERYPARAM2 = "pt"; NO = "no"; Empty = ""; USER_CREATE = "users/create"; USER_GET = "users/one"; USER_LIST = "users/many?f=&pt=yes"; Transaction_CREATE = "transactions/create"; Transaction_GET = "transactions/one"; Transaction_LIST = "transactions/many?f=%sandpt=no"; ACCESS_KEY = "access_key"; SECRET_KEY = "access_secret"; TOKEN = "token"; Bearer = "Bearer ";
#!/usr/bin/python # encoding: utf-8 def search(key, *args, kwargs): pass if __name__ == "__main__": pass
"""A utility module for ASP (Active Server Pages on MS Internet Info Server. Contains: iif -- A utility function to avoid using "if" statements in ASP <% tags """ def iif(cond, t, f): if cond: return t else: return f
dog = {} dog['name'] = 'Bruce' dog['color'] = 'Black' dog['Breed'] = 'Pitbull' dog['Leg'] = 10.3 dog['Idade'] = '2 Years' student = { 'firstname': 'Diego', 'lastname': 'Fregolente', 'gender': 'Male', 'marital status': 'Dating', 'country': 'Brazil', 'city': 'São Paulo', 'address': { 'Street':'Estrada Agua Chata 3050', 'zip': '12345-321' } } lenght_student = len(student) student['skills'] = ['HTML', 'Python'] print(type(student.get('skills'))) print(type(student.get('sasdasd'))) student['skills'].append('CSS') print(student.get('skills')) keys_dict = list(student.keys()) print(keys_dict) values_dict = list(student.values()) print(values_dict) listsdict = list(student.items()) print(listsdict) student.popitem() student.pop('firstname') del student
# -*- coding: utf-8 -*- # @Author: rish # @Date: 2020-08-02 23:03:40 # @Last Modified by: rish # @Last Modified time: 2020-08-04 01:20:05 def info(): print( 'er_extractor module - functionality for data collection of exchange\ rates based on provided arguments and persistence of data collected\ into the database.' )
class Node(object): def __init__(self, value = None, leftChild = None, rightChild = None): self.value = value self.leftChild = leftChild self.rightChild = rightChild
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def lowestCommonAncestor(self, root, p, q): if root is None or root == p or root == q: return root l = self.lowestCommonAncestor(root.left, p, q) r = self.lowestCommonAncestor(root.right, p, q) if l is None: return r else: if r is None: return l return root if __name__ == "__main__": solution = Solution() root = TreeNode(3) root.left = TreeNode(5) root.right = TreeNode(1) root.left.left = TreeNode(6) root.left.right = TreeNode(2) root.left.right.left = TreeNode(7) root.left.right.right = TreeNode(4) root.right.left = TreeNode(0) root.right.right = TreeNode(8) print(solution.lowestCommonAncestor(root, root.left, root.right))
#!/usr/bin/env python3 """ A crude solver for [Move Here Move There] (https://www.newgrounds.com/portal/view/718498). """ board = { (0, 0): "X", (3, 0): "X", (4, 0): [(-3, 3)], (6, 0): "X", (0, 1): "X", (4, 2): "X", (0, 4): [(4, 0)], (3, 4): [(3, -3)], (4, 4): [(1, 0), (-1, 1)], (1, 5): "X", (3, 5): [(-1, -1)], (5, 5): "X", } pieces = [ [(-1, -1), (0, 4)], [(2, -2), (-1, -1)], [(4, 0)], [(0, -5)], [(2, 2)], [(0, 3)], [(-2, -2)], [(-5, 0)], ] start = (3, 4) maxes = (6, 5) def move(pos, piece): """ Return new position after moving by one piece. :param pos: A 2-tuple of `int`s, describing the starting position. :param piece: A list of 2-tuples of `int`s, describing one piece's moves. :raise ValueError: Raised if the move is impossible. :return: A 2-tuple of `int`s describing the new position. """ for jmp in piece: pos = (pos[0] + jmp[0], pos[1] + jmp[1]) if not (0 <= pos[0] <= maxes[0] and 0 <= pos[1] <= maxes[1]): raise ValueError() return pos def step(pos, pieces, history): """ Execute one step. :param pos: A 2-tuple of `int`s, describing the starting position. :param pieces: A list of lists of 2-tuples of `int`s, describing still unused pieces. :param history: A list of lists of 2-tuples of `int`s, describing already used pieces. """ if not pieces and all(v == "X" for v in board.values()): print(f"{pos}: {history}") return try: nxt = board[pos] except KeyError: for pidx, piece in enumerate(pieces): try: pos2 = move(pos, piece) except ValueError: continue else: board[pos] = "X" step(pos2, pieces[:pidx] + pieces[pidx + 1:], history + [piece]) del board[pos] else: if nxt == "X": return try: pos2 = move(pos, nxt) except ValueError: return else: board[pos] = "X" step(pos2, pieces, history) board[pos] = nxt step(start, pieces, list())
# -*- coding: utf-8 -*- """ Last update: Sep. 2, 2020 @author: Asieh Abolpour Mofrad Initialization values details This code is used for simulation results reported in an article entitled: ''Enhanced Equivalence Projective Simulation: a Framework for Modeling Formation of Stimulus Equivalence Classes" in Neural Computation, MIT Press. """ def environment_parameters_details(ID): details = environment_details() return details[ID]['num_classes'], details[ID]['training_order'], \ details[ID]['plot_blocks'], details[ID]['plot_blocks_ID'], \ details[ID]['mastery_training'] def environment_details(): """ Here the information for the environment will be provided. The number is what in the interaction file must be specified. plot_blocks shows representation for bar diagrams. """ environment_parameters_detail = { 1: { # This is the example at the paper "num_classes":3, "training_order": { 1:[('A','B',30)], 2:[('B','C',30)], 3:[('D','C',30)] }, "plot_blocks": { 'relation_type':{'Direct':['AB','BC','DC'], 'Derived':['BA','CB','CD','AC','CA','BD','DB','AD','DA']} }, "plot_blocks_ID": { 'relation_type':['Direct','Derived'] }, "mastery_training": 0.9 }, 10: { # This is the example at the paper "num_classes":5, "training_order": { 1:[('A','B',50)], 2:[('B','C',50)], 3:[('D','C',50)] }, "plot_blocks": { 'relation_type':{'Direct':['AB','BC','DC'], 'Derived':['BA','CB','CD','AC','CA','BD','DB','AD','DA']} }, "plot_blocks_ID": { 'relation_type':['Direct','Derived'] }, "mastery_training": 0.95 }, 2: { # This is the Sidman and Tailby experiment (1982) "num_classes": 3, "training_order": { 1:[('A1','B1',10),('A2','B2',10)], 2:[('A1','B1',10),('A3','B3',10)], 3:[('A2','B2',10),('A3','B3',10)], 4:[('A1','B1',10),('A2','B2',10),('A3','B3',10)], 5:[('A1','C1',10),('A2','C2',10)], 6:[('A1','C1',10),('A3','C3',10)], 7:[('A2','C2',10),('A3','C3',10)], 8:[('A1','C1',10),('A2','C2',10),('A3','C3',10)], 9: [('A1','B1',5),('A2','B2',5),('A3','B3',5), ('A1','C1',5),('A2','C2',5), ('A3','C3',5)], 10: [('D1','C1',10),('D2','C2',10)], 11:[('D1','C1',10),('D3','C3',10)], 12: [('D2','C2',10),('D3','C3',10)], 13:[('D1','C1',10),('D2','C2',10),('D3','C3',10)], 14:[('A1','B1',5),('A2','B2',5),('A3','B3',5), ('A1','C1',5),('A2','C2',5), ('A3','C3',5), ('D1','C1',5),('D2','C2',5),('D3','C3',5)] }, "plot_blocks": { 'relation_type':{'Baseline':['AB','AC','DC'], 'Symmetry':['BA','CA','CD'], 'Equivalence':['BC','CB','BD','DB','AD','DA']} }, "plot_blocks_ID": { 'relation_type':['Baseline','Symmetry','Equivalence'] }, "mastery_training": 0.9 }, 3: { # This is the Devany et. al. experiment (1986) "num_classes": 2, "training_order": { 1:[('A1','B1',10)], 2:[('A2','B2',10)], 3:[('A1','B1',5),('A2','B2',5)], 4:[('A1','C1',10)], 5:[('A2','C2',10)], 6:[('A1','C1',5),('A2','C2',5)], 7: [('A1','B1',2),('A2','B2',2),('A1','C1',2), ('A2','C2',2)] }, "plot_blocks": { 'relation_type':{'Baseline':['AB','AC'],'Symmetry':['BA','CA'], 'Equivalence':['BC','CB']} }, "plot_blocks_ID": {'relation_type':['Baseline','Symmetry','Equivalence']}, "mastery_training": 0.9 }, # This is the Spencer and Chase experiment (1996) 4: { # "num_classes": 3, "training_order": { 1:[('A','B',48)], 2:[('A','B',24),('B','C',24)], 3:[('A','B',12),('B','C',12),('C','D',24)], 4:[('A','B',9),('B','C',9),('C','D',9),('D','E',24)], 5:[('A','B',6),('B','C',6),('C','D',6),('D','E',6), ('E','F',24)], 6:[('A','B',3),('B','C',3),('C','D',3),('D','E',6), ('E','F',9),('F','G',24)], 7:[('A','B',3),('B','C',3),('C','D',3),('D','E',3), ('E','F',3),('F','G',3)] }, "plot_blocks": { 'nodal_distance':{ 'Bsl':['AB','BC','CD','DE','EF','FG'], 'Sym':['BA','CB','DC','ED','FE','GF'], '1-Tr':['AC','BD','CE','DF','EG'], '2-Tr':['AD','BE','CF','DG'], '3-Tr':['AE','BF','CG'], '4-Tr':['AF','BG'], '5-Tr':['AG'], '1-Eq':['CA','DB','EC','FD','GE'], '2-Eq':['DA','EB','FC','GD'], '3-Eq':['EA','FB','GC'], '4-Eq':['FA','GB'], '5-Eq':['GA'] }, 'relation_type':{ 'Baseline':['AB','BC','CD','DE','EF','FG'], 'Symmetry':['BA','CB','DC','ED','FE','GF'], 'Transivity':['AC','BD','CE','DF','EG', 'AD','BE','CF','DG','AE', 'BF','CG','AF','BG','AG'], 'Equivalence':['CA','DB','EC','FD','GE', 'DA','EB','FC','GD','EA', 'FB','GC','FA','GB','GA'] } }, "plot_blocks_ID": { 'nodal_distance':['Bsl','Sym','1-Tr','2-Tr','3-Tr', '4-Tr','5-Tr','1-Eq','2-Eq','3-Eq', '4-Eq','5-Eq'], 'relation_type':['Baseline','Symmetry', 'Transivity','Equivalence'] }, "mastery_training": 0.9 }, # This is an alternative to the Sidman and Tailby experiment (1982) 5: { "num_classes": 3, "training_order": { 1:[('A1','B1',10),('B2','A2',10)], 2:[('A1','B1',10),('A3','B3',10)], 3:[('B2','A2',10),('A3','B3',10)], 4:[('A1','B1',10),('B2','A2',10),('A3','B3',10)], 5:[('A1','C1',10),('C2','A2',10)], 6:[('A1','C1',10),('A3','C3',10)], 7:[('C2','A2',10),('A3','C3',10)], 8:[('A1','C1',10),('C2','A2',10),('A3','C3',10)], 9: [('A1','B1',5),('B2','A2',5),('A3','B3',5), ('A1','C1',5),('C2','A2',5), ('A3','C3',5)], 10: [('D1','C1',10),('C2','D2',10)], 11:[('D1','C1',10),('D3','C3',10)], 12: [('C2','D2',10),('D3','C3',10)], 13:[('D1','C1',10),('C2','D2',10),('D3','C3',10)], 14:[('A1','B1',5),('B2','A2',5),('A3','B3',5), ('A1','C1',5),('C2','A2',5), ('A3','C3',5), ('D1','C1',5),('C2','D2',5),('D3','C3',5)] }, "plot_blocks": { 'relation_type':{ 'Baseline':['AB','AC','DC'], 'Symmetry':['BA','CA','CD'], 'Equivalence':['BC','CB','BD','DB','AD','DA'] } }, "plot_blocks_ID": {'relation_type':['Baseline','Symmetry','Equivalence']}, "mastery_training": 0.9 }, # This is the Devany et. al. experiment (1986), by changing the training. 6: { "num_classes": 2, "training_order": { 1:[('A1','B1',10)], 2:[('B2','A2',10)], 3:[('A1','B1',5),('B2','A2',5)], 4:[('A1','C1',10)], 5:[('C2','A2',10)], 6:[('A1','C1',5),('C2','A2',5)], 7: [('A1','B1',2),('B2','A2',2),('A1','C1',2),('C2','A2',2)] }, "plot_blocks": {}, "plot_blocks_ID": {}, "mastery_training": 0.9 }, # This is OTM version of Spencer and Chase experiment (1996) 7: { # "num_classes": 3, "training_order": { 1:[('A','B',48)], 2:[('A','B',24),('A','C',24)], 3:[('A','B',12),('A','C',12),('A','D',24)], 4:[('A','B',9),('A','C',9),('A','D',9),('A','E',24)], 5:[('A','B',6),('A','C',6),('A','D',6),('A','E',6), ('A','F',24)], 6:[('A','B',3),('A','C',3),('A','D',3),('A','E',6), ('A','F',9),('A','G',24)], 7:[('A','B',3),('A','C',3),('A','D',3),('A','E',3), ('A','F',3),('A','G',3)] }, "plot_blocks": { 'relation_type':{ 'Baseline':['AB','AC','AD','AE','AF','AG'], 'Symmetry':['BA','CA','DA','EA','FA','GA'], 'Equivalence':['BC','BD','BE','BF','BG', 'CB','CD','CE','CF','CG', 'DB','DC','DE','DF','DG', 'EB','EC','ED','EF','EG', 'FB','FC','FD','FE','FG', 'GB','GC','GD','GE','GF'] } }, "plot_blocks_ID": { 'relation_type':['Baseline','Symmetry','Equivalence'] }, "mastery_training": 0.9 }, # This is MTO version of Spencer and Chase experiment (1996) 8: { # "num_classes": 3, "training_order": { 1:[('A','G',48)], 2:[('A','G',24),('B','G',24)], 3:[('A','G',12),('B','G',12),('C','G',24)], 4:[('A','G',9),('B','G',9),('C','G',9),('D','G',24)], 5:[('A','G',6),('B','G',6),('C','G',6),('D','G',6), ('E','G',24)], 6:[('A','G',3),('B','G',3),('C','G',3),('D','G',6), ('E','G',9),('F','G',24)], 7:[('A','G',3),('B','G',3),('C','G',3),('D','G',3), ('E','G',3),('F','G',3)] }, "plot_blocks": { 'relation_type':{ 'Baseline':['AG','BG','CG','DG','EG','FG'], 'Symmetry':['GA','GB','GC','GD','GE','GF'], 'Equivalence':['AB','AC','AD','AE','AF', 'BA','BC','BD','BE','BF', 'CA','CB','CD','CE','CF', 'DA','DB','DC','DE','DF', 'EA','EB','EC','ED','EF', 'FA','FB','FC','FD','FE'] } }, "plot_blocks_ID": { 'relation_type':['Baseline','Symmetry','Equivalence'] }, "mastery_training": 0.9 }, # This is OTM version of Spencer and Chase experiment (1996) 9: { # "num_classes": 3, "training_order": { 1:[('A','B',48)], 2:[('A','B',24),('C','A',24)], 3:[('A','B',12),('C','A',12),('A','D',24)], 4:[('A','B',9),('C','A',9),('A','D',9),('E','A',24)], 5:[('A','B',6),('C','A',6),('A','D',6),('E','A',6), ('A','F',24)], 6:[('A','B',3),('C','A',3),('A','D',3),('E','A',6), ('A','F',9),('G','A',24)], 7:[('A','B',3),('C','A',3),('A','D',3),('E','A',3), ('A','F',3),('G','A',3)] }, "plot_blocks": { 'relation_type':{ 'Baseline':['AB','CA','AD','EA','AF','GA'], 'Symmetry':['BA','AC','DA','AE','FA','AG'], 'Equivalence':['BC','BD','BE','BF','BG', 'CB','CD','CE','CF','CG', 'DB','DC','DE','DF','DG', 'EB','EC','ED','EF','EG', 'FB','FC','FD','FE','FG', 'GB','GC','GD','GE','GF'] } }, "plot_blocks_ID": { 'relation_type':['Baseline','Symmetry','Equivalence'] }, "mastery_training": 0.9 }, 11: { # "num_classes": 3, "training_order": { 1:[('A','B',30)], 2:[('B','C',30)], 3:[('C','D',30)], 4:[('D','E',30)], 5:[('E','F',30)], 6:[('F','G',30)], }, "plot_blocks": {}, "plot_blocks_ID": {}, "mastery_training": 0.9 }, 12: { # OTM "num_classes": 6, "training_order": { 1:[('A','B',60)], 2:[('A','C',60)], 3:[('A','D',60)], 4:[('A','E',60)], 5:[('A','F',60)], 6:[('A','G',60)], }, "plot_blocks": {}, "plot_blocks_ID": {}, "mastery_training": 0.9 }, 13: { # OTM "num_classes": 6, "training_order": { 1:[('A','G',60)], 2:[('B','G',60)], 3:[('C','G',60)], 4:[('D','G',60)], 5:[('E','G',60)], 6:[('F','G',60)], }, "plot_blocks": {}, "plot_blocks_ID": {}, "mastery_training": 0.9 }, } return environment_parameters_detail
class Writing: ''' --help = This class provides the working of TOEFL Writing section. ''' def question(self): pass def __init__(self): pass ## TODO: Label - instructions, question ## TODO: Text Field - Write answerd
class GameObject: def __init__(self, data, localizer): # self.key will be set prior to invoking _name() self.key = self._key(data) self.name = self._name(localizer) self.prerequisites = self._prerequisites(data[self.key]) def _name(self, localizer): return localizer.get(self.key) def _key(self, data): return list(data.keys())[0] def _prerequisites(self, data): return self._valueOrDefault(data, 'prerequisites', []) def _valueOrDefault(self, data, name, default): try: val = next(iter(key for key in data if list(key.keys())[0] == name))[name] except StopIteration: val = default return val def _boolFromYes(self, data, name, default = False): try: yes_no = next(iter(key for key in data if list(key.keys())[0] == name))[name] yes_no = True if yes_no.lower() == 'yes' else False except StopIteration: yes_no = default return yes_no
ALL_LETTERS = [ letter.lower() for letter in [ "E", "A", "R", "I", "O", "T", "N", "S", "L", "C", "U", "D", "P", "M", "H", "G", "B", "F", "Y", "W", "K", "V", "X", "Z", "J", "Q", ] ] class GameState: def __init__(self, word_length=5): self.word_length = word_length self.unexplored_letters = ALL_LETTERS self.bad_letters = {idx: [] for idx in range(word_length)} self.potential_letters = {idx: [] for idx in range(word_length)} self.solution = {idx: [] for idx in range(word_length)} def print(self): print("Bad letters:") print(self.bad_letters) print("Potential letters:") print(self.potential_letters) print("All potential letters:") print(self.all_potential_letters()) print("Solution:") print(self.print_solution()) def print_solution(self): solution = "" for letter in self.solution.values(): if letter == []: solution += "_" else: solution += letter return solution def update(self, guess, results): # print(f"Updating Game State with guess={guess} and results={results}") # print("Before update") # self.print() for idx in range(self.word_length): try: letter = guess[idx] except IndexError: raise IndexError(f"Entered guess length should be {self.word_length}") try: result = results[idx] except IndexError: raise IndexError(f"Entered result length should be {self.word_length}") # remove from unexplored letters try: self.unexplored_letters.remove(letter) except ValueError: pass if result == "0": # remove from possible letters self.add_bad_letter(letter, idx) elif result == "1": self.add_potential_letter(letter, idx) elif result == "2": # add to solution self.add_valid_letter(letter, idx) # self.print() # input("After update") def all_valid_letters(self): return filter(lambda x: x not in self.bad_letters, ALL_LETTERS) def required_letters(self): return list(set([letter for letter in self.solution.values() if letter != []])) def unchecked_vowels(self): return [ letter for letter in ["a", "e", "i", "o", "u", "y"] if letter in self.unexplored_letters ] def possible_words(self, words, ignore_solution=False): possible_words = [] for word in words: invalid = False if not self.valid_word(word) and not ignore_solution: invalid = True continue if not invalid and not ignore_solution: for idx, letter in self.solution.items(): if letter != [] and word[idx] != letter: invalid = True continue if not invalid: possible_words.append(word) return possible_words def valid_word(self, word): # invalid if bad letters present at each index for index, bad_letters in self.bad_letters.items(): if word[index] in bad_letters: return False return True def add_bad_letter(self, letter, idx): self.bad_letters[idx].append(letter) self.bad_letters[idx] = list(set(self.bad_letters[idx])) def add_potential_letter(self, letter, found_at): try: tmp = list(set(self.potential_letters[found_at])) tmp.remove(letter) self.potential_letters[found_at] = tmp except ValueError: pass # add to misplaced letters self.add_bad_letter(letter, found_at) for idx in range(self.word_length): if idx != found_at: # only update other indices if not already part of the solution if self.solution[idx] == []: self.potential_letters[idx].append(letter) def add_valid_letter(self, letter, index): self.solution[index] = letter self.potential_letters[index] = [] def all_potential_letters(self): all_potential_letters = [] for _, letters in self.potential_letters.items(): all_potential_letters.extend(letters) for _, letters in self.solution.items(): all_potential_letters.extend(letters) return list(set(all_potential_letters)) def unexplored_vowels(self): return [ letter for letter in ["a", "e", "i", "o", "u", "y"] if letter in self.unexplored_letters ]
# delete the item ‘Indian’ created in the dictionary for L3_10 theDict = dict() theDict['Indian'] = 'Charles Bronson' theDict['1'] = 'Airplane' theDict['2'] = 'Car' theDict['3'] = 'Boat' print('theDict before: ', theDict) # now delete the item del theDict['Indian'] print('theDict after: ', theDict)
class PistonResponse: def __init__(self, data: dict) -> None: self.ran = data.get("ran") self.language = data.get("language") self.version = data.get("version") self.stdout = data.get("stdout") self.stderr = data.get("stderr") self.output = data.get("output") def __repr__(self) -> str: return f"<PistonResponse language='{self.language}' version='{self.version}' ran={self.ran}>" def __str__(self) -> str: return self.output def __eq__(self, o) -> bool: if isinstance(o, PistonResponse): return self.output == o.output else: return self.output == o.output def __ne__(self, o) -> bool: return not self.__eq__(o)
# 066 - TRATANDO VARIOS VALORES V1.0 # LER VARIOS NUMEROS INTEIROS, PARA QUANDO FOR DIGITADO 999 E SOMAR TODOS DIGITADOS # DESCONSIDERANDO 999 somar = qtd = 0 while True: n = int(input('Digite um numero: [Digite 999 para parar[: ')) if n == 999: break somar += n qtd += 1 print(f'Foram digitados {qtd} numeros, com o total de {somar}')
""" LC 2156 The hash of a 0-indexed string s of length k, given integers p and m, is computed using the following function: hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m. Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1 to val('z') = 26. You are given a string s and the integers power, modulo, k, and hashValue. Return sub, the first substring of s of length k such that hash(sub, power, modulo) == hashValue. The test cases will be generated such that an answer always exists. A substring is a contiguous non-empty sequence of characters within a string. Example 1: Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0 Output: "ee" Explanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0. "ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee". Example 2: Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32 Output: "fbx" Explanation: The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32. The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32. "fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx". Note that "bxz" also has a hash of 32 but it appears later than "fbx". """ class Solution: def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str: base = 1 code = 0 for i in range(len(s) - k, len(s)): v = ord(s[i]) - 96 code +=(base * v) % modulo base = (base * power) % modulo i = len(s) - k tail = len(s) p_end = pow(power, k - 1, modulo) ans = i while i > 0: i -= 1 tail -= 1 code -= (ord(s[tail]) - 96) * p_end code =(code * power) % modulo code = (code + (ord(s[i]) - 96)) % modulo if code == hashValue: ans = i return s[ans: ans + k] """ Time O(N) Space O(1) """
numero = int(input('Digite um numero: ')) total = 0 for c in range(1, numero + 1): if numero % c == 0: print('\33[32m', end='') total += 1 else: print('\33[33m', end='') print(f'{c} ', end='') if total == 2: print(' numero é primo') else: print(' numero nao é primo')
# 本方法的目标是爬取某站点的资源到本地, # 然后上传至七牛云或者通过邮件附件发送到指定的email, 最后删除本地的文件 # 由于文件名是未知的, 是可以任意构造的, 所以最后删除本地文件的代码是致命的 # 解决方案: # a. 将下载文件放置一个文件夹 temp 下, 然后 rm -f temp/* # b. 将文件名使用base64等进行编码, 然后 rm -f encrypt_base64(filename) def download(self, url, email): # 解析下载链接 download_url = self.download_parser(url) # 获取cookie_jar jar = self.get_cookie_jar() headers = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) ' 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36' } # 请求资源内容 r = requests.get(download_url, cookies=jar, headers=headers) if r.status_code == 200: # 获取文件名 filename = str(r.headers['Content-Disposition'].split('"')[1].encode('ISO-8859-1'), encoding='utf-8') # 写入文件 with open(filename, 'wb') as f: f.write(r.content) file_size = helper.get_file_size(filename) if file_size is not None: # 文件如果大于50MB,使用七牛云存储 if file_size > 50 * 1024 * 1024: print('使用七牛云') # 上传到七牛云 helper.upload_to_qiniu(filename) helper.send_email(email, self.qiniu_domain + filename) else: print('使用附件') helper.send_email_with_file(email, filename) # 删除本地文件 cmd = 'rm -f ' + filename os.system(cmd)
#Fatiamento oi = 'Curso em Vídeo Python' print(oi[3:14]) print(oi[9]) print(oi[0:21:2]) print(oi[:14]) print(oi[8:]) print(oi[8::3])
class MissingVenvException(Exception): def __init__(self, msg=''): super().__init__(msg) class CantRunProgramException(Exception): def __init__(self, msg=''): super().__init__(msg) class NoPythonExeFound(Exception): def __init__(self, msg=''): super().__init__(msg='') class NoPluginsSelected(Exception): def __init__(self, msg=''): super().__init__(msg)
# Sem else Condicao simples # Com else Condicao composta nome = str(input('Qual eh o seu nome: ')) if nome == 'Rafael': print('Que nome lindo voce tem!') else: print('Seu nome eh tao normal!') print('Bom dia, {}' .format(nome))
class Cliente: def __init__(self, nome, sexo, data_nascimento, email, profissao, endereco): self.__nome = nome self.__sexo = sexo self.__data_nascimento = data_nascimento self.__email = email self.__profissao = profissao self.__endereco = endereco @property def nome(self): return self.__nome @nome.setter def nome(self, nome): self.__nome = nome @property def sexo(self): return self.__sexo @sexo.setter def sexo(self, sexo): self.__sexo = sexo @property def data_nascimento(self): return self.__data_nascimento @data_nascimento.setter def data_nascimento(self, data_nascimento): self.__data_nascimento = data_nascimento @property def email(self): return self.__email @email.setter def email(self, email): self.__email = email @property def profissao(self): return self.__profissao @profissao.setter def profissao(self, profissao): self.__profissao = profissao @property def endereco(self): return self.__endereco @endereco.setter def endereco(self, endereco): self.__endereco = endereco
# 3.3 Write a program to prompt for a score between 0.0 and 1.0. # If the score is out of range, print an error. # If the score is between 0.0 and 1.0, print a grade using the following table: # Score Grade # >= 0.9 A # >= 0.8 B # >= 0.7 C # >= 0.6 D # < 0.6 F # If the user enters a value out of range, # print a suitable error message and exit. For the test, enter a score of 0.85. score=float(input("Enter the score between 0.0 and 1.0")) if score >1.0 and score<0.0: print("Error out of range input.") elif score >=0.9: print("A") elif score >=0.8: print("B") elif score >=0.7: print("C") elif score >= 0.6: print("D") elif score < 0.6: print("F") else: print("Invalid or no input") k="Hellow zworld" print(max(k))
num_1 = int(input("Enter a number: ")) num_3 = 0 while num_1 > 0: num_2 = num_1 % 10 print(num_2,end = "") num_1 = num_1 // 10 num_3 = num_3 + num_2 print(" ",num_2**3) print(" ") print(num_3)
class Solution: def maximalRectangle(self, matrix): res, m, n = 0, len(matrix), len(matrix and matrix[0]) for i in range(m): for j in range(n): if matrix[i][j] != "0": if j > 0 and matrix[i][j - 1] != "0": matrix[i][j] = matrix[i][j - 1] + 1 else: matrix[i][j] = 1 mn, sm, k = matrix[i][j], 0, i + 1 while k > 0 and matrix[k - 1][j] != "0": if matrix[k - 1][j] < mn: sm, mn = (i - k + 2) * matrix[k - 1][j], matrix[k - 1][j] else: sm += mn if sm > res: res = sm k -= 1 return res
database = { 'name': 'splice_auth_db', 'user': 'postgres', 'password': '#100100Borjan', 'host': '127.0.0.1', 'port': 5432, } mail = { 'host': 'localhost', 'port': 25, 'user': '', 'password': '#100100Borjan', 'tls': False, 'ssl': False, }
class State(object): def __init__(self, data): self.data = data pass def change_data(self, data): self.data = data
# coding=utf-8 KEYBOARD_URL_MAPS = { 'default': [ [ 'Site wide shortcuts', # keyboard category [ # ('keyboard shortcut', 'keyboard info') ('s', 'Focus search bar'), ('g n', 'Go to Notifications'), ('g h', 'Go to personal page'), ('?', 'Bring up this help dialog'), ], ], [ 'Registration and login', [ ('l r', 'Open register window'), ('l o', 'Open login window'), ('l t', 'Logout'), ('l c', 'Close register/login window'), ], ], [ 'Notifications', [ ('e / I / y', 'Mark as read'), ], ], [ 'Personal page', [ ('g s', 'Go to personal settings page'), ('g t', 'Go to personal topic page'), ] ] ], '/': [ [ 'Topic list shortcuts', [ ('j', 'Move selection down'), ('k', 'Move selection up'), ('o', 'Open selection'), ], ], [ 'Create Topic', [ ('t o', 'Open create topic window'), ('t q', 'Close create topic window'), ('t s', 'Submit create topic'), ], ] ], '/post': [ [ 'Reply Topic', [ ('p o', 'Open reply topic window'), ('p q', 'Close reply topic window'), ('p s', 'Submit reply topic'), ], ], ] } # http://clrs.cc/ CATEGORY_COLORS = ( '#001f3f', # Navy '#0074D9', # Blue '#7FDBFF', # Aqua '#39CCCC', # Teal '#3D9970', # Olive '#2ECC40', # Green '#01FF70', # Lime '#FFDC00', # Yellow '#FF851B', # Orange '#FF4136', # Red '#85144b', # Maroon '#F012BE', # Fuchsia '#b10dc9', # Purple '#111111', # black '#aaaaaa', # Gray '#dddddd', # Silver )
class Files: path = './coordinates/' qatar = 'qatar.csv' western_sahara = 'western_sahara.csv' uruguay = 'uruguay.csv' djibouti = 'djibouti.csv' random_10_cities = 'random_10_cities.csv' random_20_cities = 'random_20_cities.csv' random_30_cities = 'random_30_cities.csv' # config class ENConfig: read_file = True file_path = Files.path city_file = Files.random_20_cities city_num = 100 class SOMConfig: read_file = True file_path = Files.path city_file = Files.random_20_cities city_num = 30 class HNConfig: read_file = True file_path = Files.path city_file = Files.random_10_cities city_num = 30 class GifMakerConfig: __path = './results/' __problem_set = 'random_30_cities/' __en_path = 'elastic_nets/' __som_path = 'self_organizing_map/' source_dir = __path + __problem_set + __en_path
#Exercício página 241 class User(): """Modelar um usuário""" def __init__(self, first_name, last_name, age, location): self.first_name = first_name self.last_name = last_name self.age = age self.location = location self.full_name = first_name +" "+last_name self.login_attempts = 0 def describe_user(self): print("Name: "+ self.full_name.title()) print("Age: "+ str(self.age)) print("Location: "+self.location.title()) def greet_user(self): print("\nBem vindo á plataforma, "+ self.full_name.title()+"!") def increment_login_attempts(self): """Adiciona uma tentativa """ self.login_attempts += 1 def reset_login_attempts(self): """Reseta as tentativas""" self.login_attempts = 0 print("Tentativas resetadas") def get_login_attempts(self): return self.login_attempts class Admin(User): def __init__(self,first_name,last_name,age,location): super().__init__(first_name,last_name,age,location) self.adm_privileges = Privileges() class Privileges(): def __init__(self): self.privileges=['can add post', 'can delete post','can accept user','can ban user'] def show_privileges(self): for privilege in self.privileges: print(privilege) adm = Admin('Bruno','Pires',19,'Joinville') adm.adm_privileges.show_privileges()
number = int(input("Which number do you want to check? ")) if number % 2==0: print("Even") else: print("Odd")
"""You kwow, a little of this, a little of that.""" class CacheDict(dict): def get(self, key): try: return self[key] except KeyError: return None def set(self, key, value, time): self[key] = value class SettingsRequired(RuntimeWarning): pass
def eigenvalues(eigenvalues_at_kpoints, kpoint_index=0, spin_index=0): """ Returns eigenvalues for a given kpoint and spin. Args: eigenvalues_at_kpoints (list): a list of eigenvalues for all kpoints. kpoint_index (int): kpoint index. spin_index (int): spin index. Returns: ndarray """ spin_map = {0: 0.5, 1: -0.5} for eigenvalue in eigenvalues_at_kpoints[kpoint_index]["eigenvalues"]: if eigenvalue['spin'] == spin_map[spin_index]: return eigenvalue['energies'] def to_array_with_ids(array): """ Converts a given array to an array of objects with id. Args: array (list): array to convert Returns: list """ return [{"id": index + 1, "value": value} for index, value in enumerate(array)]
class DataRandomAccess(): def __init__(self, dataset): self._dataset = dataset self._scheme = dataset._scheme def __getitem__(self, slice): return self._scheme.ra(slice)
# STRUCTURE INFORMATION WITH A SIMPLE STACK METHOD # Santiago Garcia Arango, July 2020 """ Stacks are simple data-structures that work really well, when we have a problem that involves adding or removing elements but following the concept of LIFO(Last-In, First-Out). This means that the operations affect always the "top-item" that is currently on the stack. We usually create methods to: PUSH --> Add item on top of the stack. POP --> Remove top item of the stack. CLEAR --> Delete all items on the stack. UNDO --> Let us "go back" in the stack operations once. """ class Stack(): """ --------STACK CLASS HELP-------- -->Parameters: :param name: string for the name of stack.\n -->Methods: :push(): add element on top of stack. :pop(): delete top element of stack. :look_last_item(): return last element of stack. :clear_stack(): delete all stack elements. :__str__(): return stack. """ def __init__(self, name="No name"): self.stack = [] self.name = name def push(self, item): """:param item: object or item to be added to stack.""" self.stack.append(item) def pop(self): if len(self.stack) > 0: # ".pop()" is a Python method to remove last element of list. return self.stack.pop() else: return None def look_last_item(self): if len(self.stack) > 0: return self.stack[len(self.stack)-1] else: return None def clear_stack(self): self.stack = [] def __str__(self): return str(self.stack) # Check test in script < test_stack.py >
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/1/10 下午8:52 # @Author : Jason # @File : config.py MARKDOWN = { 'h1': ('\n# ', ''), 'h2': ('\n## ', ''), 'code': ('\n```\n', '\n```\n'), 'ul': ('', ''), 'ol': ('', ''), 'li': ('- ', ''), 'blockquote': ('\n> ', ''), 'i': ('*', '*\n'), 'b': ('**', '**\n'), 'bi': ('**', '**\n'), 'p': ('\n', '\n'), } PRE_ELEMENTS = { 'bi': '<b><i>(.*?)</i></b>', 'ul': '<ul.*?>(.*?)</ul>', 'ol': '<ol.*?>(.*?)</ol>', } BlOCK_ELEMENTS = { 'h1': '<h1.*?>(.*?)</h1>', 'h2': '<h2.*?>(.*?)</h2>', 'code': '<pre.*?><code.*?>(.*?)</code></pre>', 'li': '<li.*?>(.*?)</li>', 'blockquote': '<blockquote.*?>(.*?)</blockquote>', 'i': '<i.*?>(.*?)</i>', 'b': '<b.*?>(.*?)</b>', 'p': '<p> (.*?)</p>', 'link': '<a.*?>.*?<span class="LinkCard-title".*?>(.*?)</span>.*?<span class="LinkCard-meta">(.*?)</span>.*?</a>', 'latex': '<img.*?alt="(.*?)".*?>', 'img_with_content': '<noscript>.*?src="(.*?)".*?</noscript>.*?<figcaption>(.*?)</figcaption>', } INLINE_ELEMENTS_LIST_KEYS = list(BlOCK_ELEMENTS.keys()) DELETE_ELEMENTS = ['<span.*?>', '</span>', '<div.*?>', '</div>']
class Result(object): """ Base class for analysis results """ def __init__(self): self.results = [] self.header = 'Abstract analysis result' def is_ok(self): return len(self.results) == 0 def add(self, err): self.results.append(err) def format_header(self): return "\n{}\n---\n".format(self.header)
num = int(input()) num2 = int(input()) soma = num + num2 print('X = {}'.format(soma))
print('hey its a calculator') print('select from thr below') print('select 1 for addtion, 2 for multiplication, 3 for division, 4 for substract') while True: try: opearation = int(input('select 1 or 2 or 3 or 4 : ')) break except ValueError: print("pls enter a number") while True: try: num1 = int(input("pls enter the first number : ")) break except ValueError: print("pls enter a number") while True: try: num2 = int(input("pls enter the 2nd number : ")) break except ValueError: print("enter a number") if opearation is 1: print('the sum of this is ', num1+num2) elif opearation is 2: print('the multiplication of this is ', num1*num2) elif opearation is 3: print('the division of this is ', num1/num2) elif opearation is 4: print('the substaction of this is ', num1-num2) else: print('pls select a vaild option')
def extractLilBlissNovels(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if ':' in item['title'] and 'Side Story' in item['title'] and not postfix: postfix = item['title'].split(':')[-1] if 'Wei Wei Yi Xiao Hen Qing Cheng' in item['tags']: return buildReleaseMessageWithType(item, 'Wei Wei Yi Xiao Hen Qing Cheng', vol, chp, frag=frag, postfix=postfix) if 'Memory Lost' in item['tags']: return buildReleaseMessageWithType(item, 'Memory Lost', vol, chp, frag=frag, postfix=postfix) return False
def _single_fortran_object_impl(ctx): toolchain_cflags = (ctx.fragments.cpp.compiler_options([]) + ctx.fragments.cpp.c_options + ctx.fragments.cpp.unfiltered_compiler_options([]) + ['-fPIC', '-Wno-maybe-uninitialized', '-Wno-unused-dummy-argument', '-Wno-conversion', '-Wno-unused-variable', '-Wno-character-truncation']) cmd = toolchain_cflags + ['-c', ctx.file.src.path, '-o', ctx.outputs.pic_o.path] filtered_cmd = [] # Strip out the C/C++/Clang specific flags. exclude_flags = ['-fcolor-diagnostics', '-Wswitch-enum', '-Wpointer-arith', '-Wcast-qual', '-Wwrite-strings', '-Wsign-compare', '-Wformat=2', '-Werror', '-Wextra', '-Wno-builtin-macro-redefined', '-Wunused-local-typedefs', '-D__has_feature(x)=0', '-fmacro-backtrace-limit=0'] for flag in cmd: if flag not in exclude_flags and not (flag.startswith('-fsanitize') or flag.startswith('-fno-sanitize')): filtered_cmd.append(flag) ctx.action( inputs = [ctx.file.src] + ctx.files._cc_toolchain, outputs = [ctx.outputs.pic_o], mnemonic = "Fortran", executable = ctx.fragments.cpp.compiler_executable, arguments = filtered_cmd, progress_message = 'Building %s' % ctx.outputs.pic_o.short_path, ) def _define_fortran_output(attrs): if not attrs.src.name.endswith('.f'): fail('Fortran files must end in \'.f\'', 'src') fortran_file_base = attrs.src.name[:-2] return { 'pic_o': fortran_file_base + '.pic.o', } _single_fortran_object = rule( implementation = _single_fortran_object_impl, attrs = { 'src': attr.label(single_file=True, allow_files=FileType(['.f'])), 'cc_libs': attr.label_list(providers=['cc']), # TODO(Brian): Replace this with something more fine-grained from the # configuration fragment or something. '_cc_toolchain': attr.label( default = Label('//tools/cpp:toolchain'), ), }, outputs = _define_fortran_output, fragments = [ 'cpp', ], ) def fortran_library(name, srcs, deps = [], visibility = None): """Builds a shared library from a set of fortran files. Args: srcs: list of fortran files ending in .f deps: cc_library or fortran_library dependencies. """ pic_o_files = [] for src in srcs: pic_o_file = src[:-2] + '.pic.o' _single_fortran_object( name = name + '_' + pic_o_file, src = src, visibility = ['//visibility:private'], ) pic_o_files.append(pic_o_file) native.cc_library( name = name, deps = deps, srcs = pic_o_files, linkopts = [ '-lgfortran', ], visibility = visibility, )
# Column/Label Types NULL = 'null' CATEGORICAL = 'categorical' TEXT = 'text' NUMERICAL = 'numerical' ENTITY = 'entity' # Feature Types ARRAY = 'array'
def lift1d(n): """ Convert the first n arguments of the decorated function to 1d lists if they are not passed as lists, then unpack lists before returning """ def decorator(fn): def new_fn(*args, **kwargs): assert len(args) >= n, 'Expected first {} arguments to be non-keyword' args_to_lift, args_remaining = args[:n], args[n:] all_are_1d = all(not isinstance(arg, list) for arg in args_to_lift) none_is_1d = all(isinstance(arg, list) for arg in args_to_lift) all_or_none_1d = all_are_1d ^ none_is_1d assert all_or_none_1d, 'Expected first {} arguments either all to be lists, or none to be lists: {}'.format( n, args_to_lift) if all_are_1d: args_to_lift = tuple([arg] for arg in args_to_lift) args_lifted = args_to_lift + args_remaining ret = fn(*args_lifted, **kwargs) if not ret or not all_are_1d: return ret if isinstance(ret, tuple): # unpack lists again return tuple(r[0] for r in ret) return ret[0] return new_fn return decorator
#Ordenacao de listas #1. Dada uma lista, retornar o elemento que esta a cabeca (ou seja, na posicao 0). def algorithmic_sort(lista,type): if type == 1: #Selection Sort for i in range(len(lista)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(lista)): if lista[min_idx] > lista[j]: min_idx = j # Swap the found minimum element with # the first element lista[i], lista[min_idx] = lista[min_idx], lista[i] return lista if type == 2: #Bubble Sort for i in range(len(lista)): # Last i elements are already in place for j in range(0, len(lista)-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if lista[j] > lista[j+1] : lista[j], lista[j+1] = lista[j+1], lista[j] return lista if type == 3: #Quick Sort return quicksort(lista) return None #Quick Sort Functions# def quicksort(lista): lesser = [] equal = [] greater = [] if len(lista) > 1: pivot = lista[0] for x in lista: if x < pivot: lesser.append(x) elif x == pivot: equal.append(x) else: greater.append(x) return quicksort(lesser)+equal+quicksort(greater) else: return lista ###################### #2. Similar ao numero anterior, mas sem restricao no tipo dos elementos da lista de entrada. A funcao de ordenacao recebe, num parametro adicional, a rela¸cao de ordem (uma funcao binaria booleana para comparacao elemento a elemento) segundo a qual a lista de entrada deve ser ordenada. def algorithmic_sort_2(lista,type,compare): if type == 1: #Selection Sort for i in range(len(lista)): # Find the minimum element in remaining # unsorted array min_idx = i for j in range(i+1, len(lista)): if compare(lista[min_idx],lista[j]): min_idx = j # Swap the found minimum element with # the first element lista[i], lista[min_idx] = lista[min_idx], lista[i] return lista if type == 2: #Bubble Sort for i in range(len(lista)): # Last i elements are already in place for j in range(0, len(lista)-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if compare(lista[j],lista[j+1]) : lista[j], lista[j+1] = lista[j+1], lista[j] return lista if type == 3: #Quick Sort return quicksort2(lista,compare) return None #Quick Sort Functions# def quicksort2(lista,compare): la = [] equal = [] lb = [] if len(lista) > 1: pivot = lista[0] for x in lista: if compare(x,pivot): lb.append(x) elif x == pivot: equal.append(x) else: la.append(x) return quicksort2(la,compare)+equal+quicksort2(lb,compare) else: return lista ###################### if __name__ == "__main__": #1 print("1) " + str(algorithmic_sort([3,2,5,1,4],1))) print("1) " + str(algorithmic_sort([3,2,5,1,4],2))) print("1) " + str(algorithmic_sort([3,2,5,1,4],3))) #2 comparassion = lambda x,y: x<y print("2) " + str(algorithmic_sort_2([3,2,5,1,4],1,comparassion))) print("2) " + str(algorithmic_sort_2([3,2,5,1,4],2,comparassion))) print("2) " + str(algorithmic_sort_2([3,2,5,1,4],3,comparassion)))
class Driver: def __init__(self, cores: int) -> None: self._cores = cores def shield_cpu(self, *cpu): pass def unshield_cpu(self, *cpu): pass
i = 40 - 3 for j in range(3, 12, 2): print(j) i = i + 1 print(i)
#qualquer coisa c =10 d =2 print(c/d) a = c + d e = c + d
""" ## Questions: MEDIUM ### 1015. [Smallest Integer Divisible by K](https://leetcode.com/problems/smallest-integer-divisible-by-k) Given a positive integer K, you need find the smallest positive integer N such that N is divisible by K, and N only contains the digit 1. Return the length of N. If there is no such N, return -1. Example 1: Input: 1 Output: 1 Explanation: The smallest answer is N = 1, which has length 1. Example 2: Input: 2 Output: -1 Explanation: There is no such positive integer N divisible by 2. Example 3: Input: 3 Output: 3 Explanation: The smallest answer is N = 111, which has length 3. Note: 1 <= K <= 10^5 """ # Solutions class Solution: """ Time Complexity: o(K) Space Complexity: O(K) """ def smallestRepunitDivByK(self, K: int) -> int: N = 1 track = dict() while True: rem = N % K if rem == 0: return len(str(N)) if track.get(rem): return -1 track[rem] = True N = N * 10 + 1 # Runtime : 2008 ms, faster than 33.74% of Python3 online submissions # Memory Usage : 18.7 MB, less than 5.29% of Python3 online submissions class Solution: """ Time Complexity: o(K) Space Complexity: O(1) """ def smallestRepunitDivByK(self, K: int) -> int: rem = 0 for length_N in range(1, K + 1): rem = (rem * 10 + 1) % K if rem == 0: return length_N return -1 # Runtime : 40 ms, faster than 95.94% of Python3 online submissions # Memory Usage : 13.8 MB, less than 84.55% of Python3 online submissions
__author__ = "Adriaan van der Graaf" class Sample: """ Implements a sample. only name is stored. Attributes ---------- Name: str sample name Phenotype: can be a value, an array or dictionary of values, but initialized as None """ def __init__(self, name, phenotype=None): self.name = name self.phenotype = phenotype def _str__(self): return self.name
# Jim Lawless # License: https://github.com/jimlawless/AoC2020/LICENSE x=0 y=0 # treat N,W as -1, S,W as +1. # NESW directions=[-1,1,1,-1] # begin with East direction=1 infile = open("input.txt","r") for line in infile: line=line.rstrip() cmd=line[0:1] arg=int(line[1:]) if cmd=="F": if((direction==0)or(direction==2)): y=y+directions[direction]*arg else: x=x+directions[direction]*arg if cmd=="N": y=y+directions[0]*arg if cmd=="E": x=x+directions[1]*arg if cmd=="W": x=x+directions[3]*arg if cmd=="S": y=y+directions[2]*arg if cmd=="R": count=arg//90 direction=(direction+count)% len(directions) if cmd=="L": count=arg//90 while count>0: direction=direction-1 if direction<0: direction = 3 count=count -1 infile.close() print("{} {}".format(x,y)) if x<0: x=x*-1 if y<0: y=y*-1 print(x+y)
print(4 + 4) print(10 - 2) print(2 * 4) print(int(64 / 8))
"""Color palette information for the Tetris game.""" WHITE = (255, 255, 255) GRAY = (185, 185, 185) BLACK = (0, 0, 0) CYAN = (4, 216, 219) LIGHT_CYAN = (3, 252, 255) BLUE = (20, 27, 194) LIGHT_BLUE = (25, 34, 251) ORANGE = (202, 131, 24) LIGHT_ORANGE = (250, 146, 0) YELLOW = (218, 217, 42) LIGHT_YELLOW = (255, 255, 0) GREEN = (9, 220, 43) LIGHT_GREEN = (61, 255, 0) PURPLE = (133, 29, 200) LIGHT_PURPLE = (146, 0, 255) RED = (202, 34, 5) LIGHT_RED = (246, 0, 0) # the color of the game border BORDERCOLOR = WHITE # the background color for the game board BGCOLOR = BLACK # the color to use for text labels TEXTCOLOR = WHITE # the shadow color for text to give perspective TEXTSHADOWCOLOR = GRAY # the background color for Tetrominos COLORS = ( CYAN, BLUE, ORANGE, YELLOW, GREEN, PURPLE, RED ) # the foreground color for Tetrominos LIGHTCOLORS = ( LIGHT_CYAN, LIGHT_BLUE, LIGHT_ORANGE, LIGHT_YELLOW, LIGHT_GREEN, LIGHT_PURPLE, LIGHT_RED ) # The color palette for game pieces PALETTE = {shape: index for index, shape in enumerate(list('IJLOSTZ'))}
def next0(A,n,x): while x<n and A[x]!=0: x+=1 return x n=int(input()) A=[int(j) for j in input().split()] b=0 for i in range(n): if A[i]==1: b=next0(A,n,max(b,i)) if b==n: break A[i],A[b]=A[b],A[i] for i in A: print(i,end=" ")
c = get_config() # get the config object c.IPKernelApp.pylab = 'inline' # in-line figure when using Matplotlib c.NotebookApp.ip = '*' c.NotebookApp.allow_remote_access = True # allow access from outside localhost c.NotebookApp.open_browser = False # do not open a browser window by default when using notebooks c.NotebookApp.notebook_dir = '/notebooks' c.NotebookApp.allow_root = True # Allow to run Jupyter from root user inside Docker container
class Solution: def reverse(self, x: int) -> int: reverse = '' num = x if num < 0: neg = True num = -1 * (num) num = str(num) for i in range (len(num),0,-1): reverse += num[i-1] final = (-1 * int(reverse)) else: num = str(num) for i in range (len(num),0,-1): reverse += num[i-1] final = (int(reverse)) if(final in range((-2**31),((2**31)-1))): return final else: return 0
def groupAnagrams(strs): x=[[i,tuple(sorted(list(i)))] for i in strs] # print(x) d= {} for i,j in x: if j not in d: d[j] = [i] else: d[j].append(i) return(d.values())
class Pagination(object): # 定pagination类 page_size = 10 page_size_query_param = 'page_size' page_query_param = 'page' max_page_size = 100
number = "9,223,372,036,854,775,807" cleanedNumber = '' for i in range(0, len(number)): if number[i] in '0123456789': cleanedNumber = number[i] newNumber = int(cleanedNumber) print("The number is {} ".format(newNumber)) x = 23 x += 1 print(x) x -= 4 print(x) x *= 5 print(x) x /= 4 print(x) x **=2 print(x) x %= 60 print(x) greeting = "Good " greeting += "morning " print(greeting) greeting *= 5 print(greeting) # += -= *= /= %= **= <<= >>= &= ^= |=