content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/python3 # -*- coding: utf-8 -*- class Weather: def __init__(self, temp): self.temp = temp class Person: def __init__(self, name, age): self.name = name self.age = age class Application: def __init__(self): pass def get_webpage(self): print('From application') clas...
class Weather: def __init__(self, temp): self.temp = temp class Person: def __init__(self, name, age): self.name = name self.age = age class Application: def __init__(self): pass def get_webpage(self): print('From application') class Creatdb: def __ini...
""" """ load("@bazel_skylib//lib:paths.bzl", "paths") load("@fbcode_macros//build_defs/lib/thrift:thrift_interface.bzl", "thrift_interface") load("@fbcode_macros//build_defs/lib:haskell_common.bzl", "haskell_common") load("@fbcode_macros//build_defs/lib:haskell_rules.bzl", "haskell_rules") load("@fbcode_macros//build_...
""" """ load('@bazel_skylib//lib:paths.bzl', 'paths') load('@fbcode_macros//build_defs/lib/thrift:thrift_interface.bzl', 'thrift_interface') load('@fbcode_macros//build_defs/lib:haskell_common.bzl', 'haskell_common') load('@fbcode_macros//build_defs/lib:haskell_rules.bzl', 'haskell_rules') load('@fbcode_macros//build_d...
def zero_fuel(distance_to_pump, mpg, fuel_left): #Happy Coding! ;) if distance_to_pump<=fuel_left*mpg: return 1 else: return 0
def zero_fuel(distance_to_pump, mpg, fuel_left): if distance_to_pump <= fuel_left * mpg: return 1 else: return 0
[ ## list of dictionnaries for different arities of the same functor { 'functor' : { ## intrinsics values related to functor 'arity' : 2, ## functor number of parameters #'ret_arity' : "2", ## must be '0' or omitted if not a tuple 'types' : ['real_'],##, 'unsigned_int_', 'sign...
[{'functor': {'arity': 2, 'types': ['real_'], 'rturn': {'default': 'typename boost::result_of<nt2::meta::floating(T)>::type'}, 'call_types': ['T', 'iT'], 'type_defs': ['typedef int iT;']}, 'unit': {'all_parts': {'first_stamp': 'created by $author$ the $date$', 'stamp': 'modified by $author$ the $date$'}, 'global_heade...
# Sphinx uses the all list to check every module is loaded, but in some cases it is not and a warning is generated: # missing attribute mentioned in :members: or __all__: module """Allows users to do ``from xyz import *`` """ __all__ = ["couchdb", "mongodb"]
"""Allows users to do ``from xyz import *`` """ __all__ = ['couchdb', 'mongodb']
print("Dados da primeira pessoa") nome1 = input("Nome: ") idade1 = int(input("Idade: ")) print("Dados da segunda pessoa ") nome2 = input("Nome: ") idade2 = int(input("Idade: ")) media = (idade1 + idade2) / 2 print(f"A idade media de {nome1} e {nome2} e de {media:.1f} anos")
print('Dados da primeira pessoa') nome1 = input('Nome: ') idade1 = int(input('Idade: ')) print('Dados da segunda pessoa ') nome2 = input('Nome: ') idade2 = int(input('Idade: ')) media = (idade1 + idade2) / 2 print(f'A idade media de {nome1} e {nome2} e de {media:.1f} anos')
#!/usr/bin/env python3 def DAfromTopWdth(TopWdth): return (TopWdth/2.44) ** 2.941176470588235 def CSA(DA): return 0.75 * DA ** 0.53 def cross_section_area_BlckBrn(TopWdth): ''' Calculate channel cross sectional area from channel Top Width using Blackburn et al. 2017 equations ''' cs_area ...
def d_afrom_top_wdth(TopWdth): return (TopWdth / 2.44) ** 2.941176470588235 def csa(DA): return 0.75 * DA ** 0.53 def cross_section_area__blck_brn(TopWdth): """ Calculate channel cross sectional area from channel Top Width using Blackburn et al. 2017 equations """ cs_area = 0.75 * ((TopWdt...
# %% #caesar cipher class his_cip: def __init__(self): self.alf = "abcdefghijklmnopqrstuvwxyz" self.alf2 = self.alf*2 self.len_ = len(self.alf) def caesar_enc(self,plaintext,key): ciphertext = "" alpha = self.alf*2 #replace dots and getting all in lower ...
class His_Cip: def __init__(self): self.alf = 'abcdefghijklmnopqrstuvwxyz' self.alf2 = self.alf * 2 self.len_ = len(self.alf) def caesar_enc(self, plaintext, key): ciphertext = '' alpha = self.alf * 2 plaintext = plaintext.lower() if isinstance(plaintext...
# /xhr/resources/conditional.py -- to fake a 304 response def main(request, response): tag = request.GET.first(b"tag", None) redirect = request.GET.first(b"redirect", None) match = request.headers.get(b"If-None-Match", None) date = request.GET.first(b"date", b"") modified = request.headers.get(b"If...
def main(request, response): tag = request.GET.first(b'tag', None) redirect = request.GET.first(b'redirect', None) match = request.headers.get(b'If-None-Match', None) date = request.GET.first(b'date', b'') modified = request.headers.get(b'If-Modified-Since', None) response.headers.set(b'Access-C...
""" For more details regarding inputs and output in form of complex dictionaries see the original source docs at: %host%/docs/source/ProjectInterface.html for example: `https://editor.webgme.org/docs/source/ProjectInterface.html <https://editor.webgme.org/docs/source/ProjectInterface.html>`_ """ class P...
""" For more details regarding inputs and output in form of complex dictionaries see the original source docs at: %host%/docs/source/ProjectInterface.html for example: `https://editor.webgme.org/docs/source/ProjectInterface.html <https://editor.webgme.org/docs/source/ProjectInterface.html>`_ """ class Project(objec...
__title__ = 'emailer' __description__ = 'Send scheduled emails' __url__ = 'https://github.com/WhiteHalmos/emailer' __author__ = 'Peter Wen' __author_email__ = 'peter@whitehalmos.org' __license__ = 'MIT' __version__ = '1.0.17-dev'
__title__ = 'emailer' __description__ = 'Send scheduled emails' __url__ = 'https://github.com/WhiteHalmos/emailer' __author__ = 'Peter Wen' __author_email__ = 'peter@whitehalmos.org' __license__ = 'MIT' __version__ = '1.0.17-dev'
def runLengthEncoding(string): curr_mult = 1 new_str = [] for i in range(len(string) - 1): if string[i] != string[i + 1] or curr_mult == 9: new_str.append(str(curr_mult) + string[i]) curr_mult = 1 else: curr_mult += 1 return ''.join(new_str + [str(cu...
def run_length_encoding(string): curr_mult = 1 new_str = [] for i in range(len(string) - 1): if string[i] != string[i + 1] or curr_mult == 9: new_str.append(str(curr_mult) + string[i]) curr_mult = 1 else: curr_mult += 1 return ''.join(new_str + [str(cu...
ASSETS = [ { "name": "Very Conservative Streep", "id": 15077 }, { "name": "Conservative Clooney", "id": 188 }, { "name": "Moderate Pit", "id": 187 }, { "name": "Risky Norris", "id": 186 } ]
assets = [{'name': 'Very Conservative Streep', 'id': 15077}, {'name': 'Conservative Clooney', 'id': 188}, {'name': 'Moderate Pit', 'id': 187}, {'name': 'Risky Norris', 'id': 186}]
#!/usr/bin/python # /**************************************************************************** # exportKML # Copyright (c) 2014-2018, Kjeld Jensen <kj@kjen.dk> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following condi...
""" 2015-03-22 Kjeld Removed unnecessary trkptend() function 2015-11-18 Kjeld Added optional absolute altitude mode 2018-03-13 Kjeld Added a """ class Kmlclass: def __init__(self): return def begin(self, fname, name, desc, width): self.f = open(fname, 'w') self.f.write('<?xml version...
''' URL: https://leetcode.com/problems/minimum-depth-of-binary-tree/ Difficulty: Easy Description: Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with...
""" URL: https://leetcode.com/problems/minimum-depth-of-binary-tree/ Difficulty: Easy Description: Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Note: A leaf is a node with...
class B: def __init__(self,a,b,c,**others): self.a = a self.b = b self.c = c def verify(self): print(self.a,self.b,self.c) args = {'a':10,'b':20,'c':30,'extra':'unexpected'} x = B(**args) x.verify()
class B: def __init__(self, a, b, c, **others): self.a = a self.b = b self.c = c def verify(self): print(self.a, self.b, self.c) args = {'a': 10, 'b': 20, 'c': 30, 'extra': 'unexpected'} x = b(**args) x.verify()
for _ in range(int(input())): n = int(input()) _n = int(str(n)[::-1]) res = str(n + _n) print('YES' if res == res[::-1] else 'NO')
for _ in range(int(input())): n = int(input()) _n = int(str(n)[::-1]) res = str(n + _n) print('YES' if res == res[::-1] else 'NO')
# Copyright (c) 2021 Qualcomm Technologies, Inc. # All Rights Reserved. class map_output_transform: def __init__(self, video_level=False): self.video_level = video_level def __call__(self, output): probs, y_mh, ids = output if self.video_level: ids = [x.rsplit("...
class Map_Output_Transform: def __init__(self, video_level=False): self.video_level = video_level def __call__(self, output): (probs, y_mh, ids) = output if self.video_level: ids = [x.rsplit('_', 1)[0] for x in ids] return (probs.squeeze(dim=1), y_mh, ids)
input = """120183 105169 58942 105283 100729 57778 59601 86011 148930 76533 132625 79105 66334 87695 148836 129384 71225 96010 67221 139037 90010 72531 145543 137983 63687 131307 62602 129223 76717 98896 58484 127996 128840 60723 149932 141443 96997 96196 104670 104055 129552 54426 104507 80241 91570 140053 106108 1197...
input = '120183\n105169\n58942\n105283\n100729\n57778\n59601\n86011\n148930\n76533\n132625\n79105\n66334\n87695\n148836\n129384\n71225\n96010\n67221\n139037\n90010\n72531\n145543\n137983\n63687\n131307\n62602\n129223\n76717\n98896\n58484\n127996\n128840\n60723\n149932\n141443\n96997\n96196\n104670\n104055\n129552\n5442...
def test_command_char(): assert True # Placeholder
def test_command_char(): assert True
class SessionHelper: def __init__(self, app): self.app = app def login(self, login, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_xpath("//*[@id='username']").send_keys(login) wd.find_element_by_css_selector(".width-40").click() wd.fi...
class Sessionhelper: def __init__(self, app): self.app = app def login(self, login, password): wd = self.app.wd self.app.open_home_page() wd.find_element_by_xpath("//*[@id='username']").send_keys(login) wd.find_element_by_css_selector('.width-40').click() wd.fin...
W=lambda A:(ord(A[0])-ord('A'))*26*26+(ord(A[1])-ord('A'))*26+(ord(A[2])-ord('A')) for _ in range(int(input())): A,B=input().split('-') if abs(W(A)-int(B))<=100: print('nice') else: print('not nice')
w = lambda A: (ord(A[0]) - ord('A')) * 26 * 26 + (ord(A[1]) - ord('A')) * 26 + (ord(A[2]) - ord('A')) for _ in range(int(input())): (a, b) = input().split('-') if abs(w(A) - int(B)) <= 100: print('nice') else: print('not nice')
for _ in range(int(input())): n,k=map(int,input().split()) n1=n arr=list(map(int,input().split())) maxe=max(arr)+1 arr.sort() k1=k while(k1): k1-=1 arr.append(maxe) print(arr[(n1+k)//2])
for _ in range(int(input())): (n, k) = map(int, input().split()) n1 = n arr = list(map(int, input().split())) maxe = max(arr) + 1 arr.sort() k1 = k while k1: k1 -= 1 arr.append(maxe) print(arr[(n1 + k) // 2])
# coding: utf-8 create_app_validate = { "type": "object", "properties": { "name": {"type": "string"}, "nick_name": {"type": "string"}, "env_id": {"type": "string"} }, "required": ["name", "nick_name", "env_id"], "additionalProperties": True } update_application_validate = { ...
create_app_validate = {'type': 'object', 'properties': {'name': {'type': 'string'}, 'nick_name': {'type': 'string'}, 'env_id': {'type': 'string'}}, 'required': ['name', 'nick_name', 'env_id'], 'additionalProperties': True} update_application_validate = {'type': 'object', 'properties': {'application_id': {'type': 'strin...
# -*- coding: utf-8 -*- tables_and_views = [ { "schema_object_id": 16441, "table_schema": "app", "table_object_id": 16442, "table_name": "customers", "table_type": "base table", "properties": {}, "columns": [ { "column_object_id":...
tables_and_views = [{'schema_object_id': 16441, 'table_schema': 'app', 'table_object_id': 16442, 'table_name': 'customers', 'table_type': 'base table', 'properties': {}, 'columns': [{'column_object_id': '16442/1', 'column_name': 'customernumber', 'column_description': None, 'ordinal_position': 1, 'data_type': 'integer'...
outFile = open('cdf_transcription.sub.format.csv','w') with open('cdf_transcription.sub.tsv','r') as inFile: firstLine = inFile.readline().split() firstLine = ','.join(firstLine) outFile.write(firstLine) for line in inFile: line = line.split() gene = line[0].split('|')[0] entry = [gene] for x in line[1...
out_file = open('cdf_transcription.sub.format.csv', 'w') with open('cdf_transcription.sub.tsv', 'r') as in_file: first_line = inFile.readline().split() first_line = ','.join(firstLine) outFile.write(firstLine) for line in inFile: line = line.split() gene = line[0].split('|')[0] e...
class Data: def __init__(self, alrd, v, score, cin, vv): self.alrd = alrd self.v = v self.score = score self.cin = cin self.vv = vv
class Data: def __init__(self, alrd, v, score, cin, vv): self.alrd = alrd self.v = v self.score = score self.cin = cin self.vv = vv
#! /usr/bin/env python __author__ = "Andy Tsang" __credits__ = ["Andy Tsang"] __version__ = "0.0.0" __maintainer__ = "Andy Tsang" __email__ = "atc1992andy@gmail.com" class PyQueue(): """ Queue with peek function """ # https://hg.python.org/cpython/file/2.7/Lib/Queue.py def __init__(self, maxsize=0): self.maxsi...
__author__ = 'Andy Tsang' __credits__ = ['Andy Tsang'] __version__ = '0.0.0' __maintainer__ = 'Andy Tsang' __email__ = 'atc1992andy@gmail.com' class Pyqueue: """ Queue with peek function """ def __init__(self, maxsize=0): self.maxsize = maxsize self.queue = list() def peek(self): ...
# Copyright 2017 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
load('@bazel_gazelle//:def.bzl', 'go_repository') def _maybe(repo_rule, name, **kwargs): if name not in native.existing_rules(): repo_rule(name=name, **kwargs) def popular_repos(): _maybe(go_repository, name='org_golang_x_crypto', importpath='golang.org/x/crypto', strip_prefix='crypto-de0752318171da71...
# # PySNMP MIB module E5-110-AS-ATM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/E5-110-AS-ATM-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:58:35 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, constraints_union, single_value_constraint, value_range_constraint) ...
# Copyright 2020 Xilinx Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
""" Module for registering quantization simulation transformation functions """ quantize_layer = {} def register_quant_sim_transform(xop_name): """ Return decorator for registering function to transform an operation of provided type for quantization simulation """ def __register_quant_sim_transform(...
# # PySNMP MIB module Wellfleet-IREDUND-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-IREDUND-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:40:42 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint) ...
test = { 'name': 'q2_1_2', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> # Make sure you can use any two movies; >>> correct_dis = 0.000541242; >>> dis = distance_two_features("clerks.", "the avengers", "water", "feel"); >>> np.isclose...
test = {'name': 'q2_1_2', 'points': 1, 'suites': [{'cases': [{'code': '\n >>> # Make sure you can use any two movies;\n >>> correct_dis = 0.000541242;\n >>> dis = distance_two_features("clerks.", "the avengers", "water", "feel");\n >>> np.isclose(np.round(dis, 9), correct_dis)\n ...
class AverageMeter(object): ''' computes and stores the average and current value Example: >>> loss = AverageMeter() >>> for step,batch in enumerate(train_data): >>> pred = self.model(batch) >>> raw_loss = self.metrics(pred,target) >>> loss.update(raw_loss...
class Averagemeter(object): """ computes and stores the average and current value Example: >>> loss = AverageMeter() >>> for step,batch in enumerate(train_data): >>> pred = self.model(batch) >>> raw_loss = self.metrics(pred,target) >>> loss.update(raw_loss...
# Solution 1 # O(n) time / O(1) space def findThreeLargetsNumbers(array): threeLargest = [None, None, None] for num in array: updateLargest(threeLargest, num) return threeLargest def updateLargest(threeLargest, num): if threeLargest[2] is None or num > threeLargest[2]: shiftAndUpdate(...
def find_three_largets_numbers(array): three_largest = [None, None, None] for num in array: update_largest(threeLargest, num) return threeLargest def update_largest(threeLargest, num): if threeLargest[2] is None or num > threeLargest[2]: shift_and_update(threeLargest, num, 2) elif t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Aug 20 15:25:24 2019 @author: jonasg """ f1 = 'CAM6-Oslo_altRHpiclimaer_od550aer_Column_9999_monthly.nc.csv' f2 = 'CAM6-Oslo_altRHpiclimaer_od550csaer_Column_9999_monthly.nc.csv' stats1, stats2 = [], [] with open(f1, 'r') as f: for line in f: ...
""" Created on Tue Aug 20 15:25:24 2019 @author: jonasg """ f1 = 'CAM6-Oslo_altRHpiclimaer_od550aer_Column_9999_monthly.nc.csv' f2 = 'CAM6-Oslo_altRHpiclimaer_od550csaer_Column_9999_monthly.nc.csv' (stats1, stats2) = ([], []) with open(f1, 'r') as f: for line in f: stats1.append(line.split(',')[1]) with op...
''' In a town, there are n people labelled from 1 to n. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies properties 1 and 2. You a...
""" In a town, there are n people labelled from 1 to n. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies properties 1 and 2. You a...
# A simple Python3 program # to calculate Euler's # Totient Function # Function to return # gcd of a and b def gcd(a, b): if (a == 0): return b return gcd(b % a, a) # A simple method to evaluate # Euler Totient Function def phi(n): result = 1 for i in range(2, n): if (gcd(i, n...
def gcd(a, b): if a == 0: return b return gcd(b % a, a) def phi(n): result = 1 for i in range(2, n): if gcd(i, n) == 1: result += 1 return result for n in range(1, 11): print('phi(', n, ') = ', phi(n), sep='')
'''Write a console program that enters an integer a and calculates the face of a square with a.''' a = int(input('a = ')) area = a * a print('Square =', area)
"""Write a console program that enters an integer a and calculates the face of a square with a.""" a = int(input('a = ')) area = a * a print('Square =', area)
def calc(op, n1, n2): if op == "+": return n1+n2 if op == "-": return n1-n2 if op == "*": return n1*n2 if n2 == 0: return "erro" return n1//n2 n1 = int(input()) op1 = input() n2 = int(input()) op2 = input() n3 = int(input()) try: if op1 != "*" and op1 != "/" and...
def calc(op, n1, n2): if op == '+': return n1 + n2 if op == '-': return n1 - n2 if op == '*': return n1 * n2 if n2 == 0: return 'erro' return n1 // n2 n1 = int(input()) op1 = input() n2 = int(input()) op2 = input() n3 = int(input()) try: if op1 != '*' and op1 != '...
#!/usr/bin/env python3 class Handheld(object): NOP = 0 JMP = 1 ACC = 2 OP_MAP = { 'nop': NOP, 'jmp': JMP, 'acc': ACC } def __init__(self): self._instructions = [] self._acc = 0 self._i = 0 def load_firmware(self, firmware): self._instructions = [] ...
class Handheld(object): nop = 0 jmp = 1 acc = 2 op_map = {'nop': NOP, 'jmp': JMP, 'acc': ACC} def __init__(self): self._instructions = [] self._acc = 0 self._i = 0 def load_firmware(self, firmware): self._instructions = [] for instruction in firmware: ...
def givemap(): with open('advent3.txt', 'r') as f: return [i.replace('\n', '') for i in f.readlines()] treemap = givemap() rows = len(treemap) slopes = [[1,1], [3,1], [5,1], [7,1], [1,2]] treemult = 1 for slope in slopes: hindex, vindex = [0,0] trees = 0 for row in range(rows):...
def givemap(): with open('advent3.txt', 'r') as f: return [i.replace('\n', '') for i in f.readlines()] treemap = givemap() rows = len(treemap) slopes = [[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]] treemult = 1 for slope in slopes: (hindex, vindex) = [0, 0] trees = 0 for row in range(rows): i...
_base_ = [ '../_base_/models/ocrnet_hr18.py', '../_base_/datasets/cityscapes.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py' ] # 1. dataset settings # Modify dataset related settings classes = ( 'background', 'balloon', 'text_format', 'text_effect', ) dataset_typ...
_base_ = ['../_base_/models/ocrnet_hr18.py', '../_base_/datasets/cityscapes.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_160k.py'] classes = ('background', 'balloon', 'text_format', 'text_effect') dataset_type = 'MangaDataset' img_scale = tuple([int(i * 1) for i in (425, 600)]) crop_size = (600, 4...
# A dictionary stores key-value pairs, # where each unique key is an index which holds the value associated with it. # Creating a Dictionary empty_dict = {} # Empty dictionary print(empty_dict) phone_book = {"Batman": 468426, "Cersei": 237734, "Ghostbusters": 44678} print(phone_book) # d...
empty_dict = {} print(empty_dict) phone_book = {'Batman': 468426, 'Cersei': 237734, 'Ghostbusters': 44678} print(phone_book) empty_dict = dict() print(empty_dict) phone_book = dict(Batman=468426, Cersei=237734, Ghostbusters=44678) print(phone_book) phone_book = dict([('Batman', 468426), ('Cersei', 237734), ('Ghostbuste...
# 6.00 Problem Set 2 # # Successive Approximation # def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: # >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 # >>> x = -13 # >>> print evaluate_poly(poly, x) # f(...
def evaluate_poly(poly, x): """ Computes the polynomial function for a given value x. Returns that value. Example: # >>> poly = (0.0, 0.0, 5.0, 9.3, 7.0) # f(x) = 7x^4 + 9.3x^3 + 5x^2 # >>> x = -13 # >>> print evaluate_poly(poly, x) # f(-13) = 7(-13)^4 + 9.3(-13)^3 + 5(-13)^2 180339.9 ...
address = "1600 Pennsylvania Ave NW Washington, DC" # .split() is a string method (a function that works only on strings) that splits a string into a list based on some delimiter. # In this example, we're splitting address into a list at every space. address = address.split(" ") # Address is now a list equal to: # ['...
address = '1600 Pennsylvania Ave NW Washington, DC' address = address.split(' ')
""" Holds constants required by tacorn. This mostly means paths into the Tacotron 2 and WaveRNN repositories. """ PRETRAINED_ACOUSTIC_MODELS = { "lj": {"tacotron2": "https://www.dropbox.com/s/kx7ephpl2oj72s3/taco_pretrained.zip?dl=1"} } PRETRAINED_WAVEGEN_MODELS = { "lj": {"wavernn_alt": "https://www.drop...
""" Holds constants required by tacorn. This mostly means paths into the Tacotron 2 and WaveRNN repositories. """ pretrained_acoustic_models = {'lj': {'tacotron2': 'https://www.dropbox.com/s/kx7ephpl2oj72s3/taco_pretrained.zip?dl=1'}} pretrained_wavegen_models = {'lj': {'wavernn_alt': 'https://www.dropbox.com/s/ao2...
def classes(): # think of a class as a blueprint and an object as the constructed counterpart of that blueprint. # the class can be used multiple times to build the same thing, but each iteration is a unique object. class FirstClass: # __init__ is a special constructor method that performs actio...
def classes(): class Firstclass: def __init__(self, author, title): self.author = author self.title = title def printresult(self): print(self.author, ': ', self.title) class Example: def __init__(self, capacity, weight): self.weight = ...
""" Lowest Common Multiple ---------------------- Simple implementation of the Lowest Common Multiple Algorithm. Pseudo Code: https://en.wikipedia.org/wiki/Least_common_multiple """ def lcm(a, b): """ Simple version of lcm, that does not have any dependencies. :param a: Integer :para...
""" Lowest Common Multiple ---------------------- Simple implementation of the Lowest Common Multiple Algorithm. Pseudo Code: https://en.wikipedia.org/wiki/Least_common_multiple """ def lcm(a, b): """ Simple version of lcm, that does not have any dependencies. :param a: Integer :param...
class _Break(BaseException): def __init__(self, tx, commit): super().__init__() self.tx = tx self.commit = commit class GinoTransaction: """ Represents an underlying database transaction and its connection, offering methods to manage this transaction. :class:`.GinoTransact...
class _Break(BaseException): def __init__(self, tx, commit): super().__init__() self.tx = tx self.commit = commit class Ginotransaction: """ Represents an underlying database transaction and its connection, offering methods to manage this transaction. :class:`.GinoTransact...
# Bug from 3.4 threading. Bug is handling while/else def acquire(self): with self._cond: while self: rc = False else: rc = True return rc
def acquire(self): with self._cond: while self: rc = False else: rc = True return rc
a = input("Enter a list elements separated by space ") list = a.split() even=0; odd=0; for x in list: if x % 2 == 0: even_count += 1 else: odd_count += 1 print("number of even numbers = ", even) print("number of odd numbers = ",odd)
a = input('Enter a list elements separated by space ') list = a.split() even = 0 odd = 0 for x in list: if x % 2 == 0: even_count += 1 else: odd_count += 1 print('number of even numbers = ', even) print('number of odd numbers = ', odd)
class Solution: def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int: obs = set(map(tuple, obstacles)) dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] maxDist = di = x = y = 0 for command in commands: if command == -2: di = (di - 1) % 4...
class Solution: def robot_sim(self, commands: List[int], obstacles: List[List[int]]) -> int: obs = set(map(tuple, obstacles)) dx = [0, 1, 0, -1] dy = [1, 0, -1, 0] max_dist = di = x = y = 0 for command in commands: if command == -2: di = (di - 1) ...
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for ui. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into ...
"""Presubmit script for ui. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for more details about the presubmit API built into depot_tools. """ include_cpp_files_only = ('.*\\.(cc|h|mm)$',) def check_unique_ptr(input_api, output_api, white_list=INCLUDE_CPP_FILES_ONLY, black_list=None): ...
S = list(map(str, input())) S_set = set(S) if len(S) == len(S_set): print("yes") else: print("no")
s = list(map(str, input())) s_set = set(S) if len(S) == len(S_set): print('yes') else: print('no')
class DnaAssemblyMethod(object): """General class for assembly methods. All assembly methods can store the following attributes: Parameters ---------- duration Duration required for the assembly (e.g. an estimated upper bound). The time unit is left at the choice of the user. cut...
class Dnaassemblymethod(object): """General class for assembly methods. All assembly methods can store the following attributes: Parameters ---------- duration Duration required for the assembly (e.g. an estimated upper bound). The time unit is left at the choice of the user. cut...
SECTION_POSITION_MAX_DIF = 100 """# Segment class for generic segments Members: - text - offset - cleaned_text - length (optional, default to 0) """ class Segment(): def __init__(self, text, offset, length = 0): self.text = text self.offset = offset self.length = length if length == 0: ...
section_position_max_dif = 100 '# Segment class for generic segments\n\nMembers:\n - text\n - offset\n - cleaned_text\n - length (optional, default to 0)\n' class Segment: def __init__(self, text, offset, length=0): self.text = text self.offset = offset self.length = length if ...
def frame(phrase='', ch='*') -> str: if not phrase: return f'{ch * 4}\n{ch + " " + ch}\n{ch + " " + ch}\n{ch * 4}' else: first_line = f"{ch}{ch * (len(phrase)+2)}{ch}" second_line = f"{ch}{' ' * (len(phrase)+2)}{ch}" third_line = f"{ch} {phrase} {ch}" return f'{first_l...
def frame(phrase='', ch='*') -> str: if not phrase: return f"{ch * 4}\n{ch + ' ' + ch}\n{ch + ' ' + ch}\n{ch * 4}" else: first_line = f'{ch}{ch * (len(phrase) + 2)}{ch}' second_line = f"{ch}{' ' * (len(phrase) + 2)}{ch}" third_line = f'{ch} {phrase} {ch}' return f'{firs...
class Lead: def __init__(self, activity, user): self.activity = activity self.user = user
class Lead: def __init__(self, activity, user): self.activity = activity self.user = user
class SimpleInterpreter(object): def __init__(self): self.stack = [] self.environment = {} # instruction_map = {1: self.LOAD_VALUE, # 2: self.ADD_TWO_VALUES, # 3: self.POP_FROM_STACK } def LOAD_VALUE(self, number): s...
class Simpleinterpreter(object): def __init__(self): self.stack = [] self.environment = {} def load_value(self, number): self.stack.append(number) def print_answer(self): answer = self.stack.pop() print(answer) def add_two_values(self): first_num = sel...
Result =[] scorelist = [] if __name__ == '__main__': for _ in range(int(input())): name = input() score = float(input()) Result+=[[name,score]] scorelist+=[score] b=sorted(list(set(scorelist)))[1] for a,c in sorted(Result): if c==b: print(a)
result = [] scorelist = [] if __name__ == '__main__': for _ in range(int(input())): name = input() score = float(input()) result += [[name, score]] scorelist += [score] b = sorted(list(set(scorelist)))[1] for (a, c) in sorted(Result): if c == b: print(a)
{ "includes": [ "../common.gypi" ], "targets": [ { "target_name": "libgdal_ogr_gpx_frmt", "type": "static_library", "sources": [ "../gdal/ogr/ogrsf_frmts/gpx/ogrgpxdatasource.cpp", "../gdal/ogr/ogrsf_frmts/gpx/ogrgpxdriver.cpp", "../gdal/ogr/ogrsf_frmts/gpx/ogrgpxlayer.cpp" ], "include...
{'includes': ['../common.gypi'], 'targets': [{'target_name': 'libgdal_ogr_gpx_frmt', 'type': 'static_library', 'sources': ['../gdal/ogr/ogrsf_frmts/gpx/ogrgpxdatasource.cpp', '../gdal/ogr/ogrsf_frmts/gpx/ogrgpxdriver.cpp', '../gdal/ogr/ogrsf_frmts/gpx/ogrgpxlayer.cpp'], 'include_dirs': ['../gdal/ogr/ogrsf_frmts/gpx']}]...
def find_measure(name = None, tag = None, id = None, search = None): return 'do some magic!' def get_dimension(id): return 'do some magic!' def get_indicator(id): return 'do some magic!' def get_measure(id): return 'do some magic!' def get_measure_root(id): return 'do some magic!' def get_root...
def find_measure(name=None, tag=None, id=None, search=None): return 'do some magic!' def get_dimension(id): return 'do some magic!' def get_indicator(id): return 'do some magic!' def get_measure(id): return 'do some magic!' def get_measure_root(id): return 'do some magic!' def get_root(): r...
#Given a string s, find the longest palindromic substring in s. You may assume # that the maximum length of s is 1000. def longestPalindrome(s: str) -> str: left, right = 0, len(s) - 1 def is_palindrome(sub): left, right = 0, len(sub) - 1 while left <= right: if sub[left] != sub[rig...
def longest_palindrome(s: str) -> str: (left, right) = (0, len(s) - 1) def is_palindrome(sub): (left, right) = (0, len(sub) - 1) while left <= right: if sub[left] != sub[right]: return False else: left += 1 right -= 1 ...
# 937. Reorder Data in Log Files class Solution: # Sorting by Keys def reorderLogFiles(self, logs: list[str]) -> list[str]: def get_key(log: list[str]) -> tuple: id, content = log.split(" ", maxsplit=1) return (0, content, id) if content[0].isalpha() else (1, None, None) ...
class Solution: def reorder_log_files(self, logs: list[str]) -> list[str]: def get_key(log: list[str]) -> tuple: (id, content) = log.split(' ', maxsplit=1) return (0, content, id) if content[0].isalpha() else (1, None, None) return sorted(logs, key=get_key)
class Cliente: nome = str() NIF = str() def __init__(self, nome1, NIF1): self.nome = nome1 self.NIF = NIF1 def consultar(self): print(self.nome) print(self.NIF)
class Cliente: nome = str() nif = str() def __init__(self, nome1, NIF1): self.nome = nome1 self.NIF = NIF1 def consultar(self): print(self.nome) print(self.NIF)
my_dict = {1:'Apple', 2:'Oracle',3:'Advanced Programming Practice',4:'Software Project Management', 5:'Fundamentals of mathematics'} for x in range(1,6): #print(my_dict[i]) test_str = my_dict[x] res = {i : test_str.count(i) for i in set(test_str)} print(res)
my_dict = {1: 'Apple', 2: 'Oracle', 3: 'Advanced Programming Practice', 4: 'Software Project Management', 5: 'Fundamentals of mathematics'} for x in range(1, 6): test_str = my_dict[x] res = {i: test_str.count(i) for i in set(test_str)} print(res)
{ "includes": [ "common.gypi", "local.gypi" ], "targets": [ { "target_name": "uv_tls", "product_name": "uv_tls", "type": "static_library", "dependencies": [ "deps/ringbuffer/ringbuffer.gyp:ringbuffer" ], ...
{'includes': ['common.gypi', 'local.gypi'], 'targets': [{'target_name': 'uv_tls', 'product_name': 'uv_tls', 'type': 'static_library', 'dependencies': ['deps/ringbuffer/ringbuffer.gyp:ringbuffer'], 'sources': ['./src/uv_tls.c'], 'include_dirs': ['include', 'deps/ringbuffer'], 'direct_dependent_settings': {'include_dirs'...
"""Base Attack Callback module.""" class BaseCallback: """Base Attack Callback. A callback records and/or prints specific values of each attack iteration of the `generate` method. This base class cannot be directly utilized. It must be either a function or a class implementing the `__call__`...
"""Base Attack Callback module.""" class Basecallback: """Base Attack Callback. A callback records and/or prints specific values of each attack iteration of the `generate` method. This base class cannot be directly utilized. It must be either a function or a class implementing the `__call__` ...
# https://www.hackerrank.com/challenges/mini-max-sum/problem def miniMaxSum(arr): sort = sorted(arr) large = sort.pop(len(arr)-1) small = sort.pop(0) max_sum = large min_sum = small for i in sort: max_sum += i min_sum += i print(min_sum, max_sum)
def mini_max_sum(arr): sort = sorted(arr) large = sort.pop(len(arr) - 1) small = sort.pop(0) max_sum = large min_sum = small for i in sort: max_sum += i min_sum += i print(min_sum, max_sum)
def command_ask_path(): return 'COMMAND_ASK_PATH' def command_repeat(): return 'COMMAND_REPEAT' def command_quit(): return 'COMMAND_QUIT' def command_feedback(msg): return 'COMMAND_FEEDBACK;' + msg def command_consult(): return 'COMMAND_CONSULT' def command_wait(): return 'COMMAND_WAIT...
def command_ask_path(): return 'COMMAND_ASK_PATH' def command_repeat(): return 'COMMAND_REPEAT' def command_quit(): return 'COMMAND_QUIT' def command_feedback(msg): return 'COMMAND_FEEDBACK;' + msg def command_consult(): return 'COMMAND_CONSULT' def command_wait(): return 'COMMAND_WAIT'
class Solution(object): def isUgly(self, n): """ :type n: int :rtype: bool """ if n ==0: return 0 for p in [2,3,5]: while n%p==0: n=n//p if n ==1: return True return False ...
class Solution(object): def is_ugly(self, n): """ :type n: int :rtype: bool """ if n == 0: return 0 for p in [2, 3, 5]: while n % p == 0: n = n // p if n == 1: return True return False
# coding=utf-8 """ Metaclass for event identifiers """ __author__ = "Sean" class EventMeta(type): """ Metaclass for events. Automatically fills in `identifier` and `identifiers` on class creation. If class does not have an `identifier` or it is set to None, one is generated from its module and ...
""" Metaclass for event identifiers """ __author__ = 'Sean' class Eventmeta(type): """ Metaclass for events. Automatically fills in `identifier` and `identifiers` on class creation. If class does not have an `identifier` or it is set to None, one is generated from its module and class names. This ...
""" Assignments Assigments allow you to set or clear variables, indexed variables, structure elements, functions, and general transformations. You can also get assignment and documentation information about symbols. """
""" Assignments Assigments allow you to set or clear variables, indexed variables, structure elements, functions, and general transformations. You can also get assignment and documentation information about symbols. """
"""The Translator class converts a list to HTML.""" class Translator(object): """The Translator class converts a list to HTML. Parameters ---------- input_list : list The list to translate. Returns ------- self.html_element : str The HTML translation. """ def __...
"""The Translator class converts a list to HTML.""" class Translator(object): """The Translator class converts a list to HTML. Parameters ---------- input_list : list The list to translate. Returns ------- self.html_element : str The HTML translation. """ def _...
# package information. INFO = dict( name = "import_gist", description = "script to import gist script", author = "Katsuya Ogata", author_email = "cosacog@gmail.com", license = "MIT License", url = "https://github.com/cosacog/import_gist", classifiers = [ "Programming Language :...
info = dict(name='import_gist', description='script to import gist script', author='Katsuya Ogata', author_email='cosacog@gmail.com', license='MIT License', url='https://github.com/cosacog/import_gist', classifiers=['Programming Language :: Python :: 3.5', 'License :: OSI Approved :: MIT License'])
# -*- coding: utf-8 -*- i=[1,3,5,7,9] j=[6,5,4] for I in i: for J in j: print("I=%i J=%i"%(I,I+J))
i = [1, 3, 5, 7, 9] j = [6, 5, 4] for i in i: for j in j: print('I=%i J=%i' % (I, I + J))
# Contains Duplicate II # find out whether there are two distinct indices i and j in the array # such that nums[i] = nums[j] and the absolute difference between i and j is at most k. class Solution(object): def containsNearbyDuplicate(self, nums, k): window = set() for i, num in enumerate(nums): ...
class Solution(object): def contains_nearby_duplicate(self, nums, k): window = set() for (i, num) in enumerate(nums): if i > k: window.remove(nums[i - k - 1]) if num in window: return True window.add(num) return False clas...
# -*- encoding: utf-8 -*- # Copyright: (c) 2019 H2O.ai # License: Apache License Version 2.0 (see LICENSE for details) """ :mod:`base` -- base/abstract H2O classes used internally. """ class Keyed(object): @property def key(self): """ :return: the unique key representing the object on the b...
""" :mod:`base` -- base/abstract H2O classes used internally. """ class Keyed(object): @property def key(self): """ :return: the unique key representing the object on the backend """ raise not_implemented_error('Keyed classes should have a `key` property.') def detach(self...
""" LeetCode 79: Word Search https://leetcode.com/problems/word-search/ Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same...
""" LeetCode 79: Word Search https://leetcode.com/problems/word-search/ Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same...
a = int(input()) b = int(input()) if a != 1 and b != 1: print(1) if a != 2 and b != 2: print(2) if a != 3 and b != 3: print(3)
a = int(input()) b = int(input()) if a != 1 and b != 1: print(1) if a != 2 and b != 2: print(2) if a != 3 and b != 3: print(3)
load("@rules_sphinx//sphinx:indirect_repositories.bzl", "rules_sphinx_indirect_deps") def stuff_sack_level_3_deps(): rules_sphinx_indirect_deps()
load('@rules_sphinx//sphinx:indirect_repositories.bzl', 'rules_sphinx_indirect_deps') def stuff_sack_level_3_deps(): rules_sphinx_indirect_deps()
# -*- coding: utf-8 -*- # Copyright 2021 Cohesity Inc. class SchedulingPolicyProtoContinuousSchedule(object): """Implementation of the 'SchedulingPolicyProto_ContinuousSchedule' model. TODO: type model description here. Attributes: backup_interval_mins (long|int): If this field is set, backups ...
class Schedulingpolicyprotocontinuousschedule(object): """Implementation of the 'SchedulingPolicyProto_ContinuousSchedule' model. TODO: type model description here. Attributes: backup_interval_mins (long|int): If this field is set, backups will be performed periodically every 'interval...
class IInfo: def __init__(self): # keys self.__id = None self.__parent_id = None self.__url = None self.__parent_url = None self.__create_datetime = None self.__edit_datetime = None self.__title = None self.__description = None self...
class Iinfo: def __init__(self): self.__id = None self.__parent_id = None self.__url = None self.__parent_url = None self.__create_datetime = None self.__edit_datetime = None self.__title = None self.__description = None self.__tags = set() ...
"""Internal API endpoint constant library. _______ __ _______ __ __ __ | _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----. |. 1___| _| _ | | | | _ | 1___| _| _| | <| -__| |. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____| |: 1 | ...
"""Internal API endpoint constant library. _______ __ _______ __ __ __ | _ .----.-----.--.--.--.--| | _ | |_.----|__| |--.-----. |. 1___| _| _ | | | | _ | 1___| _| _| | <| -__| |. |___|__| |_____|________|_____|____ |____|__| |__|__|__|_____| |: 1 | ...
class BaseMeasure: def min_feature_size(self, _query_size, _alpha): raise 'Not Implemented' def max_feature_size(self, _query_size, _alpha): raise 'Not Implemented' def minimum_common_feature_count(self, _query_size, _y_size, _alpha): raise 'Not Implemented' def similarity(sel...
class Basemeasure: def min_feature_size(self, _query_size, _alpha): raise 'Not Implemented' def max_feature_size(self, _query_size, _alpha): raise 'Not Implemented' def minimum_common_feature_count(self, _query_size, _y_size, _alpha): raise 'Not Implemented' def similarity(se...
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def test_find_sum_of_all_multiples(): assert find_sum_of_all_multiples(10) == 23 assert find_sum_of_all_multiples(2...
""" If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ def test_find_sum_of_all_multiples(): assert find_sum_of_all_multiples(10) == 23 assert find_sum_of_all_multiples(20...
# -*- mode: python -*- # -*- coding: utf-8 -*- ''' filter_musicalbum.py - Versa pipeline rules specification to be used with versa transform command The following example, run from the Versadistribution root directory, will generate a filtered down model file in /tmp/musicalbums-trimmed.vlit versa transform demo/pipe...
""" filter_musicalbum.py - Versa pipeline rules specification to be used with versa transform command The following example, run from the Versadistribution root directory, will generate a filtered down model file in /tmp/musicalbums-trimmed.vlit versa transform demo/pipeline/filter_musicalbum.py demo/model/musicalbum...
class Node(): """ Class to create a node with tree-like attributes. """ def __init__(self, data): """ Initialize a node with data, left, and right attributes. """ self.data = data self.left = None self.right = None def __repr__(self): return '...
class Node: """ Class to create a node with tree-like attributes. """ def __init__(self, data): """ Initialize a node with data, left, and right attributes. """ self.data = data self.left = None self.right = None def __repr__(self): return '_...
{'type':'CustomDialog', 'name':'Template', 'title':'Dialog Template', 'size':(300, 100), 'style':['resizeable'], 'components': [ {'type':'Button', 'name':'btnOK', 'position':(10, 35), 'label':'OK', 'id':5100, 'default':1, }, {'type':'Button', 'name':'btnCancel', ...
{'type': 'CustomDialog', 'name': 'Template', 'title': 'Dialog Template', 'size': (300, 100), 'style': ['resizeable'], 'components': [{'type': 'Button', 'name': 'btnOK', 'position': (10, 35), 'label': 'OK', 'id': 5100, 'default': 1}, {'type': 'Button', 'name': 'btnCancel', 'position': (100, 35), 'label': 'Cancel', 'id':...
print("Input your height :") h_ft=int(input("Feet :")) h_inch=int(input("Inches :")) h_inch+=h_ft*12 h_cm=round(h_inch*2.54,1) print("Your height is : %d cm"%h_cm)
print('Input your height :') h_ft = int(input('Feet :')) h_inch = int(input('Inches :')) h_inch += h_ft * 12 h_cm = round(h_inch * 2.54, 1) print('Your height is : %d cm' % h_cm)
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2021, Cisco Systems # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) DOCUMENTATION = r""" --- module: pnp_settings short_description: Manage PnpSettings objects of DeviceOnboardingPnp description: - Returns global P...
documentation = "\n---\nmodule: pnp_settings\nshort_description: Manage PnpSettings objects of DeviceOnboardingPnp\ndescription:\n- Returns global PnP settings of the user.\n- Updates the user's list of global PnP settings.\nversion_added: '1.0.0'\nauthor: Rafael Campos (@racampos)\noptions:\n _id:\n description:\n...
class Player: def __init__(self, master): self.master = master self.choice = "UP" self.master.bind("<Left>", lambda x: self.set_choice("LEFT")) self.master.bind("<a>", lambda x: self.set_choice("LEFT")) self.master.bind("<Right>", lambda x: self.set_choice("RIGHT")) ...
class Player: def __init__(self, master): self.master = master self.choice = 'UP' self.master.bind('<Left>', lambda x: self.set_choice('LEFT')) self.master.bind('<a>', lambda x: self.set_choice('LEFT')) self.master.bind('<Right>', lambda x: self.set_choice('RIGHT')) ...
VALID_QUERY_PARAMS = "query" SEARCH_TYPE = "type" SEARCH_DATABASE = "d" SEARCH_FORMULA = "f" SEARCH_TEXT = "t" SEARCH_LIMIT = 50 AUTHENTICATION_FAIL = "You must be an admin to perform database manipulation." FORMULA_CREATION_SUCCESS = "Formula creation is successful!" FORMULA_CREATION_FAIL = "Formula creation failed...
valid_query_params = 'query' search_type = 'type' search_database = 'd' search_formula = 'f' search_text = 't' search_limit = 50 authentication_fail = 'You must be an admin to perform database manipulation.' formula_creation_success = 'Formula creation is successful!' formula_creation_fail = 'Formula creation failed' f...
"""Trim suffix. Create string _t consisting of string _s with its suffix _w removed (if _s ends with _w). Source: programming-idioms.org """ # Implementation author: bukzor # Created on 2018-04-08T07:26:47.248912Z # Last modified on 2018-04-08T07:26:47.248912Z # Version 1 t = s.rsplit(w, 1)[0]
"""Trim suffix. Create string _t consisting of string _s with its suffix _w removed (if _s ends with _w). Source: programming-idioms.org """ t = s.rsplit(w, 1)[0]
''' What are some potential efficiency disadvantages of having very shallow inheritance trees, that is, a large set of classes, A, B, C, and so on, such that all of these classes extend a single class, Z? ''' ''' does not take advantage of the benefits on an inheritance hierarchy. So a bunch of classes extending one cl...
""" What are some potential efficiency disadvantages of having very shallow inheritance trees, that is, a large set of classes, A, B, C, and so on, such that all of these classes extend a single class, Z? """ '\ndoes not take advantage of the benefits on an inheritance hierarchy. So a bunch of classes extending one cla...
description = 'nGI XinGI setup: Gratings' group = 'lowlevel' pvprefix = 'SQ:ICON:ngiX:' display_order = 35 excludes = ['ngi_backpack'] devices = dict( g1_rz = device('nicos_ess.devices.epics.motor.HomingProtectedEpicsMotor', description = 'nGI Interferometer Grating Rotation G1 (XinGI)', motorp...
description = 'nGI XinGI setup: Gratings' group = 'lowlevel' pvprefix = 'SQ:ICON:ngiX:' display_order = 35 excludes = ['ngi_backpack'] devices = dict(g1_rz=device('nicos_ess.devices.epics.motor.HomingProtectedEpicsMotor', description='nGI Interferometer Grating Rotation G1 (XinGI)', motorpv=pvprefix + 'g1rz', errormsgp...
class ContentAnalysis: def __init__(self): self.line_count = 0 # count the total number of lines in the file self.char_count = 0 # count the number of characters in the file self.total_word_count = 0 # count the total word count in the file self.unique_word_count = 0 # count the n...
class Contentanalysis: def __init__(self): self.line_count = 0 self.char_count = 0 self.total_word_count = 0 self.unique_word_count = 0 self.white_space_count = 0 self.blank_line_count = 0 self.content = [] class Wordcount: def analyze_file(self, file_p...
class Random: def __init__(self, *param): if len(param) == 1: self.set_seed(param[0]) elif len(param) == 4: self.set_state(*param) else: raise TypeError("Random.__init__ takes either 1 or 4 arguments") def set_seed(self, seed): multiplier = 0x6C078965 temp = seed self.state = [] ...
class Random: def __init__(self, *param): if len(param) == 1: self.set_seed(param[0]) elif len(param) == 4: self.set_state(*param) else: raise type_error('Random.__init__ takes either 1 or 4 arguments') def set_seed(self, seed): multiplier = ...
#return the index of the smallest value from [start:] def posMin(lst,start): n = len(lst) firstval =lst[start] pos = start for i in range(start,n): if lst[i]<firstval: first = lst[i] pos = i return pos def selectionSort(lst): n = len(lst) for sta...
def pos_min(lst, start): n = len(lst) firstval = lst[start] pos = start for i in range(start, n): if lst[i] < firstval: first = lst[i] pos = i return pos def selection_sort(lst): n = len(lst) for start in range(n - 1): p = pos_min(lst, start) ...