content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# ------------------------------------------------------------------------------- # Name: palindromes # # Author: mourad mourafiq # ------------------------------------------------------------------------------- def longest_subpalindrome(string): """ Returns the longest subpalindrome string from the current string Return (i,j) """ #first we check if string is "" if string == "": return (0, 0) def length(slice): a, b = slice; return b - a slices = [grow(string, start, end) for start in range(len(string)) for end in (start, start + 1) ] return max(slices, key=length) def grow(string, start, end): """ starts with a 0 or 1 length palindrome and try to grow bigger """ while (start > 0 and end < len(string) and string[start - 1].upper() == string[end].upper()): start -= 1; end += 1 return (start, end)
def longest_subpalindrome(string): """ Returns the longest subpalindrome string from the current string Return (i,j) """ if string == '': return (0, 0) def length(slice): (a, b) = slice return b - a slices = [grow(string, start, end) for start in range(len(string)) for end in (start, start + 1)] return max(slices, key=length) def grow(string, start, end): """ starts with a 0 or 1 length palindrome and try to grow bigger """ while start > 0 and end < len(string) and (string[start - 1].upper() == string[end].upper()): start -= 1 end += 1 return (start, end)
""" Description: Provides ESPA specific exceptions to the processing code. License: NASA Open Source Agreement 1.3 """ class ESPAException(Exception): """Provides an ESPA specific exception specifically for ESPA processing""" pass
""" Description: Provides ESPA specific exceptions to the processing code. License: NASA Open Source Agreement 1.3 """ class Espaexception(Exception): """Provides an ESPA specific exception specifically for ESPA processing""" pass
# # PySNMP MIB module INCOGNITO-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INCOGNITO-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:42:01 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Bits, enterprises, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, ModuleIdentity, ObjectIdentity, Gauge32, Counter64, iso, IpAddress, NotificationType, MibIdentifier, Unsigned32, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "enterprises", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "ModuleIdentity", "ObjectIdentity", "Gauge32", "Counter64", "iso", "IpAddress", "NotificationType", "MibIdentifier", "Unsigned32", "Counter32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") incognito = ModuleIdentity((1, 3, 6, 1, 4, 1, 3606)) if mibBuilder.loadTexts: incognito.setLastUpdated('200304151442Z') if mibBuilder.loadTexts: incognito.setOrganization('Incognito Software Inc.') incognitoSNMPObjects = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 1)) if mibBuilder.loadTexts: incognitoSNMPObjects.setStatus('obsolete') incognitoReg = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 2)) if mibBuilder.loadTexts: incognitoReg.setStatus('current') incognitoGeneric = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 3)) if mibBuilder.loadTexts: incognitoGeneric.setStatus('current') incognitoProducts = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 4)) if mibBuilder.loadTexts: incognitoProducts.setStatus('current') incognitoCaps = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 5)) if mibBuilder.loadTexts: incognitoCaps.setStatus('current') incognitoReqs = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 6)) if mibBuilder.loadTexts: incognitoReqs.setStatus('current') incognitoExpr = ObjectIdentity((1, 3, 6, 1, 4, 1, 3606, 7)) if mibBuilder.loadTexts: incognitoExpr.setStatus('current') mibBuilder.exportSymbols("INCOGNITO-MIB", incognitoSNMPObjects=incognitoSNMPObjects, incognitoReqs=incognitoReqs, incognitoGeneric=incognitoGeneric, incognitoReg=incognitoReg, PYSNMP_MODULE_ID=incognito, incognitoProducts=incognitoProducts, incognitoCaps=incognitoCaps, incognito=incognito, incognitoExpr=incognitoExpr)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (bits, enterprises, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, integer32, module_identity, object_identity, gauge32, counter64, iso, ip_address, notification_type, mib_identifier, unsigned32, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'enterprises', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Integer32', 'ModuleIdentity', 'ObjectIdentity', 'Gauge32', 'Counter64', 'iso', 'IpAddress', 'NotificationType', 'MibIdentifier', 'Unsigned32', 'Counter32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') incognito = module_identity((1, 3, 6, 1, 4, 1, 3606)) if mibBuilder.loadTexts: incognito.setLastUpdated('200304151442Z') if mibBuilder.loadTexts: incognito.setOrganization('Incognito Software Inc.') incognito_snmp_objects = object_identity((1, 3, 6, 1, 4, 1, 3606, 1)) if mibBuilder.loadTexts: incognitoSNMPObjects.setStatus('obsolete') incognito_reg = object_identity((1, 3, 6, 1, 4, 1, 3606, 2)) if mibBuilder.loadTexts: incognitoReg.setStatus('current') incognito_generic = object_identity((1, 3, 6, 1, 4, 1, 3606, 3)) if mibBuilder.loadTexts: incognitoGeneric.setStatus('current') incognito_products = object_identity((1, 3, 6, 1, 4, 1, 3606, 4)) if mibBuilder.loadTexts: incognitoProducts.setStatus('current') incognito_caps = object_identity((1, 3, 6, 1, 4, 1, 3606, 5)) if mibBuilder.loadTexts: incognitoCaps.setStatus('current') incognito_reqs = object_identity((1, 3, 6, 1, 4, 1, 3606, 6)) if mibBuilder.loadTexts: incognitoReqs.setStatus('current') incognito_expr = object_identity((1, 3, 6, 1, 4, 1, 3606, 7)) if mibBuilder.loadTexts: incognitoExpr.setStatus('current') mibBuilder.exportSymbols('INCOGNITO-MIB', incognitoSNMPObjects=incognitoSNMPObjects, incognitoReqs=incognitoReqs, incognitoGeneric=incognitoGeneric, incognitoReg=incognitoReg, PYSNMP_MODULE_ID=incognito, incognitoProducts=incognitoProducts, incognitoCaps=incognitoCaps, incognito=incognito, incognitoExpr=incognitoExpr)
""" Events are called by the :class:`libres.db.scheduler.Scheduler` whenever something interesting occurs. The implementation is very simple: To add an event:: from libres.modules import events def on_allocations_added(context_name, allocations): pass events.on_allocations_added.append(on_allocations_added) To remove the same event:: events.on_allocations_added.remove(on_allocations_added) Events are called in the order they were added. """ class Event(list): """Event subscription. By http://stackoverflow.com/a/2022629 A list of callable objects. Calling an instance of this will cause a call to each item in the list in ascending order by index. """ def __call__(self, *args, **kwargs): for f in self: f(*args, **kwargs) on_allocations_added = Event() """ Called when an allocation is added, with the following arguments: :context: The :class:`libres.context.core.Context` used when adding the allocations. :allocations: The list of :class:`libres.db.models.Allocation` allocations to be commited. """ on_reservations_made = Event() """ Called when a reservation is made, with the following arguments: :context: The :class:`libres.context.core.Context` used when adding the reservation. :reservations: The list of :class:`libres.db.models.Reservation` reservations to be commited. This is a list because one reservation can result in multiple reservation records. All those records will have the same reservation token and the same reservee email address. """ on_reservations_confirmed = Event() """ Called when a reservation bound to a browser session is confirmed, with the following arguments: :context: The :class:`libres.context.core.Context` used when confirming the reservation. :reservations: The list of :class:`libres.db.models.Reservation` reservations being confirmed. :session_id: The session id that is being confirmed. """ on_reservations_approved = Event() """ Called when a reservation is approved, with the following arguments: :context: The :class:`libres.context.core.Context` used when approving the reservation. :reservations: The list of :class:`libres.db.models.Reservation` reservations being approved. """ on_reservations_denied = Event() """ Called when a reservation is denied, with the following arguments: :context: The :class:`libres.context.core.Context` used when denying the reservation. :reservations: The list of :class:`libres.db.models.Reservation` reservations being denied. """ on_reservations_removed = Event() """ Called when a reservation is removed, with the following arguments: :context: The :class:`libres.context.core.Context` used when removing the reservation. :reservations: The list of :class:`libres.db.models.Reservation` reservations being removed. """ on_reservation_time_changed = Event() """ Called when a reservation's time changes , with the following arguments: :context: The :class:`libres.context.core.Context` used when changing the reservation time. :reservation: The :class:`libres.db.models.Reservation` reservation whose time is changing. :old_time: A tuple of datetimes containing the old start and the old end. :new_time: A tuple of datetimes containing the new start and the new end. """
""" Events are called by the :class:`libres.db.scheduler.Scheduler` whenever something interesting occurs. The implementation is very simple: To add an event:: from libres.modules import events def on_allocations_added(context_name, allocations): pass events.on_allocations_added.append(on_allocations_added) To remove the same event:: events.on_allocations_added.remove(on_allocations_added) Events are called in the order they were added. """ class Event(list): """Event subscription. By http://stackoverflow.com/a/2022629 A list of callable objects. Calling an instance of this will cause a call to each item in the list in ascending order by index. """ def __call__(self, *args, **kwargs): for f in self: f(*args, **kwargs) on_allocations_added = event() ' Called when an allocation is added, with the following arguments:\n\n :context:\n The :class:`libres.context.core.Context` used when adding the\n allocations.\n\n :allocations:\n The list of :class:`libres.db.models.Allocation` allocations to be\n commited.\n\n' on_reservations_made = event() ' Called when a reservation is made, with the following arguments:\n\n :context:\n The :class:`libres.context.core.Context` used when adding the\n reservation.\n\n :reservations:\n The list of :class:`libres.db.models.Reservation` reservations to be\n commited. This is a list because one reservation can result in\n multiple reservation records. All those records will have the\n same reservation token and the same reservee email address.\n\n' on_reservations_confirmed = event() ' Called when a reservation bound to a browser session is confirmed, with\nthe following arguments:\n\n :context:\n The :class:`libres.context.core.Context` used when confirming the\n reservation.\n\n :reservations:\n The list of :class:`libres.db.models.Reservation` reservations being\n confirmed.\n\n :session_id:\n The session id that is being confirmed.\n' on_reservations_approved = event() ' Called when a reservation is approved, with the following arguments:\n\n :context:\n The :class:`libres.context.core.Context` used when approving the\n reservation.\n\n :reservations:\n The list of :class:`libres.db.models.Reservation` reservations being\n approved.\n\n' on_reservations_denied = event() ' Called when a reservation is denied, with the following arguments:\n\n :context:\n The :class:`libres.context.core.Context` used when denying the\n reservation.\n\n :reservations:\n The list of :class:`libres.db.models.Reservation` reservations being\n denied.\n\n' on_reservations_removed = event() ' Called when a reservation is removed, with the following arguments:\n\n :context:\n The :class:`libres.context.core.Context` used when removing the\n reservation.\n\n :reservations:\n The list of :class:`libres.db.models.Reservation` reservations being\n removed.\n\n' on_reservation_time_changed = event() " Called when a reservation's time changes , with the following arguments:\n\n :context:\n The :class:`libres.context.core.Context` used when changing the\n reservation time.\n\n :reservation:\n The :class:`libres.db.models.Reservation` reservation whose time is\n changing.\n\n :old_time:\n A tuple of datetimes containing the old start and the old end.\n\n :new_time:\n A tuple of datetimes containing the new start and the new end.\n\n"
#list example for insertion order and the dupicates l1 = [] print(type(l1)) l1.append(1) l1.append(2) l1.append(3) l1.append(4) l1.append(1) print(l1)
l1 = [] print(type(l1)) l1.append(1) l1.append(2) l1.append(3) l1.append(4) l1.append(1) print(l1)
class Shodan: """Get any Shodan information """ def __init__(self): # TODO: move key to config self.api_key = 'yKIZ2L54cQxIfnebD4V2qgPp0QQsJLpK' # TODO: add shodan api def request(self): pass
class Shodan: """Get any Shodan information """ def __init__(self): self.api_key = 'yKIZ2L54cQxIfnebD4V2qgPp0QQsJLpK' def request(self): pass
def maximum_subarray_sum(lst): '''Finds the maximum sum of all subarrays in lst in O(n) time and O(1) additional space. >>> maximum_subarray_sum([34, -50, 42, 14, -5, 86]) 137 >>> maximum_subarray_sum([-5, -1, -8, -101]) 0 ''' current_sum = 0 maximum_sum = 0 for value in lst: current_sum = max(current_sum + value, 0) maximum_sum = max(maximum_sum, current_sum) return maximum_sum
def maximum_subarray_sum(lst): """Finds the maximum sum of all subarrays in lst in O(n) time and O(1) additional space. >>> maximum_subarray_sum([34, -50, 42, 14, -5, 86]) 137 >>> maximum_subarray_sum([-5, -1, -8, -101]) 0 """ current_sum = 0 maximum_sum = 0 for value in lst: current_sum = max(current_sum + value, 0) maximum_sum = max(maximum_sum, current_sum) return maximum_sum
""" * Use an input_boolean to change between views, showing or hidding groups. * Check some groups with a connectivity binary_sensor to hide offline devices. """ # Groups visibility (expert_view group / normal view group): GROUPS_EXPERT_MODE = { 'group.salon': 'group.salon_simple', 'group.estudio_rpi2h': 'group.estudio_rpi2h_simple', 'group.dormitorio_rpi2mpd': 'group.dormitorio_rpi2mpd_simple', 'group.cocina': 'group.cocina_simple', 'group.caldera': 'group.caldera_simple', 'group.links': 'group.links_simple', 'group.cacharros': 'group.cacharros_simple', 'group.hass_control': 'group.hass_control_simple', 'group.weather': 'group.weather_simple', 'group.esp8266_3': 'group.esp8266_3_simple', 'group.enerpi_max_power_control': None, 'group.scripts': None, 'group.host_rpi3': None, 'group.host_rpi2_hat': None, 'group.host_rpi2_mpd': None, 'group.conectivity': None, 'group.esp8266_2': None, 'group.menu_automations_1': None, 'group.menu_automations_2': None, 'group.menu_automations_3': None, } GROUPS_WITH_BINARY_STATE = { 'group.esp8266_2': 'binary_sensor.esp2_online', 'group.esp8266_3': 'binary_sensor.esp3_online', 'group.cocina': 'binary_sensor.cocina_online' } # Get new value of 'expert mode' expert_mode = data.get( 'expert_mode_state', hass.states.get('input_boolean.show_expert_mode').state) == 'on' for g_expert in GROUPS_EXPERT_MODE: visible_expert = expert_mode visible_normal = not expert_mode g_normal = GROUPS_EXPERT_MODE.get(g_expert) # Hide groups of devices offline if g_expert in GROUPS_WITH_BINARY_STATE: bin_sensor = GROUPS_WITH_BINARY_STATE.get(g_expert) bin_state = hass.states.get(bin_sensor).state if bin_state is None or bin_state == 'off': visible_expert = visible_normal = False # Show and hide hass.services.call( 'group', 'set_visibility', {"entity_id": g_expert, "visible": visible_expert}) if g_normal is not None: hass.services.call( 'group', 'set_visibility', {"entity_id": g_normal, "visible": visible_normal})
""" * Use an input_boolean to change between views, showing or hidding groups. * Check some groups with a connectivity binary_sensor to hide offline devices. """ groups_expert_mode = {'group.salon': 'group.salon_simple', 'group.estudio_rpi2h': 'group.estudio_rpi2h_simple', 'group.dormitorio_rpi2mpd': 'group.dormitorio_rpi2mpd_simple', 'group.cocina': 'group.cocina_simple', 'group.caldera': 'group.caldera_simple', 'group.links': 'group.links_simple', 'group.cacharros': 'group.cacharros_simple', 'group.hass_control': 'group.hass_control_simple', 'group.weather': 'group.weather_simple', 'group.esp8266_3': 'group.esp8266_3_simple', 'group.enerpi_max_power_control': None, 'group.scripts': None, 'group.host_rpi3': None, 'group.host_rpi2_hat': None, 'group.host_rpi2_mpd': None, 'group.conectivity': None, 'group.esp8266_2': None, 'group.menu_automations_1': None, 'group.menu_automations_2': None, 'group.menu_automations_3': None} groups_with_binary_state = {'group.esp8266_2': 'binary_sensor.esp2_online', 'group.esp8266_3': 'binary_sensor.esp3_online', 'group.cocina': 'binary_sensor.cocina_online'} expert_mode = data.get('expert_mode_state', hass.states.get('input_boolean.show_expert_mode').state) == 'on' for g_expert in GROUPS_EXPERT_MODE: visible_expert = expert_mode visible_normal = not expert_mode g_normal = GROUPS_EXPERT_MODE.get(g_expert) if g_expert in GROUPS_WITH_BINARY_STATE: bin_sensor = GROUPS_WITH_BINARY_STATE.get(g_expert) bin_state = hass.states.get(bin_sensor).state if bin_state is None or bin_state == 'off': visible_expert = visible_normal = False hass.services.call('group', 'set_visibility', {'entity_id': g_expert, 'visible': visible_expert}) if g_normal is not None: hass.services.call('group', 'set_visibility', {'entity_id': g_normal, 'visible': visible_normal})
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Ce module permet d'obtenir la liste des pays valides, a partir d'un fichier donnee. """ __auteur__ = "Thefuture2092" def obtenirListePays(langue): """ cette fonction prend un argument langue et retourne la liste de pays dans cette langue. """ # ouvrir un fichier selon la langue fournie fin = open('countrylist.txt', encoding="utf-8") if langue.lower() == 'en' else open('listepays.txt', encoding="utf-8") listepays = [] prelistepays = [] for l in fin: prelistepays.append(l.replace('\x00','').strip().lower()) for l in prelistepays: if l: listepays.append(l) listepays[0]=listepays[0][2:] fin.close() return listepays #print(listepays)
""" Ce module permet d'obtenir la liste des pays valides, a partir d'un fichier donnee. """ __auteur__ = 'Thefuture2092' def obtenir_liste_pays(langue): """ cette fonction prend un argument langue et retourne la liste de pays dans cette langue. """ fin = open('countrylist.txt', encoding='utf-8') if langue.lower() == 'en' else open('listepays.txt', encoding='utf-8') listepays = [] prelistepays = [] for l in fin: prelistepays.append(l.replace('\x00', '').strip().lower()) for l in prelistepays: if l: listepays.append(l) listepays[0] = listepays[0][2:] fin.close() return listepays
""" Lab 8 """ #3.1 demo='hello world!' def cal_words(input_str): return len(input_str.split()) #3.2 demo_str='Hello world!' print(cal_words(demo_str)) #3.3 def find_min(inpu_list): min_item = inpu_list[0] for num in inpu_list: if type(num) is not str: if min_item >= num: min_item = num return min_item #3.4 demo_list = [1,2,3,4,5,6] print(find_min(demo_list)) #3.5 mix_list = [1,2,3,4,'a',6] print(find_min(mix_list))
""" Lab 8 """ demo = 'hello world!' def cal_words(input_str): return len(input_str.split()) demo_str = 'Hello world!' print(cal_words(demo_str)) def find_min(inpu_list): min_item = inpu_list[0] for num in inpu_list: if type(num) is not str: if min_item >= num: min_item = num return min_item demo_list = [1, 2, 3, 4, 5, 6] print(find_min(demo_list)) mix_list = [1, 2, 3, 4, 'a', 6] print(find_min(mix_list))
# Alternative solution using compound conditional statement in_class_test = int(input('Please enter your mark for the In Class Test: ')) exam_mark = int(input('Please input your mark for the exam: ')) coursework_mark = int(input('Please enter your mark for Component B: ')) # Calculating mark by adding the marks together and dividing by 2 component_a_mark = (in_class_test * 0.25) + (exam_mark * 0.75) module_mark = (component_a_mark + coursework_mark) / 2 print('Your mark is', module_mark, 'Calculating your result') # Uses compound boolean proposition if coursework_mark < 35 and component_a_mark < 35: print('You have not passed the module') elif module_mark < 40: print('You have failed the module') else: print('You have passed the module')
in_class_test = int(input('Please enter your mark for the In Class Test: ')) exam_mark = int(input('Please input your mark for the exam: ')) coursework_mark = int(input('Please enter your mark for Component B: ')) component_a_mark = in_class_test * 0.25 + exam_mark * 0.75 module_mark = (component_a_mark + coursework_mark) / 2 print('Your mark is', module_mark, 'Calculating your result') if coursework_mark < 35 and component_a_mark < 35: print('You have not passed the module') elif module_mark < 40: print('You have failed the module') else: print('You have passed the module')
class SarlaccPlugin: def __init__(self, logger, store): """Init method for SarlaccPlugin. Args: logger -- sarlacc logger object. store -- sarlacc store object. """ self.logger = logger self.store = store def run(self): """Runs the plugin. This method should be overridden if a plugin needs to do any initial work that isn't purely initialization. This could include starting any long running jobs / threads. """ pass def stop(self): """Stops the plugin. This method should be overridden if a plugin needs to do any extra cleanup before stopping. This could include stopping any previously started jobs / threads. """ pass async def new_attachment(self, _id, sha256, content, filename, tags): """New attachment signal. This method is called when a new, previously unseen attachment is detected. Override this method to be informed about this event. Args: _id -- the attachment postgresql record id. sha256 -- the sha256 hash of the attachment. content -- the raw file. filename -- the filename of the attachment. tags -- any tags attached to the attachment. """ pass async def new_email_address(self, _id, email_address): """New email address signal. This method is called when a new, previously unseen recipient email address is detected. Override this method to be informed about this event. Args: _id -- the email address postgresql record id. email_address -- the email address. """ pass async def new_mail_item(self, _id, subject, recipients, from_address, body, date_sent, attachments): """New email signal. This method is called when an email is received. Override this method to be informed about this event. Args: _id -- the mail item postgresql record id. subject -- the email subject. recipients -- a list of recipient email addresses. from_address -- the email address in the email's "from" header. body -- the body of the email. date_sent -- the date and time the email was sent. attachments -- a list of attachment objects in the following format: { content: the content of the attachment (raw file), filename: the name of the attachment filename } """ pass
class Sarlaccplugin: def __init__(self, logger, store): """Init method for SarlaccPlugin. Args: logger -- sarlacc logger object. store -- sarlacc store object. """ self.logger = logger self.store = store def run(self): """Runs the plugin. This method should be overridden if a plugin needs to do any initial work that isn't purely initialization. This could include starting any long running jobs / threads. """ pass def stop(self): """Stops the plugin. This method should be overridden if a plugin needs to do any extra cleanup before stopping. This could include stopping any previously started jobs / threads. """ pass async def new_attachment(self, _id, sha256, content, filename, tags): """New attachment signal. This method is called when a new, previously unseen attachment is detected. Override this method to be informed about this event. Args: _id -- the attachment postgresql record id. sha256 -- the sha256 hash of the attachment. content -- the raw file. filename -- the filename of the attachment. tags -- any tags attached to the attachment. """ pass async def new_email_address(self, _id, email_address): """New email address signal. This method is called when a new, previously unseen recipient email address is detected. Override this method to be informed about this event. Args: _id -- the email address postgresql record id. email_address -- the email address. """ pass async def new_mail_item(self, _id, subject, recipients, from_address, body, date_sent, attachments): """New email signal. This method is called when an email is received. Override this method to be informed about this event. Args: _id -- the mail item postgresql record id. subject -- the email subject. recipients -- a list of recipient email addresses. from_address -- the email address in the email's "from" header. body -- the body of the email. date_sent -- the date and time the email was sent. attachments -- a list of attachment objects in the following format: { content: the content of the attachment (raw file), filename: the name of the attachment filename } """ pass
#%% """ - Reverse Nodes in k-group - https://leetcode.com/problems/reverse-nodes-in-k-group/ - Hard Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. Example: Given this linked list: 1->2->3->4->5 For k = 2, you should return: 2->1->4->3->5 For k = 3, you should return: 3->2->1->4->5 Note: Only constant extra memory is allowed. You may not alter the values in the list's nodes, only nodes itself may be changed. """ #%% class ListNode: def __init__(self, data=0, next=None): self.data = data self.next = next #%% class S: def reverseKGroup(self, head: ListNode, k: int) -> ListNode: if not head or not head.next: return head cnt, pre, cur, nex = 1, None, head, head.next p = head while p: cnt += 1 p = p.next if cnt-1 >= k: cnt = 1 while cnt < k and nex: cnt += 1 cur.next = pre pre = cur cur = nex nex = nex.next cur.next = pre else: return cur if nex: head.next = self.reverseKGroup(nex, k) return cur #%%
""" - Reverse Nodes in k-group - https://leetcode.com/problems/reverse-nodes-in-k-group/ - Hard Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. Example: Given this linked list: 1->2->3->4->5 For k = 2, you should return: 2->1->4->3->5 For k = 3, you should return: 3->2->1->4->5 Note: Only constant extra memory is allowed. You may not alter the values in the list's nodes, only nodes itself may be changed. """ class Listnode: def __init__(self, data=0, next=None): self.data = data self.next = next class S: def reverse_k_group(self, head: ListNode, k: int) -> ListNode: if not head or not head.next: return head (cnt, pre, cur, nex) = (1, None, head, head.next) p = head while p: cnt += 1 p = p.next if cnt - 1 >= k: cnt = 1 while cnt < k and nex: cnt += 1 cur.next = pre pre = cur cur = nex nex = nex.next cur.next = pre else: return cur if nex: head.next = self.reverseKGroup(nex, k) return cur
# Implementation of a singly linked list data structure # By: Jacob Rockland # node class for linked list class Node(object): def __init__(self, data): self.data = data self.next = None # implementation of singly linked list class SinglyLinkedList(object): # initializes linked list def __init__(self, head = None, tail = None): self.head = head self.tail = tail # returns a string representation of linked list [data1, data2, ...] def __repr__(self): return repr(self.array()) # returns an array representation of linked list def array(self): array = [] curr = self.head while curr is not None: array.append(curr.data) curr = curr.next return array # adds node to end of list, O(1) def append(self, item): node = Node(item) if self.head is None: self.head = node self.tail = node else: self.tail.next = node self.tail = node # adds node to front of list, O(1) def prepend(self, item): node = Node(item) if self.head is None: self.head = node self.tail = node else: node.next = self.head self.head = node # inserts node into list after given position, O(1) def insert_after(self, curr, item): node = Node(item) if self.head is None: self.head = node self.tail = node elif curr is None: node.next = self.head self.head = node elif curr is self.tail: self.tail.next = node self.tail = node else: node.next = curr.next curr.next = node # inserts node into list in sorted position, O(n) def insert_sorted(self, item): node = Node(item) if self.head is None: self.head = node self.tail = node else: last = None curr = self.head while curr is not None and item > curr.data: last = curr curr = curr.next if curr is None: self.tail.next = node self.tail = node elif last is None: node.next = self.head self.head = node else: last.next = node node.next = curr # removes node from list after given position, O(1) def remove_after(self, curr): if self.head is None: return elif curr is None: succ = self.head.next self.head = succ if succ is None: # checks if removed last item self.tail = None elif curr.next is not None: succ = curr.next.next curr.next = succ if succ is None: # checks if removed tail item self.tail = curr # searches for a given data value in list and returns first node if found, O(n) def search(self, key): curr = self.head while curr is not None: if curr.data == key: return curr curr = curr.next return None # reverses linked list in place, O(n) def reverse(self): self.tail = self.head prev = None curr = self.head while curr is not None: succ = curr.next curr.next = prev prev = curr curr = succ self.head = prev # remove duplicates from linked list def remove_duplicates(self): if self.head is None: return curr = self.head while curr.next is not None: if curr.data == curr.next.data: curr.next = curr.next.next else: curr = curr.next
class Node(object): def __init__(self, data): self.data = data self.next = None class Singlylinkedlist(object): def __init__(self, head=None, tail=None): self.head = head self.tail = tail def __repr__(self): return repr(self.array()) def array(self): array = [] curr = self.head while curr is not None: array.append(curr.data) curr = curr.next return array def append(self, item): node = node(item) if self.head is None: self.head = node self.tail = node else: self.tail.next = node self.tail = node def prepend(self, item): node = node(item) if self.head is None: self.head = node self.tail = node else: node.next = self.head self.head = node def insert_after(self, curr, item): node = node(item) if self.head is None: self.head = node self.tail = node elif curr is None: node.next = self.head self.head = node elif curr is self.tail: self.tail.next = node self.tail = node else: node.next = curr.next curr.next = node def insert_sorted(self, item): node = node(item) if self.head is None: self.head = node self.tail = node else: last = None curr = self.head while curr is not None and item > curr.data: last = curr curr = curr.next if curr is None: self.tail.next = node self.tail = node elif last is None: node.next = self.head self.head = node else: last.next = node node.next = curr def remove_after(self, curr): if self.head is None: return elif curr is None: succ = self.head.next self.head = succ if succ is None: self.tail = None elif curr.next is not None: succ = curr.next.next curr.next = succ if succ is None: self.tail = curr def search(self, key): curr = self.head while curr is not None: if curr.data == key: return curr curr = curr.next return None def reverse(self): self.tail = self.head prev = None curr = self.head while curr is not None: succ = curr.next curr.next = prev prev = curr curr = succ self.head = prev def remove_duplicates(self): if self.head is None: return curr = self.head while curr.next is not None: if curr.data == curr.next.data: curr.next = curr.next.next else: curr = curr.next
def print_formatted(number): width = len("{0:b}".format(number)) for num in range(1, number+1): print("{0:{w}}\t{0:{w}o}\t{0:{w}X}\t{0:{w}b}".format(num, w=width)) if __name__ == '__main__': n = int(input()) print_formatted(n)
def print_formatted(number): width = len('{0:b}'.format(number)) for num in range(1, number + 1): print('{0:{w}}\t{0:{w}o}\t{0:{w}X}\t{0:{w}b}'.format(num, w=width)) if __name__ == '__main__': n = int(input()) print_formatted(n)
####################################################### # Author: Mwiza Simbeye # # Institution: African Leadership University Rwanda # # Program: Playing Card Sorting Algorithm # ####################################################### cards = [9, 10, 'J', 'K', 'Q', 'Q', 4, 5, 6, 7, 8,'A', 2, 3] ####################################################### # Convert cars to their numerical equivalent # # Example:[9, 10, 11, 12, 13, 4, 5, 6, 7, 8, 1, 2, 3] # ####################################################### converted_cards = [] for i in cards: if i == 'A': converted_cards.append(1) elif i == 'J': converted_cards.append(11) elif i == 'K': converted_cards.append(12) elif i == 'Q': converted_cards.append(13) else: converted_cards.append(i) sort = [] z = 0 while z < len(cards): smallest = converted_cards[0] for x in converted_cards: if x < smallest: smallest = x else: pass converted_cards.remove(smallest) #print (converted_cards) sort.append(smallest) #print (sort) z+=1 ####################################################### # Convert numerical values to their card equivalent # # Example: [A, 2, 3, 4, 5, 6, 7, 8, 9, 10, J, K, Q] # ####################################################### sorted_cards = [] for i in sort: if i == 1: sorted_cards.append('A') elif i == 11: sorted_cards.append('J') elif i == 12: sorted_cards.append('K') elif i == 13: sorted_cards.append('Q') else: sorted_cards.append(i) print ("The sorted cards are: "+str(sorted_cards))
cards = [9, 10, 'J', 'K', 'Q', 'Q', 4, 5, 6, 7, 8, 'A', 2, 3] converted_cards = [] for i in cards: if i == 'A': converted_cards.append(1) elif i == 'J': converted_cards.append(11) elif i == 'K': converted_cards.append(12) elif i == 'Q': converted_cards.append(13) else: converted_cards.append(i) sort = [] z = 0 while z < len(cards): smallest = converted_cards[0] for x in converted_cards: if x < smallest: smallest = x else: pass converted_cards.remove(smallest) sort.append(smallest) z += 1 sorted_cards = [] for i in sort: if i == 1: sorted_cards.append('A') elif i == 11: sorted_cards.append('J') elif i == 12: sorted_cards.append('K') elif i == 13: sorted_cards.append('Q') else: sorted_cards.append(i) print('The sorted cards are: ' + str(sorted_cards))
# Copyright: 2005-2008 Brian Harring <ferringb@gmail.com> # License: GPL2/BSD """ repository subsystem """
""" repository subsystem """
def DPLL(B, I): if len(B) == 0: return True, I for i in B: if len(i) == 0: return False, [] x = B[0][0] if x[0] != '!': x = '!' + x Bp = [[j for j in i if j != x] for i in B if not(x[1:] in i)] Ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': ' + str(True)) V, I1 = DPLL(Bp, Ip) if V: return True, I1 Bp = [[j for j in i if j != x[1:]] for i in B if not(x in i)] Ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': ' + str(False)) V, I2 = DPLL(Bp, Ip) if V: return True, I2 return False, [] expresion =[['!p', '!r', '!s'], ['!q', '!p', '!s'], ['p'], ['s']] t,r = DPLL(expresion, []) print(t) print(r)
def dpll(B, I): if len(B) == 0: return (True, I) for i in B: if len(i) == 0: return (False, []) x = B[0][0] if x[0] != '!': x = '!' + x bp = [[j for j in i if j != x] for i in B if not x[1:] in i] ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': ' + str(True)) (v, i1) = dpll(Bp, Ip) if V: return (True, I1) bp = [[j for j in i if j != x[1:]] for i in B if not x in i] ip = [i for i in I] Ip.append('Valor de ' + x[1:] + ': ' + str(False)) (v, i2) = dpll(Bp, Ip) if V: return (True, I2) return (False, []) expresion = [['!p', '!r', '!s'], ['!q', '!p', '!s'], ['p'], ['s']] (t, r) = dpll(expresion, []) print(t) print(r)
#multiplicar a nota pelo peso, depois divide a soma das notas pela soma dos pesos nota1=float(input())*2 nota2=float(input())*3 nota3=float(input())*5 media=float((nota1+nota2+nota3))/10 print("MEDIA =","%.1f"%media)
nota1 = float(input()) * 2 nota2 = float(input()) * 3 nota3 = float(input()) * 5 media = float(nota1 + nota2 + nota3) / 10 print('MEDIA =', '%.1f' % media)
VALUES_CONSTANT = "values" PREVIOUS_NODE_CONSTANT = "previous_vertex" START_NODE = "A" END_NODE = "F" # GRAPH IS 1A graph = { "A": { "B" : 5, "C" : 2 }, "B": { "E" : 4 , "D": 2 , }, "C" : { "B" : 8, "D" : 7 }, "E" : { "F" : 3 , "D" : 6 }, "D" : { "F" : 1 }, "F" : { } } # GRAPH 1B # graph = { # "A": { # "B" : 10 # }, # "B": { # "C" : 20 , # }, # "C" : { # "D" : 1 , # "E" : 30 # }, # "D" : { # "B" : 1, # }, # "E" : { # } # } # GENERATES SCORE TABLE FOR DIJKSTRA ALGORITHM def generate_score_table(): SCORE_TABLE = {} QUEUE = [START_NODE] SCORE_TABLE[START_NODE] = { VALUES_CONSTANT : 0 } VISITED = [] NEXT_FIRST_NEIGHBOR= list(graph[QUEUE[0]].keys())[0] shortest_path_length = 0 shortest_path_found_bool = False # IMPLEMENT BFS while len(QUEUE) > 0: # TRAVERSE THE EDGES for node in graph[QUEUE[0]].keys(): # IF THE !EXIST IN THE TABLE IT SHOULD INCLUDE IN THE TABLE, OTHERWISE CHECK THE VALUE cost = graph[QUEUE[0]][node] + SCORE_TABLE[QUEUE[0]][VALUES_CONSTANT] if node not in SCORE_TABLE: SCORE_TABLE[node] = { VALUES_CONSTANT : cost, PREVIOUS_NODE_CONSTANT : QUEUE[0] } else: if cost < SCORE_TABLE[node][VALUES_CONSTANT]: SCORE_TABLE[node] = { VALUES_CONSTANT: cost, PREVIOUS_NODE_CONSTANT : QUEUE[0]} if node not in VISITED and node not in QUEUE: if(NEXT_FIRST_NEIGHBOR==node and shortest_path_found_bool == False): shortest_path_length += 1 if(node == END_NODE): shortest_path_found_bool = True else: NEXT_FIRST_NEIGHBOR= list(graph[node].keys())[0] QUEUE += [node] VISITED += QUEUE[0] QUEUE.pop(0) return SCORE_TABLE,shortest_path_length def get_fastest_path(START_NODE, END_NODE, SCORE_TABLE,shortest_path): path = [] boolean_similar = False node = END_NODE while node != START_NODE: path.insert(0,node) node = SCORE_TABLE[node][PREVIOUS_NODE_CONSTANT] path.insert(0,node) if(len(path)-1 == shortest_path): boolean_similar = True else: boolean_similar = False return path, boolean_similar SCORE_TABLE,shortest_path_len = generate_score_table() fastest_path,boolean = get_fastest_path(START_NODE, END_NODE, SCORE_TABLE,shortest_path_len) print("FASTEST PATH:",fastest_path) print("BOOLEAN FOR SIMILARITY OF SHORTEST AND FASTEST:",boolean)
values_constant = 'values' previous_node_constant = 'previous_vertex' start_node = 'A' end_node = 'F' graph = {'A': {'B': 5, 'C': 2}, 'B': {'E': 4, 'D': 2}, 'C': {'B': 8, 'D': 7}, 'E': {'F': 3, 'D': 6}, 'D': {'F': 1}, 'F': {}} def generate_score_table(): score_table = {} queue = [START_NODE] SCORE_TABLE[START_NODE] = {VALUES_CONSTANT: 0} visited = [] next_first_neighbor = list(graph[QUEUE[0]].keys())[0] shortest_path_length = 0 shortest_path_found_bool = False while len(QUEUE) > 0: for node in graph[QUEUE[0]].keys(): cost = graph[QUEUE[0]][node] + SCORE_TABLE[QUEUE[0]][VALUES_CONSTANT] if node not in SCORE_TABLE: SCORE_TABLE[node] = {VALUES_CONSTANT: cost, PREVIOUS_NODE_CONSTANT: QUEUE[0]} elif cost < SCORE_TABLE[node][VALUES_CONSTANT]: SCORE_TABLE[node] = {VALUES_CONSTANT: cost, PREVIOUS_NODE_CONSTANT: QUEUE[0]} if node not in VISITED and node not in QUEUE: if NEXT_FIRST_NEIGHBOR == node and shortest_path_found_bool == False: shortest_path_length += 1 if node == END_NODE: shortest_path_found_bool = True else: next_first_neighbor = list(graph[node].keys())[0] queue += [node] visited += QUEUE[0] QUEUE.pop(0) return (SCORE_TABLE, shortest_path_length) def get_fastest_path(START_NODE, END_NODE, SCORE_TABLE, shortest_path): path = [] boolean_similar = False node = END_NODE while node != START_NODE: path.insert(0, node) node = SCORE_TABLE[node][PREVIOUS_NODE_CONSTANT] path.insert(0, node) if len(path) - 1 == shortest_path: boolean_similar = True else: boolean_similar = False return (path, boolean_similar) (score_table, shortest_path_len) = generate_score_table() (fastest_path, boolean) = get_fastest_path(START_NODE, END_NODE, SCORE_TABLE, shortest_path_len) print('FASTEST PATH:', fastest_path) print('BOOLEAN FOR SIMILARITY OF SHORTEST AND FASTEST:', boolean)
# -*- coding: utf-8 -*- # Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # This program is free software; you can redistribute it and/or modify # it under the terms of the MIT License. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MIT License for more details. csv = 'perf_Us_3' cfg_dict = { 'aux_no_0': { 'dataset': 'aux_no_0', 'p': 3, 'd': 1, 'q': 1, 'taus': [1533, 8], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'aux_smooth': { 'dataset': 'aux_smooth', 'p': 3, 'd': 1, 'q': 1, 'taus': [319, 8], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'aux_raw': { 'dataset': 'aux_raw', 'p': 3, 'd': 1, 'q': 1, 'taus': [2246, 8], 'Rs': [5, 8], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'D1': { 'dataset': 'D1_qty', 'p': 3, 'd': 1, 'q': 1, 'taus': [607, 10], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'PC_W': { 'dataset': 'PC_W', 'p': 3, 'd': 1, 'q': 1, 'taus': [9, 10], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'PC_M': { 'dataset': 'PC_M', 'p': 3, 'd': 1, 'q': 1, 'taus': [9, 10], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'ele40': { 'dataset': 'ele40', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'ele200': { 'dataset': 'ele_small', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'ele_big': { 'dataset': 'ele_big', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 1, 'filename': csv }, 'traffic_40': { 'dataset': 'traffic_40', 'p': 3, 'd': 2, 'q': 1, 'taus': [228, 5], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'traffic_80': { 'dataset': 'traffic_small', 'p': 3, 'd': 2, 'q': 1, 'taus': [228, 5], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv }, 'traffic_big': { 'dataset': 'traffic_big', 'p': 3, 'd': 2, 'q': 1, 'taus': [862, 10], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 1, 'filename': csv } }
csv = 'perf_Us_3' cfg_dict = {'aux_no_0': {'dataset': 'aux_no_0', 'p': 3, 'd': 1, 'q': 1, 'taus': [1533, 8], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'aux_smooth': {'dataset': 'aux_smooth', 'p': 3, 'd': 1, 'q': 1, 'taus': [319, 8], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'aux_raw': {'dataset': 'aux_raw', 'p': 3, 'd': 1, 'q': 1, 'taus': [2246, 8], 'Rs': [5, 8], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'D1': {'dataset': 'D1_qty', 'p': 3, 'd': 1, 'q': 1, 'taus': [607, 10], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'PC_W': {'dataset': 'PC_W', 'p': 3, 'd': 1, 'q': 1, 'taus': [9, 10], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'PC_M': {'dataset': 'PC_M', 'p': 3, 'd': 1, 'q': 1, 'taus': [9, 10], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'ele40': {'dataset': 'ele40', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'ele200': {'dataset': 'ele_small', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'ele_big': {'dataset': 'ele_big', 'p': 3, 'd': 2, 'q': 1, 'taus': [321, 20], 'Rs': [5, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 1, 'filename': csv}, 'traffic_40': {'dataset': 'traffic_40', 'p': 3, 'd': 2, 'q': 1, 'taus': [228, 5], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'traffic_80': {'dataset': 'traffic_small', 'p': 3, 'd': 2, 'q': 1, 'taus': [228, 5], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 3, 'filename': csv}, 'traffic_big': {'dataset': 'traffic_big', 'p': 3, 'd': 2, 'q': 1, 'taus': [862, 10], 'Rs': [20, 5], 'k': 15, 'tol': 0.001, 'testsize': 0.1, 'loop_time': 5, 'info': 'v2', 'Us_mode': 1, 'filename': csv}}
sal = float(input('Qual o seu salario? ')) if sal > 1250.00: print('Com o aumento seu salario sera R${:.2f}'.format(sal + (sal / 100) * 10)) else: print('Com o aumento seu salario sera R${:.2f}'.format(sal + (sal / 100) * 15))
sal = float(input('Qual o seu salario? ')) if sal > 1250.0: print('Com o aumento seu salario sera R${:.2f}'.format(sal + sal / 100 * 10)) else: print('Com o aumento seu salario sera R${:.2f}'.format(sal + sal / 100 * 15))
""" Given a nested list of integers represented as a string, implement a parser to deserialize it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Note: You may assume that the string is well-formed: String is non-empty. String does not contain white spaces. String contains only digits 0-9, [, - ,, ]. Example 1: Given s = "324", You should return a NestedInteger object which contains a single integer 324. Example 2: Given s = "[123,[456,[789]]]", Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789. """ __author__ = 'Daniel' # """ # This is the interface that allows for creating nested lists. # You should not implement it, or speculate about its implementation # """ class NestedInteger(object): def __init__(self, value=None): """ If value is not specified, initializes an empty list. Otherwise initializes a single integer equal to value. """ def isInteger(self): """ @return True if this NestedInteger holds a single integer, rather than a nested list. :rtype bool """ def add(self, elem): """ Set this NestedInteger to hold a nested list and adds a nested integer elem to it. :rtype void """ def setInteger(self, value): """ Set this NestedInteger to hold a single integer equal to value. :rtype void """ def getInteger(self): """ @return the single integer that this NestedInteger holds, if it holds a single integer Return None if this NestedInteger holds a nested list :rtype int """ def getList(self): """ @return the nested list that this NestedInteger holds, if it holds a nested list Return None if this NestedInteger holds a single integer :rtype List[NestedInteger] """ class Solution(object): def deserialize(self, s): """ NestedInteger is a UnionType in functional programming jargon. [1, [1, [2]], 3, 4] From a general example, develop an algorithm using stack The algorithm itself is easy, but the string parsing contains lots of edge cases :type s: str :rtype: NestedInteger """ if not s: return None stk = [] i = 0 while i < len(s): if s[i] == '[': stk.append(NestedInteger()) i += 1 elif s[i] == ']': ni = stk.pop() if not stk: return ni stk[-1].add(ni) i += 1 elif s[i] == ',': i += 1 else: j = i while j < len(s) and (s[j].isdigit() or s[j] == '-'): j += 1 ni = NestedInteger(int(s[i: j]) if s[i: j] else None) if not stk: return ni stk[-1].add(ni) i = j return stk.pop() if __name__ == "__main__": Solution().deserialize("[123,[456,[789]]]")
""" Given a nested list of integers represented as a string, implement a parser to deserialize it. Each element is either an integer, or a list -- whose elements may also be integers or other lists. Note: You may assume that the string is well-formed: String is non-empty. String does not contain white spaces. String contains only digits 0-9, [, - ,, ]. Example 1: Given s = "324", You should return a NestedInteger object which contains a single integer 324. Example 2: Given s = "[123,[456,[789]]]", Return a NestedInteger object containing a nested list with 2 elements: 1. An integer containing value 123. 2. A nested list containing two elements: i. An integer containing value 456. ii. A nested list with one element: a. An integer containing value 789. """ __author__ = 'Daniel' class Nestedinteger(object): def __init__(self, value=None): """ If value is not specified, initializes an empty list. Otherwise initializes a single integer equal to value. """ def is_integer(self): """ @return True if this NestedInteger holds a single integer, rather than a nested list. :rtype bool """ def add(self, elem): """ Set this NestedInteger to hold a nested list and adds a nested integer elem to it. :rtype void """ def set_integer(self, value): """ Set this NestedInteger to hold a single integer equal to value. :rtype void """ def get_integer(self): """ @return the single integer that this NestedInteger holds, if it holds a single integer Return None if this NestedInteger holds a nested list :rtype int """ def get_list(self): """ @return the nested list that this NestedInteger holds, if it holds a nested list Return None if this NestedInteger holds a single integer :rtype List[NestedInteger] """ class Solution(object): def deserialize(self, s): """ NestedInteger is a UnionType in functional programming jargon. [1, [1, [2]], 3, 4] From a general example, develop an algorithm using stack The algorithm itself is easy, but the string parsing contains lots of edge cases :type s: str :rtype: NestedInteger """ if not s: return None stk = [] i = 0 while i < len(s): if s[i] == '[': stk.append(nested_integer()) i += 1 elif s[i] == ']': ni = stk.pop() if not stk: return ni stk[-1].add(ni) i += 1 elif s[i] == ',': i += 1 else: j = i while j < len(s) and (s[j].isdigit() or s[j] == '-'): j += 1 ni = nested_integer(int(s[i:j]) if s[i:j] else None) if not stk: return ni stk[-1].add(ni) i = j return stk.pop() if __name__ == '__main__': solution().deserialize('[123,[456,[789]]]')
class QuizQuestion: def __init__(self, text, answer): self.text = text self.answer = answer @property def text(self): return self.__text @text.setter def text(self, text): self.__text = text @property def answer(self): return self.__answer @answer.setter def answer(self, answer): self.__answer = answer
class Quizquestion: def __init__(self, text, answer): self.text = text self.answer = answer @property def text(self): return self.__text @text.setter def text(self, text): self.__text = text @property def answer(self): return self.__answer @answer.setter def answer(self, answer): self.__answer = answer
class Model: def __init__(self): self._classes = {} self._relations = {} self._generalizations = {} self._associationLinks = {} def addClass(self, _class): self._classes[_class.uid()] = _class def classByUid(self, uid): return self._classes[uid] def addRelation(self, relation): lClass = relation.leftAssociation()._class().relate(relation) rClass = relation.rightAssociation()._class().relate(relation) self._relations[relation.uid()] = relation def addGeneralization(self, generalization): self._generalizations[generalization.uid()] = generalization def addAssociationLink(self, assoclink): self._associationLinks[assoclink.uid()] = assoclink def relationByUid(self, uid): return self._relations[uid] def classes(self): return self._classes def relations(self): return self._relations def generalizations(self): return self._generalizations def associationLinks(self): return self._associationLinks def superClassOf(self, _class): superclass = None for generalization in self._generalizations.values(): if generalization.subclass() == _class: superclass = generalization.superclass() break return superclass
class Model: def __init__(self): self._classes = {} self._relations = {} self._generalizations = {} self._associationLinks = {} def add_class(self, _class): self._classes[_class.uid()] = _class def class_by_uid(self, uid): return self._classes[uid] def add_relation(self, relation): l_class = relation.leftAssociation()._class().relate(relation) r_class = relation.rightAssociation()._class().relate(relation) self._relations[relation.uid()] = relation def add_generalization(self, generalization): self._generalizations[generalization.uid()] = generalization def add_association_link(self, assoclink): self._associationLinks[assoclink.uid()] = assoclink def relation_by_uid(self, uid): return self._relations[uid] def classes(self): return self._classes def relations(self): return self._relations def generalizations(self): return self._generalizations def association_links(self): return self._associationLinks def super_class_of(self, _class): superclass = None for generalization in self._generalizations.values(): if generalization.subclass() == _class: superclass = generalization.superclass() break return superclass
''' 08 - Finding ambiguous datetimes At the end of lesson 2, we saw something anomalous in our bike trip duration data. Let's see if we can identify what the problem might be. The data is loaded as onebike_datetimes, and tz has already been imported from dateutil. Instructions - Loop over the trips in onebike_datetimes: - Print any rides whose start is ambiguous. - Print any rides whose end is ambiguous. ''' # Loop over trips for trip in onebike_datetimes: # Rides with ambiguous start if tz.datetime_ambiguous(trip['start']): print("Ambiguous start at " + str(trip['start'])) # Rides with ambiguous end if tz.datetime_ambiguous(trip['end']): print("Ambiguous end at " + str(trip['end'])) # Ambiguous start at 2017-11-05 01:56:50-04:00 # Ambiguous end at 2017-11-05 01: 01: 04-04: 00
""" 08 - Finding ambiguous datetimes At the end of lesson 2, we saw something anomalous in our bike trip duration data. Let's see if we can identify what the problem might be. The data is loaded as onebike_datetimes, and tz has already been imported from dateutil. Instructions - Loop over the trips in onebike_datetimes: - Print any rides whose start is ambiguous. - Print any rides whose end is ambiguous. """ for trip in onebike_datetimes: if tz.datetime_ambiguous(trip['start']): print('Ambiguous start at ' + str(trip['start'])) if tz.datetime_ambiguous(trip['end']): print('Ambiguous end at ' + str(trip['end']))
_base_ = [ '../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/openBrand_detection.py', '../_base_/default_runtime.py' ] data = dict( samples_per_gpu=4, workers_per_gpu=2, ) # model settings model = dict( neck=[ dict( type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), dict( type='BFP', in_channels=256, num_levels=5, refine_level=2, refine_type='non_local') ], roi_head=dict( bbox_head=dict( num_classes=515, loss_bbox=dict( _delete_=True, type='BalancedL1Loss', alpha=0.5, gamma=1.5, beta=1.0, loss_weight=1.0))), # model training and testing settings train_cfg=dict( rpn=dict(sampler=dict(neg_pos_ub=5), allowed_border=-1), rcnn=dict( sampler=dict( _delete_=True, type='CombinedSampler', num=512, pos_fraction=0.25, add_gt_as_proposals=True, pos_sampler=dict(type='InstanceBalancedPosSampler'), neg_sampler=dict( type='IoUBalancedNegSampler', floor_thr=-1, floor_fraction=0, num_bins=3) ) ) ) ) # optimizer optimizer = dict(type='SGD', lr=0.04, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=10000, warmup_ratio=0.001, step=[8, 11]) runner = dict(type='EpochBasedRunner', max_epochs=12)
_base_ = ['../_base_/models/faster_rcnn_r50_fpn.py', '../_base_/datasets/openBrand_detection.py', '../_base_/default_runtime.py'] data = dict(samples_per_gpu=4, workers_per_gpu=2) model = dict(neck=[dict(type='FPN', in_channels=[256, 512, 1024, 2048], out_channels=256, num_outs=5), dict(type='BFP', in_channels=256, num_levels=5, refine_level=2, refine_type='non_local')], roi_head=dict(bbox_head=dict(num_classes=515, loss_bbox=dict(_delete_=True, type='BalancedL1Loss', alpha=0.5, gamma=1.5, beta=1.0, loss_weight=1.0))), train_cfg=dict(rpn=dict(sampler=dict(neg_pos_ub=5), allowed_border=-1), rcnn=dict(sampler=dict(_delete_=True, type='CombinedSampler', num=512, pos_fraction=0.25, add_gt_as_proposals=True, pos_sampler=dict(type='InstanceBalancedPosSampler'), neg_sampler=dict(type='IoUBalancedNegSampler', floor_thr=-1, floor_fraction=0, num_bins=3))))) optimizer = dict(type='SGD', lr=0.04, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='step', warmup='linear', warmup_iters=10000, warmup_ratio=0.001, step=[8, 11]) runner = dict(type='EpochBasedRunner', max_epochs=12)
''' Problem statement: Given a binary tree, find if it is height balanced or not. A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree. ''' class Node: # Constructor to create a new Node def __init__(self, data): self.data = data self.left = None self.right = None def get_height(root): if root is None: return 0 return 1 + max(get_height(root.left), get_height(root.right)) def isBalanced(root): if root is None: return 1 left_tree_height = get_height(root.left) right_tree_height = get_height(root.right) if abs(left_tree_height - right_tree_height) > 1: return False return isBalanced(root.left) and isBalanced(root.right) # Initial Template for Python 3 if __name__ == '__main__': root = None t = int(input()) for i in range(t): # root = None n = int(input()) arr = input().strip().split() if n == 0: print(0) continue dictTree = dict() for j in range(n): if arr[3 * j] not in dictTree: dictTree[arr[3 * j]] = Node(arr[3 * j]) parent = dictTree[arr[3 * j]] if j is 0: root = parent else: parent = dictTree[arr[3 * j]] child = Node(arr[3 * j + 1]) if (arr[3 * j + 2] == 'L'): parent.left = child else: parent.right = child dictTree[arr[3 * j + 1]] = child if isBalanced(root): print(1) else: print(0)
""" Problem statement: Given a binary tree, find if it is height balanced or not. A tree is height balanced if difference between heights of left and right subtrees is not more than one for all nodes of tree. """ class Node: def __init__(self, data): self.data = data self.left = None self.right = None def get_height(root): if root is None: return 0 return 1 + max(get_height(root.left), get_height(root.right)) def is_balanced(root): if root is None: return 1 left_tree_height = get_height(root.left) right_tree_height = get_height(root.right) if abs(left_tree_height - right_tree_height) > 1: return False return is_balanced(root.left) and is_balanced(root.right) if __name__ == '__main__': root = None t = int(input()) for i in range(t): n = int(input()) arr = input().strip().split() if n == 0: print(0) continue dict_tree = dict() for j in range(n): if arr[3 * j] not in dictTree: dictTree[arr[3 * j]] = node(arr[3 * j]) parent = dictTree[arr[3 * j]] if j is 0: root = parent else: parent = dictTree[arr[3 * j]] child = node(arr[3 * j + 1]) if arr[3 * j + 2] == 'L': parent.left = child else: parent.right = child dictTree[arr[3 * j + 1]] = child if is_balanced(root): print(1) else: print(0)
# Copyright 2016 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. inas = [('ina219', '0x40', 'pp1050_s', 1.05, 0.010, 'rem', True), ('ina219', '0x41', 'pp1800_a', 1.80, 0.010, 'rem', True), ('ina219', '0x42', 'pp1200_vddq', 1.20, 0.010, 'rem', True), ('ina219', '0x43', 'pp3300_a', 3.30, 0.010, 'rem', True), ('ina219', '0x44', 'ppvbat', 7.50, 0.010, 'rem', True), ('ina219', '0x47', 'ppvccgi', 1.00, 0.010, 'rem', True), ('ina219', '0x49', 'ppvnn', 1.00, 0.010, 'rem', True), ('ina219', '0x4a', 'pp1240_a', 1.24, 0.010, 'rem', True), ('ina219', '0x4b', 'pp5000_a', 5.00, 0.010, 'rem', True)]
inas = [('ina219', '0x40', 'pp1050_s', 1.05, 0.01, 'rem', True), ('ina219', '0x41', 'pp1800_a', 1.8, 0.01, 'rem', True), ('ina219', '0x42', 'pp1200_vddq', 1.2, 0.01, 'rem', True), ('ina219', '0x43', 'pp3300_a', 3.3, 0.01, 'rem', True), ('ina219', '0x44', 'ppvbat', 7.5, 0.01, 'rem', True), ('ina219', '0x47', 'ppvccgi', 1.0, 0.01, 'rem', True), ('ina219', '0x49', 'ppvnn', 1.0, 0.01, 'rem', True), ('ina219', '0x4a', 'pp1240_a', 1.24, 0.01, 'rem', True), ('ina219', '0x4b', 'pp5000_a', 5.0, 0.01, 'rem', True)]
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. load("//antlir/bzl:shape.bzl", "shape") conf_t = shape.shape( nameservers = shape.list(str), search_domains = shape.list(str), )
load('//antlir/bzl:shape.bzl', 'shape') conf_t = shape.shape(nameservers=shape.list(str), search_domains=shape.list(str))
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return "{} -> {}".format(self.val, self.next) class Solution: def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ current = head dummy = head while current: runner = current.next while runner and current.val == runner.val: runner = runner.next current.next = runner current = runner return head if __name__ == "__main__": head, head.next, head.next.next = ListNode(1), ListNode(1), ListNode(2) head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(3) print(head) print(Solution().deleteDuplicates(head)) """ Time Complexity = O(n) Space Complexity = O(1) Given a sorted linked list, delete all duplicates such that each element appear only once. Example: Input: 1->1->2->3->3 Output: 1->2->3 """
class Listnode: def __init__(self, x): self.val = x self.next = None def __repr__(self): if self: return '{} -> {}'.format(self.val, self.next) class Solution: def delete_duplicates(self, head): """ :type head: ListNode :rtype: ListNode """ current = head dummy = head while current: runner = current.next while runner and current.val == runner.val: runner = runner.next current.next = runner current = runner return head if __name__ == '__main__': (head, head.next, head.next.next) = (list_node(1), list_node(1), list_node(2)) (head.next.next.next, head.next.next.next.next) = (list_node(3), list_node(3)) print(head) print(solution().deleteDuplicates(head)) '\n Time Complexity = O(n)\n Space Complexity = O(1)\n\n Given a sorted linked list, delete all duplicates such that each element appear only once.\n\n Example:\n Input: 1->1->2->3->3\n Output: 1->2->3\n '
# Sudoku problem solved using backtracking def solve_sudoku(array): is_empty_cell_found = False; # Finding if there is any empty cell for i in range(0, 9): for j in range(0, 9): if array[i][j] == 0: row, col = i, j is_empty_cell_found = True break if is_empty_cell_found: break # print('row', row, 'col', col, 'is_empty_cell_found', is_empty_cell_found) if not is_empty_cell_found: return True for num in range(1, 10): # print(num) if _is_valid_move(array, row, col, num): # print('is valid move') array[row][col] = num if solve_sudoku(array): return True else: array[row][col] = 0 return False def _is_valid_move(array, row, col, num): # Checking row if same num already exists for i in range(0, 9): if array[row][i] == num: return False # Checking column if same num already exists for i in range(0, 9): if array[i][col] == num: return False # Checking the current cube row_start = row - row % 3 column_start = col - col % 3 # print(row_start, column_start) for i in range(row_start, row_start + 3): for j in range(column_start, column_start + 3): if array[i][j] == num: # print('matched in grid') return False return True def print_array(array): for i in range(0, 9): for j in range(0, 9): print(sudoku_array[i][j], end = " ") print() if __name__ == '__main__': sudoku_array = [[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] solve_sudoku(sudoku_array) print_array(sudoku_array)
def solve_sudoku(array): is_empty_cell_found = False for i in range(0, 9): for j in range(0, 9): if array[i][j] == 0: (row, col) = (i, j) is_empty_cell_found = True break if is_empty_cell_found: break if not is_empty_cell_found: return True for num in range(1, 10): if _is_valid_move(array, row, col, num): array[row][col] = num if solve_sudoku(array): return True else: array[row][col] = 0 return False def _is_valid_move(array, row, col, num): for i in range(0, 9): if array[row][i] == num: return False for i in range(0, 9): if array[i][col] == num: return False row_start = row - row % 3 column_start = col - col % 3 for i in range(row_start, row_start + 3): for j in range(column_start, column_start + 3): if array[i][j] == num: return False return True def print_array(array): for i in range(0, 9): for j in range(0, 9): print(sudoku_array[i][j], end=' ') print() if __name__ == '__main__': sudoku_array = [[3, 0, 6, 5, 0, 8, 4, 0, 0], [5, 2, 0, 0, 0, 0, 0, 0, 0], [0, 8, 7, 0, 0, 0, 0, 3, 1], [0, 0, 3, 0, 1, 0, 0, 8, 0], [9, 0, 0, 8, 6, 3, 0, 0, 5], [0, 5, 0, 0, 9, 0, 6, 0, 0], [1, 3, 0, 0, 0, 0, 2, 5, 0], [0, 0, 0, 0, 0, 0, 0, 7, 4], [0, 0, 5, 2, 0, 6, 3, 0, 0]] solve_sudoku(sudoku_array) print_array(sudoku_array)
# All rights reserved by forest fairy. # You cannot modify or share anything without sacrifice. # If you don't agree, keep calm and don't look at code bellow! __author__ = "VirtualV <https://github.com/virtualvfix>" __date__ = "03/22/18 15:40" class InstallError(Exception): """ Install exception base class. """ def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class ApkNotFoundError(InstallError): def __init__(self, value): super(ApkNotFoundError, self).__init__(value)
__author__ = 'VirtualV <https://github.com/virtualvfix>' __date__ = '03/22/18 15:40' class Installerror(Exception): """ Install exception base class. """ def __init__(self, value): self.value = value def __str__(self): return repr(self.value) class Apknotfounderror(InstallError): def __init__(self, value): super(ApkNotFoundError, self).__init__(value)
#SetExample4.py ------difference between discard() & remove() #from both remove() gives error if value not found nums = {1,2,3,4} #remove using discard() nums.discard(5) print("After discard(5) : ",nums) #reove using remove() try: nums.remove(5) print("After remove(5) : ",nums) except KeyError: print("KeyError : Value not found")
nums = {1, 2, 3, 4} nums.discard(5) print('After discard(5) : ', nums) try: nums.remove(5) print('After remove(5) : ', nums) except KeyError: print('KeyError : Value not found')
class Item: def __init__(self, name, price, quantity): self._name = name self.set_price(price) self.set_quantity(quantity) def get_name(self): return self._name def get_price(self): return self._price def get_quantity(self): return self._quantity def set_price(self, price): if price > 0: self._price = price # todo - defensive checks def set_quantity(self, quantity): if quantity >= 0: self._quantity = quantity # todo - defensive checks def buy(self, quantity_to_buy): if quantity_to_buy <= self._quantity: self._quantity -= quantity_to_buy return quantity_to_buy * self._price return 0
class Item: def __init__(self, name, price, quantity): self._name = name self.set_price(price) self.set_quantity(quantity) def get_name(self): return self._name def get_price(self): return self._price def get_quantity(self): return self._quantity def set_price(self, price): if price > 0: self._price = price def set_quantity(self, quantity): if quantity >= 0: self._quantity = quantity def buy(self, quantity_to_buy): if quantity_to_buy <= self._quantity: self._quantity -= quantity_to_buy return quantity_to_buy * self._price return 0
""" Constants for django Organice. """ ORGANICE_DJANGO_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', ] ORGANICE_CMS_APPS = [ 'cms', 'mptt', 'menus', 'sekizai', 'treebeard', 'easy_thumbnails', 'djangocms_admin_style', # 'djangocms_file', 'djangocms_maps', 'djangocms_inherit', 'djangocms_link', 'djangocms_picture', # 'djangocms_teaser', 'djangocms_text_ckeditor', # 'media_tree', # 'media_tree.contrib.cms_plugins.media_tree_image', # 'media_tree.contrib.cms_plugins.media_tree_gallery', # 'media_tree.contrib.cms_plugins.media_tree_slideshow', # 'media_tree.contrib.cms_plugins.media_tree_listing', # 'form_designer.contrib.cms_plugins.form_designer_form', ] ORGANICE_BLOG_APPS = [ 'cmsplugin_zinnia', 'django_comments', 'tagging', 'zinnia', ] ORGANICE_NEWSLETTER_APPS = [ # 'emencia.django.newsletter', 'tinymce', ] ORGANICE_UTIL_APPS = [ 'analytical', 'simple_links', 'todo', ] ORGANICE_AUTH_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.amazon', # 'allauth.socialaccount.providers.angellist', 'allauth.socialaccount.providers.bitbucket', 'allauth.socialaccount.providers.bitly', 'allauth.socialaccount.providers.dropbox_oauth2', 'allauth.socialaccount.providers.facebook', # 'allauth.socialaccount.providers.flickr', # 'allauth.socialaccount.providers.feedly', 'allauth.socialaccount.providers.github', 'allauth.socialaccount.providers.gitlab', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.instagram', 'allauth.socialaccount.providers.linkedin_oauth2', # 'allauth.socialaccount.providers.openid', 'allauth.socialaccount.providers.pinterest', 'allauth.socialaccount.providers.slack', 'allauth.socialaccount.providers.soundcloud', 'allauth.socialaccount.providers.stackexchange', # 'allauth.socialaccount.providers.tumblr', # 'allauth.socialaccount.providers.twitch', 'allauth.socialaccount.providers.twitter', 'allauth.socialaccount.providers.vimeo', # 'allauth.socialaccount.providers.vk', # 'allauth.socialaccount.providers.weibo', 'allauth.socialaccount.providers.windowslive', 'allauth.socialaccount.providers.xing', ]
""" Constants for django Organice. """ organice_django_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin'] organice_cms_apps = ['cms', 'mptt', 'menus', 'sekizai', 'treebeard', 'easy_thumbnails', 'djangocms_admin_style', 'djangocms_maps', 'djangocms_inherit', 'djangocms_link', 'djangocms_picture', 'djangocms_text_ckeditor'] organice_blog_apps = ['cmsplugin_zinnia', 'django_comments', 'tagging', 'zinnia'] organice_newsletter_apps = ['tinymce'] organice_util_apps = ['analytical', 'simple_links', 'todo'] organice_auth_apps = ['allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.amazon', 'allauth.socialaccount.providers.bitbucket', 'allauth.socialaccount.providers.bitly', 'allauth.socialaccount.providers.dropbox_oauth2', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.github', 'allauth.socialaccount.providers.gitlab', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.instagram', 'allauth.socialaccount.providers.linkedin_oauth2', 'allauth.socialaccount.providers.pinterest', 'allauth.socialaccount.providers.slack', 'allauth.socialaccount.providers.soundcloud', 'allauth.socialaccount.providers.stackexchange', 'allauth.socialaccount.providers.twitter', 'allauth.socialaccount.providers.vimeo', 'allauth.socialaccount.providers.windowslive', 'allauth.socialaccount.providers.xing']
""" dp """ class Solution: def uniquePaths(self, row: int, col: int) -> int: """ Since only 2 options are possible, either from the cell above or left, it is a dp problem. """ def is_valid(i, j): if i >= row or j >= col or i < 0 or j < 0: return False else: return True dp = [[0 for j in range(col)] for i in range(row)] for i in range(row): for j in range(col): if i ==0 and j ==0: dp[i][j] = 1 if is_valid(i -1, j): dp[i][j] += dp[i-1][j] if is_valid(i, j-1): dp[i][j] += dp[i][j-1] return dp[row-1][col-1] inp = (3,2) s = Solution() res = s.uniquePaths(*inp) print(res)
""" dp """ class Solution: def unique_paths(self, row: int, col: int) -> int: """ Since only 2 options are possible, either from the cell above or left, it is a dp problem. """ def is_valid(i, j): if i >= row or j >= col or i < 0 or (j < 0): return False else: return True dp = [[0 for j in range(col)] for i in range(row)] for i in range(row): for j in range(col): if i == 0 and j == 0: dp[i][j] = 1 if is_valid(i - 1, j): dp[i][j] += dp[i - 1][j] if is_valid(i, j - 1): dp[i][j] += dp[i][j - 1] return dp[row - 1][col - 1] inp = (3, 2) s = solution() res = s.uniquePaths(*inp) print(res)
class Solution: def makeConnected(self, n: int, connections: List[List[int]]) -> int: if len(connections) < n-1: return -1 adjacency = [set() for _ in range(n)] for x,y in connections: adjacency[x].add(y) adjacency[y].add(x) components = 0 visited = [False]*n for i in range(n): if visited[i]: continue stack = [i] components += 1 while stack: x = stack.pop() visited[x]=True for neighbor in adjacency[x]: if not visited[neighbor]: stack.append(neighbor) return components - 1
class Solution: def make_connected(self, n: int, connections: List[List[int]]) -> int: if len(connections) < n - 1: return -1 adjacency = [set() for _ in range(n)] for (x, y) in connections: adjacency[x].add(y) adjacency[y].add(x) components = 0 visited = [False] * n for i in range(n): if visited[i]: continue stack = [i] components += 1 while stack: x = stack.pop() visited[x] = True for neighbor in adjacency[x]: if not visited[neighbor]: stack.append(neighbor) return components - 1
class Solution: def bitwiseComplement(self, N: int) -> int: if N == 0: return 1 ans = 0 i = 0 while N: r = N % 2 ans += 2 ** i * (1 - r) i += 1 N //= 2 return ans
class Solution: def bitwise_complement(self, N: int) -> int: if N == 0: return 1 ans = 0 i = 0 while N: r = N % 2 ans += 2 ** i * (1 - r) i += 1 n //= 2 return ans
"""Utils related to urls.""" def uri_scheme_behind_proxy(request, url): """ Fix uris with forwarded protocol. When behind a proxy, django is reached in http, so generated urls are using http too. """ if request.META.get("HTTP_X_FORWARDED_PROTO", "http") == "https": url = url.replace("http:", "https:", 1) return url def build_absolute_uri_behind_proxy(request, url=None): """build_absolute_uri behind a proxy.""" return uri_scheme_behind_proxy(request, request.build_absolute_uri(url))
"""Utils related to urls.""" def uri_scheme_behind_proxy(request, url): """ Fix uris with forwarded protocol. When behind a proxy, django is reached in http, so generated urls are using http too. """ if request.META.get('HTTP_X_FORWARDED_PROTO', 'http') == 'https': url = url.replace('http:', 'https:', 1) return url def build_absolute_uri_behind_proxy(request, url=None): """build_absolute_uri behind a proxy.""" return uri_scheme_behind_proxy(request, request.build_absolute_uri(url))
a, b, c = input().split(' ') d, e, f = input().split(' ') g, h, i = input().split(' ') a = int(a) b = int(b) c = int(c) d = int(d) e = int(e) f = int(f) g = int(g) h = int(h) i = int(i) def resto(a, b, c): return (a + b) % c resultado_1 = resto(a, b, c) resultado_2 = resto(d, e, f) resultado_3 = resto(g, h, i) print(resultado_1) print(resultado_2) print(resultado_3)
(a, b, c) = input().split(' ') (d, e, f) = input().split(' ') (g, h, i) = input().split(' ') a = int(a) b = int(b) c = int(c) d = int(d) e = int(e) f = int(f) g = int(g) h = int(h) i = int(i) def resto(a, b, c): return (a + b) % c resultado_1 = resto(a, b, c) resultado_2 = resto(d, e, f) resultado_3 = resto(g, h, i) print(resultado_1) print(resultado_2) print(resultado_3)
jogador = {} time = [] lista = [] total = 0 while True: jogador.clear() jogador['Nome'] = input('Nome do jogador: ') quantidade = int(input('Quantas partidas {} jogou ? '.format(jogador['Nome']))) lista.clear() for i in range(0, quantidade): gol_quantidade = int(input('Quantos gols na partida {} ? '.format(i + 1))) total += gol_quantidade lista.append(gol_quantidade) jogador['Gols'] = lista jogador['Total'] = total time.append(jogador.copy()) resposta = str(input('Quer continuar ? [S/N] ')) if resposta in 'Nn': break for k, v in enumerate(time): print(f'{k:>3} ', end='') for d in v.values(): print(f'{str(d):<15}', end='') print('') print('-=' * 30) print('O jogador {} jogou {} partidas'.format(jogador['Nome'], quantidade)) for i, valor in enumerate(jogador['Gols']): print(' => Na partida {} , fez {} gols'.format(i + 1, valor)) print('Foi um total de {} gols'.format(total))
jogador = {} time = [] lista = [] total = 0 while True: jogador.clear() jogador['Nome'] = input('Nome do jogador: ') quantidade = int(input('Quantas partidas {} jogou ? '.format(jogador['Nome']))) lista.clear() for i in range(0, quantidade): gol_quantidade = int(input('Quantos gols na partida {} ? '.format(i + 1))) total += gol_quantidade lista.append(gol_quantidade) jogador['Gols'] = lista jogador['Total'] = total time.append(jogador.copy()) resposta = str(input('Quer continuar ? [S/N] ')) if resposta in 'Nn': break for (k, v) in enumerate(time): print(f'{k:>3} ', end='') for d in v.values(): print(f'{str(d):<15}', end='') print('') print('-=' * 30) print('O jogador {} jogou {} partidas'.format(jogador['Nome'], quantidade)) for (i, valor) in enumerate(jogador['Gols']): print(' => Na partida {} , fez {} gols'.format(i + 1, valor)) print('Foi um total de {} gols'.format(total))
def df_restructure_values(data, structure='list', destructive=False): '''Takes in a dataframe, and restructures the values so that the output dataframe consist of columns where the value is coupled with the column header. data | DataFrame | a pandas dataframe structure | str | 'list', 'str', 'tuple', or 'dict' destructive | bool | if False, the original dataframe will be retained ''' if destructive is False: data = data.copy(deep=True) for col in data: if structure == 'list': data[col] = [[col, i] for i in data[col]] elif structure == 'str': data[col] = [col + ' ' + i for i in data[col].astype(str)] elif structure == 'dict': data[col] = [{col: i} for i in data[col]] elif structure == 'tuple': data[col] = [(col, i) for i in data[col]] return data
def df_restructure_values(data, structure='list', destructive=False): """Takes in a dataframe, and restructures the values so that the output dataframe consist of columns where the value is coupled with the column header. data | DataFrame | a pandas dataframe structure | str | 'list', 'str', 'tuple', or 'dict' destructive | bool | if False, the original dataframe will be retained """ if destructive is False: data = data.copy(deep=True) for col in data: if structure == 'list': data[col] = [[col, i] for i in data[col]] elif structure == 'str': data[col] = [col + ' ' + i for i in data[col].astype(str)] elif structure == 'dict': data[col] = [{col: i} for i in data[col]] elif structure == 'tuple': data[col] = [(col, i) for i in data[col]] return data
T,R=int(input('Enter no. Test Cases: ')),[] while(T>0): P=[int(x) for x in input('Enter No. Cases,Sum: ').split()] A=sorted([int(x) for x in input('Enter Numbers(A): ').split()][:P[0]]) B=sorted([int(x) for x in input('Enter Numbers(B): ').split()][:P[0]]) for i in range(P[0]): if A[i]+B[-(i+1)]>P[1]: R.append('No') break elif i==P[0]-1: R.append('Yes') T-=1 for T in R: print('Output:',T)
(t, r) = (int(input('Enter no. Test Cases: ')), []) while T > 0: p = [int(x) for x in input('Enter No. Cases,Sum: ').split()] a = sorted([int(x) for x in input('Enter Numbers(A): ').split()][:P[0]]) b = sorted([int(x) for x in input('Enter Numbers(B): ').split()][:P[0]]) for i in range(P[0]): if A[i] + B[-(i + 1)] > P[1]: R.append('No') break elif i == P[0] - 1: R.append('Yes') t -= 1 for t in R: print('Output:', T)
# Copyright 2012 Justas Sadzevicius # Licensed under the MIT license: http://www.opensource.org/licenses/MIT # Notes library for Finch buzzer #("Middle C" is C4 ) frequencies = { 'C0': 16.35, 'C#0': 17.32, 'Db0': 17.32, 'D0': 18.35, 'D#0': 19.45, 'Eb0': 19.45, 'E0': 20.6, 'F0': 21.83, 'F#0': 23.12, 'Gb0': 23.12, 'G0': 24.5, 'G#0': 25.96, 'Ab0': 25.96, 'A0': 27.5, 'A#0': 29.14, 'Bb0': 29.14, 'B0': 30.87, 'C1': 32.7, 'C#1': 34.65, 'Db1': 34.65, 'D1': 36.71, 'D#1': 38.89, 'Eb1': 38.89, 'E1': 41.2, 'F1': 43.65, 'F#1': 46.25, 'Gb1': 46.25, 'G1': 49.0, 'G#1': 51.91, 'Ab1': 51.91, 'A1': 55.0, 'A#1': 58.27, 'Bb1': 58.27, 'B1': 61.74, 'C2': 65.41, 'C#2': 69.3, 'Db2': 69.3, 'D2': 73.42, 'D#2': 77.78, 'Eb2': 77.78, 'E2': 82.41, 'F2': 87.31, 'F#2': 92.5, 'Gb2': 92.5, 'G2': 98.0, 'G#2': 103.83, 'Ab2': 103.83, 'A2': 110.0, 'A#2': 116.54, 'Bb2': 116.54, 'B2': 123.47, 'C3': 130.81, 'C#3': 138.59, 'Db3': 138.59, 'D3': 146.83, 'D#3': 155.56, 'Eb3': 155.56, 'E3': 164.81, 'F3': 174.61, 'F#3': 185.0, 'Gb3': 185.0, 'G3': 196.0, 'G#3': 207.65, 'Ab3': 207.65, 'A3': 220.0, 'A#3': 233.08, 'Bb3': 233.08, 'B3': 246.94, 'C4': 261.63, 'C#4': 277.18, 'Db4': 277.18, 'D4': 293.66, 'D#4': 311.13, 'Eb4': 311.13, 'E4': 329.63, 'F4': 349.23, 'F#4': 369.99, 'Gb4': 369.99, 'G4': 392.0, 'G#4': 415.3, 'Ab4': 415.3, 'A4': 440.0, 'A#4': 466.16, 'Bb4': 466.16, 'B4': 493.88, 'C5': 523.25, 'C#5': 554.37, 'Db5': 554.37, 'D5': 587.33, 'D#5': 622.25, 'Eb5': 622.25, 'E5': 659.26, 'F5': 698.46, 'F#5': 739.99, 'Gb5': 739.99, 'G5': 783.99, 'G#5': 830.61, 'Ab5': 830.61, 'A5': 880.0, 'A#5': 932.33, 'Bb5': 932.33, 'B5': 987.77, 'C6': 1046.5, 'C#6': 1108.73, 'Db6': 1108.73, 'D6': 1174.66, 'D#6': 1244.51, 'Eb6': 1244.51, 'E6': 1318.51, 'F6': 1396.91, 'F#6': 1479.98, 'Gb6': 1479.98, 'G6': 1567.98, 'G#6': 1661.22, 'Ab6': 1661.22, 'A6': 1760.0, 'A#6': 1864.66, 'Bb6': 1864.66, 'B6': 1975.53, 'C7': 2093.0, 'C#7': 2217.46, 'Db7': 2217.46, 'D7': 2349.32, 'D#7': 2489.02, 'Eb7': 2489.02, 'E7': 2637.02, 'F7': 2793.83, 'F#7': 2959.96, 'Gb7': 2959.96, 'G7': 3135.96, 'G#7': 3322.44, 'Ab7': 3322.44, 'A7': 3520.0, 'A#7': 3729.31, 'Bb7': 3729.31, 'B7': 3951.07, 'C8': 4186.01, 'C#8': 4434.92, 'Db8': 4434.92, 'D8': 4698.64, 'D#8': 4978.03, 'Eb8': 4978.03, } class Command(object): octave = 4 note = '' duration = 0 sym = '' def reset(self): self.note = '' self.duration = 0 self.sym = '' def emit(self): if not self.note or not self.duration: return None if self.note == '-': return (0, self.duration) ref = self.note.upper()+self.sym+str(self.octave) frequency = frequencies.get(ref) if not frequency: return None return (frequency, self.duration) def parse(sheet, speed=0.25): """Parse a sheet of notes to a sequence of (duration, frequency) commands. speed is a duration of a "tick" in seconds. Each *symbol* in the sheet takes up one tick. Valid notes are C, D, E, F, G, A, B and - (which means silence). Sheet can also contain semitones: C#, Eb, etc. You can change active octave with numbers 0-8. Here are some examples: To play Do for four ticks and then Re for eight ticks, pass: 'C D ' To play Do for two ticks, then silence for two ticks, then Do again: 'C - C ' To play Do Re Mi, but octave higher: 'C5D E ' parse('C3E G E ', speed=0.25) will play C major chord over 2 seconds parse('C3 Eb G Eb ', speed=0.125) will play C minor chord over 2 seconds also """ sheet = list(sheet) commands = [] next = Command() while sheet: #pop off a token token = sheet.pop(0) #if next note is reached, append the current note onto the commands if (token in 'CDEFGAB-' and next.note): entry = next.emit() if entry: commands.append(entry) next.reset() #set the next note equal to the token next.note = token #special case for the first note if (token in 'CDEFGAB-' and not next.note): next.note = token #handle octaves elif token.isdigit(): next.octave = int(token) next.duration -= speed #handle flats and sharps elif ((token == '#' or token == 'b') and next.note): next.sym = token next.duration -= speed #rhythm next.duration += speed #append the last note into the commands entry = next.emit() if entry: commands.append(entry) next.reset() return commands def sing(finch, sheet, speed=0.05): """Sing a melody. sheet - a string of notes. For the format see parse method in notes.py speed - speed of a single tick in seconds. Example: sing('C D E F G A B C5', speed=0.1) """ music = parse(sheet, speed=speed) for freq, duration in music: if duration: finch.buzzer_with_delay(duration, int(freq))
frequencies = {'C0': 16.35, 'C#0': 17.32, 'Db0': 17.32, 'D0': 18.35, 'D#0': 19.45, 'Eb0': 19.45, 'E0': 20.6, 'F0': 21.83, 'F#0': 23.12, 'Gb0': 23.12, 'G0': 24.5, 'G#0': 25.96, 'Ab0': 25.96, 'A0': 27.5, 'A#0': 29.14, 'Bb0': 29.14, 'B0': 30.87, 'C1': 32.7, 'C#1': 34.65, 'Db1': 34.65, 'D1': 36.71, 'D#1': 38.89, 'Eb1': 38.89, 'E1': 41.2, 'F1': 43.65, 'F#1': 46.25, 'Gb1': 46.25, 'G1': 49.0, 'G#1': 51.91, 'Ab1': 51.91, 'A1': 55.0, 'A#1': 58.27, 'Bb1': 58.27, 'B1': 61.74, 'C2': 65.41, 'C#2': 69.3, 'Db2': 69.3, 'D2': 73.42, 'D#2': 77.78, 'Eb2': 77.78, 'E2': 82.41, 'F2': 87.31, 'F#2': 92.5, 'Gb2': 92.5, 'G2': 98.0, 'G#2': 103.83, 'Ab2': 103.83, 'A2': 110.0, 'A#2': 116.54, 'Bb2': 116.54, 'B2': 123.47, 'C3': 130.81, 'C#3': 138.59, 'Db3': 138.59, 'D3': 146.83, 'D#3': 155.56, 'Eb3': 155.56, 'E3': 164.81, 'F3': 174.61, 'F#3': 185.0, 'Gb3': 185.0, 'G3': 196.0, 'G#3': 207.65, 'Ab3': 207.65, 'A3': 220.0, 'A#3': 233.08, 'Bb3': 233.08, 'B3': 246.94, 'C4': 261.63, 'C#4': 277.18, 'Db4': 277.18, 'D4': 293.66, 'D#4': 311.13, 'Eb4': 311.13, 'E4': 329.63, 'F4': 349.23, 'F#4': 369.99, 'Gb4': 369.99, 'G4': 392.0, 'G#4': 415.3, 'Ab4': 415.3, 'A4': 440.0, 'A#4': 466.16, 'Bb4': 466.16, 'B4': 493.88, 'C5': 523.25, 'C#5': 554.37, 'Db5': 554.37, 'D5': 587.33, 'D#5': 622.25, 'Eb5': 622.25, 'E5': 659.26, 'F5': 698.46, 'F#5': 739.99, 'Gb5': 739.99, 'G5': 783.99, 'G#5': 830.61, 'Ab5': 830.61, 'A5': 880.0, 'A#5': 932.33, 'Bb5': 932.33, 'B5': 987.77, 'C6': 1046.5, 'C#6': 1108.73, 'Db6': 1108.73, 'D6': 1174.66, 'D#6': 1244.51, 'Eb6': 1244.51, 'E6': 1318.51, 'F6': 1396.91, 'F#6': 1479.98, 'Gb6': 1479.98, 'G6': 1567.98, 'G#6': 1661.22, 'Ab6': 1661.22, 'A6': 1760.0, 'A#6': 1864.66, 'Bb6': 1864.66, 'B6': 1975.53, 'C7': 2093.0, 'C#7': 2217.46, 'Db7': 2217.46, 'D7': 2349.32, 'D#7': 2489.02, 'Eb7': 2489.02, 'E7': 2637.02, 'F7': 2793.83, 'F#7': 2959.96, 'Gb7': 2959.96, 'G7': 3135.96, 'G#7': 3322.44, 'Ab7': 3322.44, 'A7': 3520.0, 'A#7': 3729.31, 'Bb7': 3729.31, 'B7': 3951.07, 'C8': 4186.01, 'C#8': 4434.92, 'Db8': 4434.92, 'D8': 4698.64, 'D#8': 4978.03, 'Eb8': 4978.03} class Command(object): octave = 4 note = '' duration = 0 sym = '' def reset(self): self.note = '' self.duration = 0 self.sym = '' def emit(self): if not self.note or not self.duration: return None if self.note == '-': return (0, self.duration) ref = self.note.upper() + self.sym + str(self.octave) frequency = frequencies.get(ref) if not frequency: return None return (frequency, self.duration) def parse(sheet, speed=0.25): """Parse a sheet of notes to a sequence of (duration, frequency) commands. speed is a duration of a "tick" in seconds. Each *symbol* in the sheet takes up one tick. Valid notes are C, D, E, F, G, A, B and - (which means silence). Sheet can also contain semitones: C#, Eb, etc. You can change active octave with numbers 0-8. Here are some examples: To play Do for four ticks and then Re for eight ticks, pass: 'C D ' To play Do for two ticks, then silence for two ticks, then Do again: 'C - C ' To play Do Re Mi, but octave higher: 'C5D E ' parse('C3E G E ', speed=0.25) will play C major chord over 2 seconds parse('C3 Eb G Eb ', speed=0.125) will play C minor chord over 2 seconds also """ sheet = list(sheet) commands = [] next = command() while sheet: token = sheet.pop(0) if token in 'CDEFGAB-' and next.note: entry = next.emit() if entry: commands.append(entry) next.reset() next.note = token if token in 'CDEFGAB-' and (not next.note): next.note = token elif token.isdigit(): next.octave = int(token) next.duration -= speed elif (token == '#' or token == 'b') and next.note: next.sym = token next.duration -= speed next.duration += speed entry = next.emit() if entry: commands.append(entry) next.reset() return commands def sing(finch, sheet, speed=0.05): """Sing a melody. sheet - a string of notes. For the format see parse method in notes.py speed - speed of a single tick in seconds. Example: sing('C D E F G A B C5', speed=0.1) """ music = parse(sheet, speed=speed) for (freq, duration) in music: if duration: finch.buzzer_with_delay(duration, int(freq))
class Solution: def findMaximumXOR(self, nums: List[int]) -> int: L = len(bin(max(nums))) - 2 nums = [[(num >> i) & 1 for i in range(L)][::-1] for num in nums] maxXor, trie = 0, {} for num in nums: currentNode, xorNode, currentXor = trie, trie, 0 for bit in num: currentNode = currentNode.setdefault(bit, {}) toggledBit = 1 - bit if toggledBit in xorNode: currentXor = (currentXor << 1) | 1 xorNode = xorNode[toggledBit] else: currentXor = currentXor << 1 xorNode = xorNode[bit] maxXor = max(maxXor, currentXor) return maxXor
class Solution: def find_maximum_xor(self, nums: List[int]) -> int: l = len(bin(max(nums))) - 2 nums = [[num >> i & 1 for i in range(L)][::-1] for num in nums] (max_xor, trie) = (0, {}) for num in nums: (current_node, xor_node, current_xor) = (trie, trie, 0) for bit in num: current_node = currentNode.setdefault(bit, {}) toggled_bit = 1 - bit if toggledBit in xorNode: current_xor = currentXor << 1 | 1 xor_node = xorNode[toggledBit] else: current_xor = currentXor << 1 xor_node = xorNode[bit] max_xor = max(maxXor, currentXor) return maxXor
""" Implementing DefaultErrorHandler. Object default_error_handler is used as global object to register a callbacks for exceptions in asynchronous operators, """ def _default_error_callback(exc_type, exc_value, exc_traceback): """ Default error callback is printing traceback of the exception """ raise exc_value.with_traceback(exc_traceback) class DefaultErrorHandler: """ DefaultErrorHandler object is a callable which is calling a registered callback and is used for handling exceptions when asynchronous operators receiving an exception during .emit(). The callback can be registered via the .set(callback) method. The default callback is _default_error_callback which is dumping the traceback of the exception. """ def __init__(self): self._error_callback = _default_error_callback def __call__(self, exc_type, exc_value, exc_traceback): """ When calling the call will be forwarded to the registered callback """ self._error_callback(exc_type, exc_value, exc_traceback) def set(self, error_callback): """ Register a new callback :param error_callback: the callback to be registered """ self._error_callback = error_callback def reset(self): """ Reset to the default callback (dumping traceback) """ self._error_callback = _default_error_callback default_error_handler = DefaultErrorHandler() # pylint: disable=invalid-name
""" Implementing DefaultErrorHandler. Object default_error_handler is used as global object to register a callbacks for exceptions in asynchronous operators, """ def _default_error_callback(exc_type, exc_value, exc_traceback): """ Default error callback is printing traceback of the exception """ raise exc_value.with_traceback(exc_traceback) class Defaulterrorhandler: """ DefaultErrorHandler object is a callable which is calling a registered callback and is used for handling exceptions when asynchronous operators receiving an exception during .emit(). The callback can be registered via the .set(callback) method. The default callback is _default_error_callback which is dumping the traceback of the exception. """ def __init__(self): self._error_callback = _default_error_callback def __call__(self, exc_type, exc_value, exc_traceback): """ When calling the call will be forwarded to the registered callback """ self._error_callback(exc_type, exc_value, exc_traceback) def set(self, error_callback): """ Register a new callback :param error_callback: the callback to be registered """ self._error_callback = error_callback def reset(self): """ Reset to the default callback (dumping traceback) """ self._error_callback = _default_error_callback default_error_handler = default_error_handler()
''' 2969 6299 9629 ''' def prime(n): if n <= 2: return n == 2 elif n % 2 == 0: return False else: #vsa liha ostanejo d = 3 while d ** 2 <= n: if n % d == 0: return False d += 2 return True for x in range(1000, 10000-2*3330): if sorted(list(str(x))) == sorted(list(str(x + 3330))) == sorted(list(str(x + 2*3330))): if prime(x): if prime(x + 3330): if prime(x + 2*3330): print(f'{x}{x+3330}{x+2*3330}') ''' 148748178147 296962999629 '''
""" 2969 6299 9629 """ def prime(n): if n <= 2: return n == 2 elif n % 2 == 0: return False else: d = 3 while d ** 2 <= n: if n % d == 0: return False d += 2 return True for x in range(1000, 10000 - 2 * 3330): if sorted(list(str(x))) == sorted(list(str(x + 3330))) == sorted(list(str(x + 2 * 3330))): if prime(x): if prime(x + 3330): if prime(x + 2 * 3330): print(f'{x}{x + 3330}{x + 2 * 3330}') '\n148748178147\n296962999629\n'
class Rectangle: pass rect1 = Rectangle() rect2 = Rectangle() rect1.height = 30 rect1.width = 10 rect2.height = 5 rect2.width = 10 rect1.area = rect1.height * rect1.width rect2.area = rect2.height * rect2.width print(rect2.area)
class Rectangle: pass rect1 = rectangle() rect2 = rectangle() rect1.height = 30 rect1.width = 10 rect2.height = 5 rect2.width = 10 rect1.area = rect1.height * rect1.width rect2.area = rect2.height * rect2.width print(rect2.area)
"""Configuration information for an AgPipeline Transformer """ class Configuration: """Contains configuration information on Transformers """ # Silence this error until we have public methods # pylint: disable=too-few-public-methods # The version number of the transformer transformer_version = None # The transformer description transformer_description = None # Short name of the transformer transformer_name = None # The sensor associated with the transformer transformer_sensor = None # The transformer type (eg: 'rgbmask', 'plotclipper') transformer_type = None # The name of the author of the extractor author_name = None # The email of the author of the extractor author_email = None # Contributors to this transformer contributors = [] # Repository URI of where the source code lives repository = None # Override flag for disabling the metadata file requirement. # Uncomment and set to False to override default behavior # metadata_needed = True
"""Configuration information for an AgPipeline Transformer """ class Configuration: """Contains configuration information on Transformers """ transformer_version = None transformer_description = None transformer_name = None transformer_sensor = None transformer_type = None author_name = None author_email = None contributors = [] repository = None
# Copyright (c) 2017, Matt Layman class AbortError(Exception): """Any fatal errors that would prevent handroll from proceeding should signal with the ``AbortError`` exception."""
class Aborterror(Exception): """Any fatal errors that would prevent handroll from proceeding should signal with the ``AbortError`` exception."""
"""Strip .HTML extension from URIs.""" def process(app, stream): for item in stream: # Most modern HTTP servers implicitly serve one of these files when # requested URL is pointing to a directory on filesystem. Hence in # order to provide "pretty" URLs we need to transform destination # address accordingly. if item["destination"].name not in ("index.html", "index.htm"): item["destination"] = item["destination"].parent.joinpath( item["destination"].stem, "index.html" ) yield item
"""Strip .HTML extension from URIs.""" def process(app, stream): for item in stream: if item['destination'].name not in ('index.html', 'index.htm'): item['destination'] = item['destination'].parent.joinpath(item['destination'].stem, 'index.html') yield item
# # Font compiler # fonts = [ None ] * 64 current = -1 for l in open("font.txt").readlines(): print(l) if l.strip() != "": if l[0] == ':': current = ord(l[1]) & 0x3F fonts[current] = [] else: l = l.strip().replace(".","0").replace("X","1") assert len(l) == 3 fonts[current].append(int(l,2)) for i in range(0,64): print(i,fonts[i]) assert(len(fonts[i]) == 5) n = 0 for g in fonts[i]: n = n * 8 + g n = n * 2 + 1 fonts[i] = n open("fonttable.asm","w").write("\n".join([" dw "+str(x) for x in fonts]))
fonts = [None] * 64 current = -1 for l in open('font.txt').readlines(): print(l) if l.strip() != '': if l[0] == ':': current = ord(l[1]) & 63 fonts[current] = [] else: l = l.strip().replace('.', '0').replace('X', '1') assert len(l) == 3 fonts[current].append(int(l, 2)) for i in range(0, 64): print(i, fonts[i]) assert len(fonts[i]) == 5 n = 0 for g in fonts[i]: n = n * 8 + g n = n * 2 + 1 fonts[i] = n open('fonttable.asm', 'w').write('\n'.join([' dw ' + str(x) for x in fonts]))
"""Classes used in warehouse""" class ItemSet: """A set of identical items. The dimensions is a tuple (x, y, z) of the dimensions of a single item. The weight is a weight of a single member""" def __init__(self, dimensions, weight, ref_id, quantity, colour): self.dimensions = dimensions self.weight = weight self.ref_id = ref_id self.quantity = quantity self.colour = colour def __str__(self): return f"An ItemSet of {self.quantity} individual items of size {self.dimensions}, individual weight {self.weight}, id {self.ref_id}, colour {self.colour}" class Box: """A Box dimensions is a tuple of (x, y, z)""" def __init__(self, name, dimensions, max_weight): self.name = name self.dimensions = dimensions self.max_weight = max_weight def __str__(self): return f'A {self.name} Box of size {self.dimensions} and maximum weight {self.max_weight}' class Package: """A Package corresponds to one Box that contains items of class ItemSet of quantity 1. itemsets_and_locations is a list of tuples ordered by the order of packages being put in the box each tuple contains a ItemSet class and a """ def __init__(self, itemsets_and_locations, box, image): self.itemsets_and_locations = itemsets_and_locations self.box = box self.image = image def __str__(self): return f'Package of Box {self.box} containing ItemSets at locations {self.itemsets_and_locations}'
"""Classes used in warehouse""" class Itemset: """A set of identical items. The dimensions is a tuple (x, y, z) of the dimensions of a single item. The weight is a weight of a single member""" def __init__(self, dimensions, weight, ref_id, quantity, colour): self.dimensions = dimensions self.weight = weight self.ref_id = ref_id self.quantity = quantity self.colour = colour def __str__(self): return f'An ItemSet of {self.quantity} individual items of size {self.dimensions}, individual weight {self.weight}, id {self.ref_id}, colour {self.colour}' class Box: """A Box dimensions is a tuple of (x, y, z)""" def __init__(self, name, dimensions, max_weight): self.name = name self.dimensions = dimensions self.max_weight = max_weight def __str__(self): return f'A {self.name} Box of size {self.dimensions} and maximum weight {self.max_weight}' class Package: """A Package corresponds to one Box that contains items of class ItemSet of quantity 1. itemsets_and_locations is a list of tuples ordered by the order of packages being put in the box each tuple contains a ItemSet class and a """ def __init__(self, itemsets_and_locations, box, image): self.itemsets_and_locations = itemsets_and_locations self.box = box self.image = image def __str__(self): return f'Package of Box {self.box} containing ItemSets at locations {self.itemsets_and_locations}'
# Read a DNA Sequence def readSequence(): sequence = open(raw_input('Enter sequence filename: '),'r') sequence.readline() sequence = sequence.read().replace('\n', '') return sequence def match(a, b): if a == b: return 1 else: return -1 # Align two sequences using Smith-Waterman algorithm def alignSequences(s1, s2): gap = -2 s1 = '-'+s1 s2 = '-'+s2 mWidth = len(s1) mHeight = len(s2) similarity_matrix = [[i for i in xrange(mHeight)] for i in xrange(mWidth)] for i in range (mWidth): similarity_matrix[i][0] = 0 for j in range (mHeight): similarity_matrix[0][j] = 0 for i in range (1,mWidth): for j in range (1, mHeight): p0 = 0 p1 = similarity_matrix[i-1][j-1] + match(s1[i], s2[j]) p2 = similarity_matrix[i][j-1] + gap p3 = similarity_matrix[i-1][j] + gap similarity_matrix[i][j] = max(p0, p1, p2, p3) #Find biggest number in the similarity matrix maxNumber = 0 maxNumberI = 0 maxNumberJ = 0 for i in range(mWidth): for j in range(mHeight): if similarity_matrix[i][j] >= maxNumber: maxNumber = similarity_matrix[i][j] maxNumberI = i maxNumberJ = j i = maxNumberI j = maxNumberJ alignmentS1 = '' alignmentS2 = '' while similarity_matrix[i][j] > 0: if similarity_matrix[i][j] == similarity_matrix[i-1][j-1] + match(s1[i], s2[j]): alignmentS1 = s1[i] + alignmentS1 alignmentS2 = s2[j] + alignmentS2 j-=1 i-=1 elif similarity_matrix[i][j] == similarity_matrix[i-1][j] + gap: alignmentS1 = s1[i] + alignmentS1 alignmentS2 = '-' + alignmentS2 i-=1 else: alignmentS1 = '-' + alignmentS1 alignmentS2 = s2[j] + alignmentS2 j-=1 qtdeAlinhamento = 0 for i in range(max(len(alignmentS1), len(alignmentS2))): if alignmentS1[i] == alignmentS2[i]: qtdeAlinhamento+=1 print('Tabela final:',similarity_matrix) print('Melhor alinhamento local para a sequencia 1: ', alignmentS1) print('Melhor alinhamento local para a sequencia 2: ', alignmentS2) print('Identidade do alinhamento: ', qtdeAlinhamento) s1 = readSequence() s2 = readSequence() alignSequences(s1, s2)
def read_sequence(): sequence = open(raw_input('Enter sequence filename: '), 'r') sequence.readline() sequence = sequence.read().replace('\n', '') return sequence def match(a, b): if a == b: return 1 else: return -1 def align_sequences(s1, s2): gap = -2 s1 = '-' + s1 s2 = '-' + s2 m_width = len(s1) m_height = len(s2) similarity_matrix = [[i for i in xrange(mHeight)] for i in xrange(mWidth)] for i in range(mWidth): similarity_matrix[i][0] = 0 for j in range(mHeight): similarity_matrix[0][j] = 0 for i in range(1, mWidth): for j in range(1, mHeight): p0 = 0 p1 = similarity_matrix[i - 1][j - 1] + match(s1[i], s2[j]) p2 = similarity_matrix[i][j - 1] + gap p3 = similarity_matrix[i - 1][j] + gap similarity_matrix[i][j] = max(p0, p1, p2, p3) max_number = 0 max_number_i = 0 max_number_j = 0 for i in range(mWidth): for j in range(mHeight): if similarity_matrix[i][j] >= maxNumber: max_number = similarity_matrix[i][j] max_number_i = i max_number_j = j i = maxNumberI j = maxNumberJ alignment_s1 = '' alignment_s2 = '' while similarity_matrix[i][j] > 0: if similarity_matrix[i][j] == similarity_matrix[i - 1][j - 1] + match(s1[i], s2[j]): alignment_s1 = s1[i] + alignmentS1 alignment_s2 = s2[j] + alignmentS2 j -= 1 i -= 1 elif similarity_matrix[i][j] == similarity_matrix[i - 1][j] + gap: alignment_s1 = s1[i] + alignmentS1 alignment_s2 = '-' + alignmentS2 i -= 1 else: alignment_s1 = '-' + alignmentS1 alignment_s2 = s2[j] + alignmentS2 j -= 1 qtde_alinhamento = 0 for i in range(max(len(alignmentS1), len(alignmentS2))): if alignmentS1[i] == alignmentS2[i]: qtde_alinhamento += 1 print('Tabela final:', similarity_matrix) print('Melhor alinhamento local para a sequencia 1: ', alignmentS1) print('Melhor alinhamento local para a sequencia 2: ', alignmentS2) print('Identidade do alinhamento: ', qtdeAlinhamento) s1 = read_sequence() s2 = read_sequence() align_sequences(s1, s2)
def flip(arr, i): start = 0 while start < i: temp = arr[start] arr[start] = arr[i] arr[i] = temp start += 1 i -= 1 def findMax(arr, n): mi = 0 for i in range(0,n): if arr[i] > arr[mi]: mi = i return mi def pancakeSort(arr, n): curr_size = n while curr_size > 1: mi = findMax(arr, curr_size) if mi != curr_size-1: flip(arr, mi) flip(arr, curr_size-1) curr_size -= 1 n = int(input("Enter the size of array : ")) arr = list(map(int, input("Enter the array elements :\n").strip().split()))[:n] print("Before") print(arr) pancakeSort(arr, n); print ("Sorted Array ") print(arr)
def flip(arr, i): start = 0 while start < i: temp = arr[start] arr[start] = arr[i] arr[i] = temp start += 1 i -= 1 def find_max(arr, n): mi = 0 for i in range(0, n): if arr[i] > arr[mi]: mi = i return mi def pancake_sort(arr, n): curr_size = n while curr_size > 1: mi = find_max(arr, curr_size) if mi != curr_size - 1: flip(arr, mi) flip(arr, curr_size - 1) curr_size -= 1 n = int(input('Enter the size of array : ')) arr = list(map(int, input('Enter the array elements :\n').strip().split()))[:n] print('Before') print(arr) pancake_sort(arr, n) print('Sorted Array ') print(arr)
n = int(input()) s = [] while n != 0: n -= 1 name = input() s.append(name) r = input() for i in range(len(s)): if r in s[i]: while r in s[i]: s[i] = s[i].replace(r, "") max_seq = "" for i in range(len(s[0])): ans = "" for j in range(i, len(s[0])): ans += s[0][j] for k in range(1, len(s)): if ans in s[k]: if len(ans) > len(max_seq): max_seq = ans print(max_seq)
n = int(input()) s = [] while n != 0: n -= 1 name = input() s.append(name) r = input() for i in range(len(s)): if r in s[i]: while r in s[i]: s[i] = s[i].replace(r, '') max_seq = '' for i in range(len(s[0])): ans = '' for j in range(i, len(s[0])): ans += s[0][j] for k in range(1, len(s)): if ans in s[k]: if len(ans) > len(max_seq): max_seq = ans print(max_seq)
class EnvMap(object): """EnvMap object used to load and render map from file""" def __init__(self, map_path): super(EnvMap, self).__init__() self.map_path = map_path self.load_map() def get_all_treasure_locations(self): treasure_locations = [] for row in range(len(self.grid)): for col in range(len(self.grid[row])): if self.has_treasure(row, col): treasure_locations.append((row, col)) return treasure_locations def get_all_wall_locations(self): wall_locations = [] for row in range(len(self.grid)): for col in range(len(self.grid[row])): if self.has_wall(row, col): wall_locations.append((row, col)) return wall_locations def get_all_lightning_probability(self): lightning_probability = [] for row in range(len(self.grid)): r = [] for col in range(len(self.grid[row])): r.append(self.get_lightning_probability(row, col)) lightning_probability.append(r) return lightning_probability def load_map(self): self.grid = [] with open(self.map_path) as fp: line = fp.readline() while line: row = list(map(float, line.strip().split())) self.grid.append(row) line = fp.readline() def render(self): for row in self.grid: print(row) def agent_location(self): for row in range(len(self.grid)): for col in range(len(self.grid[row])): if self.is_agent_position(row, col): return (row, col) return None def has_wall(self, row, col): return self.grid[row][col] == 2 def has_treasure(self, row, col): return self.grid[row][col] == 3 def is_agent_position(self, row, col): return self.grid[row][col] == 4 def get_lightning_probability(self, row, col): if (self.has_wall(row, col) or self.is_agent_position(row, col) or self.has_treasure(row, col)): return 0 return self.grid[row][col] def shape(self): return (len(self.grid), len(self.grid[0]))
class Envmap(object): """EnvMap object used to load and render map from file""" def __init__(self, map_path): super(EnvMap, self).__init__() self.map_path = map_path self.load_map() def get_all_treasure_locations(self): treasure_locations = [] for row in range(len(self.grid)): for col in range(len(self.grid[row])): if self.has_treasure(row, col): treasure_locations.append((row, col)) return treasure_locations def get_all_wall_locations(self): wall_locations = [] for row in range(len(self.grid)): for col in range(len(self.grid[row])): if self.has_wall(row, col): wall_locations.append((row, col)) return wall_locations def get_all_lightning_probability(self): lightning_probability = [] for row in range(len(self.grid)): r = [] for col in range(len(self.grid[row])): r.append(self.get_lightning_probability(row, col)) lightning_probability.append(r) return lightning_probability def load_map(self): self.grid = [] with open(self.map_path) as fp: line = fp.readline() while line: row = list(map(float, line.strip().split())) self.grid.append(row) line = fp.readline() def render(self): for row in self.grid: print(row) def agent_location(self): for row in range(len(self.grid)): for col in range(len(self.grid[row])): if self.is_agent_position(row, col): return (row, col) return None def has_wall(self, row, col): return self.grid[row][col] == 2 def has_treasure(self, row, col): return self.grid[row][col] == 3 def is_agent_position(self, row, col): return self.grid[row][col] == 4 def get_lightning_probability(self, row, col): if self.has_wall(row, col) or self.is_agent_position(row, col) or self.has_treasure(row, col): return 0 return self.grid[row][col] def shape(self): return (len(self.grid), len(self.grid[0]))
testArray = [1, 2, 3, 4, 5] testString = 'this is the test string' newString = testString + str(testArray) print(newString)
test_array = [1, 2, 3, 4, 5] test_string = 'this is the test string' new_string = testString + str(testArray) print(newString)
class Solution: def alienOrder(self, words: List[str]) -> str: """ Approach: 1. Make a graph according to the letters order, comparing to adjacent words 2. Find Topological order based on the graph Examples: ["ba", "bc", "ac", "cab"] b: a a: c res = bac ["ywx", "wz", "xww", "xz", "zyy", "zwz"] y: 0 w: 2 z: 2 x: 1 y: w, w w: x, z x: z res = ywxz """ n = len(words) graph = defaultdict(list) indegree = defaultdict(int) for word in words: for character in word: indegree[character] = 0 for i in range(n-1): word1, word2 = words[i], words[i+1] idx1, idx2 = 0, 0 while idx1 < len(word1) and idx2 < len(word2): char1 = word1[idx1] char2 = word2[idx2] if char1 != char2: graph[char1].append(char2) indegree[char2] += 1 break idx1 += 1 idx2 += 1 else: if len(word2) < len(word1): return "" order = [] q = deque([node for node, count in indegree.items() if count == 0]) while q: source = q.popleft() order.append(source) for dest in graph[source]: indegree[dest] -= 1 if indegree[dest] <= 0: q.append(dest) if len(order) != len(indegree): return "" return "".join(order)
class Solution: def alien_order(self, words: List[str]) -> str: """ Approach: 1. Make a graph according to the letters order, comparing to adjacent words 2. Find Topological order based on the graph Examples: ["ba", "bc", "ac", "cab"] b: a a: c res = bac ["ywx", "wz", "xww", "xz", "zyy", "zwz"] y: 0 w: 2 z: 2 x: 1 y: w, w w: x, z x: z res = ywxz """ n = len(words) graph = defaultdict(list) indegree = defaultdict(int) for word in words: for character in word: indegree[character] = 0 for i in range(n - 1): (word1, word2) = (words[i], words[i + 1]) (idx1, idx2) = (0, 0) while idx1 < len(word1) and idx2 < len(word2): char1 = word1[idx1] char2 = word2[idx2] if char1 != char2: graph[char1].append(char2) indegree[char2] += 1 break idx1 += 1 idx2 += 1 else: if len(word2) < len(word1): return '' order = [] q = deque([node for (node, count) in indegree.items() if count == 0]) while q: source = q.popleft() order.append(source) for dest in graph[source]: indegree[dest] -= 1 if indegree[dest] <= 0: q.append(dest) if len(order) != len(indegree): return '' return ''.join(order)
""" https://leetcode.com/problems/find-lucky-integer-in-an-array/ Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value. Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1. Example 1: Input: arr = [2,2,3,4] Output: 2 Explanation: The only lucky number in the array is 2 because frequency[2] == 2. Example 2: Input: arr = [1,2,2,3,3,3] Output: 3 Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them. Example 3: Input: arr = [2,2,2,3,3] Output: -1 Explanation: There are no lucky numbers in the array. Example 4: Input: arr = [5] Output: -1 Example 5: Input: arr = [7,7,7,7,7,7,7] Output: 7 Constraints: 1 <= arr.length <= 500 1 <= arr[i] <= 500 """ # time complexity: O(n), space complexity: O(n) class Solution: def findLucky(self, arr: List[int]) -> int: dic = dict() for num in arr: dic[num] = dic.get(num, 0) + 1 result = -1 for key, item in dic.items(): if key == item and key > result: result = key return result
""" https://leetcode.com/problems/find-lucky-integer-in-an-array/ Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value. Return a lucky integer in the array. If there are multiple lucky integers return the largest of them. If there is no lucky integer return -1. Example 1: Input: arr = [2,2,3,4] Output: 2 Explanation: The only lucky number in the array is 2 because frequency[2] == 2. Example 2: Input: arr = [1,2,2,3,3,3] Output: 3 Explanation: 1, 2 and 3 are all lucky numbers, return the largest of them. Example 3: Input: arr = [2,2,2,3,3] Output: -1 Explanation: There are no lucky numbers in the array. Example 4: Input: arr = [5] Output: -1 Example 5: Input: arr = [7,7,7,7,7,7,7] Output: 7 Constraints: 1 <= arr.length <= 500 1 <= arr[i] <= 500 """ class Solution: def find_lucky(self, arr: List[int]) -> int: dic = dict() for num in arr: dic[num] = dic.get(num, 0) + 1 result = -1 for (key, item) in dic.items(): if key == item and key > result: result = key return result
def load_sensitivity_study_file_names(design): """ Parameters ---------- design: Name of design Returns experiment files names of a design ------- """ file_names = {} if design == 'NAE-IAW': path = '../Files_Results/Sensitivity_Study/NAE-IAW/' file_names['FILE_MeanDrift_var0.01'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.01_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-10_10.32.pickle_2021-08-24_12.30_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_MeanDrift_var0.05'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.05_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.42.pickle_2021-08-24_14.36_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_MeanDrift_var0.25'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.25_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.45.pickle_2021-08-24_17.24_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_VarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyVarianceDrift_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_11.15.pickle_2021-08-24_20.58_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_MeanVarianceDrift_all_broken'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_100MinDimBroken_300MinL_2000MaxL_2021-08-06_10.54.pickle_2021-08-24_13.34_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_MeanVarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.53.pickle_2021-08-24_16.22_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_RandomRBF_Generator'] = 'Sensitivity_Study_RandomRandomRBF_50DR_100Dims_50Centroids_1MinDriftCentroids_300MinL_2000MaxL_2021-08-06_10.57.pickle_2021-08-24_13.20_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_MergedStream'] = 'Sensitivity_Study_Mixed_300MinDistance_DATASET_A_RandomNumpyRandomNormalUniform_DATASET_B_RandomRandomRBF.pickle_2021-08-24_13.08_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_FashionMNIST'] = 'Sensitivity_Study_RandomMNIST_and_FashionMNIST_SortAllNumbers19DR_2021-08-06_11.07.pickle_2021-08-25_12.07_10ITERATIONS_fitNewAETrue_fitFalse' if design == 'RAE-IAW': path = '../Files_Results/Sensitivity_Study/RAE-IAW/' file_names['FILE_MeanDrift_var0.01'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.01_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-10_10.32.pickle_2021-08-11_19.36_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_MeanDrift_var0.05'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.05_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.42.pickle_2021-08-12_00.04_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_MeanDrift_var0.25'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.25_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.45.pickle_2021-08-12_14.18_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_VarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyVarianceDrift_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_11.15.pickle_2021-08-12_18.04_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_MeanVarianceDrift_all_broken'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_100MinDimBroken_300MinL_2000MaxL_2021-08-06_10.54.pickle_2021-08-12_20.47_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_MeanVarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.53.pickle_2021-08-13_00.30_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_RandomRBF_Generator'] = 'Sensitivity_Study_RandomRandomRBF_50DR_100Dims_50Centroids_1MinDriftCentroids_300MinL_2000MaxL_2021-08-06_10.57.pickle_2021-08-12_19.37_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_MergedStream'] = 'Sensitivity_Study_Mixed_300MinDistance_DATASET_A_RandomNumpyRandomNormalUniform_DATASET_B_RandomRandomRBF.pickle_2021-08-13_03.54_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_FashionMNIST'] = 'Sensitivity_Study_RandomMNIST_and_FashionMNIST_SortAllNumbers19DR_2021-08-06_11.07.pickle_2021-08-12_22.40_10ITERATIONS_fitNewAEFalse_fitTrue' return path, file_names
def load_sensitivity_study_file_names(design): """ Parameters ---------- design: Name of design Returns experiment files names of a design ------- """ file_names = {} if design == 'NAE-IAW': path = '../Files_Results/Sensitivity_Study/NAE-IAW/' file_names['FILE_MeanDrift_var0.01'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.01_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-10_10.32.pickle_2021-08-24_12.30_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_MeanDrift_var0.05'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.05_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.42.pickle_2021-08-24_14.36_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_MeanDrift_var0.25'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.25_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.45.pickle_2021-08-24_17.24_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_VarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyVarianceDrift_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_11.15.pickle_2021-08-24_20.58_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_MeanVarianceDrift_all_broken'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_100MinDimBroken_300MinL_2000MaxL_2021-08-06_10.54.pickle_2021-08-24_13.34_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_MeanVarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.53.pickle_2021-08-24_16.22_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_RandomRBF_Generator'] = 'Sensitivity_Study_RandomRandomRBF_50DR_100Dims_50Centroids_1MinDriftCentroids_300MinL_2000MaxL_2021-08-06_10.57.pickle_2021-08-24_13.20_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_MergedStream'] = 'Sensitivity_Study_Mixed_300MinDistance_DATASET_A_RandomNumpyRandomNormalUniform_DATASET_B_RandomRandomRBF.pickle_2021-08-24_13.08_10ITERATIONS_fitNewAETrue_fitFalse' file_names['FILE_FashionMNIST'] = 'Sensitivity_Study_RandomMNIST_and_FashionMNIST_SortAllNumbers19DR_2021-08-06_11.07.pickle_2021-08-25_12.07_10ITERATIONS_fitNewAETrue_fitFalse' if design == 'RAE-IAW': path = '../Files_Results/Sensitivity_Study/RAE-IAW/' file_names['FILE_MeanDrift_var0.01'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.01_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-10_10.32.pickle_2021-08-11_19.36_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_MeanDrift_var0.05'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.05_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.42.pickle_2021-08-12_00.04_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_MeanDrift_var0.25'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyMeanDrift_var0.25_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.45.pickle_2021-08-12_14.18_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_VarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_onlyVarianceDrift_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_11.15.pickle_2021-08-12_18.04_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_MeanVarianceDrift_all_broken'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_100MinDimBroken_300MinL_2000MaxL_2021-08-06_10.54.pickle_2021-08-12_20.47_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_MeanVarianceDrift'] = 'Sensitivity_Study_RandomNumpyRandomNormalUniform_50DR_100Dims_1MinDimBroken_300MinL_2000MaxL_2021-08-06_10.53.pickle_2021-08-13_00.30_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_RandomRBF_Generator'] = 'Sensitivity_Study_RandomRandomRBF_50DR_100Dims_50Centroids_1MinDriftCentroids_300MinL_2000MaxL_2021-08-06_10.57.pickle_2021-08-12_19.37_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_MergedStream'] = 'Sensitivity_Study_Mixed_300MinDistance_DATASET_A_RandomNumpyRandomNormalUniform_DATASET_B_RandomRandomRBF.pickle_2021-08-13_03.54_10ITERATIONS_fitNewAEFalse_fitTrue' file_names['FILE_FashionMNIST'] = 'Sensitivity_Study_RandomMNIST_and_FashionMNIST_SortAllNumbers19DR_2021-08-06_11.07.pickle_2021-08-12_22.40_10ITERATIONS_fitNewAEFalse_fitTrue' return (path, file_names)
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. class DepthInfo: # The default depth that we travel before forcing a foreign key attribute DEFAULT_MAX_DEPTH = 2 # The max depth set if the user specified to not use max depth MAX_DEPTH_LIMIT = 32 def __init__(self, current_depth, max_depth, max_depth_exceeded): # The maximum depth that we can resolve entity attributes. # This value is set in resolution guidance. self.current_depth = current_depth # type: int # The current depth that we are resolving at. Each entity attribute that we resolve # into adds 1 to depth. self.max_depth = max_depth # type: int # Indicates if the maxDepth value has been hit when resolving self.max_depth_exceeded = max_depth_exceeded # type: int
class Depthinfo: default_max_depth = 2 max_depth_limit = 32 def __init__(self, current_depth, max_depth, max_depth_exceeded): self.current_depth = current_depth self.max_depth = max_depth self.max_depth_exceeded = max_depth_exceeded
class Solution: def isMatch(self, text, pattern): if not pattern: return not text first_match = bool(text) and pattern[0] in {text[0], '.'} if len(pattern) >= 2 and pattern[1] == '*': return (self.isMatch(text, pattern[2:]) or first_match and self.isMatch(text[1:], pattern)) else: return first_match and self.isMatch(text[1:], pattern[1:]) class Solution: def isMatch(self, text, pattern): memo = {} def dp(i, j): if (i, j) not in memo: if j == len(pattern): ans = i == len(text) else: first_match = i < len(text) and pattern[j] in {text[i], '.'} if j+1 < len(pattern) and pattern[j+1] == '*': ans = dp(i, j+2) or first_match and dp(i+1, j) else: ans = first_match and dp(i+1, j+1) memo[i, j] = ans return memo[i, j] return dp(0, 0) class Solution: def isMatch(self, text, pattern): dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)] dp[-1][-1] = True for i in range(len(text), -1, -1): for j in range(len(pattern) - 1, -1, -1): first_match = i < len(text) and pattern[j] in {text[i], '.'} if j+1 < len(pattern) and pattern[j+1] == '*': dp[i][j] = dp[i][j+2] or first_match and dp[i+1][j] else: dp[i][j] = first_match and dp[i+1][j+1] return dp[0][0]
class Solution: def is_match(self, text, pattern): if not pattern: return not text first_match = bool(text) and pattern[0] in {text[0], '.'} if len(pattern) >= 2 and pattern[1] == '*': return self.isMatch(text, pattern[2:]) or (first_match and self.isMatch(text[1:], pattern)) else: return first_match and self.isMatch(text[1:], pattern[1:]) class Solution: def is_match(self, text, pattern): memo = {} def dp(i, j): if (i, j) not in memo: if j == len(pattern): ans = i == len(text) else: first_match = i < len(text) and pattern[j] in {text[i], '.'} if j + 1 < len(pattern) and pattern[j + 1] == '*': ans = dp(i, j + 2) or (first_match and dp(i + 1, j)) else: ans = first_match and dp(i + 1, j + 1) memo[i, j] = ans return memo[i, j] return dp(0, 0) class Solution: def is_match(self, text, pattern): dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)] dp[-1][-1] = True for i in range(len(text), -1, -1): for j in range(len(pattern) - 1, -1, -1): first_match = i < len(text) and pattern[j] in {text[i], '.'} if j + 1 < len(pattern) and pattern[j + 1] == '*': dp[i][j] = dp[i][j + 2] or (first_match and dp[i + 1][j]) else: dp[i][j] = first_match and dp[i + 1][j + 1] return dp[0][0]
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Associations Management', 'version': '0.1', 'category': 'Marketing', 'description': """ This module is to configure modules related to an association. ============================================================== It installs the profile for associations to manage events, registrations, memberships, membership products (schemes). """, 'depends': ['base_setup', 'membership', 'event'], 'data': ['views/association_views.xml'], 'demo': [], 'installable': True, 'auto_install': False, }
{'name': 'Associations Management', 'version': '0.1', 'category': 'Marketing', 'description': '\nThis module is to configure modules related to an association.\n==============================================================\n\nIt installs the profile for associations to manage events, registrations, memberships, \nmembership products (schemes).\n ', 'depends': ['base_setup', 'membership', 'event'], 'data': ['views/association_views.xml'], 'demo': [], 'installable': True, 'auto_install': False}
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class SnapKorf(MakefilePackage): """SNAP is a general purpose gene finding program suitable for both eukaryotic and prokaryotic genomes.""" homepage = "http://korflab.ucdavis.edu/software.html" url = "http://korflab.ucdavis.edu/Software/snap-2013-11-29.tar.gz" git = "https://github.com/KorfLab/SNAP.git" version('2021-11-04', commit='62ff3120fceccb03b5eea9d21afec3167dedfa94') version('2013-11-29', sha256='e2a236392d718376356fa743aa49a987aeacd660c6979cee67121e23aeffc66a') depends_on('perl', type=('build', 'run')) def edit(self, spec, prefix): if spec.satisfies('@2013-11-29%gcc@6:'): rstr = '\\1 -Wno-tautological-compare -Wno-misleading-indentation' filter_file('(-Werror)', rstr, 'Zoe/Makefile') rstr = '\\1 -Wno-error=format-overflow -Wno-misleading-indentation' filter_file('(-Werror)', rstr, 'Makefile') filter_file(r'(^const char \* zoeFunction;)', 'extern \\1', 'Zoe/zoeTools.h') filter_file(r'(^const char \* zoeConstructor;)', 'extern \\1', 'Zoe/zoeTools.h') filter_file(r'(^const char \* zoeMethod;)', 'extern \\1', 'Zoe/zoeTools.h') def install(self, spec, prefix): mkdirp(prefix.bin) progs = ['snap', 'fathom', 'forge'] if spec.satisfies('@2013-11-29'): progs = progs + ['depend', 'exonpairs', 'hmm-info'] for p in progs: install(p, prefix.bin) install('*.pl', prefix.bin) install_tree('Zoe', prefix.Zoe) install_tree('HMM', prefix.HMM) install_tree('DNA', prefix.DNA) def setup_run_environment(self, env): env.set('ZOE', self.prefix) env.prepend_path('PATH', self.prefix)
class Snapkorf(MakefilePackage): """SNAP is a general purpose gene finding program suitable for both eukaryotic and prokaryotic genomes.""" homepage = 'http://korflab.ucdavis.edu/software.html' url = 'http://korflab.ucdavis.edu/Software/snap-2013-11-29.tar.gz' git = 'https://github.com/KorfLab/SNAP.git' version('2021-11-04', commit='62ff3120fceccb03b5eea9d21afec3167dedfa94') version('2013-11-29', sha256='e2a236392d718376356fa743aa49a987aeacd660c6979cee67121e23aeffc66a') depends_on('perl', type=('build', 'run')) def edit(self, spec, prefix): if spec.satisfies('@2013-11-29%gcc@6:'): rstr = '\\1 -Wno-tautological-compare -Wno-misleading-indentation' filter_file('(-Werror)', rstr, 'Zoe/Makefile') rstr = '\\1 -Wno-error=format-overflow -Wno-misleading-indentation' filter_file('(-Werror)', rstr, 'Makefile') filter_file('(^const char \\* zoeFunction;)', 'extern \\1', 'Zoe/zoeTools.h') filter_file('(^const char \\* zoeConstructor;)', 'extern \\1', 'Zoe/zoeTools.h') filter_file('(^const char \\* zoeMethod;)', 'extern \\1', 'Zoe/zoeTools.h') def install(self, spec, prefix): mkdirp(prefix.bin) progs = ['snap', 'fathom', 'forge'] if spec.satisfies('@2013-11-29'): progs = progs + ['depend', 'exonpairs', 'hmm-info'] for p in progs: install(p, prefix.bin) install('*.pl', prefix.bin) install_tree('Zoe', prefix.Zoe) install_tree('HMM', prefix.HMM) install_tree('DNA', prefix.DNA) def setup_run_environment(self, env): env.set('ZOE', self.prefix) env.prepend_path('PATH', self.prefix)
def format_sql(table, obj: dict) -> str: cols = ','.join(obj.keys()) values = ','.join(obj.values()) sql = "insert into {table} ({cols}) values ({values})".format(table=table, cols=cols, values=values) return def format_sqls(table, objs: list) -> str: obj = objs.__getitem__(0) cols = ','.join(obj.keys()) values = get_values_str(objs) sql = "insert into {table} ({cols}) values {values}".format(table=table, cols=cols, values=values) return sql def get_values_str(objs: list): values = [] for obj in objs: values.append("({sqlValue})".format(sqlValue=','.join("'%s'" % o for o in obj.values()))) return ",".join(values) # format_sqls("coin", [{"a": "1", "b": "2"}, {"a": "3", "b": "4"}])
def format_sql(table, obj: dict) -> str: cols = ','.join(obj.keys()) values = ','.join(obj.values()) sql = 'insert into {table} ({cols}) values ({values})'.format(table=table, cols=cols, values=values) return def format_sqls(table, objs: list) -> str: obj = objs.__getitem__(0) cols = ','.join(obj.keys()) values = get_values_str(objs) sql = 'insert into {table} ({cols}) values {values}'.format(table=table, cols=cols, values=values) return sql def get_values_str(objs: list): values = [] for obj in objs: values.append('({sqlValue})'.format(sqlValue=','.join(("'%s'" % o for o in obj.values())))) return ','.join(values)
# Head ends here def next_move(posr, posc, board): p = 0 q = 0 dmin = 0 dmax = 0 position = 0 for i in range(5) : count = 0 for j in range(5) : if board[i][j] == "d" : count += 1 if count == 1 : dmax = dmin = j elif count > 1 : dmax = j if count > 0 : for l in range(dmin , dmax + 1): if position < dmin : for k in range(position , dmin , 1) : print("RIGHT") position = k + 1 elif position > dmin : for k in range(position , dmin , -1) : if board[i][k] == "d" : print("CLEAN") board[i][k] == "-" print("LEFT") position = k - 1 elif position == dmin : print("CLEAN") board[i][dmin] = "-" if dmin != dmax : position += 1 print("RIGHT") if i != 4 : print("DOWN") # Tail starts here if __name__ == "__main__": pos = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(5)] next_move(pos[0], pos[1], board) # Slight Changes in the above code # Head ends here def next_move(posr, posc, board): p = 0 q = 0 dmin = 0 dmax = 0 position = 0 for i in range(5) : count = 0 for j in range(5) : if board[i][j] == "d" : count += 1 if count == 1 : dmax = dmin = j elif count > 1 : dmax = j if count > 0 : for l in range(dmin , dmax + 1): if position < dmin : for k in range(position , dmin , 1) : print("RIGHT") position = k + 1 if position > dmin : for k in range(position , dmin , -1) : if board[i][k] == "d" : print("CLEAN") board[i][k] == "-" print("LEFT") position = k - 1 if position == dmin : print("CLEAN") board[i][dmin] = "-" if dmin != dmax : position += 1 print("RIGHT") if i != 4 : print("DOWN") # Tail starts here if __name__ == "__main__": pos = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(5)] next_move(pos[0], pos[1], board)
def next_move(posr, posc, board): p = 0 q = 0 dmin = 0 dmax = 0 position = 0 for i in range(5): count = 0 for j in range(5): if board[i][j] == 'd': count += 1 if count == 1: dmax = dmin = j elif count > 1: dmax = j if count > 0: for l in range(dmin, dmax + 1): if position < dmin: for k in range(position, dmin, 1): print('RIGHT') position = k + 1 elif position > dmin: for k in range(position, dmin, -1): if board[i][k] == 'd': print('CLEAN') board[i][k] == '-' print('LEFT') position = k - 1 elif position == dmin: print('CLEAN') board[i][dmin] = '-' if dmin != dmax: position += 1 print('RIGHT') if i != 4: print('DOWN') if __name__ == '__main__': pos = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(5)] next_move(pos[0], pos[1], board) def next_move(posr, posc, board): p = 0 q = 0 dmin = 0 dmax = 0 position = 0 for i in range(5): count = 0 for j in range(5): if board[i][j] == 'd': count += 1 if count == 1: dmax = dmin = j elif count > 1: dmax = j if count > 0: for l in range(dmin, dmax + 1): if position < dmin: for k in range(position, dmin, 1): print('RIGHT') position = k + 1 if position > dmin: for k in range(position, dmin, -1): if board[i][k] == 'd': print('CLEAN') board[i][k] == '-' print('LEFT') position = k - 1 if position == dmin: print('CLEAN') board[i][dmin] = '-' if dmin != dmax: position += 1 print('RIGHT') if i != 4: print('DOWN') if __name__ == '__main__': pos = [int(i) for i in input().strip().split()] board = [[j for j in input().strip()] for i in range(5)] next_move(pos[0], pos[1], board)
class Person: def __init__(self, name): self.name = name # create the method greet here def greet(self): print(f"Hello, I am {self.name}!") in_name = input() p = Person(in_name) p.greet()
class Person: def __init__(self, name): self.name = name def greet(self): print(f'Hello, I am {self.name}!') in_name = input() p = person(in_name) p.greet()
load("@wix_oss_infra//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "org_xerial_snappy_snappy_java", artifact = "org.xerial.snappy:snappy-java:1.1.7.1", artifact_sha256 = "bb52854753feb1919f13099a53475a2a8eb65dbccd22839a9b9b2e1a2190b951", srcjar_sha256 = "a01c58c2af4bf16d2b841c74f76d98489bc03b5f9cf63aea33a8cb14ce376258", )
load('@wix_oss_infra//:import_external.bzl', import_external='safe_wix_scala_maven_import_external') def dependencies(): import_external(name='org_xerial_snappy_snappy_java', artifact='org.xerial.snappy:snappy-java:1.1.7.1', artifact_sha256='bb52854753feb1919f13099a53475a2a8eb65dbccd22839a9b9b2e1a2190b951', srcjar_sha256='a01c58c2af4bf16d2b841c74f76d98489bc03b5f9cf63aea33a8cb14ce376258')
'''from flask import render_template from flask import Response from flask import Flask app = Flask(__name__) @app.route('/') def index(): return render_template('streaming2.html') def generate(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpg\r\n\r\n' + frame + b'\r\n\r\n') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')'''
"""from flask import render_template from flask import Response from flask import Flask app = Flask(__name__) @app.route('/') def index(): return render_template('streaming2.html') def generate(camera): while True: frame = camera.get_frame() yield (b'--frame\r ' b'Content-Type: image/jpg\r \r ' + frame + b'\r \r ') @app.route('/video_feed') def video_feed(): return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')"""
class AbBuildUnsuccesful(Exception): """ Build was not successful """ def __init__(self, msg, output): self.msg = msg self.output = output def __str__(self): return "%s" % self.msg
class Abbuildunsuccesful(Exception): """ Build was not successful """ def __init__(self, msg, output): self.msg = msg self.output = output def __str__(self): return '%s' % self.msg
class StreamQueue: repeat = False current = None streams = [] def next(self): if self.repeat and self.current is not None: return self.current self.current = None if len(self.streams) > 0: self.current = self.streams.pop(0) return self.current def add(self, url): self.streams.append(url) def clear(self): self.current = None self.streams.clear() def __len__(self): return len(self.streams)
class Streamqueue: repeat = False current = None streams = [] def next(self): if self.repeat and self.current is not None: return self.current self.current = None if len(self.streams) > 0: self.current = self.streams.pop(0) return self.current def add(self, url): self.streams.append(url) def clear(self): self.current = None self.streams.clear() def __len__(self): return len(self.streams)
# GCD, LCM """ T = int(input()) def lcm(x, y): if x > y: greater = x else: greater = y while True: if greater % x == 0 and greater % y == 0: lcm = greater break greater += 1 return lcm for _ in range(T): M, N, x, y = map(int(), input().split()) """ def get_year(m, n, x, y): while x <= m * n: if (x-y) % n == 0: return x x += m return -1 T = int(input()) for _ in range(T): m, n, x, y = map(int, input().split()) print(get_year(m,n,x,y))
""" T = int(input()) def lcm(x, y): if x > y: greater = x else: greater = y while True: if greater % x == 0 and greater % y == 0: lcm = greater break greater += 1 return lcm for _ in range(T): M, N, x, y = map(int(), input().split()) """ def get_year(m, n, x, y): while x <= m * n: if (x - y) % n == 0: return x x += m return -1 t = int(input()) for _ in range(T): (m, n, x, y) = map(int, input().split()) print(get_year(m, n, x, y))
def Move(): global ArchiveIndex, gameData playerShip.landedBefore = playerShip.landedOn playerShip.landedOn = None for Thing in PlanetContainer: XDiff = playerShip.X - Thing.X YDiff = playerShip.Y + Thing.Y Distance = (XDiff ** 2 + YDiff ** 2) ** 0.5 if Distance > 40000: ArchiveContainer.append(Thing) PlanetContainer.remove(Thing) elif Distance <= Thing.size + 26: # collision OR landed --> check speed if playerShip.speed > 2: playerShip.hull -= playerShip.speed ** 2 if playerShip.hull <= 0: # crash! # Play('boom') if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: # 592+1000 playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 DisplayMessage( "You crashed and died in the explosion. You lose.") gameData = None return "to menu" else: # land! playerShip.landedOn = PlanetContainer.index(Thing) if not Thing.playerLanded: if gameData.tutorial and gameData.stage == 1: checkProgress("player landed") if ( Thing.baseAt is not None and ( ( Thing.X + Thing.size * cos(radians(Thing.baseAt + 90)) - playerShip.X ) ** 2 + ( -Thing.Y - Thing.size * sin(radians(Thing.baseAt + 90)) - playerShip.Y ) ** 2 ) ** 0.5 < 60 ): Thing.playerLanded = "base" else: Thing.playerLanded = True playerShip.toX = 0 playerShip.toY = 0 continue else: NDistance = ( (playerShip.X + playerShip.toX - Thing.X) ** 2 + (playerShip.Y + playerShip.toY + Thing.Y) ** 2 ) ** 0.5 if NDistance < Distance: playerShip.toX = Thing.size / 20 / Distance * XDiff / Distance playerShip.toY = Thing.size / 20 / Distance * YDiff / Distance playerShip.speed = ( playerShip.toX ** 2 + playerShip.toY ** 2 ) ** 0.5 playerShip.angle = degrees( atan2(-playerShip.toX, playerShip.toY) ) playerShip.move() playerShip.toX = 0 playerShip.toY = 0 continue else: Thing.playerLanded = False if gameData.stage > 0 and Thing.enemyAt is not None: pos = radians(Thing.enemyAt + 90) X = Thing.X + Thing.size * cos(pos) Y = Thing.Y + Thing.size * sin(pos) if ((playerShip.X - X) ** 2 + (playerShip.Y + Y) ** 2) ** 0.5 < 300: playerShip.hull -= random.randint(1, 3) * random.randint(1, 3) gameData.shootings = 3 if playerShip.hull <= 0: # Play('boom') if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: # 592+1000 playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 DisplayMessage("You where shot and died. You lose.") gameData = None return "to menu" Acceleration = Thing.size / 20 / Distance playerShip.toX -= Acceleration * XDiff / Distance playerShip.toY -= Acceleration * YDiff / Distance playerShip.speed = (playerShip.toX ** 2 + playerShip.toY ** 2) ** 0.5 playerShip.angle = degrees(atan2(-playerShip.toX, playerShip.toY)) for Thing in ShipContainer: # move ships Thing.move() if gameData.stage > 0: if ( (playerShip.X - Thing.X) ** 2 + (playerShip.Y + Thing.Y) ** 2 ) ** 0.5 < 300: playerShip.hull -= random.randint(1, 3) * random.randint(1, 3) gameData.shootings = 3 if playerShip.hull <= 0: Play("boom") if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: # 592+1000 playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 DisplayMessage("You where shot and died. You lose.") gameData = None return "to menu" for Thing in WreckContainer: Thing.explosion += 0.1 if Thing.explosion > 10: WreckContainer.remove(Thing) playerShip.move() if sectors.pixels2sector(playerShip.X, playerShip.Y) != sectors.pixels2sector( playerShip.X - playerShip.toX, playerShip.Y - playerShip.toY ): checkProgress("sector changed") playerView.X = playerShip.X playerView.Y = playerShip.Y if playerShip.oil <= 0: # Play('boom') if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: # 592+1000 playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.oil = 0 DisplayMessage( "Your oilsupply is empty. You can't do anything anymore. You lose." ) gameData = None return "to menu" playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 playerShip.oil = 1000 if Frames % 10 == 0: try: Distance = ( (playerShip.X - ArchiveContainer[ArchiveIndex].X) ** 2 + (playerShip.Y + ArchiveContainer[ArchiveIndex].Y) ** 2 ) ** 0.5 if Distance < 35000: T = ArchiveContainer.pop(ArchiveIndex) if type(T) == Planet: PlanetContainer.append(T) elif T.dead: WreckContainer.append(T) else: ShipContainer.append(T) ArchiveIndex = ArchiveIndex % len(ArchiveContainer) else: ArchiveIndex = (ArchiveIndex + 1) % len(ArchiveContainer) except: # If the ArchiveContainer is empty pass
def move(): global ArchiveIndex, gameData playerShip.landedBefore = playerShip.landedOn playerShip.landedOn = None for thing in PlanetContainer: x_diff = playerShip.X - Thing.X y_diff = playerShip.Y + Thing.Y distance = (XDiff ** 2 + YDiff ** 2) ** 0.5 if Distance > 40000: ArchiveContainer.append(Thing) PlanetContainer.remove(Thing) elif Distance <= Thing.size + 26: if playerShip.speed > 2: playerShip.hull -= playerShip.speed ** 2 if playerShip.hull <= 0: if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 display_message('You crashed and died in the explosion. You lose.') game_data = None return 'to menu' else: playerShip.landedOn = PlanetContainer.index(Thing) if not Thing.playerLanded: if gameData.tutorial and gameData.stage == 1: check_progress('player landed') if Thing.baseAt is not None and ((Thing.X + Thing.size * cos(radians(Thing.baseAt + 90)) - playerShip.X) ** 2 + (-Thing.Y - Thing.size * sin(radians(Thing.baseAt + 90)) - playerShip.Y) ** 2) ** 0.5 < 60: Thing.playerLanded = 'base' else: Thing.playerLanded = True playerShip.toX = 0 playerShip.toY = 0 continue else: n_distance = ((playerShip.X + playerShip.toX - Thing.X) ** 2 + (playerShip.Y + playerShip.toY + Thing.Y) ** 2) ** 0.5 if NDistance < Distance: playerShip.toX = Thing.size / 20 / Distance * XDiff / Distance playerShip.toY = Thing.size / 20 / Distance * YDiff / Distance playerShip.speed = (playerShip.toX ** 2 + playerShip.toY ** 2) ** 0.5 playerShip.angle = degrees(atan2(-playerShip.toX, playerShip.toY)) playerShip.move() playerShip.toX = 0 playerShip.toY = 0 continue else: Thing.playerLanded = False if gameData.stage > 0 and Thing.enemyAt is not None: pos = radians(Thing.enemyAt + 90) x = Thing.X + Thing.size * cos(pos) y = Thing.Y + Thing.size * sin(pos) if ((playerShip.X - X) ** 2 + (playerShip.Y + Y) ** 2) ** 0.5 < 300: playerShip.hull -= random.randint(1, 3) * random.randint(1, 3) gameData.shootings = 3 if playerShip.hull <= 0: if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 display_message('You where shot and died. You lose.') game_data = None return 'to menu' acceleration = Thing.size / 20 / Distance playerShip.toX -= Acceleration * XDiff / Distance playerShip.toY -= Acceleration * YDiff / Distance playerShip.speed = (playerShip.toX ** 2 + playerShip.toY ** 2) ** 0.5 playerShip.angle = degrees(atan2(-playerShip.toX, playerShip.toY)) for thing in ShipContainer: Thing.move() if gameData.stage > 0: if ((playerShip.X - Thing.X) ** 2 + (playerShip.Y + Thing.Y) ** 2) ** 0.5 < 300: playerShip.hull -= random.randint(1, 3) * random.randint(1, 3) gameData.shootings = 3 if playerShip.hull <= 0: play('boom') if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.hull = 0 display_message('You where shot and died. You lose.') game_data = None return 'to menu' for thing in WreckContainer: Thing.explosion += 0.1 if Thing.explosion > 10: WreckContainer.remove(Thing) playerShip.move() if sectors.pixels2sector(playerShip.X, playerShip.Y) != sectors.pixels2sector(playerShip.X - playerShip.toX, playerShip.Y - playerShip.toY): check_progress('sector changed') playerView.X = playerShip.X playerView.Y = playerShip.Y if playerShip.oil <= 0: if gameData.homePlanet in ArchiveContainer: PlanetContainer.append(gameData.homePlanet) ArchiveContainer.remove(gameData.homePlanet) if gameData.homePlanet.oil > 1592: playerShip.hull = 592 playerShip.oil = 1000 playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 gameData.homePlanet.oil -= 1592 else: playerShip.oil = 0 display_message("Your oilsupply is empty. You can't do anything anymore. You lose.") game_data = None return 'to menu' playerShip.X = 0 playerShip.Y = 25 playerShip.toX = 0 playerShip.toY = 0 playerShip.faceAngle = 180 playerShip.oil = 1000 if Frames % 10 == 0: try: distance = ((playerShip.X - ArchiveContainer[ArchiveIndex].X) ** 2 + (playerShip.Y + ArchiveContainer[ArchiveIndex].Y) ** 2) ** 0.5 if Distance < 35000: t = ArchiveContainer.pop(ArchiveIndex) if type(T) == Planet: PlanetContainer.append(T) elif T.dead: WreckContainer.append(T) else: ShipContainer.append(T) archive_index = ArchiveIndex % len(ArchiveContainer) else: archive_index = (ArchiveIndex + 1) % len(ArchiveContainer) except: pass
""" >= 0.9 A >= 0.8 B >= 0.7 C >= 0.6 D < 0.6 F """ score = input("Enter Score: ") try: s = float(score) except: print("please enter numeric numbers") quit() if s>1.0 or s< 0.0: print("value out of range! please enter number btw 1.0 and 0.0") elif s >= 0.9: print("A") elif s >=0.8: print("B") elif s >=0.7: print("C") elif s >=0.6: print("D") else: print("F")
""" >= 0.9 A >= 0.8 B >= 0.7 C >= 0.6 D < 0.6 F """ score = input('Enter Score: ') try: s = float(score) except: print('please enter numeric numbers') quit() if s > 1.0 or s < 0.0: print('value out of range! please enter number btw 1.0 and 0.0') elif s >= 0.9: print('A') elif s >= 0.8: print('B') elif s >= 0.7: print('C') elif s >= 0.6: print('D') else: print('F')
def names(l): # list way new = [] for i in l: if not i in new: new.append(i) # set way new = list(set(l)) print(new) names(["Michele", "Robin", "Sara", "Michele"])
def names(l): new = [] for i in l: if not i in new: new.append(i) new = list(set(l)) print(new) names(['Michele', 'Robin', 'Sara', 'Michele'])
mylist = [1, 2, 3] # Imprime 1,2,3 for x in mylist: print(x)
mylist = [1, 2, 3] for x in mylist: print(x)
""" 141. Linked List Cycle """ class Solution(object): def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ slow = fast = head while fast and fast.next: fast = fast.next.next slow = slow.next if slow == fast: return True return False
""" 141. Linked List Cycle """ class Solution(object): def has_cycle(self, head): """ :type head: ListNode :rtype: bool """ slow = fast = head while fast and fast.next: fast = fast.next.next slow = slow.next if slow == fast: return True return False
#Print without newline or space print("\n") for j in range(10): print("") for i in range(10): print(' @ ', end="") print("\n")
print('\n') for j in range(10): print('') for i in range(10): print(' @ ', end='') print('\n')
class Entry: def __init__(self, obj, line_number = 1): self.obj = obj self.line_number = line_number def __repr__(self): return "In {}, line {}".format(self.obj.name, self.line_number) class CallStack: def __init__(self, initial = None): self.__stack = [] if not initial else initial def __repr__(self): stk = "\n".join([str(entry) for entry in self.__stack]) return "Traceback (Most recent call last):\n" + stk + "\n" __str__ = __repr__ def __len__(self): return len(self.__stack) def append(self, entry): self.__stack.append(entry) def pop(self): last = self.__stack[-1] self.__stack.pop() return last def __getitem__(self, index): if isinstance(index, slice): return CallStack(self.__stack[index]) else: return self.__stack[index]
class Entry: def __init__(self, obj, line_number=1): self.obj = obj self.line_number = line_number def __repr__(self): return 'In {}, line {}'.format(self.obj.name, self.line_number) class Callstack: def __init__(self, initial=None): self.__stack = [] if not initial else initial def __repr__(self): stk = '\n'.join([str(entry) for entry in self.__stack]) return 'Traceback (Most recent call last):\n' + stk + '\n' __str__ = __repr__ def __len__(self): return len(self.__stack) def append(self, entry): self.__stack.append(entry) def pop(self): last = self.__stack[-1] self.__stack.pop() return last def __getitem__(self, index): if isinstance(index, slice): return call_stack(self.__stack[index]) else: return self.__stack[index]
class BaseConfig(): API_PREFIX = '/api' TESTING = False DEBUG = False SECRET_KEY = '@!s3cr3t' AGENT_SOCK = 'cmdsrv__0' class DevConfig(BaseConfig): FLASK_ENV = 'development' DEBUG = True CELERY_BROKER = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' REDIS_URL = "redis://localhost:6379/0" IFACE = "eno2" class ProductionConfig(BaseConfig): FLASK_ENV = 'production' CELERY_BROKER = 'redis://localhost:6379/0' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' REDIS_URL = "redis://localhost:6379/0" class TestConfig(BaseConfig): FLASK_ENV = 'development' TESTING = True DEBUG = True # make celery execute tasks synchronously in the same process CELERY_ALWAYS_EAGER = True
class Baseconfig: api_prefix = '/api' testing = False debug = False secret_key = '@!s3cr3t' agent_sock = 'cmdsrv__0' class Devconfig(BaseConfig): flask_env = 'development' debug = True celery_broker = 'redis://localhost:6379/0' celery_result_backend = 'redis://localhost:6379/0' redis_url = 'redis://localhost:6379/0' iface = 'eno2' class Productionconfig(BaseConfig): flask_env = 'production' celery_broker = 'redis://localhost:6379/0' celery_result_backend = 'redis://localhost:6379/0' redis_url = 'redis://localhost:6379/0' class Testconfig(BaseConfig): flask_env = 'development' testing = True debug = True celery_always_eager = True
while True: x,y=map(int,input().split()) if x==0 and y==0: break print(x+y)
while True: (x, y) = map(int, input().split()) if x == 0 and y == 0: break print(x + y)
def encode(json, schema): payload = schema.Main() payload.github = json['github'] payload.patreon = json['patreon'] payload.open_collective = json['open_collective'] payload.ko_fi = json['ko_fi'] payload.tidelift = json['tidelift'] payload.community_bridge = json['community_bridge'] payload.liberapay = json['liberapay'] payload.issuehunt = json['issuehunt'] payload.otechie = json['otechie'] payload.custom = json['custom'] return payload def decode(payload): return payload.__dict__
def encode(json, schema): payload = schema.Main() payload.github = json['github'] payload.patreon = json['patreon'] payload.open_collective = json['open_collective'] payload.ko_fi = json['ko_fi'] payload.tidelift = json['tidelift'] payload.community_bridge = json['community_bridge'] payload.liberapay = json['liberapay'] payload.issuehunt = json['issuehunt'] payload.otechie = json['otechie'] payload.custom = json['custom'] return payload def decode(payload): return payload.__dict__
#!/usr/local/bin/python3 """ This is written by Zhiyang Ong to try out Solutions 1-4 from [Sceenivasan, 2017]. Reference for Solutions 1, 2, 3, and 4 [Sceenivasan, 2017]: Sreeram Sceenivasan, "How to implement a switch-case statement in Python: No in-built switch statement here," from JAXenter.com, Software {\rm \&}\ Support Media {GmbH}, Frankfurt, Germany, October 24, 2017. Available online from JAXenter.com at: https://jaxenter.com/implement-switch-case-statement-python-138315.html; June 26, 2020 was the last accessed date See https://gist.github.com/eda-ricercatore/8cbb931f330af2b5e96edaa8b89ed0c4 for the public GitHub Gist of this. """ # -------------------------------------------------------- # Solution 1. def switch_demo(argument): switcher = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } #print(switcher.get(argument, "Invalid month")) return switcher.get(argument, "Invalid month") # -------------------------------------------------------- # Solution 2. def one(): return "January" def two(): return "February" def three(): return "March" def four(): return "April" def five(): return "May" def six(): return "June" def seven(): return "July" def eight(): return "August" def nine(): return "September" def ten(): return "October" def eleven(): return "November" def twelve(): return "December" # For solution 4, create a case for the 93th month. def new_month(): return "new-month-created" """ Redundant function. For solution 4, create a catch-all case for invalid input. def invalid_input(): return "Invalid month" """ """ Create a dictionary with function names as values, rather than basic data types such as strings and integers/floats, since the values of a Python dictionary can be of any data type. Likewise, we can also use lambdas as values for a dictionary. This enables users to use the dictionary "to execute ... blocks of code within each function". """ def numbers_to_months(argument): switcher = { 1: one, 2: two, 3: three, 4: four, 5: five, 6: six, 7: seven, 8: eight, 9: nine, 10: ten, 11: eleven, 12: twelve } # Get the function from switcher dictionary func = switcher.get(argument, lambda: "Invalid month") # Execute the function #print(func()) return func() # -------------------------------------------------------- # Solution 3. class Switcher(object): def numbers_to_months(self, argument): #Dispatch method method_name = 'month_' + str(argument) # Get the method from 'self'. Default to a lambda. method = getattr(self, method_name, lambda: "Invalid month") # Call the method as we return it return method() def month_1(self): return "January" def month_2(self): return "February" def month_3(self): return "March" def month_4(self): return "April" def month_5(self): return "May" def month_6(self): return "June" def month_7(self): return "July" def month_8(self): return "August" def month_9(self): return "September" def month_10(self): return "October" def month_11(self): return "November" def month_12(self): return "December" # -------------------------------------------------------- # Solution 4. switcher = { 1: one, 2: two, 3: three, 4: four, 5: five, 6: six, 7: seven, 8: eight, 9: nine, 10: ten, 11: eleven, 12: twelve } """ Published Solution 4 in [Sceenivasan, 2017] fails to work for the default case, or the catch-all case for cases not covered in the dictionary named "switcher". Used a lambda function to provide the catch-all case for cases not covered in the dictionary named "switcher". """ def numbers_to_strings(argument): # Get the function from switcher dictionary #func = switcher.get(argument, "nothing") func = switcher.get(argument, lambda: "Invalid month") # Execute the function return func() # -------------------------------------------------------- # Solution from [patel, 2017] def f(x): return { 1 : "output for case 1", 2 : "output for case 2", 3 : "output for case 3" }.get(x, "default case") # -------------------------------------------------------- """ Solution 5. Modified solution from Stephan Schielke, April 8, 2017 at 15:19. Use static functions with a dictionary. """ @staticmethod def spring_months(): return "March-May" @staticmethod def summer_months(): return "June-August" @staticmethod def fall_months(): return "September-November" @staticmethod def winter_months(): return "December-February" months_of_year = { 1: winter_months, 2: winter_months, 3: spring_months, 4: spring_months, 5: spring_months, 6: summer_months, 7: summer_months, 8: summer_months, 9: fall_months, 10: fall_months, 11: fall_months, 12: winter_months } # -------------------------------------------------------- """ Solutions not considered: + From user5359735/IanMobbs, June 13, 2016 at 17:09, - Reference: https://stackoverflow.com/a/11479840/1531728 * Comment from user to answer from Prashant Kumar, last edited on December 3, 2014. - Sanjay Manohar, July 26, 2017 at 14:26, mentioned that putting code in constant string in (double) quotes for evaluation using "eval" has multiple risks, such as: * checking for errors by text editor and IDE. + Cannot use features of text editor and IDE, such syntax highlighting. * Not "optimized to bytecode at compilation." * lambda functions can be used instead, but is "considered un-Pythonic". """ ############################################################### # Main method for the program. # If this is executed as a Python script, if __name__ == "__main__": print("=== Trying solutions from [Sceenivasan, 2017].") #print("Get month for 9:",switch_demo(9),"=") print("Trying Solution 1.") print("= Testing: switch_demo().") for x in range(1, 12+1): print("Get month for:",x,"named:",switch_demo(x),"=") print("Get month for 56798:",switch_demo(56798),"=") print("Get month for -443:",switch_demo(-443),"=") print("Trying Solution 2.") print("= Testing: numbers_to_months().") for x in range(1, 12+1): print("Get month for:",x,"named:",numbers_to_months(x),"=") print("Get month for 56798:",numbers_to_months(56798),"=") print("Get month for -443:",numbers_to_months(-443),"=") print("Trying Solution 3.") print("= Testing: Switcher class solution with lambda function.") a=Switcher() for x in range(1, 12+1): print("Get month for:",x,"named:",a.numbers_to_months(x),"=") print("Get month for 56798:",a.numbers_to_months(56798),"=") print("Get month for -443:",a.numbers_to_months(-443),"=") print("Trying Solution 4.") print("= Testing: numbers_to_strings() method with modification to dictionary.") for x in range(1, 12+1): print("Get month for:",x,"named:",numbers_to_strings(x),"=") print(" - Modify the case for the 8th month to the 3rd month, March.") switcher[8] = three print("Get month for 8:",numbers_to_strings(8),"=") print(" - Create a case for the 93th month.") switcher[93] = new_month print("Get month for 93:",numbers_to_strings(93),"=") print("Get month for 56798:",numbers_to_strings(56798),"=") print("Get month for -443:",numbers_to_strings(-443),"=") """ \cite{Bader2020a} describes multiple default data structures supported by the Python Standard Library \cite{DrakeJr2016b}. Here, the example uses a dictionary. """ print("Trying Solution 5.") print("= Testing: dictionary-based solution using static functions.") for x in range(1, 12+1): print("Get season for:",x,":::",months_of_year[x].__func__(),"=") print(" - Modify the case for the 8th month to the winter season.") months_of_year[8] = winter_months print("Get month for 8:",months_of_year[8].__func__(),"=") print(" - Create a case for the 93th month.") months_of_year[93] = spring_months print("Get month for 93:",months_of_year[93].__func__(),"=") try: print("Get month for 56798:",months_of_year[56798].__func__(),"=") except KeyError as invalid_key: print("Cannot use invalid key to access a key:value pair in a Python dictionary.") print("The key 56798 being used is invalid.") try: print("Get month for -443:",months_of_year[-443].__func__(),"=") except KeyError as invalid_key: print("Cannot use invalid key to access a key:value pair in a Python dictionary.") print("The key -443 being used is invalid.") """ Additional resources that I looked at: + Prashant Kumar, Answer to "What is the Python equivalent for a case/switch statement? [duplicate]," Stack Exchange Inc., New York, NY, December 3, 2014. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/11479840/1531728; June 27, 2020 was the last accessed date. - This is used as Solution 1 in [Sceenivasan, 2017]. - References the following: * Shrutarshi Basu, "Switch-case statement in Python", Powerful Python series, The ByteBaker, Cambridge, MA, November 3, 2008. Available online from The ByteBaker: Powerful Python at: + Raymond Hettinger, Answer to "Why doesn't Python have switch-case?," Stack Exchange Inc., New York, NY, October 12, 2017. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/46701087/1531728; June 27, 2020 was the last accessed date. - "We considered it at one point, but without having a way to declare named constants, there is no way to generate an efficient jump table. So all we would be left with is syntactic sugar for something we could already do with if-elif-elif-else chains. - "See PEP 275 and PEP 3103 for a full discussion." * https://www.python.org/dev/peps/pep-0275/ * https://www.python.org/dev/peps/pep-3103/ - "Roughly the rationale is that the various proposals failed to live up to people's expections about what switch-case would do, and they failed to improve on existing solutions (like dictionary-based dispatch, if-elif-chains, getattr-based dispatch, or old-fashioned polymorphism dispatch to objects with differing implementations for the same method)." + wim glenn, Answer to "Why doesn't Python have switch-case?," Stack Exchange Inc., New York, NY, October 12, 2017. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/46701135/1531728; June 27, 2020 was the last accessed date. - https://docs.python.org/3/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python + vedant patel and Vincenzo Carrese, Answer to "Why doesn't Python have switch-case?," Stack Exchange Inc., New York, NY, December 20, 2017. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/47902285/1531728; June 27, 2020 was the last accessed date. - [patel, 2017] """ print("Trying Solution from [patel, 2017].") print("= Testing: dictionary method, alternate specification/declaration.") """ range(1, 3+2) results in 1, 2, 3, 4, since range(x,y) results in x, x+1, ..., y-2, y-1. """ for x in range(1, 3+2): #for x in range(1, 8): print("Trying index:",x,"with output:",f(x),"=")
""" This is written by Zhiyang Ong to try out Solutions 1-4 from [Sceenivasan, 2017]. Reference for Solutions 1, 2, 3, and 4 [Sceenivasan, 2017]: Sreeram Sceenivasan, "How to implement a switch-case statement in Python: No in-built switch statement here," from JAXenter.com, Software {\rm \\&}\\ Support Media {GmbH}, Frankfurt, Germany, October 24, 2017. Available online from JAXenter.com at: https://jaxenter.com/implement-switch-case-statement-python-138315.html; June 26, 2020 was the last accessed date See https://gist.github.com/eda-ricercatore/8cbb931f330af2b5e96edaa8b89ed0c4 for the public GitHub Gist of this. """ def switch_demo(argument): switcher = {1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'} return switcher.get(argument, 'Invalid month') def one(): return 'January' def two(): return 'February' def three(): return 'March' def four(): return 'April' def five(): return 'May' def six(): return 'June' def seven(): return 'July' def eight(): return 'August' def nine(): return 'September' def ten(): return 'October' def eleven(): return 'November' def twelve(): return 'December' def new_month(): return 'new-month-created' '\n\tRedundant function.\n\tFor solution 4, create a catch-all case for invalid input.\ndef invalid_input():\n\treturn "Invalid month"\n' '\n\tCreate a dictionary with function names as values, rather\n\t\tthan basic data types such as strings and integers/floats,\n\t\tsince the values of a Python dictionary can be of any\n\t\tdata type.\n\tLikewise, we can also use lambdas as values for a dictionary.\n\t\n\tThis enables users to use the dictionary "to execute ...\n\t\tblocks of code within each function".\n' def numbers_to_months(argument): switcher = {1: one, 2: two, 3: three, 4: four, 5: five, 6: six, 7: seven, 8: eight, 9: nine, 10: ten, 11: eleven, 12: twelve} func = switcher.get(argument, lambda : 'Invalid month') return func() class Switcher(object): def numbers_to_months(self, argument): method_name = 'month_' + str(argument) method = getattr(self, method_name, lambda : 'Invalid month') return method() def month_1(self): return 'January' def month_2(self): return 'February' def month_3(self): return 'March' def month_4(self): return 'April' def month_5(self): return 'May' def month_6(self): return 'June' def month_7(self): return 'July' def month_8(self): return 'August' def month_9(self): return 'September' def month_10(self): return 'October' def month_11(self): return 'November' def month_12(self): return 'December' switcher = {1: one, 2: two, 3: three, 4: four, 5: five, 6: six, 7: seven, 8: eight, 9: nine, 10: ten, 11: eleven, 12: twelve} '\n\tPublished Solution 4 in [Sceenivasan, 2017] fails to work\n\t\tfor the default case, or the catch-all case for cases\n\t\tnot covered in the dictionary named "switcher".\n\t\n\tUsed a lambda function to provide the catch-all case for\n\t\tcases not covered in the dictionary named "switcher".\n' def numbers_to_strings(argument): func = switcher.get(argument, lambda : 'Invalid month') return func() def f(x): return {1: 'output for case 1', 2: 'output for case 2', 3: 'output for case 3'}.get(x, 'default case') '\n\tSolution 5.\n\n\tModified solution from Stephan Schielke, April 8, 2017 at 15:19.\n\n\tUse static functions with a dictionary.\n' @staticmethod def spring_months(): return 'March-May' @staticmethod def summer_months(): return 'June-August' @staticmethod def fall_months(): return 'September-November' @staticmethod def winter_months(): return 'December-February' months_of_year = {1: winter_months, 2: winter_months, 3: spring_months, 4: spring_months, 5: spring_months, 6: summer_months, 7: summer_months, 8: summer_months, 9: fall_months, 10: fall_months, 11: fall_months, 12: winter_months} '\n\tSolutions not considered:\n\t+ From user5359735/IanMobbs, June 13, 2016 at 17:09, \n\t\t- Reference: https://stackoverflow.com/a/11479840/1531728\n\t\t\t* Comment from user to answer from Prashant Kumar,\n\t\t\t\tlast edited on December 3, 2014.\n\t\t- Sanjay Manohar, July 26, 2017 at 14:26, mentioned that\n\t\t\tputting code in constant string in (double) quotes\n\t\t\tfor evaluation using "eval" has multiple risks, such as:\n\t\t\t* checking for errors by text editor and IDE.\n\t\t\t\t+ Cannot use features of text editor and IDE, such\n\t\t\t\t\tsyntax highlighting.\n\t\t\t* Not "optimized to bytecode at compilation."\n\t\t\t* lambda functions can be used instead, but is\n\t\t\t\t"considered un-Pythonic".\n\t\t\n' if __name__ == '__main__': print('===\tTrying solutions from [Sceenivasan, 2017].') print('Trying Solution 1.') print('=\tTesting: switch_demo().') for x in range(1, 12 + 1): print('Get month for:', x, 'named:', switch_demo(x), '=') print('Get month for 56798:', switch_demo(56798), '=') print('Get month for -443:', switch_demo(-443), '=') print('Trying Solution 2.') print('=\tTesting: numbers_to_months().') for x in range(1, 12 + 1): print('Get month for:', x, 'named:', numbers_to_months(x), '=') print('Get month for 56798:', numbers_to_months(56798), '=') print('Get month for -443:', numbers_to_months(-443), '=') print('Trying Solution 3.') print('=\tTesting: Switcher class solution with lambda function.') a = switcher() for x in range(1, 12 + 1): print('Get month for:', x, 'named:', a.numbers_to_months(x), '=') print('Get month for 56798:', a.numbers_to_months(56798), '=') print('Get month for -443:', a.numbers_to_months(-443), '=') print('Trying Solution 4.') print('=\tTesting: numbers_to_strings() method with modification to dictionary.') for x in range(1, 12 + 1): print('Get month for:', x, 'named:', numbers_to_strings(x), '=') print('\t- Modify the case for the 8th month to the 3rd month, March.') switcher[8] = three print('Get month for 8:', numbers_to_strings(8), '=') print('\t- Create a case for the 93th month.') switcher[93] = new_month print('Get month for 93:', numbers_to_strings(93), '=') print('Get month for 56798:', numbers_to_strings(56798), '=') print('Get month for -443:', numbers_to_strings(-443), '=') '\n\t\t\\cite{Bader2020a} describes multiple default data structures\n\t\t\tsupported by the Python Standard Library \\cite{DrakeJr2016b}.\n\n\t\tHere, the example uses a dictionary.\n\t' print('Trying Solution 5.') print('=\tTesting: dictionary-based solution using static functions.') for x in range(1, 12 + 1): print('Get season for:', x, ':::', months_of_year[x].__func__(), '=') print('\t- Modify the case for the 8th month to the winter season.') months_of_year[8] = winter_months print('Get month for 8:', months_of_year[8].__func__(), '=') print('\t- Create a case for the 93th month.') months_of_year[93] = spring_months print('Get month for 93:', months_of_year[93].__func__(), '=') try: print('Get month for 56798:', months_of_year[56798].__func__(), '=') except KeyError as invalid_key: print('Cannot use invalid key to access a key:value pair in a Python dictionary.') print('The key 56798 being used is invalid.') try: print('Get month for -443:', months_of_year[-443].__func__(), '=') except KeyError as invalid_key: print('Cannot use invalid key to access a key:value pair in a Python dictionary.') print('The key -443 being used is invalid.') '\n\t\tAdditional resources that I looked at:\n\t\t+ Prashant Kumar, Answer to "What is the Python equivalent for a case/switch statement? [duplicate]," Stack Exchange Inc., New York, NY, December 3, 2014. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/11479840/1531728; June 27, 2020 was the last accessed date.\n\t\t\t- This is used as Solution 1 in [Sceenivasan, 2017].\n\t\t\t- References the following:\n\t\t\t\t* Shrutarshi Basu, "Switch-case statement in Python",\n\t\t\t\t\tPowerful Python series, The ByteBaker, Cambridge, MA,\n\t\t\t\t\tNovember 3, 2008.\n\t\t\t\t\tAvailable online from The ByteBaker: Powerful Python at: \n\t\t+ Raymond Hettinger, Answer to "Why doesn\'t Python have switch-case?," Stack Exchange Inc., New York, NY, October 12, 2017. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/46701087/1531728; June 27, 2020 was the last accessed date.\n\t\t\t- "We considered it at one point, but without having a way to declare named constants, there is no way to generate an efficient jump table. So all we would be left with is syntactic sugar for something we could already do with if-elif-elif-else chains.\n\t\t\t- "See PEP 275 and PEP 3103 for a full discussion."\n\t\t\t\t* https://www.python.org/dev/peps/pep-0275/\n\t\t\t\t* https://www.python.org/dev/peps/pep-3103/\n\t\t\t- "Roughly the rationale is that the various proposals failed to live up to people\'s expections about what switch-case would do, and they failed to improve on existing solutions (like dictionary-based dispatch, if-elif-chains, getattr-based dispatch, or old-fashioned polymorphism dispatch to objects with differing implementations for the same method)."\n\t\t+ wim glenn, Answer to "Why doesn\'t Python have switch-case?," Stack Exchange Inc., New York, NY, October 12, 2017. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/46701135/1531728; June 27, 2020 was the last accessed date.\n\t\t\t- https://docs.python.org/3/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python\n\t\t+ vedant patel and Vincenzo Carrese, Answer to "Why doesn\'t Python have switch-case?," Stack Exchange Inc., New York, NY, December 20, 2017. Available online from Stack Exchange Inc.: Stack Overflow: Questions at: https://stackoverflow.com/a/47902285/1531728; June 27, 2020 was the last accessed date.\n\t\t\t- [patel, 2017]\n\t' print('Trying Solution from [patel, 2017].') print('=\tTesting: dictionary method, alternate specification/declaration.') '\n\t\trange(1, 3+2) results in 1, 2, 3, 4, since range(x,y)\n\t\t\tresults in x, x+1, ..., y-2, y-1.\n\t' for x in range(1, 3 + 2): print('Trying index:', x, 'with output:', f(x), '=')
# Implement a MyCalendar class to store your events. A new event can be added if adding the event will not cause a double booking. # # Your class will have the method, book(int start, int end). Formally, this represents a booking on the half open interval [start, end), the range of real numbers x such that start <= x < end. # # A double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.) # # For each call to the method MyCalendar.book, return true if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false and do not add the event to the calendar. # # Your class will be called like this: MyCalendar cal = new MyCalendar(); MyCalendar.book(start, end) # Example 1: # MyCalendar(); # MyCalendar.book(10, 20); // returns true # MyCalendar.book(15, 25); // returns false # MyCalendar.book(20, 30); // returns true # Explanation: # The first event can be booked. The second can't because time 15 is already booked by another event. # The third event can be booked, as the first event takes every time less than 20, but not including 20. # Note: # # The number of calls to MyCalendar.book per test case will be at most 1000. # In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9]. class MyCalendar(object): def __init__(self): pass def book(self, start, end): """ :type start: int :type end: int :rtype: bool """ # Your MyCalendar object will be instantiated and called as such: # obj = MyCalendar() # param_1 = obj.book(start,end)
class Mycalendar(object): def __init__(self): pass def book(self, start, end): """ :type start: int :type end: int :rtype: bool """
#!/usr/bin/python3 OPENVSWITCH_SERVICES_EXPRS = [r"ovsdb-\S+", r"ovs-vswitch\S+", r"ovn\S+"] OVS_PKGS = [r"libc-bin", r"openvswitch-switch", r"ovn", ] OVS_DAEMONS = {"ovs-vswitchd": {"logs": "var/log/openvswitch/ovs-vswitchd.log"}, "ovsdb-server": {"logs": "var/log/openvswitch/ovsdb-server.log"}}
openvswitch_services_exprs = ['ovsdb-\\S+', 'ovs-vswitch\\S+', 'ovn\\S+'] ovs_pkgs = ['libc-bin', 'openvswitch-switch', 'ovn'] ovs_daemons = {'ovs-vswitchd': {'logs': 'var/log/openvswitch/ovs-vswitchd.log'}, 'ovsdb-server': {'logs': 'var/log/openvswitch/ovsdb-server.log'}}
#!/usr/bin/env python3 inputs = {} reduced = {} with open("input.txt") as f: for line in f: inp, to = map(lambda x: x.strip(), line.split("->")) inputs[to] = inp.split(" ") inputs["b"] = "956" def reduce(name): try: return int(name) except: pass try: return int(inputs[name]) except: pass if name not in reduced: exp = inputs[name] if len(exp) == 1: res = reduce(exp[0]) else: op = exp[-2] if op == "NOT": res = ~reduce(exp[1]) & 0xffff elif op == "AND": res = reduce(exp[0]) & reduce(exp[2]) elif op == "OR": res = reduce(exp[0]) | reduce(exp[2]) elif op == "LSHIFT": res = reduce(exp[0]) << reduce(exp[2]) elif op == "RSHIFT": res = reduce(exp[0]) >> reduce(exp[2]) reduced[name] = res return reduced[name] print(reduce("a"))
inputs = {} reduced = {} with open('input.txt') as f: for line in f: (inp, to) = map(lambda x: x.strip(), line.split('->')) inputs[to] = inp.split(' ') inputs['b'] = '956' def reduce(name): try: return int(name) except: pass try: return int(inputs[name]) except: pass if name not in reduced: exp = inputs[name] if len(exp) == 1: res = reduce(exp[0]) else: op = exp[-2] if op == 'NOT': res = ~reduce(exp[1]) & 65535 elif op == 'AND': res = reduce(exp[0]) & reduce(exp[2]) elif op == 'OR': res = reduce(exp[0]) | reduce(exp[2]) elif op == 'LSHIFT': res = reduce(exp[0]) << reduce(exp[2]) elif op == 'RSHIFT': res = reduce(exp[0]) >> reduce(exp[2]) reduced[name] = res return reduced[name] print(reduce('a'))
LCGDIR = '../lib/sunos5' LIBDIR = '${LCGDIR}' BF_PYTHON = '/usr/local' BF_PYTHON_VERSION = '3.2' BF_PYTHON_INC = '${BF_PYTHON}/include/python${BF_PYTHON_VERSION}' BF_PYTHON_BINARY = '${BF_PYTHON}/bin/python${BF_PYTHON_VERSION}' BF_PYTHON_LIB = 'python${BF_PYTHON_VERSION}' #BF_PYTHON+'/lib/python'+BF_PYTHON_VERSION+'/config/libpython'+BF_PYTHON_VERSION+'.a' BF_PYTHON_LINKFLAGS = ['-Xlinker', '-export-dynamic'] WITH_BF_OPENAL = True WITH_BF_STATICOPENAL = False BF_OPENAL = '/usr/local' BF_OPENAL_INC = '${BF_OPENAL}/include' BF_OPENAL_LIBPATH = '${BF_OPENAL}/lib' BF_OPENAL_LIB = 'openal' # Warning, this static lib configuration is untested! users of this OS please confirm. BF_OPENAL_LIB_STATIC = '${BF_OPENAL}/lib/libopenal.a' # Warning, this static lib configuration is untested! users of this OS please confirm. BF_CXX = '/usr' WITH_BF_STATICCXX = False BF_CXX_LIB_STATIC = '${BF_CXX}/lib/libstdc++.a' WITH_BF_SDL = True BF_SDL = '/usr/local' #$(shell sdl-config --prefix) BF_SDL_INC = '${BF_SDL}/include/SDL' #$(shell $(BF_SDL)/bin/sdl-config --cflags) BF_SDL_LIBPATH = '${BF_SDL}/lib' BF_SDL_LIB = 'SDL' #BF_SDL #$(shell $(BF_SDL)/bin/sdl-config --libs) -lSDL_mixer WITH_BF_OPENEXR = True WITH_BF_STATICOPENEXR = False BF_OPENEXR = '/usr/local' BF_OPENEXR_INC = ['${BF_OPENEXR}/include', '${BF_OPENEXR}/include/OpenEXR' ] BF_OPENEXR_LIBPATH = '${BF_OPENEXR}/lib' BF_OPENEXR_LIB = 'Half IlmImf Iex Imath ' # Warning, this static lib configuration is untested! users of this OS please confirm. BF_OPENEXR_LIB_STATIC = '${BF_OPENEXR}/lib/libHalf.a ${BF_OPENEXR}/lib/libIlmImf.a ${BF_OPENEXR}/lib/libIex.a ${BF_OPENEXR}/lib/libImath.a ${BF_OPENEXR}/lib/libIlmThread.a' WITH_BF_DDS = True WITH_BF_JPEG = True BF_JPEG = '/usr/local' BF_JPEG_INC = '${BF_JPEG}/include' BF_JPEG_LIBPATH = '${BF_JPEG}/lib' BF_JPEG_LIB = 'jpeg' WITH_BF_PNG = True BF_PNG = '/usr/local' BF_PNG_INC = '${BF_PNG}/include' BF_PNG_LIBPATH = '${BF_PNG}/lib' BF_PNG_LIB = 'png' BF_TIFF = '/usr/local' BF_TIFF_INC = '${BF_TIFF}/include' WITH_BF_ZLIB = True BF_ZLIB = '/usr' BF_ZLIB_INC = '${BF_ZLIB}/include' BF_ZLIB_LIBPATH = '${BF_ZLIB}/lib' BF_ZLIB_LIB = 'z' WITH_BF_INTERNATIONAL = True BF_GETTEXT = '/usr/local' BF_GETTEXT_INC = '${BF_GETTEXT}/include' BF_GETTEXT_LIB = 'gettextlib' BF_GETTEXT_LIBPATH = '${BF_GETTEXT}/lib' WITH_BF_GAMEENGINE=False WITH_BF_PLAYER = False WITH_BF_BULLET = True BF_BULLET = '#extern/bullet2/src' BF_BULLET_INC = '${BF_BULLET}' BF_BULLET_LIB = 'extern_bullet' #WITH_BF_NSPR = True #BF_NSPR = $(LIBDIR)/nspr #BF_NSPR_INC = -I$(BF_NSPR)/include -I$(BF_NSPR)/include/nspr #BF_NSPR_LIB = # Uncomment the following line to use Mozilla inplace of netscape #CPPFLAGS += -DMOZ_NOT_NET # Location of MOZILLA/Netscape header files... #BF_MOZILLA = $(LIBDIR)/mozilla #BF_MOZILLA_INC = -I$(BF_MOZILLA)/include/mozilla/nspr -I$(BF_MOZILLA)/include/mozilla -I$(BF_MOZILLA)/include/mozilla/xpcom -I$(BF_MOZILLA)/include/mozilla/idl #BF_MOZILLA_LIB = # Will fall back to look in BF_MOZILLA_INC/nspr and BF_MOZILLA_LIB # if this is not set. # # Be paranoid regarding library creation (do not update archives) #BF_PARANOID = True # enable freetype2 support for text objects BF_FREETYPE = '/usr/local' BF_FREETYPE_INC = '${BF_FREETYPE}/include ${BF_FREETYPE}/include/freetype2' BF_FREETYPE_LIBPATH = '${BF_FREETYPE}/lib' BF_FREETYPE_LIB = 'freetype' WITH_BF_QUICKTIME = False # -DWITH_QUICKTIME BF_QUICKTIME = '/usr/local' BF_QUICKTIME_INC = '${BF_QUICKTIME}/include' WITH_BF_ICONV = True BF_ICONV = "/usr" BF_ICONV_INC = '${BF_ICONV}/include' BF_ICONV_LIB = 'iconv' BF_ICONV_LIBPATH = '${BF_ICONV}/lib' # enable ffmpeg support WITH_BF_FFMPEG = True # -DWITH_FFMPEG BF_FFMPEG = '/usr/local' BF_FFMPEG_INC = '${BF_FFMPEG}/include' BF_FFMPEG_LIBPATH='${BF_FFMPEG}/lib' BF_FFMPEG_LIB = 'avformat avcodec avutil avdevice' # Mesa Libs should go here if your using them as well.... WITH_BF_STATICOPENGL = False BF_OPENGL = '/usr/openwin' BF_OPENGL_INC = '${BF_OPENGL}/include' BF_OPENGL_LIB = 'GL GLU X11 Xi' BF_OPENGL_LIBPATH = '${BF_OPENGL}/lib' BF_OPENGL_LIB_STATIC = '${BF_OPENGL_LIBPATH}/libGL.a ${BF_OPENGL_LIBPATH}/libGLU.a ${BF_OPENGL_LIBPATH}/libXxf86vm.a ${BF_OPENGL_LIBPATH}/libX11.a ${BF_OPENGL_LIBPATH}/libXi.a ${BF_OPENGL_LIBPATH}/libXext.a ${BF_OPENGL_LIBPATH}/libXxf86vm.a' ## CC = 'gcc' CXX = 'g++' ##ifeq ($CPU),alpha) ## CFLAGS += -pipe -fPIC -funsigned-char -fno-strict-aliasing -mieee CCFLAGS = ['-pipe','-fPIC','-funsigned-char','-fno-strict-aliasing'] CPPFLAGS = ['-DSUN_OGL_NO_VERTEX_MACROS'] CXXFLAGS = ['-pipe','-fPIC','-funsigned-char','-fno-strict-aliasing'] REL_CFLAGS = ['-DNDEBUG', '-O2'] REL_CCFLAGS = ['-DNDEBUG', '-O2'] ##BF_DEPEND = True ## ##AR = ar ##ARFLAGS = ruv ##ARFLAGSQUIET = ru ## C_WARN = ['-Wno-char-subscripts', '-Wdeclaration-after-statement'] CC_WARN = ['-Wall'] ##FIX_STUBS_WARNINGS = -Wno-unused LLIBS = ['c', 'm', 'dl', 'pthread', 'stdc++'] ##LOPTS = --dynamic ##DYNLDFLAGS = -shared $(LDFLAGS) BF_PROFILE_CCFLAGS = ['-pg', '-g '] BF_PROFILE_LINKFLAGS = ['-pg'] BF_PROFILE = False BF_DEBUG = False BF_DEBUG_CCFLAGS = ['-D_DEBUG'] BF_BUILDDIR = '../build/sunos5' BF_INSTALLDIR='../install/sunos5' PLATFORM_LINKFLAGS = []
lcgdir = '../lib/sunos5' libdir = '${LCGDIR}' bf_python = '/usr/local' bf_python_version = '3.2' bf_python_inc = '${BF_PYTHON}/include/python${BF_PYTHON_VERSION}' bf_python_binary = '${BF_PYTHON}/bin/python${BF_PYTHON_VERSION}' bf_python_lib = 'python${BF_PYTHON_VERSION}' bf_python_linkflags = ['-Xlinker', '-export-dynamic'] with_bf_openal = True with_bf_staticopenal = False bf_openal = '/usr/local' bf_openal_inc = '${BF_OPENAL}/include' bf_openal_libpath = '${BF_OPENAL}/lib' bf_openal_lib = 'openal' bf_openal_lib_static = '${BF_OPENAL}/lib/libopenal.a' bf_cxx = '/usr' with_bf_staticcxx = False bf_cxx_lib_static = '${BF_CXX}/lib/libstdc++.a' with_bf_sdl = True bf_sdl = '/usr/local' bf_sdl_inc = '${BF_SDL}/include/SDL' bf_sdl_libpath = '${BF_SDL}/lib' bf_sdl_lib = 'SDL' with_bf_openexr = True with_bf_staticopenexr = False bf_openexr = '/usr/local' bf_openexr_inc = ['${BF_OPENEXR}/include', '${BF_OPENEXR}/include/OpenEXR'] bf_openexr_libpath = '${BF_OPENEXR}/lib' bf_openexr_lib = 'Half IlmImf Iex Imath ' bf_openexr_lib_static = '${BF_OPENEXR}/lib/libHalf.a ${BF_OPENEXR}/lib/libIlmImf.a ${BF_OPENEXR}/lib/libIex.a ${BF_OPENEXR}/lib/libImath.a ${BF_OPENEXR}/lib/libIlmThread.a' with_bf_dds = True with_bf_jpeg = True bf_jpeg = '/usr/local' bf_jpeg_inc = '${BF_JPEG}/include' bf_jpeg_libpath = '${BF_JPEG}/lib' bf_jpeg_lib = 'jpeg' with_bf_png = True bf_png = '/usr/local' bf_png_inc = '${BF_PNG}/include' bf_png_libpath = '${BF_PNG}/lib' bf_png_lib = 'png' bf_tiff = '/usr/local' bf_tiff_inc = '${BF_TIFF}/include' with_bf_zlib = True bf_zlib = '/usr' bf_zlib_inc = '${BF_ZLIB}/include' bf_zlib_libpath = '${BF_ZLIB}/lib' bf_zlib_lib = 'z' with_bf_international = True bf_gettext = '/usr/local' bf_gettext_inc = '${BF_GETTEXT}/include' bf_gettext_lib = 'gettextlib' bf_gettext_libpath = '${BF_GETTEXT}/lib' with_bf_gameengine = False with_bf_player = False with_bf_bullet = True bf_bullet = '#extern/bullet2/src' bf_bullet_inc = '${BF_BULLET}' bf_bullet_lib = 'extern_bullet' bf_freetype = '/usr/local' bf_freetype_inc = '${BF_FREETYPE}/include ${BF_FREETYPE}/include/freetype2' bf_freetype_libpath = '${BF_FREETYPE}/lib' bf_freetype_lib = 'freetype' with_bf_quicktime = False bf_quicktime = '/usr/local' bf_quicktime_inc = '${BF_QUICKTIME}/include' with_bf_iconv = True bf_iconv = '/usr' bf_iconv_inc = '${BF_ICONV}/include' bf_iconv_lib = 'iconv' bf_iconv_libpath = '${BF_ICONV}/lib' with_bf_ffmpeg = True bf_ffmpeg = '/usr/local' bf_ffmpeg_inc = '${BF_FFMPEG}/include' bf_ffmpeg_libpath = '${BF_FFMPEG}/lib' bf_ffmpeg_lib = 'avformat avcodec avutil avdevice' with_bf_staticopengl = False bf_opengl = '/usr/openwin' bf_opengl_inc = '${BF_OPENGL}/include' bf_opengl_lib = 'GL GLU X11 Xi' bf_opengl_libpath = '${BF_OPENGL}/lib' bf_opengl_lib_static = '${BF_OPENGL_LIBPATH}/libGL.a ${BF_OPENGL_LIBPATH}/libGLU.a ${BF_OPENGL_LIBPATH}/libXxf86vm.a ${BF_OPENGL_LIBPATH}/libX11.a ${BF_OPENGL_LIBPATH}/libXi.a ${BF_OPENGL_LIBPATH}/libXext.a ${BF_OPENGL_LIBPATH}/libXxf86vm.a' cc = 'gcc' cxx = 'g++' ccflags = ['-pipe', '-fPIC', '-funsigned-char', '-fno-strict-aliasing'] cppflags = ['-DSUN_OGL_NO_VERTEX_MACROS'] cxxflags = ['-pipe', '-fPIC', '-funsigned-char', '-fno-strict-aliasing'] rel_cflags = ['-DNDEBUG', '-O2'] rel_ccflags = ['-DNDEBUG', '-O2'] c_warn = ['-Wno-char-subscripts', '-Wdeclaration-after-statement'] cc_warn = ['-Wall'] llibs = ['c', 'm', 'dl', 'pthread', 'stdc++'] bf_profile_ccflags = ['-pg', '-g '] bf_profile_linkflags = ['-pg'] bf_profile = False bf_debug = False bf_debug_ccflags = ['-D_DEBUG'] bf_builddir = '../build/sunos5' bf_installdir = '../install/sunos5' platform_linkflags = []
""" Connected client statistics """ class Statistics(object): """ A connected client statistics """ def __init__(self, downspeed, online, upspeed): self._downspeed = downspeed self._online = online self._upspeed = upspeed def get_downspeed(self): return self._downspeed def get_online(self): return self._online def get_upspeed(self): return self._upspeed def create_statistic_from_json(json_entry): # json_entry = json.loads(json_entry_as_string) return Statistics(json_entry['downspeed'], json_entry['online'], json_entry['upspeed'])
""" Connected client statistics """ class Statistics(object): """ A connected client statistics """ def __init__(self, downspeed, online, upspeed): self._downspeed = downspeed self._online = online self._upspeed = upspeed def get_downspeed(self): return self._downspeed def get_online(self): return self._online def get_upspeed(self): return self._upspeed def create_statistic_from_json(json_entry): return statistics(json_entry['downspeed'], json_entry['online'], json_entry['upspeed'])
t=input() while(t>0): s=raw_input() str=s.split(' ') b=int(str[0]) c=int(str[1]) d=int(str[2]) print (c-b)+(c-d) t=t-1
t = input() while t > 0: s = raw_input() str = s.split(' ') b = int(str[0]) c = int(str[1]) d = int(str[2]) print(c - b) + (c - d) t = t - 1
def generate_shared_public_key(my_private_key, their_public_pair, generator): """ Two parties each generate a private key and share their public key with the other party over an insecure channel. The shared public key can be generated by either side, but not by eavesdroppers. You can then use the entropy from the shared public key to created a common symmetric key for encryption. (This is beyond of the scope of pycoin.) See also <https://en.wikipedia.org/wiki/Key_exchange> :param my_private_key: an integer private key :param their_public_pair: a pair ``(x, y)`` representing a public key for the ``generator`` :param generator: a :class:`Generator <pycoin.ecdsa.Generator.Generator>` :returns: a :class:`Point <pycoin.ecdsa.Point.Point>`, which can be used as a shared public key. """ p = generator.Point(*their_public_pair) return my_private_key * p
def generate_shared_public_key(my_private_key, their_public_pair, generator): """ Two parties each generate a private key and share their public key with the other party over an insecure channel. The shared public key can be generated by either side, but not by eavesdroppers. You can then use the entropy from the shared public key to created a common symmetric key for encryption. (This is beyond of the scope of pycoin.) See also <https://en.wikipedia.org/wiki/Key_exchange> :param my_private_key: an integer private key :param their_public_pair: a pair ``(x, y)`` representing a public key for the ``generator`` :param generator: a :class:`Generator <pycoin.ecdsa.Generator.Generator>` :returns: a :class:`Point <pycoin.ecdsa.Point.Point>`, which can be used as a shared public key. """ p = generator.Point(*their_public_pair) return my_private_key * p
__version__ = "0.1" __requires__ = [ "apptools>=4.2.0", "numpy>=1.6", "traits>=4.4", "enable>4.2", "chaco>=4.4", "fiona>=1.0.2", "scimath>=4.1.2", "shapely>=1.2.17", "tables>=2.4.0", "sdi", ]
__version__ = '0.1' __requires__ = ['apptools>=4.2.0', 'numpy>=1.6', 'traits>=4.4', 'enable>4.2', 'chaco>=4.4', 'fiona>=1.0.2', 'scimath>=4.1.2', 'shapely>=1.2.17', 'tables>=2.4.0', 'sdi']
# A plugin is supposed to define a setup function # which returns the type that the plugin provides # # This plugin fails to do so def useless(): print("Hello World")
def useless(): print('Hello World')
""" This module is deprecated and has been moved to `//toolchains/built_tools/...` """ load("//foreign_cc/built_tools:ninja_build.bzl", _ninja_tool = "ninja_tool") load(":deprecation.bzl", "print_deprecation") print_deprecation() ninja_tool = _ninja_tool
""" This module is deprecated and has been moved to `//toolchains/built_tools/...` """ load('//foreign_cc/built_tools:ninja_build.bzl', _ninja_tool='ninja_tool') load(':deprecation.bzl', 'print_deprecation') print_deprecation() ninja_tool = _ninja_tool
class Number: def numSum(num): count = [] for x in range(1, (num+1)): count.append(x) print(sum(count)) if __name__ == "__main__": num = int(input("Enter A Number: ")) numSum(num)
class Number: def num_sum(num): count = [] for x in range(1, num + 1): count.append(x) print(sum(count)) if __name__ == '__main__': num = int(input('Enter A Number: ')) num_sum(num)
logging.info(" *** Step 3: Build features *** ".format()) # %% =========================================================================== # Feature - Pure Breed Boolean column # ============================================================================= def pure_breed(row): # print(row) mixed_breed_keywords = ['domestic', 'tabby', 'mixed'] # Mixed if labelled as such if row['Breed1'] == 'Mixed Breed': return False # Possible pure if no second breed elif row['Breed2'] == 'NA': # Reject domestic keywords if any([word in row['Breed1'].lower() for word in mixed_breed_keywords]): return False else: return True else: return False #%% Build the pipeline this_pipeline = sk.pipeline.Pipeline([ ('feat: Pure Breed', trf.MultipleToNewFeature(['Breed1','Breed2'], 'Pure Breed', pure_breed)), ]) logging.info("Created pipeline:") for i, step in enumerate(this_pipeline.steps): print(i, step[0], step[1].__str__()) #%% Fit Transform original_cols = df_all.columns df_all = this_pipeline.fit_transform(df_all) logging.info("Pipeline complete. {} new columns.".format(len(df_all.columns) - len(original_cols)))
logging.info(' *** Step 3: Build features *** '.format()) def pure_breed(row): mixed_breed_keywords = ['domestic', 'tabby', 'mixed'] if row['Breed1'] == 'Mixed Breed': return False elif row['Breed2'] == 'NA': if any([word in row['Breed1'].lower() for word in mixed_breed_keywords]): return False else: return True else: return False this_pipeline = sk.pipeline.Pipeline([('feat: Pure Breed', trf.MultipleToNewFeature(['Breed1', 'Breed2'], 'Pure Breed', pure_breed))]) logging.info('Created pipeline:') for (i, step) in enumerate(this_pipeline.steps): print(i, step[0], step[1].__str__()) original_cols = df_all.columns df_all = this_pipeline.fit_transform(df_all) logging.info('Pipeline complete. {} new columns.'.format(len(df_all.columns) - len(original_cols)))
aws_access_key_id=None aws_secret_access_key=None img_bucket_name=None
aws_access_key_id = None aws_secret_access_key = None img_bucket_name = None
# -*- coding: utf-8 -*- """Deep Go Patterns ====== Design Patterns """
"""Deep Go Patterns ====== Design Patterns """
def get_tickets(path): with open(path, 'r') as fh: yield fh.read().splitlines() def get_new_range(_min, _max, value): # print(_min, _max, value) if value == 'F' or value == 'L': mid = _min + (_max - _min) // 2 return (_min, mid) if value == 'B' or value == 'R': mid = _min + (_max - _min) // 2 + 1 return (mid, _max) print("something is wrong") def get_id(ticket): # print(ticket) range_min = 0 range_max = 127 tpl = (0, 127) for item in ticket[0:7]: tpl = get_new_range(range_min, range_max, item) range_min, range_max = tpl row = tpl[0] range_min = 0 range_max = 7 tpl = (0, 7) for item in ticket[-3:]: tpl = get_new_range(range_min, range_max, item) range_min, range_max = tpl column = tpl[0] return row * 8 + column _file = 'resources/day5_input.txt' _id = 0 ids = [] for tickets in get_tickets(_file): for ticket in tickets: ticket_id = get_id(ticket) ids.append(ticket_id) if ticket_id > _id: _id = ticket_id print("Day 5 - part I:", _id) # print(ids) for i in range(_id): if i not in ids and i-1 in ids and i+1 in ids: print("Day 5 - part II:", i)
def get_tickets(path): with open(path, 'r') as fh: yield fh.read().splitlines() def get_new_range(_min, _max, value): if value == 'F' or value == 'L': mid = _min + (_max - _min) // 2 return (_min, mid) if value == 'B' or value == 'R': mid = _min + (_max - _min) // 2 + 1 return (mid, _max) print('something is wrong') def get_id(ticket): range_min = 0 range_max = 127 tpl = (0, 127) for item in ticket[0:7]: tpl = get_new_range(range_min, range_max, item) (range_min, range_max) = tpl row = tpl[0] range_min = 0 range_max = 7 tpl = (0, 7) for item in ticket[-3:]: tpl = get_new_range(range_min, range_max, item) (range_min, range_max) = tpl column = tpl[0] return row * 8 + column _file = 'resources/day5_input.txt' _id = 0 ids = [] for tickets in get_tickets(_file): for ticket in tickets: ticket_id = get_id(ticket) ids.append(ticket_id) if ticket_id > _id: _id = ticket_id print('Day 5 - part I:', _id) for i in range(_id): if i not in ids and i - 1 in ids and (i + 1 in ids): print('Day 5 - part II:', i)