content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
site = 'ftp.skilldrick.co.uk' webRoot = '/public_html' localDir = '.' #by default use current directory remoteDir = 'tmpl' ignoreDirs = ['.git', 'fancybox', 'safeinc'] ignoreFileSuffixes = ['.py', '.pyc', '~', '#', '.swp', '.gitignore', '.lastrun', 'Makefile', '.bat', 'Thumbs.db', 'README.markdown']
site = 'ftp.skilldrick.co.uk' web_root = '/public_html' local_dir = '.' remote_dir = 'tmpl' ignore_dirs = ['.git', 'fancybox', 'safeinc'] ignore_file_suffixes = ['.py', '.pyc', '~', '#', '.swp', '.gitignore', '.lastrun', 'Makefile', '.bat', 'Thumbs.db', 'README.markdown']
class Node: def __init__(self, data): self.data = data self.next = None class CircularLinkedList: def __init__(self): self.head = None self.tail = None self.length = 0 def append(self, data): new_node = Node(data) if not self.head: self.head = new_node self.head.next = self.head else: curr_node = self.head while curr_node.next != self.head: curr_node = curr_node.next curr_node.next = new_node; new_node.next = self.head def prepend(self, data): new_node = Node(data) curr_node = self.head new_node.next = self.head if not self.head: new_node.next = self.head else: while curr_node.next != self.head: curr_node = curr_node.next curr_node.next = new_node self.head = new_node def delete(self, key): if self.head is None: return if self.head.next == self.head and self.head.data == key: self.head = None elif self.head.data == key: curr_node = self.head while curr_node.next != self.head: curr_node = curr_node.next curr_node.next = self.head.next self.head = self.head.next else: curr_node = self.head prev = None while curr_node.next != self.head: prev = curr_node curr_node = curr_node.next # print('ss',curr_node.data) if curr_node.data == key: prev.next = curr_node.next curr_node = curr_node.next def lookup(self): curr_node = self.head while curr_node: print(curr_node.data) curr_node = curr_node.next if curr_node == self.head: break circularLls = CircularLinkedList() # circularLls.append(1) # circularLls.append(2) # circularLls.append(3) # circularLls.append(4) # circularLls.prepend(0) # circularLls.prepend(-1) circularLls.delete(1) circularLls.lookup()
class Node: def __init__(self, data): self.data = data self.next = None class Circularlinkedlist: def __init__(self): self.head = None self.tail = None self.length = 0 def append(self, data): new_node = node(data) if not self.head: self.head = new_node self.head.next = self.head else: curr_node = self.head while curr_node.next != self.head: curr_node = curr_node.next curr_node.next = new_node new_node.next = self.head def prepend(self, data): new_node = node(data) curr_node = self.head new_node.next = self.head if not self.head: new_node.next = self.head else: while curr_node.next != self.head: curr_node = curr_node.next curr_node.next = new_node self.head = new_node def delete(self, key): if self.head is None: return if self.head.next == self.head and self.head.data == key: self.head = None elif self.head.data == key: curr_node = self.head while curr_node.next != self.head: curr_node = curr_node.next curr_node.next = self.head.next self.head = self.head.next else: curr_node = self.head prev = None while curr_node.next != self.head: prev = curr_node curr_node = curr_node.next if curr_node.data == key: prev.next = curr_node.next curr_node = curr_node.next def lookup(self): curr_node = self.head while curr_node: print(curr_node.data) curr_node = curr_node.next if curr_node == self.head: break circular_lls = circular_linked_list() circularLls.delete(1) circularLls.lookup()
n = 8 if n%2==0 and (n in range(2,6) or n>20 ): print ("Not Weird") else: print ("Weird")
n = 8 if n % 2 == 0 and (n in range(2, 6) or n > 20): print('Not Weird') else: print('Weird')
routes = Blueprint("routes", __name__, template_folder="templates") if not os.path.exists(os.path.dirname(recipyGui.config.get("tinydb"))): os.mkdir(os.path.dirname(recipyGui.config.get("tinydb"))) @recipyGui.route("/") def index(): form = SearchForm() query = request.args.get("query", "").strip() escaped_query = re.escape(query) if query else query db = utils.open_or_create_db() runs = search_database(db, query=escaped_query) runs = [_change_date(r) for r in runs] runs = sorted(runs, key=lambda x: x["date"], reverse=True) run_ids = [] for run in runs: if "notes" in run.keys(): run["notes"] = str(escape(run["notes"])) run_ids.append(run.eid) db.close() return render_template("list.html", runs=runs, query=escaped_query, search_bar_query=query, form=form, run_ids=str(run_ids), dbfile=recipyGui.config.get("tinydb")) @recipyGui.route("/run_details") def run_details(): form = SearchForm() annotateRunForm = AnnotateRunForm() query = request.args.get("query", "") run_id = int(request.args.get("id")) db = utils.open_or_create_db() r = db.get(eid=run_id) if r is not None: diffs = db.table("filediffs").search(Query().run_id == run_id) else: flash("Run not found.", "danger") diffs = [] r = _change_date(r) db.close() return render_template("details.html", query=query, form=form, annotateRunForm=annotateRunForm, run=r, dbfile=recipyGui.config.get("tinydb"), diffs=diffs) @recipyGui.route("/latest_run") def latest_run(): form = SearchForm() annotateRunForm = AnnotateRunForm() db = utils.open_or_create_db() r = get_latest_run() if r is not None: diffs = db.table("filediffs").search(Query().run_id == r.eid) else: flash("No latest run (database is empty).", "danger") diffs = [] r = _change_date(r) db.close() return render_template("details.html", query="", form=form, run=r, annotateRunForm=annotateRunForm, dbfile=recipyGui.config.get("tinydb"), diffs=diffs, active_page="latest_run") @recipyGui.route("/annotate", methods=["POST"]) def annotate(): notes = request.form["notes"] run_id = int(request.form["run_id"]) query = request.args.get("query", "") db = utils.open_or_create_db() db.update({"notes": notes}, eids=[run_id]) db.close() return redirect(url_for("run_details", id=run_id, query=query)) @recipyGui.route("/runs2json", methods=["POST"]) def runs2json(): run_ids = literal_eval(request.form["run_ids"]) db = db = utils.open_or_create_db() runs = [db.get(eid=run_id) for run_id in run_ids] db.close() response = make_response(dumps(runs, indent=2, sort_keys=True, default=unicode)) response.headers["content-type"] = "application/json" response.headers["Content-Disposition"] = "attachment; filename=runs.json" return response @recipyGui.route("/patched_modules") def patched_modules(): db = utils.open_or_create_db() modules = db.table("patches").all() db.close() form = SearchForm() return render_template("patched_modules.html", form=form, active_page="patched_modules", modules=modules, dbfile=recipyGui.config.get("tinydb"))
routes = blueprint('routes', __name__, template_folder='templates') if not os.path.exists(os.path.dirname(recipyGui.config.get('tinydb'))): os.mkdir(os.path.dirname(recipyGui.config.get('tinydb'))) @recipyGui.route('/') def index(): form = search_form() query = request.args.get('query', '').strip() escaped_query = re.escape(query) if query else query db = utils.open_or_create_db() runs = search_database(db, query=escaped_query) runs = [_change_date(r) for r in runs] runs = sorted(runs, key=lambda x: x['date'], reverse=True) run_ids = [] for run in runs: if 'notes' in run.keys(): run['notes'] = str(escape(run['notes'])) run_ids.append(run.eid) db.close() return render_template('list.html', runs=runs, query=escaped_query, search_bar_query=query, form=form, run_ids=str(run_ids), dbfile=recipyGui.config.get('tinydb')) @recipyGui.route('/run_details') def run_details(): form = search_form() annotate_run_form = annotate_run_form() query = request.args.get('query', '') run_id = int(request.args.get('id')) db = utils.open_or_create_db() r = db.get(eid=run_id) if r is not None: diffs = db.table('filediffs').search(query().run_id == run_id) else: flash('Run not found.', 'danger') diffs = [] r = _change_date(r) db.close() return render_template('details.html', query=query, form=form, annotateRunForm=annotateRunForm, run=r, dbfile=recipyGui.config.get('tinydb'), diffs=diffs) @recipyGui.route('/latest_run') def latest_run(): form = search_form() annotate_run_form = annotate_run_form() db = utils.open_or_create_db() r = get_latest_run() if r is not None: diffs = db.table('filediffs').search(query().run_id == r.eid) else: flash('No latest run (database is empty).', 'danger') diffs = [] r = _change_date(r) db.close() return render_template('details.html', query='', form=form, run=r, annotateRunForm=annotateRunForm, dbfile=recipyGui.config.get('tinydb'), diffs=diffs, active_page='latest_run') @recipyGui.route('/annotate', methods=['POST']) def annotate(): notes = request.form['notes'] run_id = int(request.form['run_id']) query = request.args.get('query', '') db = utils.open_or_create_db() db.update({'notes': notes}, eids=[run_id]) db.close() return redirect(url_for('run_details', id=run_id, query=query)) @recipyGui.route('/runs2json', methods=['POST']) def runs2json(): run_ids = literal_eval(request.form['run_ids']) db = db = utils.open_or_create_db() runs = [db.get(eid=run_id) for run_id in run_ids] db.close() response = make_response(dumps(runs, indent=2, sort_keys=True, default=unicode)) response.headers['content-type'] = 'application/json' response.headers['Content-Disposition'] = 'attachment; filename=runs.json' return response @recipyGui.route('/patched_modules') def patched_modules(): db = utils.open_or_create_db() modules = db.table('patches').all() db.close() form = search_form() return render_template('patched_modules.html', form=form, active_page='patched_modules', modules=modules, dbfile=recipyGui.config.get('tinydb'))
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: a = headA b = headB while a != b: if a: a = a.next else: a = headB if b: b = b.next else: b = headA return a
class Solution: def get_intersection_node(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: a = headA b = headB while a != b: if a: a = a.next else: a = headB if b: b = b.next else: b = headA return a
def reformat(string): string = string.replace('-', '').replace('(', '').replace(')', '') return string[-10:] if len(string) > 7 else '495' + string[-7:] n = 4 notes = [input() for i in range(n)] for note in notes[1:]: print('YES' if reformat(notes[0]) == reformat(note) else 'NO')
def reformat(string): string = string.replace('-', '').replace('(', '').replace(')', '') return string[-10:] if len(string) > 7 else '495' + string[-7:] n = 4 notes = [input() for i in range(n)] for note in notes[1:]: print('YES' if reformat(notes[0]) == reformat(note) else 'NO')
class SQLiteQueryResultSpy(object): def __init__(self, row_count, lazy_result): self.row_count = row_count self.number_of_elements = row_count self.lazy_result = lazy_result @property def rowcount(self): return self.row_count def fetchone(self): self.number_of_elements -= 1 if self.number_of_elements < 0: return None return self.lazy_result()
class Sqlitequeryresultspy(object): def __init__(self, row_count, lazy_result): self.row_count = row_count self.number_of_elements = row_count self.lazy_result = lazy_result @property def rowcount(self): return self.row_count def fetchone(self): self.number_of_elements -= 1 if self.number_of_elements < 0: return None return self.lazy_result()
def odeeuler(F,x0,y0,h,N): x = x0 y = y0 for i in range(1,N+1): y += h*F(x,y) x += h return y
def odeeuler(F, x0, y0, h, N): x = x0 y = y0 for i in range(1, N + 1): y += h * f(x, y) x += h return y
REQUEST_LAUNCH_MSG = "Hello, I'm Otto Investment bot, I' here to inform you about your investments. Do you want me to tell you a report on your portfolio? Or maybe information about specific stock? " REQUEST_LAUNCH_REPROMPT = "Go on, tell me what can I do for you." REQUEST_END_MSG = "Bye bye. " # General INTENT_GENERAL_OK = "Ok then." INTENT_GENERAL_REPROMPT = "Is there something else I can help you with?" # Help INTENT_HELP = "Looks like you are confused. You can ask about a stock price, market cap of a company, add and remove stocks from virtual portfolio. Get a performance report on your portfolio. You can also get an investing term explained or a investing strategy. You can even ask bout the news regarding a traded company. What would like to do?" # Price INTENT_STOCK_PRICE_MSG = "The price of {0} is ${1}." INTENT_STOCK_PRICE_MSG_FAIL = "Sorry, there was a problem getting data for {}" # Market Cap INTENT_MARKET_CAP_MSG = "The Market Cap of {0} is ${1}." INTENT_MARKET_CAP_MSG_FAIL = "Sorry, there was a problem getting market capitalization for {}" # Investing Strategy INTENT_INVEST_STRAT_MSG = "Here is a example of investing strategy, this one is called {}. {}" # Watchlist INTENT_WATCHLIST_REPORT_TOP_STOCK = "The best performing stock is {} which is {} {:.2f}%. " INTENT_WATCHLIST_REPORT_WORST_STOCK = "The worst performing stock is {} which is {} {:.2f}%. " INTENT_WATCHLIST_REPORT_MSG_INTRO = "Here is your watchlist:" INTENT_WATCHLIST_REPORT_MSG_BODY = " Stock {} is {} {:.2f}%. " INTENT_WATCHLIST_EMPTY_MSG = "Your watchlist is empty. " INTENT_ADD_TO_WATCHLIST_ASK_CONFIRMATION = "Should I add stock {}? " INTENT_ADD_TO_WATCHLIST_DENIED = "Ok, not adding it. " INTENT_ADD_TO_WATCHLIST_CONFIRMED = "Ok, adding {} to watchlist. " INTENT_ADDED_TO_WATCHLIST = "Stock {} was added to watchlist. " INTENT_ADDED_TO_WATCHLIST_EXISTS = "Stock {} is already in your watchlist. " INTENT_ADDED_TO_WATCHLIST_FAIL = "Couldn't add stock to watchlist. " INTENT_REMOVE_FROM_WATCHLIST_ASK_CONFIRMATION = "Should I remove {}? " INTENT_REMOVE_FROM_WATCHLIST_DENIED = "Ok, not removing it. " INTENT_REMOVE_FROM_WATCHLIST_CONFIRMED = "Ok, removing {} from watchlist. " INTENT_REMOVE_FROM_WATCHLIST_NOT_THERE = "There is no stock {} in your watchlist. " INTENT_REMOVE_FROM_WATCHLIST_FAIL = "Couldn't remove stock from watchlist. " # Education INTENT_EDU_IN_CONSTRUCTION = "Can't explain {} right now." # News INTENT_NEWS_ABOUT_COMPANY_INTRO = "Here are some articles mentioning {}: " INTENT_NEWS_ABOUT_COMPANY_ASK_MORE_INFO = "Should I send you a link to one of the articles? " INTENT_NEWS_ABOUT_COMPANY_ASK_ARTICLE_NO = "Which one? " INTENT_NEWS_ABOUT_COMPANY_FAIL_ARTICLE_NOT_FOUND = "Sorry, couldn't find this article. " INTENT_NEWS_ABOUT_COMPANY_ARTICLE_SENT = "Article was sent to your device. " INTENT_NEWS_ABOUT_COMPANY_ARTICLE_CARD_TITLE = "Article about {}" INTENT_NEWS_ABOUT_COMPANY_ARTICLE_CARD_CONTENT = "{}" # Analytics recommendation INTENT_RCMD_NO_RCMD = "There is no analyst recommendation for this stock." INTENT_RCMD_STRONG_BUY = "The analysts are strongly suggesting to buy this stock." INTENT_RCMD_BUY = "The analysts are suggesting to consider buying this stock." INTENT_RCMD_OPT_HOLD = "The analysts are somewhat optimistic, they are torn between holding or even buying this stock." INTENT_RCMD_HOLD = "The analysts suggest not making any decisions just yet, you should hold to this stock." INTENT_RCMD_PES_HOLD = "The analysts are worried about this one, they suggest holding, whit some intentions to selling." INTENT_RCMD_SELL = "The stock has been underperforming, analysts suggest considering selling." INTENT_RCMD_STRONG_SELL = "The analysts strongly suggest selling this stock." # Error states ERROR_NOT_AUTHENTICATED = "First you need to authenticate in the Alexa App." ERROR_NOT_AUTHENTICATED_REPROMPT = "Please go to the Alexa App and link your Facebook account to use this feature." ERROR_CANT_ADD_TO_WATCHLIST = "Sorry, I wasn't able to add stock {} to watchlist." ERROR_NEWS_BAD_TICKER = "Sorry it is not possible to get news for this company." ERROR_NEWS_NO_NEWS = "Sorry, there are now news for company {}"
request_launch_msg = "Hello, I'm Otto Investment bot, I' here to inform you about your investments. Do you want me to tell you a report on your portfolio? Or maybe information about specific stock? " request_launch_reprompt = 'Go on, tell me what can I do for you.' request_end_msg = 'Bye bye. ' intent_general_ok = 'Ok then.' intent_general_reprompt = 'Is there something else I can help you with?' intent_help = 'Looks like you are confused. You can ask about a stock price, market cap of a company, add and remove stocks from virtual portfolio. Get a performance report on your portfolio. You can also get an investing term explained or a investing strategy. You can even ask bout the news regarding a traded company. What would like to do?' intent_stock_price_msg = 'The price of {0} is ${1}.' intent_stock_price_msg_fail = 'Sorry, there was a problem getting data for {}' intent_market_cap_msg = 'The Market Cap of {0} is ${1}.' intent_market_cap_msg_fail = 'Sorry, there was a problem getting market capitalization for {}' intent_invest_strat_msg = 'Here is a example of investing strategy, this one is called {}. {}' intent_watchlist_report_top_stock = 'The best performing stock is {} which is {} {:.2f}%. ' intent_watchlist_report_worst_stock = 'The worst performing stock is {} which is {} {:.2f}%. ' intent_watchlist_report_msg_intro = 'Here is your watchlist:' intent_watchlist_report_msg_body = ' Stock {} is {} {:.2f}%. ' intent_watchlist_empty_msg = 'Your watchlist is empty. ' intent_add_to_watchlist_ask_confirmation = 'Should I add stock {}? ' intent_add_to_watchlist_denied = 'Ok, not adding it. ' intent_add_to_watchlist_confirmed = 'Ok, adding {} to watchlist. ' intent_added_to_watchlist = 'Stock {} was added to watchlist. ' intent_added_to_watchlist_exists = 'Stock {} is already in your watchlist. ' intent_added_to_watchlist_fail = "Couldn't add stock to watchlist. " intent_remove_from_watchlist_ask_confirmation = 'Should I remove {}? ' intent_remove_from_watchlist_denied = 'Ok, not removing it. ' intent_remove_from_watchlist_confirmed = 'Ok, removing {} from watchlist. ' intent_remove_from_watchlist_not_there = 'There is no stock {} in your watchlist. ' intent_remove_from_watchlist_fail = "Couldn't remove stock from watchlist. " intent_edu_in_construction = "Can't explain {} right now." intent_news_about_company_intro = 'Here are some articles mentioning {}: ' intent_news_about_company_ask_more_info = 'Should I send you a link to one of the articles? ' intent_news_about_company_ask_article_no = 'Which one? ' intent_news_about_company_fail_article_not_found = "Sorry, couldn't find this article. " intent_news_about_company_article_sent = 'Article was sent to your device. ' intent_news_about_company_article_card_title = 'Article about {}' intent_news_about_company_article_card_content = '{}' intent_rcmd_no_rcmd = 'There is no analyst recommendation for this stock.' intent_rcmd_strong_buy = 'The analysts are strongly suggesting to buy this stock.' intent_rcmd_buy = 'The analysts are suggesting to consider buying this stock.' intent_rcmd_opt_hold = 'The analysts are somewhat optimistic, they are torn between holding or even buying this stock.' intent_rcmd_hold = 'The analysts suggest not making any decisions just yet, you should hold to this stock.' intent_rcmd_pes_hold = 'The analysts are worried about this one, they suggest holding, whit some intentions to selling.' intent_rcmd_sell = 'The stock has been underperforming, analysts suggest considering selling.' intent_rcmd_strong_sell = 'The analysts strongly suggest selling this stock.' error_not_authenticated = 'First you need to authenticate in the Alexa App.' error_not_authenticated_reprompt = 'Please go to the Alexa App and link your Facebook account to use this feature.' error_cant_add_to_watchlist = "Sorry, I wasn't able to add stock {} to watchlist." error_news_bad_ticker = 'Sorry it is not possible to get news for this company.' error_news_no_news = 'Sorry, there are now news for company {}'
# A string index should always be within range s = "Hello" print(s[5]) # Syntax error - valid indices for s are 0-4
s = 'Hello' print(s[5])
#!/anaconda3/bin/python3.6 # coding=utf-8 if __name__ == "__main__": print("suppliermgr package")
if __name__ == '__main__': print('suppliermgr package')
# encoding: utf-8 # Copyright 2008 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. ''' EDRN RDF Service: unit and functional tests. '''
""" EDRN RDF Service: unit and functional tests. """
with open("input.txt") as input_file: lines = input_file.readlines() fish = [int(n) for n in lines[0].split(",")] print(fish) for _ in range(80): fish = [f-1 for f in fish] zeroes = fish.count(-1) for i, f in enumerate(fish): if f == -1: fish[i] = 6 fish.extend([8]*zeroes) print(len(fish))
with open('input.txt') as input_file: lines = input_file.readlines() fish = [int(n) for n in lines[0].split(',')] print(fish) for _ in range(80): fish = [f - 1 for f in fish] zeroes = fish.count(-1) for (i, f) in enumerate(fish): if f == -1: fish[i] = 6 fish.extend([8] * zeroes) print(len(fish))
def test_first(setup_teardown): text_logo = setup_teardown.find_element_by_id('logo').text assert text_logo == 'Your Store'
def test_first(setup_teardown): text_logo = setup_teardown.find_element_by_id('logo').text assert text_logo == 'Your Store'
def calculaMulta (velocidade): if velocidade > 50 and velocidade < 55: return 230 elif velocidade > 55 and velocidade <= 60: return 340 elif velocidade > 60: valor = (velocidade-50) * 19.28 return valor else: return 0 vel = int(input("Informe a velocidade :")) print(calculaMulta(vel))
def calcula_multa(velocidade): if velocidade > 50 and velocidade < 55: return 230 elif velocidade > 55 and velocidade <= 60: return 340 elif velocidade > 60: valor = (velocidade - 50) * 19.28 return valor else: return 0 vel = int(input('Informe a velocidade :')) print(calcula_multa(vel))
class Solution: def removeElement(self, nums: List[int], val: int) -> int: for numbers in range(len(nums)): if val not in nums: break if len(nums) == 0: return 0 else: nums.remove(val) print(len(nums)) print ("nums = ",nums)
class Solution: def remove_element(self, nums: List[int], val: int) -> int: for numbers in range(len(nums)): if val not in nums: break if len(nums) == 0: return 0 else: nums.remove(val) print(len(nums)) print('nums = ', nums)
# import matplotlib.pyplot as plt # Menge an Werten zahlen = "1203456708948673516874354531568764645" # Initialisieren der Histogramm Variable histogramm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for index in range(len(zahlen)): histogramm[int(zahlen[index])] += 1 # plt.hist(histogramm, bins = 9) # plt.show() for i in range(0,10): print("Die Zahl", i, "kommt", histogramm[i], "Mal vor.")
zahlen = '1203456708948673516874354531568764645' histogramm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for index in range(len(zahlen)): histogramm[int(zahlen[index])] += 1 for i in range(0, 10): print('Die Zahl', i, 'kommt', histogramm[i], 'Mal vor.')
#!/usr/bin/env pytho codigo = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '.': '.-.-.-', ',': '--..--', ':': '---...', ';': '-.-.-.', '?': '..--..', '!': '-.-.--', '"': '.-..-.', "'": '.----.', '+': '.-.-.', '-': '-....-', '/': '-..-.', '=': '-...-', '_': '..--.-', '$': '...-..-', '@': '.--.-.', '&': '.-...', '(': '-.--.', ')': '-.--.-' } palabra = input("Palabra:") lista_codigos = [] for caracter in palabra: if caracter.islower(): caracter=caracter.upper() lista_codigos.append(codigo[caracter]) print (" ".join(lista_codigos)) morse=input("Morse:") lista_morse=morse.split(" ") palabra = "" for cod in lista_morse: #letra=[key for key,valor in codigo.items() if valor==cod][0] for key,valor in codigo.items(): if valor == cod: letra = key palabra=palabra+letra print (palabra)
codigo = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '.': '.-.-.-', ',': '--..--', ':': '---...', ';': '-.-.-.', '?': '..--..', '!': '-.-.--', '"': '.-..-.', "'": '.----.', '+': '.-.-.', '-': '-....-', '/': '-..-.', '=': '-...-', '_': '..--.-', '$': '...-..-', '@': '.--.-.', '&': '.-...', '(': '-.--.', ')': '-.--.-'} palabra = input('Palabra:') lista_codigos = [] for caracter in palabra: if caracter.islower(): caracter = caracter.upper() lista_codigos.append(codigo[caracter]) print(' '.join(lista_codigos)) morse = input('Morse:') lista_morse = morse.split(' ') palabra = '' for cod in lista_morse: for (key, valor) in codigo.items(): if valor == cod: letra = key palabra = palabra + letra print(palabra)
class Cloth: def __init__(self, name, shop_url, available, brand_logo, price, img_url): self.name = name self.shop_url = shop_url self.available = available self.brand_logo = brand_logo self.price = price self.img_url = img_url def __str__(self): print('Name: {0}\nBrand: {1}\nPrice: {2}\nAvailable: {3}, Link to the shop: {4}'.format(self.name, self.brand, self.price, self.available, self.shop_url))
class Cloth: def __init__(self, name, shop_url, available, brand_logo, price, img_url): self.name = name self.shop_url = shop_url self.available = available self.brand_logo = brand_logo self.price = price self.img_url = img_url def __str__(self): print('Name: {0}\nBrand: {1}\nPrice: {2}\nAvailable: {3}, Link to the shop: {4}'.format(self.name, self.brand, self.price, self.available, self.shop_url))
def pickingNumbers(a): solution = 0 for num1 in a: if a.count(num1) + a.count(num1 + 1) > solution: solution = a.count(num1) + a.count(num1 + 1) return solution
def picking_numbers(a): solution = 0 for num1 in a: if a.count(num1) + a.count(num1 + 1) > solution: solution = a.count(num1) + a.count(num1 + 1) return solution
# while loops def nearest_square(limit): number = 0 while (number+1) ** 2 < limit: number += 1 return number ** 2 test1 = nearest_square(40) print("expected result: 36, actual result: {}".format(test1)) # black jack card_deck = [4, 11, 8, 5, 13, 2, 8, 10] hand = [] while sum(hand) <= 21: hand.append(card_deck.pop()) #removes from deck print(hand) # headline ticker for news, up to 140 chars headlines = ["Local Bear Eaten by Man", "Legislature Announces New Laws", "Peasant Discovers Violence Inherent in System", "Cat Rescues Fireman Stuck in Tree", "Brave Knight Runs Away", "Papperbok Review: Totally Triffic"] news_ticker = "" for headline in headlines: if len(news_ticker) + len(headline) <= 140: news_ticker += headline + " " else: for letter in headline: if len(news_ticker) < 140: news_ticker += letter else: break; print(news_ticker) # alternative for above, shorter news_ticker = "" for headline in headlines: news_ticker += headline + " " if len(news_ticker) >= 140: # just take first 140 after creating full news_ticker = news_ticker[:140] break; print(news_ticker)
def nearest_square(limit): number = 0 while (number + 1) ** 2 < limit: number += 1 return number ** 2 test1 = nearest_square(40) print('expected result: 36, actual result: {}'.format(test1)) card_deck = [4, 11, 8, 5, 13, 2, 8, 10] hand = [] while sum(hand) <= 21: hand.append(card_deck.pop()) print(hand) headlines = ['Local Bear Eaten by Man', 'Legislature Announces New Laws', 'Peasant Discovers Violence Inherent in System', 'Cat Rescues Fireman Stuck in Tree', 'Brave Knight Runs Away', 'Papperbok Review: Totally Triffic'] news_ticker = '' for headline in headlines: if len(news_ticker) + len(headline) <= 140: news_ticker += headline + ' ' else: for letter in headline: if len(news_ticker) < 140: news_ticker += letter else: break print(news_ticker) news_ticker = '' for headline in headlines: news_ticker += headline + ' ' if len(news_ticker) >= 140: news_ticker = news_ticker[:140] break print(news_ticker)
A_1,B_1 = input().split(" ") a = int(A_1) b = int(B_1) if a > b: horas = (24-a) + b print("O JOGO DUROU %i HORA(S)"%(horas)) elif a == b: print("O JOGO DUROU 24 HORA(S)") else: horas = b - a print("O JOGO DUROU %i HORA(S)"%(horas))
(a_1, b_1) = input().split(' ') a = int(A_1) b = int(B_1) if a > b: horas = 24 - a + b print('O JOGO DUROU %i HORA(S)' % horas) elif a == b: print('O JOGO DUROU 24 HORA(S)') else: horas = b - a print('O JOGO DUROU %i HORA(S)' % horas)
# https://app.codesignal.com/arcade/code-arcade/well-of-integration/QmK8kHTyKqh8xDoZk def threeSplit(numbers): # From a list of numbers, cut into three pieces such that each # piece contains an integer, and the sum of integers in each # piece is the same. # We know that the total sum of elements in the array is divisible by 3. # So any 3 segments it can be divided into must have sum total/3. total = sum(numbers) third = total / 3 # The count of starts, this is, places where it adds to a third. start_count = 0 # Acum so far of values in the array. acum_sum = 0 # Result which will hold the amount of ways the array can be split into 3 equally. result = 0 for idx in range(len(numbers) - 1): # Keep accumulating values. acum_sum += numbers[idx] # A second splitting point is if up to this point it adds to two thirds. # Checked before the start point for the case in which a third of the total # is equal to two thirds, because the total added up to 0. Also for a second # splitting point to be valid, there has to be at least one starting point. if acum_sum == 2 * third and start_count > 0: # Any "second splitting point" found will work with any of the previously # found "starting splitting points", so add up the amount of such points # found until the current one. result += start_count # A starting splitting point is if up to this point it adds up to a third. if acum_sum == third: start_count += 1 return result
def three_split(numbers): total = sum(numbers) third = total / 3 start_count = 0 acum_sum = 0 result = 0 for idx in range(len(numbers) - 1): acum_sum += numbers[idx] if acum_sum == 2 * third and start_count > 0: result += start_count if acum_sum == third: start_count += 1 return result
def elevadorLotado(paradas, capacidade): energiaGasta = 0 while paradas: ultimo = paradas[-1] energiaGasta += 2*ultimo paradas = paradas[:-capacidade] return energiaGasta testes = int(input()) for x in range(testes): NCM = input().split() capacidade = int(NCM[1]) destinhos = list(map(int,input().split())) destinhos.sort() s = elevadorLotado(destinhos, capacidade) print(s)
def elevador_lotado(paradas, capacidade): energia_gasta = 0 while paradas: ultimo = paradas[-1] energia_gasta += 2 * ultimo paradas = paradas[:-capacidade] return energiaGasta testes = int(input()) for x in range(testes): ncm = input().split() capacidade = int(NCM[1]) destinhos = list(map(int, input().split())) destinhos.sort() s = elevador_lotado(destinhos, capacidade) print(s)
with open('EN_op_1_57X32A15_31.csv','r') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row[1])
with open('EN_op_1_57X32A15_31.csv', 'r') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row[1])
chars = { 'A': ['010', '101', '111', '101', '101'], 'B': ['110', '101', '111', '101', '110'], 'C': ['011', '100', '100', '100', '011'], 'D': ['110', '101', '101', '101', '110'], 'E': ['111', '100', '111', '100', '111'], 'F': ['111', '100', '111', '100', '100'], 'G': ['0111', '1000', '1011', '1001', '0110'], 'H': ['101', '101', '111', '101', '101'], 'I': ['111', '010', '010', '010', '111'], 'J': ['111', '010', '010', '010', '110'], 'K': ['1001', '1010', '1100', '1010', '1001'], 'L': ['100', '100', '100', '100', '111'], 'M': ['10001', '11011', '10101', '10001', '10001'], 'N': ['1001', '1101', '1111', '1011', '1001'], 'O': ['010', '101', '101', '101', '010'], 'P': ['110', '101', '110', '100', '100'], 'Q': ['0110', '1001', '1001', '1011', '0111'], 'R': ['110', '101', '110', '101', '101'], 'S': ['011', '100', '011', '001', '110'], 'T': ['111', '010', '010', '010', '010'], 'U': ['101', '101', '101', '101', '010'], 'V': ['10001', '10001', '10001', '01010', '00100'], 'W': ['10001', '10001', '10101', '11011', '10001'], 'X': ['1001', '0110', '0110', '0110', '1001'], 'Y': ['101', '101', '010', '010', '010'], 'Z': ['1111', '0010', '0100', '1000', '1111'], '.': ['0', '0', '0', '0', '1'], ':': ['0', '1', '0', '1', '0'], '!': ['1', '1', '1', '0', '1'], '?': ['01110', '10001', '00110', '00000', '00100'], '\'': ['11', '11', '00', '00', '00'], '\"': ['11', '00', '00', '00', '00'], ' ': ['0', '0', '0', '0', '0'], ',': ['00', '00', '00', '01', '11'], '/': ['001', '011', '010', '110', '100'], '\\': ['100', '110', '010', '011', '001'], '0': ['010', '101', '101', '101', '010'], '1': ['010', '110', '010', '010', '111'], '2': ['011', '101', '010', '100', '111'], '3': ['111', '001', '111', '001', '111'], '4': ['011', '101', '111', '001', '001'], '5': ['111', '100', '111', '001', '111'], '6': ['111', '100', '111', '101', '111'], '7': ['111', '001', '010', '100', '100'], '8': ['111', '101', '111', '101', '111'], '9': ['111', '101', '111', '001', '111'] } def get_mapping(string): global chars mapping = ['','','','',''] string = string.upper() for char in string: if char in chars: char_mapping = chars[char] else: char_mapping = ['0','0','0','0','0'] mapping = [ mapping[0] + char_mapping[0] + '0', mapping[1] + char_mapping[1] + '0', mapping[2] + char_mapping[2] + '0', mapping[3] + char_mapping[3] + '0', mapping[4] + char_mapping[4] + '0' ] return mapping
chars = {'A': ['010', '101', '111', '101', '101'], 'B': ['110', '101', '111', '101', '110'], 'C': ['011', '100', '100', '100', '011'], 'D': ['110', '101', '101', '101', '110'], 'E': ['111', '100', '111', '100', '111'], 'F': ['111', '100', '111', '100', '100'], 'G': ['0111', '1000', '1011', '1001', '0110'], 'H': ['101', '101', '111', '101', '101'], 'I': ['111', '010', '010', '010', '111'], 'J': ['111', '010', '010', '010', '110'], 'K': ['1001', '1010', '1100', '1010', '1001'], 'L': ['100', '100', '100', '100', '111'], 'M': ['10001', '11011', '10101', '10001', '10001'], 'N': ['1001', '1101', '1111', '1011', '1001'], 'O': ['010', '101', '101', '101', '010'], 'P': ['110', '101', '110', '100', '100'], 'Q': ['0110', '1001', '1001', '1011', '0111'], 'R': ['110', '101', '110', '101', '101'], 'S': ['011', '100', '011', '001', '110'], 'T': ['111', '010', '010', '010', '010'], 'U': ['101', '101', '101', '101', '010'], 'V': ['10001', '10001', '10001', '01010', '00100'], 'W': ['10001', '10001', '10101', '11011', '10001'], 'X': ['1001', '0110', '0110', '0110', '1001'], 'Y': ['101', '101', '010', '010', '010'], 'Z': ['1111', '0010', '0100', '1000', '1111'], '.': ['0', '0', '0', '0', '1'], ':': ['0', '1', '0', '1', '0'], '!': ['1', '1', '1', '0', '1'], '?': ['01110', '10001', '00110', '00000', '00100'], "'": ['11', '11', '00', '00', '00'], '"': ['11', '00', '00', '00', '00'], ' ': ['0', '0', '0', '0', '0'], ',': ['00', '00', '00', '01', '11'], '/': ['001', '011', '010', '110', '100'], '\\': ['100', '110', '010', '011', '001'], '0': ['010', '101', '101', '101', '010'], '1': ['010', '110', '010', '010', '111'], '2': ['011', '101', '010', '100', '111'], '3': ['111', '001', '111', '001', '111'], '4': ['011', '101', '111', '001', '001'], '5': ['111', '100', '111', '001', '111'], '6': ['111', '100', '111', '101', '111'], '7': ['111', '001', '010', '100', '100'], '8': ['111', '101', '111', '101', '111'], '9': ['111', '101', '111', '001', '111']} def get_mapping(string): global chars mapping = ['', '', '', '', ''] string = string.upper() for char in string: if char in chars: char_mapping = chars[char] else: char_mapping = ['0', '0', '0', '0', '0'] mapping = [mapping[0] + char_mapping[0] + '0', mapping[1] + char_mapping[1] + '0', mapping[2] + char_mapping[2] + '0', mapping[3] + char_mapping[3] + '0', mapping[4] + char_mapping[4] + '0'] return mapping
SAGA_ENABLED = 1 MIN_DETECTED_FACE_WIDTH = 20 MIN_DETECTED_FACE_HEIGHT = 20 PICKLE_FILES_DIR = "/app/facenet/resources/output" MODEL_FILES_DIR = "/app/facenet/resources/model" UPLOAD_DIR = "/app/resources/images/" # PICKLE_FILES_DIR = '/Users/ashishgupta/git/uPresent/face-recognition/resources/output' # MODEL_FILES_DIR = '/Users/ashishgupta/git/uPresent/face-recognition/resources/model' # UPLOAD_DIR = '/Users/ashishgupta/git/uPresent/face-recognition/resources/images/' # DATASET_PATH = '/Users/anchitseth/Desktop/facenet-data-vol/dataset' # PICKLE_FILES_DIR = '/Users/anchitseth/Desktop/facenet-data-vol/output' # MODEL_FILES_DIR = '/Users/anchitseth/Desktop/facenet-data-vol/model'
saga_enabled = 1 min_detected_face_width = 20 min_detected_face_height = 20 pickle_files_dir = '/app/facenet/resources/output' model_files_dir = '/app/facenet/resources/model' upload_dir = '/app/resources/images/'
class Contact: def __init__(self, first_name: str, second_name: str, phone_number: str): self._first_name = first_name self._second_name = second_name self._phone_number = phone_number @property def first_name(self): return self._first_name @property def second_name(self): return self._second_name @property def phone_number(self): return self._phone_number @first_name.setter def first_name(self, name: str): self._first_name = name @second_name.setter def second_name(self, surname: str): self._second_name = surname @phone_number.setter def phone_number(self, number: str): self._phone_number = number
class Contact: def __init__(self, first_name: str, second_name: str, phone_number: str): self._first_name = first_name self._second_name = second_name self._phone_number = phone_number @property def first_name(self): return self._first_name @property def second_name(self): return self._second_name @property def phone_number(self): return self._phone_number @first_name.setter def first_name(self, name: str): self._first_name = name @second_name.setter def second_name(self, surname: str): self._second_name = surname @phone_number.setter def phone_number(self, number: str): self._phone_number = number
def answer(l): res = 0 length = len(l) for x in xrange(length): left = 0 right = 0 for i in xrange(x): if not (l[x] % l[i]): left = left + 1 for i in xrange(x + 1, length): if not (l[i] % l[x]): right = right + 1 res = res + left * right return res # Provided test cases. assert(answer([1, 1, 1]) == 1) assert(answer([1, 2, 3, 4, 5, 6]) == 3) # Custom test cases. assert(answer([1]) == 0) assert(answer([1, 2]) == 0) assert(answer([2, 4]) == 0) assert(answer([1, 1, 1, 1]) == 4) assert(answer([1, 1, 1, 1, 1]) == 10) assert(answer([1, 1, 1, 1, 1, 1]) == 20) assert(answer([1, 1, 1, 1, 1, 1, 1]) == 35) assert(answer([1, 1, 2]) == 1) assert(answer([1, 1, 2, 2]) == 4) assert(answer([1, 1, 2, 2, 2]) == 10) assert(answer([1, 1, 2, 2, 2, 3]) == 11) assert(answer([1, 2, 4, 8, 16]) == 10) assert(answer([2, 4, 5, 9, 12, 34, 45]) == 1) assert(answer([2, 2, 2, 2, 4, 4, 5, 6, 8, 8, 8]) == 90) assert(answer([2, 4, 8]) == 1) assert(answer([2, 4, 8, 16]) == 4) assert(answer([3, 4, 2, 7]) == 0) assert(answer([6, 5, 4, 3, 2, 1]) == 0) assert(answer([4, 7, 14]) == 0) assert(answer([4, 21, 7, 14, 8, 56, 56, 42]) == 9) assert(answer([4, 21, 7, 14, 56, 8, 56, 4, 42]) == 7) assert(answer([4, 7, 14, 8, 21, 56, 42]) == 4) assert(answer([4, 8, 4, 16]) == 2)
def answer(l): res = 0 length = len(l) for x in xrange(length): left = 0 right = 0 for i in xrange(x): if not l[x] % l[i]: left = left + 1 for i in xrange(x + 1, length): if not l[i] % l[x]: right = right + 1 res = res + left * right return res assert answer([1, 1, 1]) == 1 assert answer([1, 2, 3, 4, 5, 6]) == 3 assert answer([1]) == 0 assert answer([1, 2]) == 0 assert answer([2, 4]) == 0 assert answer([1, 1, 1, 1]) == 4 assert answer([1, 1, 1, 1, 1]) == 10 assert answer([1, 1, 1, 1, 1, 1]) == 20 assert answer([1, 1, 1, 1, 1, 1, 1]) == 35 assert answer([1, 1, 2]) == 1 assert answer([1, 1, 2, 2]) == 4 assert answer([1, 1, 2, 2, 2]) == 10 assert answer([1, 1, 2, 2, 2, 3]) == 11 assert answer([1, 2, 4, 8, 16]) == 10 assert answer([2, 4, 5, 9, 12, 34, 45]) == 1 assert answer([2, 2, 2, 2, 4, 4, 5, 6, 8, 8, 8]) == 90 assert answer([2, 4, 8]) == 1 assert answer([2, 4, 8, 16]) == 4 assert answer([3, 4, 2, 7]) == 0 assert answer([6, 5, 4, 3, 2, 1]) == 0 assert answer([4, 7, 14]) == 0 assert answer([4, 21, 7, 14, 8, 56, 56, 42]) == 9 assert answer([4, 21, 7, 14, 56, 8, 56, 4, 42]) == 7 assert answer([4, 7, 14, 8, 21, 56, 42]) == 4 assert answer([4, 8, 4, 16]) == 2
# NOTE: The sitename and dataname corresponding to the observation are 'y' by default # Any latents that are not population level model_constants = { 'arm.anova_radon_nopred': { 'population_effects':{'mu_a', 'sigma_a', 'sigma_y'}, 'ylims':(1000, 5000), 'ylims_zoomed':(1000, 1200) }, 'arm.anova_radon_nopred_chr': { 'population_effects':{'sigma_a', 'sigma_y', 'mu_a'}, 'ylims':(1000, 5000), 'ylims_zoomed':(1000, 1200) }, 'arm.congress': { 'population_effects':{'beta', 'sigma'}, 'sitename':'vote_88', 'dataname':'vote_88', 'ylims':(1000, 5000), # CHANGE! 'ylims_zoomed':(1000, 1200) # CHANGE! }, 'arm.earnings_latin_square': { 'population_effects':{"sigma_a1", "sigma_a2", "sigma_b1", "sigma_b2", "sigma_c", "sigma_d", "sigma_y", 'mu_a1', 'mu_a2', 'mu_b1', 'mu_b2', 'mu_c', 'mu_d'}, 'ylims':(800, 5000), 'ylims_zoomed':(800, 5000) }, 'arm.earnings_latin_square_chr': { 'population_effects':{"sigma_a1", "sigma_a2", "sigma_b1", "sigma_b2", "sigma_c", "sigma_d", "sigma_y", 'mu_a1', 'mu_a2', 'mu_b1', 'mu_b2', 'mu_c', 'mu_d'}, 'ylims':(800, 5000), 'ylims_zoomed':(800, 5000) }, 'arm.earnings_vary_si': { 'population_effects':{"sigma_a1", "sigma_a2", "sigma_y", "mu_a1", "mu_a2"}, 'sitename':'log_earn', 'dataname':'log_earn', 'ylims':(800, 5000), # CHANGE! 'ylims_zoomed':(800, 5000) # CHANGE! }, 'arm.earnings_vary_si_chr': { 'population_effects':{"sigma_a1", "sigma_a2", "sigma_y", "mu_a1", "mu_a2"}, 'sitename':'log_earn', 'dataname':'log_earn', 'ylims':(800, 5000), # CHANGE! 'ylims_zoomed':(800, 5000) # CHANGE! }, 'arm.earnings1': { 'population_effects':{"sigma", "beta"}, 'sitename':'earn_pos', 'dataname':'earn_pos', 'ylims':(800, 5000), # CHANGE! 'ylims_zoomed':(800, 5000) # CHANGE! }, 'arm.earnings2': { 'population_effects':{"sigma", "beta"}, 'sitename':'log_earnings', 'dataname':'log_earnings', 'ylims':(800, 5000), # CHANGE! 'ylims_zoomed':(800, 5000) # CHANGE! }, 'arm.election88_ch14': { 'population_effects':{'mu_a', 'sigma_a', 'b'}, 'ylims':(1200, 2000), 'ylims_zoomed':(1200, 1400) }, 'arm.election88_ch19': { 'population_effects':{'beta', 'mu_age', 'sigma_age', 'mu_edu', 'sigma_edu', 'mu_age_edu', 'sigma_age_edu', 'mu_region', 'sigma_region', 'b_v_prev'}, 'ylims':(1200, 2000), # CHANGE! 'ylims_zoomed':(1200, 1400) # CHANGE! }, 'arm.electric': { 'population_effects':{'beta', 'mu_a', 'sigma_a', 'sigma_y'}, 'ylims':(1200, 2000), # CHANGE! 'ylims_zoomed':(1200, 1400) # CHANGE! }, 'arm.electric_1a': { 'population_effects':set(), 'ylims':(1200, 2000), # CHANGE! 'ylims_zoomed':(1200, 1400) # CHANGE! }, 'arm.hiv': { 'population_effects':{'mu_a1', 'sigma_a1', 'mu_a2', 'sigma_a2', 'sigma_y'}, 'ylims':(1200, 2000), # CHANGE! 'ylims_zoomed':(1200, 1400) # CHANGE! }, 'arm.wells_dist': { 'population_effects':{'beta'}, 'sitename':'switched', 'dataname':'switched', 'ylims':(2000, 7500), 'ylims_zoomed':(2000, 2500) }, 'arm.wells_dae_inter_c': { 'population_effects':{'beta'}, 'sitename':'switched', 'dataname':'switched', 'ylims':(1800, 4000), 'ylims_zoomed':(1800, 2200) }, 'arm.radon_complete_pool': { 'population_effects':{'beta', 'sigma'}, 'ylims':(1000, 4000), 'ylims_zoomed':(1000, 1400) }, 'arm.radon_group': { 'population_effects':{'beta', 'sigma', 'mu_alpha', 'sigma_alpha', 'mu_beta', 'sigma_beta'}, 'ylims':(1000, 4000), 'ylims_zoomed':(1000, 1200), }, 'arm.radon_inter_vary': { 'population_effects':{'beta', 'sigma_y', 'sigma_a', 'sigma_b', 'sigma_beta', 'mu_a', 'mu_b', 'mu_beta'}, 'ylims':(1000, 5000), 'ylims_zoomed':(1000, 1300) }, }
model_constants = {'arm.anova_radon_nopred': {'population_effects': {'mu_a', 'sigma_a', 'sigma_y'}, 'ylims': (1000, 5000), 'ylims_zoomed': (1000, 1200)}, 'arm.anova_radon_nopred_chr': {'population_effects': {'sigma_a', 'sigma_y', 'mu_a'}, 'ylims': (1000, 5000), 'ylims_zoomed': (1000, 1200)}, 'arm.congress': {'population_effects': {'beta', 'sigma'}, 'sitename': 'vote_88', 'dataname': 'vote_88', 'ylims': (1000, 5000), 'ylims_zoomed': (1000, 1200)}, 'arm.earnings_latin_square': {'population_effects': {'sigma_a1', 'sigma_a2', 'sigma_b1', 'sigma_b2', 'sigma_c', 'sigma_d', 'sigma_y', 'mu_a1', 'mu_a2', 'mu_b1', 'mu_b2', 'mu_c', 'mu_d'}, 'ylims': (800, 5000), 'ylims_zoomed': (800, 5000)}, 'arm.earnings_latin_square_chr': {'population_effects': {'sigma_a1', 'sigma_a2', 'sigma_b1', 'sigma_b2', 'sigma_c', 'sigma_d', 'sigma_y', 'mu_a1', 'mu_a2', 'mu_b1', 'mu_b2', 'mu_c', 'mu_d'}, 'ylims': (800, 5000), 'ylims_zoomed': (800, 5000)}, 'arm.earnings_vary_si': {'population_effects': {'sigma_a1', 'sigma_a2', 'sigma_y', 'mu_a1', 'mu_a2'}, 'sitename': 'log_earn', 'dataname': 'log_earn', 'ylims': (800, 5000), 'ylims_zoomed': (800, 5000)}, 'arm.earnings_vary_si_chr': {'population_effects': {'sigma_a1', 'sigma_a2', 'sigma_y', 'mu_a1', 'mu_a2'}, 'sitename': 'log_earn', 'dataname': 'log_earn', 'ylims': (800, 5000), 'ylims_zoomed': (800, 5000)}, 'arm.earnings1': {'population_effects': {'sigma', 'beta'}, 'sitename': 'earn_pos', 'dataname': 'earn_pos', 'ylims': (800, 5000), 'ylims_zoomed': (800, 5000)}, 'arm.earnings2': {'population_effects': {'sigma', 'beta'}, 'sitename': 'log_earnings', 'dataname': 'log_earnings', 'ylims': (800, 5000), 'ylims_zoomed': (800, 5000)}, 'arm.election88_ch14': {'population_effects': {'mu_a', 'sigma_a', 'b'}, 'ylims': (1200, 2000), 'ylims_zoomed': (1200, 1400)}, 'arm.election88_ch19': {'population_effects': {'beta', 'mu_age', 'sigma_age', 'mu_edu', 'sigma_edu', 'mu_age_edu', 'sigma_age_edu', 'mu_region', 'sigma_region', 'b_v_prev'}, 'ylims': (1200, 2000), 'ylims_zoomed': (1200, 1400)}, 'arm.electric': {'population_effects': {'beta', 'mu_a', 'sigma_a', 'sigma_y'}, 'ylims': (1200, 2000), 'ylims_zoomed': (1200, 1400)}, 'arm.electric_1a': {'population_effects': set(), 'ylims': (1200, 2000), 'ylims_zoomed': (1200, 1400)}, 'arm.hiv': {'population_effects': {'mu_a1', 'sigma_a1', 'mu_a2', 'sigma_a2', 'sigma_y'}, 'ylims': (1200, 2000), 'ylims_zoomed': (1200, 1400)}, 'arm.wells_dist': {'population_effects': {'beta'}, 'sitename': 'switched', 'dataname': 'switched', 'ylims': (2000, 7500), 'ylims_zoomed': (2000, 2500)}, 'arm.wells_dae_inter_c': {'population_effects': {'beta'}, 'sitename': 'switched', 'dataname': 'switched', 'ylims': (1800, 4000), 'ylims_zoomed': (1800, 2200)}, 'arm.radon_complete_pool': {'population_effects': {'beta', 'sigma'}, 'ylims': (1000, 4000), 'ylims_zoomed': (1000, 1400)}, 'arm.radon_group': {'population_effects': {'beta', 'sigma', 'mu_alpha', 'sigma_alpha', 'mu_beta', 'sigma_beta'}, 'ylims': (1000, 4000), 'ylims_zoomed': (1000, 1200)}, 'arm.radon_inter_vary': {'population_effects': {'beta', 'sigma_y', 'sigma_a', 'sigma_b', 'sigma_beta', 'mu_a', 'mu_b', 'mu_beta'}, 'ylims': (1000, 5000), 'ylims_zoomed': (1000, 1300)}}
def addStrings(num1: str, num2: str) -> str: i, j = len(num1) - 1, len(num2) - 1 tmp = 0 result = "" while i >= 0 or j >= 0: if i >= 0: tmp += int(num1[i]) i -= 1 if j >= 0: tmp += int(num2[j]) j -= 1 result = str(tmp % 10) + result tmp //= 10 if tmp != 0: result = str(tmp) + result return result if __name__ == "__main__": num1 = "999999" num2 = "99" result = addStrings(num1, num2) print(result)
def add_strings(num1: str, num2: str) -> str: (i, j) = (len(num1) - 1, len(num2) - 1) tmp = 0 result = '' while i >= 0 or j >= 0: if i >= 0: tmp += int(num1[i]) i -= 1 if j >= 0: tmp += int(num2[j]) j -= 1 result = str(tmp % 10) + result tmp //= 10 if tmp != 0: result = str(tmp) + result return result if __name__ == '__main__': num1 = '999999' num2 = '99' result = add_strings(num1, num2) print(result)
intin = int(input()) if intin == 2: print("NO") elif intin%2==0: if intin%4==0: print("YES") elif (intin-2)%4==0: print("YES") else: print("NO") else: print("NO")
intin = int(input()) if intin == 2: print('NO') elif intin % 2 == 0: if intin % 4 == 0: print('YES') elif (intin - 2) % 4 == 0: print('YES') else: print('NO') else: print('NO')
def rgb(r, g, b): s="" if r>255: r=255 elif g>255: g=255 elif b>255: b=255 if r<0: r=0 elif g<0: g=0 elif b<0: b=0 r='{0:x}'.format(r) g='{0:x}'.format(g) b='{0:x}'.format(b) if int(r,16)<=15 and int(r,16)>=0: r='0'+r if int(g,16)<=15 and int(g,16)>=0: g='0'+g if int(b,16)<=15 and int(b,16)>=0: b='0'+b s+=r+g+b return s.upper()
def rgb(r, g, b): s = '' if r > 255: r = 255 elif g > 255: g = 255 elif b > 255: b = 255 if r < 0: r = 0 elif g < 0: g = 0 elif b < 0: b = 0 r = '{0:x}'.format(r) g = '{0:x}'.format(g) b = '{0:x}'.format(b) if int(r, 16) <= 15 and int(r, 16) >= 0: r = '0' + r if int(g, 16) <= 15 and int(g, 16) >= 0: g = '0' + g if int(b, 16) <= 15 and int(b, 16) >= 0: b = '0' + b s += r + g + b return s.upper()
# https://www.reddit.com/r/dailyprogrammer/comments/1ystvb/022414_challenge_149_easy_disemvoweler/ def disem(str): result = '' rem_vowels = '' vowels = 'aeiou' for c in str: if c not in vowels and not c.isspace(): result += c elif not c.isspace(): rem_vowels += c print(result + '\n' + rem_vowels) def main(): phrase = input('\nPlease enter a line: ') disem(phrase) choice = input('\nAgain? ') if choice != 'n': main() quit() main() # Need to actually call the main() method!
def disem(str): result = '' rem_vowels = '' vowels = 'aeiou' for c in str: if c not in vowels and (not c.isspace()): result += c elif not c.isspace(): rem_vowels += c print(result + '\n' + rem_vowels) def main(): phrase = input('\nPlease enter a line: ') disem(phrase) choice = input('\nAgain? ') if choice != 'n': main() quit() main()
''' @description 2019/09/22 20:53 '''
""" @description 2019/09/22 20:53 """
def setup(): size (500,500) background (100) smooth() noLoop() strokeWeight(15) str(100) def draw (): fill (250) rect (100,100, 100,100) fill (50) rect (200,200, 50,100)
def setup(): size(500, 500) background(100) smooth() no_loop() stroke_weight(15) str(100) def draw(): fill(250) rect(100, 100, 100, 100) fill(50) rect(200, 200, 50, 100)
#Write a function that accepts a 2D list of integers and returns the maximum EVEN value for the entire list. #You can assume that the number of columns in each row is the same. #Your function should return None if the list is empty or all the numbers in the 2D list are odd. #Do NOT use python's built in max() function. def even_empty_odd(list2d): len_list = 0 even_numbers = [] odd_numbers = [] count = 0 #if the list is empty for list_number in list2d: len_list += len(list_number) if len_list == 0: return None #if the list is gretaer than zero else: for list_number in list2d: for number in list_number: #find the even numbers if number % 2 == 0: even_numbers.append(number) #append all the even numbers in the even_numbers list else: #find the odd numbers odd_numbers.append(number) #append all the odd numbers in the odd_numbers list count += 1 #Compare if the len of the odd_numbers list is equal to count #if True that means that all the numbers are odds if len(odd_numbers) == count: return "All the numbers in the list are odds" #if not it means that at least there is onw even number else: even_numbers.sort() return even_numbers[len(even_numbers)-1] print(even_empty_odd([[1,8],[3,2]]))
def even_empty_odd(list2d): len_list = 0 even_numbers = [] odd_numbers = [] count = 0 for list_number in list2d: len_list += len(list_number) if len_list == 0: return None else: for list_number in list2d: for number in list_number: if number % 2 == 0: even_numbers.append(number) else: odd_numbers.append(number) count += 1 if len(odd_numbers) == count: return 'All the numbers in the list are odds' else: even_numbers.sort() return even_numbers[len(even_numbers) - 1] print(even_empty_odd([[1, 8], [3, 2]]))
### assuming you have Google Chrome installed... ## remember `pip3 install -r setup.py` before trying any scrapers in this dir # have a nice day selenium chromedriver requests
selenium chromedriver requests
class Power: def __init__(self, power_id, name, amount): self.power_id = power_id self.power_name = name self.amount = amount @classmethod def from_json(cls, json_object): return cls(json_object["id"], json_object["name"], json_object["amount"]) def __eq__(self, other): return self.power_id == other.power_id and self.amount == other.amount
class Power: def __init__(self, power_id, name, amount): self.power_id = power_id self.power_name = name self.amount = amount @classmethod def from_json(cls, json_object): return cls(json_object['id'], json_object['name'], json_object['amount']) def __eq__(self, other): return self.power_id == other.power_id and self.amount == other.amount
DB_PORT=5432 DB_USERNAME="postgres" DB_PASSWORD="password" DB_HOST="127.0.0.1" DB_DATABASE="eventtriggertest"
db_port = 5432 db_username = 'postgres' db_password = 'password' db_host = '127.0.0.1' db_database = 'eventtriggertest'
setting = { 'file': './data/crime2010_2018.csv', 'limit': 10000, 'source': [0,1,2,3,7,8,10,11,14,16,23,5,25], 'vars': { 0 : 'num', 1 : 'date_reported', 2:'date_occured', 3:'time_occured', 7:'crime_code', 8:'crime_desc', 10:'victim_age', 11:'victim_sex', 14:'premise_desc', 16:'weapon', 23:'address', 5:'area',25:'location' } }
setting = {'file': './data/crime2010_2018.csv', 'limit': 10000, 'source': [0, 1, 2, 3, 7, 8, 10, 11, 14, 16, 23, 5, 25], 'vars': {0: 'num', 1: 'date_reported', 2: 'date_occured', 3: 'time_occured', 7: 'crime_code', 8: 'crime_desc', 10: 'victim_age', 11: 'victim_sex', 14: 'premise_desc', 16: 'weapon', 23: 'address', 5: 'area', 25: 'location'}}
'''from axju.core.tools import SmartCLI from axju.worker.git import GitWorker def main(): cli = SmartCLI(GitWorker) cli.run() if __name__ == '__main__': main() '''
"""from axju.core.tools import SmartCLI from axju.worker.git import GitWorker def main(): cli = SmartCLI(GitWorker) cli.run() if __name__ == '__main__': main() """
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Michael Eaton <[email protected]> # # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. # this is a windows documentation stub. actual code lives in the .ps1 # file of the same name ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: win_firewall version_added: '2.4' short_description: Enable or disable the Windows Firewall description: - Enable or Disable Windows Firewall profiles. options: profiles: description: - Specify one or more profiles to change. choices: - Domain - Private - Public default: [Domain, Private, Public] state: description: - Set state of firewall for given profile. choices: - enabled - disabled requirements: - This module requires Windows Management Framework 5 or later. author: Michael Eaton (@MichaelEaton83) ''' EXAMPLES = r''' - name: Enable firewall for Domain, Public and Private profiles win_firewall: state: enabled profiles: - Domain - Private - Public tags: enable_firewall - name: Disable Domain firewall win_firewall: state: disabled profiles: - Domain tags: disable_firewall ''' RETURN = r''' enabled: description: current firewall status for chosen profile (after any potential change) returned: always type: bool sample: true profiles: description: chosen profile returned: always type: string sample: Domain state: description: desired state of the given firewall profile(s) returned: always type: list sample: enabled '''
ansible_metadata = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} documentation = "\n---\nmodule: win_firewall\nversion_added: '2.4'\nshort_description: Enable or disable the Windows Firewall\ndescription:\n- Enable or Disable Windows Firewall profiles.\noptions:\n profiles:\n description:\n - Specify one or more profiles to change.\n choices:\n - Domain\n - Private\n - Public\n default: [Domain, Private, Public]\n state:\n description:\n - Set state of firewall for given profile.\n choices:\n - enabled\n - disabled\nrequirements:\n - This module requires Windows Management Framework 5 or later.\nauthor: Michael Eaton (@MichaelEaton83)\n" examples = '\n- name: Enable firewall for Domain, Public and Private profiles\n win_firewall:\n state: enabled\n profiles:\n - Domain\n - Private\n - Public\n tags: enable_firewall\n\n- name: Disable Domain firewall\n win_firewall:\n state: disabled\n profiles:\n - Domain\n tags: disable_firewall\n' return = '\nenabled:\n description: current firewall status for chosen profile (after any potential change)\n returned: always\n type: bool\n sample: true\nprofiles:\n description: chosen profile\n returned: always\n type: string\n sample: Domain\nstate:\n description: desired state of the given firewall profile(s)\n returned: always\n type: list\n sample: enabled\n'
load("//webgen:webgen.bzl", "erb_file", "js_file", "scss_file", "website") def page(name, file, out=None, data=False, math=False, plot=False): extra_templates = [] if data: extra_templates.append("template/data.html") if math: extra_templates.append("template/mathjax.html") if plot: extra_templates.append("template/plot.html") if plot == "tape": extra_templates.append("template/plot_tape.html") erb_file( name = name, srcs = [file, "template/default.html"] + extra_templates, out = out if out else file, bootstrap = True, ) def script(name, file=None, files=[], out=None, plot=False): extra_sources = [] if plot: extra_sources.append("vis/js/plot.js") if plot == "prog" or plot == "tape": extra_sources.append("vis/js/plot_prog.js") if plot == "tape": extra_sources.append("vis/js/plot_tape.js") js_file( name = name, srcs = extra_sources + ([file] if file else []) + files, out = out if out else file, )
load('//webgen:webgen.bzl', 'erb_file', 'js_file', 'scss_file', 'website') def page(name, file, out=None, data=False, math=False, plot=False): extra_templates = [] if data: extra_templates.append('template/data.html') if math: extra_templates.append('template/mathjax.html') if plot: extra_templates.append('template/plot.html') if plot == 'tape': extra_templates.append('template/plot_tape.html') erb_file(name=name, srcs=[file, 'template/default.html'] + extra_templates, out=out if out else file, bootstrap=True) def script(name, file=None, files=[], out=None, plot=False): extra_sources = [] if plot: extra_sources.append('vis/js/plot.js') if plot == 'prog' or plot == 'tape': extra_sources.append('vis/js/plot_prog.js') if plot == 'tape': extra_sources.append('vis/js/plot_tape.js') js_file(name=name, srcs=extra_sources + ([file] if file else []) + files, out=out if out else file)
#data kualitatif a = "the dogis hungry. The cat is bored. the snack is awake." s = a.split(".") print(s) print(s[0]) print(s[1]) print(s[2])
a = 'the dogis hungry. The cat is bored. the snack is awake.' s = a.split('.') print(s) print(s[0]) print(s[1]) print(s[2])
''' Completion sample module ''' def func_module_level(i, a='foo'): 'some docu' return i * a class ModClass: ''' some inner namespace class''' @classmethod def class_level_func(cls, boolean=True): return boolean class NestedClass: ''' some inner namespace class''' @classmethod def class_level_func(cls, a_str='foo', boolean=True): return boolean or a_str @classmethod def a_really_really_loooo_path_to_func(i=23, j='str'): '''## Some documentation over `multiple` lines - list1 - list2 ''' return i
""" Completion sample module """ def func_module_level(i, a='foo'): """some docu""" return i * a class Modclass: """ some inner namespace class""" @classmethod def class_level_func(cls, boolean=True): return boolean class Nestedclass: """ some inner namespace class""" @classmethod def class_level_func(cls, a_str='foo', boolean=True): return boolean or a_str @classmethod def a_really_really_loooo_path_to_func(i=23, j='str'): """## Some documentation over `multiple` lines - list1 - list2 """ return i
N = int(input()) A = int(input()) for a in range(A+1): for j in range(21): if a + 500 * j == N: print("Yes") exit() print("No")
n = int(input()) a = int(input()) for a in range(A + 1): for j in range(21): if a + 500 * j == N: print('Yes') exit() print('No')
# Scrapy settings for uefispider project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'uefispider' SPIDER_MODULES = ['uefispider.spiders'] NEWSPIDER_MODULE = 'uefispider.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent USER_AGENT = 'uefispider (+https://github.com/theopolis/uefi-spider)' ITEM_PIPELINES = { 'uefispider.pipelines.UefispiderPipeline': 1 } COOKIES_DEBUG = True
bot_name = 'uefispider' spider_modules = ['uefispider.spiders'] newspider_module = 'uefispider.spiders' user_agent = 'uefispider (+https://github.com/theopolis/uefi-spider)' item_pipelines = {'uefispider.pipelines.UefispiderPipeline': 1} cookies_debug = True
class Solution: def baseNeg2(self, N: int) -> str: if N == 0: return "0" nums = [] while N != 0: r = N % (-2) N //= (-2) if r < 0: r += 2 N += 1 nums.append(r) return ''.join(map(str, nums[::-1]))
class Solution: def base_neg2(self, N: int) -> str: if N == 0: return '0' nums = [] while N != 0: r = N % -2 n //= -2 if r < 0: r += 2 n += 1 nums.append(r) return ''.join(map(str, nums[::-1]))
# This file contains the different states of the api class Config(object): DEBUG = False SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db' SQLALCHEMY_TRACK_MODIFICATIONS = False class Production(Config): DEBUG = False class DevelopmentConfig(Config): DEBUG = True
class Config(object): debug = False sqlalchemy_database_uri = 'sqlite:///database.db' sqlalchemy_track_modifications = False class Production(Config): debug = False class Developmentconfig(Config): debug = True
#!/usr/bin/env python print('nihao')
print('nihao')
def friend_find(line): check=[i for i,j in enumerate(line) if j=="red"] total=0 for i in check: if i>=2 and line[i-1]=="blue" and line[i-2]=="blue": total+=1 elif (i>=1 and i<=len(line)-2) and line[i-1]=="blue" and line[i+1]=="blue": total+=1 elif (i<=len(line)-3) and line[i+1]=="blue" and line[i+2]=="blue": total+=1 return total
def friend_find(line): check = [i for (i, j) in enumerate(line) if j == 'red'] total = 0 for i in check: if i >= 2 and line[i - 1] == 'blue' and (line[i - 2] == 'blue'): total += 1 elif (i >= 1 and i <= len(line) - 2) and line[i - 1] == 'blue' and (line[i + 1] == 'blue'): total += 1 elif i <= len(line) - 3 and line[i + 1] == 'blue' and (line[i + 2] == 'blue'): total += 1 return total
# _*_ coding: utf-8 _*_ # # Package: bookstore.src.core.validator __all__ = ["validators"]
__all__ = ['validators']
sanitizedLines = [] with open("diff.txt") as f: for line in f: sanitizedLines.append("https://interclip.app/" + line.strip()) print(str(sanitizedLines))
sanitized_lines = [] with open('diff.txt') as f: for line in f: sanitizedLines.append('https://interclip.app/' + line.strip()) print(str(sanitizedLines))
# # chmod this file securely and be sure to remove the default users # users = { "frodo" : "1ring", "yossarian" : "catch22", "ayla" : "jondalar", }
users = {'frodo': '1ring', 'yossarian': 'catch22', 'ayla': 'jondalar'}
def calcMul(items): mulTotal = 1 for i in items: mulTotal *= i return mulTotal print("The multiple is: ",calcMul([10,20,30]))
def calc_mul(items): mul_total = 1 for i in items: mul_total *= i return mulTotal print('The multiple is: ', calc_mul([10, 20, 30]))
def validate_contract_create(request, **kwargs): if request.validated['auction'].status not in ['active.qualification', 'active.awarded']: request.errors.add('body', 'data', 'Can\'t add contract in current ({}) auction status'.format(request.validated['auction'].status)) request.errors.status = 403 return def validate_contract_update(request, **kwargs): if request.validated['auction_status'] not in ['active.qualification', 'active.awarded']: request.errors.add('body', 'data', 'Can\'t update contract in current ({}) auction status'.format( request.validated['auction_status'])) request.errors.status = 403 return if any([i.status != 'active' for i in request.validated['auction'].lots if i.id in [a.lotID for a in request.validated['auction'].awards if a.id == request.context.awardID]]): request.errors.add('body', 'data', 'Can update contract only in active lot status') request.errors.status = 403 return
def validate_contract_create(request, **kwargs): if request.validated['auction'].status not in ['active.qualification', 'active.awarded']: request.errors.add('body', 'data', "Can't add contract in current ({}) auction status".format(request.validated['auction'].status)) request.errors.status = 403 return def validate_contract_update(request, **kwargs): if request.validated['auction_status'] not in ['active.qualification', 'active.awarded']: request.errors.add('body', 'data', "Can't update contract in current ({}) auction status".format(request.validated['auction_status'])) request.errors.status = 403 return if any([i.status != 'active' for i in request.validated['auction'].lots if i.id in [a.lotID for a in request.validated['auction'].awards if a.id == request.context.awardID]]): request.errors.add('body', 'data', 'Can update contract only in active lot status') request.errors.status = 403 return
class User: def __init__(self, userName, firstName, lastName, passportNumber, address1, address2, zipCode): self.userName = userName self.firstName = firstName self.lastName = lastName self.passportNumber = passportNumber self.address1 = address1 self.address2 = address2 self.zipCode = zipCode def toString(self): return "[userName: " + self.userName + ", firstName: " + self.firstName + ", lastName: " + self.lastName + ", passportNumber: " + self.passportNumber +\ ", address1: " + self.address1 + ", address2: " + self.address2 + ", zipCode: " + self.zipCode + "]"
class User: def __init__(self, userName, firstName, lastName, passportNumber, address1, address2, zipCode): self.userName = userName self.firstName = firstName self.lastName = lastName self.passportNumber = passportNumber self.address1 = address1 self.address2 = address2 self.zipCode = zipCode def to_string(self): return '[userName: ' + self.userName + ', firstName: ' + self.firstName + ', lastName: ' + self.lastName + ', passportNumber: ' + self.passportNumber + ', address1: ' + self.address1 + ', address2: ' + self.address2 + ', zipCode: ' + self.zipCode + ']'
# pylint: skip-file # pylint: disable=too-many-instance-attributes class VMInstance(GCPResource): '''Object to represent a gcp instance''' resource_type = "compute.v1.instance" # pylint: disable=too-many-arguments def __init__(self, rname, project, zone, machine_type, metadata, tags, disks, network_interfaces, service_accounts=None, ): '''constructor for gcp resource''' super(VMInstance, self).__init__(rname, VMInstance.resource_type, project, zone) self._machine_type = machine_type self._service_accounts = service_accounts self._machine_type_url = None self._tags = tags self._metadata = [] if metadata and isinstance(metadata, dict): self._metadata = {'items': [{'key': key, 'value': value} for key, value in metadata.items()]} elif metadata and isinstance(metadata, list): self._metadata = [{'key': label['key'], 'value': label['value']} for label in metadata] self._disks = disks self._network_interfaces = network_interfaces self._properties = None @property def service_accounts(self): '''property for resource service accounts ''' return self._service_accounts @property def network_interfaces(self): '''property for resource machine network_interfaces ''' return self._network_interfaces @property def machine_type(self): '''property for resource machine type ''' return self._machine_type @property def machine_type_url(self): '''property for resource machine type url''' if self._machine_type_url == None: self._machine_type_url = Utils.zonal_compute_url(self.project, self.zone, 'machineTypes', self.machine_type) return self._machine_type_url @property def tags(self): '''property for resource tags ''' return self._tags @property def metadata(self): '''property for resource metadata''' return self._metadata @property def disks(self): '''property for resource disks''' return self._disks @property def properties(self): '''property for holding the properties''' if self._properties == None: self._properties = {'zone': self.zone, 'machineType': self.machine_type_url, 'metadata': self.metadata, 'tags': self.tags, 'disks': self.disks, 'networkInterfaces': self.network_interfaces, } if self.service_accounts: self._properties['serviceAccounts'] = self.service_accounts return self._properties def to_resource(self): '''return the resource representation''' return {'name': self.name, 'type': VMInstance.resource_type, 'properties': self.properties, }
class Vminstance(GCPResource): """Object to represent a gcp instance""" resource_type = 'compute.v1.instance' def __init__(self, rname, project, zone, machine_type, metadata, tags, disks, network_interfaces, service_accounts=None): """constructor for gcp resource""" super(VMInstance, self).__init__(rname, VMInstance.resource_type, project, zone) self._machine_type = machine_type self._service_accounts = service_accounts self._machine_type_url = None self._tags = tags self._metadata = [] if metadata and isinstance(metadata, dict): self._metadata = {'items': [{'key': key, 'value': value} for (key, value) in metadata.items()]} elif metadata and isinstance(metadata, list): self._metadata = [{'key': label['key'], 'value': label['value']} for label in metadata] self._disks = disks self._network_interfaces = network_interfaces self._properties = None @property def service_accounts(self): """property for resource service accounts """ return self._service_accounts @property def network_interfaces(self): """property for resource machine network_interfaces """ return self._network_interfaces @property def machine_type(self): """property for resource machine type """ return self._machine_type @property def machine_type_url(self): """property for resource machine type url""" if self._machine_type_url == None: self._machine_type_url = Utils.zonal_compute_url(self.project, self.zone, 'machineTypes', self.machine_type) return self._machine_type_url @property def tags(self): """property for resource tags """ return self._tags @property def metadata(self): """property for resource metadata""" return self._metadata @property def disks(self): """property for resource disks""" return self._disks @property def properties(self): """property for holding the properties""" if self._properties == None: self._properties = {'zone': self.zone, 'machineType': self.machine_type_url, 'metadata': self.metadata, 'tags': self.tags, 'disks': self.disks, 'networkInterfaces': self.network_interfaces} if self.service_accounts: self._properties['serviceAccounts'] = self.service_accounts return self._properties def to_resource(self): """return the resource representation""" return {'name': self.name, 'type': VMInstance.resource_type, 'properties': self.properties}
# # Variables: # - Surname: String # - SurnameLength, NextCodeNumber, CustomerID, i: Integer # - NextChar: Char # Surname = input("Enter your surname: ") SurnameLength = len(Surname) CustomerID = 0 for i in range(0, SurnameLength): NextChar = Surname[i] NextCodeNumber = ord(NextChar) CustomerID = CustomerID + NextCodeNumber print("Customer ID is ", CustomerID)
surname = input('Enter your surname: ') surname_length = len(Surname) customer_id = 0 for i in range(0, SurnameLength): next_char = Surname[i] next_code_number = ord(NextChar) customer_id = CustomerID + NextCodeNumber print('Customer ID is ', CustomerID)
class classproperty(object): '''Implements both @property and @classmethod behavior.''' def __init__(self, getter): self.getter = getter def __get__(self, instance, owner): return self.getter(instance) if instance else self.getter(owner)
class Classproperty(object): """Implements both @property and @classmethod behavior.""" def __init__(self, getter): self.getter = getter def __get__(self, instance, owner): return self.getter(instance) if instance else self.getter(owner)
def is_empty(text): if text in [None,'']: return True return False
def is_empty(text): if text in [None, '']: return True return False
mysql_config = { 'user': 'USER', 'password': 'PASSWORD', 'host': 'HOST', 'port': 3306, 'charset': 'utf8mb4', 'database': 'DATABASE', 'raise_on_warnings': False, 'use_pure': False, }
mysql_config = {'user': 'USER', 'password': 'PASSWORD', 'host': 'HOST', 'port': 3306, 'charset': 'utf8mb4', 'database': 'DATABASE', 'raise_on_warnings': False, 'use_pure': False}
movie = {"title": "padmavati", "director": "Bhansali","year": "2018", "rating": "4.5"} print(movie) print(movie['year']) movie['year'] = 2019 #update data. print(movie['year']) print('-' * 20) for x in movie: print(x) #this print key. print(movie[x]) #this print value at key. print('-' * 20) movie = {} movie['title'] = 'Manikarnika' movie['Director'] = 'kangana Ranut' movie['year'] = '2015' print(movie) movie['actor'] = ['kangana Ranut', 'Khilge','Pelge'] #defining a list within dictionary. movie['other_detail'] = {'language': 'Hindi', 'runtime': '180min'} #defining a dictinary witnin dictionay. print(movie) print('\n...........new example........') orders = {'apple': 2, 'banana': 5 , 'orange': 10} print(orders.values()) print(list(orders)) print(list(orders.values())) for tuple in list(orders.items()): #iterate in dictionary , converting in tuple by using items() method. print(tuple)
movie = {'title': 'padmavati', 'director': 'Bhansali', 'year': '2018', 'rating': '4.5'} print(movie) print(movie['year']) movie['year'] = 2019 print(movie['year']) print('-' * 20) for x in movie: print(x) print(movie[x]) print('-' * 20) movie = {} movie['title'] = 'Manikarnika' movie['Director'] = 'kangana Ranut' movie['year'] = '2015' print(movie) movie['actor'] = ['kangana Ranut', 'Khilge', 'Pelge'] movie['other_detail'] = {'language': 'Hindi', 'runtime': '180min'} print(movie) print('\n...........new example........') orders = {'apple': 2, 'banana': 5, 'orange': 10} print(orders.values()) print(list(orders)) print(list(orders.values())) for tuple in list(orders.items()): print(tuple)
def comb(m, s): if m == 1: return [[x] for x in s] if m == len(s): return [s] return [s[:1] + a for a in comb(m-1, s[1:])] + comb(m, s[1:])
def comb(m, s): if m == 1: return [[x] for x in s] if m == len(s): return [s] return [s[:1] + a for a in comb(m - 1, s[1:])] + comb(m, s[1:])
n, x = map(int, input().split()) mark_sheet = [] for _ in range(x): mark_sheet.append( map(float, input().split()) ) for i in zip(*mark_sheet): print( sum(i)/len(i) )
(n, x) = map(int, input().split()) mark_sheet = [] for _ in range(x): mark_sheet.append(map(float, input().split())) for i in zip(*mark_sheet): print(sum(i) / len(i))
__name__ = "lbry" __version__ = "0.42.1" version = tuple(__version__.split('.'))
__name__ = 'lbry' __version__ = '0.42.1' version = tuple(__version__.split('.'))
# coding=utf-8 class AutumnInvokeException(Exception): pass class InvocationTargetException(Exception): pass if __name__ == '__main__': pass
class Autumninvokeexception(Exception): pass class Invocationtargetexception(Exception): pass if __name__ == '__main__': pass
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: ''' T: O(n log n + n^3) S: O(1) ''' n = len(nums) if n < 4: return [] nums.sort() results = set() for x in range(n): for y in range(x+1, n): i, j = y + 1, n-1 while i < j: summ = nums[x] + nums[y] + nums[i] + nums[j] if summ == target: results.add((nums[x],nums[y], nums[i], nums[j])) i += 1 elif summ < target: i += 1 else: j -= 1 return results
class Solution: def four_sum(self, nums: List[int], target: int) -> List[List[int]]: """ T: O(n log n + n^3) S: O(1) """ n = len(nums) if n < 4: return [] nums.sort() results = set() for x in range(n): for y in range(x + 1, n): (i, j) = (y + 1, n - 1) while i < j: summ = nums[x] + nums[y] + nums[i] + nums[j] if summ == target: results.add((nums[x], nums[y], nums[i], nums[j])) i += 1 elif summ < target: i += 1 else: j -= 1 return results
class event_meta(object): def __init__(self): super(event_meta, self).__init__() def n_views(self): return max(self._n_views, 1) def refresh(self, meta_vec): self._n_views = len(meta_vec) self._x_min = [] self._y_min = [] self._x_max = [] self._y_max = [] self._y_n_pixels = [] self._x_n_pixels = [] x_ind = 0 y_ind = 1 for meta in meta_vec: self._x_min.append(meta.origin(0)) self._y_min.append(meta.origin(1)) self._x_max.append(meta.image_size(0) + meta.origin(0)) self._y_max.append(meta.image_size(1) + meta.origin(1)) self._x_n_pixels.append(meta.number_of_voxels(0)) self._y_n_pixels.append(meta.number_of_voxels(1)) for i in range(self._n_views): if self._x_min[i] == self._x_max[i]: self._x_max[i] = self._x_min[i] + self._x_n_pixels[i] if self._y_min[i] == self._y_max[i]: self._y_max[i] = self._y_min[i] + self._y_n_pixels[i] def cols(self, plane): return self._x_n_pixels[plane] def width(self, plane): return self._x_max[plane] - self._x_min[plane] def comp_x(self, plane): return self.width(plane) / self.cols(plane) def rows(self, plane): return self._y_n_pixels[plane] def height(self, plane): return self._y_max[plane] - self._y_min[plane] def comp_y(self, plane): return self.height(plane) / self.rows(plane) def wire_to_col(self, wire, plane): return self.cols(plane) * (1.0*(wire - self.min_x(plane)) / self.width(plane)) def time_to_row(self, time, plane): return self.rows(plane) * (1.0*(time - self.min_y(plane)) / self.height(plane)) def min_y(self, plane): return self._y_min[plane] def max_y(self, plane): return self._y_max[plane] def min_x(self, plane): return self._x_min[plane] def max_x(self, plane): return self._x_max[plane] def range(self, plane): if plane >= 0 and plane < self._n_views: return ((self._x_min[plane], self._x_min[plane] ), (self._x_min[plane], self._x_min[plane])) else: print("ERROR: plane {} not available.".format(plane)) return ((-1, 1), (-1, 1)) class event_meta3D(object): def __init__(self): super(event_meta3D, self).__init__() def refresh(self, meta): x_ind = 0 y_ind = 1 z_ind = 2 self._x_min = meta.origin(x_ind) self._y_min = meta.origin(y_ind) self._z_min = meta.origin(z_ind) self._x_max = meta.image_size(x_ind) + meta.origin(x_ind) self._y_max = meta.image_size(y_ind) + meta.origin(y_ind) self._z_max = meta.image_size(z_ind) + meta.origin(z_ind) self._y_n_pixels = meta.number_of_voxels(x_ind) self._x_n_pixels = meta.number_of_voxels(y_ind) self._z_n_pixels = meta.number_of_voxels(z_ind) def size_voxel_x(self): return (self._x_max - self._x_min) / self._x_n_pixels def size_voxel_y(self): return (self._y_max - self._y_min) / self._y_n_pixels def size_voxel_z(self): return (self._z_max - self._z_min) / self._z_n_pixels def n_voxels_x(self): return self._x_n_pixels def n_voxels_y(self): return self._y_n_pixels def n_voxels_z(self): return self._z_n_pixels def dim_x(self): return self._x_max - self._x_min def dim_y(self): return self._y_max - self._y_min def dim_z(self): return self._z_max - self._z_min def width(self): return self.dim_x() def height(self): return self.dim_y() def length(self): return self.dim_z() def min_y(self): return self._y_min def max_y(self): return self._y_max def min_x(self): return self._x_min def max_x(self): return self._x_max def min_z(self): return self._z_min def max_z(self): return self._z_max
class Event_Meta(object): def __init__(self): super(event_meta, self).__init__() def n_views(self): return max(self._n_views, 1) def refresh(self, meta_vec): self._n_views = len(meta_vec) self._x_min = [] self._y_min = [] self._x_max = [] self._y_max = [] self._y_n_pixels = [] self._x_n_pixels = [] x_ind = 0 y_ind = 1 for meta in meta_vec: self._x_min.append(meta.origin(0)) self._y_min.append(meta.origin(1)) self._x_max.append(meta.image_size(0) + meta.origin(0)) self._y_max.append(meta.image_size(1) + meta.origin(1)) self._x_n_pixels.append(meta.number_of_voxels(0)) self._y_n_pixels.append(meta.number_of_voxels(1)) for i in range(self._n_views): if self._x_min[i] == self._x_max[i]: self._x_max[i] = self._x_min[i] + self._x_n_pixels[i] if self._y_min[i] == self._y_max[i]: self._y_max[i] = self._y_min[i] + self._y_n_pixels[i] def cols(self, plane): return self._x_n_pixels[plane] def width(self, plane): return self._x_max[plane] - self._x_min[plane] def comp_x(self, plane): return self.width(plane) / self.cols(plane) def rows(self, plane): return self._y_n_pixels[plane] def height(self, plane): return self._y_max[plane] - self._y_min[plane] def comp_y(self, plane): return self.height(plane) / self.rows(plane) def wire_to_col(self, wire, plane): return self.cols(plane) * (1.0 * (wire - self.min_x(plane)) / self.width(plane)) def time_to_row(self, time, plane): return self.rows(plane) * (1.0 * (time - self.min_y(plane)) / self.height(plane)) def min_y(self, plane): return self._y_min[plane] def max_y(self, plane): return self._y_max[plane] def min_x(self, plane): return self._x_min[plane] def max_x(self, plane): return self._x_max[plane] def range(self, plane): if plane >= 0 and plane < self._n_views: return ((self._x_min[plane], self._x_min[plane]), (self._x_min[plane], self._x_min[plane])) else: print('ERROR: plane {} not available.'.format(plane)) return ((-1, 1), (-1, 1)) class Event_Meta3D(object): def __init__(self): super(event_meta3D, self).__init__() def refresh(self, meta): x_ind = 0 y_ind = 1 z_ind = 2 self._x_min = meta.origin(x_ind) self._y_min = meta.origin(y_ind) self._z_min = meta.origin(z_ind) self._x_max = meta.image_size(x_ind) + meta.origin(x_ind) self._y_max = meta.image_size(y_ind) + meta.origin(y_ind) self._z_max = meta.image_size(z_ind) + meta.origin(z_ind) self._y_n_pixels = meta.number_of_voxels(x_ind) self._x_n_pixels = meta.number_of_voxels(y_ind) self._z_n_pixels = meta.number_of_voxels(z_ind) def size_voxel_x(self): return (self._x_max - self._x_min) / self._x_n_pixels def size_voxel_y(self): return (self._y_max - self._y_min) / self._y_n_pixels def size_voxel_z(self): return (self._z_max - self._z_min) / self._z_n_pixels def n_voxels_x(self): return self._x_n_pixels def n_voxels_y(self): return self._y_n_pixels def n_voxels_z(self): return self._z_n_pixels def dim_x(self): return self._x_max - self._x_min def dim_y(self): return self._y_max - self._y_min def dim_z(self): return self._z_max - self._z_min def width(self): return self.dim_x() def height(self): return self.dim_y() def length(self): return self.dim_z() def min_y(self): return self._y_min def max_y(self): return self._y_max def min_x(self): return self._x_min def max_x(self): return self._x_max def min_z(self): return self._z_min def max_z(self): return self._z_max
def sum(a, b): return a + b a = int(input("Enter a number: ")) b = int(input("Enter another number: ")) c = sum(a, b) print("The sum of the two numbers is: ", c)
def sum(a, b): return a + b a = int(input('Enter a number: ')) b = int(input('Enter another number: ')) c = sum(a, b) print('The sum of the two numbers is: ', c)
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: positives_and_zero = collections.deque() negatives = collections.deque() for x in nums: if x < 0: negatives.appendleft(x * x) else: positives_and_zero.append(x * x) ans = [] while(len(negatives) > 0 and len(positives_and_zero) > 0): if positives_and_zero < negatives: ans.append(positives_and_zero.popleft()) else: ans.append(negatives.popleft()) # one of them is empty so order doesn't matter ans += positives_and_zero + negatives return ans
class Solution: def sorted_squares(self, nums: List[int]) -> List[int]: positives_and_zero = collections.deque() negatives = collections.deque() for x in nums: if x < 0: negatives.appendleft(x * x) else: positives_and_zero.append(x * x) ans = [] while len(negatives) > 0 and len(positives_and_zero) > 0: if positives_and_zero < negatives: ans.append(positives_and_zero.popleft()) else: ans.append(negatives.popleft()) ans += positives_and_zero + negatives return ans
class Solution: # @param A : list of integers # @param B : list of integers # @return an integer def computeGCD(self, x, y): if x > y: small = y else: small = x gcd = 1 for i in range(1, small + 1): if ((x % i == 0) and (y % i == 0)): gcd = i return gcd def maxPoints(self, A, B): N = len(A) if N <= 2: return N max_points = 0 for i in range(N): hash_map = {} horizontal = 0 vertical = 0 overlap = 1 x1, y1 = A[i], B[i] for j in range(i + 1, N): x2, y2 = A[j], B[j] if x1 == x2 and y1 == y2: overlap += 1 elif x1 == x2: vertical += 1 elif y1 == y2: horizontal += 1 else: dy = y2 - y1 dx = x2 - x1 slope = 1.0* dy / dx if slope in hash_map: hash_map[slope] = hash_map[slope] + 1 else: hash_map[slope] = 1 curr_max = max(list(hash_map.values()) + [vertical, horizontal]) curr_max += overlap max_points = max(max_points, curr_max) return max_points
class Solution: def compute_gcd(self, x, y): if x > y: small = y else: small = x gcd = 1 for i in range(1, small + 1): if x % i == 0 and y % i == 0: gcd = i return gcd def max_points(self, A, B): n = len(A) if N <= 2: return N max_points = 0 for i in range(N): hash_map = {} horizontal = 0 vertical = 0 overlap = 1 (x1, y1) = (A[i], B[i]) for j in range(i + 1, N): (x2, y2) = (A[j], B[j]) if x1 == x2 and y1 == y2: overlap += 1 elif x1 == x2: vertical += 1 elif y1 == y2: horizontal += 1 else: dy = y2 - y1 dx = x2 - x1 slope = 1.0 * dy / dx if slope in hash_map: hash_map[slope] = hash_map[slope] + 1 else: hash_map[slope] = 1 curr_max = max(list(hash_map.values()) + [vertical, horizontal]) curr_max += overlap max_points = max(max_points, curr_max) return max_points
TVOC =2300 if TVOC <=2500 and TVOC >=2000: print("Level-5", "Unhealty") print("Hygienic Rating - Situation not acceptable") print("Recommendation - Use only if unavoidable/Intense ventilation necessary") print("Exposure Limit - Hours")
tvoc = 2300 if TVOC <= 2500 and TVOC >= 2000: print('Level-5', 'Unhealty') print('Hygienic Rating - Situation not acceptable') print('Recommendation - Use only if unavoidable/Intense ventilation necessary') print('Exposure Limit - Hours')
for i in range(10): print(i) i = 1 while i < 6: print(i) i += 1
for i in range(10): print(i) i = 1 while i < 6: print(i) i += 1
'''Spiral Matrix''' # spiral :: Int -> [[Int]] def spiral(n): '''The rows of a spiral matrix of order N. ''' def go(rows, cols, x): return [list(range(x, x + cols))] + [ list(reversed(x)) for x in zip(*go(cols, rows - 1, x + cols)) ] if 0 < rows else [[]] return go(n, n, 0) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Spiral matrix of order 5, in wiki table markup''' print(wikiTable( spiral(5) )) # FORMATTING ---------------------------------------------- # wikiTable :: [[a]] -> String def wikiTable(rows): '''Wiki markup for a no-frills tabulation of rows.''' return '{| class="wikitable" style="' + ( 'width:12em;height:12em;table-layout:fixed;"|-\n' ) + '\n|-\n'.join([ '| ' + ' || '.join([str(cell) for cell in row]) for row in rows ]) + '\n|}' # MAIN --- if __name__ == '__main__': main()
"""Spiral Matrix""" def spiral(n): """The rows of a spiral matrix of order N. """ def go(rows, cols, x): return [list(range(x, x + cols))] + [list(reversed(x)) for x in zip(*go(cols, rows - 1, x + cols))] if 0 < rows else [[]] return go(n, n, 0) def main(): """Spiral matrix of order 5, in wiki table markup""" print(wiki_table(spiral(5))) def wiki_table(rows): """Wiki markup for a no-frills tabulation of rows.""" return '{| class="wikitable" style="' + 'width:12em;height:12em;table-layout:fixed;"|-\n' + '\n|-\n'.join(['| ' + ' || '.join([str(cell) for cell in row]) for row in rows]) + '\n|}' if __name__ == '__main__': main()
class Flight: def __init__(self, origin, destination, month, fare, currency, fare_type, date): self.origin = origin self.destination = destination self.month = month self.fare = fare self.currency = currency self.fare_type = fare_type self.date = date def __str__(self): return self.origin + self.destination + self.month + self.fare + self.currency + self.fare_type + self.date
class Flight: def __init__(self, origin, destination, month, fare, currency, fare_type, date): self.origin = origin self.destination = destination self.month = month self.fare = fare self.currency = currency self.fare_type = fare_type self.date = date def __str__(self): return self.origin + self.destination + self.month + self.fare + self.currency + self.fare_type + self.date
# Users to create/delete users = [ {'name': 'user1', 'password': 'passwd1', 'email': '[email protected]', 'tenant': 'tenant1', 'enabled': True}, {'name': 'user3', 'password': 'paafdssswd1', 'email': '[email protected]', 'tenant': 'tenant1', 'enabled': False} ] # Roles to create/delete roles = [ {'name': 'SomeRole'} ] # Keypairs to create/delete # Connected to user's list keypairs = [ {'name': 'key1', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn4vaa1MvLLIQM9G2i9eo2OWoW66i7' '/tz+F+sSBxjiscmXMGSUxZN1a0yK4TO2l71/MenfAsHCSgu75vyno62JTOLo+QKG07ly' '8vx9RF+mp+bP/6g0nhcgndOD30NPLEv3vtZbZRDiYeb3inc/ZmAy8kLoRPXE3sW4v+xq' '+PB2nqu38DUemKU9WlZ9F5Fbhz7aVFDhBjvFNDw7w5nO7zeAFz2RbajJksQlHP62VmkW' 'mTgu/otEuhM8GcjZIXlfHJtv0utMNfqQsNQ8qzt38OKXn/k2czmZX59DXomwdo3DUSmk' 'SHym3kZtZPSTgT6GIGoWA1+QHlhx5kiMVEN+YRZF vagrant'}, {'name': 'key2', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn4vaa1MvLLIQM9G2i9eo2OWoW66i7' '/tz+F+sSBxjiscmXMGSUxZN1a0yK4TO2l71/MenfAsHCSgu75vyno62JTOLo+QKG07ly' '8vx9RF+mp+bP/6g0nhcgndOD30NPLEv3vtZbZRDiYeb3inc/ZmAy8kLoRPXE3sW4v+xq' '+PB2nqu38DUemKU9WlZ9F5Fbhz7aVFDhBjvFNDw7w5nO7zeAFz2RbajJksQlHP62VmkW' 'mTgu/otEuhM8GcjZIXlfHJtv0utMNfqQsNQ8qzt38OKXn/k2czmZX59DXomwdo3DUSmk' 'SHym3kZtZPSTgT6GIGoWA1+QHlhx5kiMVEN+YRZF vagrant'} ] # Images to create/delete images = [ {'name': 'image1', 'copy_from': 'http://download.cirros-cloud.net/0.3.3/ci' 'rros-0.3.3-x86_64-disk.img', 'is_public': True}, {'name': 'image2', 'copy_from': 'http://download.cirros-cloud.net/0.3.3/ci' 'rros-0.3.3-x86_64-disk.img', 'container_format': 'bare', 'disk_format': 'qcow2', 'is_public': False} ] # Flavors to create/delete flavors = [ {'name': 'm1.tiny'} # {'name': 'flavorname1', 'disk': '7', 'ram': '64', 'vcpus': '1'}, # Disabled for now, but in the future we need to generate non-pubic flavors # {'name': 'flavorname3', 'disk': '10', 'ram': '32', 'vcpus': '1', # 'is_public': False}, # {'name': 'flavorname2', 'disk': '5', 'ram': '48', 'vcpus': '2'} ] # Security groups to create/delete security_groups = [{'security_groups': [ {'name': 'sg11', 'description': 'Blah blah group', 'rules': [{'ip_protocol': 'icmp', 'from_port': '0', 'to_port': '255', 'cidr': '0.0.0.0/0'}, {'ip_protocol': 'tcp', 'from_port': '80', 'to_port': '80', 'cidr': '0.0.0.0/0'}]}, {'name': 'sg12', 'description': 'Blah blah group2'}]}] # Networks to create/delete # Connected to tenants ext_net = {'name': 'shared_net', 'admin_state_up': True, 'shared': True, 'router:external': True} networks = [ {'name': 'mynetwork1', 'admin_state_up': True}, ] # Subnets to create/delete ext_subnet = {'cidr': '172.18.10.0/24', 'ip_version': 4} subnets = [ {'cidr': '10.4.2.0/24', 'ip_version': 4}, ] # VM's to create/delete vms = [ {'name': 'server1', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server2', 'image': 'image2', 'flavor': 'm1.tiny'}, {'name': 'server3', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server4', 'image': 'image2', 'flavor': 'm1.tiny'}, {'name': 'server5', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server6', 'image': 'image1', 'flavor': 'm1.tiny'} ] routers = [ { 'router': { 'name': 'ext_router', 'external_gateway_info': { 'network_id': 'shared_net'}, 'admin_state_up': True}} ] # VM's snapshots to create/delete snapshots = [ {'server': 'server2', 'image_name': 'asdasd'} ] # Cinder images to create/delete cinder_volumes = [ {'name': 'cinder_volume1', 'size': 1}, {'name': 'cinder_volume2', 'size': 1, 'server_to_attach': 'server2', 'device': '/dev/vdb'} ] # Cinder snapshots to create/delete cinder_snapshots = [ {'display_name': 'snapsh1', 'volume_id': 'cinder_volume1'} ] # Emulate different VM states vm_states = [ {'name': 'server1', 'state': 'error'}, {'name': 'server2', 'state': 'stop'}, {'name': 'server3', 'state': 'suspend'}, {'name': 'server4', 'state': 'pause'}, {'name': 'server5', 'state': 'resize'} ] # Client's versions NOVA_CLIENT_VERSION = '1.1' GLANCE_CLIENT_VERSION = '1' NEUTRON_CLIENT_VERSION = '2.0' CINDER_CLIENT_VERSION = '1'
users = [{'name': 'user1', 'password': 'passwd1', 'email': '[email protected]', 'tenant': 'tenant1', 'enabled': True}, {'name': 'user3', 'password': 'paafdssswd1', 'email': '[email protected]', 'tenant': 'tenant1', 'enabled': False}] roles = [{'name': 'SomeRole'}] keypairs = [{'name': 'key1', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn4vaa1MvLLIQM9G2i9eo2OWoW66i7/tz+F+sSBxjiscmXMGSUxZN1a0yK4TO2l71/MenfAsHCSgu75vyno62JTOLo+QKG07ly8vx9RF+mp+bP/6g0nhcgndOD30NPLEv3vtZbZRDiYeb3inc/ZmAy8kLoRPXE3sW4v+xq+PB2nqu38DUemKU9WlZ9F5Fbhz7aVFDhBjvFNDw7w5nO7zeAFz2RbajJksQlHP62VmkWmTgu/otEuhM8GcjZIXlfHJtv0utMNfqQsNQ8qzt38OKXn/k2czmZX59DXomwdo3DUSmkSHym3kZtZPSTgT6GIGoWA1+QHlhx5kiMVEN+YRZF vagrant'}, {'name': 'key2', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn4vaa1MvLLIQM9G2i9eo2OWoW66i7/tz+F+sSBxjiscmXMGSUxZN1a0yK4TO2l71/MenfAsHCSgu75vyno62JTOLo+QKG07ly8vx9RF+mp+bP/6g0nhcgndOD30NPLEv3vtZbZRDiYeb3inc/ZmAy8kLoRPXE3sW4v+xq+PB2nqu38DUemKU9WlZ9F5Fbhz7aVFDhBjvFNDw7w5nO7zeAFz2RbajJksQlHP62VmkWmTgu/otEuhM8GcjZIXlfHJtv0utMNfqQsNQ8qzt38OKXn/k2czmZX59DXomwdo3DUSmkSHym3kZtZPSTgT6GIGoWA1+QHlhx5kiMVEN+YRZF vagrant'}] images = [{'name': 'image1', 'copy_from': 'http://download.cirros-cloud.net/0.3.3/cirros-0.3.3-x86_64-disk.img', 'is_public': True}, {'name': 'image2', 'copy_from': 'http://download.cirros-cloud.net/0.3.3/cirros-0.3.3-x86_64-disk.img', 'container_format': 'bare', 'disk_format': 'qcow2', 'is_public': False}] flavors = [{'name': 'm1.tiny'}] security_groups = [{'security_groups': [{'name': 'sg11', 'description': 'Blah blah group', 'rules': [{'ip_protocol': 'icmp', 'from_port': '0', 'to_port': '255', 'cidr': '0.0.0.0/0'}, {'ip_protocol': 'tcp', 'from_port': '80', 'to_port': '80', 'cidr': '0.0.0.0/0'}]}, {'name': 'sg12', 'description': 'Blah blah group2'}]}] ext_net = {'name': 'shared_net', 'admin_state_up': True, 'shared': True, 'router:external': True} networks = [{'name': 'mynetwork1', 'admin_state_up': True}] ext_subnet = {'cidr': '172.18.10.0/24', 'ip_version': 4} subnets = [{'cidr': '10.4.2.0/24', 'ip_version': 4}] vms = [{'name': 'server1', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server2', 'image': 'image2', 'flavor': 'm1.tiny'}, {'name': 'server3', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server4', 'image': 'image2', 'flavor': 'm1.tiny'}, {'name': 'server5', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server6', 'image': 'image1', 'flavor': 'm1.tiny'}] routers = [{'router': {'name': 'ext_router', 'external_gateway_info': {'network_id': 'shared_net'}, 'admin_state_up': True}}] snapshots = [{'server': 'server2', 'image_name': 'asdasd'}] cinder_volumes = [{'name': 'cinder_volume1', 'size': 1}, {'name': 'cinder_volume2', 'size': 1, 'server_to_attach': 'server2', 'device': '/dev/vdb'}] cinder_snapshots = [{'display_name': 'snapsh1', 'volume_id': 'cinder_volume1'}] vm_states = [{'name': 'server1', 'state': 'error'}, {'name': 'server2', 'state': 'stop'}, {'name': 'server3', 'state': 'suspend'}, {'name': 'server4', 'state': 'pause'}, {'name': 'server5', 'state': 'resize'}] nova_client_version = '1.1' glance_client_version = '1' neutron_client_version = '2.0' cinder_client_version = '1'
# -*- coding: utf-8 -*- __title__ = 'ci_release_publisher' __description__ = 'A script for publishing Travis-CI build artifacts on GitHub Releases' __version__ = '0.2.0' __url__ = 'https://github.com/nurupo/ci-release-publisher' __author__ = 'Maxim Biro' __author_email__ = '[email protected]' __license__ = 'MIT' __copyright__ = 'Copyright 2018-2020 Maxim Biro'
__title__ = 'ci_release_publisher' __description__ = 'A script for publishing Travis-CI build artifacts on GitHub Releases' __version__ = '0.2.0' __url__ = 'https://github.com/nurupo/ci-release-publisher' __author__ = 'Maxim Biro' __author_email__ = '[email protected]' __license__ = 'MIT' __copyright__ = 'Copyright 2018-2020 Maxim Biro'
n=1260 count=0 list=[500,100,50,10] for coin in list: count += n//coin n %= coin print(count)
n = 1260 count = 0 list = [500, 100, 50, 10] for coin in list: count += n // coin n %= coin print(count)
# MEDIUM # inorder traversal using iterative # Time O(N) Space O(H) class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: return self.iterative(root,k) self.index= 1 self.result = -1 self.inOrder(root,k) return self.result def iterative(self,root,k): stack = [] i = 1 while root or stack: while root: stack.append(root) root = root.left curr = stack.pop() # print(curr.val) if i == k: return curr.val i += 1 if curr.right: root = curr.right def inOrder(self,root,k): if not root: return self.inOrder(root.left,k) # print(root.val,self.index) if self.index == k: self.result = root.val self.index += 1 self.inOrder(root.right,k)
class Solution: def kth_smallest(self, root: TreeNode, k: int) -> int: return self.iterative(root, k) self.index = 1 self.result = -1 self.inOrder(root, k) return self.result def iterative(self, root, k): stack = [] i = 1 while root or stack: while root: stack.append(root) root = root.left curr = stack.pop() if i == k: return curr.val i += 1 if curr.right: root = curr.right def in_order(self, root, k): if not root: return self.inOrder(root.left, k) if self.index == k: self.result = root.val self.index += 1 self.inOrder(root.right, k)
def solution(N): A, B = 0, 0 mult = 1 while N > 0: q, r = divmod(N, 10) if r == 5: A, B = A + mult * 2, B + mult * 3 elif r == 0: A, B = A + mult, B + mult * 9 q -= 1 else: A, B = A + mult, B + mult * (r - 1) mult *= 10 N = q print(A+B) return str(A) + ' ' + str(B) def main(): T = int(input()) for t in range(T): N = int(input()) answer = solution(N) print('Case #' + str(t+1) + ': ' + answer) if __name__ == '__main__': main()
def solution(N): (a, b) = (0, 0) mult = 1 while N > 0: (q, r) = divmod(N, 10) if r == 5: (a, b) = (A + mult * 2, B + mult * 3) elif r == 0: (a, b) = (A + mult, B + mult * 9) q -= 1 else: (a, b) = (A + mult, B + mult * (r - 1)) mult *= 10 n = q print(A + B) return str(A) + ' ' + str(B) def main(): t = int(input()) for t in range(T): n = int(input()) answer = solution(N) print('Case #' + str(t + 1) + ': ' + answer) if __name__ == '__main__': main()
def sum_digits(n): s=0 while n: s += n % 10 n /= 10 return s def factorial(n): if n == 0: return 1 else: return n*factorial(n-1) def sum_factorial_digits(n): return sum_digits(factorial(n)) def main(): print(sum_factorial_digits(10)) print(sum_factorial_digits(100)) print(sum_factorial_digits(500)) if __name__ == "__main__": #test() main()
def sum_digits(n): s = 0 while n: s += n % 10 n /= 10 return s def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) def sum_factorial_digits(n): return sum_digits(factorial(n)) def main(): print(sum_factorial_digits(10)) print(sum_factorial_digits(100)) print(sum_factorial_digits(500)) if __name__ == '__main__': main()
username = input("Please enter your name: ") lastLength = 0 while True: f = open('msgbuffer.txt', 'r+') messages = f.readlines() mailboxSize = len(messages) if mailboxSize > 0 and mailboxSize > lastLength: print( messages[-1] ) lastLength = mailboxSize message = input("|") if message == 'read': print( messages[-1] ) f.write( '%s:%s' % (username, message) ) f.write('\n') f.close()
username = input('Please enter your name: ') last_length = 0 while True: f = open('msgbuffer.txt', 'r+') messages = f.readlines() mailbox_size = len(messages) if mailboxSize > 0 and mailboxSize > lastLength: print(messages[-1]) last_length = mailboxSize message = input('|') if message == 'read': print(messages[-1]) f.write('%s:%s' % (username, message)) f.write('\n') f.close()
#! /usr/bin/env python # _*_ coding:utf-8 _*_ class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSameTree(self, p, q): if not p and not q: return True elif not p or not q: return False elif p.val != q.val: return False if self.isSameTree(p.left, q.left): return self.isSameTree(p.right, q.right) else: return False def gen_tree(nums): for i, n in enumerate(nums): node = TreeNode(n) nums[i] = node root = nums[0] if __name__ == '__main__': so = Solution() def test(): pass test()
class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def is_same_tree(self, p, q): if not p and (not q): return True elif not p or not q: return False elif p.val != q.val: return False if self.isSameTree(p.left, q.left): return self.isSameTree(p.right, q.right) else: return False def gen_tree(nums): for (i, n) in enumerate(nums): node = tree_node(n) nums[i] = node root = nums[0] if __name__ == '__main__': so = solution() def test(): pass test()
class disjoint_set: def __init__(self,vertex): self.parent = self self.rank = 0 self.vertex = vertex def find(self): if self.parent != self: self.parent = self.parent.find() return self.parent def joinSets(self,otherTree): root = self.find() otherTreeRoot = otherTree.find() if root == otherTreeRoot: return if root.rank < otherTreeRoot.rank: root.parent = otherTreeRoot elif otherTreeRoot.rank < root.rank: otherTreeRoot.parent = root else: otherTreeRoot.parent = root root.rank += 1
class Disjoint_Set: def __init__(self, vertex): self.parent = self self.rank = 0 self.vertex = vertex def find(self): if self.parent != self: self.parent = self.parent.find() return self.parent def join_sets(self, otherTree): root = self.find() other_tree_root = otherTree.find() if root == otherTreeRoot: return if root.rank < otherTreeRoot.rank: root.parent = otherTreeRoot elif otherTreeRoot.rank < root.rank: otherTreeRoot.parent = root else: otherTreeRoot.parent = root root.rank += 1
def get_test_data(): return { "contact": { "name": "Paul Kempa", "company": "Baltimore Steel Factory" }, "invoice": { "items": [ { "quantity": 12, "description": "Item description No.0", "unitprice": 12000.3, "linetotal": 20 }, { "quantity": 1290, "description": "Item description No.0", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.1", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.2", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.3", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.4", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.5", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.6", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.7", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.8", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.9", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.10", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.11", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.12", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.13", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.14", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.15", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.16", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.17", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.18", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.19", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.20", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.21", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.22", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.23", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.24", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.25", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.26", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.27", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.28", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.29", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.30", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.31", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.32", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.33", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.34", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.35", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.36", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.37", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.38", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.39", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.40", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.41", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.42", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.43", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.44", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.45", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.46", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.47", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.48", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.49", "unitprice": 12.3, "linetotal": 20000 } ], "total": 50000000.01 } }
def get_test_data(): return {'contact': {'name': 'Paul Kempa', 'company': 'Baltimore Steel Factory'}, 'invoice': {'items': [{'quantity': 12, 'description': 'Item description No.0', 'unitprice': 12000.3, 'linetotal': 20}, {'quantity': 1290, 'description': 'Item description No.0', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.1', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.2', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.3', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.4', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.5', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.6', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.7', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.8', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.9', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.10', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.11', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.12', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.13', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.14', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.15', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.16', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.17', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.18', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.19', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.20', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.21', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.22', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.23', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.24', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.25', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.26', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.27', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.28', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.29', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.30', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.31', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.32', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.33', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.34', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.35', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.36', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.37', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.38', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.39', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.40', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.41', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.42', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.43', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.44', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.45', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.46', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.47', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.48', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.49', 'unitprice': 12.3, 'linetotal': 20000}], 'total': 50000000.01}}
class Node: def __init__(self, data, next=None): self.data = data self.next = next class LinkedList: def __init__(self, *args, **kwargs): self.head = Node(None) def appende(self, data): node = Node(data) node.next = self.head self.head = node # Print linked list def print_my_list(self): node = self.head while node.next is not None: print(node.data, end=" ") node = node.next # count number of node in linked list def countNodes(self): count = 0 node = self.head while node.next is not None: count += 1 node = node.next return count def Kth(self, k): # Count nodes in linked list n = self.countNodes() # check if k is valid if n < k: return if (2 * k - 1) == n: return x = self.head x_prev = Node(None) for i in range(k - 1): x_prev = x x = x.next y = self.head y_prev = Node(None) for i in range(n - k): y_prev = y y = y.next if x_prev is not None: x_prev.next = y # Same thing applies to y_prev if y_prev is not None: y_prev.next = x temp = x.next x.next = y.next y.next = temp # Change head pointers when k is 1 or n if k == 1: self.head = y if k == n: self.head = x if __name__ == '__main__': My_List = LinkedList() for i in range(8, 0, -1): My_List.appende(i) My_List.appende(7) My_List.appende(6) My_List.appende(5) My_List.appende(4) My_List.appende(3) My_List.appende(2) My_List.appende(1) My_List.print_my_list() for i in range(1, 9): My_List.Kth(i) print("Modified List for k = ", i) My_List.print_my_list() print("\n")
class Node: def __init__(self, data, next=None): self.data = data self.next = next class Linkedlist: def __init__(self, *args, **kwargs): self.head = node(None) def appende(self, data): node = node(data) node.next = self.head self.head = node def print_my_list(self): node = self.head while node.next is not None: print(node.data, end=' ') node = node.next def count_nodes(self): count = 0 node = self.head while node.next is not None: count += 1 node = node.next return count def kth(self, k): n = self.countNodes() if n < k: return if 2 * k - 1 == n: return x = self.head x_prev = node(None) for i in range(k - 1): x_prev = x x = x.next y = self.head y_prev = node(None) for i in range(n - k): y_prev = y y = y.next if x_prev is not None: x_prev.next = y if y_prev is not None: y_prev.next = x temp = x.next x.next = y.next y.next = temp if k == 1: self.head = y if k == n: self.head = x if __name__ == '__main__': my__list = linked_list() for i in range(8, 0, -1): My_List.appende(i) My_List.appende(7) My_List.appende(6) My_List.appende(5) My_List.appende(4) My_List.appende(3) My_List.appende(2) My_List.appende(1) My_List.print_my_list() for i in range(1, 9): My_List.Kth(i) print('Modified List for k = ', i) My_List.print_my_list() print('\n')
# # PySNMP MIB module Wellfleet-NPK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-NPK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:34:31 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibIdentifier, Gauge32, Bits, Counter32, NotificationType, IpAddress, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Counter64, TimeTicks, ModuleIdentity, Integer32, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Gauge32", "Bits", "Counter32", "NotificationType", "IpAddress", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Counter64", "TimeTicks", "ModuleIdentity", "Integer32", "ObjectIdentity") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") wfGameGroup, = mibBuilder.importSymbols("Wellfleet-COMMON-MIB", "wfGameGroup") wfNpkBase = MibIdentifier((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8)) wfNpkBaseCreate = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNpkBaseCreate.setStatus('mandatory') wfNpkBaseHash = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 2), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNpkBaseHash.setStatus('mandatory') wfNpkBaseLastMod = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNpkBaseLastMod.setStatus('mandatory') mibBuilder.exportSymbols("Wellfleet-NPK-MIB", wfNpkBase=wfNpkBase, wfNpkBaseHash=wfNpkBaseHash, wfNpkBaseLastMod=wfNpkBaseLastMod, wfNpkBaseCreate=wfNpkBaseCreate)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_union, constraints_intersection, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueSizeConstraint') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (mib_identifier, gauge32, bits, counter32, notification_type, ip_address, iso, mib_scalar, mib_table, mib_table_row, mib_table_column, unsigned32, counter64, time_ticks, module_identity, integer32, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'Gauge32', 'Bits', 'Counter32', 'NotificationType', 'IpAddress', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32', 'Counter64', 'TimeTicks', 'ModuleIdentity', 'Integer32', 'ObjectIdentity') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') (wf_game_group,) = mibBuilder.importSymbols('Wellfleet-COMMON-MIB', 'wfGameGroup') wf_npk_base = mib_identifier((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8)) wf_npk_base_create = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('created', 1), ('deleted', 2))).clone('created')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfNpkBaseCreate.setStatus('mandatory') wf_npk_base_hash = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 2), octet_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfNpkBaseHash.setStatus('mandatory') wf_npk_base_last_mod = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 3), display_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfNpkBaseLastMod.setStatus('mandatory') mibBuilder.exportSymbols('Wellfleet-NPK-MIB', wfNpkBase=wfNpkBase, wfNpkBaseHash=wfNpkBaseHash, wfNpkBaseLastMod=wfNpkBaseLastMod, wfNpkBaseCreate=wfNpkBaseCreate)
def retrieveDB_data(db, option, title): data_ref = db.collection(option).document(title) docs = data_ref.get() return docs.to_dict() async def initDB(db, objectList, objectDb, firestore): if objectList is None: data = {"create": "create"} objectDb.set(data) objectDb.update({"create": firestore.DELETE_FIELD}) return async def checkChannel(db, firestore, channelId, guildId): channel_fetch = retrieveDB_data(db, option="channel-list", title=str(guildId)) channel_DB_init = db.collection("channel-list").document(str(guildId)) await initDB(db, channel_fetch, channel_DB_init, firestore) try: channelVerify = channel_fetch[f"{channelId}"] except (KeyError, TypeError): return return channelVerify async def checkUser(db, firestore, userId, guildId): user_projects = retrieveDB_data(db, option="user-projects", title=str(guildId)) user_projectsDB = db.collection("user-projects").document(str(guildId)) await initDB(db, user_projects, user_projectsDB, firestore) try: userVerify = user_projects[str(userId)] except (KeyError, TypeError): return return userVerify async def check_existingProject(db, mention, project, guildId): user_projects = retrieveDB_data(db, option="user-projects", title=str(guildId)) userProject = user_projects[str(mention)] if str(userProject) != str(project): return userProject return
def retrieve_db_data(db, option, title): data_ref = db.collection(option).document(title) docs = data_ref.get() return docs.to_dict() async def initDB(db, objectList, objectDb, firestore): if objectList is None: data = {'create': 'create'} objectDb.set(data) objectDb.update({'create': firestore.DELETE_FIELD}) return async def checkChannel(db, firestore, channelId, guildId): channel_fetch = retrieve_db_data(db, option='channel-list', title=str(guildId)) channel_db_init = db.collection('channel-list').document(str(guildId)) await init_db(db, channel_fetch, channel_DB_init, firestore) try: channel_verify = channel_fetch[f'{channelId}'] except (KeyError, TypeError): return return channelVerify async def checkUser(db, firestore, userId, guildId): user_projects = retrieve_db_data(db, option='user-projects', title=str(guildId)) user_projects_db = db.collection('user-projects').document(str(guildId)) await init_db(db, user_projects, user_projectsDB, firestore) try: user_verify = user_projects[str(userId)] except (KeyError, TypeError): return return userVerify async def check_existingProject(db, mention, project, guildId): user_projects = retrieve_db_data(db, option='user-projects', title=str(guildId)) user_project = user_projects[str(mention)] if str(userProject) != str(project): return userProject return
BLACK = -999 DEFAULT = 0 NORMAL = 1 PRIVATE = 10 ADMIN = 21 OWNER = 22 WHITE = 51 SUPERUSER = 999 SU = SUPERUSER
black = -999 default = 0 normal = 1 private = 10 admin = 21 owner = 22 white = 51 superuser = 999 su = SUPERUSER
################################################# Cars = [["Lamborghini", 1000000, 2, 40000], ["Ferrari", 1500000, 2.5, 50000], ["BMW", 800000, 1.5, 20000]] ################################################# print("#"*80) print("#" + "Welcome to XYZ Car Dealership".center(78) + "#") print("#"*80 + "\n") while True: print("#"*80) print("#" + "What Would You Like To Do Today?".center(78) + "#") print("#" + "A) Buy A Car ".center(78) + "#") print("#" + "B) Rent A Car".center(78) + "#") print("#"*80 + "\n") mode = input("Choose Option (A/B):\t").lower() while mode not in "ab" and mode != "ab": mode = input("Choose Option (A/B):\t").lower() if mode == "a": print("#"*80) print("#" + "Choose A Car".center(78) + "#") print("#" + "1) Lamborghini ".center(78) + "#") print("#" + "2) Ferrari ".center(78) + "#") print("#" + "3) BMW ".center(78) + "#") print("#" + "4) Input Your own Car".center(78) + "#") print("#"*80) op = int(input("Choose Option: ")) while op != 1 and op != 2 and op != 3 and op != 4: op = int(input("Choose Option: ")) if op == 4: buyPrice = int(input("Enter Buy Price of Car: ")) maintainanceCostPercentage = int(input("Enter Annual Maintainance Percentage of Car: ")) years = int(input("How many Years: ")) else: i = op-1 print("Checking for " + Cars[i][0] + "...") years = int(input("How many Years: ")) buyPrice = Cars[i][1] maintainanceCostPercentage = Cars[i][2] Price = buyPrice + buyPrice * (years-1) * maintainanceCostPercentage / 100 p = "Buy For $" + str(Price) print("\n" + "#"*80) print("#" + "Receipt".center(78) + "#") print("#" + "-------".center(78) + "#") print("#" + "".center(78) + "#") print("#" + p.center(78) + "#") print("#"*80) elif mode == "b": print("#"*80) print("#" + "Choose A Car".center(78) + "#") print("#" + "1) Lamborghini ".center(78) + "#") print("#" + "2) Ferrari ".center(78) + "#") print("#" + "3) BMW ".center(78) + "#") print("#" + "4) Input Your own Car".center(78) + "#") print("#"*80) op = int(input("Choose Option: ")) while op != 1 and op != 2 and op != 3 and op != 4: op = int(input("Choose Option: ")) if op == 4: rent = int(input("Enter monthly Rental Price of Car: ")) months = int(input("How many Months: ")) else: i = op-1 months = int(input("How many Months: ")) rent = Cars[i][3] Price = months * rent p = "\n\nPrice to rent for " + str(months) + " months is $" + str(Price) print("\n" + "#"*80) print("#" + "Receipt".center(78) + "#") print("#" + "-------".center(78) + "#") print("#" + "".center(78) + "#") print("#" + p.center(78) + "#") print("#"*80) if input("Would You like to Exit? (y/n) ").lower() == "y": break print("#"*80) print("#" + "Thank You!".center(78) + "#") print("#"*80)
cars = [['Lamborghini', 1000000, 2, 40000], ['Ferrari', 1500000, 2.5, 50000], ['BMW', 800000, 1.5, 20000]] print('#' * 80) print('#' + 'Welcome to XYZ Car Dealership'.center(78) + '#') print('#' * 80 + '\n') while True: print('#' * 80) print('#' + 'What Would You Like To Do Today?'.center(78) + '#') print('#' + 'A) Buy A Car '.center(78) + '#') print('#' + 'B) Rent A Car'.center(78) + '#') print('#' * 80 + '\n') mode = input('Choose Option (A/B):\t').lower() while mode not in 'ab' and mode != 'ab': mode = input('Choose Option (A/B):\t').lower() if mode == 'a': print('#' * 80) print('#' + 'Choose A Car'.center(78) + '#') print('#' + '1) Lamborghini '.center(78) + '#') print('#' + '2) Ferrari '.center(78) + '#') print('#' + '3) BMW '.center(78) + '#') print('#' + '4) Input Your own Car'.center(78) + '#') print('#' * 80) op = int(input('Choose Option: ')) while op != 1 and op != 2 and (op != 3) and (op != 4): op = int(input('Choose Option: ')) if op == 4: buy_price = int(input('Enter Buy Price of Car: ')) maintainance_cost_percentage = int(input('Enter Annual Maintainance Percentage of Car: ')) years = int(input('How many Years: ')) else: i = op - 1 print('Checking for ' + Cars[i][0] + '...') years = int(input('How many Years: ')) buy_price = Cars[i][1] maintainance_cost_percentage = Cars[i][2] price = buyPrice + buyPrice * (years - 1) * maintainanceCostPercentage / 100 p = 'Buy For $' + str(Price) print('\n' + '#' * 80) print('#' + 'Receipt'.center(78) + '#') print('#' + '-------'.center(78) + '#') print('#' + ''.center(78) + '#') print('#' + p.center(78) + '#') print('#' * 80) elif mode == 'b': print('#' * 80) print('#' + 'Choose A Car'.center(78) + '#') print('#' + '1) Lamborghini '.center(78) + '#') print('#' + '2) Ferrari '.center(78) + '#') print('#' + '3) BMW '.center(78) + '#') print('#' + '4) Input Your own Car'.center(78) + '#') print('#' * 80) op = int(input('Choose Option: ')) while op != 1 and op != 2 and (op != 3) and (op != 4): op = int(input('Choose Option: ')) if op == 4: rent = int(input('Enter monthly Rental Price of Car: ')) months = int(input('How many Months: ')) else: i = op - 1 months = int(input('How many Months: ')) rent = Cars[i][3] price = months * rent p = '\n\nPrice to rent for ' + str(months) + ' months is $' + str(Price) print('\n' + '#' * 80) print('#' + 'Receipt'.center(78) + '#') print('#' + '-------'.center(78) + '#') print('#' + ''.center(78) + '#') print('#' + p.center(78) + '#') print('#' * 80) if input('Would You like to Exit? (y/n) ').lower() == 'y': break print('#' * 80) print('#' + 'Thank You!'.center(78) + '#') print('#' * 80)
n1 = 0 n2 = 0 choice = 4 high_number = n1 while choice != 5: while choice == 4: print('=' * 50) n1 = int(input('Choose a number: ')) n2 = int(input('Choose another number: ')) if n1 > n2: high_number = n1 else: high_number = n2 print('=' * 45) print('What do you want to do with the numbers?') print('[1] to add them up.') print('[2] to multiply them.') print('[3] to find the higher number.') print('[4] to choose new numbers.') print('[5] nothing, quit the program.') choice = int(input('')) if choice == 1: print(f'The sum of the entered values is {n1 + n2}.') choice = 5 elif choice == 2: print(f'The product of the numbers entered is {n1 * n2}') choice = 5 elif choice == 3: print(f'The higher number entered was {high_number}') choice = 5
n1 = 0 n2 = 0 choice = 4 high_number = n1 while choice != 5: while choice == 4: print('=' * 50) n1 = int(input('Choose a number: ')) n2 = int(input('Choose another number: ')) if n1 > n2: high_number = n1 else: high_number = n2 print('=' * 45) print('What do you want to do with the numbers?') print('[1] to add them up.') print('[2] to multiply them.') print('[3] to find the higher number.') print('[4] to choose new numbers.') print('[5] nothing, quit the program.') choice = int(input('')) if choice == 1: print(f'The sum of the entered values is {n1 + n2}.') choice = 5 elif choice == 2: print(f'The product of the numbers entered is {n1 * n2}') choice = 5 elif choice == 3: print(f'The higher number entered was {high_number}') choice = 5
white = { "Flour": "100", "Water": "65", "Oil": "4", "Salt": "2", "Yeast": "1.5" }
white = {'Flour': '100', 'Water': '65', 'Oil': '4', 'Salt': '2', 'Yeast': '1.5'}
class Row: def __init__(self, title=None, columns=None, properties=None): self.title = title self.columns = columns or [] self.properties = properties or [] def __str__(self): return str(self.title) def __len__(self): return len(self.title or '') def __iter__(self): yield from self.columns def add_cell(self, cell): self.columns.append(cell) def add_property(self, property): self.properties.append(property)
class Row: def __init__(self, title=None, columns=None, properties=None): self.title = title self.columns = columns or [] self.properties = properties or [] def __str__(self): return str(self.title) def __len__(self): return len(self.title or '') def __iter__(self): yield from self.columns def add_cell(self, cell): self.columns.append(cell) def add_property(self, property): self.properties.append(property)
#!/usr/bin/env python3 def readFile(filename): #READFILE reads a file and returns its entire contents # file_contents = READFILE(filename) reads a file and returns its entire # contents in file_contents # # Load File with open(filename) as fid: file_contents = fid.read() #end return file_contents #end
def read_file(filename): with open(filename) as fid: file_contents = fid.read() return file_contents
# values_only # Function which accepts a dictionary of key value pairs and returns a new flat list of only the values. # # Uses the .items() function with a for loop on the dictionary to track both the key and value of the iteration and # returns a new list by appending the values to it. Best used on 1 level-deep key:value pair dictionaries and not # nested data-structures. def values_only(dictionary): lst = [] for v in dictionary.values(): lst.append(v) # for k, v in dictionary.items(): # lst.append(v) return lst ages = { "Peter": 10, "Isabel": 11, "Anna": 9, } print(values_only(ages)) # [10, 11, 9]
def values_only(dictionary): lst = [] for v in dictionary.values(): lst.append(v) return lst ages = {'Peter': 10, 'Isabel': 11, 'Anna': 9} print(values_only(ages))
# Example 1: Showing the Root Mean Squared Error (RMSE) metric. Penalises large residuals # Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {"objective":"reg:linear", "max_depth":4} # Perform cross-validation: cv_results cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='rmse', as_pandas=True, seed=123) # Print cv_results print(cv_results) # Extract and print final boosting round metric print((cv_results["test-rmse-mean"]).tail(1)) # Example 2: Showing the Mean Absolute Error (MAE) metric # Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {"objective":"reg:linear", "max_depth":4} # Perform cross-validation: cv_results cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='mae', as_pandas=True, seed=123) # Print cv_results print(cv_results) # Extract and print final boosting round metric print((cv_results["test-mae-mean"]).tail(1))
housing_dmatrix = xgb.DMatrix(data=X, label=y) params = {'objective': 'reg:linear', 'max_depth': 4} cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='rmse', as_pandas=True, seed=123) print(cv_results) print(cv_results['test-rmse-mean'].tail(1)) housing_dmatrix = xgb.DMatrix(data=X, label=y) params = {'objective': 'reg:linear', 'max_depth': 4} cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='mae', as_pandas=True, seed=123) print(cv_results) print(cv_results['test-mae-mean'].tail(1))
# Author: Isabella Doyle # this is the menu def displayMenu(): print("What would you like to do?") print("\t(a) Add new student") print("\t(v) View students") print("\t(q) Quit") # strips any whitespace from the left/right of the string option = input("Please select an option (a/v/q): ").strip() return option def doAdd(students): studentDict = {} studentDict["Name"] = input("Enter student's name: ") studentDict["module"] = readModules() students.append(studentDict) def readModules(): modules = [] moduleName = input("\tEnter the first module name (blank to quit): ").strip() while moduleName != "": module = {} module["Name"] = moduleName module["Grade"] = int(input("\t\tEnter grade: ").strip()) modules.append(module) moduleName = input("\tEnter the next module name (blank to quit): ").strip() return modules def doView(): print(students) # main program students = [] selection = displayMenu() while (selection != ""): if selection == "a": doAdd(students) elif selection == "v": doView() else: print("Invalid input entered.") print(students)
def display_menu(): print('What would you like to do?') print('\t(a) Add new student') print('\t(v) View students') print('\t(q) Quit') option = input('Please select an option (a/v/q): ').strip() return option def do_add(students): student_dict = {} studentDict['Name'] = input("Enter student's name: ") studentDict['module'] = read_modules() students.append(studentDict) def read_modules(): modules = [] module_name = input('\tEnter the first module name (blank to quit): ').strip() while moduleName != '': module = {} module['Name'] = moduleName module['Grade'] = int(input('\t\tEnter grade: ').strip()) modules.append(module) module_name = input('\tEnter the next module name (blank to quit): ').strip() return modules def do_view(): print(students) students = [] selection = display_menu() while selection != '': if selection == 'a': do_add(students) elif selection == 'v': do_view() else: print('Invalid input entered.') print(students)
def my_sum(n): return sum(list(map(int, n))) def resolve(): n, a, b = list(map(int, input().split())) counter = 0 for i in range(n + 1): if a <= my_sum(str(i)) <= b: counter += i print(counter)
def my_sum(n): return sum(list(map(int, n))) def resolve(): (n, a, b) = list(map(int, input().split())) counter = 0 for i in range(n + 1): if a <= my_sum(str(i)) <= b: counter += i print(counter)