content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# Current version of the bcftbx package __version__ = '1.11.1' def get_version(): """Returns a string with the current version of the bcftbx package (e.g., "0.2.0") """ return __version__
__version__ = '1.11.1' def get_version(): """Returns a string with the current version of the bcftbx package (e.g., "0.2.0") """ return __version__
person='abc' video_source_number=0 thresholds=[.9,.85,.85,.85,.85,.95,.9] extra_thresholds=[.85,.85,.85,.85] #select the image widow and press w,s,a,d keys while running the script and looking in appropriate direction to change threshold tsrf=True #if true only image of eye will be processed may increase accuracy mode=False print_frame_rate=False print_additive_average_frame_rate=False cursor_speed=3 auto_correct_threshold=False auto_correct_left_pixel_limit=.5 auto_correct_right_pixel_limit=.5 auto_correct_up_pixel_limit=.5 auto_correct_down_pixel_limit=.5 delay_after_dclick_or_enable=.1 threshold_correction_rate=.01 auto_threshold_correct_rate=.01 brightness_correction=False #brightness_correction doesnt work well show_left_eye=True show_left_eyebrow=True landmarks=[['bros',17,21,19,'1122'],['eye',36,39,37,40],['eye',36,39,37,40],['eye',36,39,37,40],['eye',36,39,37,40],['eye',36,39,37,40],['eye',42,45,43,46]] data=['bros','up','down','left','right','dclick','r_close'] color=[[0,0,0],[0,50,100],[100,50,0],[100,150,200],[200,150,100],[200,0,0],[0,0,0]] extra_colors=[[0,50,100],[100,50,0],[100,150,200],[200,150,100]] correct=['e','u','d','l','r','c','m'] steps=['raise your left eyebrow','look up','look down','look left','look right','close left eye','close right eye'] if tsrf==False and brightness_correction==True: brightness_correction=False print("brightness correction can't work with tsrf disabled as it takes cropped image from tensorflow and makes its average brightness equal to data") print("turning off brightness correction") if tsrf==False and mode==True: mode==False;print('2 modes only when tsrf enabled')
person = 'abc' video_source_number = 0 thresholds = [0.9, 0.85, 0.85, 0.85, 0.85, 0.95, 0.9] extra_thresholds = [0.85, 0.85, 0.85, 0.85] tsrf = True mode = False print_frame_rate = False print_additive_average_frame_rate = False cursor_speed = 3 auto_correct_threshold = False auto_correct_left_pixel_limit = 0.5 auto_correct_right_pixel_limit = 0.5 auto_correct_up_pixel_limit = 0.5 auto_correct_down_pixel_limit = 0.5 delay_after_dclick_or_enable = 0.1 threshold_correction_rate = 0.01 auto_threshold_correct_rate = 0.01 brightness_correction = False show_left_eye = True show_left_eyebrow = True landmarks = [['bros', 17, 21, 19, '1122'], ['eye', 36, 39, 37, 40], ['eye', 36, 39, 37, 40], ['eye', 36, 39, 37, 40], ['eye', 36, 39, 37, 40], ['eye', 36, 39, 37, 40], ['eye', 42, 45, 43, 46]] data = ['bros', 'up', 'down', 'left', 'right', 'dclick', 'r_close'] color = [[0, 0, 0], [0, 50, 100], [100, 50, 0], [100, 150, 200], [200, 150, 100], [200, 0, 0], [0, 0, 0]] extra_colors = [[0, 50, 100], [100, 50, 0], [100, 150, 200], [200, 150, 100]] correct = ['e', 'u', 'd', 'l', 'r', 'c', 'm'] steps = ['raise your left eyebrow', 'look up', 'look down', 'look left', 'look right', 'close left eye', 'close right eye'] if tsrf == False and brightness_correction == True: brightness_correction = False print("brightness correction can't work with tsrf disabled as it takes cropped image from tensorflow and makes its average brightness equal to data") print('turning off brightness correction') if tsrf == False and mode == True: mode == False print('2 modes only when tsrf enabled')
# # PySNMP MIB module RBTWS-RF-DETECT-TC (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RBTWS-RF-DETECT-TC # Produced by pysmi-0.3.4 at Mon Apr 29 20:45:14 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) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint") rbtwsMibs, = mibBuilder.importSymbols("RBTWS-ROOT-MIB", "rbtwsMibs") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") IpAddress, Gauge32, TimeTicks, MibIdentifier, Bits, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Counter64, Integer32, Unsigned32, iso, ModuleIdentity, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Gauge32", "TimeTicks", "MibIdentifier", "Bits", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Counter64", "Integer32", "Unsigned32", "iso", "ModuleIdentity", "NotificationType") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") rbtwsRFDetectTc = ModuleIdentity((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 4, 11)) rbtwsRFDetectTc.setRevisions(('2007-04-18 00:02', '2007-03-28 00:01',)) if mibBuilder.loadTexts: rbtwsRFDetectTc.setLastUpdated('200704191855Z') if mibBuilder.loadTexts: rbtwsRFDetectTc.setOrganization('Enterasys Networks') class RbtwsRFDetectClassificationReason(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)) namedValues = NamedValues(("other", 1), ("default-classification", 2), ("rogue-list", 3), ("ap-in-modo", 4), ("neighbor-list", 5), ("ssid-masquerade", 6), ("seen-in-network", 7), ("ad-hoc", 8), ("ssid-list", 9), ("pass-fingerprint", 10), ("fail-fingerprint", 11)) class RbtwsRFDetectClassification(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6)) namedValues = NamedValues(("other", 1), ("not-classified", 2), ("member", 3), ("neighbor", 4), ("suspect", 5), ("rogue", 6)) class RbtwsRFDetectNetworkingMode(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("ad-hoc", 1), ("infrastructure", 2)) mibBuilder.exportSymbols("RBTWS-RF-DETECT-TC", RbtwsRFDetectClassification=RbtwsRFDetectClassification, rbtwsRFDetectTc=rbtwsRFDetectTc, PYSNMP_MODULE_ID=rbtwsRFDetectTc, RbtwsRFDetectNetworkingMode=RbtwsRFDetectNetworkingMode, RbtwsRFDetectClassificationReason=RbtwsRFDetectClassificationReason)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, value_range_constraint, constraints_union, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint') (rbtws_mibs,) = mibBuilder.importSymbols('RBTWS-ROOT-MIB', 'rbtwsMibs') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (ip_address, gauge32, time_ticks, mib_identifier, bits, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, counter64, integer32, unsigned32, iso, module_identity, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Gauge32', 'TimeTicks', 'MibIdentifier', 'Bits', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'Counter64', 'Integer32', 'Unsigned32', 'iso', 'ModuleIdentity', 'NotificationType') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') rbtws_rf_detect_tc = module_identity((1, 3, 6, 1, 4, 1, 52, 4, 15, 1, 4, 11)) rbtwsRFDetectTc.setRevisions(('2007-04-18 00:02', '2007-03-28 00:01')) if mibBuilder.loadTexts: rbtwsRFDetectTc.setLastUpdated('200704191855Z') if mibBuilder.loadTexts: rbtwsRFDetectTc.setOrganization('Enterasys Networks') class Rbtwsrfdetectclassificationreason(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)) named_values = named_values(('other', 1), ('default-classification', 2), ('rogue-list', 3), ('ap-in-modo', 4), ('neighbor-list', 5), ('ssid-masquerade', 6), ('seen-in-network', 7), ('ad-hoc', 8), ('ssid-list', 9), ('pass-fingerprint', 10), ('fail-fingerprint', 11)) class Rbtwsrfdetectclassification(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6)) named_values = named_values(('other', 1), ('not-classified', 2), ('member', 3), ('neighbor', 4), ('suspect', 5), ('rogue', 6)) class Rbtwsrfdetectnetworkingmode(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('ad-hoc', 1), ('infrastructure', 2)) mibBuilder.exportSymbols('RBTWS-RF-DETECT-TC', RbtwsRFDetectClassification=RbtwsRFDetectClassification, rbtwsRFDetectTc=rbtwsRFDetectTc, PYSNMP_MODULE_ID=rbtwsRFDetectTc, RbtwsRFDetectNetworkingMode=RbtwsRFDetectNetworkingMode, RbtwsRFDetectClassificationReason=RbtwsRFDetectClassificationReason)
# Collaborators (including web sites where you got help: (enter none if you didn't need help) # none # A note on style: Dictionaries can be defined before or after functions. board = {'1': ' ' , '2': ' ' , '3': ' ' ,'4': ' ' , '5': ' ' , '6': ' ' ,'7': ' ' , '8': ' ' , '9': ' ' } def gameboard(board): print(board['1'] + '|' + board['2'] + '|' + board['3']) print('-+-+-') print(board['4'] + '|' + board['5'] + '|' + board['6']) print('-+-+-') print(board['7'] + '|' + board['8'] + '|' + board['9']) def main(): num = 0 global player player = 'X' for i in range(10): gameboard(board) print("It is player " + player + "'s turn. " + player + ", what do you want to move? Use the keys: 1, 2, 3, 4, 5, 6, 7, 8, 9 to pick a spot on the board: ") move = input() if board[move] == ' ': board[move] = player num += 1 else: print("That spot is already filled. pick another move") continue if num >= 1: if board['1'] == board['2'] == board['3'] != ' ': gameboard(board) print(player + " won.") break elif board['4'] == board['5'] == board['6'] != ' ': gameboard(board) print(player + " won.") break elif board['7'] == board['8'] == board['9'] != ' ': gameboard(board) print(player + " won.") break elif board['1'] == board['4'] == board['7'] != ' ': gameboard(board) print(player + " won.") break elif board['2'] == board['5'] == board['8'] != ' ': gameboard(board) print(player + " won.") break elif board['3'] == board['6'] == board['9'] != ' ': gameboard(board) print(player + " won.") break elif board['1'] == board['5'] == board['9'] != ' ': gameboard(board) print(player + " won.") break elif board['3'] == board['5'] == board['7'] != ' ': gameboard(board) print(player + " won.") break if player =='X': player = 'O' else: player = 'X' if num == 9: gameboard(board) print("It's a Tie!!") break try: main() except: print("bad input") if player == 'X': player = 'X' else: player = 'O' main()
board = {'1': ' ', '2': ' ', '3': ' ', '4': ' ', '5': ' ', '6': ' ', '7': ' ', '8': ' ', '9': ' '} def gameboard(board): print(board['1'] + '|' + board['2'] + '|' + board['3']) print('-+-+-') print(board['4'] + '|' + board['5'] + '|' + board['6']) print('-+-+-') print(board['7'] + '|' + board['8'] + '|' + board['9']) def main(): num = 0 global player player = 'X' for i in range(10): gameboard(board) print('It is player ' + player + "'s turn. " + player + ', what do you want to move? Use the keys: 1, 2, 3, 4, 5, 6, 7, 8, 9 to pick a spot on the board: ') move = input() if board[move] == ' ': board[move] = player num += 1 else: print('That spot is already filled. pick another move') continue if num >= 1: if board['1'] == board['2'] == board['3'] != ' ': gameboard(board) print(player + ' won.') break elif board['4'] == board['5'] == board['6'] != ' ': gameboard(board) print(player + ' won.') break elif board['7'] == board['8'] == board['9'] != ' ': gameboard(board) print(player + ' won.') break elif board['1'] == board['4'] == board['7'] != ' ': gameboard(board) print(player + ' won.') break elif board['2'] == board['5'] == board['8'] != ' ': gameboard(board) print(player + ' won.') break elif board['3'] == board['6'] == board['9'] != ' ': gameboard(board) print(player + ' won.') break elif board['1'] == board['5'] == board['9'] != ' ': gameboard(board) print(player + ' won.') break elif board['3'] == board['5'] == board['7'] != ' ': gameboard(board) print(player + ' won.') break if player == 'X': player = 'O' else: player = 'X' if num == 9: gameboard(board) print("It's a Tie!!") break try: main() except: print('bad input') if player == 'X': player = 'X' else: player = 'O' main()
{ "cells": [ { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Financial Analysis\n", "Total Months:86\n", "Total Amount:38382578\n", "-2315.1176470588234\n", "Feb-2012 1926159\n", "Sep-2013 -2196167\n" ] } ], "source": [ "#import file\n", "import os\n", "import csv\n", "\n", "#declare the csv path\n", "csvpath = os.path.join('Resources','budget_data.csv')\n", "\n", "#declare the variables \n", "total_months = 0\n", "total_revenue =0\n", "changes =[]\n", "date_count = []\n", "greatest_increase = 0\n", "greatest_increase_month = 0\n", "greatest_decrease = 0\n", "greatest_decrease_month = 0\n", "\n", "# Open the csv\n", "with open(csvpath, newline = '') as csvfile:\n", " csvreader = csv.reader(csvfile, delimiter = ',')\n", " next(csvreader, None)\n", " row = next(csvreader)\n", " \n", " # calculate the total number of months and total revenue\n", " previous_profit = int(row[1])\n", " total_months = total_months + 1\n", " total_revenue = total_revenue + int(row[1])\n", " greatest_increase = int(row[1])\n", " greatest_increase_month = row[0]\n", "\n", " for row in csvreader:\n", " \n", " total_months = total_months + 1\n", " total_revenue = total_revenue + int(row[1])\n", "\n", " # calculate change from month-to-month\n", " change = int(row[1]) - previous_profit\n", " changes.append(change)\n", " previous_profit = int(row[1])\n", " date_count.append(row[0])\n", " \n", " #calculate the greatest increase\n", " if int(row[1]) > greatest_increase:\n", " greatest_increase = int(row[1])\n", " greatest_increase_month = row[0]\n", " \n", " #calculate the greatest decrease\n", " if int(row[1]) < greatest_decrease:\n", " greatest_decrease = int(row[1])\n", " greatest_decrease_month = row[0] \n", " \n", " # calculate the average and date\n", " average_change = sum(changes)/len(changes)\n", "\n", " high = max(changes)\n", " low = min(changes)\n", "\n", " # print values\n", " print(\"Financial Analysis\")\n", " print(\"Total Months:\" + str(total_months))\n", " print(\"Total Amount:\" + str(total_revenue))\n", " print(average_change)\n", " print(greatest_increase_month, max(changes))\n", " print(greatest_decrease_month, min(changes))\n", "\n", "\n", " # write output files\n", " PyBank = open(\"output.txt\",\"w+\")\n", " PyBank.write(\"Financial Analysis\") \n", " PyBank.write('\\n' +\"Total Months\" + str(total_months)) \n", " PyBank.write('\\n' +\"Total Amount\" + str(total_revenue)) \n", " PyBank.write('\\n' +\"Average\" + str(average_change)) \n", " PyBank.write('\\n' +greatest_increase_month) \n", " PyBank.write('\\n' +str(high))\n", " PyBank.write('\\n' +greatest_decrease_month) \n", " PyBank.write('\\n' +str(low)) " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3.9.1 64-bit ('3.9')", "language": "python", "name": "python391jvsc74a57bd07812ea015bdcee6f23a998adcdd2ef97c151c0c241b7b7070987d9313e41299d" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.1" }, "metadata": { "interpreter": { "hash": "7812ea015bdcee6f23a998adcdd2ef97c151c0c241b7b7070987d9313e41299d" } } }, "nbformat": 4, "nbformat_minor": 4 }
{'cells': [{'cell_type': 'code', 'execution_count': 4, 'metadata': {}, 'outputs': [{'name': 'stdout', 'output_type': 'stream', 'text': ['Financial Analysis\n', 'Total Months:86\n', 'Total Amount:38382578\n', '-2315.1176470588234\n', 'Feb-2012 1926159\n', 'Sep-2013 -2196167\n']}], 'source': ['#import file\n', 'import os\n', 'import csv\n', '\n', '#declare the csv path\n', "csvpath = os.path.join('Resources','budget_data.csv')\n", '\n', '#declare the variables \n', 'total_months = 0\n', 'total_revenue =0\n', 'changes =[]\n', 'date_count = []\n', 'greatest_increase = 0\n', 'greatest_increase_month = 0\n', 'greatest_decrease = 0\n', 'greatest_decrease_month = 0\n', '\n', '# Open the csv\n', "with open(csvpath, newline = '') as csvfile:\n", " csvreader = csv.reader(csvfile, delimiter = ',')\n", ' next(csvreader, None)\n', ' row = next(csvreader)\n', ' \n', ' # calculate the total number of months and total revenue\n', ' previous_profit = int(row[1])\n', ' total_months = total_months + 1\n', ' total_revenue = total_revenue + int(row[1])\n', ' greatest_increase = int(row[1])\n', ' greatest_increase_month = row[0]\n', '\n', ' for row in csvreader:\n', ' \n', ' total_months = total_months + 1\n', ' total_revenue = total_revenue + int(row[1])\n', '\n', ' # calculate change from month-to-month\n', ' change = int(row[1]) - previous_profit\n', ' changes.append(change)\n', ' previous_profit = int(row[1])\n', ' date_count.append(row[0])\n', ' \n', ' #calculate the greatest increase\n', ' if int(row[1]) > greatest_increase:\n', ' greatest_increase = int(row[1])\n', ' greatest_increase_month = row[0]\n', ' \n', ' #calculate the greatest decrease\n', ' if int(row[1]) < greatest_decrease:\n', ' greatest_decrease = int(row[1])\n', ' greatest_decrease_month = row[0] \n', ' \n', ' # calculate the average and date\n', ' average_change = sum(changes)/len(changes)\n', '\n', ' high = max(changes)\n', ' low = min(changes)\n', '\n', ' # print values\n', ' print("Financial Analysis")\n', ' print("Total Months:" + str(total_months))\n', ' print("Total Amount:" + str(total_revenue))\n', ' print(average_change)\n', ' print(greatest_increase_month, max(changes))\n', ' print(greatest_decrease_month, min(changes))\n', '\n', '\n', ' # write output files\n', ' PyBank = open("output.txt","w+")\n', ' PyBank.write("Financial Analysis") \n', ' PyBank.write(\'\\n\' +"Total Months" + str(total_months)) \n', ' PyBank.write(\'\\n\' +"Total Amount" + str(total_revenue)) \n', ' PyBank.write(\'\\n\' +"Average" + str(average_change)) \n', " PyBank.write('\\n' +greatest_increase_month) \n", " PyBank.write('\\n' +str(high))\n", " PyBank.write('\\n' +greatest_decrease_month) \n", " PyBank.write('\\n' +str(low)) "]}, {'cell_type': 'code', 'execution_count': null, 'metadata': {}, 'outputs': [], 'source': []}], 'metadata': {'kernelspec': {'display_name': "Python 3.9.1 64-bit ('3.9')", 'language': 'python', 'name': 'python391jvsc74a57bd07812ea015bdcee6f23a998adcdd2ef97c151c0c241b7b7070987d9313e41299d'}, 'language_info': {'codemirror_mode': {'name': 'ipython', 'version': 3}, 'file_extension': '.py', 'mimetype': 'text/x-python', 'name': 'python', 'nbconvert_exporter': 'python', 'pygments_lexer': 'ipython3', 'version': '3.9.1'}, 'metadata': {'interpreter': {'hash': '7812ea015bdcee6f23a998adcdd2ef97c151c0c241b7b7070987d9313e41299d'}}}, 'nbformat': 4, 'nbformat_minor': 4}
# Puzzle Input with open('Day13_Input.txt') as puzzle_input: bus_info = puzzle_input.read().split('\n') # Get the departure time and the IDs departure = int(bus_info[0]) bus_id = bus_info[1].split(',') # Remove the x's while 'x' in bus_id: bus_id.remove('x') # Convert the IDs to integers bus_id = list(map(int, bus_id)) # Calculate the waiting times waiting_times = [] for ID in bus_id: # The negative part is the time the bus departs before we can leave waiting_times += [-(departure % ID) + ID] # the positive part changes it to after we left # See which bus gave us the minimum waiting time min_index = waiting_times.index(min(waiting_times)) # Show the result print(waiting_times[min_index] * bus_id[min_index])
with open('Day13_Input.txt') as puzzle_input: bus_info = puzzle_input.read().split('\n') departure = int(bus_info[0]) bus_id = bus_info[1].split(',') while 'x' in bus_id: bus_id.remove('x') bus_id = list(map(int, bus_id)) waiting_times = [] for id in bus_id: waiting_times += [-(departure % ID) + ID] min_index = waiting_times.index(min(waiting_times)) print(waiting_times[min_index] * bus_id[min_index])
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"PseudoData": "00_pseudodata.ipynb", "paper_sig": "00_pseudodata.ipynb", "paper_bkg": "00_pseudodata.ipynb", "ModelWrapper": "01_model_wrapper.ipynb", "DataSet": "02_data.ipynb", "WeightedDataLoader": "02_data.ipynb", "DataPair": "02_data.ipynb", "get_paper_data": "02_data.ipynb", "AbsCallback": "03_callback.ipynb", "LossTracker": "03_callback.ipynb", "EarlyStopping": "03_callback.ipynb", "SaveBest": "03_callback.ipynb", "PredHandler": "03_callback.ipynb", "PaperSystMod": "03_callback.ipynb", "GradClip": "03_callback.ipynb", "to_device": "04_utils.ipynb", "device": "04_utils.ipynb", "to_np": "04_utils.ipynb", "init_net": "04_utils.ipynb", "plt_style": "05_plotting.ipynb", "plt_sz": "05_plotting.ipynb", "plt_cat_pal": "05_plotting.ipynb", "plt_tk_sz": "05_plotting.ipynb", "plt_lbl_sz": "05_plotting.ipynb", "plt_title_sz": "05_plotting.ipynb", "plt_leg_sz": "05_plotting.ipynb", "plot_preds": "05_plotting.ipynb", "plot_likelihood": "05_plotting.ipynb", "bin_preds": "06_inference.ipynb", "get_shape": "06_inference.ipynb", "get_paper_syst_shapes": "06_inference.ipynb", "get_likelihood_width": "06_inference.ipynb", "interp_shape": "06_inference.ipynb", "calc_nll": "06_inference.ipynb", "jacobian": "06_inference.ipynb", "calc_grad_hesse": "06_inference.ipynb", "calc_profile": "06_inference.ipynb", "VariableSoftmax": "07_inferno_exact.ipynb", "AbsInferno": "07_inferno_exact.ipynb", "PaperInferno": "07_inferno_exact.ipynb", "InfernoPred": "07_inferno_exact.ipynb", "AbsApproxInferno": "08_inferno_interp.ipynb", "ApproxPaperInferno": "08_inferno_interp.ipynb"} modules = ["pseudodata.py", "model_wrapper.py", "data.py", "callback.py", "utils.py", "plotting.py", "inference.py", "inferno.py"] doc_url = "https://GilesStrong.github.io/pytorch_inferno/" git_url = "https://github.com/GilesStrong/pytorch_inferno/tree/master/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'PseudoData': '00_pseudodata.ipynb', 'paper_sig': '00_pseudodata.ipynb', 'paper_bkg': '00_pseudodata.ipynb', 'ModelWrapper': '01_model_wrapper.ipynb', 'DataSet': '02_data.ipynb', 'WeightedDataLoader': '02_data.ipynb', 'DataPair': '02_data.ipynb', 'get_paper_data': '02_data.ipynb', 'AbsCallback': '03_callback.ipynb', 'LossTracker': '03_callback.ipynb', 'EarlyStopping': '03_callback.ipynb', 'SaveBest': '03_callback.ipynb', 'PredHandler': '03_callback.ipynb', 'PaperSystMod': '03_callback.ipynb', 'GradClip': '03_callback.ipynb', 'to_device': '04_utils.ipynb', 'device': '04_utils.ipynb', 'to_np': '04_utils.ipynb', 'init_net': '04_utils.ipynb', 'plt_style': '05_plotting.ipynb', 'plt_sz': '05_plotting.ipynb', 'plt_cat_pal': '05_plotting.ipynb', 'plt_tk_sz': '05_plotting.ipynb', 'plt_lbl_sz': '05_plotting.ipynb', 'plt_title_sz': '05_plotting.ipynb', 'plt_leg_sz': '05_plotting.ipynb', 'plot_preds': '05_plotting.ipynb', 'plot_likelihood': '05_plotting.ipynb', 'bin_preds': '06_inference.ipynb', 'get_shape': '06_inference.ipynb', 'get_paper_syst_shapes': '06_inference.ipynb', 'get_likelihood_width': '06_inference.ipynb', 'interp_shape': '06_inference.ipynb', 'calc_nll': '06_inference.ipynb', 'jacobian': '06_inference.ipynb', 'calc_grad_hesse': '06_inference.ipynb', 'calc_profile': '06_inference.ipynb', 'VariableSoftmax': '07_inferno_exact.ipynb', 'AbsInferno': '07_inferno_exact.ipynb', 'PaperInferno': '07_inferno_exact.ipynb', 'InfernoPred': '07_inferno_exact.ipynb', 'AbsApproxInferno': '08_inferno_interp.ipynb', 'ApproxPaperInferno': '08_inferno_interp.ipynb'} modules = ['pseudodata.py', 'model_wrapper.py', 'data.py', 'callback.py', 'utils.py', 'plotting.py', 'inference.py', 'inferno.py'] doc_url = 'https://GilesStrong.github.io/pytorch_inferno/' git_url = 'https://github.com/GilesStrong/pytorch_inferno/tree/master/' def custom_doc_links(name): return None
def min(x, y): return x > y and x or y def gcd(x, y): res = -1 for i in range(1, min(x, y) + 1): if x % i == 0 and y % i == 0: if res < i: res = i return res N, M = map(int, input().split()) print(gcd(N, M)) print(gcd(N, M) * (N // gcd(N, M)) * (M // gcd(N, M)))
def min(x, y): return x > y and x or y def gcd(x, y): res = -1 for i in range(1, min(x, y) + 1): if x % i == 0 and y % i == 0: if res < i: res = i return res (n, m) = map(int, input().split()) print(gcd(N, M)) print(gcd(N, M) * (N // gcd(N, M)) * (M // gcd(N, M)))
# Python - 3.6.0 fruitList = { 1: 'kiwi', 2: 'pear', 3: 'kiwi', 4: 'banana', 5: 'melon', 6: 'banana', 7: 'melon', 8: 'pineapple', 9: 'apple', 10: 'pineapple', 11: 'cucumber', 12: 'pineapple', 13: 'cucumber', 14: 'orange', 15: 'grape', 16: 'orange', 17: 'grape', 18: 'apple', 19: 'grape', 20: 'cherry', 21: 'pear', 22: 'cherry', 23: 'pear', 24: 'kiwi', 25: 'banana', 26: 'kiwi', 27: 'apple', 28: 'melon', 29: 'banana', 30: 'melon', 31: 'pineapple', 32: 'melon', 33: 'pineapple', 34: 'cucumber', 35: 'orange', 36: 'apple', 37: 'orange', 38: 'grape', 39: 'orange', 40: 'grape', 41: 'cherry', 42: 'pear', 43: 'cherry', 44: 'pear', 45: 'apple', 46: 'pear', 47: 'kiwi', 48: 'banana', 49: 'kiwi', 50: 'banana', 51: 'melon', 52: 'pineapple', 53: 'melon', 54: 'apple', 55: 'cucumber', 56: 'pineapple', 57: 'cucumber', 58: 'orange', 59: 'cucumber', 60: 'orange', 61: 'grape', 62: 'cherry', 63: 'apple', 64: 'cherry', 65: 'pear', 66: 'cherry', 67: 'pear', 68: 'kiwi', 69: 'pear', 70: 'kiwi', 71: 'banana', 72: 'apple', 73: 'banana', 74: 'melon', 75: 'pineapple', 76: 'melon', 77: 'pineapple', 78: 'cucumber', 79: 'pineapple', 80: 'cucumber', 81: 'apple', 82: 'grape', 83: 'orange', 84: 'grape', 85: 'cherry', 86: 'grape', 87: 'cherry', 88: 'pear', 89: 'cherry', 90: 'apple', 91: 'kiwi', 92: 'banana', 93: 'kiwi', 94: 'banana', 95: 'melon', 96: 'banana', 97: 'melon', 98: 'pineapple', 99: 'apple', 100: 'pineapple' } def subtract_sum(number): while number > 0: number -= sum([int(i) for i in str(number)]) if number in fruitList: return fruitList[number] return ''
fruit_list = {1: 'kiwi', 2: 'pear', 3: 'kiwi', 4: 'banana', 5: 'melon', 6: 'banana', 7: 'melon', 8: 'pineapple', 9: 'apple', 10: 'pineapple', 11: 'cucumber', 12: 'pineapple', 13: 'cucumber', 14: 'orange', 15: 'grape', 16: 'orange', 17: 'grape', 18: 'apple', 19: 'grape', 20: 'cherry', 21: 'pear', 22: 'cherry', 23: 'pear', 24: 'kiwi', 25: 'banana', 26: 'kiwi', 27: 'apple', 28: 'melon', 29: 'banana', 30: 'melon', 31: 'pineapple', 32: 'melon', 33: 'pineapple', 34: 'cucumber', 35: 'orange', 36: 'apple', 37: 'orange', 38: 'grape', 39: 'orange', 40: 'grape', 41: 'cherry', 42: 'pear', 43: 'cherry', 44: 'pear', 45: 'apple', 46: 'pear', 47: 'kiwi', 48: 'banana', 49: 'kiwi', 50: 'banana', 51: 'melon', 52: 'pineapple', 53: 'melon', 54: 'apple', 55: 'cucumber', 56: 'pineapple', 57: 'cucumber', 58: 'orange', 59: 'cucumber', 60: 'orange', 61: 'grape', 62: 'cherry', 63: 'apple', 64: 'cherry', 65: 'pear', 66: 'cherry', 67: 'pear', 68: 'kiwi', 69: 'pear', 70: 'kiwi', 71: 'banana', 72: 'apple', 73: 'banana', 74: 'melon', 75: 'pineapple', 76: 'melon', 77: 'pineapple', 78: 'cucumber', 79: 'pineapple', 80: 'cucumber', 81: 'apple', 82: 'grape', 83: 'orange', 84: 'grape', 85: 'cherry', 86: 'grape', 87: 'cherry', 88: 'pear', 89: 'cherry', 90: 'apple', 91: 'kiwi', 92: 'banana', 93: 'kiwi', 94: 'banana', 95: 'melon', 96: 'banana', 97: 'melon', 98: 'pineapple', 99: 'apple', 100: 'pineapple'} def subtract_sum(number): while number > 0: number -= sum([int(i) for i in str(number)]) if number in fruitList: return fruitList[number] return ''
__all__ = [ 'base_controller', 'imaging', 'telephony', 'data_tools', 'security_and_networking', 'geolocation', 'e_commerce', 'www', ]
__all__ = ['base_controller', 'imaging', 'telephony', 'data_tools', 'security_and_networking', 'geolocation', 'e_commerce', 'www']
f = open('test16.txt', 'rt') rows = f.readlines() for row in rows: print(row) f.close() # while True: # row = f.readline() # print(row) # if not row: # break # f.close()
f = open('test16.txt', 'rt') rows = f.readlines() for row in rows: print(row) f.close()
flagArray = [0 for i in range(32)] flag = "" flagArray[0] = 'd' flagArray[29] = '9' flagArray[4] = 'r' flagArray[2] = '5' flagArray[23] = 'r' flagArray[3] = 'c' flagArray[17] = '4' flagArray[1] = '3' flagArray[7] = 'b' flagArray[10] = '_' flagArray[5] = '4' flagArray[9] = '3' flagArray[11] = 't' flagArray[15] = 'c' flagArray[8] = 'l' flagArray[12] = 'H' flagArray[20] = 'c' flagArray[14] = '_' flagArray[6] = 'm' flagArray[24] = '5' flagArray[18] = 'r' flagArray[13] = '3' flagArray[19] = '4' flagArray[21] = 'T' flagArray[16] = 'H' flagArray[27] = '5' flagArray[30] = '2' flagArray[25] = '_' flagArray[22] = '3' flagArray[28] = '0' flagArray[26] = '7' flagArray[31] = 'e' for i in range(0, len(flagArray)): flag = flag + str(flagArray[i]) print(flag)
flag_array = [0 for i in range(32)] flag = '' flagArray[0] = 'd' flagArray[29] = '9' flagArray[4] = 'r' flagArray[2] = '5' flagArray[23] = 'r' flagArray[3] = 'c' flagArray[17] = '4' flagArray[1] = '3' flagArray[7] = 'b' flagArray[10] = '_' flagArray[5] = '4' flagArray[9] = '3' flagArray[11] = 't' flagArray[15] = 'c' flagArray[8] = 'l' flagArray[12] = 'H' flagArray[20] = 'c' flagArray[14] = '_' flagArray[6] = 'm' flagArray[24] = '5' flagArray[18] = 'r' flagArray[13] = '3' flagArray[19] = '4' flagArray[21] = 'T' flagArray[16] = 'H' flagArray[27] = '5' flagArray[30] = '2' flagArray[25] = '_' flagArray[22] = '3' flagArray[28] = '0' flagArray[26] = '7' flagArray[31] = 'e' for i in range(0, len(flagArray)): flag = flag + str(flagArray[i]) print(flag)
print("Enter a selection from the below menu. Press '0' to exit.") menu_items = ["Bake a loaf of bread", "Bake a pound cake", "Prepare Roast Chicken", "Make Curry", \ "Put a rack of ribs in the smoker", "Buy dinner out", "Have ice cream", "Sandwiches - again"] select = None while True: for i in range(len(menu_items)): print(f"{i+1}:\t{menu_items[i]}") select = int(input("\nMake a selection: ")) if select == 0: print("Shutting down!\n") break if select > len(menu_items): print("I don't have that many options today!\n") continue select -= 1 print(f"\nYou selected: {menu_items[select]}\n")
print("Enter a selection from the below menu. Press '0' to exit.") menu_items = ['Bake a loaf of bread', 'Bake a pound cake', 'Prepare Roast Chicken', 'Make Curry', 'Put a rack of ribs in the smoker', 'Buy dinner out', 'Have ice cream', 'Sandwiches - again'] select = None while True: for i in range(len(menu_items)): print(f'{i + 1}:\t{menu_items[i]}') select = int(input('\nMake a selection: ')) if select == 0: print('Shutting down!\n') break if select > len(menu_items): print("I don't have that many options today!\n") continue select -= 1 print(f'\nYou selected: {menu_items[select]}\n')
""" Write a program to remove the item present at index 4 and add it to the 2nd position and at the end of the list. Given: list1 = [34, 54, 67, 89, 11, 43, 94] Expected Output: List After removing element at index 4 [34, 54, 67, 89, 43, 94] List after Adding element at index 2 [34, 54, 11, 67, 89, 43, 94] List after Adding element at last [34, 54, 11, 67, 89, 43, 94, 11] """ list1 = [34, 54, 67, 89, 11, 43, 94] element = list1[4] list1.pop(4) list1.insert(2, element) list1.append(element) print(list1)
""" Write a program to remove the item present at index 4 and add it to the 2nd position and at the end of the list. Given: list1 = [34, 54, 67, 89, 11, 43, 94] Expected Output: List After removing element at index 4 [34, 54, 67, 89, 43, 94] List after Adding element at index 2 [34, 54, 11, 67, 89, 43, 94] List after Adding element at last [34, 54, 11, 67, 89, 43, 94, 11] """ list1 = [34, 54, 67, 89, 11, 43, 94] element = list1[4] list1.pop(4) list1.insert(2, element) list1.append(element) print(list1)
def primes(n): out = list() sieve = [True] * (n+1) for p in range(2, n+1): if sieve[p]: out.append(p) for i in range(p, n+1, p): sieve[i] = False return out def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False r = int(n**0.5) f = 5 while f <= r: if n % f == 0 or n % (f + 2) == 0: return False f += 6 return True
def primes(n): out = list() sieve = [True] * (n + 1) for p in range(2, n + 1): if sieve[p]: out.append(p) for i in range(p, n + 1, p): sieve[i] = False return out def is_prime(n): if n <= 1: return False if n <= 3: return True if n % 2 == 0 or n % 3 == 0: return False r = int(n ** 0.5) f = 5 while f <= r: if n % f == 0 or n % (f + 2) == 0: return False f += 6 return True
class Solution: def maxArea(self, height: List[int]) -> int: area = 0 left_pivot = 0 right_pivot = len(height)-1 while left_pivot != right_pivot: current_area = abs(right_pivot-left_pivot) * min(height[left_pivot], height[right_pivot]) # update the area if current_area > area: area = current_area #update the pivots if height[left_pivot] < height[right_pivot]: left_pivot += 1 else: right_pivot -= 1 return area
class Solution: def max_area(self, height: List[int]) -> int: area = 0 left_pivot = 0 right_pivot = len(height) - 1 while left_pivot != right_pivot: current_area = abs(right_pivot - left_pivot) * min(height[left_pivot], height[right_pivot]) if current_area > area: area = current_area if height[left_pivot] < height[right_pivot]: left_pivot += 1 else: right_pivot -= 1 return area
print("------------------") print("------------------") print("------------------") print("------------------") print("------------------") num1 = 10 num2 = 20
print('------------------') print('------------------') print('------------------') print('------------------') print('------------------') num1 = 10 num2 = 20
#exceptions def spam(divided_by): try: return 42 / divided_by except: print('Invalid argument.') print(spam(2)) print(spam(0)) print(spam(1))
def spam(divided_by): try: return 42 / divided_by except: print('Invalid argument.') print(spam(2)) print(spam(0)) print(spam(1))
# Slackbot API Information slack_bot_token = "xoxb-2650828670406-2670419769553-qxTzP6Sbh9tlqfYIA52wh1bZ" bot_id = "xoxb-2650828670406-2670419769553-qxTzP6Sbh9tlqfYIA52wh1bZ" # AIML FIles directory = "/aiml" learn_file = "std-startup.xml" respond = "load aiml b"
slack_bot_token = 'xoxb-2650828670406-2670419769553-qxTzP6Sbh9tlqfYIA52wh1bZ' bot_id = 'xoxb-2650828670406-2670419769553-qxTzP6Sbh9tlqfYIA52wh1bZ' directory = '/aiml' learn_file = 'std-startup.xml' respond = 'load aiml b'
#-*- coding: UTF-8 -*- def log_info(msg): print ('bn info:'+msg); return; def log_error(msg): print ('bn error:'+msg); return; def log_debug(msg): print ('bn debug:'+msg); return;
def log_info(msg): print('bn info:' + msg) return def log_error(msg): print('bn error:' + msg) return def log_debug(msg): print('bn debug:' + msg) return
def fighter(): i01.moveHead(160,87) i01.moveArm("left",31,75,152,10) i01.moveArm("right",3,94,33,16) i01.moveHand("left",161,151,133,127,107,83) i01.moveHand("right",99,130,152,154,145,180) i01.moveTorso(90,90,90)
def fighter(): i01.moveHead(160, 87) i01.moveArm('left', 31, 75, 152, 10) i01.moveArm('right', 3, 94, 33, 16) i01.moveHand('left', 161, 151, 133, 127, 107, 83) i01.moveHand('right', 99, 130, 152, 154, 145, 180) i01.moveTorso(90, 90, 90)
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): if self is None: return "Nil" else: return "{} -> {}".format(self.val, repr(self.next)) class Solution: def oddEvenList(self, head): """ :type head: ListNode :rtype: ListNode Time: N Space: 1 """ if not head: return head slow, fast = head, head.next while fast and fast.next: even_head = slow.next slow.next = fast.next slow = slow.next fast.next = slow.next slow.next = even_head fast = fast.next return head if __name__ == "__main__": head = ListNode(1) head.next = ListNode(2) head.next.next = ListNode(3) head.next.next.next = ListNode(4) head.next.next.next.next = ListNode(5) print(Solution().oddEvenList(head))
class Listnode: def __init__(self, x): self.val = x self.next = None def __repr__(self): if self is None: return 'Nil' else: return '{} -> {}'.format(self.val, repr(self.next)) class Solution: def odd_even_list(self, head): """ :type head: ListNode :rtype: ListNode Time: N Space: 1 """ if not head: return head (slow, fast) = (head, head.next) while fast and fast.next: even_head = slow.next slow.next = fast.next slow = slow.next fast.next = slow.next slow.next = even_head fast = fast.next return head if __name__ == '__main__': head = list_node(1) head.next = list_node(2) head.next.next = list_node(3) head.next.next.next = list_node(4) head.next.next.next.next = list_node(5) print(solution().oddEvenList(head))
# -*- coding: utf-8 -*- __name__ = "bayrell-common" __version__ = "0.0.2" __description__ = "Bayrell Common Library" __license__ = "Apache License Version 2.0" __author__ = "Ildar Bikmamatov" __email__ = "support@bayrell.org" __copyright__ = "Copyright 2016-2018" __url__ = "https://github.com/bayrell/common_py3"
__name__ = 'bayrell-common' __version__ = '0.0.2' __description__ = 'Bayrell Common Library' __license__ = 'Apache License Version 2.0' __author__ = 'Ildar Bikmamatov' __email__ = 'support@bayrell.org' __copyright__ = 'Copyright 2016-2018' __url__ = 'https://github.com/bayrell/common_py3'
description = 'Verify the application shows the correct error message when creating a project without name' pages = ['common', 'index'] def setup(data): common.access_golem(data.env.url, data.env.admin) def test(data): click(index.create_project_button) click(index.create_button) index.verify_error_message('Project name is too short')
description = 'Verify the application shows the correct error message when creating a project without name' pages = ['common', 'index'] def setup(data): common.access_golem(data.env.url, data.env.admin) def test(data): click(index.create_project_button) click(index.create_button) index.verify_error_message('Project name is too short')
expected_output = { 'group':{ 1:{ 'state':'Ready', 'core_interfaces':{ 'Bundle-Ether2':{ 'state':'up' }, 'TenGigE0/1/0/6/1':{ 'state':'up' } }, 'access_interfaces':{ 'Bundle-Ether1':{ 'state':'up' } } } } }
expected_output = {'group': {1: {'state': 'Ready', 'core_interfaces': {'Bundle-Ether2': {'state': 'up'}, 'TenGigE0/1/0/6/1': {'state': 'up'}}, 'access_interfaces': {'Bundle-Ether1': {'state': 'up'}}}}}
""" Configuration for Captain's Log. """ # The log file. Use an absolute path to be safe. log_file = "/path/to/file"
""" Configuration for Captain's Log. """ log_file = '/path/to/file'
class Band: def __init__(self, musicians={}): self._musicians = musicians def add_musician(self, musician): if musician is None: raise ValueError("Missing required musician instance!") if musician.get_email() in self._musicians.keys(): raise ValueError("Email already exists!") self._musicians[musician.get_email()] = musician print(self) def add_instrument(self, musician_email, instrument): if musician_email not in self._musicians.keys(): raise ValueError("Musician does not exist!") self._musicians[musician_email].add_instrument(instrument) print(self) def remove_instrument(self, name, manufacturer, model, musician_email): if musician_email not in self._musicians.keys(): raise ValueError("Musician does not exist!") musician = self._musicians[musician_email] for inst in musician.get_instruments(): if inst.get_name() == name and inst.get_manufacturer() == manufacturer \ and inst.get_model() == model: musician.get_instruments().remove(inst) break print(self) def __str__(self): band = "The band's musicians & instruments:\n" for musician in self._musicians.values(): band += musician.__str__() band += "\n" return band @property def musicians(self): return self._musicians
class Band: def __init__(self, musicians={}): self._musicians = musicians def add_musician(self, musician): if musician is None: raise value_error('Missing required musician instance!') if musician.get_email() in self._musicians.keys(): raise value_error('Email already exists!') self._musicians[musician.get_email()] = musician print(self) def add_instrument(self, musician_email, instrument): if musician_email not in self._musicians.keys(): raise value_error('Musician does not exist!') self._musicians[musician_email].add_instrument(instrument) print(self) def remove_instrument(self, name, manufacturer, model, musician_email): if musician_email not in self._musicians.keys(): raise value_error('Musician does not exist!') musician = self._musicians[musician_email] for inst in musician.get_instruments(): if inst.get_name() == name and inst.get_manufacturer() == manufacturer and (inst.get_model() == model): musician.get_instruments().remove(inst) break print(self) def __str__(self): band = "The band's musicians & instruments:\n" for musician in self._musicians.values(): band += musician.__str__() band += '\n' return band @property def musicians(self): return self._musicians
""" A pig-latinzer """ def pig_latinize(word_list): """ Pig-latinizes a list of words. Args: word_list: The list of words to pig-latinize. Returns: A generator containing the pig-latinized words. """ for word in word_list: if word is None: continue if len(word.strip()) == 0: continue if word.lower()[0] in "aeiou": yield word + "ay" else: yield word[1:] + word[0] + "ay"
""" A pig-latinzer """ def pig_latinize(word_list): """ Pig-latinizes a list of words. Args: word_list: The list of words to pig-latinize. Returns: A generator containing the pig-latinized words. """ for word in word_list: if word is None: continue if len(word.strip()) == 0: continue if word.lower()[0] in 'aeiou': yield (word + 'ay') else: yield (word[1:] + word[0] + 'ay')
''' You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase. Given a non-empty string S and a number K, format the string according to the rules described above. Example 1: Input: S = "5F3Z-2e-9-w", K = 4 Output: "5F3Z-2E9W" Explanation: The string S has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. Example 2: Input: S = "2-5g-3-J", K = 2 Output: "2-5G-3J" Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. Note: The length of string S will not exceed 12,000, and K is a positive integer. String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-). String S is non-empty. ''' class Solution(object): def licenseKeyFormatting(self, S, K): """ :type S: str :type K: int :rtype: str """ S = S.replace('-','').upper() result = "" if len(S)%K == 0: for index in range(0, len(S), K): result += S[index:index+K] + "-" else: result = S[:len(S)%K] + "-" for index in range(len(S)%K, len(S), K): result += S[index:index+K] + "-" return result[:-1]
""" You are given a license key represented as a string S which consists only alphanumeric character and dashes. The string is separated into N+1 groups by N dashes. Given a number K, we would want to reformat the strings such that each group contains exactly K characters, except for the first group which could be shorter than K, but still must contain at least one character. Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase. Given a non-empty string S and a number K, format the string according to the rules described above. Example 1: Input: S = "5F3Z-2e-9-w", K = 4 Output: "5F3Z-2E9W" Explanation: The string S has been split into two parts, each part has 4 characters. Note that the two extra dashes are not needed and can be removed. Example 2: Input: S = "2-5g-3-J", K = 2 Output: "2-5G-3J" Explanation: The string S has been split into three parts, each part has 2 characters except the first part as it could be shorter as mentioned above. Note: The length of string S will not exceed 12,000, and K is a positive integer. String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-). String S is non-empty. """ class Solution(object): def license_key_formatting(self, S, K): """ :type S: str :type K: int :rtype: str """ s = S.replace('-', '').upper() result = '' if len(S) % K == 0: for index in range(0, len(S), K): result += S[index:index + K] + '-' else: result = S[:len(S) % K] + '-' for index in range(len(S) % K, len(S), K): result += S[index:index + K] + '-' return result[:-1]
class TestStackiPalletInfo: def test_no_pallet_name(self, run_ansible_module): result = run_ansible_module("stacki_pallet_info") assert result.status == "SUCCESS" assert result.data["changed"] is False def test_pallet_name(self, run_ansible_module): pallet_name = "stacki" result = run_ansible_module("stacki_pallet_info", name=pallet_name) assert result.status == "SUCCESS" assert result.data["changed"] is False assert len(result.data["pallets"]) == 1 assert result.data["pallets"][0]["name"] == pallet_name def test_invalid_pallet_name(self, run_ansible_module): pallet_name = "fake_pallet_name" result = run_ansible_module("stacki_pallet_info", name=pallet_name) assert "FAIL" in result.status assert result.data["changed"] is False assert "error" in result.data["msg"] assert "not a valid pallet" in result.data["msg"]
class Teststackipalletinfo: def test_no_pallet_name(self, run_ansible_module): result = run_ansible_module('stacki_pallet_info') assert result.status == 'SUCCESS' assert result.data['changed'] is False def test_pallet_name(self, run_ansible_module): pallet_name = 'stacki' result = run_ansible_module('stacki_pallet_info', name=pallet_name) assert result.status == 'SUCCESS' assert result.data['changed'] is False assert len(result.data['pallets']) == 1 assert result.data['pallets'][0]['name'] == pallet_name def test_invalid_pallet_name(self, run_ansible_module): pallet_name = 'fake_pallet_name' result = run_ansible_module('stacki_pallet_info', name=pallet_name) assert 'FAIL' in result.status assert result.data['changed'] is False assert 'error' in result.data['msg'] assert 'not a valid pallet' in result.data['msg']
'''(Record and Move on Technique [E]): Given a sorted array A and a target T, find the target. If the target is not in the array, find the number closest to the target. For example, if A = [2,3,5,8,9,11] and T = 7, return 8.''' def record(arr, mid, res, T): if res == -1 or abs(arr[mid] - T) < abs(arr[res] - T): return mid return res def closestElement(arr, T): low = 0 high = len(arr) - 1 res = -1 while low <= high: mid = low + (high - low) // 2 res = record(arr, mid, res, T) if arr[mid] > T: high = mid - 1 elif arr[mid] < T: low = mid + 1 else: return mid return res print(closestElement([2,3,5,8,9,11], 7)) # Output: 3 # Time: O(logn) Space: O(1)
"""(Record and Move on Technique [E]): Given a sorted array A and a target T, find the target. If the target is not in the array, find the number closest to the target. For example, if A = [2,3,5,8,9,11] and T = 7, return 8.""" def record(arr, mid, res, T): if res == -1 or abs(arr[mid] - T) < abs(arr[res] - T): return mid return res def closest_element(arr, T): low = 0 high = len(arr) - 1 res = -1 while low <= high: mid = low + (high - low) // 2 res = record(arr, mid, res, T) if arr[mid] > T: high = mid - 1 elif arr[mid] < T: low = mid + 1 else: return mid return res print(closest_element([2, 3, 5, 8, 9, 11], 7))
f1 = open("../train_pre_1") f2 = open("../test_pre_1") out1 = open("../train_pre_1b","w") out2 = open("../test_pre_1b","w") t = open("../train_gbdt_out") v = open("../test_gbdt_out") add = [] for i in xrange(30,49): add.append("C" + str(i)) line = f1.readline() print >> out1, line[:-1] + "," + ",".join(add) line = f2.readline() print >> out2, line[:-1] + "," + ",".join(add) for i in xrange(40428967): line = f1.readline()[:-1] a = t.readline()[:-1] ll = a.split(" ")[1:] for j in xrange(19): line += "," + add[j] + "_" + ll[j] print >> out1,line for i in xrange(4577464): line = f2.readline()[:-1] a = v.readline()[:-1] ll = a.split(" ")[1:] for j in xrange(19): line += "," + add[j] + "_" + ll[j] print >> out2,line f1.close() f2.close() out1.close() out2.close() t.close() v.close()
f1 = open('../train_pre_1') f2 = open('../test_pre_1') out1 = open('../train_pre_1b', 'w') out2 = open('../test_pre_1b', 'w') t = open('../train_gbdt_out') v = open('../test_gbdt_out') add = [] for i in xrange(30, 49): add.append('C' + str(i)) line = f1.readline() (print >> out1, line[:-1] + ',' + ','.join(add)) line = f2.readline() (print >> out2, line[:-1] + ',' + ','.join(add)) for i in xrange(40428967): line = f1.readline()[:-1] a = t.readline()[:-1] ll = a.split(' ')[1:] for j in xrange(19): line += ',' + add[j] + '_' + ll[j] (print >> out1, line) for i in xrange(4577464): line = f2.readline()[:-1] a = v.readline()[:-1] ll = a.split(' ')[1:] for j in xrange(19): line += ',' + add[j] + '_' + ll[j] (print >> out2, line) f1.close() f2.close() out1.close() out2.close() t.close() v.close()
class Solution: def readBinaryWatch(self, num: int) -> List[str]: return [str(h)+':'+'0'*(m<10)+str(m) for h in range(12) for m in range(60) if (bin(m)+bin(h)).count('1') == num]
class Solution: def read_binary_watch(self, num: int) -> List[str]: return [str(h) + ':' + '0' * (m < 10) + str(m) for h in range(12) for m in range(60) if (bin(m) + bin(h)).count('1') == num]
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( a ) : return ( 4 * a ) #TOFILL if __name__ == '__main__': param = [ (98,), (9,), (18,), (38,), (84,), (8,), (39,), (6,), (60,), (47,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
def f_gold(a): return 4 * a if __name__ == '__main__': param = [(98,), (9,), (18,), (38,), (84,), (8,), (39,), (6,), (60,), (47,)] n_success = 0 for (i, parameters_set) in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print('#Results: %i, %i' % (n_success, len(param)))
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ def helper(start): pre = start while start and start.next: if start.val != start.next.val : pre = start start = start.next else: while start.next and start.val == start.next.val: start = start.next pre.next = start.next start = pre.next empty = ListNode(None) empty.next = head helper(empty) return empty.next
class Solution(object): def delete_duplicates(self, head): """ :type head: ListNode :rtype: ListNode """ def helper(start): pre = start while start and start.next: if start.val != start.next.val: pre = start start = start.next else: while start.next and start.val == start.next.val: start = start.next pre.next = start.next start = pre.next empty = list_node(None) empty.next = head helper(empty) return empty.next
selRoi = 0 top_left= [20,40] bottom_right = [60,120] #For cars2.avi top_left= [40,50] bottom_right = [60,80] top_left2= [110,40] bottom_right2 = [150,120] first_time = 1 video_path = 'cars2.avi'
sel_roi = 0 top_left = [20, 40] bottom_right = [60, 120] top_left = [40, 50] bottom_right = [60, 80] top_left2 = [110, 40] bottom_right2 = [150, 120] first_time = 1 video_path = 'cars2.avi'
class Animal: def __init__(self): self.age = 1 def eat(self): print("eat") class Mammal(Animal): def walk(self): print("walk") m = Mammal() print(isinstance(m, Mammal)) print(isinstance(m, Animal)) print(isinstance(Mammal, object)) o = object() print(issubclass(Mammal, Animal)) print(issubclass(Mammal, object))
class Animal: def __init__(self): self.age = 1 def eat(self): print('eat') class Mammal(Animal): def walk(self): print('walk') m = mammal() print(isinstance(m, Mammal)) print(isinstance(m, Animal)) print(isinstance(Mammal, object)) o = object() print(issubclass(Mammal, Animal)) print(issubclass(Mammal, object))
inventory_dict = { "core": [ "PrettyName", "Present", "Functional" ], "fan": [ "PrettyName", "Present", "MeetsMinimumShipLevel", "Functional" ], "fan_wc": [ "PrettyName", "Present", "MeetsMinimumShipLevel" ], "fru": [ "PrettyName", "Present", "PartNumber", "SerialNumber", "Manufacturer", "BuildDate", "Model", "Version", "FieldReplaceable", "Cached", "Functional" ], "gpu": [ "PrettyName", "Present", "FieldReplaceable", "Functional" ] }
inventory_dict = {'core': ['PrettyName', 'Present', 'Functional'], 'fan': ['PrettyName', 'Present', 'MeetsMinimumShipLevel', 'Functional'], 'fan_wc': ['PrettyName', 'Present', 'MeetsMinimumShipLevel'], 'fru': ['PrettyName', 'Present', 'PartNumber', 'SerialNumber', 'Manufacturer', 'BuildDate', 'Model', 'Version', 'FieldReplaceable', 'Cached', 'Functional'], 'gpu': ['PrettyName', 'Present', 'FieldReplaceable', 'Functional']}
SEAL_CHECKER = 9300535 SEAL_OF_TIME = 2159367 if not sm.hasQuest(25672): sm.createQuestWithQRValue(25672, "1") sm.showFieldEffect("lightning/screenMsg/6", 0)
seal_checker = 9300535 seal_of_time = 2159367 if not sm.hasQuest(25672): sm.createQuestWithQRValue(25672, '1') sm.showFieldEffect('lightning/screenMsg/6', 0)
# -*- coding: utf-8 -*- class PayStatementReportData(object): """Implementation of the 'Pay Statement Report Data' model. TODO: type model description here. Attributes: asset_ids (list of string): The list of pay statement asset IDs. extract_earnings (bool): Field to indicate whether to extract the earnings on all pay statements. extract_deductions (bool): Field to indicate whether to extract the deductions on all pay statements. extract_direct_deposit (bool): Field to indicate whether to extract the direct deposits on all pay statements. """ # Create a mapping from Model property names to API property names _names = { "asset_ids":'assetIds', "extract_earnings":'extractEarnings', "extract_deductions":'extractDeductions', "extract_direct_deposit":'extractDirectDeposit' } def __init__(self, asset_ids=None, extract_earnings=True, extract_deductions=False, extract_direct_deposit=True, additional_properties = {}): """Constructor for the PayStatementReportData class""" # Initialize members of the class self.asset_ids = asset_ids self.extract_earnings = extract_earnings self.extract_deductions = extract_deductions self.extract_direct_deposit = extract_direct_deposit # Add additional model properties to the instance self.additional_properties = additional_properties @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary asset_ids = dictionary.get('assetIds') extract_earnings = dictionary.get("extractEarnings") if dictionary.get("extractEarnings") else True extract_deductions = dictionary.get("extractDeductions") if dictionary.get("extractDeductions") else False extract_direct_deposit = dictionary.get("extractDirectDeposit") if dictionary.get("extractDirectDeposit") else True # Clean out expected properties from dictionary for key in cls._names.values(): if key in dictionary: del dictionary[key] # Return an object of this model return cls(asset_ids, extract_earnings, extract_deductions, extract_direct_deposit, dictionary)
class Paystatementreportdata(object): """Implementation of the 'Pay Statement Report Data' model. TODO: type model description here. Attributes: asset_ids (list of string): The list of pay statement asset IDs. extract_earnings (bool): Field to indicate whether to extract the earnings on all pay statements. extract_deductions (bool): Field to indicate whether to extract the deductions on all pay statements. extract_direct_deposit (bool): Field to indicate whether to extract the direct deposits on all pay statements. """ _names = {'asset_ids': 'assetIds', 'extract_earnings': 'extractEarnings', 'extract_deductions': 'extractDeductions', 'extract_direct_deposit': 'extractDirectDeposit'} def __init__(self, asset_ids=None, extract_earnings=True, extract_deductions=False, extract_direct_deposit=True, additional_properties={}): """Constructor for the PayStatementReportData class""" self.asset_ids = asset_ids self.extract_earnings = extract_earnings self.extract_deductions = extract_deductions self.extract_direct_deposit = extract_direct_deposit self.additional_properties = additional_properties @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None asset_ids = dictionary.get('assetIds') extract_earnings = dictionary.get('extractEarnings') if dictionary.get('extractEarnings') else True extract_deductions = dictionary.get('extractDeductions') if dictionary.get('extractDeductions') else False extract_direct_deposit = dictionary.get('extractDirectDeposit') if dictionary.get('extractDirectDeposit') else True for key in cls._names.values(): if key in dictionary: del dictionary[key] return cls(asset_ids, extract_earnings, extract_deductions, extract_direct_deposit, dictionary)
class Solution: def minJumps(self, arr: List[int]) -> int: if len(arr) == 1: return 0 d = collections.defaultdict(list) for index, element in enumerate(arr): d[element].append(index) queue = collections.deque([(0, 0)]) s = set() s.add(0) while len(queue): currIndex, jumps = queue.popleft() for nextIndex in [currIndex + 1, currIndex - 1] + d[arr[currIndex]][::-1]: if nextIndex < len(arr) and nextIndex > -1 and nextIndex != currIndex and nextIndex not in s: if nextIndex == len(arr) - 1: return jumps + 1 s.add(nextIndex) queue.append((nextIndex, jumps + 1)) return -1
class Solution: def min_jumps(self, arr: List[int]) -> int: if len(arr) == 1: return 0 d = collections.defaultdict(list) for (index, element) in enumerate(arr): d[element].append(index) queue = collections.deque([(0, 0)]) s = set() s.add(0) while len(queue): (curr_index, jumps) = queue.popleft() for next_index in [currIndex + 1, currIndex - 1] + d[arr[currIndex]][::-1]: if nextIndex < len(arr) and nextIndex > -1 and (nextIndex != currIndex) and (nextIndex not in s): if nextIndex == len(arr) - 1: return jumps + 1 s.add(nextIndex) queue.append((nextIndex, jumps + 1)) return -1
_base_ = './model_r3d18.py' model = dict( backbone=dict(type='R2Plus1D'), )
_base_ = './model_r3d18.py' model = dict(backbone=dict(type='R2Plus1D'))
def func(x): """ Parameters: x(int): first line of the description second line third line Example:: assert func(42) is None """
def func(x): """ Parameters: x(int): first line of the description second line third line Example:: assert func(42) is None """
""" Uni project. Update literature. Developer: Stanislav Alexandrovich Ermokhin """ dic = dict() for item in ['_ru', '_en']: with open('literature'+item+'.txt') as a: lst = a.read().split(';') dic[item] = lst new_lst = list() for key in dic: dic[key] = sorted(['\t'+item.replace('\n', '') for item in dic[key]]) for item in dic[key]: new_lst.append(item) with open('literature.txt', 'w') as a: a.write('\n'.join(new_lst))
""" Uni project. Update literature. Developer: Stanislav Alexandrovich Ermokhin """ dic = dict() for item in ['_ru', '_en']: with open('literature' + item + '.txt') as a: lst = a.read().split(';') dic[item] = lst new_lst = list() for key in dic: dic[key] = sorted(['\t' + item.replace('\n', '') for item in dic[key]]) for item in dic[key]: new_lst.append(item) with open('literature.txt', 'w') as a: a.write('\n'.join(new_lst))
'''input ABCD No BACD Yes ''' # -*- coding: utf-8 -*- # CODE FESTIVAL 2017 qual C # Problem A if __name__ == '__main__': s = input() if 'AC' in s: print('Yes') else: print('No')
"""input ABCD No BACD Yes """ if __name__ == '__main__': s = input() if 'AC' in s: print('Yes') else: print('No')
ss = input() out = ss[0] for i in range(1, len(ss)): if ss[i] != ss[i-1]: out += ss[i] print(out)
ss = input() out = ss[0] for i in range(1, len(ss)): if ss[i] != ss[i - 1]: out += ss[i] print(out)
def onStart(): parent().par.Showshortcut = True def onCreate(): onStart()
def on_start(): parent().par.Showshortcut = True def on_create(): on_start()
#Edited by Joseph Hutchens def test(): print("Sucessfully Complete") return 1 test()
def test(): print('Sucessfully Complete') return 1 test()
def pipe_commands(commands): """Pipe commands together""" return ' | '.join(commands) def build_and_pipe_commands(commands): """Command to build then pipe commands together""" built_commands = [x.build_command() for x in commands] return pipe_commands(built_commands)
def pipe_commands(commands): """Pipe commands together""" return ' | '.join(commands) def build_and_pipe_commands(commands): """Command to build then pipe commands together""" built_commands = [x.build_command() for x in commands] return pipe_commands(built_commands)
__all__ = [ 'ValidationError', 'MethodMissingError', ] class ValidationError(Exception): pass class MethodMissingError(Exception): pass
__all__ = ['ValidationError', 'MethodMissingError'] class Validationerror(Exception): pass class Methodmissingerror(Exception): pass
def main(): while True: text = input("Enter a number: ") if not text: print("Later...") break num = int(text) num_class = "small" if num < 100 else "huge!" print(f"The number is {num_class}")
def main(): while True: text = input('Enter a number: ') if not text: print('Later...') break num = int(text) num_class = 'small' if num < 100 else 'huge!' print(f'The number is {num_class}')
"""An Extensible Dependency Resolver """ __version__ = "0.0.0a3"
"""An Extensible Dependency Resolver """ __version__ = '0.0.0a3'
quadruple_operations = [ '+', # 0 '-', '*', '/', '%', '=', # 5 '==', '>', '<', '<=', '>=', # 10 '<>', 'and', 'or', 'goto', 'gotof', # 15 'gotot', 'ret', 'return', 'gosub', 'era', # 20 'param', 'print', 'read', 'write', '(', # 25 ')' ] class zStack: """Traditional stack implementation""" def __init__(self): self.arr = [] # returns the last element in the stack def top(self): return self.arr[len(self.arr)-1] # returns the last element in the stack and removes it def pop(self): return self.arr.pop() # adds an element to the stack def push(self, val): self.arr.append(val) # returns wether the stack is empty or not def empty(self): return (1 if len(self.arr) else 0) # returns the size of the stack def size(self): return len(self.arr) # print the stack def print(self): print('---') for x in range(0, len(self.arr)): print('<',x,',',self.arr[x],'>') class zQueue: """Traditional queue implementation""" def __init__(self): self.arr = [] # returns the first element in the queue def front(self): return self.arr[0] # returns the first element in the queue and removes it def pop(self): return self.arr.pop(0) # adds an element to the queue def push(self, val): self.arr.append(val) # returns wether the queue is empty or not def empty(self): return (1 if len(self.arr) else 0) class zHash: """Traditional hash implementation where each bin is a pair, 0 is key 1 is value""" def __init__(self, n): self.n = n self.table = [None] * n # hash function, retrieved from https://en.wikibooks.org/wiki/Data_Structures/Hash_Tables def _joaat_Hash(self, key): hash = 0 for i in range(0, len(key)): hash += ord(key[i]) hash += (hash << 10) hash ^ (hash >> 6) hash += (hash << 3) hash ^ (hash >> 11) hash += (hash << 15) return hash # function for finding a slot using joaat hash and linear probing def _findSlot(self, key): i = self._joaat_Hash(key) % self.n j = i - 1 while(self.table[i] and self.table[i][0] != key and j != i): i += 1 % self.n if(j == i): return "Table full" return i # gets the value on the hash def get(self, key): i = self._findSlot(key) if(not self.table[i]): return "Record not found" else: return self.table[i][1] # sets or updates the corresponding key def set(self, key, val): i = self._findSlot(key) if(not self.table[i]): #key not in table, adding value self.table[i] = [key, val] return "Key not found, adding" else: # key already in table, updating value self.table[i][1] = val return "Key found, updating" # removes a key value pair from the hash def remove(self, key): i = self._findSlot(key) if(not self.table[i]): return "Record not found" else: self.table[i] = None return "Erased"
quadruple_operations = ['+', '-', '*', '/', '%', '=', '==', '>', '<', '<=', '>=', '<>', 'and', 'or', 'goto', 'gotof', 'gotot', 'ret', 'return', 'gosub', 'era', 'param', 'print', 'read', 'write', '(', ')'] class Zstack: """Traditional stack implementation""" def __init__(self): self.arr = [] def top(self): return self.arr[len(self.arr) - 1] def pop(self): return self.arr.pop() def push(self, val): self.arr.append(val) def empty(self): return 1 if len(self.arr) else 0 def size(self): return len(self.arr) def print(self): print('---') for x in range(0, len(self.arr)): print('<', x, ',', self.arr[x], '>') class Zqueue: """Traditional queue implementation""" def __init__(self): self.arr = [] def front(self): return self.arr[0] def pop(self): return self.arr.pop(0) def push(self, val): self.arr.append(val) def empty(self): return 1 if len(self.arr) else 0 class Zhash: """Traditional hash implementation where each bin is a pair, 0 is key 1 is value""" def __init__(self, n): self.n = n self.table = [None] * n def _joaat__hash(self, key): hash = 0 for i in range(0, len(key)): hash += ord(key[i]) hash += hash << 10 hash ^ hash >> 6 hash += hash << 3 hash ^ hash >> 11 hash += hash << 15 return hash def _find_slot(self, key): i = self._joaat_Hash(key) % self.n j = i - 1 while self.table[i] and self.table[i][0] != key and (j != i): i += 1 % self.n if j == i: return 'Table full' return i def get(self, key): i = self._findSlot(key) if not self.table[i]: return 'Record not found' else: return self.table[i][1] def set(self, key, val): i = self._findSlot(key) if not self.table[i]: self.table[i] = [key, val] return 'Key not found, adding' else: self.table[i][1] = val return 'Key found, updating' def remove(self, key): i = self._findSlot(key) if not self.table[i]: return 'Record not found' else: self.table[i] = None return 'Erased'
def main(): # problem1() # problem2() # problem3() problem4() # Create a function that has two variables. # One called greeting and another called myName. # Print out greeting and myName two different ways without using the following examples def problem1(): greeting = "Hello world" myName = "Chey" print("%s my name is %s." %(greeting,myName)) # print(f"{greeting} my name is {myName}.") # Create a function that asks the user for a secret password. # Create a loop that quits with the user's quit word. # If the user doesn't enter that word, ask them to guess again. def problem2(): secretPassword = input("Enter secret password ") while (True): password = input("Enter password ") if password == secretPassword: break else: print("Try Again!!") # Create a function that prints 0 to 100 three times in a row (vertically). def problem3(): for firstLoop in range(3): for secondLoop in range(101): print(secondLoop) def problem4(): randomNum = random.randint(0,5) userInput = "" while(userInput != str(randomNum)): userInput = input("Guess the number") if __name__ == '__main__': main()
def main(): problem4() def problem1(): greeting = 'Hello world' my_name = 'Chey' print('%s my name is %s.' % (greeting, myName)) def problem2(): secret_password = input('Enter secret password ') while True: password = input('Enter password ') if password == secretPassword: break else: print('Try Again!!') def problem3(): for first_loop in range(3): for second_loop in range(101): print(secondLoop) def problem4(): random_num = random.randint(0, 5) user_input = '' while userInput != str(randomNum): user_input = input('Guess the number') if __name__ == '__main__': main()
# 037 # Ask the user to enter their name and display each letter in # their name on a separate line name = input('Enter ya name: ') for i in range(len(name)): print(name[i])
name = input('Enter ya name: ') for i in range(len(name)): print(name[i])
# Dictionary Keys, Items and Values mice = {'harold': 'tiny mouse', 'rose': 'nipple mouse', 'willy wonka': 'dead mouse'} # Looping over a dictionary for m in mice.values(): # All values of the dictionary print(m) print() for m in mice.keys(): # All keys of the dictionary print(m) print() for m in mice.items(): # All items of the dictionary print(m) print() # Or get all info from the dictionary for key, value in mice.items(): print(value + ' ' + key + ' represent!') # Checkin a dictionary for a specific value print() print('harold' in mice.keys()) # True print('harold' in mice.values()) # False
mice = {'harold': 'tiny mouse', 'rose': 'nipple mouse', 'willy wonka': 'dead mouse'} for m in mice.values(): print(m) print() for m in mice.keys(): print(m) print() for m in mice.items(): print(m) print() for (key, value) in mice.items(): print(value + ' ' + key + ' represent!') print() print('harold' in mice.keys()) print('harold' in mice.values())
def selection_sort(items): """Implementation of selection sort where a given list of items are sorted in ascending order and returned""" for current_position in range(len(items)): # assume the current position as the smallest values position smallest_item_position = current_position # iterate through all elements from current position to the end including current position for location in range(current_position, len(items)): # check if an item exists which is less in value than the value in most recent smallest item if items[location] < items[smallest_item_position]: smallest_item_position = location # Interchange the values of current position and the smallest value found in the rest of the list temporary_item = items[current_position] items[current_position] = items[smallest_item_position] items[smallest_item_position] = temporary_item return items print(selection_sort([9, 8, 1, 3, 4]))
def selection_sort(items): """Implementation of selection sort where a given list of items are sorted in ascending order and returned""" for current_position in range(len(items)): smallest_item_position = current_position for location in range(current_position, len(items)): if items[location] < items[smallest_item_position]: smallest_item_position = location temporary_item = items[current_position] items[current_position] = items[smallest_item_position] items[smallest_item_position] = temporary_item return items print(selection_sort([9, 8, 1, 3, 4]))
def make_greeting(name, formality): return ( "Greetings and felicitations, {}!".format(name) if formality else "Hello, {}!".format(name) )
def make_greeting(name, formality): return 'Greetings and felicitations, {}!'.format(name) if formality else 'Hello, {}!'.format(name)
# Python modules # 3rd party modules # Our modules class PulseDesignPreview(object): """A lightweight version of a pulse design that's good for populating lists of designs (as in the design browser dialog). """ def __init__(self, attributes=None): self.id = "" self.uuid = "" self.name = "" self.creator = "" self.created = "" self.is_public = False self.comment = "" # referrers is a (possibly empty) list of 2-tuples of (id, name). # This contains all of the pulse sequences that refer to this # pulse project. self.referrers = [ ] if attributes is not None: self.inflate(attributes) if self.comment is None: self.comment = "" def __str__(self): return self.__unicode__() def __unicode__(self): lines = [ ] lines.append("--- Preview of Pulse Design %s ---" % self.id) lines.append("Name: %s" % self.name) lines.append("Public: %s" % ("True" if self.is_public else "False")) lines.append("comment: %s" % self.comment[:100]) # __unicode__() must return a Unicode object. In practice the code # above always generates Unicode, but we ensure it here. return '\n'.join(lines) @property def is_frozen(self): """ A pulse design is frozen when it's public or when one or more pulse sequences refers to it. """ return bool(self.referrers) or self.is_public def inflate(self, source): if hasattr(source, "makeelement"): # Quacks like an ElementTree.Element # PulseDesignPreview are never deflated to XML, so there's no # support for inflating them from XML raise NotImplementedError elif hasattr(source, "keys"): # Quacks like a dict for key in list(source.keys()): if hasattr(self, key): setattr(self, key, source[key])
class Pulsedesignpreview(object): """A lightweight version of a pulse design that's good for populating lists of designs (as in the design browser dialog). """ def __init__(self, attributes=None): self.id = '' self.uuid = '' self.name = '' self.creator = '' self.created = '' self.is_public = False self.comment = '' self.referrers = [] if attributes is not None: self.inflate(attributes) if self.comment is None: self.comment = '' def __str__(self): return self.__unicode__() def __unicode__(self): lines = [] lines.append('--- Preview of Pulse Design %s ---' % self.id) lines.append('Name: %s' % self.name) lines.append('Public: %s' % ('True' if self.is_public else 'False')) lines.append('comment: %s' % self.comment[:100]) return '\n'.join(lines) @property def is_frozen(self): """ A pulse design is frozen when it's public or when one or more pulse sequences refers to it. """ return bool(self.referrers) or self.is_public def inflate(self, source): if hasattr(source, 'makeelement'): raise NotImplementedError elif hasattr(source, 'keys'): for key in list(source.keys()): if hasattr(self, key): setattr(self, key, source[key])
class MockMetaMachine(object): def __init__(self, meta_business_unit_id_set, tag_id_set, platform, type, serial_number="YO"): self.meta_business_unit_id_set = set(meta_business_unit_id_set) self._tag_id_set = set(tag_id_set) self.platform = platform self.type = type self.serial_number = serial_number self.has_deb_packages = platform == "LINUX" def get_probe_filtering_values(self): return self.platform, self.type, self.meta_business_unit_id_set, self._tag_id_set @property def cached_probe_filtering_values(self): return self.get_probe_filtering_values()
class Mockmetamachine(object): def __init__(self, meta_business_unit_id_set, tag_id_set, platform, type, serial_number='YO'): self.meta_business_unit_id_set = set(meta_business_unit_id_set) self._tag_id_set = set(tag_id_set) self.platform = platform self.type = type self.serial_number = serial_number self.has_deb_packages = platform == 'LINUX' def get_probe_filtering_values(self): return (self.platform, self.type, self.meta_business_unit_id_set, self._tag_id_set) @property def cached_probe_filtering_values(self): return self.get_probe_filtering_values()
__all__ = ('CMD_STATUS', 'CMD_STATUS_NAME', 'CMD_BLOCKED', 'CMD_READY', 'CMD_ASSIGNED', 'CMD_RUNNING', 'CMD_FINISHING', 'CMD_DONE', 'CMD_ERROR', 'CMD_CANCELED', 'CMD_TIMEOUT', 'isFinalStatus', 'isRunningStatus') CMD_STATUS = (CMD_BLOCKED, CMD_READY, CMD_ASSIGNED, CMD_RUNNING, CMD_FINISHING, CMD_DONE, CMD_TIMEOUT, CMD_ERROR, CMD_CANCELED) = range(9) CMD_STATUS_NAME = ('BLOCKED', 'READY', 'ASSIGNED', 'RUNNING', 'FINISHING', 'DONE', 'TIMEOUT', 'ERROR', 'CANCELED') CMD_STATUS_SHORT_NAMES = ("B", "I", "A", "R", "F", "D", "T", "E", "C") def isFinalStatus(status): return status in (CMD_DONE, CMD_ERROR, CMD_CANCELED, CMD_TIMEOUT) def isRunningStatus(status): return status in (CMD_RUNNING, CMD_FINISHING, CMD_ASSIGNED)
__all__ = ('CMD_STATUS', 'CMD_STATUS_NAME', 'CMD_BLOCKED', 'CMD_READY', 'CMD_ASSIGNED', 'CMD_RUNNING', 'CMD_FINISHING', 'CMD_DONE', 'CMD_ERROR', 'CMD_CANCELED', 'CMD_TIMEOUT', 'isFinalStatus', 'isRunningStatus') cmd_status = (cmd_blocked, cmd_ready, cmd_assigned, cmd_running, cmd_finishing, cmd_done, cmd_timeout, cmd_error, cmd_canceled) = range(9) cmd_status_name = ('BLOCKED', 'READY', 'ASSIGNED', 'RUNNING', 'FINISHING', 'DONE', 'TIMEOUT', 'ERROR', 'CANCELED') cmd_status_short_names = ('B', 'I', 'A', 'R', 'F', 'D', 'T', 'E', 'C') def is_final_status(status): return status in (CMD_DONE, CMD_ERROR, CMD_CANCELED, CMD_TIMEOUT) def is_running_status(status): return status in (CMD_RUNNING, CMD_FINISHING, CMD_ASSIGNED)
uri = "postgres://user:password@host/database" # Postgresql url connection string token = "" # Discord bot token POLL_ROLE_PING = None # Role ID to ping for polls, leave as None to not ping THREAD_INACTIVE_HOURS = 12 # How many hours of inactivity are required for a ADD_USERS_IDS = [] # List of user ids to add to a thread on joi
uri = 'postgres://user:password@host/database' token = '' poll_role_ping = None thread_inactive_hours = 12 add_users_ids = []
# copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google Inc. # # Licensed under the Apache License Version 2.0 = uthe "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http //www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing software # distributed under the License is distributed on an "AS IS" BASIS # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Keys(object): NULL = u'\ue000' CANCEL = u'\ue001' # ^break HELP = u'\ue002' BACK_SPACE = u'\ue003' TAB = u'\ue004' CLEAR = u'\ue005' RETURN = u'\ue006' ENTER = u'\ue007' SHIFT = u'\ue008' LEFT_SHIFT = u'\ue008' # alias CONTROL = u'\ue009' LEFT_CONTROL = u'\ue009' # alias ALT = u'\ue00a' LEFT_ALT = u'\ue00a' # alias PAUSE = u'\ue00b' ESCAPE = u'\ue00c' SPACE = u'\ue00d' PAGE_UP = u'\ue00e' PAGE_DOWN = u'\ue00f' END = u'\ue010' HOME = u'\ue011' LEFT = u'\ue012' ARROW_LEFT = u'\ue012' # alias UP = u'\ue013' ARROW_UP = u'\ue013' # alias RIGHT = u'\ue014' ARROW_RIGHT = u'\ue014' # alias DOWN = u'\ue015' ARROW_DOWN = u'\ue015' # alias INSERT = u'\ue016' DELETE = u'\ue017' SEMICOLON = u'\ue018' EQUALS = u'\ue019' NUMPAD0 = u'\ue01a' # numbe pad keys NUMPAD1 = u'\ue01b' NUMPAD2 = u'\ue01c' NUMPAD3 = u'\ue01d' NUMPAD4 = u'\ue01e' NUMPAD5 = u'\ue01f' NUMPAD6 = u'\ue020' NUMPAD7 = u'\ue021' NUMPAD8 = u'\ue022' NUMPAD9 = u'\ue023' MULTIPLY = u'\ue024' ADD = u'\ue025' SEPARATOR = u'\ue026' SUBTRACT = u'\ue027' DECIMAL = u'\ue028' DIVIDE = u'\ue029' F1 = u'\ue031' # function keys F2 = u'\ue032' F3 = u'\ue033' F4 = u'\ue034' F5 = u'\ue035' F6 = u'\ue036' F7 = u'\ue037' F8 = u'\ue038' F9 = u'\ue039' F10 = u'\ue03a' F11 = u'\ue03b' F12 = u'\ue03c' META = u'\ue03d' COMMAND = u'\ue03d'
class Keys(object): null = u'\ue000' cancel = u'\ue001' help = u'\ue002' back_space = u'\ue003' tab = u'\ue004' clear = u'\ue005' return = u'\ue006' enter = u'\ue007' shift = u'\ue008' left_shift = u'\ue008' control = u'\ue009' left_control = u'\ue009' alt = u'\ue00a' left_alt = u'\ue00a' pause = u'\ue00b' escape = u'\ue00c' space = u'\ue00d' page_up = u'\ue00e' page_down = u'\ue00f' end = u'\ue010' home = u'\ue011' left = u'\ue012' arrow_left = u'\ue012' up = u'\ue013' arrow_up = u'\ue013' right = u'\ue014' arrow_right = u'\ue014' down = u'\ue015' arrow_down = u'\ue015' insert = u'\ue016' delete = u'\ue017' semicolon = u'\ue018' equals = u'\ue019' numpad0 = u'\ue01a' numpad1 = u'\ue01b' numpad2 = u'\ue01c' numpad3 = u'\ue01d' numpad4 = u'\ue01e' numpad5 = u'\ue01f' numpad6 = u'\ue020' numpad7 = u'\ue021' numpad8 = u'\ue022' numpad9 = u'\ue023' multiply = u'\ue024' add = u'\ue025' separator = u'\ue026' subtract = u'\ue027' decimal = u'\ue028' divide = u'\ue029' f1 = u'\ue031' f2 = u'\ue032' f3 = u'\ue033' f4 = u'\ue034' f5 = u'\ue035' f6 = u'\ue036' f7 = u'\ue037' f8 = u'\ue038' f9 = u'\ue039' f10 = u'\ue03a' f11 = u'\ue03b' f12 = u'\ue03c' meta = u'\ue03d' command = u'\ue03d'
class Account: """ A simple account class """ """ The constructor that initializes the objects fields """ def __init__(self, owner, amount=0.00): self.owner = owner self.amount = amount self.transactions = [] def __repr__(self): return f'Account {self.owner},{self.amount} ' def __str__(self): return f'Account belongs to {self.owner} and has a balance of {self.amount} Ksh Only ' """ Create new Accounts""" acc1 = Account('Victor') # Amount is initialized with a default value of 0.0 acc2 = Account('Roseline', 1000.00) # Amount is initialized with the value 1000.00 print('') print(str(acc2)) print(repr(acc1))
class Account: """ A simple account class """ ' The constructor that initializes the objects fields ' def __init__(self, owner, amount=0.0): self.owner = owner self.amount = amount self.transactions = [] def __repr__(self): return f'Account {self.owner},{self.amount} ' def __str__(self): return f'Account belongs to {self.owner} and has a balance of {self.amount} Ksh Only ' ' Create new Accounts' acc1 = account('Victor') acc2 = account('Roseline', 1000.0) print('') print(str(acc2)) print(repr(acc1))
def my_cleaner(dryrun): if dryrun: print('dryrun, dont really execute') return print('execute cleaner...') def task_sample(): return { "actions" : None, "clean" : [my_cleaner], }
def my_cleaner(dryrun): if dryrun: print('dryrun, dont really execute') return print('execute cleaner...') def task_sample(): return {'actions': None, 'clean': [my_cleaner]}
def NumFunc(myList1=[],myList2=[],*args): list3 = list(set(myList1).intersection(myList2)) return list3 myList1 = [1,2,3,4,5,6] myList2 = [3, 5, 7, 9] NumFunc(myList1,myList2)
def num_func(myList1=[], myList2=[], *args): list3 = list(set(myList1).intersection(myList2)) return list3 my_list1 = [1, 2, 3, 4, 5, 6] my_list2 = [3, 5, 7, 9] num_func(myList1, myList2)
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeKLists(self, lists: List[ListNode]) -> ListNode: ans = list() for node in lists: val = node while (val != None): ans.append(val.val) val = val.next ans = sorted(ans) sub = None point = None for x in ans: if sub == None: sub = ListNode(x) point = sub else: point.next = ListNode(x) point = point.next return sub # home = None # point = None # val = None # while True: # val = None # for i in range(len(lists)): # if lists[i] == None: # continue # if val == None: # val = i # continue # if lists[i].val < lists[val].val: # val = i # if val == None: # break # if home == None: # home = lists[val] # point = home # lists[val] = lists[val].next # else: # point.next = lists[val] # point = point.next # lists[val] = lists[val].next # return home
class Solution: def merge_k_lists(self, lists: List[ListNode]) -> ListNode: ans = list() for node in lists: val = node while val != None: ans.append(val.val) val = val.next ans = sorted(ans) sub = None point = None for x in ans: if sub == None: sub = list_node(x) point = sub else: point.next = list_node(x) point = point.next return sub
# Copyright (C) 2021 <FacuFalcone - CaidevOficial> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. def bag(sizeBag: int, kilos: list, values: list, index: int): # Base Case 1 if index == 0 or sizeBag == 0: return 0 # Base Case 2 elif kilos[index-1] > sizeBag: return bag(sizeBag, kilos, values, index-1) return max(values[index-1]+bag(sizeBag-kilos[index-1], kilos, values, index-1), bag(sizeBag, kilos, values, index-1)) if __name__ == "__main__": values = [60, 100, 120] kilos = [10, 20, 30] sizeBag = 50 index = len(values) result = bag(sizeBag, kilos, values, index) print(result)
def bag(sizeBag: int, kilos: list, values: list, index: int): if index == 0 or sizeBag == 0: return 0 elif kilos[index - 1] > sizeBag: return bag(sizeBag, kilos, values, index - 1) return max(values[index - 1] + bag(sizeBag - kilos[index - 1], kilos, values, index - 1), bag(sizeBag, kilos, values, index - 1)) if __name__ == '__main__': values = [60, 100, 120] kilos = [10, 20, 30] size_bag = 50 index = len(values) result = bag(sizeBag, kilos, values, index) print(result)
""" lab9 """ #3.1 class my_stat(): def cal_sigma(self,m,n): self.result=0 for i in range (n,m+1): self.result=self.result+i return self.result def cal_p(self,m,n): self.result=1 for i in range (n,m+1): self.result=self.result*i return self.result def cal_f(self,m): if m == 0: return(1) else: return m * self.cal_f(m-1) def cal_pr(self,m,n): return(self.cal_f(m)/self.cal_f(m-n)) #3.3 my_cal = my_stat() print(my_cal.cal_sigma(5,3)) my_cal = my_stat() print(my_cal.cal_p(5,3)) print(my_cal.cal_f(5)) print (my_cal.cal_pr(5,3))
""" lab9 """ class My_Stat: def cal_sigma(self, m, n): self.result = 0 for i in range(n, m + 1): self.result = self.result + i return self.result def cal_p(self, m, n): self.result = 1 for i in range(n, m + 1): self.result = self.result * i return self.result def cal_f(self, m): if m == 0: return 1 else: return m * self.cal_f(m - 1) def cal_pr(self, m, n): return self.cal_f(m) / self.cal_f(m - n) my_cal = my_stat() print(my_cal.cal_sigma(5, 3)) my_cal = my_stat() print(my_cal.cal_p(5, 3)) print(my_cal.cal_f(5)) print(my_cal.cal_pr(5, 3))
#Replace all ______ with rjust, ljust or center. THICKNESS = int(input()) #This must be an odd number c = 'H' # Top Cone for i in range(THICKNESS): print((c*i).rjust(THICKNESS-1)+c+(c*i).ljust(THICKNESS-1)) # Top Pillars for i in range(THICKNESS+1): print((c*THICKNESS).center(THICKNESS*2)+(c*THICKNESS).center(THICKNESS*6)) # Middle Belt for i in range((THICKNESS+1)//2): print((c*THICKNESS*5).center(THICKNESS*6)) # Bottom Pillars for i in range(THICKNESS+1): print((c*THICKNESS).center(THICKNESS*2)+(c*THICKNESS).center(THICKNESS*6)) # Bottom Cone for i in range(THICKNESS): print(((c*(THICKNESS-i-1)).rjust(THICKNESS)+c+(c*(THICKNESS-i-1)).ljust(THICKNESS)).rjust(THICKNESS*6))
thickness = int(input()) c = 'H' for i in range(THICKNESS): print((c * i).rjust(THICKNESS - 1) + c + (c * i).ljust(THICKNESS - 1)) for i in range(THICKNESS + 1): print((c * THICKNESS).center(THICKNESS * 2) + (c * THICKNESS).center(THICKNESS * 6)) for i in range((THICKNESS + 1) // 2): print((c * THICKNESS * 5).center(THICKNESS * 6)) for i in range(THICKNESS + 1): print((c * THICKNESS).center(THICKNESS * 2) + (c * THICKNESS).center(THICKNESS * 6)) for i in range(THICKNESS): print(((c * (THICKNESS - i - 1)).rjust(THICKNESS) + c + (c * (THICKNESS - i - 1)).ljust(THICKNESS)).rjust(THICKNESS * 6))
cellsize = 200 cells = {} recording = False class Cell: def __init__(self, x, y, ix, iy): self.x, self.y = x, y self.ix, self.iy = ix, iy # positional indices self.xdiv = 1.0 self.ydiv = 1.0 self.left = None self.up = None def left_inter(self): if self.left: return self.f(frameCount)[0] + self.left.left_inter() else: return self.f(frameCount)[0] def up_inter(self): if self.up: return self.f(frameCount)[1] + self.up.up_inter() else: return self.f(frameCount)[1] def f(self, fc): return cos(fc/self.xdiv), sin(fc/self.ydiv) def draw_me(self): pushStyle() pushMatrix() translate(self.x, self.y) fill(0, 0, 1) noStroke() circle(0, 0, 5) # calculate interference from previous cells # average out based on position ix = self.left_inter() / self.ix iy = self.up_inter() / self.iy fill(0, 1, 1, 0.5) circle(ix*cellsize*0.3, iy*cellsize*0.3, 2) popMatrix() popStyle() def __repr__(self): return "{}, {}".format(self.x, self.y) def setup(): size(800, 800) colorMode(HSB, 360, 1, 1, 1) background(0, 0, 0) for x in range(4): for y in range(4): cells[x,y] = Cell(x*cellsize+cellsize/2, y*cellsize+cellsize/2, x+1, y+1) cells[x,y].xdiv, cells[x,y].ydiv = 100.0, 100.0 # set up neighbour properties for y in range(4): for x in range(4): if x != 0: cells[x,y].left = cells[x-1,y] if y != 0: cells[x,y].up = cells[x,y-1] cells[0,0].xdiv, cells[0,0].ydiv = 100.0, 100.0 # set up vertical seeds for i in range(1,4): cells[0,i].xdiv, cells[0,i].ydiv = random(50, 100), random(30, 50) # set up horizontal seeds for i in range(1,4): cells[i,0].xdiv, cells[i,0].ydiv = random(30, 50), random(50, 100) def draw(): noStroke() fill(0, 0, 0, 0.04) square(0, 0, height) for k in cells: cells[k].draw_me() if recording and frameCount < 1500: saveFrame("frames/#####.png") else: noLoop() print("Done.")
cellsize = 200 cells = {} recording = False class Cell: def __init__(self, x, y, ix, iy): (self.x, self.y) = (x, y) (self.ix, self.iy) = (ix, iy) self.xdiv = 1.0 self.ydiv = 1.0 self.left = None self.up = None def left_inter(self): if self.left: return self.f(frameCount)[0] + self.left.left_inter() else: return self.f(frameCount)[0] def up_inter(self): if self.up: return self.f(frameCount)[1] + self.up.up_inter() else: return self.f(frameCount)[1] def f(self, fc): return (cos(fc / self.xdiv), sin(fc / self.ydiv)) def draw_me(self): push_style() push_matrix() translate(self.x, self.y) fill(0, 0, 1) no_stroke() circle(0, 0, 5) ix = self.left_inter() / self.ix iy = self.up_inter() / self.iy fill(0, 1, 1, 0.5) circle(ix * cellsize * 0.3, iy * cellsize * 0.3, 2) pop_matrix() pop_style() def __repr__(self): return '{}, {}'.format(self.x, self.y) def setup(): size(800, 800) color_mode(HSB, 360, 1, 1, 1) background(0, 0, 0) for x in range(4): for y in range(4): cells[x, y] = cell(x * cellsize + cellsize / 2, y * cellsize + cellsize / 2, x + 1, y + 1) (cells[x, y].xdiv, cells[x, y].ydiv) = (100.0, 100.0) for y in range(4): for x in range(4): if x != 0: cells[x, y].left = cells[x - 1, y] if y != 0: cells[x, y].up = cells[x, y - 1] (cells[0, 0].xdiv, cells[0, 0].ydiv) = (100.0, 100.0) for i in range(1, 4): (cells[0, i].xdiv, cells[0, i].ydiv) = (random(50, 100), random(30, 50)) for i in range(1, 4): (cells[i, 0].xdiv, cells[i, 0].ydiv) = (random(30, 50), random(50, 100)) def draw(): no_stroke() fill(0, 0, 0, 0.04) square(0, 0, height) for k in cells: cells[k].draw_me() if recording and frameCount < 1500: save_frame('frames/#####.png') else: no_loop() print('Done.')
HUOBI_URL_PRO = "https://api.huobi.sg" HUOBI_URL_VN = "https://api.huobi.sg" HUOBI_URL_SO = "https://api.huobi.sg" HUOBI_WEBSOCKET_URI_PRO = "wss://api.huobi.sg" HUOBI_WEBSOCKET_URI_VN = "wss://api.huobi.sg" HUOBI_WEBSOCKET_URI_SO = "wss://api.huobi.sg" class WebSocketDefine: Uri = HUOBI_WEBSOCKET_URI_PRO class RestApiDefine: Url = HUOBI_URL_PRO class HttpMethod: GET = "GET" GET_SIGN = "GET_SIGN" POST = "POST" POST_SIGN = "POST_SIGN" class ApiVersion: VERSION_V1 = "v1" VERSION_V2 = "v2" def get_default_server_url(user_configed_url): if user_configed_url and len(user_configed_url): return user_configed_url else: return RestApiDefine.Url
huobi_url_pro = 'https://api.huobi.sg' huobi_url_vn = 'https://api.huobi.sg' huobi_url_so = 'https://api.huobi.sg' huobi_websocket_uri_pro = 'wss://api.huobi.sg' huobi_websocket_uri_vn = 'wss://api.huobi.sg' huobi_websocket_uri_so = 'wss://api.huobi.sg' class Websocketdefine: uri = HUOBI_WEBSOCKET_URI_PRO class Restapidefine: url = HUOBI_URL_PRO class Httpmethod: get = 'GET' get_sign = 'GET_SIGN' post = 'POST' post_sign = 'POST_SIGN' class Apiversion: version_v1 = 'v1' version_v2 = 'v2' def get_default_server_url(user_configed_url): if user_configed_url and len(user_configed_url): return user_configed_url else: return RestApiDefine.Url
""" Tests using cards CLI (command line interface). """ def test_add(db_empty, cards_cli, cards_cli_list_items): # GIVEN an empty database # WHEN a new card is added cards_cli("add something -o okken") # THEN The listing returns just the new card items = cards_cli_list_items("list") assert len(items) == 1 assert items[0].summary == "something" assert items[0].owner == "okken" def test_list_filter(db_empty, cards_cli, cards_cli_list_items): """ Also kinda tests update """ # GIVEN # two items owned by okken, one that is done # two items with no owner, one that is done cards_cli("add -o okken one") cards_cli("add -o anyone two") cards_cli("add -o okken three") cards_cli("add four") cards_cli("add five") # get the ids for a couple of them items = cards_cli_list_items("list") for i in items: if i.summary in ("three", "four"): cards_cli(f"update {i.id} -d") # `cards --noowner -o okken -d` should return two items items = cards_cli_list_items("list --noowner -o okken -d") assert len(items) == 2 for i in items: assert i.summary in ("three", "four") assert i.done == "x" assert i.owner in ("okken", "") def test_count(db_empty, cards_cli): cards_cli("add one") cards_cli("add two") assert cards_cli("count") == "2" def test_delete(db_empty, cards_cli, cards_cli_list_items): # GIVEN a db with 2 items cards_cli("add one") cards_cli("add two") an_id = cards_cli_list_items("list")[0].id # WHEN we delete one item cards_cli(f"delete {an_id}") # THEN the other card remains assert cards_cli("count") == "1" def test_version(cards_cli): """ Should return 3 digits separated by a dot """ version = cards_cli("version").split(".") assert len(version) == 3 assert all([d.isdigit() for d in version])
""" Tests using cards CLI (command line interface). """ def test_add(db_empty, cards_cli, cards_cli_list_items): cards_cli('add something -o okken') items = cards_cli_list_items('list') assert len(items) == 1 assert items[0].summary == 'something' assert items[0].owner == 'okken' def test_list_filter(db_empty, cards_cli, cards_cli_list_items): """ Also kinda tests update """ cards_cli('add -o okken one') cards_cli('add -o anyone two') cards_cli('add -o okken three') cards_cli('add four') cards_cli('add five') items = cards_cli_list_items('list') for i in items: if i.summary in ('three', 'four'): cards_cli(f'update {i.id} -d') items = cards_cli_list_items('list --noowner -o okken -d') assert len(items) == 2 for i in items: assert i.summary in ('three', 'four') assert i.done == 'x' assert i.owner in ('okken', '') def test_count(db_empty, cards_cli): cards_cli('add one') cards_cli('add two') assert cards_cli('count') == '2' def test_delete(db_empty, cards_cli, cards_cli_list_items): cards_cli('add one') cards_cli('add two') an_id = cards_cli_list_items('list')[0].id cards_cli(f'delete {an_id}') assert cards_cli('count') == '1' def test_version(cards_cli): """ Should return 3 digits separated by a dot """ version = cards_cli('version').split('.') assert len(version) == 3 assert all([d.isdigit() for d in version])
def index(array,index): try: return array[index] except: return array def append(array,value): try: array.append(value) except: pass return array def remove(array,index): try: del array[index] except: pass return array def dedupe(array): try: return list(dict.fromkeys(array)) except: return array
def index(array, index): try: return array[index] except: return array def append(array, value): try: array.append(value) except: pass return array def remove(array, index): try: del array[index] except: pass return array def dedupe(array): try: return list(dict.fromkeys(array)) except: return array
class Entity(): def __init__(self, entityID, type, attributeMap): self.__entityID = entityID self.__type = type self.__attributeMap = attributeMap @property def entityID(self): return self.__entityID @entityID.setter def entityID(self, entityID): self.__entityID = entityID @property def type(self): return self.__type @type.setter def type(self, type): self.__type = type @property def attributeMap(self): return self.__attributeMap @attributeMap.setter def attributeMap(self, attributeMap): self.__attributeMap = attributeMap
class Entity: def __init__(self, entityID, type, attributeMap): self.__entityID = entityID self.__type = type self.__attributeMap = attributeMap @property def entity_id(self): return self.__entityID @entityID.setter def entity_id(self, entityID): self.__entityID = entityID @property def type(self): return self.__type @type.setter def type(self, type): self.__type = type @property def attribute_map(self): return self.__attributeMap @attributeMap.setter def attribute_map(self, attributeMap): self.__attributeMap = attributeMap
""" Abstract Syntax Tree Nodes """ class AST: ... class LetraNode(AST): def __init__(self, token): self.token = token def __repr__(self): return f'{self.token}' class NumeroNode(AST): def __init__(self, token): self.token = token def __repr__(self): return f'{self.token}' class BinOpNode(AST): def __init__(self, left, token, right): self.left = left self.token = token self.right = right def __repr__(self): return f'{self.left} : {self.token} : {self.right}' class UnaryOpNode(AST): def __init__(self, op_tok, node): self.op_tok = op_tok self.node = node def __repr__(self): return f'{self.op_tok}, {self.node}' class BaryabolAccessNode(AST): def __init__(self, baryabol_name): self.baryabol_name = baryabol_name def __repr__(self): return f'{self.baryabol_name}' class BaryabolAssignNode(AST): def __init__(self, baryabol_name, expression): self.baryabol_name = baryabol_name self.expression = expression def __repr__(self): return f'{self.baryabol_name} : {self.expression}' class IpahayagNode(AST): def __init__(self, ipapahayag): self.ipapahayag = ipapahayag def __repr__(self): return f'{self.ipapahayag}' class KungNode(AST): def __init__(self, expressions, condition, body): self.expressions = expressions self.condition = condition self.body = body def __repr__(self): return f'{self.condition}' class TukuyinEstablishNode(AST): def __init__(self, func_name, params, body): self.func_name = func_name self.params = params self.body = body def __repr__(self): return f'{self.condition}' class TukuyinAccessNode(AST): def __init__(self, func_name, params): self.func_name = func_name self.params = params def __repr__(self): return f'{self.condition}'
""" Abstract Syntax Tree Nodes """ class Ast: ... class Letranode(AST): def __init__(self, token): self.token = token def __repr__(self): return f'{self.token}' class Numeronode(AST): def __init__(self, token): self.token = token def __repr__(self): return f'{self.token}' class Binopnode(AST): def __init__(self, left, token, right): self.left = left self.token = token self.right = right def __repr__(self): return f'{self.left} : {self.token} : {self.right}' class Unaryopnode(AST): def __init__(self, op_tok, node): self.op_tok = op_tok self.node = node def __repr__(self): return f'{self.op_tok}, {self.node}' class Baryabolaccessnode(AST): def __init__(self, baryabol_name): self.baryabol_name = baryabol_name def __repr__(self): return f'{self.baryabol_name}' class Baryabolassignnode(AST): def __init__(self, baryabol_name, expression): self.baryabol_name = baryabol_name self.expression = expression def __repr__(self): return f'{self.baryabol_name} : {self.expression}' class Ipahayagnode(AST): def __init__(self, ipapahayag): self.ipapahayag = ipapahayag def __repr__(self): return f'{self.ipapahayag}' class Kungnode(AST): def __init__(self, expressions, condition, body): self.expressions = expressions self.condition = condition self.body = body def __repr__(self): return f'{self.condition}' class Tukuyinestablishnode(AST): def __init__(self, func_name, params, body): self.func_name = func_name self.params = params self.body = body def __repr__(self): return f'{self.condition}' class Tukuyinaccessnode(AST): def __init__(self, func_name, params): self.func_name = func_name self.params = params def __repr__(self): return f'{self.condition}'
# # from src/3dgraph.c # # a part of main to tdGraph # _MAX_VALUE = float("inf") class parametersTDGraph: def __init__(self, m, n, t, u, minX, minY, minZ, maxX, maxY, maxZ): self.m = m self.n = n self.t = t self.u = u self.minX = minX self.minY = minY self.minZ = minZ self.maxX = maxX self.maxY = maxY self.maxZ = maxZ def tdGraph(plotter, aFunction, parameters): P = parameters lowerHorizon = [ _MAX_VALUE for _ in range(P.m + 4 * P.n + 1) ] upperHorizon = [ -_MAX_VALUE for _ in range(P.m + 4 * P.n + 1) ] for i in range(P.n + 1): flagA = False z = P.minZ + (P.maxZ - P.minZ) / P.n * i for j in range(P.m + 1): flagB = False idx = j + 2 * (P.n - i) x = P.minX + (P.maxX - P.minX) / P.m * j y = P.t * (aFunction(x, z) - P.minY) / (P.maxY - P.minY) + P.u * i if y < lowerHorizon[idx]: lowerHorizon[idx], flagB = y, True if y > upperHorizon[idx]: upperHorizon[idx], flagB = y, True if flagB and flagA: plotter.draw(2 * idx, 2 * y) else: plotter.move(2 * idx, 2 * y) flagA = flagB
_max_value = float('inf') class Parameterstdgraph: def __init__(self, m, n, t, u, minX, minY, minZ, maxX, maxY, maxZ): self.m = m self.n = n self.t = t self.u = u self.minX = minX self.minY = minY self.minZ = minZ self.maxX = maxX self.maxY = maxY self.maxZ = maxZ def td_graph(plotter, aFunction, parameters): p = parameters lower_horizon = [_MAX_VALUE for _ in range(P.m + 4 * P.n + 1)] upper_horizon = [-_MAX_VALUE for _ in range(P.m + 4 * P.n + 1)] for i in range(P.n + 1): flag_a = False z = P.minZ + (P.maxZ - P.minZ) / P.n * i for j in range(P.m + 1): flag_b = False idx = j + 2 * (P.n - i) x = P.minX + (P.maxX - P.minX) / P.m * j y = P.t * (a_function(x, z) - P.minY) / (P.maxY - P.minY) + P.u * i if y < lowerHorizon[idx]: (lowerHorizon[idx], flag_b) = (y, True) if y > upperHorizon[idx]: (upperHorizon[idx], flag_b) = (y, True) if flagB and flagA: plotter.draw(2 * idx, 2 * y) else: plotter.move(2 * idx, 2 * y) flag_a = flagB
# -*- coding: utf-8 -*- """ fahrToCelsius is the function that converts the input temperature from degrees Fahrenheit to degrees Celsius. tempFahrenheit is input value of temperature in degrees Fahrenheit. convertedTemp is returned value of the function that is value of temperature in degrees Celsius. tempClassifier is the function that classifies temperature into 4 different classes (0,1,2,3). tempCelsius is input value of temperature in degrees Celsius. The fuction returns value of class (0 - cold, 1 - slippery, 2 - comfortable, 3 - warm) Author: Pavel Zhuchkov - 21.03.2018 Modified by - None """ # Definition of the function that converts Fahrenheit to Celsius def fahrToCelsius(tempFahrenheit): convertedTemp = (tempFahrenheit - 32) / 1.8 return convertedTemp # Definition of the function that classifies temperature into 4 different classes def tempClassifier(tempCelsius): if tempCelsius < -2: return 0 elif tempCelsius >= -2 and tempCelsius <= 2: return 1 elif tempCelsius > 2 and tempCelsius <= 15: return 2 else: return 3
""" fahrToCelsius is the function that converts the input temperature from degrees Fahrenheit to degrees Celsius. tempFahrenheit is input value of temperature in degrees Fahrenheit. convertedTemp is returned value of the function that is value of temperature in degrees Celsius. tempClassifier is the function that classifies temperature into 4 different classes (0,1,2,3). tempCelsius is input value of temperature in degrees Celsius. The fuction returns value of class (0 - cold, 1 - slippery, 2 - comfortable, 3 - warm) Author: Pavel Zhuchkov - 21.03.2018 Modified by - None """ def fahr_to_celsius(tempFahrenheit): converted_temp = (tempFahrenheit - 32) / 1.8 return convertedTemp def temp_classifier(tempCelsius): if tempCelsius < -2: return 0 elif tempCelsius >= -2 and tempCelsius <= 2: return 1 elif tempCelsius > 2 and tempCelsius <= 15: return 2 else: return 3
class CreateSingleEventRequest: def __init__(self, chart_key, event_key=None, table_booking_config=None, social_distancing_ruleset_key=None): if chart_key: self.chartKey = chart_key if event_key: self.eventKey = event_key if table_booking_config is not None: self.tableBookingConfig = table_booking_config.to_json() if social_distancing_ruleset_key is not None: self.socialDistancingRulesetKey = social_distancing_ruleset_key
class Createsingleeventrequest: def __init__(self, chart_key, event_key=None, table_booking_config=None, social_distancing_ruleset_key=None): if chart_key: self.chartKey = chart_key if event_key: self.eventKey = event_key if table_booking_config is not None: self.tableBookingConfig = table_booking_config.to_json() if social_distancing_ruleset_key is not None: self.socialDistancingRulesetKey = social_distancing_ruleset_key
# # PySNMP MIB module PYSNMP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PYSNMP-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:43:00 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) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibScalar, MibTable, MibTableRow, MibTableColumn, Gauge32, Bits, NotificationType, enterprises, IpAddress, Counter64, MibIdentifier, ObjectIdentity, ModuleIdentity, Counter32, iso, TimeTicks, Unsigned32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Gauge32", "Bits", "NotificationType", "enterprises", "IpAddress", "Counter64", "MibIdentifier", "ObjectIdentity", "ModuleIdentity", "Counter32", "iso", "TimeTicks", "Unsigned32", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") pysnmp = ModuleIdentity((1, 3, 6, 1, 4, 1, 20408)) pysnmp.setRevisions(('2017-04-14 00:00', '2005-05-14 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: pysnmp.setRevisionsDescriptions(('Updated addresses', 'Initial revision',)) if mibBuilder.loadTexts: pysnmp.setLastUpdated('201704140000Z') if mibBuilder.loadTexts: pysnmp.setOrganization('The PySNMP Project') if mibBuilder.loadTexts: pysnmp.setContactInfo('E-mail: Ilya Etingof <etingof@gmail.com> GitHub: https://github.com/etingof/pysnmp') if mibBuilder.loadTexts: pysnmp.setDescription('PySNMP top-level MIB tree infrastructure') pysnmpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 1)) pysnmpExamples = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 2)) pysnmpEnumerations = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3)) pysnmpModuleIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 1)) pysnmpAgentOIDs = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 2)) pysnmpDomains = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 3, 3)) pysnmpExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 9999)) pysnmpNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4)) pysnmpNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 0)) pysnmpNotificationObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 4, 1)) pysnmpConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5)) pysnmpCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 1)) pysnmpGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 20408, 5, 2)) mibBuilder.exportSymbols("PYSNMP-MIB", pysnmpNotifications=pysnmpNotifications, pysnmpObjects=pysnmpObjects, pysnmpGroups=pysnmpGroups, pysnmp=pysnmp, pysnmpNotificationObjects=pysnmpNotificationObjects, pysnmpExamples=pysnmpExamples, pysnmpCompliances=pysnmpCompliances, PYSNMP_MODULE_ID=pysnmp, pysnmpNotificationPrefix=pysnmpNotificationPrefix, pysnmpEnumerations=pysnmpEnumerations, pysnmpModuleIDs=pysnmpModuleIDs, pysnmpAgentOIDs=pysnmpAgentOIDs, pysnmpConformance=pysnmpConformance, pysnmpExperimental=pysnmpExperimental, pysnmpDomains=pysnmpDomains)
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (mib_scalar, mib_table, mib_table_row, mib_table_column, gauge32, bits, notification_type, enterprises, ip_address, counter64, mib_identifier, object_identity, module_identity, counter32, iso, time_ticks, unsigned32, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Gauge32', 'Bits', 'NotificationType', 'enterprises', 'IpAddress', 'Counter64', 'MibIdentifier', 'ObjectIdentity', 'ModuleIdentity', 'Counter32', 'iso', 'TimeTicks', 'Unsigned32', 'Integer32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') pysnmp = module_identity((1, 3, 6, 1, 4, 1, 20408)) pysnmp.setRevisions(('2017-04-14 00:00', '2005-05-14 00:00')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: pysnmp.setRevisionsDescriptions(('Updated addresses', 'Initial revision')) if mibBuilder.loadTexts: pysnmp.setLastUpdated('201704140000Z') if mibBuilder.loadTexts: pysnmp.setOrganization('The PySNMP Project') if mibBuilder.loadTexts: pysnmp.setContactInfo('E-mail: Ilya Etingof <etingof@gmail.com> GitHub: https://github.com/etingof/pysnmp') if mibBuilder.loadTexts: pysnmp.setDescription('PySNMP top-level MIB tree infrastructure') pysnmp_objects = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 1)) pysnmp_examples = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 2)) pysnmp_enumerations = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 3)) pysnmp_module_i_ds = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 3, 1)) pysnmp_agent_oi_ds = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 3, 2)) pysnmp_domains = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 3, 3)) pysnmp_experimental = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 9999)) pysnmp_notification_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 4)) pysnmp_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 4, 0)) pysnmp_notification_objects = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 4, 1)) pysnmp_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 5)) pysnmp_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 5, 1)) pysnmp_groups = mib_identifier((1, 3, 6, 1, 4, 1, 20408, 5, 2)) mibBuilder.exportSymbols('PYSNMP-MIB', pysnmpNotifications=pysnmpNotifications, pysnmpObjects=pysnmpObjects, pysnmpGroups=pysnmpGroups, pysnmp=pysnmp, pysnmpNotificationObjects=pysnmpNotificationObjects, pysnmpExamples=pysnmpExamples, pysnmpCompliances=pysnmpCompliances, PYSNMP_MODULE_ID=pysnmp, pysnmpNotificationPrefix=pysnmpNotificationPrefix, pysnmpEnumerations=pysnmpEnumerations, pysnmpModuleIDs=pysnmpModuleIDs, pysnmpAgentOIDs=pysnmpAgentOIDs, pysnmpConformance=pysnmpConformance, pysnmpExperimental=pysnmpExperimental, pysnmpDomains=pysnmpDomains)
def uniform_cost_search(graph, start, goal): path = [] explored_nodes = list() if start == goal: return path, explored_nodes path.append(start) path_cost = 0 frontier = [(path_cost, path)] while len(frontier) > 0: path_cost_till_now, path_till_now = pop_frontier(frontier) current_node = path_till_now[-1] explored_nodes.append(current_node) if current_node == goal: return path_till_now, explored_nodes neighbours = graph[current_node] neighbours_list_int = [int(n) for n in neighbours] neighbours_list_int.sort(reverse=False) neighbours_list_str = [str(n) for n in neighbours_list_int] for neighbour in neighbours_list_str: path_to_neighbour = path_till_now.copy() path_to_neighbour.append(neighbour) extra_cost = 1 neighbour_cost = extra_cost + path_cost_till_now new_element = (neighbour_cost, path_to_neighbour) is_there, indexx, neighbour_old_cost, _ = get_frontier_params_new(neighbour, frontier) if (neighbour not in explored_nodes) and not is_there: frontier.append(new_element) elif is_there: if neighbour_old_cost > neighbour_cost: frontier.pop(indexx) frontier.append(new_element) return None, None
def uniform_cost_search(graph, start, goal): path = [] explored_nodes = list() if start == goal: return (path, explored_nodes) path.append(start) path_cost = 0 frontier = [(path_cost, path)] while len(frontier) > 0: (path_cost_till_now, path_till_now) = pop_frontier(frontier) current_node = path_till_now[-1] explored_nodes.append(current_node) if current_node == goal: return (path_till_now, explored_nodes) neighbours = graph[current_node] neighbours_list_int = [int(n) for n in neighbours] neighbours_list_int.sort(reverse=False) neighbours_list_str = [str(n) for n in neighbours_list_int] for neighbour in neighbours_list_str: path_to_neighbour = path_till_now.copy() path_to_neighbour.append(neighbour) extra_cost = 1 neighbour_cost = extra_cost + path_cost_till_now new_element = (neighbour_cost, path_to_neighbour) (is_there, indexx, neighbour_old_cost, _) = get_frontier_params_new(neighbour, frontier) if neighbour not in explored_nodes and (not is_there): frontier.append(new_element) elif is_there: if neighbour_old_cost > neighbour_cost: frontier.pop(indexx) frontier.append(new_element) return (None, None)
def fibonacci(n): seznam = [] (a, b) = (0, 1) for i in range(n): (a, b) = (b, a+b) seznam.append(a) return [a, seznam] def stevke(stevilo): n = 1 while n > 0: #nevem kako naj bolje napisem if fibonacci(n)[0] > 10 ** (stevilo -1): return fibonacci(n)[1].index(fibonacci(n)[0]) + 1 n = n + 1 print(stevke(1000))
def fibonacci(n): seznam = [] (a, b) = (0, 1) for i in range(n): (a, b) = (b, a + b) seznam.append(a) return [a, seznam] def stevke(stevilo): n = 1 while n > 0: if fibonacci(n)[0] > 10 ** (stevilo - 1): return fibonacci(n)[1].index(fibonacci(n)[0]) + 1 n = n + 1 print(stevke(1000))
spam = 42 # global variable def printSpam(): print('Spam = ' + str(spam)) def eggs(): spam = 42 # local variable return spam print('example xyz') def Spam(): eggs = 99 bacon() print(eggs) def bacon(): ham = 101 eggs = 0 def assignSpam(var): global spam spam = var Spam() printSpam() assignSpam(25) printSpam()
spam = 42 def print_spam(): print('Spam = ' + str(spam)) def eggs(): spam = 42 return spam print('example xyz') def spam(): eggs = 99 bacon() print(eggs) def bacon(): ham = 101 eggs = 0 def assign_spam(var): global spam spam = var spam() print_spam() assign_spam(25) print_spam()
""" URL: https://codeforces.com/problemset/problem/1422/C Author: Safiul Kabir [safiulanik at gmail.com] Tags: combinatorics, dp, math, *1700 ---------------------In Progress--------------------- """ mod = 10 ** 9 + 7 def a(s): # s = input() ll = len(s) summ = 0 for i in range(ll): current_digit = int(s[i]) c1 = current_digit * 10 ** (ll - i - 1) * i * (i + 1) // 2 c2_coff = ''.join([str(j) for j in range(ll - i - 1, 0, -1)]) if len(c2_coff) > 9: c2_coff = 987654321 elif len(c2_coff) > 0: c2_coff = int(c2_coff) else: c2_coff = 0 c2 = current_digit * c2_coff summ += c1 summ += c2 summ %= mod print(summ) a('100500100500') a('107')
""" URL: https://codeforces.com/problemset/problem/1422/C Author: Safiul Kabir [safiulanik at gmail.com] Tags: combinatorics, dp, math, *1700 ---------------------In Progress--------------------- """ mod = 10 ** 9 + 7 def a(s): ll = len(s) summ = 0 for i in range(ll): current_digit = int(s[i]) c1 = current_digit * 10 ** (ll - i - 1) * i * (i + 1) // 2 c2_coff = ''.join([str(j) for j in range(ll - i - 1, 0, -1)]) if len(c2_coff) > 9: c2_coff = 987654321 elif len(c2_coff) > 0: c2_coff = int(c2_coff) else: c2_coff = 0 c2 = current_digit * c2_coff summ += c1 summ += c2 summ %= mod print(summ) a('100500100500') a('107')
n = int(input().strip()) ar = list(map(int, input().strip().split(' '))) print (ar.count(max(ar))) #https://www.hackerrank.com/challenges/birthday-cake-candles/problem
n = int(input().strip()) ar = list(map(int, input().strip().split(' '))) print(ar.count(max(ar)))
class Project: def __init__(self, id=None, name=None, description=None): self.id = id self.name = name self.description = description def __repr__(self): return "%s: %s, %s" % (self.id, self.name, self.description) def __eq__(self, other): return self.id == other.id and self.name == other.name def __lt__(self, other): return int(self.id) < int(other.id)
class Project: def __init__(self, id=None, name=None, description=None): self.id = id self.name = name self.description = description def __repr__(self): return '%s: %s, %s' % (self.id, self.name, self.description) def __eq__(self, other): return self.id == other.id and self.name == other.name def __lt__(self, other): return int(self.id) < int(other.id)
class Service: def __init__(self, name): self.name = name self.methods = {} def rpc(self, func_name): def decorator(func): self._save_method(func_name, func) return func if isinstance(func_name, str): return decorator func = func_name func_name = func.__name__ return decorator(func) def _save_method(self, method: str, func): self.methods[method] = func.__name__ def get_methods(self, obj): methods = {} for method, func_name in self.methods.items(): func = getattr(obj, func_name) methods[method] = func return methods
class Service: def __init__(self, name): self.name = name self.methods = {} def rpc(self, func_name): def decorator(func): self._save_method(func_name, func) return func if isinstance(func_name, str): return decorator func = func_name func_name = func.__name__ return decorator(func) def _save_method(self, method: str, func): self.methods[method] = func.__name__ def get_methods(self, obj): methods = {} for (method, func_name) in self.methods.items(): func = getattr(obj, func_name) methods[method] = func return methods
def prime_factors(strs): result = [] float=2 while float: if strs%float==0: strs = strs / float result.append(float) else: float = float+1 if float>strs: break return result
def prime_factors(strs): result = [] float = 2 while float: if strs % float == 0: strs = strs / float result.append(float) else: float = float + 1 if float > strs: break return result
''' Steven Kyritsis CS100 2021F Section 031 HW 10, November 12, 2021 ''' #3 def shareoneletter(wordlist): d={} for w in wordlist: d[w]=[] for i in wordlist: match=False for c in w: if c in i: match=True if match and i not in d[w]: d[w].append(i) return d print(shareoneletter(['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']))
""" Steven Kyritsis CS100 2021F Section 031 HW 10, November 12, 2021 """ def shareoneletter(wordlist): d = {} for w in wordlist: d[w] = [] for i in wordlist: match = False for c in w: if c in i: match = True if match and i not in d[w]: d[w].append(i) return d print(shareoneletter(['I', 'say', 'what', 'I', 'mean', 'and', 'I', 'mean', 'what', 'I', 'say']))
# A server used to store and retrieve arbitrary data. # This is used by: ./dispatcher.js def main(request, response): response.headers.set(b'Access-Control-Allow-Origin', b'*') response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST') response.headers.set(b'Access-Control-Allow-Headers', b'Content-Type') response.headers.set(b'Cache-Control', b'no-cache, no-store, must-revalidate') if request.method == u'OPTIONS': # CORS preflight return b'' uuid = request.GET[b'uuid'] stash = request.server.stash; with stash.lock: queue = stash.take(uuid) if queue is None: queue = [] if request.method == u'POST': queue.append(request.body) ret = b'done' else: if len(queue) == 0: ret = b'not ready' else: ret = queue.pop(0) stash.put(uuid, queue) return ret;
def main(request, response): response.headers.set(b'Access-Control-Allow-Origin', b'*') response.headers.set(b'Access-Control-Allow-Methods', b'OPTIONS, GET, POST') response.headers.set(b'Access-Control-Allow-Headers', b'Content-Type') response.headers.set(b'Cache-Control', b'no-cache, no-store, must-revalidate') if request.method == u'OPTIONS': return b'' uuid = request.GET[b'uuid'] stash = request.server.stash with stash.lock: queue = stash.take(uuid) if queue is None: queue = [] if request.method == u'POST': queue.append(request.body) ret = b'done' elif len(queue) == 0: ret = b'not ready' else: ret = queue.pop(0) stash.put(uuid, queue) return ret
clarify_boosted = { 'abita cove': ["cooked cod"], 'the red city': ["baked potatoes", "carrots", "iron ingot"], 'claybound': ["cooked salmon"] } aliases = { 'Quartz': 'Quartz Crystal', 'Potatoes': 'Baked Potatoes', 'Nether Wart': 'Nether Wart Block' }
clarify_boosted = {'abita cove': ['cooked cod'], 'the red city': ['baked potatoes', 'carrots', 'iron ingot'], 'claybound': ['cooked salmon']} aliases = {'Quartz': 'Quartz Crystal', 'Potatoes': 'Baked Potatoes', 'Nether Wart': 'Nether Wart Block'}
while True: linha = input("Digite qualquer coisa ou \"fim\" para terminar: ") if linha == "fim": break print(linha) print("Fim!")
while True: linha = input('Digite qualquer coisa ou "fim" para terminar: ') if linha == 'fim': break print(linha) print('Fim!')
""" What you will learn: - How to add, subtract, multiply divide numbers - Float division and integer division - Modulus (finding the remainder) - Dealing with exponents - Python will crash on errors (like divide by 0) Okay now lets do more cool things with variables. Like making python do math for us! What you need to do: Pt 1 - solve x = 45 + 4(4/6+2)^5 --- should = 584.391 - solve x = (4/5*5+1)^.5 --- should = 2.23607 Pt 2 - understand why divide0 and divide1 have different results - what is mod0 and mod1 - write code to determine if 39879827239498734985798 is divisible by 3 without a remainder Pt 3 - divide a number by 0. Watch what happens. Note the type of error it is Pt 4 - try to add an int and string together. What happens? """ x = 6 y = 2 adder = x + y # some simple addition suber = x - y # some simple subtraction multr = x * y # some simple multiplication divide0 = x / y divide1 = x // y mod0 = x % y mod1 = y % x power = x ** 6 # the "**" means to the power of p0 = "Hi " P1 = " My Name IS" P2 = " Slime Shady" P = p0 + P1 + P2 print(P)
""" What you will learn: - How to add, subtract, multiply divide numbers - Float division and integer division - Modulus (finding the remainder) - Dealing with exponents - Python will crash on errors (like divide by 0) Okay now lets do more cool things with variables. Like making python do math for us! What you need to do: Pt 1 - solve x = 45 + 4(4/6+2)^5 --- should = 584.391 - solve x = (4/5*5+1)^.5 --- should = 2.23607 Pt 2 - understand why divide0 and divide1 have different results - what is mod0 and mod1 - write code to determine if 39879827239498734985798 is divisible by 3 without a remainder Pt 3 - divide a number by 0. Watch what happens. Note the type of error it is Pt 4 - try to add an int and string together. What happens? """ x = 6 y = 2 adder = x + y suber = x - y multr = x * y divide0 = x / y divide1 = x // y mod0 = x % y mod1 = y % x power = x ** 6 p0 = 'Hi ' p1 = ' My Name IS' p2 = ' Slime Shady' p = p0 + P1 + P2 print(P)
phrase = input('Enter a phrase: ') for c in phrase: if c in 'aeoiuAEOIU': print(c)
phrase = input('Enter a phrase: ') for c in phrase: if c in 'aeoiuAEOIU': print(c)
""" https://leetcode.com/problems/number-of-islands/ """ class Solution: """ Wrapper for LeetCode Solution """ def numIslands(self, grid: [[str]]) -> int: """ Determines the number of islands in a matrix, before destroying them """ # No islands or land if not grid or not grid[0]: return 0 islands_found = 0 for row_index, row in enumerate(grid): for col_index, _col in enumerate(row): # if the current position is an island if grid[row_index][col_index] == "1": # Mark island as found islands_found += 1 # Destory entire island self._destroy_island(grid, row_index, col_index) return islands_found def _destroy_island(self, grid: [[str]], row_index: int, col_index: int): """ Destroys the entire island """ out_of_bounds_longitude = col_index < 0 or col_index >= len(grid[0]) out_of_bounds_latitude = row_index < 0 or row_index >= len(grid) if out_of_bounds_longitude or out_of_bounds_latitude: return current_position = grid[row_index][col_index] if current_position == "0": return # Destroy island underneath the current position grid[row_index][col_index] = "0" # Destroy contigious island landmass to the north, south, east and west self._destroy_island(grid, row_index-1, col_index) self._destroy_island(grid, row_index+1, col_index) self._destroy_island(grid, row_index, col_index-1) self._destroy_island(grid, row_index, col_index+1) def main(): """ The entry point of the python script """ world_1 = [ ["1","1","1","1","0"], ["1","1","0","1","0"], ["1","1","0","0","0"], ["0","0","0","0","1"] ] sln = Solution() number_of_islands_world_1 = sln.numIslands(world_1) print(f"Number of islands destroyed in world_1: {number_of_islands_world_1}") if __name__ == "__main__": main()
""" https://leetcode.com/problems/number-of-islands/ """ class Solution: """ Wrapper for LeetCode Solution """ def num_islands(self, grid: [[str]]) -> int: """ Determines the number of islands in a matrix, before destroying them """ if not grid or not grid[0]: return 0 islands_found = 0 for (row_index, row) in enumerate(grid): for (col_index, _col) in enumerate(row): if grid[row_index][col_index] == '1': islands_found += 1 self._destroy_island(grid, row_index, col_index) return islands_found def _destroy_island(self, grid: [[str]], row_index: int, col_index: int): """ Destroys the entire island """ out_of_bounds_longitude = col_index < 0 or col_index >= len(grid[0]) out_of_bounds_latitude = row_index < 0 or row_index >= len(grid) if out_of_bounds_longitude or out_of_bounds_latitude: return current_position = grid[row_index][col_index] if current_position == '0': return grid[row_index][col_index] = '0' self._destroy_island(grid, row_index - 1, col_index) self._destroy_island(grid, row_index + 1, col_index) self._destroy_island(grid, row_index, col_index - 1) self._destroy_island(grid, row_index, col_index + 1) def main(): """ The entry point of the python script """ world_1 = [['1', '1', '1', '1', '0'], ['1', '1', '0', '1', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '0', '0', '1']] sln = solution() number_of_islands_world_1 = sln.numIslands(world_1) print(f'Number of islands destroyed in world_1: {number_of_islands_world_1}') if __name__ == '__main__': main()
# author Mahmud Ahsan # -------------------- # msmath module under mspack package # -------------------- def sum(x, y): return x + y def subtract(x, y): return x - y def multiplication(x, y): return x * y def division(x, y): return x / y
def sum(x, y): return x + y def subtract(x, y): return x - y def multiplication(x, y): return x * y def division(x, y): return x / y
rows=input() rows=int(rows) k=0 matrixList=[]; evenMatrix=[] while rows!=0: matrix=input() matrix=matrix.split(", "); matrix=[int(e) for e in matrix] e=0; elements=len(matrix) matrixList.append([]) while e < elements: matrixList[k].append(matrix[0]) del matrix[0] e += 1 rows-=1; k+=1 for k in matrixList: evenMatrix.append([]) for j in k: if j%2==0: evenMatrix[len(evenMatrix)-1].append(j) print(evenMatrix)
rows = input() rows = int(rows) k = 0 matrix_list = [] even_matrix = [] while rows != 0: matrix = input() matrix = matrix.split(', ') matrix = [int(e) for e in matrix] e = 0 elements = len(matrix) matrixList.append([]) while e < elements: matrixList[k].append(matrix[0]) del matrix[0] e += 1 rows -= 1 k += 1 for k in matrixList: evenMatrix.append([]) for j in k: if j % 2 == 0: evenMatrix[len(evenMatrix) - 1].append(j) print(evenMatrix)
def profitable_gamble(prob, prize, pay): if prob * prize > pay: return True return False print(profitable_gamble(4,8,12))
def profitable_gamble(prob, prize, pay): if prob * prize > pay: return True return False print(profitable_gamble(4, 8, 12))
#addition.py def add(a,b): return a+b a=int(input("Enter the a value")) b= int(input("Enter the b value")) c=add(a,b) print(c)
def add(a, b): return a + b a = int(input('Enter the a value')) b = int(input('Enter the b value')) c = add(a, b) print(c)
class DissectError(Exception): """ Error when - initially parsing / constructing a message (Checksum error, message to small, ...) or - trying to access data / certain attributes (No payload, payload too small, payload does make no sense) May also occur when encountering edge cases not yet handled by the dissector """ pass
class Dissecterror(Exception): """ Error when - initially parsing / constructing a message (Checksum error, message to small, ...) or - trying to access data / certain attributes (No payload, payload too small, payload does make no sense) May also occur when encountering edge cases not yet handled by the dissector """ pass