content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def funny(x): if (x%2 == 1): return x+1 else: return funny(x-1) print(funny(7)) print(funny(6))
def funny(x): if x % 2 == 1: return x + 1 else: return funny(x - 1) print(funny(7)) print(funny(6))
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This package contains only the Brewery DB API key. It is necessary to provide an alternate method for this key entry when using chalice so that secrets aren't improperly shared. """ BREWERY_KEY = "<YOUR_BREWERY_DB_API_APP_KEY_HERE>" S3_BUCKET = "<YOUR_S3_BUCKET>"
""" This package contains only the Brewery DB API key. It is necessary to provide an alternate method for this key entry when using chalice so that secrets aren't improperly shared. """ brewery_key = '<YOUR_BREWERY_DB_API_APP_KEY_HERE>' s3_bucket = '<YOUR_S3_BUCKET>'
class TweetComplaint: def __init__(self, complain_text, city, state, tweet_id, username, image_url): self.complain_text = complain_text self.tweet_id = tweet_id self.username = username self.city = city self.state = state self.image_url = image_url self.status = "reported" def __str__(self): return self.complain_text +'\n'+ str(self.tweet_id) +'\n'+ self.username +'\n'+ self.city +'\n'+ self.state +'\n'+ self.image_url def to_dict(self): return {'category': '', 'city': self.city, 'state': self.state, 'image_url': self.image_url, 'status': self.status, 'text': self.complain_text, 'tweet_id': self.tweet_id, 'username': self.username}
class Tweetcomplaint: def __init__(self, complain_text, city, state, tweet_id, username, image_url): self.complain_text = complain_text self.tweet_id = tweet_id self.username = username self.city = city self.state = state self.image_url = image_url self.status = 'reported' def __str__(self): return self.complain_text + '\n' + str(self.tweet_id) + '\n' + self.username + '\n' + self.city + '\n' + self.state + '\n' + self.image_url def to_dict(self): return {'category': '', 'city': self.city, 'state': self.state, 'image_url': self.image_url, 'status': self.status, 'text': self.complain_text, 'tweet_id': self.tweet_id, 'username': self.username}
class Solution: def rob(self, num): ls = [[0, 0]] for e in num: ls.append([max(ls[-1][0], ls[-1][1]), ls[-1][0] + e]) return max(ls[-1])
class Solution: def rob(self, num): ls = [[0, 0]] for e in num: ls.append([max(ls[-1][0], ls[-1][1]), ls[-1][0] + e]) return max(ls[-1])
# -*- coding: utf-8 -*- __version__ = '0.16.1.dev0' PROJECT_NAME = "planemo" PROJECT_USERAME = "galaxyproject" RAW_CONTENT_URL = "https://raw.github.com/%s/%s/master/" % ( PROJECT_USERAME, PROJECT_NAME )
__version__ = '0.16.1.dev0' project_name = 'planemo' project_userame = 'galaxyproject' raw_content_url = 'https://raw.github.com/%s/%s/master/' % (PROJECT_USERAME, PROJECT_NAME)
"""This is the entry point of the program.""" def bubble_sort(list_of_numbers): for i in range(len(list_of_numbers)-1,0,-1): for j in range(i): if list_of_numbers[j] > list_of_numbers[j+1]: placeholder = list_of_numbers[j] list_of_numbers[j] = list_of_numbers[j+1] list_of_numbers[j+1] = placeholder return list_of_numbers if __name__ == '__main__': print(bubble_sort([9, 1, 3, 11, 7, 2, 42, 111]))
"""This is the entry point of the program.""" def bubble_sort(list_of_numbers): for i in range(len(list_of_numbers) - 1, 0, -1): for j in range(i): if list_of_numbers[j] > list_of_numbers[j + 1]: placeholder = list_of_numbers[j] list_of_numbers[j] = list_of_numbers[j + 1] list_of_numbers[j + 1] = placeholder return list_of_numbers if __name__ == '__main__': print(bubble_sort([9, 1, 3, 11, 7, 2, 42, 111]))
spec = { 'name' : "ODL demo", 'external network name' : "exnet3", 'keypair' : "X220", 'controller' : "r720", 'dns' : "10.30.65.200", 'credentials' : { 'user' : "nic", 'password' : "nic", 'project' : "nic" }, # 'credentials' : { 'user' : "admin", 'password' : "admin", 'project' : "admin" }, # NOTE: network start/end range - # a) must not include the gateway IP # b) when assigning host IPs remember taht a DHCP server will be allocated from the range as well as the hosts # Probably on the first or second available IP in the range.... 'Networks' : [ { 'name' : "odldemo" , "start": "192.168.50.2", "end": "192.168.50.254", "subnet" :" 192.168.50.0/24", "gateway": "192.168.50.1" }, { 'name' : "odldemo2" , "start": "192.168.111.2", "end": "192.168.111.254", "subnet" :" 192.168.111.0/24", "gateway": "192.168.111.1" }, { 'name' : "odldemo3" , "start": "172.16.0.2", "end": "172.16.0.254", "subnet" :" 172.16.0.0/24", "gateway": "172.16.0.1" }, ], # Hint: list explicity required external IPs first to avoid them being claimed by hosts that don't care... 'Hosts' : [ { 'name' : "devstack-control" , 'image' : "trusty64" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.20", "devstack-control"), ("odldemo2" , "192.168.111.10"), ("odldemo3" , "172.16.0.10") ] }, { 'name' : "devstack-compute-1" , 'image' : "trusty64" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.21","devstack-compute-1"), ("odldemo2" , "192.168.111.11"), ("odldemo3" , "172.16.0.11") ] }, # { 'name' : "devstack-compute-2" , 'image' : "trusty64" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.22") ] }, # { 'name' : "devstack-compute-3" , 'image' : "trusty64" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.23") ] }, { 'name' : "kilo-controller" , 'image' : "Centos7" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.60", "kilo-controller"), ("odldemo2" , "192.168.111.50"), ("odldemo3" , "172.16.0.50") ] }, { 'name' : "kilo-compute-1" , 'image' : "Centos7" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.61", "kilo-compute-1"), ("odldemo2" , "192.168.111.51"), ("odldemo3" , "172.16.0.51") ] }, { 'name' : "kilo-compute-2" , 'image' : "Centos7" , 'flavor':"m1.xlarge" , 'net' : [ ("odldemo" , "192.168.50.62", "kilo-compute-2"), ("odldemo2" , "192.168.111.52"), ("odldemo3" , "172.16.0.52") ] }, ] }
spec = {'name': 'ODL demo', 'external network name': 'exnet3', 'keypair': 'X220', 'controller': 'r720', 'dns': '10.30.65.200', 'credentials': {'user': 'nic', 'password': 'nic', 'project': 'nic'}, 'Networks': [{'name': 'odldemo', 'start': '192.168.50.2', 'end': '192.168.50.254', 'subnet': ' 192.168.50.0/24', 'gateway': '192.168.50.1'}, {'name': 'odldemo2', 'start': '192.168.111.2', 'end': '192.168.111.254', 'subnet': ' 192.168.111.0/24', 'gateway': '192.168.111.1'}, {'name': 'odldemo3', 'start': '172.16.0.2', 'end': '172.16.0.254', 'subnet': ' 172.16.0.0/24', 'gateway': '172.16.0.1'}], 'Hosts': [{'name': 'devstack-control', 'image': 'trusty64', 'flavor': 'm1.xlarge', 'net': [('odldemo', '192.168.50.20', 'devstack-control'), ('odldemo2', '192.168.111.10'), ('odldemo3', '172.16.0.10')]}, {'name': 'devstack-compute-1', 'image': 'trusty64', 'flavor': 'm1.xlarge', 'net': [('odldemo', '192.168.50.21', 'devstack-compute-1'), ('odldemo2', '192.168.111.11'), ('odldemo3', '172.16.0.11')]}, {'name': 'kilo-controller', 'image': 'Centos7', 'flavor': 'm1.xlarge', 'net': [('odldemo', '192.168.50.60', 'kilo-controller'), ('odldemo2', '192.168.111.50'), ('odldemo3', '172.16.0.50')]}, {'name': 'kilo-compute-1', 'image': 'Centos7', 'flavor': 'm1.xlarge', 'net': [('odldemo', '192.168.50.61', 'kilo-compute-1'), ('odldemo2', '192.168.111.51'), ('odldemo3', '172.16.0.51')]}, {'name': 'kilo-compute-2', 'image': 'Centos7', 'flavor': 'm1.xlarge', 'net': [('odldemo', '192.168.50.62', 'kilo-compute-2'), ('odldemo2', '192.168.111.52'), ('odldemo3', '172.16.0.52')]}]}
#encoding:utf-8 subreddit = 'kratom' t_channel = '@r_kratom' def send_post(submission, r2t): return r2t.send_simple(submission)
subreddit = 'kratom' t_channel = '@r_kratom' def send_post(submission, r2t): return r2t.send_simple(submission)
n = 5 count = 0 total = 0 startCount = n - 3 while True: if count == n: break elif count < n: x = int(input()) if count > startCount: total = total + x count = count + 1 print('') print('Sum is %d.' % total)
n = 5 count = 0 total = 0 start_count = n - 3 while True: if count == n: break elif count < n: x = int(input()) if count > startCount: total = total + x count = count + 1 print('') print('Sum is %d.' % total)
JPEG_10918 = ( 'SOF0', 'SOF1', 'SOF2', 'SOF3', 'SOF5', 'SOF6', 'SOF7', 'SOF9', 'SOF10', 'SOF11', 'SOF13', 'SOF14', 'SOF15', ) JPEG_14495 = ('SOF55', 'LSE', ) JPEG_15444 = ('SOC', ) PARSE_SUPPORTED = { '10918' : [ 'Process 1', 'Process 2', 'Process 4', 'Process 14', ] } DECODE_SUPPORTED = {} ENCODE_SUPPORTED = {} ZIGZAG = [ 0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63]
jpeg_10918 = ('SOF0', 'SOF1', 'SOF2', 'SOF3', 'SOF5', 'SOF6', 'SOF7', 'SOF9', 'SOF10', 'SOF11', 'SOF13', 'SOF14', 'SOF15') jpeg_14495 = ('SOF55', 'LSE') jpeg_15444 = ('SOC',) parse_supported = {'10918': ['Process 1', 'Process 2', 'Process 4', 'Process 14']} decode_supported = {} encode_supported = {} zigzag = [0, 1, 5, 6, 14, 15, 27, 28, 2, 4, 7, 13, 16, 26, 29, 42, 3, 8, 12, 17, 25, 30, 41, 43, 9, 11, 18, 24, 31, 40, 44, 53, 10, 19, 23, 32, 39, 45, 52, 54, 20, 22, 33, 38, 46, 51, 55, 60, 21, 34, 37, 47, 50, 56, 59, 61, 35, 36, 48, 49, 57, 58, 62, 63]
class Solution: def numberOfArithmeticSlices(self, A: List[int]) -> int: count, currentSum = 0, 0 for i in range(2, len(A)): if A[i] - A[i - 1] == A[i - 1] - A[i - 2]: count += 1 else: currentSum += ((count + 1) * count) // 2 count = 0 currentSum += ((count + 1) * count) // 2 return currentSum
class Solution: def number_of_arithmetic_slices(self, A: List[int]) -> int: (count, current_sum) = (0, 0) for i in range(2, len(A)): if A[i] - A[i - 1] == A[i - 1] - A[i - 2]: count += 1 else: current_sum += (count + 1) * count // 2 count = 0 current_sum += (count + 1) * count // 2 return currentSum
#Add Key imports here! TRAIN_URL = "https://raw.githubusercontent.com/karkir0003/DSGT-Bootcamp-Material/main/Udemy%20Material/Airline%20Satisfaction/train.csv" def read_train_dataset(): """ This function should read in the train.csv and return it in whatever representation you like """ ###YOUR CODE HERE#### raise NotImplementedError("Did not implement read_train_dataset() function") ##################### def preprocess_dataset(dataset): """ Given the raw dataset read in from your read_train_dataset() function, process the dataset accordingly """ ###YOUR CODE HERE#### raise NotImplementedError("Did not implement read_train_dataset() function") ##################### def train_model(): """ Given your cleaned data, train your Machine Learning model on it and return the model MANDATORY FUNCTION TO IMPLEMENT """ ####YOUR CODE HERE##### raise NotImplementedError("Did not implement the train_model() function") #######################
train_url = 'https://raw.githubusercontent.com/karkir0003/DSGT-Bootcamp-Material/main/Udemy%20Material/Airline%20Satisfaction/train.csv' def read_train_dataset(): """ This function should read in the train.csv and return it in whatever representation you like """ raise not_implemented_error('Did not implement read_train_dataset() function') def preprocess_dataset(dataset): """ Given the raw dataset read in from your read_train_dataset() function, process the dataset accordingly """ raise not_implemented_error('Did not implement read_train_dataset() function') def train_model(): """ Given your cleaned data, train your Machine Learning model on it and return the model MANDATORY FUNCTION TO IMPLEMENT """ raise not_implemented_error('Did not implement the train_model() function')
#!/usr/bin/env python # encoding: utf-8 """ candy.py Created by Shengwei on 2014-07-22. """ # https://oj.leetcode.com/problems/candy/ # tags: hard, array, greedy, logic """ There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements: Each child must have at least one candy. Children with a higher rating get more candies than their neighbors. What is the minimum candies you must give? """ # https://oj.leetcode.com/discuss/76/does-anyone-have-a-better-idea # TODO: try alternative class Solution: # @param ratings, a list of integer # @return an integer def candy(self, ratings): count = [1] for index in xrange(1, len(ratings)): # note: child gets the same rating can have fewer # candies than the neighbors # e.g., rating [1, 2, 2, 3] -> candies [1, 2, 1, 2] if ratings[index] > ratings[index-1]: count.append(count[-1] + 1) else: count.append(1) for index in xrange(-2, -len(ratings)-1, -1): if ratings[index] > ratings[index+1]: count[index] = max(count[index], count[index+1] + 1) return sum(count)
""" candy.py Created by Shengwei on 2014-07-22. """ '\nThere are N children standing in a line. Each child is assigned a rating value.\n\nYou are giving candies to these children subjected to the following requirements:\n\nEach child must have at least one candy.\nChildren with a higher rating get more candies than their neighbors.\nWhat is the minimum candies you must give?\n' class Solution: def candy(self, ratings): count = [1] for index in xrange(1, len(ratings)): if ratings[index] > ratings[index - 1]: count.append(count[-1] + 1) else: count.append(1) for index in xrange(-2, -len(ratings) - 1, -1): if ratings[index] > ratings[index + 1]: count[index] = max(count[index], count[index + 1] + 1) return sum(count)
""" Visualization styles. """ __author__ = "Alexander Urban" __email__ = "aurban@atomistic.net" __date__ = "2021-01-23" __version__ = "0.1" CPK = { 'H': 'white', 'C': 'black', 'N': 'blue', 'O': 'red', 'F': 'green', 'Cl': 'green', 'Br': '0x8b0000', 'I': '0x9400d3', 'He': 'cyan', 'Ne': 'cyan', 'Ar': 'cyan', 'Ce': 'cyan', 'Kr': 'cyan', 'P': 'orange', 'S': 'yellow', 'B': '0xffa07a', 'Li': 'violet', 'Na': 'violet', 'K': 'violet', 'Rb': 'violet', 'Cs': 'violet', 'Fr': 'violet', 'Be': '0x2e8b57', 'Mg': '0x2e8b57', 'Ca': '0x2e8b57', 'Sr': '0x2e8b57', 'Ba': '0x2e8b57', 'Ra': '0x2e8b57', 'Ti': '0x808080', 'Fe': '0xff8c00', 'default': '0xda70d6' } DEFAULT_COLORS = CPK.copy() DEFAULT_COLORS.update({ 'Li': '0x32cd32', 'Sc': '0x6b8e23', 'Ti': '0x48d1cc', 'V': '0xC71585', 'Cr': '0x87cefa', 'Mn': '0x8b008b', 'Co': '0x00008b', 'Ni': 'blue', 'Cu': '0x8b0000', 'Zn': '0xadd8e6', 'Pt': 'cyan', 'Ir': 'violet' }) class AtomStyle(object): def __init__(self, style, colors=DEFAULT_COLORS, **style_specs): """ Arguments: style (str): line, cross, stick, sphere, cartoon, clicksphere colors (dict): element specific colors style_specs: other options for specific styles, such as sphere scales or bond radii. See documentation for AtomStyleSpec """ self.styles = [style] self.colors = colors self.style_specs = [style_specs] def add_style(self, style, **style_specs): """ Add another style to the representation. Arguments: style (str): line, cross, stick, sphere, cartoon, clicksphere style_specs: other options for specific styles, such as sphere scales or bond radii. See documentation for AtomStyleSpec """ self.styles.append(style) self.style_specs.append(style_specs) def apply(self, model, selection=None): """ Apply style to a structure model. Arguments: model (3Dmol.js Model): the structure model selection (dict): AtomSelectionSpec """ if selection is not None: sel = selection else: sel = {} if 'default' in self.colors: default_color = self.colors['default'] else: default_color = None style_dict = {} for i, style in enumerate(self.styles): style_dict[style] = self.style_specs[i] if default_color is not None: style_dict[style]['color'] = default_color model.setStyle(sel, style_dict) # Overwrite default styles with element-specific colors. Woud # be great to make use of mode.setColorByElement() but I could # not figure out how to use this method from Python. for species in self.colors: if species != 'default': species_dict = style_dict.copy() for style in species_dict: species_dict[style].update({'color': self.colors[species]}) model.setStyle({'elem': species, **sel}, species_dict) class StickStyle(AtomStyle): def __init__(self, bond_radius=0.1, **kwargs): super(StickStyle, self).__init__( style='stick', radius=bond_radius, **kwargs) class VanDerWaalsStyle(AtomStyle): def __init__(self, sphere_scale=1.0, **kwargs): super(VanDerWaalsStyle, self).__init__( style='sphere', scale=sphere_scale, **kwargs) class BallAndStickStyle(AtomStyle): def __init__(self, sphere_scale=0.4, bond_radius=0.1, **kwargs): super(BallAndStickStyle, self).__init__( style='sphere', scale=sphere_scale, **kwargs) self.add_style(style="stick", radius=bond_radius, **kwargs) class UnitCellStyle(dict): def __init__(self, linewidth=1.0, linecolor='black', showaxes=False, showlabels=True): style = dict( box=dict(linewidth=linewidth, color=linecolor), ) if not showaxes: style['astyle'] = {'hidden': True} style['bstyle'] = {'hidden': True} style['cstyle'] = {'hidden': True} if showaxes and showlabels: style['alabel'] = "a" style['blabel'] = "b" style['clabel'] = "c" super(UnitCellStyle, self).__init__(**style)
""" Visualization styles. """ __author__ = 'Alexander Urban' __email__ = 'aurban@atomistic.net' __date__ = '2021-01-23' __version__ = '0.1' cpk = {'H': 'white', 'C': 'black', 'N': 'blue', 'O': 'red', 'F': 'green', 'Cl': 'green', 'Br': '0x8b0000', 'I': '0x9400d3', 'He': 'cyan', 'Ne': 'cyan', 'Ar': 'cyan', 'Ce': 'cyan', 'Kr': 'cyan', 'P': 'orange', 'S': 'yellow', 'B': '0xffa07a', 'Li': 'violet', 'Na': 'violet', 'K': 'violet', 'Rb': 'violet', 'Cs': 'violet', 'Fr': 'violet', 'Be': '0x2e8b57', 'Mg': '0x2e8b57', 'Ca': '0x2e8b57', 'Sr': '0x2e8b57', 'Ba': '0x2e8b57', 'Ra': '0x2e8b57', 'Ti': '0x808080', 'Fe': '0xff8c00', 'default': '0xda70d6'} default_colors = CPK.copy() DEFAULT_COLORS.update({'Li': '0x32cd32', 'Sc': '0x6b8e23', 'Ti': '0x48d1cc', 'V': '0xC71585', 'Cr': '0x87cefa', 'Mn': '0x8b008b', 'Co': '0x00008b', 'Ni': 'blue', 'Cu': '0x8b0000', 'Zn': '0xadd8e6', 'Pt': 'cyan', 'Ir': 'violet'}) class Atomstyle(object): def __init__(self, style, colors=DEFAULT_COLORS, **style_specs): """ Arguments: style (str): line, cross, stick, sphere, cartoon, clicksphere colors (dict): element specific colors style_specs: other options for specific styles, such as sphere scales or bond radii. See documentation for AtomStyleSpec """ self.styles = [style] self.colors = colors self.style_specs = [style_specs] def add_style(self, style, **style_specs): """ Add another style to the representation. Arguments: style (str): line, cross, stick, sphere, cartoon, clicksphere style_specs: other options for specific styles, such as sphere scales or bond radii. See documentation for AtomStyleSpec """ self.styles.append(style) self.style_specs.append(style_specs) def apply(self, model, selection=None): """ Apply style to a structure model. Arguments: model (3Dmol.js Model): the structure model selection (dict): AtomSelectionSpec """ if selection is not None: sel = selection else: sel = {} if 'default' in self.colors: default_color = self.colors['default'] else: default_color = None style_dict = {} for (i, style) in enumerate(self.styles): style_dict[style] = self.style_specs[i] if default_color is not None: style_dict[style]['color'] = default_color model.setStyle(sel, style_dict) for species in self.colors: if species != 'default': species_dict = style_dict.copy() for style in species_dict: species_dict[style].update({'color': self.colors[species]}) model.setStyle({'elem': species, **sel}, species_dict) class Stickstyle(AtomStyle): def __init__(self, bond_radius=0.1, **kwargs): super(StickStyle, self).__init__(style='stick', radius=bond_radius, **kwargs) class Vanderwaalsstyle(AtomStyle): def __init__(self, sphere_scale=1.0, **kwargs): super(VanDerWaalsStyle, self).__init__(style='sphere', scale=sphere_scale, **kwargs) class Ballandstickstyle(AtomStyle): def __init__(self, sphere_scale=0.4, bond_radius=0.1, **kwargs): super(BallAndStickStyle, self).__init__(style='sphere', scale=sphere_scale, **kwargs) self.add_style(style='stick', radius=bond_radius, **kwargs) class Unitcellstyle(dict): def __init__(self, linewidth=1.0, linecolor='black', showaxes=False, showlabels=True): style = dict(box=dict(linewidth=linewidth, color=linecolor)) if not showaxes: style['astyle'] = {'hidden': True} style['bstyle'] = {'hidden': True} style['cstyle'] = {'hidden': True} if showaxes and showlabels: style['alabel'] = 'a' style['blabel'] = 'b' style['clabel'] = 'c' super(UnitCellStyle, self).__init__(**style)
app_name = 'tulius.profile' urlpatterns = [ ]
app_name = 'tulius.profile' urlpatterns = []
# # PySNMP MIB module CISCO-WBX-MEETING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-WBX-MEETING-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:04:58 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) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup") Counter64, NotificationType, IpAddress, Integer32, Counter32, Gauge32, MibIdentifier, ModuleIdentity, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, TimeTicks, iso, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "NotificationType", "IpAddress", "Integer32", "Counter32", "Gauge32", "MibIdentifier", "ModuleIdentity", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "TimeTicks", "iso", "ObjectIdentity") AutonomousType, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "AutonomousType", "TextualConvention", "DisplayString") ciscoWebExMeetingMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809)) ciscoWebExMeetingMIB.setRevisions(('2013-05-29 00:00',)) if mibBuilder.loadTexts: ciscoWebExMeetingMIB.setLastUpdated('201305290000Z') if mibBuilder.loadTexts: ciscoWebExMeetingMIB.setOrganization('Cisco Systems Inc.') ciscoWebExMeetingMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 0)) ciscoWebExMeetingMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 1)) ciscoWebExMeetingMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 2)) class CiscoWebExCommSysResource(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4)) namedValues = NamedValues(("cpu", 0), ("memory", 1), ("swap", 2), ("fileDescriptor", 3), ("disk", 4)) class CiscoWebExCommSysResMonitoringStatus(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1)) namedValues = NamedValues(("closed", 0), ("open", 1)) ciscoWebExCommInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 1)) ciscoWebExCommSystemResource = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2)) cwCommSystemVersion = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommSystemVersion.setStatus('current') cwCommSystemObjectID = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 1, 2), AutonomousType()).setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommSystemObjectID.setStatus('current') cwCommCPUUsageObject = ObjectIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1)) if mibBuilder.loadTexts: cwCommCPUUsageObject.setStatus('current') cwCommCPUTotalUsage = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('percent').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUTotalUsage.setStatus('current') cwCommCPUUsageWindow = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 2), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(1, 60))).setUnits('Minute').setMaxAccess("readwrite") if mibBuilder.loadTexts: cwCommCPUUsageWindow.setStatus('current') cwCommCPUTotalNumber = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 3), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUTotalNumber.setStatus('current') cwCommCPUUsageTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4), ) if mibBuilder.loadTexts: cwCommCPUUsageTable.setStatus('current') cwCommCPUUsageEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1), ).setIndexNames((0, "CISCO-WBX-MEETING-MIB", "cwCommCPUIndex")) if mibBuilder.loadTexts: cwCommCPUUsageEntry.setStatus('current') cwCommCPUIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))) if mibBuilder.loadTexts: cwCommCPUIndex.setStatus('current') cwCommCPUName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUName.setStatus('current') cwCommCPUUsage = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 3), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('percent').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUUsage.setStatus('current') cwCommCPUUsageUser = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 4), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUUsageUser.setStatus('current') cwCommCPUUsageNice = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 5), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUUsageNice.setStatus('current') cwCommCPUUsageSystem = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 6), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUUsageSystem.setStatus('current') cwCommCPUUsageIdle = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 7), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUUsageIdle.setStatus('current') cwCommCPUUsageIOWait = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 8), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUUsageIOWait.setStatus('current') cwCommCPUUsageIRQ = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 9), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUUsageIRQ.setStatus('current') cwCommCPUUsageSoftIRQ = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 10), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUUsageSoftIRQ.setStatus('current') cwCommCPUUsageSteal = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 11), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUUsageSteal.setStatus('current') cwCommCPUUsageCapacitySubTotal = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 12), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUUsageCapacitySubTotal.setStatus('current') cwCommCPUMonitoringStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 5), CiscoWebExCommSysResMonitoringStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUMonitoringStatus.setStatus('current') cwCommCPUCapacityTotal = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 6), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KHz').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommCPUCapacityTotal.setStatus('current') cwCommMEMUsageObject = ObjectIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2)) if mibBuilder.loadTexts: cwCommMEMUsageObject.setStatus('current') cwCommMEMUsage = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('percent').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommMEMUsage.setStatus('current') cwCommMEMMonitoringStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2, 2), CiscoWebExCommSysResMonitoringStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommMEMMonitoringStatus.setStatus('current') cwCommMEMTotal = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2, 3), Gauge32()).setUnits('MBytes').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommMEMTotal.setStatus('current') cwCommMEMSwapUsageObject = ObjectIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 3)) if mibBuilder.loadTexts: cwCommMEMSwapUsageObject.setStatus('current') cwCommMEMSwapUsage = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 3, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('percent').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommMEMSwapUsage.setStatus('current') cwCommMEMSwapMonitoringStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 3, 2), CiscoWebExCommSysResMonitoringStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommMEMSwapMonitoringStatus.setStatus('current') cwCommSysResourceNotificationObject = ObjectIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4)) if mibBuilder.loadTexts: cwCommSysResourceNotificationObject.setStatus('current') cwCommNotificationHostAddressType = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 1), InetAddressType()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: cwCommNotificationHostAddressType.setStatus('current') cwCommNotificationHostAddress = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 2), InetAddress()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: cwCommNotificationHostAddress.setStatus('current') cwCommNotificationResName = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 3), CiscoWebExCommSysResource()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: cwCommNotificationResName.setStatus('current') cwCommNotificationResValue = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 4), Unsigned32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: cwCommNotificationResValue.setStatus('current') cwCommNotificationSeqNum = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 5), Counter32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: cwCommNotificationSeqNum.setStatus('current') cwCommDiskUsageObject = ObjectIdentity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5)) if mibBuilder.loadTexts: cwCommDiskUsageObject.setStatus('current') cwCommDiskUsageCount = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommDiskUsageCount.setStatus('current') cwCommDiskUsageTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2), ) if mibBuilder.loadTexts: cwCommDiskUsageTable.setStatus('current') cwCommDiskUsageEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1), ).setIndexNames((0, "CISCO-WBX-MEETING-MIB", "cwCommDiskUsageIndex")) if mibBuilder.loadTexts: cwCommDiskUsageEntry.setStatus('current') cwCommDiskUsageIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))) if mibBuilder.loadTexts: cwCommDiskUsageIndex.setStatus('current') cwCommDiskPartitionName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommDiskPartitionName.setStatus('current') cwCommDiskUsage = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 3), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setUnits('percent').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommDiskUsage.setStatus('current') cwCommDiskTotal = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 4), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setUnits('KB').setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommDiskTotal.setStatus('current') cwCommDiskMonitoringStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 3), CiscoWebExCommSysResMonitoringStatus()).setMaxAccess("readonly") if mibBuilder.loadTexts: cwCommDiskMonitoringStatus.setStatus('current') cwCommSystemResourceUsageNormalEvent = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 809, 0, 1)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddressType"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddress"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResName"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResValue"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationSeqNum")) if mibBuilder.loadTexts: cwCommSystemResourceUsageNormalEvent.setStatus('current') cwCommSystemResourceUsageMinorEvent = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 809, 0, 2)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddressType"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddress"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResName"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResValue"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationSeqNum")) if mibBuilder.loadTexts: cwCommSystemResourceUsageMinorEvent.setStatus('current') cwCommSystemResourceUsageMajorEvent = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 809, 0, 3)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddressType"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddress"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResName"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResValue"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationSeqNum")) if mibBuilder.loadTexts: cwCommSystemResourceUsageMajorEvent.setStatus('current') cwCommMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 1)) cwCommMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 1, 1)).setObjects(("CISCO-WBX-MEETING-MIB", "ciscoWebExCommInfoGroup"), ("CISCO-WBX-MEETING-MIB", "ciscoWebExCommSystemResourceGroup"), ("CISCO-WBX-MEETING-MIB", "ciscoWebExMeetingMIBNotifsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cwCommMIBCompliance = cwCommMIBCompliance.setStatus('current') cwCommMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2)) ciscoWebExCommInfoGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2, 1)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommSystemVersion"), ("CISCO-WBX-MEETING-MIB", "cwCommSystemObjectID")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoWebExCommInfoGroup = ciscoWebExCommInfoGroup.setStatus('current') ciscoWebExCommSystemResourceGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2, 2)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommCPUTotalUsage"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageWindow"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUTotalNumber"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUName"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsage"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUMonitoringStatus"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageUser"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageNice"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageSystem"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageIdle"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageIOWait"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageIRQ"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageSoftIRQ"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageSteal"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUUsageCapacitySubTotal"), ("CISCO-WBX-MEETING-MIB", "cwCommCPUCapacityTotal"), ("CISCO-WBX-MEETING-MIB", "cwCommMEMUsage"), ("CISCO-WBX-MEETING-MIB", "cwCommMEMMonitoringStatus"), ("CISCO-WBX-MEETING-MIB", "cwCommMEMSwapUsage"), ("CISCO-WBX-MEETING-MIB", "cwCommMEMSwapMonitoringStatus"), ("CISCO-WBX-MEETING-MIB", "cwCommMEMTotal"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddressType"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationHostAddress"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResName"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationResValue"), ("CISCO-WBX-MEETING-MIB", "cwCommNotificationSeqNum"), ("CISCO-WBX-MEETING-MIB", "cwCommDiskUsageCount"), ("CISCO-WBX-MEETING-MIB", "cwCommDiskPartitionName"), ("CISCO-WBX-MEETING-MIB", "cwCommDiskUsage"), ("CISCO-WBX-MEETING-MIB", "cwCommDiskTotal"), ("CISCO-WBX-MEETING-MIB", "cwCommDiskMonitoringStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoWebExCommSystemResourceGroup = ciscoWebExCommSystemResourceGroup.setStatus('current') ciscoWebExMeetingMIBNotifsGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2, 3)).setObjects(("CISCO-WBX-MEETING-MIB", "cwCommSystemResourceUsageNormalEvent"), ("CISCO-WBX-MEETING-MIB", "cwCommSystemResourceUsageMinorEvent"), ("CISCO-WBX-MEETING-MIB", "cwCommSystemResourceUsageMajorEvent")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoWebExMeetingMIBNotifsGroup = ciscoWebExMeetingMIBNotifsGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-WBX-MEETING-MIB", CiscoWebExCommSysResource=CiscoWebExCommSysResource, cwCommMEMUsage=cwCommMEMUsage, ciscoWebExCommInfo=ciscoWebExCommInfo, cwCommCPUUsageIRQ=cwCommCPUUsageIRQ, cwCommCPUUsageCapacitySubTotal=cwCommCPUUsageCapacitySubTotal, cwCommNotificationHostAddressType=cwCommNotificationHostAddressType, CiscoWebExCommSysResMonitoringStatus=CiscoWebExCommSysResMonitoringStatus, cwCommSystemResourceUsageNormalEvent=cwCommSystemResourceUsageNormalEvent, cwCommCPUUsageNice=cwCommCPUUsageNice, ciscoWebExMeetingMIBNotifs=ciscoWebExMeetingMIBNotifs, cwCommNotificationResValue=cwCommNotificationResValue, cwCommCPUUsageUser=cwCommCPUUsageUser, cwCommSystemVersion=cwCommSystemVersion, cwCommDiskPartitionName=cwCommDiskPartitionName, cwCommMEMMonitoringStatus=cwCommMEMMonitoringStatus, cwCommCPUUsageIdle=cwCommCPUUsageIdle, cwCommMIBCompliances=cwCommMIBCompliances, cwCommDiskUsageCount=cwCommDiskUsageCount, cwCommCPUCapacityTotal=cwCommCPUCapacityTotal, cwCommMIBGroups=cwCommMIBGroups, cwCommMEMTotal=cwCommMEMTotal, cwCommMEMSwapUsage=cwCommMEMSwapUsage, cwCommSystemResourceUsageMinorEvent=cwCommSystemResourceUsageMinorEvent, cwCommDiskMonitoringStatus=cwCommDiskMonitoringStatus, cwCommMEMSwapUsageObject=cwCommMEMSwapUsageObject, cwCommSystemObjectID=cwCommSystemObjectID, cwCommCPUUsageSystem=cwCommCPUUsageSystem, cwCommCPUUsageWindow=cwCommCPUUsageWindow, cwCommCPUIndex=cwCommCPUIndex, cwCommSystemResourceUsageMajorEvent=cwCommSystemResourceUsageMajorEvent, cwCommCPUUsageSoftIRQ=cwCommCPUUsageSoftIRQ, cwCommDiskUsageTable=cwCommDiskUsageTable, cwCommCPUUsageObject=cwCommCPUUsageObject, cwCommCPUUsageEntry=cwCommCPUUsageEntry, ciscoWebExMeetingMIB=ciscoWebExMeetingMIB, cwCommMEMUsageObject=cwCommMEMUsageObject, cwCommNotificationHostAddress=cwCommNotificationHostAddress, cwCommNotificationResName=cwCommNotificationResName, ciscoWebExMeetingMIBNotifsGroup=ciscoWebExMeetingMIBNotifsGroup, cwCommDiskTotal=cwCommDiskTotal, ciscoWebExCommSystemResourceGroup=ciscoWebExCommSystemResourceGroup, cwCommDiskUsageIndex=cwCommDiskUsageIndex, cwCommDiskUsage=cwCommDiskUsage, ciscoWebExCommSystemResource=ciscoWebExCommSystemResource, cwCommMEMSwapMonitoringStatus=cwCommMEMSwapMonitoringStatus, cwCommCPUMonitoringStatus=cwCommCPUMonitoringStatus, cwCommDiskUsageEntry=cwCommDiskUsageEntry, ciscoWebExMeetingMIBConform=ciscoWebExMeetingMIBConform, cwCommSysResourceNotificationObject=cwCommSysResourceNotificationObject, cwCommCPUTotalNumber=cwCommCPUTotalNumber, cwCommCPUUsageTable=cwCommCPUUsageTable, cwCommCPUUsageIOWait=cwCommCPUUsageIOWait, cwCommMIBCompliance=cwCommMIBCompliance, ciscoWebExCommInfoGroup=ciscoWebExCommInfoGroup, cwCommDiskUsageObject=cwCommDiskUsageObject, cwCommCPUUsageSteal=cwCommCPUUsageSteal, ciscoWebExMeetingMIBObjects=ciscoWebExMeetingMIBObjects, PYSNMP_MODULE_ID=ciscoWebExMeetingMIB, cwCommCPUUsage=cwCommCPUUsage, cwCommNotificationSeqNum=cwCommNotificationSeqNum, cwCommCPUTotalUsage=cwCommCPUTotalUsage, cwCommCPUName=cwCommCPUName)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, value_size_constraint, single_value_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ConstraintsIntersection') (cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt') (inet_address_type, inet_address) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddressType', 'InetAddress') (snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') (module_compliance, object_group, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'ObjectGroup', 'NotificationGroup') (counter64, notification_type, ip_address, integer32, counter32, gauge32, mib_identifier, module_identity, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, unsigned32, time_ticks, iso, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter64', 'NotificationType', 'IpAddress', 'Integer32', 'Counter32', 'Gauge32', 'MibIdentifier', 'ModuleIdentity', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32', 'TimeTicks', 'iso', 'ObjectIdentity') (autonomous_type, textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'AutonomousType', 'TextualConvention', 'DisplayString') cisco_web_ex_meeting_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 809)) ciscoWebExMeetingMIB.setRevisions(('2013-05-29 00:00',)) if mibBuilder.loadTexts: ciscoWebExMeetingMIB.setLastUpdated('201305290000Z') if mibBuilder.loadTexts: ciscoWebExMeetingMIB.setOrganization('Cisco Systems Inc.') cisco_web_ex_meeting_mib_notifs = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 0)) cisco_web_ex_meeting_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 1)) cisco_web_ex_meeting_mib_conform = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 2)) class Ciscowebexcommsysresource(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1, 2, 3, 4)) named_values = named_values(('cpu', 0), ('memory', 1), ('swap', 2), ('fileDescriptor', 3), ('disk', 4)) class Ciscowebexcommsysresmonitoringstatus(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1)) named_values = named_values(('closed', 0), ('open', 1)) cisco_web_ex_comm_info = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 1)) cisco_web_ex_comm_system_resource = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2)) cw_comm_system_version = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 1, 1), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommSystemVersion.setStatus('current') cw_comm_system_object_id = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 1, 2), autonomous_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommSystemObjectID.setStatus('current') cw_comm_cpu_usage_object = object_identity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1)) if mibBuilder.loadTexts: cwCommCPUUsageObject.setStatus('current') cw_comm_cpu_total_usage = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 1), gauge32().subtype(subtypeSpec=value_range_constraint(0, 100))).setUnits('percent').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUTotalUsage.setStatus('current') cw_comm_cpu_usage_window = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 2), gauge32().subtype(subtypeSpec=value_range_constraint(1, 60))).setUnits('Minute').setMaxAccess('readwrite') if mibBuilder.loadTexts: cwCommCPUUsageWindow.setStatus('current') cw_comm_cpu_total_number = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 3), gauge32().subtype(subtypeSpec=value_range_constraint(0, 64))).setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUTotalNumber.setStatus('current') cw_comm_cpu_usage_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4)) if mibBuilder.loadTexts: cwCommCPUUsageTable.setStatus('current') cw_comm_cpu_usage_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1)).setIndexNames((0, 'CISCO-WBX-MEETING-MIB', 'cwCommCPUIndex')) if mibBuilder.loadTexts: cwCommCPUUsageEntry.setStatus('current') cw_comm_cpu_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 128))) if mibBuilder.loadTexts: cwCommCPUIndex.setStatus('current') cw_comm_cpu_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 255))).setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUName.setStatus('current') cw_comm_cpu_usage = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 3), gauge32().subtype(subtypeSpec=value_range_constraint(0, 100))).setUnits('percent').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUUsage.setStatus('current') cw_comm_cpu_usage_user = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 4), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KHz').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUUsageUser.setStatus('current') cw_comm_cpu_usage_nice = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 5), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KHz').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUUsageNice.setStatus('current') cw_comm_cpu_usage_system = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 6), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KHz').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUUsageSystem.setStatus('current') cw_comm_cpu_usage_idle = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 7), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KHz').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUUsageIdle.setStatus('current') cw_comm_cpu_usage_io_wait = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 8), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KHz').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUUsageIOWait.setStatus('current') cw_comm_cpu_usage_irq = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 9), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KHz').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUUsageIRQ.setStatus('current') cw_comm_cpu_usage_soft_irq = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 10), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KHz').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUUsageSoftIRQ.setStatus('current') cw_comm_cpu_usage_steal = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 11), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KHz').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUUsageSteal.setStatus('current') cw_comm_cpu_usage_capacity_sub_total = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 4, 1, 12), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KHz').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUUsageCapacitySubTotal.setStatus('current') cw_comm_cpu_monitoring_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 5), cisco_web_ex_comm_sys_res_monitoring_status()).setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUMonitoringStatus.setStatus('current') cw_comm_cpu_capacity_total = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 1, 6), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KHz').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommCPUCapacityTotal.setStatus('current') cw_comm_mem_usage_object = object_identity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2)) if mibBuilder.loadTexts: cwCommMEMUsageObject.setStatus('current') cw_comm_mem_usage = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2, 1), gauge32().subtype(subtypeSpec=value_range_constraint(0, 100))).setUnits('percent').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommMEMUsage.setStatus('current') cw_comm_mem_monitoring_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2, 2), cisco_web_ex_comm_sys_res_monitoring_status()).setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommMEMMonitoringStatus.setStatus('current') cw_comm_mem_total = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 2, 3), gauge32()).setUnits('MBytes').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommMEMTotal.setStatus('current') cw_comm_mem_swap_usage_object = object_identity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 3)) if mibBuilder.loadTexts: cwCommMEMSwapUsageObject.setStatus('current') cw_comm_mem_swap_usage = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 3, 1), gauge32().subtype(subtypeSpec=value_range_constraint(0, 100))).setUnits('percent').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommMEMSwapUsage.setStatus('current') cw_comm_mem_swap_monitoring_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 3, 2), cisco_web_ex_comm_sys_res_monitoring_status()).setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommMEMSwapMonitoringStatus.setStatus('current') cw_comm_sys_resource_notification_object = object_identity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4)) if mibBuilder.loadTexts: cwCommSysResourceNotificationObject.setStatus('current') cw_comm_notification_host_address_type = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 1), inet_address_type()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: cwCommNotificationHostAddressType.setStatus('current') cw_comm_notification_host_address = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 2), inet_address()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: cwCommNotificationHostAddress.setStatus('current') cw_comm_notification_res_name = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 3), cisco_web_ex_comm_sys_resource()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: cwCommNotificationResName.setStatus('current') cw_comm_notification_res_value = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 4), unsigned32()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: cwCommNotificationResValue.setStatus('current') cw_comm_notification_seq_num = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 4, 5), counter32()).setMaxAccess('accessiblefornotify') if mibBuilder.loadTexts: cwCommNotificationSeqNum.setStatus('current') cw_comm_disk_usage_object = object_identity((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5)) if mibBuilder.loadTexts: cwCommDiskUsageObject.setStatus('current') cw_comm_disk_usage_count = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 1), gauge32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommDiskUsageCount.setStatus('current') cw_comm_disk_usage_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2)) if mibBuilder.loadTexts: cwCommDiskUsageTable.setStatus('current') cw_comm_disk_usage_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1)).setIndexNames((0, 'CISCO-WBX-MEETING-MIB', 'cwCommDiskUsageIndex')) if mibBuilder.loadTexts: cwCommDiskUsageEntry.setStatus('current') cw_comm_disk_usage_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 128))) if mibBuilder.loadTexts: cwCommDiskUsageIndex.setStatus('current') cw_comm_disk_partition_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(0, 128))).setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommDiskPartitionName.setStatus('current') cw_comm_disk_usage = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 3), gauge32().subtype(subtypeSpec=value_range_constraint(0, 100))).setUnits('percent').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommDiskUsage.setStatus('current') cw_comm_disk_total = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 2, 1, 4), gauge32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setUnits('KB').setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommDiskTotal.setStatus('current') cw_comm_disk_monitoring_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 809, 1, 2, 5, 3), cisco_web_ex_comm_sys_res_monitoring_status()).setMaxAccess('readonly') if mibBuilder.loadTexts: cwCommDiskMonitoringStatus.setStatus('current') cw_comm_system_resource_usage_normal_event = notification_type((1, 3, 6, 1, 4, 1, 9, 9, 809, 0, 1)).setObjects(('CISCO-WBX-MEETING-MIB', 'cwCommNotificationHostAddressType'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationHostAddress'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationResName'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationResValue'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationSeqNum')) if mibBuilder.loadTexts: cwCommSystemResourceUsageNormalEvent.setStatus('current') cw_comm_system_resource_usage_minor_event = notification_type((1, 3, 6, 1, 4, 1, 9, 9, 809, 0, 2)).setObjects(('CISCO-WBX-MEETING-MIB', 'cwCommNotificationHostAddressType'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationHostAddress'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationResName'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationResValue'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationSeqNum')) if mibBuilder.loadTexts: cwCommSystemResourceUsageMinorEvent.setStatus('current') cw_comm_system_resource_usage_major_event = notification_type((1, 3, 6, 1, 4, 1, 9, 9, 809, 0, 3)).setObjects(('CISCO-WBX-MEETING-MIB', 'cwCommNotificationHostAddressType'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationHostAddress'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationResName'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationResValue'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationSeqNum')) if mibBuilder.loadTexts: cwCommSystemResourceUsageMajorEvent.setStatus('current') cw_comm_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 1)) cw_comm_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 1, 1)).setObjects(('CISCO-WBX-MEETING-MIB', 'ciscoWebExCommInfoGroup'), ('CISCO-WBX-MEETING-MIB', 'ciscoWebExCommSystemResourceGroup'), ('CISCO-WBX-MEETING-MIB', 'ciscoWebExMeetingMIBNotifsGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cw_comm_mib_compliance = cwCommMIBCompliance.setStatus('current') cw_comm_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2)) cisco_web_ex_comm_info_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2, 1)).setObjects(('CISCO-WBX-MEETING-MIB', 'cwCommSystemVersion'), ('CISCO-WBX-MEETING-MIB', 'cwCommSystemObjectID')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_web_ex_comm_info_group = ciscoWebExCommInfoGroup.setStatus('current') cisco_web_ex_comm_system_resource_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2, 2)).setObjects(('CISCO-WBX-MEETING-MIB', 'cwCommCPUTotalUsage'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsageWindow'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUTotalNumber'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUName'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsage'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUMonitoringStatus'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsageUser'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsageNice'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsageSystem'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsageIdle'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsageIOWait'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsageIRQ'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsageSoftIRQ'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsageSteal'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUUsageCapacitySubTotal'), ('CISCO-WBX-MEETING-MIB', 'cwCommCPUCapacityTotal'), ('CISCO-WBX-MEETING-MIB', 'cwCommMEMUsage'), ('CISCO-WBX-MEETING-MIB', 'cwCommMEMMonitoringStatus'), ('CISCO-WBX-MEETING-MIB', 'cwCommMEMSwapUsage'), ('CISCO-WBX-MEETING-MIB', 'cwCommMEMSwapMonitoringStatus'), ('CISCO-WBX-MEETING-MIB', 'cwCommMEMTotal'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationHostAddressType'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationHostAddress'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationResName'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationResValue'), ('CISCO-WBX-MEETING-MIB', 'cwCommNotificationSeqNum'), ('CISCO-WBX-MEETING-MIB', 'cwCommDiskUsageCount'), ('CISCO-WBX-MEETING-MIB', 'cwCommDiskPartitionName'), ('CISCO-WBX-MEETING-MIB', 'cwCommDiskUsage'), ('CISCO-WBX-MEETING-MIB', 'cwCommDiskTotal'), ('CISCO-WBX-MEETING-MIB', 'cwCommDiskMonitoringStatus')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_web_ex_comm_system_resource_group = ciscoWebExCommSystemResourceGroup.setStatus('current') cisco_web_ex_meeting_mib_notifs_group = notification_group((1, 3, 6, 1, 4, 1, 9, 9, 809, 2, 2, 3)).setObjects(('CISCO-WBX-MEETING-MIB', 'cwCommSystemResourceUsageNormalEvent'), ('CISCO-WBX-MEETING-MIB', 'cwCommSystemResourceUsageMinorEvent'), ('CISCO-WBX-MEETING-MIB', 'cwCommSystemResourceUsageMajorEvent')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_web_ex_meeting_mib_notifs_group = ciscoWebExMeetingMIBNotifsGroup.setStatus('current') mibBuilder.exportSymbols('CISCO-WBX-MEETING-MIB', CiscoWebExCommSysResource=CiscoWebExCommSysResource, cwCommMEMUsage=cwCommMEMUsage, ciscoWebExCommInfo=ciscoWebExCommInfo, cwCommCPUUsageIRQ=cwCommCPUUsageIRQ, cwCommCPUUsageCapacitySubTotal=cwCommCPUUsageCapacitySubTotal, cwCommNotificationHostAddressType=cwCommNotificationHostAddressType, CiscoWebExCommSysResMonitoringStatus=CiscoWebExCommSysResMonitoringStatus, cwCommSystemResourceUsageNormalEvent=cwCommSystemResourceUsageNormalEvent, cwCommCPUUsageNice=cwCommCPUUsageNice, ciscoWebExMeetingMIBNotifs=ciscoWebExMeetingMIBNotifs, cwCommNotificationResValue=cwCommNotificationResValue, cwCommCPUUsageUser=cwCommCPUUsageUser, cwCommSystemVersion=cwCommSystemVersion, cwCommDiskPartitionName=cwCommDiskPartitionName, cwCommMEMMonitoringStatus=cwCommMEMMonitoringStatus, cwCommCPUUsageIdle=cwCommCPUUsageIdle, cwCommMIBCompliances=cwCommMIBCompliances, cwCommDiskUsageCount=cwCommDiskUsageCount, cwCommCPUCapacityTotal=cwCommCPUCapacityTotal, cwCommMIBGroups=cwCommMIBGroups, cwCommMEMTotal=cwCommMEMTotal, cwCommMEMSwapUsage=cwCommMEMSwapUsage, cwCommSystemResourceUsageMinorEvent=cwCommSystemResourceUsageMinorEvent, cwCommDiskMonitoringStatus=cwCommDiskMonitoringStatus, cwCommMEMSwapUsageObject=cwCommMEMSwapUsageObject, cwCommSystemObjectID=cwCommSystemObjectID, cwCommCPUUsageSystem=cwCommCPUUsageSystem, cwCommCPUUsageWindow=cwCommCPUUsageWindow, cwCommCPUIndex=cwCommCPUIndex, cwCommSystemResourceUsageMajorEvent=cwCommSystemResourceUsageMajorEvent, cwCommCPUUsageSoftIRQ=cwCommCPUUsageSoftIRQ, cwCommDiskUsageTable=cwCommDiskUsageTable, cwCommCPUUsageObject=cwCommCPUUsageObject, cwCommCPUUsageEntry=cwCommCPUUsageEntry, ciscoWebExMeetingMIB=ciscoWebExMeetingMIB, cwCommMEMUsageObject=cwCommMEMUsageObject, cwCommNotificationHostAddress=cwCommNotificationHostAddress, cwCommNotificationResName=cwCommNotificationResName, ciscoWebExMeetingMIBNotifsGroup=ciscoWebExMeetingMIBNotifsGroup, cwCommDiskTotal=cwCommDiskTotal, ciscoWebExCommSystemResourceGroup=ciscoWebExCommSystemResourceGroup, cwCommDiskUsageIndex=cwCommDiskUsageIndex, cwCommDiskUsage=cwCommDiskUsage, ciscoWebExCommSystemResource=ciscoWebExCommSystemResource, cwCommMEMSwapMonitoringStatus=cwCommMEMSwapMonitoringStatus, cwCommCPUMonitoringStatus=cwCommCPUMonitoringStatus, cwCommDiskUsageEntry=cwCommDiskUsageEntry, ciscoWebExMeetingMIBConform=ciscoWebExMeetingMIBConform, cwCommSysResourceNotificationObject=cwCommSysResourceNotificationObject, cwCommCPUTotalNumber=cwCommCPUTotalNumber, cwCommCPUUsageTable=cwCommCPUUsageTable, cwCommCPUUsageIOWait=cwCommCPUUsageIOWait, cwCommMIBCompliance=cwCommMIBCompliance, ciscoWebExCommInfoGroup=ciscoWebExCommInfoGroup, cwCommDiskUsageObject=cwCommDiskUsageObject, cwCommCPUUsageSteal=cwCommCPUUsageSteal, ciscoWebExMeetingMIBObjects=ciscoWebExMeetingMIBObjects, PYSNMP_MODULE_ID=ciscoWebExMeetingMIB, cwCommCPUUsage=cwCommCPUUsage, cwCommNotificationSeqNum=cwCommNotificationSeqNum, cwCommCPUTotalUsage=cwCommCPUTotalUsage, cwCommCPUName=cwCommCPUName)
# Column/Label Types NULL = 'null' CATEGORICAL = 'categorical' TEXT = 'text' NUMERICAL = 'numerical' ENTITY = 'entity' # Feature Types ARRAY = 'array' # backend PYTORCH = "pytorch" MXNET = "mxnet"
null = 'null' categorical = 'categorical' text = 'text' numerical = 'numerical' entity = 'entity' array = 'array' pytorch = 'pytorch' mxnet = 'mxnet'
def main(): a,b,c,k = map(int,input().split()) ans = 0 ans += min(a, k) ans -= max(0, k-a-b) print(ans) if __name__ == "__main__": main()
def main(): (a, b, c, k) = map(int, input().split()) ans = 0 ans += min(a, k) ans -= max(0, k - a - b) print(ans) if __name__ == '__main__': main()
def main(): # equilibrate then isolate cold finger info('Equilibrate then isolate coldfinger') close(name="C", description="Bone to Turbo") sleep(1) open(name="B", description="Bone to Diode Laser") sleep(20) close(name="B", description="Bone to Diode Laser")
def main(): info('Equilibrate then isolate coldfinger') close(name='C', description='Bone to Turbo') sleep(1) open(name='B', description='Bone to Diode Laser') sleep(20) close(name='B', description='Bone to Diode Laser')
#!/usr/bin/python3 """ Verifies which numbers from a list of postive integers are even, using filter and lambda. filter() constructs a list of elements which were successfully evaluated, according with the lambda function, upon the elements of an iterable (list, strings, etc.). """ __author__ = "@ivanleoncz" numbers = [1, 2, 3, 4, 5, 6, 7, 8, 11] even = filter(lambda n: n % 2 == 0, numbers) print("Positive Integers: ", numbers) print("Who is even: ", list(even))
""" Verifies which numbers from a list of postive integers are even, using filter and lambda. filter() constructs a list of elements which were successfully evaluated, according with the lambda function, upon the elements of an iterable (list, strings, etc.). """ __author__ = '@ivanleoncz' numbers = [1, 2, 3, 4, 5, 6, 7, 8, 11] even = filter(lambda n: n % 2 == 0, numbers) print('Positive Integers: ', numbers) print('Who is even: ', list(even))
class AmrTypes: dbpedia = { "person": "dbo:Person", "family": "dbo:Agent", "animal": "dbo:Animal", "language": "dbo:Language", "nationality": "dbo:Country", "ethnic-group": "dbo:EthnicGroup", "regional-group": "dbo:EthnicGroup", "religious-group": "dbo:Religious", "political-movement": "dbo:PoliticalParty", "organization": "dbo:Organisation", "company": "dbo:Company", "government-organization": "dbo:Organisation", "military": "dbo:MilitaryPerson", "criminal-organization": "dbo:Criminal", "political-party": "dbo:PoliticalParty", "market-sector": "owl:Thing", "school": "dbo:School", "university": "dbo:University", "research-institute": "dbo:EducationalInstitution", "team": "dbo:SportsTeam", "league": "dbo:SportsSeason", "location": "dbo:Place", "city": "dbo:City", "city-district": "dbo:AdministrativeRegion", "county": "dbo:AdministrativeRegion", "state": "dbo:AdministrativeRegion", "province": "dbo:AdministrativeRegion", "territory": "dbo:Place", "country": "dbo:Country", "local-region": "dbo:AdministrativeRegion", "country-region": "dbo:AdministrativeRegion", "world-region": "dbo:AdministrativeRegion", "continent": "dbo:Continent", "ocean": "dbo:BodyOfWater", "sea": "dbo:Sea", "lake": "dbo:Lake", "river": "dbo:River", "gulf": "dbo:NaturalPlace", "bay": "dbo:NaturalPlace", "strait": "owl:Thing", "peninsula": "dbo:Place", "mountain": "dbo:Mountain", "volcano": "dbo:Volcano", "valley": "dbo:Valley", "canyon": "dbo:Place", "island": "dbo:Island", "desert": "dbo:NaturalPlace", "forest": "dbo:NaturalPlace", "moon": "dbo:Planet", "planet": "dbo:Planet", "star": "dbo:Star", "constellation": "dbo:Constellation", "facility": "dbo:Building", "airport": "dbo:Airport", "station": "dbo:Station", "port": "dbo:Place", "tunnel": "dbo:Tunnel", "bridge": "dbo:Bridge", "road": "dbo:Road", "railway-line": "dbo:RailwayStation", "canal": "dbo:Canal", "building": "dbo:Building", "theater": "dbo:Theatre", "museum": "dbo:Museum", "palace": "dbo:Building", "hotel": "dbo:Hotel", "worship-place": "dbo:Building", "sports-facility": "dbo:Stadium", "market": "dbo:Place", "park": "dbo:Park", "zoo": "dbo:Park", "amusement-park": "dbo:AmusementParkAttraction", "event": "dbo:Event", "incident": "dbo:Event", "natural-disaster": "dbo:NaturalEvent", "earthquake": "dbo:NaturalEvent", "war": "dbo:MilitaryConflict", "conference": "dbo:Event", "game": "dbo:Game", "festival": "dbo:Festival", "product": "owl:Thing", "vehicle": "dbo:MeanOfTransportation", "ship": "dbo:Ship", "aircraft": "dbo:Aircraft", "aircraft-type": "dbo:Aircraft", "spaceship": "dbo:Spacecraft", "car-make": "dbo:Automobile", "work-of-art": "dbo:Work", "picture": "dbo:Work", "music": "dbo:MusicalWork", "show": "dbo:TelevisionEpisode", "broadcast-program": "dbo:TelevisionEpisode", "publication": "dbo:WrittenWork", "book": "dbo:Book", "newspaper": "dbo:Newspaper", "magazine": "dbo:Magazine", "journal": "dbo:WrittenWork", "natural-object": "owl:Thing", "award": "dbo:Award", "law": "owl:Thing", "court-decision": "owl:Thing", "treaty": "owl:Thing", "music-key": "dbo:MusicalWork", "musical-note": "dbo:MusicalWork", "food-dish": "dbo:Food", "writing-script": "dbo:Work", "variable": "owl:Thing", "program": "owl:Thing", "molecular-physical-entity" "small-molecule": "owl:Thing", "protein": "dbo:Protein", "protein-family": "dbo:Protein", "protein-segment": "dbo:Protein", "amino-acid": "owl:Thing", "macro-molecular-complex": "owl:Thing", "enzyme": "dbo:Enzyme", "nucleic-acid": "owl:Thing", "pathway": "owl:Thing", "gene": "dbo:Gene", "dna-sequence": "owl:Thing", "cell": "owl:Thing", "cell-line": "owl:Thing", "species": "dbo:Species", "taxon": "owl:Thing", "disease": "dbo:Disease", "medical-condition": "owl:Thing" }
class Amrtypes: dbpedia = {'person': 'dbo:Person', 'family': 'dbo:Agent', 'animal': 'dbo:Animal', 'language': 'dbo:Language', 'nationality': 'dbo:Country', 'ethnic-group': 'dbo:EthnicGroup', 'regional-group': 'dbo:EthnicGroup', 'religious-group': 'dbo:Religious', 'political-movement': 'dbo:PoliticalParty', 'organization': 'dbo:Organisation', 'company': 'dbo:Company', 'government-organization': 'dbo:Organisation', 'military': 'dbo:MilitaryPerson', 'criminal-organization': 'dbo:Criminal', 'political-party': 'dbo:PoliticalParty', 'market-sector': 'owl:Thing', 'school': 'dbo:School', 'university': 'dbo:University', 'research-institute': 'dbo:EducationalInstitution', 'team': 'dbo:SportsTeam', 'league': 'dbo:SportsSeason', 'location': 'dbo:Place', 'city': 'dbo:City', 'city-district': 'dbo:AdministrativeRegion', 'county': 'dbo:AdministrativeRegion', 'state': 'dbo:AdministrativeRegion', 'province': 'dbo:AdministrativeRegion', 'territory': 'dbo:Place', 'country': 'dbo:Country', 'local-region': 'dbo:AdministrativeRegion', 'country-region': 'dbo:AdministrativeRegion', 'world-region': 'dbo:AdministrativeRegion', 'continent': 'dbo:Continent', 'ocean': 'dbo:BodyOfWater', 'sea': 'dbo:Sea', 'lake': 'dbo:Lake', 'river': 'dbo:River', 'gulf': 'dbo:NaturalPlace', 'bay': 'dbo:NaturalPlace', 'strait': 'owl:Thing', 'peninsula': 'dbo:Place', 'mountain': 'dbo:Mountain', 'volcano': 'dbo:Volcano', 'valley': 'dbo:Valley', 'canyon': 'dbo:Place', 'island': 'dbo:Island', 'desert': 'dbo:NaturalPlace', 'forest': 'dbo:NaturalPlace', 'moon': 'dbo:Planet', 'planet': 'dbo:Planet', 'star': 'dbo:Star', 'constellation': 'dbo:Constellation', 'facility': 'dbo:Building', 'airport': 'dbo:Airport', 'station': 'dbo:Station', 'port': 'dbo:Place', 'tunnel': 'dbo:Tunnel', 'bridge': 'dbo:Bridge', 'road': 'dbo:Road', 'railway-line': 'dbo:RailwayStation', 'canal': 'dbo:Canal', 'building': 'dbo:Building', 'theater': 'dbo:Theatre', 'museum': 'dbo:Museum', 'palace': 'dbo:Building', 'hotel': 'dbo:Hotel', 'worship-place': 'dbo:Building', 'sports-facility': 'dbo:Stadium', 'market': 'dbo:Place', 'park': 'dbo:Park', 'zoo': 'dbo:Park', 'amusement-park': 'dbo:AmusementParkAttraction', 'event': 'dbo:Event', 'incident': 'dbo:Event', 'natural-disaster': 'dbo:NaturalEvent', 'earthquake': 'dbo:NaturalEvent', 'war': 'dbo:MilitaryConflict', 'conference': 'dbo:Event', 'game': 'dbo:Game', 'festival': 'dbo:Festival', 'product': 'owl:Thing', 'vehicle': 'dbo:MeanOfTransportation', 'ship': 'dbo:Ship', 'aircraft': 'dbo:Aircraft', 'aircraft-type': 'dbo:Aircraft', 'spaceship': 'dbo:Spacecraft', 'car-make': 'dbo:Automobile', 'work-of-art': 'dbo:Work', 'picture': 'dbo:Work', 'music': 'dbo:MusicalWork', 'show': 'dbo:TelevisionEpisode', 'broadcast-program': 'dbo:TelevisionEpisode', 'publication': 'dbo:WrittenWork', 'book': 'dbo:Book', 'newspaper': 'dbo:Newspaper', 'magazine': 'dbo:Magazine', 'journal': 'dbo:WrittenWork', 'natural-object': 'owl:Thing', 'award': 'dbo:Award', 'law': 'owl:Thing', 'court-decision': 'owl:Thing', 'treaty': 'owl:Thing', 'music-key': 'dbo:MusicalWork', 'musical-note': 'dbo:MusicalWork', 'food-dish': 'dbo:Food', 'writing-script': 'dbo:Work', 'variable': 'owl:Thing', 'program': 'owl:Thing', 'molecular-physical-entitysmall-molecule': 'owl:Thing', 'protein': 'dbo:Protein', 'protein-family': 'dbo:Protein', 'protein-segment': 'dbo:Protein', 'amino-acid': 'owl:Thing', 'macro-molecular-complex': 'owl:Thing', 'enzyme': 'dbo:Enzyme', 'nucleic-acid': 'owl:Thing', 'pathway': 'owl:Thing', 'gene': 'dbo:Gene', 'dna-sequence': 'owl:Thing', 'cell': 'owl:Thing', 'cell-line': 'owl:Thing', 'species': 'dbo:Species', 'taxon': 'owl:Thing', 'disease': 'dbo:Disease', 'medical-condition': 'owl:Thing'}
students = [] def get_students_titlecase(): students_titlecase = [] for student in students: students_titlecase.append(student['name'].title()) return students_titlecase def print_students_titlecase(): print(get_students_titlecase()) def add_student(name, student_id = 332): student = {'name': name, 'student_id': student_id} students.append(student) def save_file(student): try: f = open('student.txt','a') f.write(student + '\n') f.close() except Exception: print('could not save file') def read_file(): try: f = open('student.txt', 'r') for student in f.readlines(): add_student(student) f.close() except Exception: print('Could not read file') read_file() print_students_titlecase() student_name = input('enter student name: ') student_id = input('enter student id: ') add_student(student_name, student_id) save_file(student_name)
students = [] def get_students_titlecase(): students_titlecase = [] for student in students: students_titlecase.append(student['name'].title()) return students_titlecase def print_students_titlecase(): print(get_students_titlecase()) def add_student(name, student_id=332): student = {'name': name, 'student_id': student_id} students.append(student) def save_file(student): try: f = open('student.txt', 'a') f.write(student + '\n') f.close() except Exception: print('could not save file') def read_file(): try: f = open('student.txt', 'r') for student in f.readlines(): add_student(student) f.close() except Exception: print('Could not read file') read_file() print_students_titlecase() student_name = input('enter student name: ') student_id = input('enter student id: ') add_student(student_name, student_id) save_file(student_name)
# author: @s.gholami # ----------------------------------------------------------------------- # read_matrix_input.py # ----------------------------------------------------------------------- # Accept inputs from console # Populate the list with the inputs to form a matrix def equations_to_matrix() -> list: """ :return: augmented matrix formed from user input (user inputs = linear equations) :rtype: list """ n = int(input("input number of rows ")) m = int(input("input number of columns ")) A = [] for row_space in range(n): print("input row ", row_space + 1) row = input().split() if len(row) == m: row_map = list(map(int, row)) # use map function convert string to integer A.append(row_map) else: print("length must be the column size of A") equations_to_matrix() print(A) return A # main for function call. if __name__ == "__main__": # __name__ = m_determinant equations_to_matrix() else: print("read_matrix_input.py is being imported into another module ")
def equations_to_matrix() -> list: """ :return: augmented matrix formed from user input (user inputs = linear equations) :rtype: list """ n = int(input('input number of rows ')) m = int(input('input number of columns ')) a = [] for row_space in range(n): print('input row ', row_space + 1) row = input().split() if len(row) == m: row_map = list(map(int, row)) A.append(row_map) else: print('length must be the column size of A') equations_to_matrix() print(A) return A if __name__ == '__main__': equations_to_matrix() else: print('read_matrix_input.py is being imported into another module ')
class Solution: def numIslands(self, grid: List[List[str]]) -> int: return num_islands(grid) def num_islands(grid): res = 0 R = len(grid) C = len(grid[0]) def dfs(i, j): if grid[i][j] == '1': grid[i][j] = '0' if i > 0: dfs(i - 1, j) if i < R - 1: dfs(i + 1, j) if j > 0: dfs(i, j - 1) if j < C - 1: dfs(i, j + 1) for i in range(R): for j in range(C): if grid[i][j] == '1': res += 1 dfs(i, j) return res
class Solution: def num_islands(self, grid: List[List[str]]) -> int: return num_islands(grid) def num_islands(grid): res = 0 r = len(grid) c = len(grid[0]) def dfs(i, j): if grid[i][j] == '1': grid[i][j] = '0' if i > 0: dfs(i - 1, j) if i < R - 1: dfs(i + 1, j) if j > 0: dfs(i, j - 1) if j < C - 1: dfs(i, j + 1) for i in range(R): for j in range(C): if grid[i][j] == '1': res += 1 dfs(i, j) return res
sample_rate = 16000 audio_duration = 10 audio_samples = sample_rate * audio_duration audio_duration_flusense = 1 audio_samples_flusense = sample_rate * audio_duration_flusense window_size = 512 overlap = 256 mel_bins = 64 device = 'cuda' num_epochs = 30 gamma = 0.4 patience = 4 step = 10 random_seed = 36851234 split_ratio = 0.2 classes_num = 2 classes_num_flusense = 9 exclude = ['burp', 'vomit', 'hiccup', 'snore', 'wheeze'] valid_labels = ['cough', 'speech', 'etc', 'silence', 'sneeze', 'gasp', 'breathe', 'sniffle', 'throat-clearing'] flusense_weights = [63.38, 2.45, 1.0, 47.78, 13.49, 27.89, 24.93, 0.91, 128.05]
sample_rate = 16000 audio_duration = 10 audio_samples = sample_rate * audio_duration audio_duration_flusense = 1 audio_samples_flusense = sample_rate * audio_duration_flusense window_size = 512 overlap = 256 mel_bins = 64 device = 'cuda' num_epochs = 30 gamma = 0.4 patience = 4 step = 10 random_seed = 36851234 split_ratio = 0.2 classes_num = 2 classes_num_flusense = 9 exclude = ['burp', 'vomit', 'hiccup', 'snore', 'wheeze'] valid_labels = ['cough', 'speech', 'etc', 'silence', 'sneeze', 'gasp', 'breathe', 'sniffle', 'throat-clearing'] flusense_weights = [63.38, 2.45, 1.0, 47.78, 13.49, 27.89, 24.93, 0.91, 128.05]
def minion_game(string): # your code goes here vowels = frozenset('AEIOU') length = len(string) kev_sc = 0 stu_sc = 0 for i in range(length): if string[i] in vowels: kev_sc += length - i else: stu_sc += length - i if kev_sc > stu_sc: print('Kevin', kev_sc) elif kev_sc < stu_sc: print('Stuart', stu_sc) else: print('Draw') if __name__ == '__main__': s = input() minion_game(s)
def minion_game(string): vowels = frozenset('AEIOU') length = len(string) kev_sc = 0 stu_sc = 0 for i in range(length): if string[i] in vowels: kev_sc += length - i else: stu_sc += length - i if kev_sc > stu_sc: print('Kevin', kev_sc) elif kev_sc < stu_sc: print('Stuart', stu_sc) else: print('Draw') if __name__ == '__main__': s = input() minion_game(s)
class Message: def __init__(self, to_channel): self.to_channel = to_channel self.timestamp = "" self.text = "" self.blocks = [] self.is_completed = False def get_message(self): return { "ts": self.timestamp, "channel": self.to_channel, "text": self.text, "blocks": self.blocks, }
class Message: def __init__(self, to_channel): self.to_channel = to_channel self.timestamp = '' self.text = '' self.blocks = [] self.is_completed = False def get_message(self): return {'ts': self.timestamp, 'channel': self.to_channel, 'text': self.text, 'blocks': self.blocks}
productions = { (52, 1): [1,25,47,53,49 ], (53, 2): [54, 57,59,62,64], (53, 3): [54,57,59,62,64], (53, 4): [54,57,59,62,64], (53, 5): [54,57,59,62,64], (53, 6): [54,57,59,62,64], (54, 2): [2,55,47], (54, 3): [0], (54, 4): [0], (54, 5): [0], (54, 6): [0], (55, 25): [25,56], (56, 39): [0], (56, 46): [46,25,56], (56, 47): [0], (57, 3): [3,25,40,26,47,58], (57, 4): [0], (57, 5): [0], (57, 6): [0], (58, 4): [0], (58, 5): [0], (58, 6): [0], (58, 25): [25,40,26,47,58], (59, 4): [4,55,39,61,47,60], (59, 5): [0], (59, 6): [0], (60, 5): [0], (60, 6): [0], (60, 25): [55,39,61,47,60], (61, 8): [8], (61, 9): [9,34,26,50,26,35,10,8], (62, 5): [5,25,63,47,53,47,62], (62, 6): [0], (63, 36): [36,55,39,8,37], (63, 39): [0], (64, 6): [6,66,65,7], (65, 7): [0], (65, 47): [47,66,65], (66, 6): [64], (66, 7): [0], (66, 11): [11,25,69], (66, 12): [12,25 ], (66, 13): [13,77,14,66,71], (66, 15): [0], (66, 16): [16,77,17,66], (66, 18): [18,66,19,77], (66, 19): [0], (66, 20): [20,36,72,74,37], (66, 21): [21,36,75,76,37], (66, 25): [25,67], (66, 27): [27,25,38,77,28,77,17,66], (66, 29): [29,77,10,84,7 ], (66, 47): [0], (67, 34): [68,38,77], (67, 38): [68,38,77], (67, 39): [39,66], (68, 34): [34,77,35], (68, 38): [0], (69, 7): [0], (69, 15): [0], (69, 19): [0], (69, 36): [36,77,70,37], (69, 47): [0], (70, 37): [0], (70, 46): [46,77,70 ], (71, 7): [0], (71, 15): [15,66], (71, 19): [0], (71, 47): [0], (72, 25): [25,73], (73, 7): [0], (73, 10): [0], (73, 14): [0], (73, 15): [0], (73, 17): [0], (73, 19): [0], (73, 22): [0], (73, 23): [0], (73, 28): [0], (73, 30): [0], (73, 31): [0], (73, 32): [0], (73, 33): [0], (73, 34): [34,77,35], (73, 35): [0], (73, 37): [0], (73, 40): [0], (73, 41): [0], (73, 42): [0], (73, 43): [0], (73, 44): [0], (73, 45): [0], (73, 46): [0], (73, 47): [0], (74, 37): [0], (74, 46): [46,72,74], (75, 24): [77], (75, 25): [77], (75, 26): [77], (75, 30): [77], (75, 31): [77], (75, 36): [77], (75, 48): [48], (76, 37): [0], (76, 46): [46,75,76], (77, 24): [79,78 ], (77, 25): [79,78 ], (77, 26): [79,78 ], (77, 30): [79,78 ], (77, 31): [79,78 ], (77, 36): [79,78 ], (78, 7): [0], (78, 10): [0], (78, 14): [0], (78, 15): [0], (78, 17): [0], (78, 19): [0], (78, 28): [0], (78, 35): [0], (78, 37): [0], (78, 40): [40,79], (78, 41): [41,79], (78, 42): [42,79], (78, 43): [43,79], (78, 44): [44,79 ], (78, 45): [45,79], (78, 46): [0], (78, 47): [0], (79, 24): [81,80], (79, 25): [81,80], (79, 26): [81,80], (79, 30): [30,81,80], (79, 31): [31,81,80], (79, 36): [81,80], (80, 7): [0], (80, 10): [0], (80, 14): [0], (80, 15): [0], (80, 17): [0], (80, 19): [0], (80, 22): [22,81,80], (80, 28): [0], (80, 30): [30,81,80], (80, 31): [31,81,80], (80, 35): [0], (80, 37): [0], (80, 40): [0], (80, 41): [0], (80, 42): [0], (80, 43): [0], (80, 44): [0], (80, 45): [0], (80, 46): [0], (80, 47): [0], (81, 24): [83,82 ], (81, 25): [83,82 ], (81, 26): [83,82 ], (81, 36): [83,82 ], (82, 7): [0], (82, 10): [0], (82, 14): [0], (82, 15): [0], (82, 17): [0], (82, 19): [0], (82, 22): [0], (82, 23): [23,83,82], (82, 28): [0], (82, 30): [0], (82, 31): [0], (82, 32): [32,83,82], (82, 33): [33,83,82], (82, 35): [0], (82, 37): [0], (82, 40): [0], (82, 41): [0], (82, 42): [0], (82, 43): [0], (82, 44): [0], (82, 45): [0], (82, 46): [0], (82, 47): [0], (83, 24): [24,83], (83, 25): [72], (83, 26): [26], (83, 36): [36,77,37], (84, 26): [26,86,39,66,85], (85, 7): [0], (85, 47): [47,84], (86, 39): [0], (86, 46): [46,26,86] }
productions = {(52, 1): [1, 25, 47, 53, 49], (53, 2): [54, 57, 59, 62, 64], (53, 3): [54, 57, 59, 62, 64], (53, 4): [54, 57, 59, 62, 64], (53, 5): [54, 57, 59, 62, 64], (53, 6): [54, 57, 59, 62, 64], (54, 2): [2, 55, 47], (54, 3): [0], (54, 4): [0], (54, 5): [0], (54, 6): [0], (55, 25): [25, 56], (56, 39): [0], (56, 46): [46, 25, 56], (56, 47): [0], (57, 3): [3, 25, 40, 26, 47, 58], (57, 4): [0], (57, 5): [0], (57, 6): [0], (58, 4): [0], (58, 5): [0], (58, 6): [0], (58, 25): [25, 40, 26, 47, 58], (59, 4): [4, 55, 39, 61, 47, 60], (59, 5): [0], (59, 6): [0], (60, 5): [0], (60, 6): [0], (60, 25): [55, 39, 61, 47, 60], (61, 8): [8], (61, 9): [9, 34, 26, 50, 26, 35, 10, 8], (62, 5): [5, 25, 63, 47, 53, 47, 62], (62, 6): [0], (63, 36): [36, 55, 39, 8, 37], (63, 39): [0], (64, 6): [6, 66, 65, 7], (65, 7): [0], (65, 47): [47, 66, 65], (66, 6): [64], (66, 7): [0], (66, 11): [11, 25, 69], (66, 12): [12, 25], (66, 13): [13, 77, 14, 66, 71], (66, 15): [0], (66, 16): [16, 77, 17, 66], (66, 18): [18, 66, 19, 77], (66, 19): [0], (66, 20): [20, 36, 72, 74, 37], (66, 21): [21, 36, 75, 76, 37], (66, 25): [25, 67], (66, 27): [27, 25, 38, 77, 28, 77, 17, 66], (66, 29): [29, 77, 10, 84, 7], (66, 47): [0], (67, 34): [68, 38, 77], (67, 38): [68, 38, 77], (67, 39): [39, 66], (68, 34): [34, 77, 35], (68, 38): [0], (69, 7): [0], (69, 15): [0], (69, 19): [0], (69, 36): [36, 77, 70, 37], (69, 47): [0], (70, 37): [0], (70, 46): [46, 77, 70], (71, 7): [0], (71, 15): [15, 66], (71, 19): [0], (71, 47): [0], (72, 25): [25, 73], (73, 7): [0], (73, 10): [0], (73, 14): [0], (73, 15): [0], (73, 17): [0], (73, 19): [0], (73, 22): [0], (73, 23): [0], (73, 28): [0], (73, 30): [0], (73, 31): [0], (73, 32): [0], (73, 33): [0], (73, 34): [34, 77, 35], (73, 35): [0], (73, 37): [0], (73, 40): [0], (73, 41): [0], (73, 42): [0], (73, 43): [0], (73, 44): [0], (73, 45): [0], (73, 46): [0], (73, 47): [0], (74, 37): [0], (74, 46): [46, 72, 74], (75, 24): [77], (75, 25): [77], (75, 26): [77], (75, 30): [77], (75, 31): [77], (75, 36): [77], (75, 48): [48], (76, 37): [0], (76, 46): [46, 75, 76], (77, 24): [79, 78], (77, 25): [79, 78], (77, 26): [79, 78], (77, 30): [79, 78], (77, 31): [79, 78], (77, 36): [79, 78], (78, 7): [0], (78, 10): [0], (78, 14): [0], (78, 15): [0], (78, 17): [0], (78, 19): [0], (78, 28): [0], (78, 35): [0], (78, 37): [0], (78, 40): [40, 79], (78, 41): [41, 79], (78, 42): [42, 79], (78, 43): [43, 79], (78, 44): [44, 79], (78, 45): [45, 79], (78, 46): [0], (78, 47): [0], (79, 24): [81, 80], (79, 25): [81, 80], (79, 26): [81, 80], (79, 30): [30, 81, 80], (79, 31): [31, 81, 80], (79, 36): [81, 80], (80, 7): [0], (80, 10): [0], (80, 14): [0], (80, 15): [0], (80, 17): [0], (80, 19): [0], (80, 22): [22, 81, 80], (80, 28): [0], (80, 30): [30, 81, 80], (80, 31): [31, 81, 80], (80, 35): [0], (80, 37): [0], (80, 40): [0], (80, 41): [0], (80, 42): [0], (80, 43): [0], (80, 44): [0], (80, 45): [0], (80, 46): [0], (80, 47): [0], (81, 24): [83, 82], (81, 25): [83, 82], (81, 26): [83, 82], (81, 36): [83, 82], (82, 7): [0], (82, 10): [0], (82, 14): [0], (82, 15): [0], (82, 17): [0], (82, 19): [0], (82, 22): [0], (82, 23): [23, 83, 82], (82, 28): [0], (82, 30): [0], (82, 31): [0], (82, 32): [32, 83, 82], (82, 33): [33, 83, 82], (82, 35): [0], (82, 37): [0], (82, 40): [0], (82, 41): [0], (82, 42): [0], (82, 43): [0], (82, 44): [0], (82, 45): [0], (82, 46): [0], (82, 47): [0], (83, 24): [24, 83], (83, 25): [72], (83, 26): [26], (83, 36): [36, 77, 37], (84, 26): [26, 86, 39, 66, 85], (85, 7): [0], (85, 47): [47, 84], (86, 39): [0], (86, 46): [46, 26, 86]}
class CDI(): def __init__(self,v3,v2,v3SessionID,v3BaseURL,v2BaseURL,v2icSessionID): print("Created CDI Class") self._v3=v3 self._v2=v2 self._v3SessionID = v3SessionID self._v3BaseURL = v3BaseURL self._v2BaseURL = v2BaseURL self._v2icSessionID = v2icSessionID
class Cdi: def __init__(self, v3, v2, v3SessionID, v3BaseURL, v2BaseURL, v2icSessionID): print('Created CDI Class') self._v3 = v3 self._v2 = v2 self._v3SessionID = v3SessionID self._v3BaseURL = v3BaseURL self._v2BaseURL = v2BaseURL self._v2icSessionID = v2icSessionID
"""List all the extensions.""" names = [ "tourney", "season", "refresh", "misc", ]
"""List all the extensions.""" names = ['tourney', 'season', 'refresh', 'misc']
# ---------------------------------------------------------------------------- # MODES: serial # CLASSES: nightly # # Test Case: multicolor.py # # Tests: Tests setting colors using the multiColor field in some of # our plots. # Plots - Boundary, Contour, FilledBoundary, Subset # Operators - Transform # # Programmer: Brad Whitlock # Date: Wed Apr 6 17:52:12 PST 2005 # # Modifications: # # Mark C. Miller, Thu Jul 13 22:41:56 PDT 2006 # Added test of user-specified material colors # # Mark C. Miller, Wed Jan 20 07:37:11 PST 2010 # Added ability to swtich between Silo's HDF5 and PDB data. # ---------------------------------------------------------------------------- def TestColorDefinitions(testname, colors): s = "" for c in colors: s = s + str(c) + "\n" TestText(testname, s) def TestMultiColor(section, plotAtts, decreasingOpacity): # Get the current colors. m = plotAtts.GetMultiColor() # Test what the image currently looks like. Test("multicolor_%d_00" % section) # Change the colors all at once. We should have red->blue for i in range(len(m)): t = float(i) / float(len(m) - 1) c = int(t * 255.) m[i] = (255-c, 0, c, 255) plotAtts.SetMultiColor(m) SetPlotOptions(plotAtts) Test("multicolor_%d_01" % section) TestColorDefinitions("multicolor_%d_02" % section, plotAtts.GetMultiColor()) # Change the colors another way. We should get green to blue for i in range(len(m)): t = float(i) / float(len(m) - 1) c = int(t * 255.) plotAtts.SetMultiColor(i, 0, 255-c, c) SetPlotOptions(plotAtts) Test("multicolor_%d_03" % section) TestColorDefinitions("multicolor_%d_04" % section, plotAtts.GetMultiColor()) # Change the colors another way. We should get yellow to red but # the redder it gets, the more transparent it should also get. for i in range(len(m)): t = float(i) / float(len(m) - 1) c = int(t * 255.) if decreasingOpacity: plotAtts.SetMultiColor(i, (255, 255-c, 0, 255 - c)) else: plotAtts.SetMultiColor(i, (255, 255-c, 0, c)) SetPlotOptions(plotAtts) Test("multicolor_%d_05" % section) TestColorDefinitions("multicolor_%d_06" % section, plotAtts.GetMultiColor()) def test1(): TestSection("Testing setting of multiColor in Boundary plot") # Set up the plot OpenDatabase(silo_data_path("rect2d.silo")) AddPlot("Boundary", "mat1") b = BoundaryAttributes() b.lineWidth = 4 DrawPlots() # Test the plot TestMultiColor(0, b, 0) # Delete the plots DeleteAllPlots() def test2(): TestSection("Testing setting of multiColor in Contour plot") # Set up the plot OpenDatabase(silo_data_path("noise.silo")) AddPlot("Contour", "hardyglobal") c = ContourAttributes() c.contourNLevels = 20 SetPlotOptions(c) DrawPlots() # Set the view. v = GetView3D() v.viewNormal = (-0.400348, -0.676472, 0.618148) v.focus = (0,0,0) v.viewUp = (-0.916338, 0.300483, -0.264639) v.parallelScale = 17.3205 v.imagePan = (0, 0.0397866) v.imageZoom = 1.07998 SetView3D(v) # Test the plot TestMultiColor(1, c, 0) # Delete the plots DeleteAllPlots() def test3(): TestSection("Testing setting of multiColor in FilledBoundary plot") # Set up the plots. First we want globe so we can see something inside # of the Subset plot to make sure that setting alpha works. OpenDatabase(silo_data_path("globe.silo")) AddPlot("Pseudocolor", "w") p = PseudocolorAttributes() p.legendFlag = 0 p.colorTableName = "xray" SetPlotOptions(p) OpenDatabase(silo_data_path("bigsil.silo")) AddPlot("FilledBoundary", "mat") f = FilledBoundaryAttributes() f.legendFlag = 0 SetPlotOptions(f) # Add an operator to globe to make it small. SetActivePlots(0) AddOperator("Transform", 0) t = TransformAttributes() t.doScale = 1 t.scaleX, t.scaleY, t.scaleZ = 0.04, 0.04, 0.04 t.doTranslate = 1 t.translateX, t.translateY, t.translateZ = 0.5, 0.5, 0.5 SetOperatorOptions(t) SetActivePlots(1) DrawPlots() # Set the view. v = GetView3D() v.viewNormal = (-0.385083, -0.737931, -0.554229) v.focus = (0.5, 0.5, 0.5) v.viewUp = (-0.922871, 0.310902, 0.227267) v.parallelScale = 0.866025 v.imagePan = (-0.0165315, 0.0489375) v.imageZoom = 1.13247 SetView3D(v) # Test the plot TestMultiColor(2, f, 1) # Delete the plots DeleteAllPlots() def test4(): TestSection("Testing setting of multiColor in Subset plot") # Set up the plots. First we want globe so we can see something inside # of the Subset plot to make sure that setting alpha works. OpenDatabase(silo_data_path("globe.silo")) AddPlot("Pseudocolor", "w") p = PseudocolorAttributes() p.legendFlag = 0 p.colorTableName = "xray" SetPlotOptions(p) OpenDatabase(silo_data_path("bigsil.silo")) AddPlot("Subset", "domains") s = SubsetAttributes() s.legendFlag = 0 SetPlotOptions(s) # Add an operator to globe to make it small. SetActivePlots(0) AddOperator("Transform", 0) t = TransformAttributes() t.doScale = 1 t.scaleX, t.scaleY, t.scaleZ = 0.04, 0.04, 0.04 t.doTranslate = 1 t.translateX, t.translateY, t.translateZ = 0.5, 0.5, 0.5 SetOperatorOptions(t) SetActivePlots(1) DrawPlots() # Set the view. v = GetView3D() v.viewNormal = (-0.385083, -0.737931, -0.554229) v.focus = (0.5, 0.5, 0.5) v.viewUp = (-0.922871, 0.310902, 0.227267) v.parallelScale = 0.866025 v.imagePan = (-0.0165315, 0.0489375) v.imageZoom = 1.13247 SetView3D(v) # Test the plot TestMultiColor(3, s, 1) # Delete the plots DeleteAllPlots() def test5(): TestSection("Testing user defined colors for FilledBoundary") ResetView() OpenDatabase(silo_data_path("globe_matcolors.silo")) AddPlot("FilledBoundary","mat1") AddOperator("Slice") DrawPlots() Test("multicolor_matcolors") DeleteAllPlots() def main(): test1() test2() test3() test4() test5() # Run the tests main() Exit()
def test_color_definitions(testname, colors): s = '' for c in colors: s = s + str(c) + '\n' test_text(testname, s) def test_multi_color(section, plotAtts, decreasingOpacity): m = plotAtts.GetMultiColor() test('multicolor_%d_00' % section) for i in range(len(m)): t = float(i) / float(len(m) - 1) c = int(t * 255.0) m[i] = (255 - c, 0, c, 255) plotAtts.SetMultiColor(m) set_plot_options(plotAtts) test('multicolor_%d_01' % section) test_color_definitions('multicolor_%d_02' % section, plotAtts.GetMultiColor()) for i in range(len(m)): t = float(i) / float(len(m) - 1) c = int(t * 255.0) plotAtts.SetMultiColor(i, 0, 255 - c, c) set_plot_options(plotAtts) test('multicolor_%d_03' % section) test_color_definitions('multicolor_%d_04' % section, plotAtts.GetMultiColor()) for i in range(len(m)): t = float(i) / float(len(m) - 1) c = int(t * 255.0) if decreasingOpacity: plotAtts.SetMultiColor(i, (255, 255 - c, 0, 255 - c)) else: plotAtts.SetMultiColor(i, (255, 255 - c, 0, c)) set_plot_options(plotAtts) test('multicolor_%d_05' % section) test_color_definitions('multicolor_%d_06' % section, plotAtts.GetMultiColor()) def test1(): test_section('Testing setting of multiColor in Boundary plot') open_database(silo_data_path('rect2d.silo')) add_plot('Boundary', 'mat1') b = boundary_attributes() b.lineWidth = 4 draw_plots() test_multi_color(0, b, 0) delete_all_plots() def test2(): test_section('Testing setting of multiColor in Contour plot') open_database(silo_data_path('noise.silo')) add_plot('Contour', 'hardyglobal') c = contour_attributes() c.contourNLevels = 20 set_plot_options(c) draw_plots() v = get_view3_d() v.viewNormal = (-0.400348, -0.676472, 0.618148) v.focus = (0, 0, 0) v.viewUp = (-0.916338, 0.300483, -0.264639) v.parallelScale = 17.3205 v.imagePan = (0, 0.0397866) v.imageZoom = 1.07998 set_view3_d(v) test_multi_color(1, c, 0) delete_all_plots() def test3(): test_section('Testing setting of multiColor in FilledBoundary plot') open_database(silo_data_path('globe.silo')) add_plot('Pseudocolor', 'w') p = pseudocolor_attributes() p.legendFlag = 0 p.colorTableName = 'xray' set_plot_options(p) open_database(silo_data_path('bigsil.silo')) add_plot('FilledBoundary', 'mat') f = filled_boundary_attributes() f.legendFlag = 0 set_plot_options(f) set_active_plots(0) add_operator('Transform', 0) t = transform_attributes() t.doScale = 1 (t.scaleX, t.scaleY, t.scaleZ) = (0.04, 0.04, 0.04) t.doTranslate = 1 (t.translateX, t.translateY, t.translateZ) = (0.5, 0.5, 0.5) set_operator_options(t) set_active_plots(1) draw_plots() v = get_view3_d() v.viewNormal = (-0.385083, -0.737931, -0.554229) v.focus = (0.5, 0.5, 0.5) v.viewUp = (-0.922871, 0.310902, 0.227267) v.parallelScale = 0.866025 v.imagePan = (-0.0165315, 0.0489375) v.imageZoom = 1.13247 set_view3_d(v) test_multi_color(2, f, 1) delete_all_plots() def test4(): test_section('Testing setting of multiColor in Subset plot') open_database(silo_data_path('globe.silo')) add_plot('Pseudocolor', 'w') p = pseudocolor_attributes() p.legendFlag = 0 p.colorTableName = 'xray' set_plot_options(p) open_database(silo_data_path('bigsil.silo')) add_plot('Subset', 'domains') s = subset_attributes() s.legendFlag = 0 set_plot_options(s) set_active_plots(0) add_operator('Transform', 0) t = transform_attributes() t.doScale = 1 (t.scaleX, t.scaleY, t.scaleZ) = (0.04, 0.04, 0.04) t.doTranslate = 1 (t.translateX, t.translateY, t.translateZ) = (0.5, 0.5, 0.5) set_operator_options(t) set_active_plots(1) draw_plots() v = get_view3_d() v.viewNormal = (-0.385083, -0.737931, -0.554229) v.focus = (0.5, 0.5, 0.5) v.viewUp = (-0.922871, 0.310902, 0.227267) v.parallelScale = 0.866025 v.imagePan = (-0.0165315, 0.0489375) v.imageZoom = 1.13247 set_view3_d(v) test_multi_color(3, s, 1) delete_all_plots() def test5(): test_section('Testing user defined colors for FilledBoundary') reset_view() open_database(silo_data_path('globe_matcolors.silo')) add_plot('FilledBoundary', 'mat1') add_operator('Slice') draw_plots() test('multicolor_matcolors') delete_all_plots() def main(): test1() test2() test3() test4() test5() main() exit()
def run_tests_count_tokens(config): scenario = sp.test_scenario() admin, [alice, bob] = get_addresses() scenario.h1("Tests count token") #----------------------------------------------------- scenario.h2("Nothing is minted") contract = create_new_contract(config, admin, scenario, []) count = contract.count_tokens() scenario.verify(count == 0) #----------------------------------------------------- scenario.h2("One token is minted") contract = create_new_contract(config, admin, scenario, [alice]) count = contract.count_tokens() scenario.verify(count == 1) #----------------------------------------------------- scenario.h2("Two token are minted") contract = create_new_contract(config, admin, scenario, [alice]) count = contract.count_tokens() scenario.verify(count == 1) contract.mint(1).run(sender=admin, amount=sp.mutez(1000000)) count = contract.count_tokens() scenario.verify(count == 2) #----------------------------------------------------- scenario.h2("Mint fails are not counted as tokens") config.max_editions = 2 contract = create_new_contract(config, admin, scenario, [alice, bob]) count = contract.count_tokens() scenario.verify(count == 2) contract.mint(1).run(sender=admin, amount=sp.mutez(1000000), valid=False) count = contract.count_tokens() scenario.verify(count == 2)
def run_tests_count_tokens(config): scenario = sp.test_scenario() (admin, [alice, bob]) = get_addresses() scenario.h1('Tests count token') scenario.h2('Nothing is minted') contract = create_new_contract(config, admin, scenario, []) count = contract.count_tokens() scenario.verify(count == 0) scenario.h2('One token is minted') contract = create_new_contract(config, admin, scenario, [alice]) count = contract.count_tokens() scenario.verify(count == 1) scenario.h2('Two token are minted') contract = create_new_contract(config, admin, scenario, [alice]) count = contract.count_tokens() scenario.verify(count == 1) contract.mint(1).run(sender=admin, amount=sp.mutez(1000000)) count = contract.count_tokens() scenario.verify(count == 2) scenario.h2('Mint fails are not counted as tokens') config.max_editions = 2 contract = create_new_contract(config, admin, scenario, [alice, bob]) count = contract.count_tokens() scenario.verify(count == 2) contract.mint(1).run(sender=admin, amount=sp.mutez(1000000), valid=False) count = contract.count_tokens() scenario.verify(count == 2)
gal_sgd = ['HP0370', 'HP0950', 'HP0371', 'HP0557', 'HP0202', 'HP0587', 'HP0618', 'HP1112', 'HP0255', 'HP0859', 'HP0089', 'HP0106', 'HP0738', 'HP0942', 'HP0976', 'HP1483', 'HP1280', 'HP1281', 'HP1282', 'HP0598', 'HP1505', 'HP0422', 'HP1399', 'HP1017', 'HP1189', 'HP0723', 'HP0034', 'HP1084', 'HP1229', 'HP0672', 'HP1406', 'HP1376', 'HP0558', 'HP0195', 'HP0561', 'HP1237', 'HP0919', 'HP1443', 'HP0291', 'HP0663', 'HP0349', 'HP0107', 'HP0290', 'HP0566', 'HP0215', 'HP0804', 'HP0029', 'HP0134', 'HP0321', 'HP0510', 'HP1013', 'HP1545', 'HP1510', 'HP1011', 'HP0266', 'HP0581', 'HP1232', 'HP1038', 'HP0283', 'HP0929', 'HP0400', 'HP1228', 'HP0831', 'HP1474', 'HP0216', 'HP0354', 'HP0642', 'HP1161', 'HP1087', 'HP0577', 'HP0683', 'HP0961', 'HP1532', 'HP0045', 'HP0183', 'HP0512', 'HP1491', 'HP0549', 'HP0509', 'HP0044', 'HP0858', 'HP0860', 'HP0409', 'HP0928', 'HP0802', 'HP1158', 'HP0822', 'HP1050', 'HP1279', 'HP1468', 'HP1275', 'HP0829', 'HP0230', 'HP0003', 'HP0867', 'HP0279', 'HP0043', 'HP0090', 'HP0086', 'HP0625', 'HP1020', 'HP0197', 'HP0957', 'HP1058', 'HP1394', 'HP0329', 'HP0198', 'HP1337', 'HP1355', 'HP0240', 'HP0005', 'HP0588', 'HP0590', 'HP0589', 'HP0591', 'HP1257', 'HP0293', 'HP0006', 'HP0493', 'HP1348', 'HP1111', 'HP1109', 'HP1108', 'HP1110', 'HP0075', 'HP0096', 'HP0397', 'HP0737', 'HP1016', 'HP0620', 'HP1380', 'HP1218', 'HP0742', 'HP0401', 'HP1357', 'HP0736', 'HP0652', 'HP1071', 'HP1475', 'HP1356', 'HP0002', 'HP1574', 'HP0105', 'HP0680', 'HP0364', 'HP0574', 'HP0857', 'HP0212', 'HP0624', 'HP1210', 'HP1249', 'HP0157', 'HP0832', 'HP0626', 'HP0098', 'HP1088', 'HP1533', 'HP0194', 'HP1458', 'HP0825', 'HP0824', 'HP1164', 'HP1277', 'HP1278', 'HP0196', 'HP1494', 'HP1375', 'HP0648', 'HP1155', 'HP0494', 'HP0623', 'HP1418', 'HP0740', 'HP1052', 'HP0777'] glu_sgd = ['HP0370', 'HP0950', 'HP0371', 'HP0557', 'HP0202', 'HP0587', 'HP0618', 'HP1112', 'HP0255', 'HP0859', 'HP0089', 'HP0106', 'HP0738', 'HP0942', 'HP0976', 'HP1483', 'HP1280', 'HP1281', 'HP1282', 'HP0598', 'HP1505', 'HP0422', 'HP1399', 'HP1017', 'HP1189', 'HP0723', 'HP0034', 'HP1084', 'HP1229', 'HP0672', 'HP1406', 'HP1376', 'HP0558', 'HP0195', 'HP0561', 'HP1237', 'HP0919', 'HP1443', 'HP0291', 'HP0663', 'HP0349', 'HP0107', 'HP0290', 'HP0566', 'HP0215', 'HP0804', 'HP0029', 'HP0134', 'HP0321', 'HP0510', 'HP1013', 'HP1545', 'HP1510', 'HP1011', 'HP0266', 'HP0581', 'HP1232', 'HP1038', 'HP0283', 'HP0929', 'HP0400', 'HP1228', 'HP0831', 'HP1474', 'HP0216', 'HP0354', 'HP0642', 'HP1161', 'HP1087', 'HP0577', 'HP0683', 'HP0961', 'HP0646', 'HP1532', 'HP0045', 'HP0183', 'HP0512', 'HP1491', 'HP0549', 'HP0509', 'HP0044', 'HP0858', 'HP0860', 'HP0409', 'HP0928', 'HP0802', 'HP1158', 'HP0822', 'HP1050', 'HP1279', 'HP1468', 'HP1275', 'HP0829', 'HP0230', 'HP0003', 'HP0867', 'HP0279', 'HP0043', 'HP0090', 'HP0086', 'HP0625', 'HP1020', 'HP0197', 'HP0957', 'HP1058', 'HP1394', 'HP0329', 'HP0198', 'HP1337', 'HP1355', 'HP0240', 'HP0005', 'HP0588', 'HP0590', 'HP0589', 'HP0591', 'HP1257', 'HP0293', 'HP0006', 'HP0493', 'HP1348', 'HP1111', 'HP1109', 'HP1108', 'HP1110', 'HP0075', 'HP0096', 'HP0397', 'HP0737', 'HP1016', 'HP0620', 'HP1380', 'HP1218', 'HP0742', 'HP0401', 'HP1357', 'HP0736', 'HP0652', 'HP1071', 'HP1475', 'HP1356', 'HP0002', 'HP1574', 'HP0105', 'HP0680', 'HP0364', 'HP0574', 'HP0857', 'HP0212', 'HP0624', 'HP1210', 'HP1249', 'HP0157', 'HP0832', 'HP0626', 'HP0098', 'HP1088', 'HP1533', 'HP0194', 'HP1458', 'HP0825', 'HP0824', 'HP1164', 'HP1277', 'HP1278', 'HP0196', 'HP1494', 'HP1375', 'HP0648', 'HP1155', 'HP0494', 'HP0623', 'HP1418', 'HP0360', 'HP0740', 'HP1052', 'HP0777'] sgd = ['HP0370', 'HP0950', 'HP0371', 'HP0557', 'HP0202', 'HP0587', 'HP0618', 'HP1112', 'HP0255', 'HP0859', 'HP0089', 'HP0106', 'HP0738', 'HP0942', 'HP0976', 'HP1483', 'HP1280', 'HP1281', 'HP1282', 'HP0598', 'HP1505', 'HP0422', 'HP1399', 'HP1017', 'HP1189', 'HP0723', 'HP0034', 'HP1084', 'HP1229', 'HP0672', 'HP1539', 'HP1227', 'HP1538', 'HP1540', 'HP1406', 'HP1376', 'HP0558', 'HP0195', 'HP0561', 'HP1237', 'HP0919', 'HP1443', 'HP0291', 'HP0663', 'HP0349', 'HP0147', 'HP0144', 'HP0145', 'HP0146', 'HP0107', 'HP0290', 'HP0566', 'HP0215', 'HP0804', 'HP0029', 'HP0134', 'HP0321', 'HP0510', 'HP1013', 'HP1545', 'HP1510', 'HP1011', 'HP0266', 'HP0581', 'HP1232', 'HP1038', 'HP0283', 'HP0929', 'HP0400', 'HP1228', 'HP0831', 'HP1474', 'HP0216', 'HP0354', 'HP0154', 'HP0176', 'HP1385', 'HP0642', 'HP1161', 'HP1087', 'HP0577', 'HP0683', 'HP0961', 'HP0646', 'HP1532', 'HP0045', 'HP0183', 'HP0512', 'HP1491', 'HP0549', 'HP0509', 'HP0044', 'HP0858', 'HP0860', 'HP0409', 'HP0928', 'HP0802', 'HP1158', 'HP0822', 'HP1050', 'HP1279', 'HP1468', 'HP1275', 'HP0829', 'HP0230', 'HP0003', 'HP0867', 'HP0279', 'HP0043', 'HP0090', 'HP0086', 'HP0625', 'HP1020', 'HP0197', 'HP0957', 'HP1058', 'HP1394', 'HP0329', 'HP0198', 'HP1337', 'HP1355', 'HP0240', 'HP0005', 'HP0588', 'HP0590', 'HP0589', 'HP0591', 'HP1257', 'HP0293', 'HP0006', 'HP0493', 'HP1348', 'HP1111', 'HP1109', 'HP1108', 'HP1110', 'HP0075', 'HP0096', 'HP0397', 'HP1166', 'HP1345', 'HP0974', 'HP0737', 'HP1016', 'HP0620', 'HP1380', 'HP0121', 'HP1218', 'HP0742', 'HP0401', 'HP1357', 'HP0736', 'HP0652', 'HP1071', 'HP1475', 'HP1356', 'HP0002', 'HP1574', 'HP0105', 'HP0680', 'HP0364', 'HP0574', 'HP0857', 'HP0212', 'HP0624', 'HP1210', 'HP1249', 'HP0157', 'HP0832', 'HP0389', 'HP0626', 'HP0098', 'HP1088', 'HP1533', 'HP0194', 'HP1458', 'HP0825', 'HP0824', 'HP1164', 'HP1277', 'HP1278', 'HP0196', 'HP1494', 'HP1375', 'HP0648', 'HP1155', 'HP0494', 'HP0623', 'HP1418', 'HP0360', 'HP0740', 'HP1052', 'HP0777'] m = len(glu_sgd) n = len(gal_sgd) w = len(sgd) # Glucose and galactose comparision print("\nGlucose and galactose comparision mismatch") i = j = 0 while i < m and j < n: if glu_sgd[i] != gal_sgd[j]: print(glu_sgd[i]) i += 1 else: i += 1 j += 1 # WT and Glucose comparision print("\nWT and Glucose comparision mismatch") i = j = 0 while i < w and j < m: if sgd[i] != glu_sgd[j]: print(glu_sgd[i]) i += 1 else: i += 1 j += 1
gal_sgd = ['HP0370', 'HP0950', 'HP0371', 'HP0557', 'HP0202', 'HP0587', 'HP0618', 'HP1112', 'HP0255', 'HP0859', 'HP0089', 'HP0106', 'HP0738', 'HP0942', 'HP0976', 'HP1483', 'HP1280', 'HP1281', 'HP1282', 'HP0598', 'HP1505', 'HP0422', 'HP1399', 'HP1017', 'HP1189', 'HP0723', 'HP0034', 'HP1084', 'HP1229', 'HP0672', 'HP1406', 'HP1376', 'HP0558', 'HP0195', 'HP0561', 'HP1237', 'HP0919', 'HP1443', 'HP0291', 'HP0663', 'HP0349', 'HP0107', 'HP0290', 'HP0566', 'HP0215', 'HP0804', 'HP0029', 'HP0134', 'HP0321', 'HP0510', 'HP1013', 'HP1545', 'HP1510', 'HP1011', 'HP0266', 'HP0581', 'HP1232', 'HP1038', 'HP0283', 'HP0929', 'HP0400', 'HP1228', 'HP0831', 'HP1474', 'HP0216', 'HP0354', 'HP0642', 'HP1161', 'HP1087', 'HP0577', 'HP0683', 'HP0961', 'HP1532', 'HP0045', 'HP0183', 'HP0512', 'HP1491', 'HP0549', 'HP0509', 'HP0044', 'HP0858', 'HP0860', 'HP0409', 'HP0928', 'HP0802', 'HP1158', 'HP0822', 'HP1050', 'HP1279', 'HP1468', 'HP1275', 'HP0829', 'HP0230', 'HP0003', 'HP0867', 'HP0279', 'HP0043', 'HP0090', 'HP0086', 'HP0625', 'HP1020', 'HP0197', 'HP0957', 'HP1058', 'HP1394', 'HP0329', 'HP0198', 'HP1337', 'HP1355', 'HP0240', 'HP0005', 'HP0588', 'HP0590', 'HP0589', 'HP0591', 'HP1257', 'HP0293', 'HP0006', 'HP0493', 'HP1348', 'HP1111', 'HP1109', 'HP1108', 'HP1110', 'HP0075', 'HP0096', 'HP0397', 'HP0737', 'HP1016', 'HP0620', 'HP1380', 'HP1218', 'HP0742', 'HP0401', 'HP1357', 'HP0736', 'HP0652', 'HP1071', 'HP1475', 'HP1356', 'HP0002', 'HP1574', 'HP0105', 'HP0680', 'HP0364', 'HP0574', 'HP0857', 'HP0212', 'HP0624', 'HP1210', 'HP1249', 'HP0157', 'HP0832', 'HP0626', 'HP0098', 'HP1088', 'HP1533', 'HP0194', 'HP1458', 'HP0825', 'HP0824', 'HP1164', 'HP1277', 'HP1278', 'HP0196', 'HP1494', 'HP1375', 'HP0648', 'HP1155', 'HP0494', 'HP0623', 'HP1418', 'HP0740', 'HP1052', 'HP0777'] glu_sgd = ['HP0370', 'HP0950', 'HP0371', 'HP0557', 'HP0202', 'HP0587', 'HP0618', 'HP1112', 'HP0255', 'HP0859', 'HP0089', 'HP0106', 'HP0738', 'HP0942', 'HP0976', 'HP1483', 'HP1280', 'HP1281', 'HP1282', 'HP0598', 'HP1505', 'HP0422', 'HP1399', 'HP1017', 'HP1189', 'HP0723', 'HP0034', 'HP1084', 'HP1229', 'HP0672', 'HP1406', 'HP1376', 'HP0558', 'HP0195', 'HP0561', 'HP1237', 'HP0919', 'HP1443', 'HP0291', 'HP0663', 'HP0349', 'HP0107', 'HP0290', 'HP0566', 'HP0215', 'HP0804', 'HP0029', 'HP0134', 'HP0321', 'HP0510', 'HP1013', 'HP1545', 'HP1510', 'HP1011', 'HP0266', 'HP0581', 'HP1232', 'HP1038', 'HP0283', 'HP0929', 'HP0400', 'HP1228', 'HP0831', 'HP1474', 'HP0216', 'HP0354', 'HP0642', 'HP1161', 'HP1087', 'HP0577', 'HP0683', 'HP0961', 'HP0646', 'HP1532', 'HP0045', 'HP0183', 'HP0512', 'HP1491', 'HP0549', 'HP0509', 'HP0044', 'HP0858', 'HP0860', 'HP0409', 'HP0928', 'HP0802', 'HP1158', 'HP0822', 'HP1050', 'HP1279', 'HP1468', 'HP1275', 'HP0829', 'HP0230', 'HP0003', 'HP0867', 'HP0279', 'HP0043', 'HP0090', 'HP0086', 'HP0625', 'HP1020', 'HP0197', 'HP0957', 'HP1058', 'HP1394', 'HP0329', 'HP0198', 'HP1337', 'HP1355', 'HP0240', 'HP0005', 'HP0588', 'HP0590', 'HP0589', 'HP0591', 'HP1257', 'HP0293', 'HP0006', 'HP0493', 'HP1348', 'HP1111', 'HP1109', 'HP1108', 'HP1110', 'HP0075', 'HP0096', 'HP0397', 'HP0737', 'HP1016', 'HP0620', 'HP1380', 'HP1218', 'HP0742', 'HP0401', 'HP1357', 'HP0736', 'HP0652', 'HP1071', 'HP1475', 'HP1356', 'HP0002', 'HP1574', 'HP0105', 'HP0680', 'HP0364', 'HP0574', 'HP0857', 'HP0212', 'HP0624', 'HP1210', 'HP1249', 'HP0157', 'HP0832', 'HP0626', 'HP0098', 'HP1088', 'HP1533', 'HP0194', 'HP1458', 'HP0825', 'HP0824', 'HP1164', 'HP1277', 'HP1278', 'HP0196', 'HP1494', 'HP1375', 'HP0648', 'HP1155', 'HP0494', 'HP0623', 'HP1418', 'HP0360', 'HP0740', 'HP1052', 'HP0777'] sgd = ['HP0370', 'HP0950', 'HP0371', 'HP0557', 'HP0202', 'HP0587', 'HP0618', 'HP1112', 'HP0255', 'HP0859', 'HP0089', 'HP0106', 'HP0738', 'HP0942', 'HP0976', 'HP1483', 'HP1280', 'HP1281', 'HP1282', 'HP0598', 'HP1505', 'HP0422', 'HP1399', 'HP1017', 'HP1189', 'HP0723', 'HP0034', 'HP1084', 'HP1229', 'HP0672', 'HP1539', 'HP1227', 'HP1538', 'HP1540', 'HP1406', 'HP1376', 'HP0558', 'HP0195', 'HP0561', 'HP1237', 'HP0919', 'HP1443', 'HP0291', 'HP0663', 'HP0349', 'HP0147', 'HP0144', 'HP0145', 'HP0146', 'HP0107', 'HP0290', 'HP0566', 'HP0215', 'HP0804', 'HP0029', 'HP0134', 'HP0321', 'HP0510', 'HP1013', 'HP1545', 'HP1510', 'HP1011', 'HP0266', 'HP0581', 'HP1232', 'HP1038', 'HP0283', 'HP0929', 'HP0400', 'HP1228', 'HP0831', 'HP1474', 'HP0216', 'HP0354', 'HP0154', 'HP0176', 'HP1385', 'HP0642', 'HP1161', 'HP1087', 'HP0577', 'HP0683', 'HP0961', 'HP0646', 'HP1532', 'HP0045', 'HP0183', 'HP0512', 'HP1491', 'HP0549', 'HP0509', 'HP0044', 'HP0858', 'HP0860', 'HP0409', 'HP0928', 'HP0802', 'HP1158', 'HP0822', 'HP1050', 'HP1279', 'HP1468', 'HP1275', 'HP0829', 'HP0230', 'HP0003', 'HP0867', 'HP0279', 'HP0043', 'HP0090', 'HP0086', 'HP0625', 'HP1020', 'HP0197', 'HP0957', 'HP1058', 'HP1394', 'HP0329', 'HP0198', 'HP1337', 'HP1355', 'HP0240', 'HP0005', 'HP0588', 'HP0590', 'HP0589', 'HP0591', 'HP1257', 'HP0293', 'HP0006', 'HP0493', 'HP1348', 'HP1111', 'HP1109', 'HP1108', 'HP1110', 'HP0075', 'HP0096', 'HP0397', 'HP1166', 'HP1345', 'HP0974', 'HP0737', 'HP1016', 'HP0620', 'HP1380', 'HP0121', 'HP1218', 'HP0742', 'HP0401', 'HP1357', 'HP0736', 'HP0652', 'HP1071', 'HP1475', 'HP1356', 'HP0002', 'HP1574', 'HP0105', 'HP0680', 'HP0364', 'HP0574', 'HP0857', 'HP0212', 'HP0624', 'HP1210', 'HP1249', 'HP0157', 'HP0832', 'HP0389', 'HP0626', 'HP0098', 'HP1088', 'HP1533', 'HP0194', 'HP1458', 'HP0825', 'HP0824', 'HP1164', 'HP1277', 'HP1278', 'HP0196', 'HP1494', 'HP1375', 'HP0648', 'HP1155', 'HP0494', 'HP0623', 'HP1418', 'HP0360', 'HP0740', 'HP1052', 'HP0777'] m = len(glu_sgd) n = len(gal_sgd) w = len(sgd) print('\nGlucose and galactose comparision mismatch') i = j = 0 while i < m and j < n: if glu_sgd[i] != gal_sgd[j]: print(glu_sgd[i]) i += 1 else: i += 1 j += 1 print('\nWT and Glucose comparision mismatch') i = j = 0 while i < w and j < m: if sgd[i] != glu_sgd[j]: print(glu_sgd[i]) i += 1 else: i += 1 j += 1
# This is not for real use! # This is normally generated by the build and install so should not be used for anything or filled in with real values. # File generated from /opt/config # GLOBAL_INJECTED_AAI1_IP_ADDR = "10.0.1.1" GLOBAL_INJECTED_AAI2_IP_ADDR = "10.0.1.2" GLOBAL_INJECTED_APPC_IP_ADDR = "10.0.2.1" GLOBAL_INJECTED_ARTIFACTS_VERSION = "1.2.0" GLOBAL_INJECTED_CLAMP_IP_ADDR = "10.0.12.1" GLOBAL_INJECTED_CLOUD_ENV = "openstack" GLOBAL_INJECTED_DCAE_IP_ADDR = "10.0.4.1" GLOBAL_INJECTED_DNS_IP_ADDR = "10.0.100.1" GLOBAL_INJECTED_DOCKER_VERSION = "1.1-STAGING-latest" GLOBAL_INJECTED_EXTERNAL_DNS = "8.8.8.8" GLOBAL_INJECTED_GERRIT_BRANCH = "amsterdam" GLOBAL_INJECTED_KEYSTONE = "http://10.12.25.2:5000" GLOBAL_INJECTED_MR_IP_ADDR = "10.0.11.1" GLOBAL_INJECTED_MSO_IP_ADDR = "10.0.5.1" GLOBAL_INJECTED_NETWORK = "oam_onap_wbaL" GLOBAL_INJECTED_NEXUS_DOCKER_REPO = "10.12.5.2:5000" GLOBAL_INJECTED_NEXUS_PASSWORD = "anonymous" GLOBAL_INJECTED_NEXUS_REPO = "https://nexus.onap.org/content/sites/raw" GLOBAL_INJECTED_NEXUS_USERNAME = "username" GLOBAL_INJECTED_OPENO_IP_ADDR = "10.0.14.1" GLOBAL_INJECTED_OPENSTACK_PASSWORD = "password" GLOBAL_INJECTED_OPENSTACK_TENANT_ID = "000007144004bacac1e39ff23105fff" GLOBAL_INJECTED_OPENSTACK_USERNAME = "username" GLOBAL_INJECTED_POLICY_IP_ADDR = "10.0.6.1" GLOBAL_INJECTED_PORTAL_IP_ADDR = "10.0.9.1" GLOBAL_INJECTED_PUBLIC_NET_ID = "971040b2-7059-49dc-b220-4fab50cb2ad4" GLOBAL_INJECTED_REGION = "RegionOne" GLOBAL_INJECTED_REMOTE_REPO = "http://gerrit.onap.org/r/testsuite/properties.git" GLOBAL_INJECTED_SCRIPT_VERSION = "1.1.1" GLOBAL_INJECTED_SDC_IP_ADDR = "10.0.3.1" GLOBAL_INJECTED_SDNC_IP_ADDR = "10.0.7.1" GLOBAL_INJECTED_SO_IP_ADDR = "10.0.5.1" GLOBAL_INJECTED_VID_IP_ADDR = "10.0.8.1" GLOBAL_INJECTED_VM_FLAVOR = "m1.medium" GLOBAL_INJECTED_UBUNTU_1404_IMAGE = "ubuntu-14-04-cloud-amd64" GLOBAL_INJECTED_UBUNTU_1604_IMAGE = "ubuntu-16-04-cloud-amd64" GLOBAL_INJECTED_PROPERTIES={ "GLOBAL_INJECTED_AAI1_IP_ADDR" : "10.0.1.1", "GLOBAL_INJECTED_AAI2_IP_ADDR" : "10.0.1.2", "GLOBAL_INJECTED_APPC_IP_ADDR" : "10.0.2.1", "GLOBAL_INJECTED_ARTIFACTS_VERSION" : "1.2.0", "GLOBAL_INJECTED_CLAMP_IP_ADDR" : "10.0.12.1", "GLOBAL_INJECTED_CLOUD_ENV" : "openstack", "GLOBAL_INJECTED_DCAE_IP_ADDR" : "10.0.4.1", "GLOBAL_INJECTED_DNS_IP_ADDR" : "10.0.100.1", "GLOBAL_INJECTED_DOCKER_VERSION" : "1.1-STAGING-latest", "GLOBAL_INJECTED_EXTERNAL_DNS" : "8.8.8.8", "GLOBAL_INJECTED_GERRIT_BRANCH" : "amsterdam", "GLOBAL_INJECTED_KEYSTONE" : "http://10.12.25.2:5000", "GLOBAL_INJECTED_MR_IP_ADDR" : "10.0.11.1", "GLOBAL_INJECTED_MSO_IP_ADDR" : "10.0.5.1", "GLOBAL_INJECTED_NETWORK" : "oam_onap_wbaL", "GLOBAL_INJECTED_NEXUS_DOCKER_REPO" : "10.12.5.2:5000", "GLOBAL_INJECTED_NEXUS_PASSWORD" : "username", "GLOBAL_INJECTED_NEXUS_REPO" : "https://nexus.onap.org/content/sites/raw", "GLOBAL_INJECTED_NEXUS_USERNAME" : "username", "GLOBAL_INJECTED_OPENO_IP_ADDR" : "10.0.14.1", "GLOBAL_INJECTED_OPENSTACK_PASSWORD" : "password", "GLOBAL_INJECTED_OPENSTACK_TENANT_ID" : "000007144004bacac1e39ff23105fff", "GLOBAL_INJECTED_OPENSTACK_USERNAME" : "demo", "GLOBAL_INJECTED_POLICY_IP_ADDR" : "10.0.6.1", "GLOBAL_INJECTED_PORTAL_IP_ADDR" : "10.0.9.1", "GLOBAL_INJECTED_PUBLIC_NET_ID" : "971040b2-7059-49dc-b220-4fab50cb2ad4", "GLOBAL_INJECTED_REGION" : "RegionOne", "GLOBAL_INJECTED_REMOTE_REPO" : "http://gerrit.onap.org/r/testsuite/properties.git", "GLOBAL_INJECTED_SCRIPT_VERSION" : "1.1.1", "GLOBAL_INJECTED_SDC_IP_ADDR" : "10.0.3.1", "GLOBAL_INJECTED_SDNC_IP_ADDR" : "10.0.7.1", "GLOBAL_INJECTED_SO_IP_ADDR" : "10.0.5.1", "GLOBAL_INJECTED_VID_IP_ADDR" : "10.0.8.1", "GLOBAL_INJECTED_VM_FLAVOR" : "m1.medium", "GLOBAL_INJECTED_UBUNTU_1404_IMAGE" : "ubuntu-14-04-cloud-amd64", "GLOBAL_INJECTED_UBUNTU_1604_IMAGE" : "ubuntu-16-04-cloud-amd64"}
global_injected_aai1_ip_addr = '10.0.1.1' global_injected_aai2_ip_addr = '10.0.1.2' global_injected_appc_ip_addr = '10.0.2.1' global_injected_artifacts_version = '1.2.0' global_injected_clamp_ip_addr = '10.0.12.1' global_injected_cloud_env = 'openstack' global_injected_dcae_ip_addr = '10.0.4.1' global_injected_dns_ip_addr = '10.0.100.1' global_injected_docker_version = '1.1-STAGING-latest' global_injected_external_dns = '8.8.8.8' global_injected_gerrit_branch = 'amsterdam' global_injected_keystone = 'http://10.12.25.2:5000' global_injected_mr_ip_addr = '10.0.11.1' global_injected_mso_ip_addr = '10.0.5.1' global_injected_network = 'oam_onap_wbaL' global_injected_nexus_docker_repo = '10.12.5.2:5000' global_injected_nexus_password = 'anonymous' global_injected_nexus_repo = 'https://nexus.onap.org/content/sites/raw' global_injected_nexus_username = 'username' global_injected_openo_ip_addr = '10.0.14.1' global_injected_openstack_password = 'password' global_injected_openstack_tenant_id = '000007144004bacac1e39ff23105fff' global_injected_openstack_username = 'username' global_injected_policy_ip_addr = '10.0.6.1' global_injected_portal_ip_addr = '10.0.9.1' global_injected_public_net_id = '971040b2-7059-49dc-b220-4fab50cb2ad4' global_injected_region = 'RegionOne' global_injected_remote_repo = 'http://gerrit.onap.org/r/testsuite/properties.git' global_injected_script_version = '1.1.1' global_injected_sdc_ip_addr = '10.0.3.1' global_injected_sdnc_ip_addr = '10.0.7.1' global_injected_so_ip_addr = '10.0.5.1' global_injected_vid_ip_addr = '10.0.8.1' global_injected_vm_flavor = 'm1.medium' global_injected_ubuntu_1404_image = 'ubuntu-14-04-cloud-amd64' global_injected_ubuntu_1604_image = 'ubuntu-16-04-cloud-amd64' global_injected_properties = {'GLOBAL_INJECTED_AAI1_IP_ADDR': '10.0.1.1', 'GLOBAL_INJECTED_AAI2_IP_ADDR': '10.0.1.2', 'GLOBAL_INJECTED_APPC_IP_ADDR': '10.0.2.1', 'GLOBAL_INJECTED_ARTIFACTS_VERSION': '1.2.0', 'GLOBAL_INJECTED_CLAMP_IP_ADDR': '10.0.12.1', 'GLOBAL_INJECTED_CLOUD_ENV': 'openstack', 'GLOBAL_INJECTED_DCAE_IP_ADDR': '10.0.4.1', 'GLOBAL_INJECTED_DNS_IP_ADDR': '10.0.100.1', 'GLOBAL_INJECTED_DOCKER_VERSION': '1.1-STAGING-latest', 'GLOBAL_INJECTED_EXTERNAL_DNS': '8.8.8.8', 'GLOBAL_INJECTED_GERRIT_BRANCH': 'amsterdam', 'GLOBAL_INJECTED_KEYSTONE': 'http://10.12.25.2:5000', 'GLOBAL_INJECTED_MR_IP_ADDR': '10.0.11.1', 'GLOBAL_INJECTED_MSO_IP_ADDR': '10.0.5.1', 'GLOBAL_INJECTED_NETWORK': 'oam_onap_wbaL', 'GLOBAL_INJECTED_NEXUS_DOCKER_REPO': '10.12.5.2:5000', 'GLOBAL_INJECTED_NEXUS_PASSWORD': 'username', 'GLOBAL_INJECTED_NEXUS_REPO': 'https://nexus.onap.org/content/sites/raw', 'GLOBAL_INJECTED_NEXUS_USERNAME': 'username', 'GLOBAL_INJECTED_OPENO_IP_ADDR': '10.0.14.1', 'GLOBAL_INJECTED_OPENSTACK_PASSWORD': 'password', 'GLOBAL_INJECTED_OPENSTACK_TENANT_ID': '000007144004bacac1e39ff23105fff', 'GLOBAL_INJECTED_OPENSTACK_USERNAME': 'demo', 'GLOBAL_INJECTED_POLICY_IP_ADDR': '10.0.6.1', 'GLOBAL_INJECTED_PORTAL_IP_ADDR': '10.0.9.1', 'GLOBAL_INJECTED_PUBLIC_NET_ID': '971040b2-7059-49dc-b220-4fab50cb2ad4', 'GLOBAL_INJECTED_REGION': 'RegionOne', 'GLOBAL_INJECTED_REMOTE_REPO': 'http://gerrit.onap.org/r/testsuite/properties.git', 'GLOBAL_INJECTED_SCRIPT_VERSION': '1.1.1', 'GLOBAL_INJECTED_SDC_IP_ADDR': '10.0.3.1', 'GLOBAL_INJECTED_SDNC_IP_ADDR': '10.0.7.1', 'GLOBAL_INJECTED_SO_IP_ADDR': '10.0.5.1', 'GLOBAL_INJECTED_VID_IP_ADDR': '10.0.8.1', 'GLOBAL_INJECTED_VM_FLAVOR': 'm1.medium', 'GLOBAL_INJECTED_UBUNTU_1404_IMAGE': 'ubuntu-14-04-cloud-amd64', 'GLOBAL_INJECTED_UBUNTU_1604_IMAGE': 'ubuntu-16-04-cloud-amd64'}
############################################################################### # Copyright (c) 2017-2020 Koren Lev (Cisco Systems), # # Yaron Yogev (Cisco Systems), Ilia Abashin (Cisco Systems) and others # # # # All rights reserved. This program and the accompanying materials # # are made available under the terms of the Apache License, Version 2.0 # # which accompanies this distribution, and is available at # # http://www.apache.org/licenses/LICENSE-2.0 # ############################################################################### VEDGE_ID = "3858e121-d861-4348-9d64-a55fcd5bf60a" VEDGE = { "configurations": { "tunnel_types": [ "vxlan" ], "tunneling_ip": "192.168.2.1" }, "host": "node-5.cisco.com", "id": "3858e121-d861-4348-9d64-a55fcd5bf60a", "tunnel_ports": { "vxlan-c0a80203": { }, "br-tun": { } }, "type": "vedge" } VEDGE_WITHOUT_CONFIGS = { } VEDGE_WITHOUT_TUNNEL_TYPES = { "configuration": { "tunnel_types": "" } } NON_ICEHOUSE_CONFIGS = { "distribution": "Mirantis", "distribution_version": "8.0" } ICEHOUSE_CONFIGS = { "distribution": "Canonical", "distribution_version": "icehouse" } HOST = { "host": "node-5.cisco.com", "id": "node-5.cisco.com", "ip_address": "192.168.0.4", "name": "node-5.cisco.com" } OTEPS_WITHOUT_CONFIGURATIONS_IN_VEDGE_RESULTS = [] OTEPS_WITHOUT_TUNNEL_TYPES_IN_VEDGE_RESULTS = [] OTEPS_FOR_NON_ICEHOUSE_DISTRIBUTION_RESULTS = [ { "host": "node-5.cisco.com", "ip_address": "192.168.2.1", "udp_port": 4789, "id": "node-5.cisco.com-otep", "name": "node-5.cisco.com-otep", "overlay_type": "vxlan", "ports": { "vxlan-c0a80203": { }, "br-tun": { } } } ] OTEPS_FOR_ICEHOUSE_DISTRIBUTION_RESULTS = [ { "host": "node-5.cisco.com", "ip_address": "192.168.0.4", "id": "node-5.cisco.com-otep", "name": "node-5.cisco.com-otep", "overlay_type": "vxlan", "ports": { "vxlan-c0a80203": { }, "br-tun": { } }, "udp_port": "67" } ] OTEPS = [ { "host": "node-5.cisco.com", "ip_address": "192.168.2.1", "udp_port": 4789 } ] OTEP_FOR_GETTING_VECONNECTOR = { "host": "node-5.cisco.com", "ip_address": "192.168.2.1", "udp_port": 4789, "id": "node-5.cisco.com-otep", "name": "node-5.cisco.com-otep", "overlay_type": "vxlan", "ports": { "vxlan-c0a80203": { }, "br-tun": { } } } HOST_ID = "node-5.cisco.com" IP_ADDRESS_SHOW_LINES = [ "2: br-mesh: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc " "pfifo_fast state UP group default qlen 1000", " link/ether 00:50:56:ac:28:9d brd ff:ff:ff:ff:ff:ff", " inet 192.168.2.1/24 brd 192.168.2.255 scope global br-mesh", " valid_lft forever preferred_lft forever", " inet6 fe80::d4e1:8fff:fe33:ed6a/64 scope global mngtmpaddr dynamic", " valid_lft 2591951sec preferred_lft 604751sec" ] OTEP_WITH_CONNECTOR = { "host": "node-5.cisco.com", "ip_address": "192.168.2.1", "udp_port": 4789, "id": "node-5.cisco.com-otep", "name": "node-5.cisco.com-otep", "overlay_type": "vxlan", "ports": { "vxlan-c0a80203": { }, "br-tun": { } }, "vconnector": "node-5.cisco.com-br-mesh" }
vedge_id = '3858e121-d861-4348-9d64-a55fcd5bf60a' vedge = {'configurations': {'tunnel_types': ['vxlan'], 'tunneling_ip': '192.168.2.1'}, 'host': 'node-5.cisco.com', 'id': '3858e121-d861-4348-9d64-a55fcd5bf60a', 'tunnel_ports': {'vxlan-c0a80203': {}, 'br-tun': {}}, 'type': 'vedge'} vedge_without_configs = {} vedge_without_tunnel_types = {'configuration': {'tunnel_types': ''}} non_icehouse_configs = {'distribution': 'Mirantis', 'distribution_version': '8.0'} icehouse_configs = {'distribution': 'Canonical', 'distribution_version': 'icehouse'} host = {'host': 'node-5.cisco.com', 'id': 'node-5.cisco.com', 'ip_address': '192.168.0.4', 'name': 'node-5.cisco.com'} oteps_without_configurations_in_vedge_results = [] oteps_without_tunnel_types_in_vedge_results = [] oteps_for_non_icehouse_distribution_results = [{'host': 'node-5.cisco.com', 'ip_address': '192.168.2.1', 'udp_port': 4789, 'id': 'node-5.cisco.com-otep', 'name': 'node-5.cisco.com-otep', 'overlay_type': 'vxlan', 'ports': {'vxlan-c0a80203': {}, 'br-tun': {}}}] oteps_for_icehouse_distribution_results = [{'host': 'node-5.cisco.com', 'ip_address': '192.168.0.4', 'id': 'node-5.cisco.com-otep', 'name': 'node-5.cisco.com-otep', 'overlay_type': 'vxlan', 'ports': {'vxlan-c0a80203': {}, 'br-tun': {}}, 'udp_port': '67'}] oteps = [{'host': 'node-5.cisco.com', 'ip_address': '192.168.2.1', 'udp_port': 4789}] otep_for_getting_veconnector = {'host': 'node-5.cisco.com', 'ip_address': '192.168.2.1', 'udp_port': 4789, 'id': 'node-5.cisco.com-otep', 'name': 'node-5.cisco.com-otep', 'overlay_type': 'vxlan', 'ports': {'vxlan-c0a80203': {}, 'br-tun': {}}} host_id = 'node-5.cisco.com' ip_address_show_lines = ['2: br-mesh: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000', ' link/ether 00:50:56:ac:28:9d brd ff:ff:ff:ff:ff:ff', ' inet 192.168.2.1/24 brd 192.168.2.255 scope global br-mesh', ' valid_lft forever preferred_lft forever', ' inet6 fe80::d4e1:8fff:fe33:ed6a/64 scope global mngtmpaddr dynamic', ' valid_lft 2591951sec preferred_lft 604751sec'] otep_with_connector = {'host': 'node-5.cisco.com', 'ip_address': '192.168.2.1', 'udp_port': 4789, 'id': 'node-5.cisco.com-otep', 'name': 'node-5.cisco.com-otep', 'overlay_type': 'vxlan', 'ports': {'vxlan-c0a80203': {}, 'br-tun': {}}, 'vconnector': 'node-5.cisco.com-br-mesh'}
class RedbotMotorActor(object): # TODO(asydorchuk): load constants from the config file. _MAXIMUM_FREQUENCY = 50 def __init__(self, gpio, power_pin, direction_pin_1, direction_pin_2): self.gpio = gpio self.power_pin = power_pin self.direction_pin_1 = direction_pin_1 self.direction_pin_2 = direction_pin_2 self.gpio.setup(power_pin, self.gpio.OUT) self.gpio.setup(direction_pin_1, self.gpio.OUT) self.gpio.setup(direction_pin_2, self.gpio.OUT) self.motor_controller = self.gpio.PWM( self.power_pin, self._MAXIMUM_FREQUENCY) def _setDirectionForward(self): self.gpio.output(self.direction_pin_1, True) self.gpio.output(self.direction_pin_2, False) def _setDirectionBackward(self): self.gpio.output(self.direction_pin_1, False) self.gpio.output(self.direction_pin_2, True) def start(self): self.gpio.output(self.direction_pin_1, False) self.gpio.output(self.direction_pin_2, False) self.motor_controller.start(0.0) self.relative_power = 0.0 def stop(self): self.gpio.output(self.direction_pin_1, False) self.gpio.output(self.direction_pin_2, False) self.motor_controller.stop() self.relative_power = 0.0 def setPower(self, relative_power): if relative_power < 0: self._setDirectionBackward() else: self._setDirectionForward() power = int(100.0 * abs(relative_power)) self.motor_controller.ChangeDutyCycle(power) self.relative_power = relative_power
class Redbotmotoractor(object): _maximum_frequency = 50 def __init__(self, gpio, power_pin, direction_pin_1, direction_pin_2): self.gpio = gpio self.power_pin = power_pin self.direction_pin_1 = direction_pin_1 self.direction_pin_2 = direction_pin_2 self.gpio.setup(power_pin, self.gpio.OUT) self.gpio.setup(direction_pin_1, self.gpio.OUT) self.gpio.setup(direction_pin_2, self.gpio.OUT) self.motor_controller = self.gpio.PWM(self.power_pin, self._MAXIMUM_FREQUENCY) def _set_direction_forward(self): self.gpio.output(self.direction_pin_1, True) self.gpio.output(self.direction_pin_2, False) def _set_direction_backward(self): self.gpio.output(self.direction_pin_1, False) self.gpio.output(self.direction_pin_2, True) def start(self): self.gpio.output(self.direction_pin_1, False) self.gpio.output(self.direction_pin_2, False) self.motor_controller.start(0.0) self.relative_power = 0.0 def stop(self): self.gpio.output(self.direction_pin_1, False) self.gpio.output(self.direction_pin_2, False) self.motor_controller.stop() self.relative_power = 0.0 def set_power(self, relative_power): if relative_power < 0: self._setDirectionBackward() else: self._setDirectionForward() power = int(100.0 * abs(relative_power)) self.motor_controller.ChangeDutyCycle(power) self.relative_power = relative_power
#!/usr/bin/env python3 print("// addTable") for a in range(0, 10): print(" '{0}': {{".format(a)) for b in range(a, 10): s = (a + b) % 10 c = (a + b) // 10 print(" '{0}': '{1}{2}',".format(b, s, c)) print(" },") print() print("// subTable") for a in range(0, 10): print(" '{0}': {{".format(a)) for b in range(0, 10): d = (a - b) % 10 c = 0 if a >= b else 1 print(" '{0}': '{1}{2}',".format(b, d, c)) print(" },") print() print("// mulTable") for a in range(0, 10): print(" '{0}': {{".format(a)) for b in range(a, 10): p = (a * b) % 10 c = (a * b) // 10 print(" '{0}': '{1}{2}',".format(b, p, c)) print(" },") print() print("// fullAdderTest") for a in range(0, 10): for b in range(0, 10): for ci in range(0, 10): s = (a + b + ci) % 10 co = (a + b + ci) // 10 print(" BadBignumTests.checkFullAdder('{0}', '{1}', '{2}', '{3}{4}');".format( a, b, ci, s, co )) print("// fullSubberTest") for a in range(0, 10): for b in range(0, 10): for bi in range(0, 10): d = (a - b - bi) % 10 bo = -((a - b - bi) // 10) print(" BadBignumTests.checkFullSubber('{0}', '{1}', '{2}', '{3}{4}');".format( a, b, bi, d, bo )) print("// mulTest") for a in range(0, 100): for b in range(a, 100): prod = a * b print(" BadBignumTests.checkMul('{0}', '{1}', '{2}');".format( a, b, prod ))
print('// addTable') for a in range(0, 10): print(" '{0}': {{".format(a)) for b in range(a, 10): s = (a + b) % 10 c = (a + b) // 10 print(" '{0}': '{1}{2}',".format(b, s, c)) print(' },') print() print('// subTable') for a in range(0, 10): print(" '{0}': {{".format(a)) for b in range(0, 10): d = (a - b) % 10 c = 0 if a >= b else 1 print(" '{0}': '{1}{2}',".format(b, d, c)) print(' },') print() print('// mulTable') for a in range(0, 10): print(" '{0}': {{".format(a)) for b in range(a, 10): p = a * b % 10 c = a * b // 10 print(" '{0}': '{1}{2}',".format(b, p, c)) print(' },') print() print('// fullAdderTest') for a in range(0, 10): for b in range(0, 10): for ci in range(0, 10): s = (a + b + ci) % 10 co = (a + b + ci) // 10 print(" BadBignumTests.checkFullAdder('{0}', '{1}', '{2}', '{3}{4}');".format(a, b, ci, s, co)) print('// fullSubberTest') for a in range(0, 10): for b in range(0, 10): for bi in range(0, 10): d = (a - b - bi) % 10 bo = -((a - b - bi) // 10) print(" BadBignumTests.checkFullSubber('{0}', '{1}', '{2}', '{3}{4}');".format(a, b, bi, d, bo)) print('// mulTest') for a in range(0, 100): for b in range(a, 100): prod = a * b print(" BadBignumTests.checkMul('{0}', '{1}', '{2}');".format(a, b, prod))
n, k = map(int, input().split()) dis = input().split() m = n while True: m = str(m) for d in dis: if d in m: break else: print(m) exit() m = int(m) + 1
(n, k) = map(int, input().split()) dis = input().split() m = n while True: m = str(m) for d in dis: if d in m: break else: print(m) exit() m = int(m) + 1
def replay(adb): adb.tap(1720, 1000) def go_to_home(adb): adb.tap(1961, 40) def go_to_battle(adb): adb.tap(1943, 928) def go_to_event_battle(adb): adb.tap(1900, 345) def select_daily_event(adb): adb.tap(313, 267) def select_unit(adb): adb.tap(1935, 935) def sortie(adb): adb.tap(1930, 947) def stage_clear_ok(adb): adb.tap(1958, 996)
def replay(adb): adb.tap(1720, 1000) def go_to_home(adb): adb.tap(1961, 40) def go_to_battle(adb): adb.tap(1943, 928) def go_to_event_battle(adb): adb.tap(1900, 345) def select_daily_event(adb): adb.tap(313, 267) def select_unit(adb): adb.tap(1935, 935) def sortie(adb): adb.tap(1930, 947) def stage_clear_ok(adb): adb.tap(1958, 996)
player_1_position = 7 player_2_position = 10 player_1_score = 0 player_2_score = 0 def roll_die(): i = 1 while 1: yield i i += 1 if i > 100: i = 1 roll = roll_die() number_of_die_rolls = 0 # while (player_1_score < 1000 and player_2_score < 1000): # for i in range(6): while 1: three_die_rolls = next(roll) + next(roll) + next(roll) number_of_die_rolls += 3 if((player_1_position + three_die_rolls) % 10 == 0): player_1_position = 10 else: player_1_position = (player_1_position + three_die_rolls) % 10 player_1_score += player_1_position print(f'p1 position: {player_1_position} p1 score: {player_1_score}') if(player_1_score >= 1000): print(f'player 1 wins!') print(f'{number_of_die_rolls} * {player_2_score} = {number_of_die_rolls * player_2_score}') break three_die_rolls = next(roll) + next(roll) + next(roll) number_of_die_rolls += 3 if((player_2_position + three_die_rolls) % 10 == 0): player_2_position = 10 else: player_2_position = (player_2_position + three_die_rolls) % 10 player_2_score += player_2_position print(f'p2 position: {player_2_position} p2 score: {player_2_score}') if(player_2_score >= 1000): print(f'player 2 wins!') print(f'{number_of_die_rolls} * {player_1_score} = {number_of_die_rolls * player_1_score}') break print(f'number of die rolls: {number_of_die_rolls}')
player_1_position = 7 player_2_position = 10 player_1_score = 0 player_2_score = 0 def roll_die(): i = 1 while 1: yield i i += 1 if i > 100: i = 1 roll = roll_die() number_of_die_rolls = 0 while 1: three_die_rolls = next(roll) + next(roll) + next(roll) number_of_die_rolls += 3 if (player_1_position + three_die_rolls) % 10 == 0: player_1_position = 10 else: player_1_position = (player_1_position + three_die_rolls) % 10 player_1_score += player_1_position print(f'p1 position: {player_1_position} p1 score: {player_1_score}') if player_1_score >= 1000: print(f'player 1 wins!') print(f'{number_of_die_rolls} * {player_2_score} = {number_of_die_rolls * player_2_score}') break three_die_rolls = next(roll) + next(roll) + next(roll) number_of_die_rolls += 3 if (player_2_position + three_die_rolls) % 10 == 0: player_2_position = 10 else: player_2_position = (player_2_position + three_die_rolls) % 10 player_2_score += player_2_position print(f'p2 position: {player_2_position} p2 score: {player_2_score}') if player_2_score >= 1000: print(f'player 2 wins!') print(f'{number_of_die_rolls} * {player_1_score} = {number_of_die_rolls * player_1_score}') break print(f'number of die rolls: {number_of_die_rolls}')
class RevasCalculations: '''Functions related to calculations go there ''' pass
class Revascalculations: """Functions related to calculations go there """ pass
""" write a first program in python3 How to run the program in terminal python3 filename.py """ print("HelloWorld in Python !!")
""" write a first program in python3 How to run the program in terminal python3 filename.py """ print('HelloWorld in Python !!')
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ] tinylist = [123, 'john'] print(list) # Prints complete list print(list[0]) # Prints first element of the list print(list[1:3]) # Prints elements starting from 2nd till 3rd print(list[2:]) # Prints elements starting from 3rd element print(tinylist * 2) # Prints list two times print(list + tinylist) # Prints concatenated lists
list = ['abcd', 786, 2.23, 'john', 70.2] tinylist = [123, 'john'] print(list) print(list[0]) print(list[1:3]) print(list[2:]) print(tinylist * 2) print(list + tinylist)
class Node: """Node for bst.""" def __init__(self, val): """Instantiate node.""" self.val = val self.right = None self.left = None def __repr__(self): """Represent node.""" return '<Node Val: {}'.format(self.val) def __str__(self): """Node value.""" return self.val class BST: """Binary search tree.""" def __init__(self): """Instatiate bst.""" self.root = None def __repr__(self): """Represent root.""" return '<BST Root {}>'.format(self.root.val) def __str__(self): """Root value.""" return self.root.val def in_order(self, operation): """In order traversal.""" def _walk(node=None): """Traverse.""" if node is None: return if node.left is not None: _walk(node.left) operation(node) if node.right is not None: _walk(node.right) _walk(self.root) def pre_order(self, operation): """Pre order traversal.""" def _walk(node=None): """Traverse.""" if node is None: return operation(node) if node.left is not None: _walk(node.left) if node.right is not None: _walk(node.right) _walk(self.root) def post_order(self, operation): """Post order traversal.""" def _walk(node=None): """Traverse.""" if node is None: return if node.left is not None: _walk(node.left) if node.right is not None: _walk(node.right) operation(node) _walk(self.root) def insert(self, val): """Add value as node to bst.""" node = Node(val) current = self.root if self.root is None: self.root = node return node while current: if val >= current.val: if current.right is not None: current = current.right else: current.right = node break elif val < current.val: if current.left is not None: current = current.left else: current.left = node break return node
class Node: """Node for bst.""" def __init__(self, val): """Instantiate node.""" self.val = val self.right = None self.left = None def __repr__(self): """Represent node.""" return '<Node Val: {}'.format(self.val) def __str__(self): """Node value.""" return self.val class Bst: """Binary search tree.""" def __init__(self): """Instatiate bst.""" self.root = None def __repr__(self): """Represent root.""" return '<BST Root {}>'.format(self.root.val) def __str__(self): """Root value.""" return self.root.val def in_order(self, operation): """In order traversal.""" def _walk(node=None): """Traverse.""" if node is None: return if node.left is not None: _walk(node.left) operation(node) if node.right is not None: _walk(node.right) _walk(self.root) def pre_order(self, operation): """Pre order traversal.""" def _walk(node=None): """Traverse.""" if node is None: return operation(node) if node.left is not None: _walk(node.left) if node.right is not None: _walk(node.right) _walk(self.root) def post_order(self, operation): """Post order traversal.""" def _walk(node=None): """Traverse.""" if node is None: return if node.left is not None: _walk(node.left) if node.right is not None: _walk(node.right) operation(node) _walk(self.root) def insert(self, val): """Add value as node to bst.""" node = node(val) current = self.root if self.root is None: self.root = node return node while current: if val >= current.val: if current.right is not None: current = current.right else: current.right = node break elif val < current.val: if current.left is not None: current = current.left else: current.left = node break return node
"""Output the number of labs required for a certain number of students.""" SEATS = 24 students = input('Enter the number of students: ') while not students.isnumeric(): students = input( "Numbers are usually numeric. Let's try this again.\n" 'Enter the number of students: ' ) students = int(students) labs, remaining = divmod(students, SEATS) labs += 1 if remaining else 0 plural = 'Labs' if students == 1 else 'Lab' print(f'{plural} required: {labs}')
"""Output the number of labs required for a certain number of students.""" seats = 24 students = input('Enter the number of students: ') while not students.isnumeric(): students = input("Numbers are usually numeric. Let's try this again.\nEnter the number of students: ") students = int(students) (labs, remaining) = divmod(students, SEATS) labs += 1 if remaining else 0 plural = 'Labs' if students == 1 else 'Lab' print(f'{plural} required: {labs}')
def solve(s): word_list = s.split(' ') name_capitalized = [] for word in word_list: name_capitalized.append(word.capitalize()) word = ' '.join(name_capitalized) return word
def solve(s): word_list = s.split(' ') name_capitalized = [] for word in word_list: name_capitalized.append(word.capitalize()) word = ' '.join(name_capitalized) return word
"""Subscribe to a specific queue and consume the messages. """ class Subscriber: def __init__(self, adapter): """Create a new subscriber with an Adapter instance. :param BaseAdapter adapter: Connection Adapter """ self.adapter = adapter def consume(self, worker): """Consume a queued message. :param function worker: Worker to execute when consuming the message """ self.adapter.consume(worker)
"""Subscribe to a specific queue and consume the messages. """ class Subscriber: def __init__(self, adapter): """Create a new subscriber with an Adapter instance. :param BaseAdapter adapter: Connection Adapter """ self.adapter = adapter def consume(self, worker): """Consume a queued message. :param function worker: Worker to execute when consuming the message """ self.adapter.consume(worker)
# # Copyright (c) 2019 Jonathan McGee <broken.source@etherealwake.com> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # """Common Implementation of GCC-Compatible C/C++ Toolchain.""" load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "action_config", "artifact_name_pattern", "feature", "flag_group", "flag_set", "variable_with_value", "with_feature_set", ) load( ":common.bzl", "ACTION_NAMES", "ALL_COMPILE_ACTIONS", "ALL_LINK_ACTIONS", "CPP_COMPILE_ACTIONS", "FEATURE_NAMES", "PREPROCESSOR_ACTIONS", "make_default_compile_flags_feature", "make_default_link_flags_feature", "make_linkstamps_feature", "make_tool", "make_user_compile_flags_feature", "make_user_link_flags_feature", ) load("//cc:rules.bzl", "cc_toolchain") # # GCC-Compatible Features # def gcc_archiver_flags_feature(ctx): return feature( name = FEATURE_NAMES.archiver_flags, flag_sets = [flag_set( actions = [ACTION_NAMES.cpp_link_static_library], flag_groups = [flag_group( flags = ["rcsD", "%{output_execpath}"], ), flag_group( iterate_over = "libraries_to_link", flag_groups = [flag_group( expand_if_equal = variable_with_value( "libraries_to_link.type", "object_file", ), flags = ["%{libraries_to_link.name}"], ), flag_group( expand_if_equal = variable_with_value( "libraries_to_link.type", "object_file_group", ), iterate_over = "libraries_to_link.object_files", flags = ["%{libraries_to_link.object_files}"], )], )], )], ) def gcc_compiler_input_flags_feature(ctx): return feature( name = FEATURE_NAMES.compiler_input_flags, flag_sets = [flag_set( actions = ALL_COMPILE_ACTIONS, flag_groups = [flag_group(flags = ["-c", "%{source_file}"])], )], ) def gcc_compiler_output_flags_feature(ctx): return feature( name = FEATURE_NAMES.compiler_output_flags, flag_sets = [flag_set( actions = ALL_COMPILE_ACTIONS, flag_groups = [flag_group(flags = ["-o", "%{output_file}"])], )], ) def gcc_dependency_file_feature(ctx): return feature( name = FEATURE_NAMES.dependency_file, enabled = True, flag_sets = [flag_set( actions = ALL_COMPILE_ACTIONS, flag_groups = [flag_group( expand_if_available = "dependency_file", flags = ["-MD", "-MF", "%{dependency_file}"], )], )], ) def gcc_fission_support(ctx): return feature( name = FEATURE_NAMES.fission_support, flag_sets = [flag_set( actions = ALL_LINK_ACTIONS, flag_groups = [flag_group( expand_if_available = "is_using_fission", flags = ["-Wl,--gdb-index"], )], )], ) def gcc_force_pic_flags_feature(ctx): return feature( name = FEATURE_NAMES.force_pic_flags, flag_sets = [flag_set( actions = [ACTION_NAMES.cpp_link_executable], flag_groups = [flag_group( expand_if_available = "force_pic", flags = ["-pie"], )], )], ) def gcc_fully_static_link(ctx): return feature( name = FEATURE_NAMES.fully_static_link, flag_sets = [flag_set( actions = ALL_LINK_ACTIONS, flag_groups = [flag_group(flags = ["-static"])], )], ) def gcc_includes_feature(ctx): return feature( name = FEATURE_NAMES.includes, enabled = True, flag_sets = [flag_set( actions = PREPROCESSOR_ACTIONS, flag_groups = [flag_group( expand_if_available = "includes", iterate_over = "includes", flags = ["-include", "%{includes}"], )], )], ) def gcc_include_paths_feature(ctx): return feature( name = FEATURE_NAMES.include_paths, enabled = True, flag_sets = [flag_set( actions = PREPROCESSOR_ACTIONS, flag_groups = [flag_group( iterate_over = "quote_include_paths", flags = ["-iquote", "%{quote_include_paths}"], ), flag_group( iterate_over = "include_paths", flags = ["-I%{include_paths}"], ), flag_group( iterate_over = "system_include_paths", flags = ["-isystem", "%{system_include_paths}"], )], )], ) def gcc_libraries_to_link_feature(ctx): whole_archive = flag_group( expand_if_true = "libraries_to_link.is_whole_archive", flags = ["-Wl,--whole-archive"], ) no_whole_archive = flag_group( expand_if_true = "libraries_to_link.is_whole_archive", flags = ["-Wl,--no-whole-archive"], ) return feature( name = FEATURE_NAMES.libraries_to_link, flag_sets = [flag_set( actions = ALL_LINK_ACTIONS, flag_groups = [flag_group( iterate_over = "libraries_to_link", flag_groups = [flag_group( expand_if_equal = variable_with_value( "libraries_to_link.type", "dynamic_library", ), flags = ["-l%{libraries_to_link.name}"], ), flag_group( expand_if_equal = variable_with_value( "libraries_to_link.type", "interface_library", ), flags = ["%{libraries_to_link.name}"], ), flag_group( expand_if_equal = variable_with_value( "libraries_to_link.type", "object_file", ), flags = ["%{libraries_to_link.name}"], ), flag_group( expand_if_equal = variable_with_value( "libraries_to_link.type", "object_file_group", ), flag_groups = [ whole_archive, flag_group(flags = ["-Wl,--start-lib"]), flag_group( iterate_over = "libraries_to_link.object_files", flags = ["%{libraries_to_link.object_files}"], ), flag_group(flags = ["-Wl,--end-lib"]), no_whole_archive, ], ), flag_group( expand_if_equal = variable_with_value( "libraries_to_link.type", "static_library", ), flag_groups = [ whole_archive, flag_group(flags = ["%{libraries_to_link.name}"]), no_whole_archive, ], ), flag_group( expand_if_equal = variable_with_value( "libraries_to_link.type", "versioned_dynamic_library", ), flags = ["-l:%{libraries_to_link.name}"], )], )], )], ) def gcc_library_search_directories_feature(ctx): return feature( name = FEATURE_NAMES.library_search_directories, flag_sets = [flag_set( actions = ALL_LINK_ACTIONS, flag_groups = [flag_group( expand_if_available = "library_search_directories", iterate_over = "library_search_directories", flags = ["-L%{library_search_directories}"], )], )], ) def gcc_linker_param_file_feature(ctx): return feature( name = FEATURE_NAMES.linker_param_file, flag_sets = [flag_set( actions = ALL_LINK_ACTIONS + [ACTION_NAMES.cpp_link_static_library], flag_groups = [flag_group( expand_if_available = "linker_param_file", flags = ["@%{linker_param_file}"], )], )], ) def gcc_output_execpath_flags_feature(ctx): return feature( name = FEATURE_NAMES.output_execpath_flags, flag_sets = [flag_set( actions = ALL_LINK_ACTIONS, flag_groups = [flag_group( flags = ["-o", "%{output_execpath}"], )], )], ) def gcc_per_object_debug_info_feature(ctx): return feature( name = FEATURE_NAMES.per_object_debug_info, enabled = True, flag_sets = [flag_set( actions = ALL_COMPILE_ACTIONS, flag_groups = [flag_group( expand_if_available = "per_object_debug_info_file", flags = ["-gsplit-dwarf"], )], )], ) def gcc_pic_feature(ctx): return feature( name = FEATURE_NAMES.pic, enabled = True, flag_sets = [flag_set( actions = ALL_COMPILE_ACTIONS, flag_groups = [flag_group( expand_if_available = "pic", flags = ["-fPIC"], )], )], ) def gcc_preprocessor_defines_feature(ctx): return feature( name = FEATURE_NAMES.preprocessor_defines, enabled = True, flag_sets = [flag_set( actions = PREPROCESSOR_ACTIONS, flag_groups = [flag_group( iterate_over = "preprocessor_defines", flags = ["-D%{preprocessor_defines}"], )], )], ) def gcc_random_seed_feature(ctx): return feature( name = FEATURE_NAMES.random_seed, enabled = True, flag_sets = [flag_set( actions = CPP_COMPILE_ACTIONS, flag_groups = [flag_group(flags = ["-frandom-seed=%{output_file}"])], )], ) def gcc_runtime_library_search_directories_feature(ctx): origin = "-Wl,-rpath,$ORIGIN/" return feature( name = FEATURE_NAMES.runtime_library_search_directories, flag_sets = [flag_set( actions = ALL_LINK_ACTIONS, flag_groups = [flag_group( expand_if_available = "runtime_library_search_directories", iterate_over = "runtime_library_search_directories", flags = [origin + "%{runtime_library_search_directories}"], )], )], ) def gcc_shared_flag_feature(ctx): return feature( name = FEATURE_NAMES.shared_flag, flag_sets = [flag_set( actions = [ ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ], flag_groups = [flag_group(flags = ["-shared"])], )], ) def gcc_static_libgcc_feature(ctx): return feature( name = FEATURE_NAMES.static_libgcc, enabled = True, flag_sets = [flag_set( actions = ALL_LINK_ACTIONS, with_features = [with_feature_set(features = [ FEATURE_NAMES.static_link_cpp_runtimes, ])], flag_groups = [flag_group(flags = ["-static-libgcc"])], )], ) def gcc_strip_debug_symbols_feature(ctx): return feature( name = FEATURE_NAMES.strip_debug_symbols, flag_sets = [flag_set( actions = ALL_LINK_ACTIONS, flag_groups = [flag_group( expand_if_available = "strip_debug_symbols", flags = ["-Wl,-S"], )], )], ) def gcc_strip_flag_set(ctx, **kwargs): """Generates list of `flag_set` for the `strip` executable.""" return [flag_set( flag_groups = [flag_group( flags = ctx.attr.stripopts, ), flag_group( flags = ["%{stripopts}"], iterate_over = "stripopts", ), flag_group( flags = ["-o", "%{output_file}", "%{input_file}"], )], **kwargs )] def gcc_sysroot_feature(ctx): return feature( name = FEATURE_NAMES.sysroot, flag_sets = [flag_set( actions = ALL_COMPILE_ACTIONS + ALL_LINK_ACTIONS, flag_groups = [flag_group( expand_if_available = "sysroot", flags = ["--sysroot=%{sysroot}"], )], )], ) def gcc_unfiltered_compile_flags_feature(ctx): return feature( name = FEATURE_NAMES.unfiltered_compile_flags, enabled = True, flag_sets = [flag_set( actions = ALL_COMPILE_ACTIONS, flag_groups = [flag_group(flags = [ "-no-canonical-prefixes", "-Wno-builtin-macro-redefined", "-D__DATE__=\"redacted\"", "-D__TIME__=\"redacted\"", "-D__TIMESTAMP__=\"redacted\"", ])], )], ) # # Core Rule Implementation # def gcc_cc_toolchain_config_impl(ctx, copts = [], linkopts = []): # Generate List of Actions action_configs = [] for action_name in ALL_COMPILE_ACTIONS: action_configs.append(action_config( action_name = action_name, implies = [ FEATURE_NAMES.default_compile_flags, FEATURE_NAMES.user_compile_flags, FEATURE_NAMES.sysroot, FEATURE_NAMES.unfiltered_compile_flags, FEATURE_NAMES.compiler_input_flags, FEATURE_NAMES.compiler_output_flags, ], tools = make_tool(ctx, ctx.file.cctool), )) for action_name in ALL_LINK_ACTIONS: if action_name == ACTION_NAMES.cpp_link_executable: implies = [FEATURE_NAMES.force_pic_flags] else: implies = [FEATURE_NAMES.shared_flag] action_configs.append(action_config( action_name = action_name, implies = implies + [ FEATURE_NAMES.default_link_flags, FEATURE_NAMES.strip_debug_symbols, FEATURE_NAMES.linkstamps, FEATURE_NAMES.output_execpath_flags, FEATURE_NAMES.runtime_library_search_directories, FEATURE_NAMES.library_search_directories, FEATURE_NAMES.libraries_to_link, FEATURE_NAMES.user_link_flags, FEATURE_NAMES.linker_param_file, FEATURE_NAMES.fission_support, FEATURE_NAMES.sysroot, ], tools = make_tool(ctx, ctx.file.linktool), )) action_configs.append(action_config( action_name = ACTION_NAMES.cpp_link_static_library, implies = [ FEATURE_NAMES.archiver_flags, FEATURE_NAMES.linker_param_file, ], tools = make_tool(ctx, ctx.file.artool), )) action_configs.append(action_config( action_name = ACTION_NAMES.strip, flag_sets = gcc_strip_flag_set(ctx), tools = make_tool(ctx, ctx.file.strip), )) # Construct List of Artifacts artifact_name_patterns = [ artifact_name_pattern("alwayslink_static_library", "lib", ".lo"), artifact_name_pattern("executable", None, None), artifact_name_pattern("included_file_list", None, ".d"), artifact_name_pattern("object_file", None, ".o"), artifact_name_pattern("static_library", "lib", ".a"), ] # Support List features = [ feature(name = FEATURE_NAMES.dbg), feature(name = FEATURE_NAMES.fastbuild), feature(name = FEATURE_NAMES.opt), feature(name = FEATURE_NAMES.no_legacy_features), ] if FEATURE_NAMES.supports_dynamic_linker in ctx.features: artifact_name_patterns.extend([ artifact_name_pattern("dynamic_library", "lib", ".so"), artifact_name_pattern("interface_library", "lib", ".ifso"), ]) features.append(feature( name = FEATURE_NAMES.supports_dynamic_linker, enabled = True, )) if FEATURE_NAMES.supports_pic in ctx.features: artifact_name_patterns.extend([ artifact_name_pattern("pic_file", None, ".pic"), artifact_name_pattern("pic_object_file", None, ".pic.o"), ]) features.append(feature( name = FEATURE_NAMES.supports_pic, enabled = True, )) if FEATURE_NAMES.supports_start_end_lib in ctx.features: features.append(feature( name = FEATURE_NAMES.supports_start_end_lib, enabled = True, )) # Action Groups features += [ # Compiler Flags make_default_compile_flags_feature(ctx, copts), gcc_dependency_file_feature(ctx), gcc_pic_feature(ctx), gcc_per_object_debug_info_feature(ctx), gcc_preprocessor_defines_feature(ctx), gcc_includes_feature(ctx), gcc_include_paths_feature(ctx), # Linker Flags make_default_link_flags_feature(ctx, linkopts), gcc_shared_flag_feature(ctx), make_linkstamps_feature(ctx), gcc_output_execpath_flags_feature(ctx), gcc_runtime_library_search_directories_feature(ctx), gcc_library_search_directories_feature(ctx), gcc_archiver_flags_feature(ctx), gcc_libraries_to_link_feature(ctx), gcc_force_pic_flags_feature(ctx), make_user_link_flags_feature(ctx), gcc_static_libgcc_feature(ctx), gcc_fission_support(ctx), gcc_strip_debug_symbols_feature(ctx), gcc_fully_static_link(ctx), # Trailing Flags make_user_compile_flags_feature(ctx), gcc_sysroot_feature(ctx), gcc_unfiltered_compile_flags_feature(ctx), gcc_linker_param_file_feature(ctx), gcc_compiler_input_flags_feature(ctx), gcc_compiler_output_flags_feature(ctx), ] # Additional Parameters sysroot = ctx.file.sysroot if sysroot: sysroot = sysroot.path # Construct CcToolchainConfigInfo config = cc_common.create_cc_toolchain_config_info( ctx = ctx, abi_libc_version = "local", abi_version = "local", action_configs = action_configs, artifact_name_patterns = artifact_name_patterns, builtin_sysroot = sysroot, cc_target_os = None, compiler = ctx.attr.compiler, cxx_builtin_include_directories = ctx.attr.builtin_include_directories, features = features, host_system_name = "local", make_variables = [], tool_paths = [], target_cpu = ctx.attr.cpu, target_libc = "local", target_system_name = ctx.attr.target, toolchain_identifier = ctx.attr.name, ) # Write out CcToolchainConfigInfo to file (diagnostics) pbtxt = ctx.actions.declare_file(ctx.attr.name + ".pbtxt") ctx.actions.write( output = pbtxt, content = config.proto, ) return [DefaultInfo(files = depset([pbtxt])), config] gcc_cc_toolchain_config = rule( attrs = { "artool": attr.label( allow_single_file = True, cfg = "host", executable = True, mandatory = True, ), "asmopts": attr.string_list(), "builtin_include_directories": attr.string_list(), "cctool": attr.label( allow_single_file = True, cfg = "host", executable = True, mandatory = True, ), "compiler": attr.string(default = "gcc"), "conlyopts": attr.string_list( default = ["-std=c17"], ), "copts": attr.string_list(), "cpu": attr.string(default = "local"), "cxxopts": attr.string_list( default = ["-std=c++17"], ), "linkopts": attr.string_list(), "linktool": attr.label( allow_single_file = True, cfg = "host", executable = True, mandatory = True, ), "modes": attr.string_list_dict(), "objcopy": attr.label( allow_single_file = True, cfg = "host", executable = True, mandatory = True, ), "strip": attr.label( allow_single_file = True, cfg = "host", executable = True, mandatory = True, ), "stripopts": attr.string_list( default = ["-S", "-p"], ), "sysroot": attr.label( allow_single_file = True, cfg = "host", ), "target": attr.string(default = "local"), }, implementation = gcc_cc_toolchain_config_impl, ) def gcc_toolchain( name, all_files, compiler_files, target_compatible_with, exec_compatible_with = None, objcopy_files = None, strip_files = None, target_files = None, visibility = None, **kwargs): """C/C++ Toolchain Macro for Generic Unix. Targets: {name}: Instance of `toolchain`. {name}-toolchain: Instance of `cc_toolchain`. """ gcc_cc_toolchain_config( name = name + "-config", tags = ["manual"], visibility = ["//visibility:private"], **kwargs ) if target_files: native.filegroup( name = name + "-files", srcs = [all_files] + target_files, tags = ["manual"], visibility = ["//visibility:private"], ) all_files = ":%s-files" % name native.filegroup( name = name + "-compiler-files", srcs = [compiler_files] + target_files, tags = ["manual"], visibility = ["//visibility:private"], ) compiler_files = ":%s-compiler-files" % name cc_toolchain( name = name + "-toolchain", all_files = all_files, ar_files = kwargs["artool"], as_files = compiler_files, compiler_files = compiler_files, dwp_files = compiler_files, libc_top = None, linker_files = all_files, objcopy_files = objcopy_files or kwargs["objcopy"], strip_files = strip_files or kwargs["strip"], supports_header_parsing = False, supports_param_files = False, toolchain_config = ":%s-config" % name, tags = ["manual"], visibility = visibility, ) native.toolchain( name = name, exec_compatible_with = exec_compatible_with, target_compatible_with = target_compatible_with, toolchain = ":%s-toolchain" % name, toolchain_type = "@bazel_tools//tools/cpp:toolchain_type", visibility = visibility, )
"""Common Implementation of GCC-Compatible C/C++ Toolchain.""" load('@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl', 'action_config', 'artifact_name_pattern', 'feature', 'flag_group', 'flag_set', 'variable_with_value', 'with_feature_set') load(':common.bzl', 'ACTION_NAMES', 'ALL_COMPILE_ACTIONS', 'ALL_LINK_ACTIONS', 'CPP_COMPILE_ACTIONS', 'FEATURE_NAMES', 'PREPROCESSOR_ACTIONS', 'make_default_compile_flags_feature', 'make_default_link_flags_feature', 'make_linkstamps_feature', 'make_tool', 'make_user_compile_flags_feature', 'make_user_link_flags_feature') load('//cc:rules.bzl', 'cc_toolchain') def gcc_archiver_flags_feature(ctx): return feature(name=FEATURE_NAMES.archiver_flags, flag_sets=[flag_set(actions=[ACTION_NAMES.cpp_link_static_library], flag_groups=[flag_group(flags=['rcsD', '%{output_execpath}']), flag_group(iterate_over='libraries_to_link', flag_groups=[flag_group(expand_if_equal=variable_with_value('libraries_to_link.type', 'object_file'), flags=['%{libraries_to_link.name}']), flag_group(expand_if_equal=variable_with_value('libraries_to_link.type', 'object_file_group'), iterate_over='libraries_to_link.object_files', flags=['%{libraries_to_link.object_files}'])])])]) def gcc_compiler_input_flags_feature(ctx): return feature(name=FEATURE_NAMES.compiler_input_flags, flag_sets=[flag_set(actions=ALL_COMPILE_ACTIONS, flag_groups=[flag_group(flags=['-c', '%{source_file}'])])]) def gcc_compiler_output_flags_feature(ctx): return feature(name=FEATURE_NAMES.compiler_output_flags, flag_sets=[flag_set(actions=ALL_COMPILE_ACTIONS, flag_groups=[flag_group(flags=['-o', '%{output_file}'])])]) def gcc_dependency_file_feature(ctx): return feature(name=FEATURE_NAMES.dependency_file, enabled=True, flag_sets=[flag_set(actions=ALL_COMPILE_ACTIONS, flag_groups=[flag_group(expand_if_available='dependency_file', flags=['-MD', '-MF', '%{dependency_file}'])])]) def gcc_fission_support(ctx): return feature(name=FEATURE_NAMES.fission_support, flag_sets=[flag_set(actions=ALL_LINK_ACTIONS, flag_groups=[flag_group(expand_if_available='is_using_fission', flags=['-Wl,--gdb-index'])])]) def gcc_force_pic_flags_feature(ctx): return feature(name=FEATURE_NAMES.force_pic_flags, flag_sets=[flag_set(actions=[ACTION_NAMES.cpp_link_executable], flag_groups=[flag_group(expand_if_available='force_pic', flags=['-pie'])])]) def gcc_fully_static_link(ctx): return feature(name=FEATURE_NAMES.fully_static_link, flag_sets=[flag_set(actions=ALL_LINK_ACTIONS, flag_groups=[flag_group(flags=['-static'])])]) def gcc_includes_feature(ctx): return feature(name=FEATURE_NAMES.includes, enabled=True, flag_sets=[flag_set(actions=PREPROCESSOR_ACTIONS, flag_groups=[flag_group(expand_if_available='includes', iterate_over='includes', flags=['-include', '%{includes}'])])]) def gcc_include_paths_feature(ctx): return feature(name=FEATURE_NAMES.include_paths, enabled=True, flag_sets=[flag_set(actions=PREPROCESSOR_ACTIONS, flag_groups=[flag_group(iterate_over='quote_include_paths', flags=['-iquote', '%{quote_include_paths}']), flag_group(iterate_over='include_paths', flags=['-I%{include_paths}']), flag_group(iterate_over='system_include_paths', flags=['-isystem', '%{system_include_paths}'])])]) def gcc_libraries_to_link_feature(ctx): whole_archive = flag_group(expand_if_true='libraries_to_link.is_whole_archive', flags=['-Wl,--whole-archive']) no_whole_archive = flag_group(expand_if_true='libraries_to_link.is_whole_archive', flags=['-Wl,--no-whole-archive']) return feature(name=FEATURE_NAMES.libraries_to_link, flag_sets=[flag_set(actions=ALL_LINK_ACTIONS, flag_groups=[flag_group(iterate_over='libraries_to_link', flag_groups=[flag_group(expand_if_equal=variable_with_value('libraries_to_link.type', 'dynamic_library'), flags=['-l%{libraries_to_link.name}']), flag_group(expand_if_equal=variable_with_value('libraries_to_link.type', 'interface_library'), flags=['%{libraries_to_link.name}']), flag_group(expand_if_equal=variable_with_value('libraries_to_link.type', 'object_file'), flags=['%{libraries_to_link.name}']), flag_group(expand_if_equal=variable_with_value('libraries_to_link.type', 'object_file_group'), flag_groups=[whole_archive, flag_group(flags=['-Wl,--start-lib']), flag_group(iterate_over='libraries_to_link.object_files', flags=['%{libraries_to_link.object_files}']), flag_group(flags=['-Wl,--end-lib']), no_whole_archive]), flag_group(expand_if_equal=variable_with_value('libraries_to_link.type', 'static_library'), flag_groups=[whole_archive, flag_group(flags=['%{libraries_to_link.name}']), no_whole_archive]), flag_group(expand_if_equal=variable_with_value('libraries_to_link.type', 'versioned_dynamic_library'), flags=['-l:%{libraries_to_link.name}'])])])]) def gcc_library_search_directories_feature(ctx): return feature(name=FEATURE_NAMES.library_search_directories, flag_sets=[flag_set(actions=ALL_LINK_ACTIONS, flag_groups=[flag_group(expand_if_available='library_search_directories', iterate_over='library_search_directories', flags=['-L%{library_search_directories}'])])]) def gcc_linker_param_file_feature(ctx): return feature(name=FEATURE_NAMES.linker_param_file, flag_sets=[flag_set(actions=ALL_LINK_ACTIONS + [ACTION_NAMES.cpp_link_static_library], flag_groups=[flag_group(expand_if_available='linker_param_file', flags=['@%{linker_param_file}'])])]) def gcc_output_execpath_flags_feature(ctx): return feature(name=FEATURE_NAMES.output_execpath_flags, flag_sets=[flag_set(actions=ALL_LINK_ACTIONS, flag_groups=[flag_group(flags=['-o', '%{output_execpath}'])])]) def gcc_per_object_debug_info_feature(ctx): return feature(name=FEATURE_NAMES.per_object_debug_info, enabled=True, flag_sets=[flag_set(actions=ALL_COMPILE_ACTIONS, flag_groups=[flag_group(expand_if_available='per_object_debug_info_file', flags=['-gsplit-dwarf'])])]) def gcc_pic_feature(ctx): return feature(name=FEATURE_NAMES.pic, enabled=True, flag_sets=[flag_set(actions=ALL_COMPILE_ACTIONS, flag_groups=[flag_group(expand_if_available='pic', flags=['-fPIC'])])]) def gcc_preprocessor_defines_feature(ctx): return feature(name=FEATURE_NAMES.preprocessor_defines, enabled=True, flag_sets=[flag_set(actions=PREPROCESSOR_ACTIONS, flag_groups=[flag_group(iterate_over='preprocessor_defines', flags=['-D%{preprocessor_defines}'])])]) def gcc_random_seed_feature(ctx): return feature(name=FEATURE_NAMES.random_seed, enabled=True, flag_sets=[flag_set(actions=CPP_COMPILE_ACTIONS, flag_groups=[flag_group(flags=['-frandom-seed=%{output_file}'])])]) def gcc_runtime_library_search_directories_feature(ctx): origin = '-Wl,-rpath,$ORIGIN/' return feature(name=FEATURE_NAMES.runtime_library_search_directories, flag_sets=[flag_set(actions=ALL_LINK_ACTIONS, flag_groups=[flag_group(expand_if_available='runtime_library_search_directories', iterate_over='runtime_library_search_directories', flags=[origin + '%{runtime_library_search_directories}'])])]) def gcc_shared_flag_feature(ctx): return feature(name=FEATURE_NAMES.shared_flag, flag_sets=[flag_set(actions=[ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library], flag_groups=[flag_group(flags=['-shared'])])]) def gcc_static_libgcc_feature(ctx): return feature(name=FEATURE_NAMES.static_libgcc, enabled=True, flag_sets=[flag_set(actions=ALL_LINK_ACTIONS, with_features=[with_feature_set(features=[FEATURE_NAMES.static_link_cpp_runtimes])], flag_groups=[flag_group(flags=['-static-libgcc'])])]) def gcc_strip_debug_symbols_feature(ctx): return feature(name=FEATURE_NAMES.strip_debug_symbols, flag_sets=[flag_set(actions=ALL_LINK_ACTIONS, flag_groups=[flag_group(expand_if_available='strip_debug_symbols', flags=['-Wl,-S'])])]) def gcc_strip_flag_set(ctx, **kwargs): """Generates list of `flag_set` for the `strip` executable.""" return [flag_set(flag_groups=[flag_group(flags=ctx.attr.stripopts), flag_group(flags=['%{stripopts}'], iterate_over='stripopts'), flag_group(flags=['-o', '%{output_file}', '%{input_file}'])], **kwargs)] def gcc_sysroot_feature(ctx): return feature(name=FEATURE_NAMES.sysroot, flag_sets=[flag_set(actions=ALL_COMPILE_ACTIONS + ALL_LINK_ACTIONS, flag_groups=[flag_group(expand_if_available='sysroot', flags=['--sysroot=%{sysroot}'])])]) def gcc_unfiltered_compile_flags_feature(ctx): return feature(name=FEATURE_NAMES.unfiltered_compile_flags, enabled=True, flag_sets=[flag_set(actions=ALL_COMPILE_ACTIONS, flag_groups=[flag_group(flags=['-no-canonical-prefixes', '-Wno-builtin-macro-redefined', '-D__DATE__="redacted"', '-D__TIME__="redacted"', '-D__TIMESTAMP__="redacted"'])])]) def gcc_cc_toolchain_config_impl(ctx, copts=[], linkopts=[]): action_configs = [] for action_name in ALL_COMPILE_ACTIONS: action_configs.append(action_config(action_name=action_name, implies=[FEATURE_NAMES.default_compile_flags, FEATURE_NAMES.user_compile_flags, FEATURE_NAMES.sysroot, FEATURE_NAMES.unfiltered_compile_flags, FEATURE_NAMES.compiler_input_flags, FEATURE_NAMES.compiler_output_flags], tools=make_tool(ctx, ctx.file.cctool))) for action_name in ALL_LINK_ACTIONS: if action_name == ACTION_NAMES.cpp_link_executable: implies = [FEATURE_NAMES.force_pic_flags] else: implies = [FEATURE_NAMES.shared_flag] action_configs.append(action_config(action_name=action_name, implies=implies + [FEATURE_NAMES.default_link_flags, FEATURE_NAMES.strip_debug_symbols, FEATURE_NAMES.linkstamps, FEATURE_NAMES.output_execpath_flags, FEATURE_NAMES.runtime_library_search_directories, FEATURE_NAMES.library_search_directories, FEATURE_NAMES.libraries_to_link, FEATURE_NAMES.user_link_flags, FEATURE_NAMES.linker_param_file, FEATURE_NAMES.fission_support, FEATURE_NAMES.sysroot], tools=make_tool(ctx, ctx.file.linktool))) action_configs.append(action_config(action_name=ACTION_NAMES.cpp_link_static_library, implies=[FEATURE_NAMES.archiver_flags, FEATURE_NAMES.linker_param_file], tools=make_tool(ctx, ctx.file.artool))) action_configs.append(action_config(action_name=ACTION_NAMES.strip, flag_sets=gcc_strip_flag_set(ctx), tools=make_tool(ctx, ctx.file.strip))) artifact_name_patterns = [artifact_name_pattern('alwayslink_static_library', 'lib', '.lo'), artifact_name_pattern('executable', None, None), artifact_name_pattern('included_file_list', None, '.d'), artifact_name_pattern('object_file', None, '.o'), artifact_name_pattern('static_library', 'lib', '.a')] features = [feature(name=FEATURE_NAMES.dbg), feature(name=FEATURE_NAMES.fastbuild), feature(name=FEATURE_NAMES.opt), feature(name=FEATURE_NAMES.no_legacy_features)] if FEATURE_NAMES.supports_dynamic_linker in ctx.features: artifact_name_patterns.extend([artifact_name_pattern('dynamic_library', 'lib', '.so'), artifact_name_pattern('interface_library', 'lib', '.ifso')]) features.append(feature(name=FEATURE_NAMES.supports_dynamic_linker, enabled=True)) if FEATURE_NAMES.supports_pic in ctx.features: artifact_name_patterns.extend([artifact_name_pattern('pic_file', None, '.pic'), artifact_name_pattern('pic_object_file', None, '.pic.o')]) features.append(feature(name=FEATURE_NAMES.supports_pic, enabled=True)) if FEATURE_NAMES.supports_start_end_lib in ctx.features: features.append(feature(name=FEATURE_NAMES.supports_start_end_lib, enabled=True)) features += [make_default_compile_flags_feature(ctx, copts), gcc_dependency_file_feature(ctx), gcc_pic_feature(ctx), gcc_per_object_debug_info_feature(ctx), gcc_preprocessor_defines_feature(ctx), gcc_includes_feature(ctx), gcc_include_paths_feature(ctx), make_default_link_flags_feature(ctx, linkopts), gcc_shared_flag_feature(ctx), make_linkstamps_feature(ctx), gcc_output_execpath_flags_feature(ctx), gcc_runtime_library_search_directories_feature(ctx), gcc_library_search_directories_feature(ctx), gcc_archiver_flags_feature(ctx), gcc_libraries_to_link_feature(ctx), gcc_force_pic_flags_feature(ctx), make_user_link_flags_feature(ctx), gcc_static_libgcc_feature(ctx), gcc_fission_support(ctx), gcc_strip_debug_symbols_feature(ctx), gcc_fully_static_link(ctx), make_user_compile_flags_feature(ctx), gcc_sysroot_feature(ctx), gcc_unfiltered_compile_flags_feature(ctx), gcc_linker_param_file_feature(ctx), gcc_compiler_input_flags_feature(ctx), gcc_compiler_output_flags_feature(ctx)] sysroot = ctx.file.sysroot if sysroot: sysroot = sysroot.path config = cc_common.create_cc_toolchain_config_info(ctx=ctx, abi_libc_version='local', abi_version='local', action_configs=action_configs, artifact_name_patterns=artifact_name_patterns, builtin_sysroot=sysroot, cc_target_os=None, compiler=ctx.attr.compiler, cxx_builtin_include_directories=ctx.attr.builtin_include_directories, features=features, host_system_name='local', make_variables=[], tool_paths=[], target_cpu=ctx.attr.cpu, target_libc='local', target_system_name=ctx.attr.target, toolchain_identifier=ctx.attr.name) pbtxt = ctx.actions.declare_file(ctx.attr.name + '.pbtxt') ctx.actions.write(output=pbtxt, content=config.proto) return [default_info(files=depset([pbtxt])), config] gcc_cc_toolchain_config = rule(attrs={'artool': attr.label(allow_single_file=True, cfg='host', executable=True, mandatory=True), 'asmopts': attr.string_list(), 'builtin_include_directories': attr.string_list(), 'cctool': attr.label(allow_single_file=True, cfg='host', executable=True, mandatory=True), 'compiler': attr.string(default='gcc'), 'conlyopts': attr.string_list(default=['-std=c17']), 'copts': attr.string_list(), 'cpu': attr.string(default='local'), 'cxxopts': attr.string_list(default=['-std=c++17']), 'linkopts': attr.string_list(), 'linktool': attr.label(allow_single_file=True, cfg='host', executable=True, mandatory=True), 'modes': attr.string_list_dict(), 'objcopy': attr.label(allow_single_file=True, cfg='host', executable=True, mandatory=True), 'strip': attr.label(allow_single_file=True, cfg='host', executable=True, mandatory=True), 'stripopts': attr.string_list(default=['-S', '-p']), 'sysroot': attr.label(allow_single_file=True, cfg='host'), 'target': attr.string(default='local')}, implementation=gcc_cc_toolchain_config_impl) def gcc_toolchain(name, all_files, compiler_files, target_compatible_with, exec_compatible_with=None, objcopy_files=None, strip_files=None, target_files=None, visibility=None, **kwargs): """C/C++ Toolchain Macro for Generic Unix. Targets: {name}: Instance of `toolchain`. {name}-toolchain: Instance of `cc_toolchain`. """ gcc_cc_toolchain_config(name=name + '-config', tags=['manual'], visibility=['//visibility:private'], **kwargs) if target_files: native.filegroup(name=name + '-files', srcs=[all_files] + target_files, tags=['manual'], visibility=['//visibility:private']) all_files = ':%s-files' % name native.filegroup(name=name + '-compiler-files', srcs=[compiler_files] + target_files, tags=['manual'], visibility=['//visibility:private']) compiler_files = ':%s-compiler-files' % name cc_toolchain(name=name + '-toolchain', all_files=all_files, ar_files=kwargs['artool'], as_files=compiler_files, compiler_files=compiler_files, dwp_files=compiler_files, libc_top=None, linker_files=all_files, objcopy_files=objcopy_files or kwargs['objcopy'], strip_files=strip_files or kwargs['strip'], supports_header_parsing=False, supports_param_files=False, toolchain_config=':%s-config' % name, tags=['manual'], visibility=visibility) native.toolchain(name=name, exec_compatible_with=exec_compatible_with, target_compatible_with=target_compatible_with, toolchain=':%s-toolchain' % name, toolchain_type='@bazel_tools//tools/cpp:toolchain_type', visibility=visibility)
#!/usr/bin/python print('Content-type: text/plain\n\n') print('script cgi with GET')
print('Content-type: text/plain\n\n') print('script cgi with GET')
# # GeomProc: geometry processing library in python + numpy # # Copyright (c) 2008-2021 Oliver van Kaick <ovankaic@gmail.com> # under the MIT License. # # See file LICENSE.txt for details on copyright licenses. # """This module contains the write_options class of the GeomProc geometry processing library. """ # Options for saving files class write_options: """A class that holds options of what information to write when saving a file Attributes ---------- write_vertex_normals : boolean Save normal vectors stored at mesh vertices write_vertex_colors : boolean Save colors stored at mesh vertices write_vertex_uvs : boolean Save (u, v) texture coordinates stored at mesh vertices write_face_normals : boolean Save normal vectors stored at mesh faces write_corner_normals : boolean Save normal vectors stored at face corners write_corner_uvs : boolean Save (u, v) texture coordinates stored at face corners texture_name : string Filename of image referenced by texture coordinates write_point_normals : boolean Save normal vectors stored at points in point cloud write_point_colors : boolean Save colors stored at points in point cloud Notes ----- Not all options are accepted by every file format. The class collects all the possible options supported by different file formats. The structure is relevant to both meshes and point clouds. """ def __init__(self): # Not all options are accepted by every file format self.write_vertex_normals = False self.write_vertex_colors = False self.write_vertex_uvs = False self.write_face_normals = False self.write_corner_normals = False self.write_corner_uvs = False self.texture_name = '' self.write_point_normals = False self.write_point_colors = False
"""This module contains the write_options class of the GeomProc geometry processing library. """ class Write_Options: """A class that holds options of what information to write when saving a file Attributes ---------- write_vertex_normals : boolean Save normal vectors stored at mesh vertices write_vertex_colors : boolean Save colors stored at mesh vertices write_vertex_uvs : boolean Save (u, v) texture coordinates stored at mesh vertices write_face_normals : boolean Save normal vectors stored at mesh faces write_corner_normals : boolean Save normal vectors stored at face corners write_corner_uvs : boolean Save (u, v) texture coordinates stored at face corners texture_name : string Filename of image referenced by texture coordinates write_point_normals : boolean Save normal vectors stored at points in point cloud write_point_colors : boolean Save colors stored at points in point cloud Notes ----- Not all options are accepted by every file format. The class collects all the possible options supported by different file formats. The structure is relevant to both meshes and point clouds. """ def __init__(self): self.write_vertex_normals = False self.write_vertex_colors = False self.write_vertex_uvs = False self.write_face_normals = False self.write_corner_normals = False self.write_corner_uvs = False self.texture_name = '' self.write_point_normals = False self.write_point_colors = False
OLD_EXP_PER_HOUR = 10 OLD_TIME_TO_LVL_DELTA = 5 NEW_EXP_PER_HOUR = 10 NEW_TIME_TO_LVL_DELTA = 7 NEW_TIME_TO_LVL_MULTIPLIER = 1.02 def old_level_to_exp(level, exp): total_exp = exp for i in range(2, level + 1): total_exp += i * OLD_TIME_TO_LVL_DELTA * OLD_EXP_PER_HOUR return total_exp def new_time_on_lvl(lvl): return float(NEW_TIME_TO_LVL_DELTA * lvl * NEW_TIME_TO_LVL_MULTIPLIER ** lvl) def exp_to_new_level(exp): level = 1 while exp >= new_time_on_lvl(level + 1) * NEW_EXP_PER_HOUR: exp -= new_time_on_lvl(level + 1) * NEW_EXP_PER_HOUR level += 1 return level, exp def old_to_new(level, exp): raw_exp = old_level_to_exp(level, exp) return exp_to_new_level(raw_exp)
old_exp_per_hour = 10 old_time_to_lvl_delta = 5 new_exp_per_hour = 10 new_time_to_lvl_delta = 7 new_time_to_lvl_multiplier = 1.02 def old_level_to_exp(level, exp): total_exp = exp for i in range(2, level + 1): total_exp += i * OLD_TIME_TO_LVL_DELTA * OLD_EXP_PER_HOUR return total_exp def new_time_on_lvl(lvl): return float(NEW_TIME_TO_LVL_DELTA * lvl * NEW_TIME_TO_LVL_MULTIPLIER ** lvl) def exp_to_new_level(exp): level = 1 while exp >= new_time_on_lvl(level + 1) * NEW_EXP_PER_HOUR: exp -= new_time_on_lvl(level + 1) * NEW_EXP_PER_HOUR level += 1 return (level, exp) def old_to_new(level, exp): raw_exp = old_level_to_exp(level, exp) return exp_to_new_level(raw_exp)
#!/usr/bin/env python3 # probleme des 8 dames def printGrid(grid): for y in range(8): print(8 - y, end=" |") for x in range(8): print(grid[x][y], "", end="") print() print("------------------") print("X |A B C D E F G H") grid = [[0] * 8 for _ in range(8)] for j in range(8): for i in range(8): grid[i][j] = (i + j) % 10 printGrid(grid)
def print_grid(grid): for y in range(8): print(8 - y, end=' |') for x in range(8): print(grid[x][y], '', end='') print() print('------------------') print('X |A B C D E F G H') grid = [[0] * 8 for _ in range(8)] for j in range(8): for i in range(8): grid[i][j] = (i + j) % 10 print_grid(grid)
class Bicicleta: def __init__(self, marca, aro, calibragem): self.marca = marca; self.aro = aro; self.calibragem = calibragem; def __str__(self): string = "Marca: "+self.marca+"\nAro: "+str(self.aro)+"\nCalibragem: "+str(self.calibragem) return string def getMarca(self): return self.marca def getAro(self): return self.aro def getCalibragem(self): return self.calibragem def getPegadaCarbono(self): pegCarb = 0 return pegCarb
class Bicicleta: def __init__(self, marca, aro, calibragem): self.marca = marca self.aro = aro self.calibragem = calibragem def __str__(self): string = 'Marca: ' + self.marca + '\nAro: ' + str(self.aro) + '\nCalibragem: ' + str(self.calibragem) return string def get_marca(self): return self.marca def get_aro(self): return self.aro def get_calibragem(self): return self.calibragem def get_pegada_carbono(self): peg_carb = 0 return pegCarb
class Node(object): def __init__(self, nm, name, capacity = 15): self.nm = nm self.name = name self.capacity = capacity self.values = [] def consume(self, from_name, value): """ All subclass need to override this function to do acturlly calculation """ pass def data_income(self, from_name, value): out_val = self.consume(from_name, value) if out_val != None: self.values.append(out_val) while len(self.values) > self.capacity: del self.values[0] self.data_output(self.name, out_val) def data_output(self, from_name, value): if from_name in self.nm.output_wires: wires = self.nm.output_wires[from_name] for wired_node in wires: wired_node.data_income(from_name, value) def snapshot(self): return [v for v in self.values]
class Node(object): def __init__(self, nm, name, capacity=15): self.nm = nm self.name = name self.capacity = capacity self.values = [] def consume(self, from_name, value): """ All subclass need to override this function to do acturlly calculation """ pass def data_income(self, from_name, value): out_val = self.consume(from_name, value) if out_val != None: self.values.append(out_val) while len(self.values) > self.capacity: del self.values[0] self.data_output(self.name, out_val) def data_output(self, from_name, value): if from_name in self.nm.output_wires: wires = self.nm.output_wires[from_name] for wired_node in wires: wired_node.data_income(from_name, value) def snapshot(self): return [v for v in self.values]
#!/usr/bin/env python # encoding: utf-8 """ @author: su jian @contact: 121116111@qq.com @file: __init__.py.py @time: 2017/8/16 17:43 """ def func(): pass class Main(): def __init__(self): pass if __name__ == '__main__': pass
""" @author: su jian @contact: 121116111@qq.com @file: __init__.py.py @time: 2017/8/16 17:43 """ def func(): pass class Main: def __init__(self): pass if __name__ == '__main__': pass
with open("spiderman.txt") as song: print(song.read(2)) print(song.read(8)) print(song.read())
with open('spiderman.txt') as song: print(song.read(2)) print(song.read(8)) print(song.read())
# -*- coding: utf-8 -*- # # Specifies the name of the last variable considered # before plotting # lastvar = "k" # # Specifies the columns to be plotted # and its label (in grace format) # col_contents = [(1, "\\f{Symbol} <r>"), (2, "\\f{Symbol} <dr>"), (3, "U\\sl")] # # Specifies the grace format of the x axis # xlabel = "\\f{Times-Italic}P"
lastvar = 'k' col_contents = [(1, '\\f{Symbol} <r>'), (2, '\\f{Symbol} <dr>'), (3, 'U\\sl')] xlabel = '\\f{Times-Italic}P'
print(open('teste_win1252.txt', errors='strict').read()) print(open('teste_win1252.txt', errors='replace').read()) print(open('teste_win1252.txt', errors='ignore').read()) print(open('teste_win1252.txt', errors='surrogateescape').read()) print(open('teste_win1252.txt', errors='backslashreplace').read())
print(open('teste_win1252.txt', errors='strict').read()) print(open('teste_win1252.txt', errors='replace').read()) print(open('teste_win1252.txt', errors='ignore').read()) print(open('teste_win1252.txt', errors='surrogateescape').read()) print(open('teste_win1252.txt', errors='backslashreplace').read())
# -------------- class_1 = ["Geoffrey Hinton", "Andrew Ng", "Sebastian Raschka", "Yoshua Bengio"] class_2 = ["Hilary Mason", "Carla Gentry", "Corinna Cortes"] new_class = class_1 + class_2 print(new_class) new_class.append("Peter Warden") print(new_class) new_class.remove("Carla Gentry") print(new_class) courses = {"Math" : 65, "English" : 70, "History" : 80, "French" : 70, "Science" : 60} total = 0 for i in courses: total += courses[i] print(total) percentage = total / len(courses) print(percentage) mathematics = {"Geoffrey Hinton" : 78, "Andrew Ng" : 95, "Sebastian Raschka" : 65, "Yoshua Benjio" : 50, "Hilary Manson" :70, "Corinna Cortes" : 66, "Peter Warden" : 75} topper = min(mathematics) print(topper) topper = topper.split() first_name = topper[0] last_name = topper[1] full_name = last_name + " " + first_name print(full_name) certificate_name = full_name.upper() print(certificate_name)
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) courses = {'Math': 65, 'English': 70, 'History': 80, 'French': 70, 'Science': 60} total = 0 for i in courses: total += courses[i] print(total) percentage = total / len(courses) print(percentage) mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95, 'Sebastian Raschka': 65, 'Yoshua Benjio': 50, 'Hilary Manson': 70, 'Corinna Cortes': 66, 'Peter Warden': 75} topper = min(mathematics) print(topper) topper = topper.split() first_name = topper[0] last_name = topper[1] full_name = last_name + ' ' + first_name print(full_name) certificate_name = full_name.upper() print(certificate_name)
""" Regularization works by penalizing model complexity. If the initial model is not complex enough to correctly describe the data then no amount of regularization will help as the model needs to get more complex to improve, not less. """;
""" Regularization works by penalizing model complexity. If the initial model is not complex enough to correctly describe the data then no amount of regularization will help as the model needs to get more complex to improve, not less. """
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" #print(full_name) #print(f"Hello, {full_name.title()}!") message = f"Hello, {full_name.title()}!" print(message) #print("\tPython") #print("Languages:\nPython\nC\nJavaScript") print("Languages:\n\tPython\n\tC\n\tJavaScript")
first_name = 'ada' last_name = 'lovelace' full_name = f'{first_name} {last_name}' message = f'Hello, {full_name.title()}!' print(message) print('Languages:\n\tPython\n\tC\n\tJavaScript')
class FakeConfig(object): def __init__( self, src_dir=None, spec_dir=None, stylesheet_urls=None, script_urls=None, stop_spec_on_expectation_failure=False, stop_on_spec_failure=False, random=True ): self._src_dir = src_dir self._spec_dir = spec_dir self._stylesheet_urls = stylesheet_urls self._script_urls = script_urls self._stop_spec_on_expectation_failure = stop_spec_on_expectation_failure self._stop_on_spec_failure = stop_on_spec_failure self._random = random self.reload_call_count = 0 def src_dir(self): return self._src_dir def spec_dir(self): return self._spec_dir def stylesheet_urls(self): return self._stylesheet_urls def script_urls(self): return self._script_urls def stop_spec_on_expectation_failure(self): return self._stop_spec_on_expectation_failure def stop_on_spec_failure(self): return self._stop_on_spec_failure def random(self): return self._random def reload(self): self.reload_call_count += 1
class Fakeconfig(object): def __init__(self, src_dir=None, spec_dir=None, stylesheet_urls=None, script_urls=None, stop_spec_on_expectation_failure=False, stop_on_spec_failure=False, random=True): self._src_dir = src_dir self._spec_dir = spec_dir self._stylesheet_urls = stylesheet_urls self._script_urls = script_urls self._stop_spec_on_expectation_failure = stop_spec_on_expectation_failure self._stop_on_spec_failure = stop_on_spec_failure self._random = random self.reload_call_count = 0 def src_dir(self): return self._src_dir def spec_dir(self): return self._spec_dir def stylesheet_urls(self): return self._stylesheet_urls def script_urls(self): return self._script_urls def stop_spec_on_expectation_failure(self): return self._stop_spec_on_expectation_failure def stop_on_spec_failure(self): return self._stop_on_spec_failure def random(self): return self._random def reload(self): self.reload_call_count += 1
class Timer: def __init__(self, bot, ring_every=1.0): self.bot = bot self.last_ring = 0.0 self.ring_every = ring_every @property def rings(self): if (self.bot.time - self.last_ring) >= self.ring_every: self.last_ring = self.bot.time return True else: return False
class Timer: def __init__(self, bot, ring_every=1.0): self.bot = bot self.last_ring = 0.0 self.ring_every = ring_every @property def rings(self): if self.bot.time - self.last_ring >= self.ring_every: self.last_ring = self.bot.time return True else: return False
#!/usr/bin/python3 class ComplexThing: def __init__(self, name, data): self.name = name self.data = data def __str__(self): return self.name + ": " + str(self.data)
class Complexthing: def __init__(self, name, data): self.name = name self.data = data def __str__(self): return self.name + ': ' + str(self.data)
# <<BEGIN-copyright>> # Copyright 2021, Lawrence Livermore National Security, LLC. # See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: BSD-3-Clause # <<END-copyright>> """ Dictionary storing numerical values. """ class NumberDict( dict ) : """ An instance of this class acts like an array of numbers with generalized (non-integer) indices. A value of zero is assumed for undefined entries. NumberDict instances support addition, and subtraction with other NumberDict instances, and multiplication and division by scalars. This class is used by the PhysicalUnit class to track units and their power. For example, for the unit 'm**2 / kg**3', the dictionary items are [('kg', -3), ('m', 2)]. """ def __getitem__( self, item ) : try: return( dict.__getitem__( self, item ) ) except KeyError: return( 0 ) def __coerce__( self, other ) : if( isinstance( other, dict ) ) : other = NumberDict( other ) other._removeUnneededDimensionlessUnit( ) return( self, other ) def __add__( self, other ) : sum_dict = NumberDict( ) for key in self : sum_dict[key] = self[key] for key in other : sum_dict[key] = sum_dict[key] + other[key] sum_dict._removeUnneededDimensionlessUnit( ) return( sum_dict ) def __sub__( self, other ) : sum_dict = NumberDict( ) for key in self : sum_dict[key] = self[key] for key in other : sum_dict[key] = sum_dict[key] - other[key] sum_dict._removeUnneededDimensionlessUnit( ) return( sum_dict ) def __mul__( self, other ) : new = NumberDict( ) for key in self : new[key] = other * self[key] new._removeUnneededDimensionlessUnit( ) return( new ) __rmul__ = __mul__ def __truediv__( self, other ) : new = NumberDict( ) for key in self : new[key] = self[key] / other new._removeUnneededDimensionlessUnit( ) return( new ) __div__ = __truediv__ def _removeUnneededDimensionlessUnit( self ) : """For internal use only.""" if( ( '' in self ) and ( len( self ) > 1 ) ) : del self['']
""" Dictionary storing numerical values. """ class Numberdict(dict): """ An instance of this class acts like an array of numbers with generalized (non-integer) indices. A value of zero is assumed for undefined entries. NumberDict instances support addition, and subtraction with other NumberDict instances, and multiplication and division by scalars. This class is used by the PhysicalUnit class to track units and their power. For example, for the unit 'm**2 / kg**3', the dictionary items are [('kg', -3), ('m', 2)]. """ def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: return 0 def __coerce__(self, other): if isinstance(other, dict): other = number_dict(other) other._removeUnneededDimensionlessUnit() return (self, other) def __add__(self, other): sum_dict = number_dict() for key in self: sum_dict[key] = self[key] for key in other: sum_dict[key] = sum_dict[key] + other[key] sum_dict._removeUnneededDimensionlessUnit() return sum_dict def __sub__(self, other): sum_dict = number_dict() for key in self: sum_dict[key] = self[key] for key in other: sum_dict[key] = sum_dict[key] - other[key] sum_dict._removeUnneededDimensionlessUnit() return sum_dict def __mul__(self, other): new = number_dict() for key in self: new[key] = other * self[key] new._removeUnneededDimensionlessUnit() return new __rmul__ = __mul__ def __truediv__(self, other): new = number_dict() for key in self: new[key] = self[key] / other new._removeUnneededDimensionlessUnit() return new __div__ = __truediv__ def _remove_unneeded_dimensionless_unit(self): """For internal use only.""" if '' in self and len(self) > 1: del self['']
CATEGORIES = [ ('Arts & Entertainment', [ 'Books & Literature', 'Celebrity Fan/Gossip', 'Fine Art', 'Humor', 'Movies', 'Music', 'Television' ]), ('Automotive', [ 'Auto Parts', 'Auto Repair', 'Buying/Selling Cars', 'Car Culture', 'Certified Pre-Owned', 'Convertible', 'Coupe', 'Crossover', 'Diesel', 'Electric Vehicle', 'Hatchback', 'Hybrid', 'Luxury', 'MiniVan', 'Mororcycles', 'Off-Road Vehicles', 'Performance Vehicles', 'Pickup', 'Road-Side Assistance', 'Sedan', 'Trucks & Accessories', 'Vintage Cars', 'Wagon', ]), ('Business', [ 'Advertising', 'Agriculture', 'Biotech/Biomedical', 'Business Software', 'Construction', 'Forestry', 'Government', 'Green Solutions', 'Human Resources', 'Logistics', 'Marketing', 'Metals', ] ), ('Careers', [ 'Career Planning', 'College', 'Financial Aid', 'Job Fairs', 'Job Search', 'Resume Writing/Advice', 'Nursing', 'Scholarships', 'Telecommuting', 'U.S. Military', 'Career Advice', ]), ('Education', [ '7-12 Education', 'Adult Education', 'Art History', 'Colledge Administration', 'College Life', 'Distance Learning', 'English as a 2nd Language', 'Language Learning', 'Graduate School', 'Homeschooling', 'Homework/Study Tips', 'K-6 Educators', 'Private School', 'Special Education', 'Studying Business', ]), ('Family & Parenting', [ 'Adoption', 'Babies & Toddlers', 'Daycare/Pre School', 'Family Internet', 'Parenting - K-6 Kids', 'Parenting teens', 'Pregnancy', 'Special Needs Kids', 'Eldercare', ]), ('Health & Fitness', [ 'Exercise', 'A.D.D.', 'AIDS/HIV', 'Allergies', 'Alternative Medicine', 'Arthritis', 'Asthma', 'Autism/PDD', 'Bipolar Disorder', 'Brain Tumor', 'Cancer', 'Cholesterol', 'Chronic Fatigue Syndrome', 'Chronic Pain', 'Cold & Flu', 'Deafness', 'Dental Care', 'Depression', 'Dermatology', 'Diabetes', 'Epilepsy', 'GERD/Acid Reflux', 'Headaches/Migraines', 'Heart Disease', 'Herbs for Health', 'Holistic Healing', 'IBS/Crohn\'s Disease', 'Incest/Abuse Support', 'Incontinence', 'Infertility', 'Men\'s Health', 'Nutrition', 'Orthopedics', 'Panic/Anxiety Disorders', 'Pediatrics', 'Physical Therapy', 'Psychology/Psychiatry', 'Senor Health', 'Sexuality', 'Sleep Disorders', 'Smoking Cessation', 'Substance Abuse', 'Thyroid Disease', 'Weight Loss', 'Women\'s Health', ]), ('Food & Drink', [ 'American Cuisine', 'Barbecues & Grilling', 'Cajun/Creole', 'Chinese Cuisine', 'Cocktails/Beer', 'Coffee/Tea', 'Cuisine-Specific', 'Desserts & Baking', 'Dining Out', 'Food Allergies', 'French Cuisine', 'Health/Lowfat Cooking', 'Italian Cuisine', 'Japanese Cuisine', 'Mexican Cuisine', 'Vegan', 'Vegetarian', 'Wine', ]), ('Hobbies & Interests', [ 'Art/Technology', 'Arts & Crafts', 'Beadwork', 'Birdwatching', 'Board Games/Puzzles', 'Candle & Soap Making', 'Card Games', 'Chess', 'Cigars', 'Collecting', 'Comic Books', 'Drawing/Sketching', 'Freelance Writing', 'Genealogy', 'Getting Published', 'Guitar', 'Home Recording', 'Investors & Patents', 'Jewelry Making', 'Magic & Illusion', 'Needlework', 'Painting', 'Photography', 'Radio', 'Roleplaying Games', 'Sci-Fi & Fantasy', 'Scrapbooking', 'Screenwriting', 'Stamps & Coins', 'Video & Computer Games', 'Woodworking', ]), ('Home & Garden', [ 'Appliances', 'Entertaining', 'Environmental Safety', 'Gardening', 'Home Repair', 'Home Theater', 'Interior Decorating', 'Landscaping', 'Remodeling & Construction', ]), ('Law, Gov\'t & Politics', [ 'Immigration', 'Legal Issues', 'U.S. Government Resources', 'Politics', 'Commentary', ]), ('News', [ 'International News', 'National News', 'Local News', ]), ('Personal Finance', [ 'Beginning Investing', 'Credit/Debt & Loans', 'Financial News', 'Financial Planning', 'Hedge Fund', 'Insurance', 'Investing', 'Mutual Funds', 'Options', 'Retirement Planning', 'Stocks', 'Tax Planning', ]), ('Society', [ 'Dating', 'Divorce Support', 'Gay Life', 'Marriage', 'Senior Living', 'Teens', 'Weddings', 'Ethnic Specific', ]), ('Science', [ 'Astrology', 'Biology', 'Chemistry', 'Geology', 'Paranormal Phenomena', 'Physics', 'Space/Astronomy', 'Geography', 'Botany', 'Weather', ]), ('Pets', [ 'Aquariums', 'Birds', 'Cats', 'Dogs', 'Large Animals', 'Reptiles', 'Veterinary Medicine', ]), ('Sports', [ 'Auto Racing', 'Baseball', 'Bicycling', 'Bodybuilding', 'Boxing', 'Canoeing/Kayaking', 'Cheerleading', 'Climbing', 'Cricket', 'Figure Skating', 'Fly Fishing', 'Football', 'Freshwater Fishing', 'Game & Fish', 'Golf', 'Horse Racing', 'Horses', 'Hunting/Shooting', 'Inline Skating', 'Martial Arts', 'Mountain Biking', 'NASCAR Racing', 'Olympics', 'Paintball', 'Power & Motorcycles', 'Pro Basketball', 'Pro Ice Hockey', 'Rodeo', 'Rugby', 'Running/Jogging', 'Sailing', 'Saltwater Fishing', 'Scuba Diving', 'Skateboarding', 'Skiing', 'Snowboarding', 'Surfing/Bodyboarding', 'Swimming', 'Table Tennis/Ping-Pong', 'Tennis', 'Volleyball', 'Walking', 'Waterski/Wakeboard', 'World Soccer', ]), ('Style & Fashion', [ 'Beauty', 'Body Art', 'Fashion', 'Jewelry', 'Clothing', 'Accessories', ]), ('Technology & Computing', [ '3-D Graphics', 'Animation', 'Antivirus Software', 'C/C++', 'Cameras & Camcorders', 'Cell Phones', 'Computer Certification', 'Computer Networking', 'Computer Peripherals', 'Computer Reviews', 'Data Centers', 'Databases', 'Desktop Publishing', 'Desktop Video', 'Email', 'Graphics Software', 'Home Video/DVD', 'Internet Technology', 'Java', 'JavaScript', 'Mac Support', 'MP3/MIDI', 'Net Conferencing', 'Net for Beginners', 'Network Security', 'Palmtops/PDAs', 'PC Support', 'Portable', 'Entertainment', 'Shareware/Freeware', 'Unix', 'Visual Basic', 'Web Clip Art', 'Web Design/HTML', 'Web Search', 'Windows', ]), ('Travel', [ 'Adventure Travel', 'Africa', 'Air Travel', 'Australia & New Zealand', 'Bed & Breakfasts', 'Budget Travel', 'Business Travel', 'By US Locale', 'Camping', 'Canada', 'Caribbean', 'Cruises', 'Eastern Europe', 'Europe', 'France', 'Greece', 'Honeymoons/Getaways', 'Hotels', 'Italy', 'Japan', 'Mexico & Central America', 'National Parks', 'South America', 'Spas', 'Theme Parks', 'Traveling with Kids', 'United Kingdom', ]), ('Real Estate', [ 'Apartments', 'Architects', 'Buying/Selling Homes', ]), ('Shopping', [ 'Contests & Freebies', 'Couponing', 'Comparison', 'Engines', ]), ('Religion & Spirituality', [ 'Alternative Religions', 'Atheism/Agnosticism', 'Buddhism', 'Catholicism', 'Christianity', 'Hinduism', 'Islam', 'Judaism', 'Latter-Day Saints', 'Pagan/Wiccan', ]), ('Uncategorized', []), ('Non-Standard Content', [ 'Unmoderated UGC', 'Extreme Graphic/Explicit Violence', 'Pornography', 'Profane Content', 'Hate Content', 'Under Construction', 'Incentivized', ]), ('Illegal Content', [ 'Illegal Content', 'Warez', 'Spyware/Malware', 'Copyright Infringement', ]) ] def from_string(s): try: cat = s[3:] if s.startswith('IAB') else s if '-' in cat: tier1, tier2 = map(int, cat.split('-')) t1c = CATEGORIES[tier1 - 1][0] t2c = CATEGORIES[tier1 - 1][1][tier2 - 1] return '{}: {}'.format(t1c, t2c) else: return CATEGORIES[int(cat) - 1][0] except (ValueError, IndexError): return s
categories = [('Arts & Entertainment', ['Books & Literature', 'Celebrity Fan/Gossip', 'Fine Art', 'Humor', 'Movies', 'Music', 'Television']), ('Automotive', ['Auto Parts', 'Auto Repair', 'Buying/Selling Cars', 'Car Culture', 'Certified Pre-Owned', 'Convertible', 'Coupe', 'Crossover', 'Diesel', 'Electric Vehicle', 'Hatchback', 'Hybrid', 'Luxury', 'MiniVan', 'Mororcycles', 'Off-Road Vehicles', 'Performance Vehicles', 'Pickup', 'Road-Side Assistance', 'Sedan', 'Trucks & Accessories', 'Vintage Cars', 'Wagon']), ('Business', ['Advertising', 'Agriculture', 'Biotech/Biomedical', 'Business Software', 'Construction', 'Forestry', 'Government', 'Green Solutions', 'Human Resources', 'Logistics', 'Marketing', 'Metals']), ('Careers', ['Career Planning', 'College', 'Financial Aid', 'Job Fairs', 'Job Search', 'Resume Writing/Advice', 'Nursing', 'Scholarships', 'Telecommuting', 'U.S. Military', 'Career Advice']), ('Education', ['7-12 Education', 'Adult Education', 'Art History', 'Colledge Administration', 'College Life', 'Distance Learning', 'English as a 2nd Language', 'Language Learning', 'Graduate School', 'Homeschooling', 'Homework/Study Tips', 'K-6 Educators', 'Private School', 'Special Education', 'Studying Business']), ('Family & Parenting', ['Adoption', 'Babies & Toddlers', 'Daycare/Pre School', 'Family Internet', 'Parenting - K-6 Kids', 'Parenting teens', 'Pregnancy', 'Special Needs Kids', 'Eldercare']), ('Health & Fitness', ['Exercise', 'A.D.D.', 'AIDS/HIV', 'Allergies', 'Alternative Medicine', 'Arthritis', 'Asthma', 'Autism/PDD', 'Bipolar Disorder', 'Brain Tumor', 'Cancer', 'Cholesterol', 'Chronic Fatigue Syndrome', 'Chronic Pain', 'Cold & Flu', 'Deafness', 'Dental Care', 'Depression', 'Dermatology', 'Diabetes', 'Epilepsy', 'GERD/Acid Reflux', 'Headaches/Migraines', 'Heart Disease', 'Herbs for Health', 'Holistic Healing', "IBS/Crohn's Disease", 'Incest/Abuse Support', 'Incontinence', 'Infertility', "Men's Health", 'Nutrition', 'Orthopedics', 'Panic/Anxiety Disorders', 'Pediatrics', 'Physical Therapy', 'Psychology/Psychiatry', 'Senor Health', 'Sexuality', 'Sleep Disorders', 'Smoking Cessation', 'Substance Abuse', 'Thyroid Disease', 'Weight Loss', "Women's Health"]), ('Food & Drink', ['American Cuisine', 'Barbecues & Grilling', 'Cajun/Creole', 'Chinese Cuisine', 'Cocktails/Beer', 'Coffee/Tea', 'Cuisine-Specific', 'Desserts & Baking', 'Dining Out', 'Food Allergies', 'French Cuisine', 'Health/Lowfat Cooking', 'Italian Cuisine', 'Japanese Cuisine', 'Mexican Cuisine', 'Vegan', 'Vegetarian', 'Wine']), ('Hobbies & Interests', ['Art/Technology', 'Arts & Crafts', 'Beadwork', 'Birdwatching', 'Board Games/Puzzles', 'Candle & Soap Making', 'Card Games', 'Chess', 'Cigars', 'Collecting', 'Comic Books', 'Drawing/Sketching', 'Freelance Writing', 'Genealogy', 'Getting Published', 'Guitar', 'Home Recording', 'Investors & Patents', 'Jewelry Making', 'Magic & Illusion', 'Needlework', 'Painting', 'Photography', 'Radio', 'Roleplaying Games', 'Sci-Fi & Fantasy', 'Scrapbooking', 'Screenwriting', 'Stamps & Coins', 'Video & Computer Games', 'Woodworking']), ('Home & Garden', ['Appliances', 'Entertaining', 'Environmental Safety', 'Gardening', 'Home Repair', 'Home Theater', 'Interior Decorating', 'Landscaping', 'Remodeling & Construction']), ("Law, Gov't & Politics", ['Immigration', 'Legal Issues', 'U.S. Government Resources', 'Politics', 'Commentary']), ('News', ['International News', 'National News', 'Local News']), ('Personal Finance', ['Beginning Investing', 'Credit/Debt & Loans', 'Financial News', 'Financial Planning', 'Hedge Fund', 'Insurance', 'Investing', 'Mutual Funds', 'Options', 'Retirement Planning', 'Stocks', 'Tax Planning']), ('Society', ['Dating', 'Divorce Support', 'Gay Life', 'Marriage', 'Senior Living', 'Teens', 'Weddings', 'Ethnic Specific']), ('Science', ['Astrology', 'Biology', 'Chemistry', 'Geology', 'Paranormal Phenomena', 'Physics', 'Space/Astronomy', 'Geography', 'Botany', 'Weather']), ('Pets', ['Aquariums', 'Birds', 'Cats', 'Dogs', 'Large Animals', 'Reptiles', 'Veterinary Medicine']), ('Sports', ['Auto Racing', 'Baseball', 'Bicycling', 'Bodybuilding', 'Boxing', 'Canoeing/Kayaking', 'Cheerleading', 'Climbing', 'Cricket', 'Figure Skating', 'Fly Fishing', 'Football', 'Freshwater Fishing', 'Game & Fish', 'Golf', 'Horse Racing', 'Horses', 'Hunting/Shooting', 'Inline Skating', 'Martial Arts', 'Mountain Biking', 'NASCAR Racing', 'Olympics', 'Paintball', 'Power & Motorcycles', 'Pro Basketball', 'Pro Ice Hockey', 'Rodeo', 'Rugby', 'Running/Jogging', 'Sailing', 'Saltwater Fishing', 'Scuba Diving', 'Skateboarding', 'Skiing', 'Snowboarding', 'Surfing/Bodyboarding', 'Swimming', 'Table Tennis/Ping-Pong', 'Tennis', 'Volleyball', 'Walking', 'Waterski/Wakeboard', 'World Soccer']), ('Style & Fashion', ['Beauty', 'Body Art', 'Fashion', 'Jewelry', 'Clothing', 'Accessories']), ('Technology & Computing', ['3-D Graphics', 'Animation', 'Antivirus Software', 'C/C++', 'Cameras & Camcorders', 'Cell Phones', 'Computer Certification', 'Computer Networking', 'Computer Peripherals', 'Computer Reviews', 'Data Centers', 'Databases', 'Desktop Publishing', 'Desktop Video', 'Email', 'Graphics Software', 'Home Video/DVD', 'Internet Technology', 'Java', 'JavaScript', 'Mac Support', 'MP3/MIDI', 'Net Conferencing', 'Net for Beginners', 'Network Security', 'Palmtops/PDAs', 'PC Support', 'Portable', 'Entertainment', 'Shareware/Freeware', 'Unix', 'Visual Basic', 'Web Clip Art', 'Web Design/HTML', 'Web Search', 'Windows']), ('Travel', ['Adventure Travel', 'Africa', 'Air Travel', 'Australia & New Zealand', 'Bed & Breakfasts', 'Budget Travel', 'Business Travel', 'By US Locale', 'Camping', 'Canada', 'Caribbean', 'Cruises', 'Eastern Europe', 'Europe', 'France', 'Greece', 'Honeymoons/Getaways', 'Hotels', 'Italy', 'Japan', 'Mexico & Central America', 'National Parks', 'South America', 'Spas', 'Theme Parks', 'Traveling with Kids', 'United Kingdom']), ('Real Estate', ['Apartments', 'Architects', 'Buying/Selling Homes']), ('Shopping', ['Contests & Freebies', 'Couponing', 'Comparison', 'Engines']), ('Religion & Spirituality', ['Alternative Religions', 'Atheism/Agnosticism', 'Buddhism', 'Catholicism', 'Christianity', 'Hinduism', 'Islam', 'Judaism', 'Latter-Day Saints', 'Pagan/Wiccan']), ('Uncategorized', []), ('Non-Standard Content', ['Unmoderated UGC', 'Extreme Graphic/Explicit Violence', 'Pornography', 'Profane Content', 'Hate Content', 'Under Construction', 'Incentivized']), ('Illegal Content', ['Illegal Content', 'Warez', 'Spyware/Malware', 'Copyright Infringement'])] def from_string(s): try: cat = s[3:] if s.startswith('IAB') else s if '-' in cat: (tier1, tier2) = map(int, cat.split('-')) t1c = CATEGORIES[tier1 - 1][0] t2c = CATEGORIES[tier1 - 1][1][tier2 - 1] return '{}: {}'.format(t1c, t2c) else: return CATEGORIES[int(cat) - 1][0] except (ValueError, IndexError): return s
class VirusFoundException(Exception): """Exception raised for detecting a virus in a file upload""" pass class InvalidExtensionException(Exception): """Exception raised for an attachment with an invalid extension""" pass class InvalidFileTypeException(Exception): """Exception raised for an attachment of an invalid type""" pass class FileSizeException(Exception): """Exception raised for an attachment that is too large""" pass
class Virusfoundexception(Exception): """Exception raised for detecting a virus in a file upload""" pass class Invalidextensionexception(Exception): """Exception raised for an attachment with an invalid extension""" pass class Invalidfiletypeexception(Exception): """Exception raised for an attachment of an invalid type""" pass class Filesizeexception(Exception): """Exception raised for an attachment that is too large""" pass
print( "Welcome to the Shape Generator:" ) cont = True shape1 = 0 shape2 = 0 shape3 = 0 shape4 = 0 shape5 = 0 shape6 = 0 drawAnotherShape = False def menu(): print() print( "This program draw the following shapes:" ) print( f"{'1) Horizontal Line':>20s}" ) print( f"{'2) Vertical Line':>18s}" ) print( f"{'3) Rectangle':>14s}" ) print( f"{'4) Left slant right angle triangle':>36s}" ) print( f"{'5) Right slant right angle triangle':>37s}" ) print( f"{'6) Isosceles triangle':>23s}" ) def printShape1(length): print( f"Here is the horizontal line with length {length}:" ) for i in range( length ): print( "*", end="" ) print() def printShape2(length): print( f"Here is the vertical line with length {length}:" ) for i in range( length ): print( "*" ) def printShape3(length, width): print( f"Here is the rectangle with length {length} and width {width}:" ) for x in range( length ): for x in range ( width): print( "*",end="") print() def printShape4(height): print( f"Here is the left slant right angle triangle with height {height}:" ) for x in range( 1, height + 1 ): for y in range (x): print( "*", end="") print() def printShape5(height): print( f"Here is the right slant right angle triangle with height {height}:" ) for x in range( 1, height + 1 ): print( " " * (height - x), end=" " ) for y in range (x): print( "*", end="" ) print() def printShape6(height): print( f"Here is the isosceles triangle with height {height}:" ) for x in range( 1, height + 1 ): for y in range (height - x + 1): print( " " , end="" ) for z in range(x * 2 - 1): print( "*", end="") print() def inputLength(): length = int( input( "Enter the length of the shape (1-20): " ) ) while length < 1 or length > 20: print( "Invalid input! You must enter a dimension between 1 and 20." ) length = int( input( "Enter the length of the shape (1-20): " ) ) return length def inputWidth(): width = int( input( "Enter the width of the rectangle (1-20): " ) ) while width < 1 or width > 20: print( "Invalid input! You must enter a dimension between 1 and 20." ) width = int( input( "Enter the width of the rectangle (1-20): " ) ) return width def inputHeight(): height = int( input( "Enter the height of the shape triangle (1-20): " ) ) while height < 1 or height > 20: print( "Invalid input! You must enter a dimension between 1 and 20." ) height = int( input( "Enter the height of the shape (1-20): " ) ) return height def inputDrawAnotherShape(): drawAnotherShape = input( "Would you like to draw another shape (y/n)? " ) while drawAnotherShape != "Y" and drawAnotherShape != "y" and drawAnotherShape != "N" and drawAnotherShape != "n": print( "Error! Incorrect input. Please enter 'y','Y','n' or 'N' to continue." ) drawAnotherShape = input( "Would you like to draw another shape (y/n)? " ) if drawAnotherShape == "Y" or drawAnotherShape == "y": cont = True else: cont = False return cont def goodbye(): print() print( "***************************************************************" ) print( "Here is a summary of the shapes that were drawn." ) print() print( f"Horizontal Line {shape1:45d}" ) print( f"Vertical Line {shape2:47d}" ) print( f"Rectangle {shape3:51d}" ) print( f"Left Slant Right Angle Triangle {shape4:29d}" ) print( f"Right Slant Right Angle Triangle {shape5:28d}" ) print( f"Isosceles Triangle {shape6:42d}" ) print() print( "Thank you for using the Shape Generator! Goodbye!" ) print( "***************************************************************" ) while cont == True: menu() shape = int( input( "Enter your choice (1-6): " ) ) while shape < 1 or shape > 6: print( "Invalid choice! Your choice must be between 1 and 6." ) shape = int( input( "Enter your choice (1-6): " ) ) if shape == 1: shape1 += 1 length = inputLength() printShape1( length ) elif shape == 2: shape2 += 1 length = inputLength() printShape2( length ) elif shape == 3: shape3 += 1 length = inputLength() width = inputWidth() printShape3( length, width ) elif shape == 4: shape4 += 1 height = inputHeight() printShape4( height ) elif shape == 5: shape5 += 1 height = inputHeight() printShape5( height ) elif shape == 6: shape6 += 1 height = inputHeight() printShape6( height ) cont = inputDrawAnotherShape() goodbye()
print('Welcome to the Shape Generator:') cont = True shape1 = 0 shape2 = 0 shape3 = 0 shape4 = 0 shape5 = 0 shape6 = 0 draw_another_shape = False def menu(): print() print('This program draw the following shapes:') print(f"{'1) Horizontal Line':>20s}") print(f"{'2) Vertical Line':>18s}") print(f"{'3) Rectangle':>14s}") print(f"{'4) Left slant right angle triangle':>36s}") print(f"{'5) Right slant right angle triangle':>37s}") print(f"{'6) Isosceles triangle':>23s}") def print_shape1(length): print(f'Here is the horizontal line with length {length}:') for i in range(length): print('*', end='') print() def print_shape2(length): print(f'Here is the vertical line with length {length}:') for i in range(length): print('*') def print_shape3(length, width): print(f'Here is the rectangle with length {length} and width {width}:') for x in range(length): for x in range(width): print('*', end='') print() def print_shape4(height): print(f'Here is the left slant right angle triangle with height {height}:') for x in range(1, height + 1): for y in range(x): print('*', end='') print() def print_shape5(height): print(f'Here is the right slant right angle triangle with height {height}:') for x in range(1, height + 1): print(' ' * (height - x), end=' ') for y in range(x): print('*', end='') print() def print_shape6(height): print(f'Here is the isosceles triangle with height {height}:') for x in range(1, height + 1): for y in range(height - x + 1): print(' ', end='') for z in range(x * 2 - 1): print('*', end='') print() def input_length(): length = int(input('Enter the length of the shape (1-20): ')) while length < 1 or length > 20: print('Invalid input! You must enter a dimension between 1 and 20.') length = int(input('Enter the length of the shape (1-20): ')) return length def input_width(): width = int(input('Enter the width of the rectangle (1-20): ')) while width < 1 or width > 20: print('Invalid input! You must enter a dimension between 1 and 20.') width = int(input('Enter the width of the rectangle (1-20): ')) return width def input_height(): height = int(input('Enter the height of the shape triangle (1-20): ')) while height < 1 or height > 20: print('Invalid input! You must enter a dimension between 1 and 20.') height = int(input('Enter the height of the shape (1-20): ')) return height def input_draw_another_shape(): draw_another_shape = input('Would you like to draw another shape (y/n)? ') while drawAnotherShape != 'Y' and drawAnotherShape != 'y' and (drawAnotherShape != 'N') and (drawAnotherShape != 'n'): print("Error! Incorrect input. Please enter 'y','Y','n' or 'N' to continue.") draw_another_shape = input('Would you like to draw another shape (y/n)? ') if drawAnotherShape == 'Y' or drawAnotherShape == 'y': cont = True else: cont = False return cont def goodbye(): print() print('***************************************************************') print('Here is a summary of the shapes that were drawn.') print() print(f'Horizontal Line {shape1:45d}') print(f'Vertical Line {shape2:47d}') print(f'Rectangle {shape3:51d}') print(f'Left Slant Right Angle Triangle {shape4:29d}') print(f'Right Slant Right Angle Triangle {shape5:28d}') print(f'Isosceles Triangle {shape6:42d}') print() print('Thank you for using the Shape Generator! Goodbye!') print('***************************************************************') while cont == True: menu() shape = int(input('Enter your choice (1-6): ')) while shape < 1 or shape > 6: print('Invalid choice! Your choice must be between 1 and 6.') shape = int(input('Enter your choice (1-6): ')) if shape == 1: shape1 += 1 length = input_length() print_shape1(length) elif shape == 2: shape2 += 1 length = input_length() print_shape2(length) elif shape == 3: shape3 += 1 length = input_length() width = input_width() print_shape3(length, width) elif shape == 4: shape4 += 1 height = input_height() print_shape4(height) elif shape == 5: shape5 += 1 height = input_height() print_shape5(height) elif shape == 6: shape6 += 1 height = input_height() print_shape6(height) cont = input_draw_another_shape() goodbye()
num = 45 # symVal = {1000:'M',900:'CM',500:'D',400:'CD',100:'C',90:'XC',50:'L',40:'XL',10:'X',9:'IX',5:'V',4:'IV',1:'I'} # romanNum = '' # i = 0 # while num > 0 : # curVal = list(symVal)[i] # for _ in range(num // curVal): # # if (divmod(num,4)[1] == 0 or divmod(num,9)[1] == 0): # romanNum += symVal[curVal] # num -= curVal # i += 1 # print(romanNum) class Solution(object): def __init__(self): self.roman = '' def intToRoman(self, num): self.num = num self.checkRoman(1000, 'M') self.checkRoman(500, 'D') self.checkRoman(100, 'C') self.checkRoman(50, 'L') self.checkRoman(10, 'X') self.checkRoman(5, 'V') self.checkRoman(1, 'I') return self.roman def checkRoman(self, value, strVal): numVal = self.num // value if (numVal > 0 and numVal < 4): for _ in range(0, numVal): self.roman += strVal self.num -= value * numVal if (value > 100 and self.num / (value - 100) > 0): self.roman += 'C' + strVal self.num -= (value - 100) if (value > 10 and self.num / (value - 10) > 0): self.roman += 'X' + strVal self.num -= (value - 10) if (value > 1 and self.num / (value - 1) > 0): self.roman += 'I' + strVal self.num -= value - 1 print(Solution().intToRoman(49))
num = 45 class Solution(object): def __init__(self): self.roman = '' def int_to_roman(self, num): self.num = num self.checkRoman(1000, 'M') self.checkRoman(500, 'D') self.checkRoman(100, 'C') self.checkRoman(50, 'L') self.checkRoman(10, 'X') self.checkRoman(5, 'V') self.checkRoman(1, 'I') return self.roman def check_roman(self, value, strVal): num_val = self.num // value if numVal > 0 and numVal < 4: for _ in range(0, numVal): self.roman += strVal self.num -= value * numVal if value > 100 and self.num / (value - 100) > 0: self.roman += 'C' + strVal self.num -= value - 100 if value > 10 and self.num / (value - 10) > 0: self.roman += 'X' + strVal self.num -= value - 10 if value > 1 and self.num / (value - 1) > 0: self.roman += 'I' + strVal self.num -= value - 1 print(solution().intToRoman(49))
# -*- coding: utf-8 -*- TO_EXCLUDE = [ "ACITAK", "ACITAK", "ADASUW", "AFEHOL", "AFENAA", "AFENAA", "AMUTEI", "AQUCOF", "AQUCOF", "AQUDAS", "AQUDAS", "ARADEE", "ATAGOQ", "ATAGOR", "ATAGOR", "BAXLA", "BAXLAP", "BAXLAP", "BICPOV", "BICPOV", "BIYWAK", "BIYWAK", "BIZLOO", "BUHVOP", "BUPVEP", "BUXZAX", "CAVWEC", "CIGXIA", "COFYOM", "COFYOM", "COFYOM", "COKNOH", "COKNOH01", "COXQOV", "COXQOV", "CUFMOG", "CUVJUA", "CUVJUA", "DIJYED", "DOVBIB", "EBUPUO", "EBUPUO", "EDIMOT", "EKIPAP01", "ENATUJ", "EQEHUE", "EQIZAF", "FAQLIV", "FEBZUH10", "FEKCEE", "FENXAY", "FIGTUL", "FIGTUL", "FIGZIG", "FIGZIG", "FIGZIG", "FIGZOM", "FIGZOM", "FIGZOM", "FIGZUS", "FIGZUS", "FINPUP01", "FIYGAY", "FODLAM02", "FUZBUX", "FUZBUX", "FUZBUX", "GASMUK", "GEVPOM", "GEVPOM", "GUVZEE", "GUVZII", "HAVHAG", "HAVHAG", "HAVHAQ", "HAVHAQ", "HAWVIN", "HAWVUZ", "HEQVUU", "HEQWAB", "HITQOR", "HITQOR", "HOJHUM", "HOMQEI", "IDIWIB", "IDIWOH", "IDIXID", "IDXID", "IJATUI", "IWIHON", "JAPYEH", "JAPYEH", "JAPYIL", "JAPYOR", "JAPYUX", "JAPZAE", "JAPZEI", "JAPZEI", "JAPZIM", "JAPZUY", "JAPZUY", "JEBWEV", "JIMNUR", "JIZJAF", "JIZJEJ", "JIZJIN", "JIZJOT", "JIZJUZ", "JUBQEE", "KAJZIH", "KAKTIA01", "KAKTIA01", "KAWCES", "KAWFUL", "KAWFUL", "KEPGES", "KEPGIW", "KEPGIW", "KEPGIW", "KERWIP", "KESSIM", "KESSIM", "KEXZUI", "KOCLEW", "KOGNIE", "KOGNIE", "KOVLOC", "KUTNUI", "KUTNUI", "LARRAA", "LARRAA", "LAVYIT", "LIDWAX", "LIDWAX", "MAHSUK", "MAHSUK01", "MAJLOZ", "MAPGUI", "MAVLED", "MELNEZ", "MELNEZ", "MIFQEZ", "MIFQOJ", "MIFQOJ", "MITFON", "MITSIS", "MOBBOU", "MOBBOU", "MOHQOQ", "MOHQOQ", "MOYZAC", "NAMTON", "NAMTON", "NAVRIO", "NECBUT", "NECBUT", "NECCUU", "NECCUU", "NENNOK", "NEZPOA", "NEZPUG", "NOJSUD", "NUHWUJ", "NUMLIQ", "NUZXAI", "NUZXAI", "OJANES", "OJANES", "OLIKUR", "ORIVUI", "PEFHIS", "PEHWEE", "PEPVEM", "PEPVEM", "PETWOC", "PETWUI", "PETXAP", "PIZHAJ", "PURVIH", "PURVIH", "QAMTEG", "QEJLID", # mixed valence not indicated "QIDFOB", "RAWFAZ", "REKPUV", "REKPUV", "RERROW", "RERROW", "REYDUX", "ROCKEZ", "ROCKEZ", "RUVHEX", "SATHUS", "SIBDUD", "SIBDUD", "SISMAL", "SISMAL", "SIYXIH", "SOKKAH", "SULPMS", "TAZGEG", "TAZGEG", "TAZGEG", "TCAZCO", "TCAZCO", "TCAZCO", "TEDDUC", "TEDDUC", "TEDDUC", "TEJFOG", "TEPWIX", "TEYLOB", "TICMEY", "TICMEY", "UDACEH", "UDOQAF", "UDOQAF", "UGARID", "UGARID", "VAYJOB", "VEYJOB", "VIGCET", "VOGBAU", "VOMMUH", "VUNQUS", "VUNQUS", "VUNQUS", "WAQFAY", "WAQKIK", "WAZKOZ", "WODZEX", "WOQKET", "WUDLIQ", "XAHREE", "XAHREE", "XAXPIX", "XEDJUN", "XEHVOW", "XEHVOW", "XOXTOW", "XOXTUC", "XUVDEZ", "YAKFIZ", "YAKFIZ", "YAMLOQ", "ZARBEZ", "ZASTUK", "ZASTUK", "ZEJWIX", "ZEJWOD", "ZEJXAQ", "ZEJXAQ", "ZEJXEU", "ZEQROE", "ZIFTIU", "ZITFIU", "ZITMUN", "RAXBAV", "BAYMOF", "GIMBIN", "KIKPOM", "VAHCEM", "ZUQVUC", "CAVXAB", "EBAGAR", "ACITAK", "ZUVVUH", "BERXAX", "BIWRUX", "ZICXOY", "XUDJUB", "ZASBEC", "PEXRIU", "TACJUE", "SOSVAX", "MATVEK", "YUSKIH", "SEBCUA", "NAYCIZ", "XAVJAF", "YAZPOG", "AQOPEB", "BAQMIR", "BIPLIX", "ZEGFOG", "KIFVOL", "CAGROT", "ROFDEV", "JIVWUH", "BIYWEO", "AKIYUO", "ROFCUK", "TIWPEU", "UFAXIJ", # Cr(III/V) disordered "YALPOR", # partially oxidized Fe and partially reduced Cu "FUGCUF", # Not so clear where the CSD got the Co(III) from "YIPDOR", # should have been excluded due to mixed valence "LOKJUR", # "do not allow distinguishing the Cu oxidation state." "TERBUQ", # mutlticonfigurational ground state "TAQDUN", "AMUTEI", "PEQXUF", "YEJJUT", "ROFDAR", "BARGAF", "FAXLOG", "ZIPFOT", "WALWEM", "UCIDEQ", "VIGQUA", "XAHREE", "WAZKOZ", "ZOCLAE", "EKINUH", "FELHUZ", "QICXEG", "WUBLEK", "ZERHAF", "FARROH", "ZEJXAQ", "UHOGUT", "XALXAJ", "SISMAL", "DEFCID", "YEGLAZ", "ZEJWIX", "CUNTOV", "FODLAM", "BAWGEO", "BUPHEA", "OLELAS", "DOCPOD", "WOKJOW", "WOQKET", "WOKJAI", "BEFZAP", "VUQWAG", "GATDAH", "TAQDUN", "WEZPEX", "LEKFEM", "BIJCUV", # highly covalent, Moessbauer is unclear "XALFUN", # from the paper Co(0) seems to be not that clea "FAGWOA", "TUQKUL", "YEXBOS", "XIHLIK", "KIWDOJ", "BALTUE", # Re(V/VII) resonance forms "BOJSUO", ]
to_exclude = ['ACITAK', 'ACITAK', 'ADASUW', 'AFEHOL', 'AFENAA', 'AFENAA', 'AMUTEI', 'AQUCOF', 'AQUCOF', 'AQUDAS', 'AQUDAS', 'ARADEE', 'ATAGOQ', 'ATAGOR', 'ATAGOR', 'BAXLA', 'BAXLAP', 'BAXLAP', 'BICPOV', 'BICPOV', 'BIYWAK', 'BIYWAK', 'BIZLOO', 'BUHVOP', 'BUPVEP', 'BUXZAX', 'CAVWEC', 'CIGXIA', 'COFYOM', 'COFYOM', 'COFYOM', 'COKNOH', 'COKNOH01', 'COXQOV', 'COXQOV', 'CUFMOG', 'CUVJUA', 'CUVJUA', 'DIJYED', 'DOVBIB', 'EBUPUO', 'EBUPUO', 'EDIMOT', 'EKIPAP01', 'ENATUJ', 'EQEHUE', 'EQIZAF', 'FAQLIV', 'FEBZUH10', 'FEKCEE', 'FENXAY', 'FIGTUL', 'FIGTUL', 'FIGZIG', 'FIGZIG', 'FIGZIG', 'FIGZOM', 'FIGZOM', 'FIGZOM', 'FIGZUS', 'FIGZUS', 'FINPUP01', 'FIYGAY', 'FODLAM02', 'FUZBUX', 'FUZBUX', 'FUZBUX', 'GASMUK', 'GEVPOM', 'GEVPOM', 'GUVZEE', 'GUVZII', 'HAVHAG', 'HAVHAG', 'HAVHAQ', 'HAVHAQ', 'HAWVIN', 'HAWVUZ', 'HEQVUU', 'HEQWAB', 'HITQOR', 'HITQOR', 'HOJHUM', 'HOMQEI', 'IDIWIB', 'IDIWOH', 'IDIXID', 'IDXID', 'IJATUI', 'IWIHON', 'JAPYEH', 'JAPYEH', 'JAPYIL', 'JAPYOR', 'JAPYUX', 'JAPZAE', 'JAPZEI', 'JAPZEI', 'JAPZIM', 'JAPZUY', 'JAPZUY', 'JEBWEV', 'JIMNUR', 'JIZJAF', 'JIZJEJ', 'JIZJIN', 'JIZJOT', 'JIZJUZ', 'JUBQEE', 'KAJZIH', 'KAKTIA01', 'KAKTIA01', 'KAWCES', 'KAWFUL', 'KAWFUL', 'KEPGES', 'KEPGIW', 'KEPGIW', 'KEPGIW', 'KERWIP', 'KESSIM', 'KESSIM', 'KEXZUI', 'KOCLEW', 'KOGNIE', 'KOGNIE', 'KOVLOC', 'KUTNUI', 'KUTNUI', 'LARRAA', 'LARRAA', 'LAVYIT', 'LIDWAX', 'LIDWAX', 'MAHSUK', 'MAHSUK01', 'MAJLOZ', 'MAPGUI', 'MAVLED', 'MELNEZ', 'MELNEZ', 'MIFQEZ', 'MIFQOJ', 'MIFQOJ', 'MITFON', 'MITSIS', 'MOBBOU', 'MOBBOU', 'MOHQOQ', 'MOHQOQ', 'MOYZAC', 'NAMTON', 'NAMTON', 'NAVRIO', 'NECBUT', 'NECBUT', 'NECCUU', 'NECCUU', 'NENNOK', 'NEZPOA', 'NEZPUG', 'NOJSUD', 'NUHWUJ', 'NUMLIQ', 'NUZXAI', 'NUZXAI', 'OJANES', 'OJANES', 'OLIKUR', 'ORIVUI', 'PEFHIS', 'PEHWEE', 'PEPVEM', 'PEPVEM', 'PETWOC', 'PETWUI', 'PETXAP', 'PIZHAJ', 'PURVIH', 'PURVIH', 'QAMTEG', 'QEJLID', 'QIDFOB', 'RAWFAZ', 'REKPUV', 'REKPUV', 'RERROW', 'RERROW', 'REYDUX', 'ROCKEZ', 'ROCKEZ', 'RUVHEX', 'SATHUS', 'SIBDUD', 'SIBDUD', 'SISMAL', 'SISMAL', 'SIYXIH', 'SOKKAH', 'SULPMS', 'TAZGEG', 'TAZGEG', 'TAZGEG', 'TCAZCO', 'TCAZCO', 'TCAZCO', 'TEDDUC', 'TEDDUC', 'TEDDUC', 'TEJFOG', 'TEPWIX', 'TEYLOB', 'TICMEY', 'TICMEY', 'UDACEH', 'UDOQAF', 'UDOQAF', 'UGARID', 'UGARID', 'VAYJOB', 'VEYJOB', 'VIGCET', 'VOGBAU', 'VOMMUH', 'VUNQUS', 'VUNQUS', 'VUNQUS', 'WAQFAY', 'WAQKIK', 'WAZKOZ', 'WODZEX', 'WOQKET', 'WUDLIQ', 'XAHREE', 'XAHREE', 'XAXPIX', 'XEDJUN', 'XEHVOW', 'XEHVOW', 'XOXTOW', 'XOXTUC', 'XUVDEZ', 'YAKFIZ', 'YAKFIZ', 'YAMLOQ', 'ZARBEZ', 'ZASTUK', 'ZASTUK', 'ZEJWIX', 'ZEJWOD', 'ZEJXAQ', 'ZEJXAQ', 'ZEJXEU', 'ZEQROE', 'ZIFTIU', 'ZITFIU', 'ZITMUN', 'RAXBAV', 'BAYMOF', 'GIMBIN', 'KIKPOM', 'VAHCEM', 'ZUQVUC', 'CAVXAB', 'EBAGAR', 'ACITAK', 'ZUVVUH', 'BERXAX', 'BIWRUX', 'ZICXOY', 'XUDJUB', 'ZASBEC', 'PEXRIU', 'TACJUE', 'SOSVAX', 'MATVEK', 'YUSKIH', 'SEBCUA', 'NAYCIZ', 'XAVJAF', 'YAZPOG', 'AQOPEB', 'BAQMIR', 'BIPLIX', 'ZEGFOG', 'KIFVOL', 'CAGROT', 'ROFDEV', 'JIVWUH', 'BIYWEO', 'AKIYUO', 'ROFCUK', 'TIWPEU', 'UFAXIJ', 'YALPOR', 'FUGCUF', 'YIPDOR', 'LOKJUR', 'TERBUQ', 'TAQDUN', 'AMUTEI', 'PEQXUF', 'YEJJUT', 'ROFDAR', 'BARGAF', 'FAXLOG', 'ZIPFOT', 'WALWEM', 'UCIDEQ', 'VIGQUA', 'XAHREE', 'WAZKOZ', 'ZOCLAE', 'EKINUH', 'FELHUZ', 'QICXEG', 'WUBLEK', 'ZERHAF', 'FARROH', 'ZEJXAQ', 'UHOGUT', 'XALXAJ', 'SISMAL', 'DEFCID', 'YEGLAZ', 'ZEJWIX', 'CUNTOV', 'FODLAM', 'BAWGEO', 'BUPHEA', 'OLELAS', 'DOCPOD', 'WOKJOW', 'WOQKET', 'WOKJAI', 'BEFZAP', 'VUQWAG', 'GATDAH', 'TAQDUN', 'WEZPEX', 'LEKFEM', 'BIJCUV', 'XALFUN', 'FAGWOA', 'TUQKUL', 'YEXBOS', 'XIHLIK', 'KIWDOJ', 'BALTUE', 'BOJSUO']
# -*- coding: utf-8 -*- URL = '127.0.0.1' PORT = 27017 DATABASE = 'MyFunctions' COLLECTION = 'FunctionCheckers' FILE_PATH = '../examples/functions.py' CATCHER = 'result' IMPORT_POST = True STATIC_POST = True FUNC_POST = True
url = '127.0.0.1' port = 27017 database = 'MyFunctions' collection = 'FunctionCheckers' file_path = '../examples/functions.py' catcher = 'result' import_post = True static_post = True func_post = True
""" =========== Exercise 1 ============= Using a list, create a shopping list of 5 items. Then print the whole list, and then each item individually. """ shopping_list = [] # Fill in with some values print(shopping_list) # Print the whole list print() # Figure out how to print individual values """ =========== Exercise 2 ============= Find something that you can eat that has nutrition facts on the label. Fill in the dictionary below with the info on the label and try printing specific information. If you can't find anything nearby you can use this example: https://www.donhummertrucking.com/media/cms/Nutrition_Facts_388AE27A88B67.png """ # When ready to work on these exercises uncomment below code # nutrition_facts = {} # Fill in with the nutrition facts from the label # print(nutrition_facts) # Print all the nutrition facts # print(nutrition_facts["value"]) # Uncomment this line and pick a value to print individually """ =========== Exercise 3 ============= Python has a function built in to allow you to take input from the command line and store it. The function is called input() and it takes one argument, which is the string to display when asking the user for input. Here is an example: ``` >> name = input('What is your name?: ') >> print(name) ``` Using the information about type casting take an input from the command line (which is always a string), convert it to an int and then double it and print it. i.e. if the user provides 21 then the program should print 42 """ # When ready to work on these exercises uncomment below code # age = input('What is your age?: ') # print(age * 2) # Find a way to convert the age to an int and multiply by 2
""" =========== Exercise 1 ============= Using a list, create a shopping list of 5 items. Then print the whole list, and then each item individually. """ shopping_list = [] print(shopping_list) print() "\n =========== Exercise 2 =============\n\n Find something that you can eat that has nutrition\n facts on the label. Fill in the dictionary below with\n the info on the label and try printing specific information.\n\n If you can't find anything nearby you can use this example: https://www.donhummertrucking.com/media/cms/Nutrition_Facts_388AE27A88B67.png\n" "\n =========== Exercise 3 =============\n\n Python has a function built in to allow you to\n take input from the command line and store it.\n\n The function is called input() and it takes one\n argument, which is the string to display when\n asking the user for input.\n\n\n Here is an example:\n ```\n >> name = input('What is your name?: ')\n\n >> print(name)\n ```\n\n Using the information about type casting take an input\n from the command line (which is always a string), convert\n it to an int and then double it and print it.\n\n i.e. if the user provides 21 then the program should print 42\n"
#Parsing and Extracting data= "From Stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008" atpos= data.find("@") print(atpos) atss= data.find(" ",atpos) #here it starts at 21 and then goes and find the next space print(atss) host= data[atpos+1: atss] #Now we are extracting the part that we are interested in print(host) #this prints uct.ac.za
data = 'From Stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' atpos = data.find('@') print(atpos) atss = data.find(' ', atpos) print(atss) host = data[atpos + 1:atss] print(host)
"""Code to add interactive highlighting of series in matplotlib plots.""" class SelectorCursor(object): """An abstract cursor that may traverse a sequence of fixed length in any order, repeatedly, and which includes a None position. Executes a notifier when a position becomes selected or deselected. """ def __init__(self, num_elems, cb_activate, cb_deactivate): self.num_elems = num_elems """Length of sequence.""" self.cb_activate = cb_activate """A callback function to be called as f(i, active=True) when an index i is activated. """ self.cb_deactivate = cb_deactivate """Analogous to above, but with active=False.""" self.cursor = None """Valid cursor indices go from 0 to num_elems - 1. None is also a valid index. """ def goto(self, i): """Go to the new index. No effect if cursor is currently i.""" if i == self.cursor: return if self.cursor is not None: self.cb_deactivate(self.cursor, active=False) self.cursor = i if self.cursor is not None: self.cb_activate(self.cursor, active=True) def changeby(self, offset): """Skip to an offset of the current position.""" states = [None] + list(range(0, self.num_elems)) i = states.index(self.cursor) i = (i + offset) % len(states) self.goto(states[i]) def next(self): self.changeby(1) def bulknext(self): self.changeby(10) def prev(self): self.changeby(-1) def bulkprev(self): self.changeby(-10) class LineSelector: """Utility class for modifying matplotlib artists to highlight selected series. """ def __init__(self, axes_list): """Construct to select from among lines of the given axes.""" # Matplotlib artists that need to be updated. self.lines = [] self.leglines = [] self.legtexts = [] for axes in axes_list: new_lines = [line for line in axes.get_lines() if line.get_label() != '_nolegend_'] leg = axes.get_legend() if leg is not None: new_leglines = leg.get_lines() new_legtexts = leg.get_texts() else: new_leglines = [] new_legtexts = [] assert len(new_lines) == len(new_leglines) == len(new_legtexts) self.lines.extend(new_lines) self.leglines.extend(new_leglines) self.legtexts.extend(new_legtexts) self.cursor = SelectorCursor( len(self.lines), self.markLine, self.unmarkLine) def markLine(self, i, active): if i == None: return line = self.lines[i] legline = self.leglines[i] legtext = self.legtexts[i] line.set_zorder(3) line.set_linewidth(3.0) legline.set_linewidth(3.0) legtext.set_color('blue') def unmarkLine(self, i, active): if i == None: return line = self.lines[i] legline = self.leglines[i] legtext = self.legtexts[i] line.set_zorder(2) line.set_linewidth(1.0) legline.set_linewidth(1.0) legtext.set_color('black') def handler(self, event): k = event.key actionmap = { 'down': self.cursor.next, 'up': self.cursor.prev, 'pagedown': self.cursor.bulknext, 'pageup': self.cursor.bulkprev, } if k not in actionmap: return actionmap[k]() event.canvas.draw() def add_lineselector(figure): """Add a line selector for all axes of the given figure. Return the mpl connection id for disconnection later. """ lineselector = LineSelector(figure.get_axes()) # Workaround for weird Heisenbug. The handler isn't reliably called # when it's a bound method, but is called if I use a wrapper for # some reason. def wrapper(event): lineselector.handler(event) return figure.canvas.mpl_connect('key_press_event', wrapper)
"""Code to add interactive highlighting of series in matplotlib plots.""" class Selectorcursor(object): """An abstract cursor that may traverse a sequence of fixed length in any order, repeatedly, and which includes a None position. Executes a notifier when a position becomes selected or deselected. """ def __init__(self, num_elems, cb_activate, cb_deactivate): self.num_elems = num_elems 'Length of sequence.' self.cb_activate = cb_activate 'A callback function to be called as f(i, active=True)\n when an index i is activated.\n ' self.cb_deactivate = cb_deactivate 'Analogous to above, but with active=False.' self.cursor = None 'Valid cursor indices go from 0 to num_elems - 1.\n None is also a valid index.\n ' def goto(self, i): """Go to the new index. No effect if cursor is currently i.""" if i == self.cursor: return if self.cursor is not None: self.cb_deactivate(self.cursor, active=False) self.cursor = i if self.cursor is not None: self.cb_activate(self.cursor, active=True) def changeby(self, offset): """Skip to an offset of the current position.""" states = [None] + list(range(0, self.num_elems)) i = states.index(self.cursor) i = (i + offset) % len(states) self.goto(states[i]) def next(self): self.changeby(1) def bulknext(self): self.changeby(10) def prev(self): self.changeby(-1) def bulkprev(self): self.changeby(-10) class Lineselector: """Utility class for modifying matplotlib artists to highlight selected series. """ def __init__(self, axes_list): """Construct to select from among lines of the given axes.""" self.lines = [] self.leglines = [] self.legtexts = [] for axes in axes_list: new_lines = [line for line in axes.get_lines() if line.get_label() != '_nolegend_'] leg = axes.get_legend() if leg is not None: new_leglines = leg.get_lines() new_legtexts = leg.get_texts() else: new_leglines = [] new_legtexts = [] assert len(new_lines) == len(new_leglines) == len(new_legtexts) self.lines.extend(new_lines) self.leglines.extend(new_leglines) self.legtexts.extend(new_legtexts) self.cursor = selector_cursor(len(self.lines), self.markLine, self.unmarkLine) def mark_line(self, i, active): if i == None: return line = self.lines[i] legline = self.leglines[i] legtext = self.legtexts[i] line.set_zorder(3) line.set_linewidth(3.0) legline.set_linewidth(3.0) legtext.set_color('blue') def unmark_line(self, i, active): if i == None: return line = self.lines[i] legline = self.leglines[i] legtext = self.legtexts[i] line.set_zorder(2) line.set_linewidth(1.0) legline.set_linewidth(1.0) legtext.set_color('black') def handler(self, event): k = event.key actionmap = {'down': self.cursor.next, 'up': self.cursor.prev, 'pagedown': self.cursor.bulknext, 'pageup': self.cursor.bulkprev} if k not in actionmap: return actionmap[k]() event.canvas.draw() def add_lineselector(figure): """Add a line selector for all axes of the given figure. Return the mpl connection id for disconnection later. """ lineselector = line_selector(figure.get_axes()) def wrapper(event): lineselector.handler(event) return figure.canvas.mpl_connect('key_press_event', wrapper)
# Solution def part1(data): stack = [] meta_sum = 0 gen = input_gen(data) for x in gen: if x != 0 or len(stack) % 2 == 1: stack.append(x) continue m = next(gen) while m > 0 or len(stack) > 0: for _ in range(m): meta_sum += next(gen) m = stack.pop() if len(stack) > 0 else 0 node = stack.pop() - 1 if len(stack) > 0 else 0 if node > 0: stack.append(node) stack.append(m) break return meta_sum def part2(data): gen = input_gen(data) children_count = next(gen) metadata_count = next(gen) root = Tree(None, children_count, metadata_count) current_node = root while True: children_count = next(gen) metadata_count = next(gen) new_node = Tree(current_node, children_count, metadata_count) current_node.children[current_node.index] = new_node current_node = new_node if children_count == 0: get_metadata(gen, current_node.metadata) while current_node.parent is not None: current_node = current_node.parent current_node.index += 1 if current_node.index < len(current_node.children): break get_metadata(gen, current_node.metadata) if current_node.parent is None and current_node.index == len(current_node.children): break return calculate_node_value(root) def input_gen(data): arr = data.split(' ') for x in arr: yield(int(x)) def get_metadata(gen, arr): for i in range(len(arr)): arr[i] = next(gen) def calculate_node_value(node): if len(node.metadata) == 0: return 0 if len(node.children) == 0: return sum(node.metadata) node_value = 0 for i in node.metadata: if i <= len(node.children): node_value += calculate_node_value(node.children[i - 1]) return node_value class Tree: def __init__(self, parent, children_count, metadata_count): self._parent = parent self._children = [None] * children_count self._metadata = [None] * metadata_count self._index = 0 @property def index(self): return self._index @index.setter def index(self, value): self._index = value @property def parent(self): return self._parent @property def children(self): return self._children @property def metadata(self): return self._metadata # Tests def test(expected, actual): assert expected == actual, 'Expected: %r, Actual: %r' % (expected, actual) test(138, part1('2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2')) test(66, part2('2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2')) # Solve real puzzle filename = 'data/day08.txt' data = [line.rstrip('\n') for line in open(filename, 'r')][0] print('Day 08, part 1: %r' % (part1(data))) print('Day 08, part 2: %r' % (part2(data)))
def part1(data): stack = [] meta_sum = 0 gen = input_gen(data) for x in gen: if x != 0 or len(stack) % 2 == 1: stack.append(x) continue m = next(gen) while m > 0 or len(stack) > 0: for _ in range(m): meta_sum += next(gen) m = stack.pop() if len(stack) > 0 else 0 node = stack.pop() - 1 if len(stack) > 0 else 0 if node > 0: stack.append(node) stack.append(m) break return meta_sum def part2(data): gen = input_gen(data) children_count = next(gen) metadata_count = next(gen) root = tree(None, children_count, metadata_count) current_node = root while True: children_count = next(gen) metadata_count = next(gen) new_node = tree(current_node, children_count, metadata_count) current_node.children[current_node.index] = new_node current_node = new_node if children_count == 0: get_metadata(gen, current_node.metadata) while current_node.parent is not None: current_node = current_node.parent current_node.index += 1 if current_node.index < len(current_node.children): break get_metadata(gen, current_node.metadata) if current_node.parent is None and current_node.index == len(current_node.children): break return calculate_node_value(root) def input_gen(data): arr = data.split(' ') for x in arr: yield int(x) def get_metadata(gen, arr): for i in range(len(arr)): arr[i] = next(gen) def calculate_node_value(node): if len(node.metadata) == 0: return 0 if len(node.children) == 0: return sum(node.metadata) node_value = 0 for i in node.metadata: if i <= len(node.children): node_value += calculate_node_value(node.children[i - 1]) return node_value class Tree: def __init__(self, parent, children_count, metadata_count): self._parent = parent self._children = [None] * children_count self._metadata = [None] * metadata_count self._index = 0 @property def index(self): return self._index @index.setter def index(self, value): self._index = value @property def parent(self): return self._parent @property def children(self): return self._children @property def metadata(self): return self._metadata def test(expected, actual): assert expected == actual, 'Expected: %r, Actual: %r' % (expected, actual) test(138, part1('2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2')) test(66, part2('2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2')) filename = 'data/day08.txt' data = [line.rstrip('\n') for line in open(filename, 'r')][0] print('Day 08, part 1: %r' % part1(data)) print('Day 08, part 2: %r' % part2(data))
""" In this problem, we need a structure to store which character occurs how many times. It is best to use a dict object; but here we will use only lists. We will keep counts in a list of two element lists. For example: [["a",3],["b",5],["z",3]] """ def add_char(store,char): """add a character to the count store""" already_there = False for x in store: if x[0] == char: x[1] = x[1] + 1 already_there = True if not already_there: store.append([char,1]) def draw_histo(store): for x in store: print(x[0],x[1]*'*') input = input("Give me a string: ") count_store = [] for x in input: add_char(count_store,x) draw_histo(count_store)
""" In this problem, we need a structure to store which character occurs how many times. It is best to use a dict object; but here we will use only lists. We will keep counts in a list of two element lists. For example: [["a",3],["b",5],["z",3]] """ def add_char(store, char): """add a character to the count store""" already_there = False for x in store: if x[0] == char: x[1] = x[1] + 1 already_there = True if not already_there: store.append([char, 1]) def draw_histo(store): for x in store: print(x[0], x[1] * '*') input = input('Give me a string: ') count_store = [] for x in input: add_char(count_store, x) draw_histo(count_store)
## IMPORTANT: Must be loaded after `02-service-common.py ## announcement service service_env = dict() service_url = f'{hub_hostname}:{service_port}' if c.JupyterHub.internal_ssl: # if we are using end-to-end mTLS, then pass # certs to service and set scheme to `https` # TODO: Generate certs automatically PKI_STORE=c.JupyterHub.internal_certs_location service_env = { 'JUPYTERHUB_SSL_CERTFILE': f'{PKI_STORE}/hub-internal/hub-internal.crt', 'JUPYTERHUB_SSL_KEYFILE': f'{PKI_STORE}/hub-internal/hub-internal.key', 'JUPYTERHUB_SSL_CLIENT_CA': f'{PKI_STORE}/hub-ca_trust.crt', } service_url = f'https://{service_url}' else: # if not, set schema to `http` service_url = f'http://{service_url}' pass # NOTE: you must generate certs for services c.JupyterHub.services += [ { # Hub-wide announcments service 'name': 'announcement', 'url': service_url, 'command': [ sys.executable, '-m', 'jupyterhub_announcement', f'--AnnouncementService.fixed_message="Welcome to the {hub_id} JupyterHub server!"', f'--AnnouncementService.port={service_port}', f'--AnnouncementQueue.persist_path=announcements.json', f'--AnnouncementService.template_paths=["{hub_path}/share/jupyterhub/templates","{hub_path}/templates"]' ], 'environment': service_env } ] # increment service port service_port += 1
service_env = dict() service_url = f'{hub_hostname}:{service_port}' if c.JupyterHub.internal_ssl: pki_store = c.JupyterHub.internal_certs_location service_env = {'JUPYTERHUB_SSL_CERTFILE': f'{PKI_STORE}/hub-internal/hub-internal.crt', 'JUPYTERHUB_SSL_KEYFILE': f'{PKI_STORE}/hub-internal/hub-internal.key', 'JUPYTERHUB_SSL_CLIENT_CA': f'{PKI_STORE}/hub-ca_trust.crt'} service_url = f'https://{service_url}' else: service_url = f'http://{service_url}' pass c.JupyterHub.services += [{'name': 'announcement', 'url': service_url, 'command': [sys.executable, '-m', 'jupyterhub_announcement', f'--AnnouncementService.fixed_message="Welcome to the {hub_id} JupyterHub server!"', f'--AnnouncementService.port={service_port}', f'--AnnouncementQueue.persist_path=announcements.json', f'--AnnouncementService.template_paths=["{hub_path}/share/jupyterhub/templates","{hub_path}/templates"]'], 'environment': service_env}] service_port += 1
def test_binary_byte_str_code(fake): assert isinstance(fake.binary_byte_str(code=True), str) def test_decimal_byte_str_code(fake): assert isinstance(fake.decimal_byte_str(code=True), str) def test_binary_byte_str(fake): assert isinstance(fake.binary_byte_str(), str) def test_decimal_byte_str(fake): assert isinstance(fake.decimal_byte_str(), str) def test_nibble(fake): assert len(fake.nibble()) == 4 assert isinstance(fake.nibble(), str) def test_octet(fake): assert len(fake.octet()) == 8 assert isinstance(fake.octet(), str) def test_byte(fake): assert len(fake.byte()) == 8 assert isinstance(fake.byte(), str) def test_word(fake): assert len(fake.word()) == 16 assert isinstance(fake.word(), str)
def test_binary_byte_str_code(fake): assert isinstance(fake.binary_byte_str(code=True), str) def test_decimal_byte_str_code(fake): assert isinstance(fake.decimal_byte_str(code=True), str) def test_binary_byte_str(fake): assert isinstance(fake.binary_byte_str(), str) def test_decimal_byte_str(fake): assert isinstance(fake.decimal_byte_str(), str) def test_nibble(fake): assert len(fake.nibble()) == 4 assert isinstance(fake.nibble(), str) def test_octet(fake): assert len(fake.octet()) == 8 assert isinstance(fake.octet(), str) def test_byte(fake): assert len(fake.byte()) == 8 assert isinstance(fake.byte(), str) def test_word(fake): assert len(fake.word()) == 16 assert isinstance(fake.word(), str)
#Classe usada para erros gerais relacionados as arestas class ArestasIncompatibilityException(Exception): def __init__(self,message :str): super().__init__(message)
class Arestasincompatibilityexception(Exception): def __init__(self, message: str): super().__init__(message)
# -*- coding: utf-8 -*- """ @author: krakowiakpawel9@gmail.com @site: e-smartdata.org """ class Drzewo: nazwa = 'Sosna' wiek = 40 wysokosc = 25 drzewo_1 = Drzewo() drzewo_2 = Drzewo() # %% print(id(drzewo_1)) print(id(drzewo_2)) # %% dir(drzewo_1) # %% drzewo_1.nazwa drzewo_1.wiek drzewo_1.wysokosc # %% drzewo_2.nazwa drzewo_2.wiek # %% drzewo_1.stan = 'dobry' print(dir(drzewo_2)) # %% Drzewo.miejsce = 'las' # %% # print(dir(drzewo_2)) # print(drzewo_2.miejsce) drzewo_2.miejsce = 'park' print(drzewo_2.miejsce)
""" @author: krakowiakpawel9@gmail.com @site: e-smartdata.org """ class Drzewo: nazwa = 'Sosna' wiek = 40 wysokosc = 25 drzewo_1 = drzewo() drzewo_2 = drzewo() print(id(drzewo_1)) print(id(drzewo_2)) dir(drzewo_1) drzewo_1.nazwa drzewo_1.wiek drzewo_1.wysokosc drzewo_2.nazwa drzewo_2.wiek drzewo_1.stan = 'dobry' print(dir(drzewo_2)) Drzewo.miejsce = 'las' drzewo_2.miejsce = 'park' print(drzewo_2.miejsce)
#Embedded file name: /Users/versonator/Hudson/live/Projects/AppLive/Resources/MIDI Remote Scripts/LPD8/consts.py """ The following consts should be substituted with the Sys Ex messages for requesting a controller's ID response and that response to allow for automatic lookup""" ID_REQUEST = 0 ID_RESP = 0 GENERIC_STOP = 23 GENERIC_PLAY = 24 GENERIC_REC = 25 GENERIC_LOOP = 20 GENERIC_RWD = 21 GENERIC_FFWD = 22 GENERIC_TRANSPORT = (GENERIC_STOP, GENERIC_PLAY, GENERIC_REC, GENERIC_LOOP, GENERIC_RWD, GENERIC_FFWD) # 16! Device encoders GENERIC_ENC1 = 56 GENERIC_ENC2 = 57 GENERIC_ENC3 = 58 GENERIC_ENC4 = 59 GENERIC_ENC5 = 60 GENERIC_ENC6 = 61 GENERIC_ENC7 = 62 GENERIC_ENC8 = 63 GENERIC_ENC9 = 64 GENERIC_ENC10 = 65 GENERIC_ENC11 = 66 GENERIC_ENC12 = 67 GENERIC_ENC13 = 68 GENERIC_ENC14 = 69 GENERIC_ENC15 = 70 GENERIC_ENC16 = 71 GENERIC_ENCODERS = (GENERIC_ENC1, GENERIC_ENC2, GENERIC_ENC3, GENERIC_ENC4, GENERIC_ENC5, GENERIC_ENC6, GENERIC_ENC7, GENERIC_ENC8, GENERIC_ENC9, GENERIC_ENC10, GENERIC_ENC11, GENERIC_ENC12, GENERIC_ENC13, GENERIC_ENC14, GENERIC_ENC15, GENERIC_ENC16) GENERIC_SLI1 = 110 GENERIC_SLI2 = 111 GENERIC_SLI3 = 112 GENERIC_SLI4 = 113 GENERIC_SLI5 = 114 GENERIC_SLI6 = 115 GENERIC_SLI7 = 116 GENERIC_SLI8 = 117 GENERIC_SLIDERS = (GENERIC_SLI1, GENERIC_SLI2, GENERIC_SLI3, GENERIC_SLI4, GENERIC_SLI5, GENERIC_SLI6, GENERIC_SLI7, GENERIC_SLI8) GENERIC_BUT1 = 52 GENERIC_BUT2 = 53 GENERIC_BUT3 = 54 GENERIC_BUT4 = 55 GENERIC_BUT5 = 56 GENERIC_BUT6 = 57 GENERIC_BUT7 = 58 GENERIC_BUT8 = 59 GENERIC_BUT9 = 60 GENERIC_BUTTONS = (GENERIC_BUT1, GENERIC_BUT2, GENERIC_BUT3, GENERIC_BUT4, GENERIC_BUT5, GENERIC_BUT6, GENERIC_BUT7, GENERIC_BUT8) GENERIC_PAD1 = 80 GENERIC_PAD2 = 81 GENERIC_PAD3 = 82 GENERIC_PAD4 = 83 GENERIC_PAD5 = 85 GENERIC_PAD6 = 86 GENERIC_PAD7 = 87 GENERIC_PAD8 = 88 GENERIC_PADS = (GENERIC_PAD1, GENERIC_PAD2, GENERIC_PAD3, GENERIC_PAD4, GENERIC_PAD5, GENERIC_PAD6, GENERIC_PAD7, GENERIC_PAD8)
""" The following consts should be substituted with the Sys Ex messages for requesting a controller's ID response and that response to allow for automatic lookup""" id_request = 0 id_resp = 0 generic_stop = 23 generic_play = 24 generic_rec = 25 generic_loop = 20 generic_rwd = 21 generic_ffwd = 22 generic_transport = (GENERIC_STOP, GENERIC_PLAY, GENERIC_REC, GENERIC_LOOP, GENERIC_RWD, GENERIC_FFWD) generic_enc1 = 56 generic_enc2 = 57 generic_enc3 = 58 generic_enc4 = 59 generic_enc5 = 60 generic_enc6 = 61 generic_enc7 = 62 generic_enc8 = 63 generic_enc9 = 64 generic_enc10 = 65 generic_enc11 = 66 generic_enc12 = 67 generic_enc13 = 68 generic_enc14 = 69 generic_enc15 = 70 generic_enc16 = 71 generic_encoders = (GENERIC_ENC1, GENERIC_ENC2, GENERIC_ENC3, GENERIC_ENC4, GENERIC_ENC5, GENERIC_ENC6, GENERIC_ENC7, GENERIC_ENC8, GENERIC_ENC9, GENERIC_ENC10, GENERIC_ENC11, GENERIC_ENC12, GENERIC_ENC13, GENERIC_ENC14, GENERIC_ENC15, GENERIC_ENC16) generic_sli1 = 110 generic_sli2 = 111 generic_sli3 = 112 generic_sli4 = 113 generic_sli5 = 114 generic_sli6 = 115 generic_sli7 = 116 generic_sli8 = 117 generic_sliders = (GENERIC_SLI1, GENERIC_SLI2, GENERIC_SLI3, GENERIC_SLI4, GENERIC_SLI5, GENERIC_SLI6, GENERIC_SLI7, GENERIC_SLI8) generic_but1 = 52 generic_but2 = 53 generic_but3 = 54 generic_but4 = 55 generic_but5 = 56 generic_but6 = 57 generic_but7 = 58 generic_but8 = 59 generic_but9 = 60 generic_buttons = (GENERIC_BUT1, GENERIC_BUT2, GENERIC_BUT3, GENERIC_BUT4, GENERIC_BUT5, GENERIC_BUT6, GENERIC_BUT7, GENERIC_BUT8) generic_pad1 = 80 generic_pad2 = 81 generic_pad3 = 82 generic_pad4 = 83 generic_pad5 = 85 generic_pad6 = 86 generic_pad7 = 87 generic_pad8 = 88 generic_pads = (GENERIC_PAD1, GENERIC_PAD2, GENERIC_PAD3, GENERIC_PAD4, GENERIC_PAD5, GENERIC_PAD6, GENERIC_PAD7, GENERIC_PAD8)
#Program 20 #Write a program to write roll no, name and marks of 'n' students in a data file "marks.dat" #Name: Vikhyat Jagini #Class: 12 #Date of Execution: 26/08/2021 n=int(input("Enter the number of students you want to store data of in the data file:")) f=open(r"C:\Python\Class 12 python\Lab Programs\BinaryFiles\marks.dat",'a') for i in range(n): print("Enter details of student", (i+1),"below") rol=int(input("Enter roll no of student:")) name=input("Enter name of student:") marks=float(input("Enter marks of student:")) rec=str(rol)+","+name+","+str(marks)+"\n" f.write(rec) f.close()
n = int(input('Enter the number of students you want to store data of in the data file:')) f = open('C:\\Python\\Class 12 python\\Lab Programs\\BinaryFiles\\marks.dat', 'a') for i in range(n): print('Enter details of student', i + 1, 'below') rol = int(input('Enter roll no of student:')) name = input('Enter name of student:') marks = float(input('Enter marks of student:')) rec = str(rol) + ',' + name + ',' + str(marks) + '\n' f.write(rec) f.close()
def is_xpath_selector(selector): """ A basic method to determine if a selector is an xpath selector. """ if ( selector.startswith("/") or selector.startswith("./") or selector.startswith("(") ): return True return False def is_link_text_selector(selector): """ A basic method to determine if a selector is a link text selector. """ if ( selector.startswith("link=") or selector.startswith("link_text=") or selector.startswith("text=") ): return True return False def is_partial_link_text_selector(selector): """ A basic method to determine if a selector is a partial link text selector. """ if ( selector.startswith("partial_link=") or selector.startswith("partial_link_text=") or selector.startswith("partial_text=") or selector.startswith("p_link=") or selector.startswith("p_link_text=") or selector.startswith("p_text=") ): return True return False def is_name_selector(selector): """ A basic method to determine if a selector is a name selector. """ if selector.startswith("name=") or selector.startswith("&"): return True return False def get_link_text_from_selector(selector): """ A basic method to get the link text from a link text selector. """ if selector.startswith("link="): return selector[len("link="):] elif selector.startswith("link_text="): return selector[len("link_text="):] elif selector.startswith("text="): return selector[len("text="):] return selector def get_partial_link_text_from_selector(selector): """ A basic method to get the partial link text from a partial link selector. """ if selector.startswith("partial_link="): return selector[len("partial_link="):] elif selector.startswith("partial_link_text="): return selector[len("partial_link_text="):] elif selector.startswith("partial_text="): return selector[len("partial_text="):] elif selector.startswith("p_link="): return selector[len("p_link="):] elif selector.startswith("p_link_text="): return selector[len("p_link_text="):] elif selector.startswith("p_text="): return selector[len("p_text="):] return selector def get_name_from_selector(selector): """ A basic method to get the name from a name selector. """ if selector.startswith("name="): return selector[len("name="):] if selector.startswith("&"): return selector[len("&"):] return selector def is_id_selector(selector): """ A basic method to determine whether a ID selector or not """ if ":id" in selector: return True return False
def is_xpath_selector(selector): """ A basic method to determine if a selector is an xpath selector. """ if selector.startswith('/') or selector.startswith('./') or selector.startswith('('): return True return False def is_link_text_selector(selector): """ A basic method to determine if a selector is a link text selector. """ if selector.startswith('link=') or selector.startswith('link_text=') or selector.startswith('text='): return True return False def is_partial_link_text_selector(selector): """ A basic method to determine if a selector is a partial link text selector. """ if selector.startswith('partial_link=') or selector.startswith('partial_link_text=') or selector.startswith('partial_text=') or selector.startswith('p_link=') or selector.startswith('p_link_text=') or selector.startswith('p_text='): return True return False def is_name_selector(selector): """ A basic method to determine if a selector is a name selector. """ if selector.startswith('name=') or selector.startswith('&'): return True return False def get_link_text_from_selector(selector): """ A basic method to get the link text from a link text selector. """ if selector.startswith('link='): return selector[len('link='):] elif selector.startswith('link_text='): return selector[len('link_text='):] elif selector.startswith('text='): return selector[len('text='):] return selector def get_partial_link_text_from_selector(selector): """ A basic method to get the partial link text from a partial link selector. """ if selector.startswith('partial_link='): return selector[len('partial_link='):] elif selector.startswith('partial_link_text='): return selector[len('partial_link_text='):] elif selector.startswith('partial_text='): return selector[len('partial_text='):] elif selector.startswith('p_link='): return selector[len('p_link='):] elif selector.startswith('p_link_text='): return selector[len('p_link_text='):] elif selector.startswith('p_text='): return selector[len('p_text='):] return selector def get_name_from_selector(selector): """ A basic method to get the name from a name selector. """ if selector.startswith('name='): return selector[len('name='):] if selector.startswith('&'): return selector[len('&'):] return selector def is_id_selector(selector): """ A basic method to determine whether a ID selector or not """ if ':id' in selector: return True return False
# Qutebrowser config # Sessions c.auto_save.session = True c.session.lazy_restore = True # Tabs c.tabs.position = 'left' c.tabs.width = 200 c.tabs.new_position.unrelated = 'next' c.tabs.background = True # Hints c.hints.mode = 'number' c.hints.auto_follow = 'full-match' c.content.pdfjs = True c.content.javascript.enabled = False c.content.javascript.can_access_clipboard = True # Use user agent of upstream browser (Chromium) {{{ # to reduce fingerprinting and compatibility issues c.content.headers.user_agent = ( 'Mozilla/5.0 ({os_info}) ' 'AppleWebKit/{webkit_version} (KHTML, like Gecko) ' '{upstream_browser_key}/{upstream_browser_version} Safari/{webkit_version}' ) # }}} c.editor.command = ['xterm', '-e', 'vim', '{file}', '-c', 'normal {line}G{column0}l'] # Search {{{ c.url.searchengines['ddg'] = c.url.searchengines['DEFAULT'] c.url.auto_search = 'never' c.url.open_base_url = True config.bind('so', 'set-cmd-text -s :open -- ddg') config.bind('sO', 'set-cmd-text -s :open -t -- ddg') config.bind('spp', 'open -- ddg {clipboard}') config.bind('spP', 'open -- ddg {primary}') config.bind('sPp', 'open -t -- ddg {clipboard}') config.bind('sPP', 'open -t -- ddg {primary}') # }}} # Bindings for controlling adblock whitelist {{{ config.bind('tbh', 'config-cycle -p -t -u *://{url:host}/* content.host_blocking.enabled ;; reload') config.bind('tbH', 'config-cycle -p -t -u *://*.{url:host}/* content.host_blocking.enabled ;; reload') config.bind('tBh', 'config-cycle -p -u *://{url:host}/* content.host_blocking.enabled ;; reload') config.bind('tBH', 'config-cycle -p -u *://*.{url:host}/* content.host_blocking.enabled ;; reload') # }}} # Aliases {{{ # Wayback Machine {{{ c.aliases['wayback'] = 'spawn -u archive -t lookup wayback' c.aliases['wayback!'] = 'spawn -u archive lookup wayback' c.aliases['waybacksave'] = 'spawn -u archive -b save wayback' c.aliases['waybacksave!'] = 'spawn -u archive save wayback' c.aliases['wb'] = c.aliases['wayback'] c.aliases['wb!'] = c.aliases['wayback!'] c.aliases['wbs'] = c.aliases['waybacksave'] c.aliases['wbs!'] = c.aliases['waybacksave!'] # }}} # archive.today {{{ c.aliases['archive'] = 'spawn -u archive -t lookup archive.today' c.aliases['archive!'] = 'spawn -u archive lookup archive.today' c.aliases['archivesave'] = 'spawn -u archive -b save archive.today' c.aliases['archivesave!'] = 'spawn -u archive save archive.today' c.aliases['ar'] = c.aliases['archive'] c.aliases['ar!'] = c.aliases['archive!'] c.aliases['ars'] = c.aliases['archivesave'] c.aliases['ars!'] = c.aliases['archivesave!'] # }}} # Invidious {{{ c.aliases['invidious'] = 'spawn -u invidious' c.aliases['inv'] = c.aliases['invidious'] # }}} c.aliases['newtab'] = 'open -t about:blank' c.aliases['nt'] = c.aliases['newtab'] c.aliases['h'] = 'help' c.aliases['Help'] = 'help -t' c.aliases['H'] = c.aliases['Help'] # }}} config.load_autoconfig() # vim: set fdm=marker:
c.auto_save.session = True c.session.lazy_restore = True c.tabs.position = 'left' c.tabs.width = 200 c.tabs.new_position.unrelated = 'next' c.tabs.background = True c.hints.mode = 'number' c.hints.auto_follow = 'full-match' c.content.pdfjs = True c.content.javascript.enabled = False c.content.javascript.can_access_clipboard = True c.content.headers.user_agent = 'Mozilla/5.0 ({os_info}) AppleWebKit/{webkit_version} (KHTML, like Gecko) {upstream_browser_key}/{upstream_browser_version} Safari/{webkit_version}' c.editor.command = ['xterm', '-e', 'vim', '{file}', '-c', 'normal {line}G{column0}l'] c.url.searchengines['ddg'] = c.url.searchengines['DEFAULT'] c.url.auto_search = 'never' c.url.open_base_url = True config.bind('so', 'set-cmd-text -s :open -- ddg') config.bind('sO', 'set-cmd-text -s :open -t -- ddg') config.bind('spp', 'open -- ddg {clipboard}') config.bind('spP', 'open -- ddg {primary}') config.bind('sPp', 'open -t -- ddg {clipboard}') config.bind('sPP', 'open -t -- ddg {primary}') config.bind('tbh', 'config-cycle -p -t -u *://{url:host}/* content.host_blocking.enabled ;; reload') config.bind('tbH', 'config-cycle -p -t -u *://*.{url:host}/* content.host_blocking.enabled ;; reload') config.bind('tBh', 'config-cycle -p -u *://{url:host}/* content.host_blocking.enabled ;; reload') config.bind('tBH', 'config-cycle -p -u *://*.{url:host}/* content.host_blocking.enabled ;; reload') c.aliases['wayback'] = 'spawn -u archive -t lookup wayback' c.aliases['wayback!'] = 'spawn -u archive lookup wayback' c.aliases['waybacksave'] = 'spawn -u archive -b save wayback' c.aliases['waybacksave!'] = 'spawn -u archive save wayback' c.aliases['wb'] = c.aliases['wayback'] c.aliases['wb!'] = c.aliases['wayback!'] c.aliases['wbs'] = c.aliases['waybacksave'] c.aliases['wbs!'] = c.aliases['waybacksave!'] c.aliases['archive'] = 'spawn -u archive -t lookup archive.today' c.aliases['archive!'] = 'spawn -u archive lookup archive.today' c.aliases['archivesave'] = 'spawn -u archive -b save archive.today' c.aliases['archivesave!'] = 'spawn -u archive save archive.today' c.aliases['ar'] = c.aliases['archive'] c.aliases['ar!'] = c.aliases['archive!'] c.aliases['ars'] = c.aliases['archivesave'] c.aliases['ars!'] = c.aliases['archivesave!'] c.aliases['invidious'] = 'spawn -u invidious' c.aliases['inv'] = c.aliases['invidious'] c.aliases['newtab'] = 'open -t about:blank' c.aliases['nt'] = c.aliases['newtab'] c.aliases['h'] = 'help' c.aliases['Help'] = 'help -t' c.aliases['H'] = c.aliases['Help'] config.load_autoconfig()
#!/usr/bin/env python3 """ Module with function to slice a matrix """ def np_slice(matrix, axes={}): """ Slices a matrix along a specific axes Returns the new matrix """ return matrix[-3:, -3:]
""" Module with function to slice a matrix """ def np_slice(matrix, axes={}): """ Slices a matrix along a specific axes Returns the new matrix """ return matrix[-3:, -3:]
class RichTextBoxSelectionTypes(Enum, IComparable, IFormattable, IConvertible): """ Specifies the type of selection in a System.Windows.Forms.RichTextBox control. enum (flags) RichTextBoxSelectionTypes,values: Empty (0),MultiChar (4),MultiObject (8),Object (2),Text (1) """ def __eq__(self, *args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self, *args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self, *args): pass def __gt__(self, *args): pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self, *args): pass def __lt__(self, *args): pass def __ne__(self, *args): pass def __reduce_ex__(self, *args): pass def __str__(self, *args): pass Empty = None MultiChar = None MultiObject = None Object = None Text = None value__ = None
class Richtextboxselectiontypes(Enum, IComparable, IFormattable, IConvertible): """ Specifies the type of selection in a System.Windows.Forms.RichTextBox control. enum (flags) RichTextBoxSelectionTypes,values: Empty (0),MultiChar (4),MultiObject (8),Object (2),Text (1) """ def __eq__(self, *args): """ x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """ pass def __format__(self, *args): """ __format__(formattable: IFormattable,format: str) -> str """ pass def __ge__(self, *args): pass def __gt__(self, *args): pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self, *args): pass def __lt__(self, *args): pass def __ne__(self, *args): pass def __reduce_ex__(self, *args): pass def __str__(self, *args): pass empty = None multi_char = None multi_object = None object = None text = None value__ = None
CODE_GAP = '-' CODE_BACKGROUND = '-' class State: """ Node in the HMM architecture, with emission probability """ def __init__(self, emission, module_id, state_id): """ :param emission: Multinomial distribution of nucleotide generation, one float value for each nucleotide :param module_id: Id of the module which contains the state :param state_id: Id of the state in the ordered state sequence """ self.emission = emission self.module_id = module_id self.state_id = state_id def is_background(self): """ Specify, if state is outside primers and motifs and emits random nucleotides without preference :return: True, if state is background type """ return False def is_insert(self): """ Specify, if state is inside primers or motifs and emits random nucleotides without preference to simulate insertions between key states :return: True, if state is insert type """ return False def is_motif(self): """ Specify, if state is in motif sequence with preferred nucleotide in emission probabilities :return: True, if state is motif type """ return False def is_sequence(self): """ Specify, if state is in primer sequence with preferred nucleotide in emission probabilities :return: True, if state is sequence type """ return False def is_key(self): """ Specify, if state has specified nucleotide that is preferred in emission probabilities :return: True, if state is key type """ return False def is_last_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return True def is_first_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return True class KeyState(State): """ State with specified nucleotide that is preferred in emission probabilities """ def __init__(self, nucleotide, emission, module_id, state_id, first, last): State.__init__(self, emission, module_id, state_id) self.nucleotide = nucleotide self.first = first self.last = last def __str__(self): return self.nucleotide.lower() def is_sequence(self): return True def is_key(self): return True def is_first_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return self.first def is_last_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return self.last class MotifState(KeyState): """ State in motif sequence with preferred nucleotide in emission probabilities """ def __init__(self, nucleotide, emission, module_id, state_id, first, last): KeyState.__init__(self, nucleotide, emission, module_id, state_id, first, last) self.module_id = module_id def __str__(self): return self.nucleotide.upper() def is_motif(self): return True class SequenceState(KeyState): """ State in primer sequence with preferred nucleotide in emission probabilities """ def __init__(self, nucleotide, emission, module_id, state_id, first, last): KeyState.__init__(self, nucleotide, emission, module_id, state_id, True, True) self.module_id = module_id def __str__(self): return self.nucleotide.lower() def is_sequence(self): return True class BackgroundState(State): """ State outside primers and motifs, that emits random nucleotides without preference """ def __init__(self, emission, state_id): State.__init__(self, emission, CODE_BACKGROUND, state_id) def __str__(self): return CODE_GAP def is_background(self): return True class InsertState(State): """ State inside primers or motifs, that emits random nucleotides without preference to simulate insertions between key states """ def __init__(self, emission, module_id, state_id): State.__init__(self, emission, module_id, state_id) def __str__(self): return CODE_GAP def is_insert(self): return True
code_gap = '-' code_background = '-' class State: """ Node in the HMM architecture, with emission probability """ def __init__(self, emission, module_id, state_id): """ :param emission: Multinomial distribution of nucleotide generation, one float value for each nucleotide :param module_id: Id of the module which contains the state :param state_id: Id of the state in the ordered state sequence """ self.emission = emission self.module_id = module_id self.state_id = state_id def is_background(self): """ Specify, if state is outside primers and motifs and emits random nucleotides without preference :return: True, if state is background type """ return False def is_insert(self): """ Specify, if state is inside primers or motifs and emits random nucleotides without preference to simulate insertions between key states :return: True, if state is insert type """ return False def is_motif(self): """ Specify, if state is in motif sequence with preferred nucleotide in emission probabilities :return: True, if state is motif type """ return False def is_sequence(self): """ Specify, if state is in primer sequence with preferred nucleotide in emission probabilities :return: True, if state is sequence type """ return False def is_key(self): """ Specify, if state has specified nucleotide that is preferred in emission probabilities :return: True, if state is key type """ return False def is_last_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return True def is_first_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return True class Keystate(State): """ State with specified nucleotide that is preferred in emission probabilities """ def __init__(self, nucleotide, emission, module_id, state_id, first, last): State.__init__(self, emission, module_id, state_id) self.nucleotide = nucleotide self.first = first self.last = last def __str__(self): return self.nucleotide.lower() def is_sequence(self): return True def is_key(self): return True def is_first_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return self.first def is_last_in_module(self): """ Is this State last in the module? :return: True, if it is last - only for MotifStates relevant """ return self.last class Motifstate(KeyState): """ State in motif sequence with preferred nucleotide in emission probabilities """ def __init__(self, nucleotide, emission, module_id, state_id, first, last): KeyState.__init__(self, nucleotide, emission, module_id, state_id, first, last) self.module_id = module_id def __str__(self): return self.nucleotide.upper() def is_motif(self): return True class Sequencestate(KeyState): """ State in primer sequence with preferred nucleotide in emission probabilities """ def __init__(self, nucleotide, emission, module_id, state_id, first, last): KeyState.__init__(self, nucleotide, emission, module_id, state_id, True, True) self.module_id = module_id def __str__(self): return self.nucleotide.lower() def is_sequence(self): return True class Backgroundstate(State): """ State outside primers and motifs, that emits random nucleotides without preference """ def __init__(self, emission, state_id): State.__init__(self, emission, CODE_BACKGROUND, state_id) def __str__(self): return CODE_GAP def is_background(self): return True class Insertstate(State): """ State inside primers or motifs, that emits random nucleotides without preference to simulate insertions between key states """ def __init__(self, emission, module_id, state_id): State.__init__(self, emission, module_id, state_id) def __str__(self): return CODE_GAP def is_insert(self): return True
def clean_string(s): result=[] for i in s: if i=="#": if result: result.pop(-1) else: result.append(i) return "".join(result)
def clean_string(s): result = [] for i in s: if i == '#': if result: result.pop(-1) else: result.append(i) return ''.join(result)
def dimensoes(matriz): li = len(matriz) c = 1 for i in matriz: c = len(i) return li, c def soma_matrizes(m1, m2): l, c = dimensoes(m1) if dimensoes(m1) == dimensoes(m2): m3 = m1 for i in range(0, l): for col in range(0, c): m3[i][col] = m1[i][col] + m2[i][col] return m3 else: return False
def dimensoes(matriz): li = len(matriz) c = 1 for i in matriz: c = len(i) return (li, c) def soma_matrizes(m1, m2): (l, c) = dimensoes(m1) if dimensoes(m1) == dimensoes(m2): m3 = m1 for i in range(0, l): for col in range(0, c): m3[i][col] = m1[i][col] + m2[i][col] return m3 else: return False
"""Sorting Algorithms config.""" FILES_REPO = "files/" IN_REPO = "files/in/" OUT_REPO = "files/out/" LOGS_REPO = "files/out/logs/" SEPARATOR = " - " STR_SIZE = 50 STR_NUMBER = 50 MAIN_DESCRIPTION = 'Sorting Algorithms' ALGORITHM_DESCRIPTION = 'execute sorting algorithm (insertionsort, \ heapsort, \ mergesort, \ quicksort, \ radixsort, \ selectionsort, \ shellsort)' NUMBER_DESCRIPTION = 'number of input values' ORDER_DESCRIPTION = 'order of input values (crescent, decreasing, random)' SIZE_DESCRIPTION = 'size of input values (small, large)'
"""Sorting Algorithms config.""" files_repo = 'files/' in_repo = 'files/in/' out_repo = 'files/out/' logs_repo = 'files/out/logs/' separator = ' - ' str_size = 50 str_number = 50 main_description = 'Sorting Algorithms' algorithm_description = 'execute sorting algorithm (insertionsort, heapsort, mergesort, quicksort, radixsort, selectionsort, shellsort)' number_description = 'number of input values' order_description = 'order of input values (crescent, decreasing, random)' size_description = 'size of input values (small, large)'
""" Description: A demo of the ord() and chr() functions in python\ for ASCII table reference, please visit http://www.asciitable.com/ """ __author__ = "Canadian Coding" # chr() takes an int and returns the corresponding ASCII character print(chr(65)) # prints 'A' print(chr(97)) # prints 'a' # ord() takes a one letter string and returns the corresponding ASCII number as an int print(ord("A")) # Prints 65 print(ord("a")) # Prints 97 def alphabet_by_ord(): """Goes through and prints the uppercase alphabet using ord() and chr() """ current_letter = ord('A') # Initialize to A for letter in range(1,27): #Iterates over all 27 letters of the alphabet print(chr(current_letter)) current_letter += 1 # Move to next letters ordinance def capitalize_by_ord(letter = "a"): """Converts lowercase characters to uppercase using ord() and chr() Returns: (str): A message with the upper and original case version of the letter """ uppercase_letter = ord(letter) - 32 # Decreasing letters ordinance by offset return "Letter {} converted to {}".format(letter, chr(uppercase_letter)) alphabet_by_ord() print(capitalize_by_ord())
""" Description: A demo of the ord() and chr() functions in python for ASCII table reference, please visit http://www.asciitable.com/ """ __author__ = 'Canadian Coding' print(chr(65)) print(chr(97)) print(ord('A')) print(ord('a')) def alphabet_by_ord(): """Goes through and prints the uppercase alphabet using ord() and chr() """ current_letter = ord('A') for letter in range(1, 27): print(chr(current_letter)) current_letter += 1 def capitalize_by_ord(letter='a'): """Converts lowercase characters to uppercase using ord() and chr() Returns: (str): A message with the upper and original case version of the letter """ uppercase_letter = ord(letter) - 32 return 'Letter {} converted to {}'.format(letter, chr(uppercase_letter)) alphabet_by_ord() print(capitalize_by_ord())
""" This module implements the Scorer Class. A Scorer tracks the match, mismatch, gap, and xdrop values. The Scorer is also responsible for calculating the dynamic programming function value and direction. """ class Scorer(): """Scorer Class""" def __init__ ( self, match, mismatch, gap, xdrop ): """ Scorer Constructor. Args: match (int): Match value mismatch (int): Mismatch value gap (int): Match value xdrop (int): X-Drop termination condition """ if not isinstance( match, int ): raise TypeError( "Invalid Match Score Type" ) if not isinstance( mismatch, int ): raise TypeError( "Invalid Mismatch Score Type" ) if not isinstance( gap, int ): raise TypeError( "Invalid Gap Score Type" ) if not isinstance( xdrop, int ): raise TypeError( "Invalid X-Drop Value Type" ) self.match = match self.mismatch = mismatch self.gap = gap self.xdrop = xdrop def calc_sq_value ( self, left_score, above_score, diag_score, nuch, nucv, max_score ): """ Computes the value of a square in the dynamic programming grid as a function of previous three squares and the two nucleotides. Args: left_score (Union[str, int]): Value of square to the left of output square above_score (Union[str, int]): Value of square above the output square diag_score (Union[str, int]): Value of square up and to the left of output square nuch (str): Horizontal sequence nucleotide associated with output square nucv (str): Vertical sequence nucleotide associated with output square max_score (int): The "best" score used to calculate X-Drop termination condition Returns: (Union[str, int]): The value of the square or "X" denoting the X-Drop termination condition has been triggered """ if not isinstance( left_score, (int, str) ): raise TypeError( "Invalid Left Square Score Type" ) if not isinstance( above_score, (int, str) ): raise TypeError( "Invalid Above Square Score Type" ) if not isinstance( diag_score, (int, str) ): raise TypeError( "Invalid Diagonal Square Score Type" ) if isinstance( left_score, str ) and left_score != "X": raise ValueError( "Invalid Left Square Score Value" ) if isinstance( above_score, str ) and above_score != "X": raise ValueError( "Invalid Above Square Score Value" ) if isinstance( diag_score, str ) and diag_score != "X": raise ValueError( "Invalid Diagonal Square Score Value" ) if not isinstance( nuch, str ): raise TypeError( "Invalid Horizontal Nucleotide Type" ) if not isinstance( nucv, str ): raise TypeError( "Invalid Vertical Nucleotide Type" ) if not isinstance( max_score, int ): raise TypeError( "Invalid Max Score Type" ) if len( nuch ) != 1 or len( nucv ) != 1: raise ValueError( "Invalid Nucleotide Value" ) potential_values = [] if diag_score != "X": if nuch == nucv: potential_values.append( diag_score + self.match ) else: potential_values.append( diag_score + self.mismatch ) if left_score != "X": potential_values.append( left_score + self.gap ) if above_score != "X": potential_values.append( above_score + self.gap ) if len( potential_values ) == 0: return "X" res = max( potential_values ) if res <= max_score - self.xdrop: res = "X" return res def calc_sq_dir_back ( self, left_score, above_score, diag_score, nuch, nucv, this_score ): """ Computes the direction the this_score value came from in the dynamic programming grid. This corresponds to the inverse of the dynamic programming function. Args: left_score (Union[str, int]): Value of square to the left of this_value square above_score (Union[str, int]): Value of square above the this_value square diag_score (Union[str, int]): Value of square up and to the left of this_value square nuch (str): Horizontal sequence nucleotide associated with this_value square nucv (str): Vertical sequence nucleotide associated with this_value square this_score (int): The score of the square in the dynamic programming grid Returns: (Tuple[int, int]): The direction the this_score value came from given as a vector """ if not isinstance( left_score, (int, str) ): raise TypeError( "Invalid Left Square Score Type" ) if not isinstance( above_score, (int, str) ): raise TypeError( "Invalid Above Square Score Type" ) if not isinstance( diag_score, (int, str) ): raise TypeError( "Invalid Diagonal Square Score Type" ) if isinstance( left_score, str ) and left_score != "X": raise ValueError( "Invalid Left Square Score Value" ) if isinstance( above_score, str ) and above_score != "X": raise ValueError( "Invalid Above Square Score Value" ) if isinstance( diag_score, str ) and diag_score != "X": raise ValueError( "Invalid Diagonal Square Score Value" ) if not isinstance( nuch, str ): raise TypeError( "Invalid Horizontal Nucleotide Type" ) if not isinstance( nucv, str ): raise TypeError( "Invalid Vertical Nucleotide Type" ) if not isinstance( this_score, int ): raise TypeError( "Invalid Square Score Type" ) if len( nuch ) != 1 or len( nucv ) != 1: raise ValueError( "Invalid Nucleotide Value" ) if diag_score != "X": if nuch == nucv and diag_score + self.match == this_score: return (-1, -1) if nuch != nucv and diag_score + self.mismatch == this_score: return (-1, -1) if left_score != "X": if left_score + self.gap == this_score: return (0, -1) if above_score != "X": if above_score + self.gap == this_score: return (-1, 0) raise RuntimeError( "Failure to calculate direction." ) def calc_sq_dir_forw ( self, right_score, below_score, diag_score, nuch, nucv ): """ Computes the direction the this_score value went to in the dynamic programming grid. Args: right_score (Union[str, int]): Value of square to the right of this square below_score (Union[str, int]): Value of square below the this square diag_score (Union[str, int]): Value of square down and to the right of this square nuch (str): Horizontal sequence nucleotide associated with this square nucv (str): Vertical sequence nucleotide associated with this square Returns: (Tuple[int, int]): The direction the this value went to given as a vector """ if not isinstance( right_score, (int, str) ): raise TypeError( "Invalid Right Square Score Type" ) if not isinstance( below_score, (int, str) ): raise TypeError( "Invalid Below Square Score Type" ) if not isinstance( diag_score, (int, str) ): raise TypeError( "Invalid Diagonal Square Score Type" ) if isinstance( right_score, str ) and right_score != "X": raise ValueError( "Invalid Right Square Score Value" ) if isinstance( below_score, str ) and below_score != "X": raise ValueError( "Invalid Below Square Score Value" ) if isinstance( diag_score, str ) and diag_score != "X": raise ValueError( "Invalid Diagonal Square Score Value" ) if not isinstance( nuch, str ): raise TypeError( "Invalid Horizontal Nucleotide Type" ) if not isinstance( nucv, str ): raise TypeError( "Invalid Vertical Nucleotide Type" ) if len( nuch ) != 1 or len( nucv ) != 1: raise ValueError( "Invalid Nucleotide Value" ) potential_values = [] if diag_score != "X": potential_values.append( diag_score ) if right_score != "X": potential_values.append( right_score ) if below_score != "X": potential_values.append( below_score ) if len( potential_values ) == 0: raise RuntimeError( "Failure to calculate direction." ) res = max( potential_values ) if res == diag_score: return (1, 1) elif res == right_score: return (0, 1) elif res == below_score: return (1, 0) raise RuntimeError( "Failure to calculate direction." )
""" This module implements the Scorer Class. A Scorer tracks the match, mismatch, gap, and xdrop values. The Scorer is also responsible for calculating the dynamic programming function value and direction. """ class Scorer: """Scorer Class""" def __init__(self, match, mismatch, gap, xdrop): """ Scorer Constructor. Args: match (int): Match value mismatch (int): Mismatch value gap (int): Match value xdrop (int): X-Drop termination condition """ if not isinstance(match, int): raise type_error('Invalid Match Score Type') if not isinstance(mismatch, int): raise type_error('Invalid Mismatch Score Type') if not isinstance(gap, int): raise type_error('Invalid Gap Score Type') if not isinstance(xdrop, int): raise type_error('Invalid X-Drop Value Type') self.match = match self.mismatch = mismatch self.gap = gap self.xdrop = xdrop def calc_sq_value(self, left_score, above_score, diag_score, nuch, nucv, max_score): """ Computes the value of a square in the dynamic programming grid as a function of previous three squares and the two nucleotides. Args: left_score (Union[str, int]): Value of square to the left of output square above_score (Union[str, int]): Value of square above the output square diag_score (Union[str, int]): Value of square up and to the left of output square nuch (str): Horizontal sequence nucleotide associated with output square nucv (str): Vertical sequence nucleotide associated with output square max_score (int): The "best" score used to calculate X-Drop termination condition Returns: (Union[str, int]): The value of the square or "X" denoting the X-Drop termination condition has been triggered """ if not isinstance(left_score, (int, str)): raise type_error('Invalid Left Square Score Type') if not isinstance(above_score, (int, str)): raise type_error('Invalid Above Square Score Type') if not isinstance(diag_score, (int, str)): raise type_error('Invalid Diagonal Square Score Type') if isinstance(left_score, str) and left_score != 'X': raise value_error('Invalid Left Square Score Value') if isinstance(above_score, str) and above_score != 'X': raise value_error('Invalid Above Square Score Value') if isinstance(diag_score, str) and diag_score != 'X': raise value_error('Invalid Diagonal Square Score Value') if not isinstance(nuch, str): raise type_error('Invalid Horizontal Nucleotide Type') if not isinstance(nucv, str): raise type_error('Invalid Vertical Nucleotide Type') if not isinstance(max_score, int): raise type_error('Invalid Max Score Type') if len(nuch) != 1 or len(nucv) != 1: raise value_error('Invalid Nucleotide Value') potential_values = [] if diag_score != 'X': if nuch == nucv: potential_values.append(diag_score + self.match) else: potential_values.append(diag_score + self.mismatch) if left_score != 'X': potential_values.append(left_score + self.gap) if above_score != 'X': potential_values.append(above_score + self.gap) if len(potential_values) == 0: return 'X' res = max(potential_values) if res <= max_score - self.xdrop: res = 'X' return res def calc_sq_dir_back(self, left_score, above_score, diag_score, nuch, nucv, this_score): """ Computes the direction the this_score value came from in the dynamic programming grid. This corresponds to the inverse of the dynamic programming function. Args: left_score (Union[str, int]): Value of square to the left of this_value square above_score (Union[str, int]): Value of square above the this_value square diag_score (Union[str, int]): Value of square up and to the left of this_value square nuch (str): Horizontal sequence nucleotide associated with this_value square nucv (str): Vertical sequence nucleotide associated with this_value square this_score (int): The score of the square in the dynamic programming grid Returns: (Tuple[int, int]): The direction the this_score value came from given as a vector """ if not isinstance(left_score, (int, str)): raise type_error('Invalid Left Square Score Type') if not isinstance(above_score, (int, str)): raise type_error('Invalid Above Square Score Type') if not isinstance(diag_score, (int, str)): raise type_error('Invalid Diagonal Square Score Type') if isinstance(left_score, str) and left_score != 'X': raise value_error('Invalid Left Square Score Value') if isinstance(above_score, str) and above_score != 'X': raise value_error('Invalid Above Square Score Value') if isinstance(diag_score, str) and diag_score != 'X': raise value_error('Invalid Diagonal Square Score Value') if not isinstance(nuch, str): raise type_error('Invalid Horizontal Nucleotide Type') if not isinstance(nucv, str): raise type_error('Invalid Vertical Nucleotide Type') if not isinstance(this_score, int): raise type_error('Invalid Square Score Type') if len(nuch) != 1 or len(nucv) != 1: raise value_error('Invalid Nucleotide Value') if diag_score != 'X': if nuch == nucv and diag_score + self.match == this_score: return (-1, -1) if nuch != nucv and diag_score + self.mismatch == this_score: return (-1, -1) if left_score != 'X': if left_score + self.gap == this_score: return (0, -1) if above_score != 'X': if above_score + self.gap == this_score: return (-1, 0) raise runtime_error('Failure to calculate direction.') def calc_sq_dir_forw(self, right_score, below_score, diag_score, nuch, nucv): """ Computes the direction the this_score value went to in the dynamic programming grid. Args: right_score (Union[str, int]): Value of square to the right of this square below_score (Union[str, int]): Value of square below the this square diag_score (Union[str, int]): Value of square down and to the right of this square nuch (str): Horizontal sequence nucleotide associated with this square nucv (str): Vertical sequence nucleotide associated with this square Returns: (Tuple[int, int]): The direction the this value went to given as a vector """ if not isinstance(right_score, (int, str)): raise type_error('Invalid Right Square Score Type') if not isinstance(below_score, (int, str)): raise type_error('Invalid Below Square Score Type') if not isinstance(diag_score, (int, str)): raise type_error('Invalid Diagonal Square Score Type') if isinstance(right_score, str) and right_score != 'X': raise value_error('Invalid Right Square Score Value') if isinstance(below_score, str) and below_score != 'X': raise value_error('Invalid Below Square Score Value') if isinstance(diag_score, str) and diag_score != 'X': raise value_error('Invalid Diagonal Square Score Value') if not isinstance(nuch, str): raise type_error('Invalid Horizontal Nucleotide Type') if not isinstance(nucv, str): raise type_error('Invalid Vertical Nucleotide Type') if len(nuch) != 1 or len(nucv) != 1: raise value_error('Invalid Nucleotide Value') potential_values = [] if diag_score != 'X': potential_values.append(diag_score) if right_score != 'X': potential_values.append(right_score) if below_score != 'X': potential_values.append(below_score) if len(potential_values) == 0: raise runtime_error('Failure to calculate direction.') res = max(potential_values) if res == diag_score: return (1, 1) elif res == right_score: return (0, 1) elif res == below_score: return (1, 0) raise runtime_error('Failure to calculate direction.')
class Node: def __init__(self, value, next=None): self.value = value self.next = next class LinkedList: def __init__(self, head=None): self.head = head def insert(self, value): node = Node(value) # Node of [3] if self.head is not None: node.next = self.head self.head = node def includes(self, value): current = self.head while current is not None: if current.value == value: return True else: current = current.next return False # insert before def append(self, value): new_node = Node(value) current = self.head if current is None: current = new_node else: while current.next is not None: current = current.next current.next = new_node def insert_before(self, new_value, value): # create new node newNode = Node(new_value) # find target node to insert node = self.head if node == None: return else: # search nodes if node.value == value: newNode.next = self.head self.head = newNode while node.next is not None: if node.next.value == value: newNode.next = node.next node.next = newNode return else: node = node.next def insert_after(self, value, new_value): newNode = Node(new_value) current = self.head if self.head == None: self.head = newNode return else: if current == value: return temp = self.head while temp.next != None: temp = temp.next temp.next = newNode def to_string(self): # defining a blank res variable results = "" # initializing ptr to head current = self.head # traversing and adding it to results while current: results += f"{ {current.value} } -> " current = current.next results += f"None" return results # Code challenge 7 def kth_from_end(self, k): length = -1 current = self.head while current: current = current.next length += 1 if k > length: return "That brings us out of the linked list" elif k < 0: return "please choose a positive number" else: current = self.head position = length - k for _ in range(0, position): current = current.next return current.value
class Node: def __init__(self, value, next=None): self.value = value self.next = next class Linkedlist: def __init__(self, head=None): self.head = head def insert(self, value): node = node(value) if self.head is not None: node.next = self.head self.head = node def includes(self, value): current = self.head while current is not None: if current.value == value: return True else: current = current.next return False def append(self, value): new_node = node(value) current = self.head if current is None: current = new_node else: while current.next is not None: current = current.next current.next = new_node def insert_before(self, new_value, value): new_node = node(new_value) node = self.head if node == None: return else: if node.value == value: newNode.next = self.head self.head = newNode while node.next is not None: if node.next.value == value: newNode.next = node.next node.next = newNode return else: node = node.next def insert_after(self, value, new_value): new_node = node(new_value) current = self.head if self.head == None: self.head = newNode return else: if current == value: return temp = self.head while temp.next != None: temp = temp.next temp.next = newNode def to_string(self): results = '' current = self.head while current: results += f'{ {current.value}} -> ' current = current.next results += f'None' return results def kth_from_end(self, k): length = -1 current = self.head while current: current = current.next length += 1 if k > length: return 'That brings us out of the linked list' elif k < 0: return 'please choose a positive number' else: current = self.head position = length - k for _ in range(0, position): current = current.next return current.value
#!/usr/bin/env python # -*- coding: utf-8 -*- db = { 'host': 'localhost', 'port': 6379 } dbnames = { 'default': 1, 'ephermal': 8 }
db = {'host': 'localhost', 'port': 6379} dbnames = {'default': 1, 'ephermal': 8}
""" One of the most enjoyable hard questions on Leetcode. A really hard problem until you break it down into smaller subproblems """ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def maxPathSum(root: TreeNode) -> int: ans = -float('inf') def find_max(node): nonlocal ans if not node: return 0 closed_loop = max(node.val, node.val + max(l := find_max(node.left), r := find_max(node.right))) ans = max(ans, closed_loop, l + node.val + r) return closed_loop find_max(root) return ans
""" One of the most enjoyable hard questions on Leetcode. A really hard problem until you break it down into smaller subproblems """ class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def max_path_sum(root: TreeNode) -> int: ans = -float('inf') def find_max(node): nonlocal ans if not node: return 0 closed_loop = max(node.val, node.val + max((l := find_max(node.left)), (r := find_max(node.right)))) ans = max(ans, closed_loop, l + node.val + r) return closed_loop find_max(root) return ans
class Tests(unittest.TestCase): def _sim_model(self, data: Tensor) -> Tensor: """ Simulated model for generating uncertainity scores. Intention is to be a placeholder until real models are used and for testing.""" return torch.rand(size=(data.shape[0],)) def setUp(self): # Init class self.sampler = Sampler(budget=10) # Init random tensor self.data = torch.rand(size=(10,2,2)) # dim (batch, length, features) # Params self.budget = 18 # All sample tests are tested for: # 1. dims (_, length, features) for input and output Tensors # 2. batch size == sample size def test_sample_random(self): self.assertEqual(self.sampler.sample_random(self.data).shape[1:], self.data.shape[1:]) self.assertEqual(self.sampler.sample_random(self.data).shape[0], self.sampler.budget) def test_sample_least_confidence(self): self.assertEqual(self.sampler.sample_least_confidence(model=self.sampler._sim_model, data=self.data).shape[1:], self.data.shape[1:]) self.assertEqual(self.sampler.sample_least_confidence(model=self.sampler._sim_model, data=self.data).shape[0], self.sampler.budget) # def test_sample_bayesian(self): # self.assertEqual(self.sampler.sample_bayesian(model=self.sampler._sim_model, no_models=3, data=self.data).shape[1:], self.data.shape[1:]) # self.assertEqual(self.sampler.sample_bayesian(model=self.sampler._sim_model, no_models=3, data=self.data).shape[0], self.sampler.budget) # def test_adversarial_sample(self): # self.assertEqual(self.sampler.sample_adversarial(self.data).shape[1:], self.data.shape[1:]) # self.assertEqual(self.sampler.sample_adversarial(self.data).shape[0], self.sampler.budget)
class Tests(unittest.TestCase): def _sim_model(self, data: Tensor) -> Tensor: """ Simulated model for generating uncertainity scores. Intention is to be a placeholder until real models are used and for testing.""" return torch.rand(size=(data.shape[0],)) def set_up(self): self.sampler = sampler(budget=10) self.data = torch.rand(size=(10, 2, 2)) self.budget = 18 def test_sample_random(self): self.assertEqual(self.sampler.sample_random(self.data).shape[1:], self.data.shape[1:]) self.assertEqual(self.sampler.sample_random(self.data).shape[0], self.sampler.budget) def test_sample_least_confidence(self): self.assertEqual(self.sampler.sample_least_confidence(model=self.sampler._sim_model, data=self.data).shape[1:], self.data.shape[1:]) self.assertEqual(self.sampler.sample_least_confidence(model=self.sampler._sim_model, data=self.data).shape[0], self.sampler.budget)
# -*- coding: utf-8 -*- #: The title of this site SITE_TITLE='HasGeek Funnel' #: Support contact email SITE_SUPPORT_EMAIL = 'test@example.com' #: TypeKit code for fonts TYPEKIT_CODE='' #: Google Analytics code UA-XXXXXX-X GA_CODE='' #: Database backend SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db' #: Secret key SECRET_KEY = 'make this something random' #: Timezone TIMEZONE = 'Asia/Calcutta' #: LastUser server LASTUSER_SERVER = 'https://auth.hasgeek.com/' #: LastUser client id LASTUSER_CLIENT_ID = '' #: LastUser client secret LASTUSER_CLIENT_SECRET = '' #: Used for attribution when shared a proposal on twitter TWITTER_ID = "hasgeek" #: Mail settings #: MAIL_FAIL_SILENTLY : default True #: MAIL_SERVER : default 'localhost' #: MAIL_PORT : default 25 #: MAIL_USE_TLS : default False #: MAIL_USE_SSL : default False #: MAIL_USERNAME : default None #: MAIL_PASSWORD : default None #: DEFAULT_MAIL_SENDER : default None MAIL_FAIL_SILENTLY = False MAIL_SERVER = 'localhost' DEFAULT_MAIL_SENDER = ('Bill Gate', 'test@example.com') # Required for Flask-Mail to work. MAIL_DEFAULT_SENDER = DEFAULT_MAIL_SENDER #: Logging: recipients of error emails ADMINS=[] #: Log file LOGFILE='error.log' #: Messages (text or HTML) WELCOME_MESSAGE = "The funnel is a space for proposals and voting on events. Pick an event to get started."
site_title = 'HasGeek Funnel' site_support_email = 'test@example.com' typekit_code = '' ga_code = '' sqlalchemy_database_uri = 'sqlite:///test.db' secret_key = 'make this something random' timezone = 'Asia/Calcutta' lastuser_server = 'https://auth.hasgeek.com/' lastuser_client_id = '' lastuser_client_secret = '' twitter_id = 'hasgeek' mail_fail_silently = False mail_server = 'localhost' default_mail_sender = ('Bill Gate', 'test@example.com') mail_default_sender = DEFAULT_MAIL_SENDER admins = [] logfile = 'error.log' welcome_message = 'The funnel is a space for proposals and voting on events. Pick an event to get started.'
""" Account: This clump of functions manage the account features for the API. Their functions are like: - Main account management. - Register with {username} {email} {password} {confirmation}. - Login with {username} {password}. - Reset password {recovery key} with {new password} {confirmation}. - Logout. - Requires user logged in. - Close account. - Requires user logged in. - Profile management (All of these require user logged in). - Get profile. - Change password with {old password} {new password} {confirmation}. - Rate place {uuid} with {score}. - Remove rate from place {uuid}. - Bookmark place {uuid} (it will add the bookmark to the end). - Unbookmark place {uuid}. - Move bookmark {uuid} to the end or, if specified {uuid_other}, before {uuid_other}. """
""" Account: This clump of functions manage the account features for the API. Their functions are like: - Main account management. - Register with {username} {email} {password} {confirmation}. - Login with {username} {password}. - Reset password {recovery key} with {new password} {confirmation}. - Logout. - Requires user logged in. - Close account. - Requires user logged in. - Profile management (All of these require user logged in). - Get profile. - Change password with {old password} {new password} {confirmation}. - Rate place {uuid} with {score}. - Remove rate from place {uuid}. - Bookmark place {uuid} (it will add the bookmark to the end). - Unbookmark place {uuid}. - Move bookmark {uuid} to the end or, if specified {uuid_other}, before {uuid_other}. """
class Node: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self): self.head = Node("head") self.size = 0 def __str__(self): cur = self.head.next out = "" while cur: out += str(cur.value) + "->" cur = cur.next return out[:-3] def is_empty(self): return self.size == 0 def peek(self): if self.is_empty(): raise Exception("Peeking from an empty stack") return self.head.next.value def push(self, value): node = Node(value) node.next = self.head.next self.head.next = node self.size += 1 def pop(self): if self.is_empty(): raise Exception("Popping from an empty stack") remove = self.head.next self.head.next = self.head.next.next self.size -= 1 return remove.value
class Node: def __init__(self, value): self.value = value self.next = None class Stack: def __init__(self): self.head = node('head') self.size = 0 def __str__(self): cur = self.head.next out = '' while cur: out += str(cur.value) + '->' cur = cur.next return out[:-3] def is_empty(self): return self.size == 0 def peek(self): if self.is_empty(): raise exception('Peeking from an empty stack') return self.head.next.value def push(self, value): node = node(value) node.next = self.head.next self.head.next = node self.size += 1 def pop(self): if self.is_empty(): raise exception('Popping from an empty stack') remove = self.head.next self.head.next = self.head.next.next self.size -= 1 return remove.value
#!/usr/bin/python # related: http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python class Worker(): SUCCESS = 1 FAILURE = 2 def test(self): return Worker.FAILURE t = Worker() t.test() if (t.test() == Worker.FAILURE): print("I got a failure status") if (t.test() == Worker.SUCCESS): print("I got a success status")
class Worker: success = 1 failure = 2 def test(self): return Worker.FAILURE t = worker() t.test() if t.test() == Worker.FAILURE: print('I got a failure status') if t.test() == Worker.SUCCESS: print('I got a success status')