content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Command(object): def __init__(self, command, description, callback): """ Construct command :param command: The command :param description: The description :param callback: The callback """ self.command = command self.description = descr...
class Command(object): def __init__(self, command, description, callback): """ Construct command :param command: The command :param description: The description :param callback: The callback """ self.command = command self.description = descrip...
# List dog_names = ["tom", "sean", "sally", "mark"] print(type(dog_names)) print(dog_names) # Adding Item On Last Position dog_names.append("sam") print(dog_names) # Adding Item On First Position dog_names.insert(0, "bruz") print(dog_names) # Delete Items del(dog_names[0]) print(dog_names) # Length Of List pr...
dog_names = ['tom', 'sean', 'sally', 'mark'] print(type(dog_names)) print(dog_names) dog_names.append('sam') print(dog_names) dog_names.insert(0, 'bruz') print(dog_names) del dog_names[0] print(dog_names) print('Length Of List: ', len(dog_names))
class BTNode: def __init__(self, data = -1, left = None, right = None): self.data = data self.left = left self.right = right class BTree: def __init__(self): self.root = None self.found = False def is_empty(self): return self.root is None def build(self, ...
class Btnode: def __init__(self, data=-1, left=None, right=None): self.data = data self.left = left self.right = right class Btree: def __init__(self): self.root = None self.found = False def is_empty(self): return self.root is None def build(self, va...
# -*- coding: utf-8 -*- """ Created on Wed Mar 13 11:30:05 2019 @author: Jongmin Sung import functions and variables into our notebooks and scripts: from projectname import something """
""" Created on Wed Mar 13 11:30:05 2019 @author: Jongmin Sung import functions and variables into our notebooks and scripts: from projectname import something """
"""Module with bad __all__ To test https://github.com/ipython/ipython/issues/9678 """ def evil(): pass def puppies(): pass __all__ = [evil, # Bad 'puppies', # Good ]
"""Module with bad __all__ To test https://github.com/ipython/ipython/issues/9678 """ def evil(): pass def puppies(): pass __all__ = [evil, 'puppies']
# -- Project information ----------------------------------------------------- project = "Test" copyright = "Test" author = "Test" # -- General configuration --------------------------------------------------- master_doc = "index" # -- Options for HTML output ------------------------------------------------- html_...
project = 'Test' copyright = 'Test' author = 'Test' master_doc = 'index' html_theme = 'pydata_sphinx_theme'
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def countUnivalSubtrees(self, root): """ :type root: TreeNode :rtype: int """ sel...
class Solution(object): def count_unival_subtrees(self, root): """ :type root: TreeNode :rtype: int """ self.count = 0 def helper(node, val): if not node: return True left = helper(node.left, node.val) right = help...
# Reads the UA list from the file "ua_list.txt" # Refer this site for list of UAs: https://developers.whatismybrowser.com/useragents/explore/ ua_file = open("ua_list.txt", "r") lines = ua_file.readlines() ua_list = [] for line in lines: line_cleaned = line.replace("\n","").lower() ua_list.append(line_cleaned)...
ua_file = open('ua_list.txt', 'r') lines = ua_file.readlines() ua_list = [] for line in lines: line_cleaned = line.replace('\n', '').lower() ua_list.append(line_cleaned) ua_list.sort() ua_list = list(dict.fromkeys(ua_list)) ua_list_count = len(ua_list) print(ua_list) print('Identified ', ua_list_count, ' UA...
# greatest of three def greatest(a,b,c): return max(a,b,c) print(greatest(2,4,3))
def greatest(a, b, c): return max(a, b, c) print(greatest(2, 4, 3))
def LCSBackTrack(v, w): v = '-' + v w = '-' + w S = [[0 for i in range(len(w))] for j in range(len(v))] Backtrack = [[0 for i in range(len(w))] for j in range(len(v))] for i in range(1, len(v)): for j in range(1, len(w)): tmp = S[i - 1][j - 1] + (1 if v[i] == w[j] else 0) ...
def lcs_back_track(v, w): v = '-' + v w = '-' + w s = [[0 for i in range(len(w))] for j in range(len(v))] backtrack = [[0 for i in range(len(w))] for j in range(len(v))] for i in range(1, len(v)): for j in range(1, len(w)): tmp = S[i - 1][j - 1] + (1 if v[i] == w[j] else 0) ...
{ "targets": [ { "target_name": "boost-parameter", "type": "none", "include_dirs": [ "1.57.0/parameter-boost-1.57.0/include" ], "all_dependent_settings": { "include_dirs": [ "1.57.0/parameter-boos...
{'targets': [{'target_name': 'boost-parameter', 'type': 'none', 'include_dirs': ['1.57.0/parameter-boost-1.57.0/include'], 'all_dependent_settings': {'include_dirs': ['1.57.0/parameter-boost-1.57.0/include']}, 'dependencies': ['../boost-config/boost-config.gyp:*', '../boost-detail/boost-detail.gyp:*', '../boost-optiona...
# -*- coding: utf-8 -*- { 'name': "WooCommerce Connector", 'summary': """This module enables users to connect woocommerce api to odoo modules of sales, partners and inventory""", 'description': """ Following are the steps to use this module effectively: 1) Put in the KEY and SECRET in the co...
{'name': 'WooCommerce Connector', 'summary': 'This module enables users to connect woocommerce api to odoo modules of sales, partners and inventory', 'description': '\n Following are the steps to use this module effectively:\n 1) Put in the KEY and SECRET in the connection menu.\n 2) Click Sync But...
class AbstractBatchifier(object): def filter(self, games): return games def apply(self, games): return games
class Abstractbatchifier(object): def filter(self, games): return games def apply(self, games): return games
"""https://leetcode.com/problems/permutations-ii/ 47. Permutations II Medium Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. Examples: >>> Solution().permuteUnique([]) [[]] Constraints: 1 <= nums.length <= 8 -10 <= nums[i] <= 10 Re...
"""https://leetcode.com/problems/permutations-ii/ 47. Permutations II Medium Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order. Examples: >>> Solution().permuteUnique([]) [[]] Constraints: 1 <= nums.length <= 8 -10 <= nums[i] <= 10 Re...
#coding:utf-8 ''' filename:clsmethod.py learn class method ''' class Message: msg = 'Python is a smart language.' def get_msg(self): print('self :',self) print('attrs of class(Message.msg):',Message.msg) print('use type(self).msg:',type(self).msg) cls = type(self) ...
""" filename:clsmethod.py learn class method """ class Message: msg = 'Python is a smart language.' def get_msg(self): print('self :', self) print('attrs of class(Message.msg):', Message.msg) print('use type(self).msg:', type(self).msg) cls = type(self) print('[...
class Solution: def findNumbers(self, nums: List[int]) -> int: if len(nums) == 0: return 0 return len(list(filter(lambda x:len(str(x))%2==0,nums)))
class Solution: def find_numbers(self, nums: List[int]) -> int: if len(nums) == 0: return 0 return len(list(filter(lambda x: len(str(x)) % 2 == 0, nums)))
""" This module contains methods that model the properties of galaxy cluster populations. """
""" This module contains methods that model the properties of galaxy cluster populations. """
# 231 - Power Of Two (Easy) # https://leetcode.com/problems/power-of-two/submissions/ class Solution: def isPowerOfTwo(self, n: int) -> bool: return n and (n & (n-1)) == 0
class Solution: def is_power_of_two(self, n: int) -> bool: return n and n & n - 1 == 0
random_test_iterations = 64 def repeat(fn): """Decorator for running the function's body multiple times.""" def repeated(): i = 0 while i < random_test_iterations: fn() i += 1 # nosetest runs functions that start with 'test_' repeated.__name__ = fn.__name__ ...
random_test_iterations = 64 def repeat(fn): """Decorator for running the function's body multiple times.""" def repeated(): i = 0 while i < random_test_iterations: fn() i += 1 repeated.__name__ = fn.__name__ return repeated
# Some sites give IR codes in this weird pronto format # Cut off the preamble and footer and find which value represents a 1 in the spacing code = "0000 0016 0000 0016 0000 0016 0000 003F 0000 003F 0000 003F 0000 0016 0000 003F 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0...
code = '0000 0016 0000 0016 0000 0016 0000 003F 0000 003F 0000 003F 0000 0016 0000 003F 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 0016 0000 003F 0000 0016 0000 003F 0000 003F 0000 0016 0000 0016 0000 003F 0000 003F 0000 0016 0000 003F 0000 0016 0000 0016 0000 003F 0000 003F 00...
# ---------------------------------------------------------------------------- # This software is in the public domain, furnished "as is", without technical # support, and with no warranty, express or implied, as to its usefulness for # any purpose. # # iscSendSampleDef # # Author: mathewson # -------------------------...
hr = 3600 sample_def = {} SampleDef['default'] = ([0 * HR], [(-24 * HR, 1 * HR)])
#Write a program (using functions!) that asks the user for a long string containing multiple words. # Print back to the user the same string, except with the words in backwards order. For example, say I type the string: # My name is Michele #Then I would see the string: # Michele is name My #shown back to me. def ...
def reverse(strng: str): list = strng.split(' ') list.reverse() return list print(reverse('My name is Michele'))
# coding: utf-8 def test_index(admin_client): """ Basic test to see if it even works. """ url = "/nothing-to-see-here/" HTTP_OK_200 = 200 respnse = admin_client.get(url) assert respnse.status_code == HTTP_OK_200
def test_index(admin_client): """ Basic test to see if it even works. """ url = '/nothing-to-see-here/' http_ok_200 = 200 respnse = admin_client.get(url) assert respnse.status_code == HTTP_OK_200
def strategy(history, memory): if memory is None or 1 == memory: return 0, 0 else: return 1, 1
def strategy(history, memory): if memory is None or 1 == memory: return (0, 0) else: return (1, 1)
with open("promote.in") as input_file: input_lst = [[*map(int, line.split())] for line in input_file] promotions = [ promotion[1] - promotion[0] for promotion in input_lst ] output = [] for promotion in promotions[::-1]: output.append(sum([])) with open("promote.out", "w") as output_file: for promotio...
with open('promote.in') as input_file: input_lst = [[*map(int, line.split())] for line in input_file] promotions = [promotion[1] - promotion[0] for promotion in input_lst] output = [] for promotion in promotions[::-1]: output.append(sum([])) with open('promote.out', 'w') as output_file: for promotion in pro...
sample_text = ''' The textwrap module can be used to format text for output in situations where pretty-printing is desired. It offers programmatic functionality similar to the paragraph wrapping or filling features found in many text editors. '''
sample_text = '\n The textwrap module can be used to format text for output in\n situations where pretty-printing is desired. It offers\n programmatic functionality similar to the paragraph wrapping\n or filling features found in many text editors.\n '
# Write your solutions for 1.5 here! class Superheros: def __init__(self, name, superpower, strength): self.name = name self.superpower = superpower self.strength = strength def hero (self): print(self.name) print(self.strength) def save_civilian (self, work): if work > self....
class Superheros: def __init__(self, name, superpower, strength): self.name = name self.superpower = superpower self.strength = strength def hero(self): print(self.name) print(self.strength) def save_civilian(self, work): if work > self.strength: print('Superhero is no...
# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'prefix_header', 'type': 'static_library', 'sources': [ 'file.c', ], 'xcode_settings': { 'GCC_...
{'targets': [{'target_name': 'prefix_header', 'type': 'static_library', 'sources': ['file.c'], 'xcode_settings': {'GCC_PREFIX_HEADER': 'header.h'}}, {'target_name': 'precompiled_prefix_header', 'type': 'shared_library', 'mac_bundle': 1, 'sources': ['file.c'], 'xcode_settings': {'GCC_PREFIX_HEADER': 'header.h', 'GCC_PRE...
#FACTORIAL OF A NUMBER a = input("Enter number1") a=int(a) factorial=1 if a==1: print('Factorial is 1') elif a<1: print('Please enter a valid number') else: for i in range(1, a+1): factorial *= i print(f'The factorial is {factorial}')
a = input('Enter number1') a = int(a) factorial = 1 if a == 1: print('Factorial is 1') elif a < 1: print('Please enter a valid number') else: for i in range(1, a + 1): factorial *= i print(f'The factorial is {factorial}')
# Copyright 2020 Q-CTRL Pty Ltd & Q-CTRL 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...
""" Defines constants for driven controls module. """ upper_bound_rabi_rate = 10000000000.0 upper_bound_detuning_rate = UPPER_BOUND_RABI_RATE upper_bound_duration = 1000000.0 lower_bound_duration = 1e-12 upper_bound_segments = 10000 primitive = 'primitive' bb1 = 'BB1' sk1 = 'SK1' wamf1 = 'WAMF1' corpse = 'CORPSE' corps...
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right node = Node("root", Node("left", Node("left.left")), Node("right")) s = "" def serialize(node, s=""): if not node: s += "# " return s s += str(node.val) ...
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right node = node('root', node('left', node('left.left')), node('right')) s = '' def serialize(node, s=''): if not node: s += '# ' return s s += str(node.val) + ...
# -*- coding: utf-8 -*- class Job: def __init__(self, job_id, name, status, start_date, end_date, source_records, processed_records, price): self.id = job_id self.name = name self.status = status self.start_date = start_date self.end_date = end_date ...
class Job: def __init__(self, job_id, name, status, start_date, end_date, source_records, processed_records, price): self.id = job_id self.name = name self.status = status self.start_date = start_date self.end_date = end_date self.source_records = source_records ...
def median(iterable): items = sorted(iterable) if len(items) == 0: raise ValueError("median() arg is an empty series") median_index = (len(items) - 1) // 2 if len(items) % 2 != 0: return items[median_index] return (items[median_index] + items[median_index + 1]) / 2 print(median([5,...
def median(iterable): items = sorted(iterable) if len(items) == 0: raise value_error('median() arg is an empty series') median_index = (len(items) - 1) // 2 if len(items) % 2 != 0: return items[median_index] return (items[median_index] + items[median_index + 1]) / 2 print(median([5, ...
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo # Copyright (C) 2011-2019 German Aerospace Center (DLR) and others. # This program and the accompanying materials # are made available under the terms of the Eclipse Public License v2.0 # which accompanies this distribution, and is available at ...
class Node: """ Nodes from a sumo network """ def __init__(self, id, type, coord, incLanes, intLanes=None): self._id = id self._type = type self._coord = coord self._incoming = [] self._outgoing = [] self._foes = {} self._prohibits = {} self._incL...
def get(): return int(input()) def get_num(): return get() def get_line(): return get_num() print(get_line())
def get(): return int(input()) def get_num(): return get() def get_line(): return get_num() print(get_line())
# ### Problem 1 # ``` # # Start with this List # list_of_many_numbers = [12, 24, 1, 34, 10, 2, 7] # ``` # Example Input/Output if the user enters the number 9: # ``` # The User entered 9 # 1 2 7 are smaller than 9 # 12 24 34 10 are larger than 9 # ``` # Ask the user to enter a number. userInput = int(input("Enter...
user_input = int(input('Enter a number ')) list_of_many_numbers = [12, 24, 1, 34, 10, 2, 7] for x in list_of_many_numbers: if userInput > x: print('the value that is smaller than the user input ', x) if userInput < x: print('the value that is greater than the user input ', x)
class Scheduler(object): def __init__(self, env, cpu_list=[], task_list=[]): self.env = env self.cpu_list = cpu_list self.task_list = [] self._lock = False self.overhead = 0 def run(self): pass def on_activate(self, job): pass def on_termin...
class Scheduler(object): def __init__(self, env, cpu_list=[], task_list=[]): self.env = env self.cpu_list = cpu_list self.task_list = [] self._lock = False self.overhead = 0 def run(self): pass def on_activate(self, job): pass def on_terminated...
""" This is a sample program to demonstrate string concatenation """ if __name__ == "__main__": alice_name = "Alice" bob_name = "Bob" print(alice_name + bob_name)
""" This is a sample program to demonstrate string concatenation """ if __name__ == '__main__': alice_name = 'Alice' bob_name = 'Bob' print(alice_name + bob_name)
# test 0 # correct answer # [0] num_topics, num_themes = 1, 1 lst = [0] with open('input.txt', 'w') as f: f.write("{} {}\n".format(num_topics, num_themes)) for l in lst: f.write(str(l) + '\n')
(num_topics, num_themes) = (1, 1) lst = [0] with open('input.txt', 'w') as f: f.write('{} {}\n'.format(num_topics, num_themes)) for l in lst: f.write(str(l) + '\n')
class Stack(): def __init__(self): self.items = [] def push(self, item): return self.items.append(item) def pop(self): return self.items.pop() def IsEmpty(self): return self.items == [] def length(self): return len(self.items) def peek(self): ...
class Stack: def __init__(self): self.items = [] def push(self, item): return self.items.append(item) def pop(self): return self.items.pop() def is_empty(self): return self.items == [] def length(self): return len(self.items) def peek(self): ...
# User input percentage = float(input("Enter your marks: ")) # Program operation & Computer output if (percentage >= 90): print("Your grade is A1 !") elif (percentage >= 80): print("Your grade is A !") elif (percentage >= 70): print("Your grade is B1 !") elif (percentage >= 60): print("Your ...
percentage = float(input('Enter your marks: ')) if percentage >= 90: print('Your grade is A1 !') elif percentage >= 80: print('Your grade is A !') elif percentage >= 70: print('Your grade is B1 !') elif percentage >= 60: print('Your grade is B !') elif percentage >= 50: print('Your grade is C, try b...
#!/usr/bin/env python # -*- coding:utf-8 -*- def q_s(v): if len(v) <=1: return v left, right = 0, len(v) - 1 item = v[int((left+right))/2] left_value = [i for i in v if i < item] right_value = [i for i in v if i > item] return q_s(left_value) + [item] + q_s(right_value) if __name...
def q_s(v): if len(v) <= 1: return v (left, right) = (0, len(v) - 1) item = v[int(left + right) / 2] left_value = [i for i in v if i < item] right_value = [i for i in v if i > item] return q_s(left_value) + [item] + q_s(right_value) if __name__ == '__main__': v = [1, 2, 4, 3, 6, 7, 8...
# # PySNMP MIB module WWP-LEOS-OAM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-LEOS-OAM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:31:22 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) ...
# https://leetcode.com/problems/longest-palindromic-subsequence/ class Solution: def longestPalindromeSubseq(self, s: str) -> int: dp = [[0 for _ in range(len(s))] for _ in range(len(s))] for row in range(len(s)): for col in range(len(s)): # Find len of longest common su...
class Solution: def longest_palindrome_subseq(self, s: str) -> int: dp = [[0 for _ in range(len(s))] for _ in range(len(s))] for row in range(len(s)): for col in range(len(s)): if s[row] == s[-1 - col]: diagonal_top_left = dp[row - 1][col - 1] if row ...
# Time: O(n) # Space: O(1) class Solution(object): def findSubstringInWraproundString(self, p): """ :type p: str :rtype: int """ letters = [0] * 26 result, length = 0, 0 for i in xrange(len(p)): curr = ord(p[i]) - ord('a') ...
class Solution(object): def find_substring_in_wrapround_string(self, p): """ :type p: str :rtype: int """ letters = [0] * 26 (result, length) = (0, 0) for i in xrange(len(p)): curr = ord(p[i]) - ord('a') if i > 0 and ord(p[i - 1]) != (...
# This file is intended for use by the drake_py_test macro defined in # //tools/skylark:drake_py.bzl and should NOT be used by anything else. """A drake_py_test should not `import unittest`. In most cases, your BUILD.bazel file should use `drake_py_unittest` to declare such tests, which provides an appropriate main()...
"""A drake_py_test should not `import unittest`. In most cases, your BUILD.bazel file should use `drake_py_unittest` to declare such tests, which provides an appropriate main() routine (and will disable this warning). In the unlikely event that you actually have a unittest and need to write your own main, set `allow_...
# -- Project information ----------------------------------------------------- project = "PyData Tests" copyright = "2020, Pydata community" author = "Pydata community" master_doc = "index" # -- General configuration --------------------------------------------------- html_theme = "pydata_sphinx_theme" html_copy_s...
project = 'PyData Tests' copyright = '2020, Pydata community' author = 'Pydata community' master_doc = 'index' html_theme = 'pydata_sphinx_theme' html_copy_source = True html_sourcelink_suffix = ''
test = { 'name': 'q5g', 'points': 1, 'suites': [ { 'cases': [ { 'code': ">>> 'result_q5g' in globals()\n" 'True', 'hidden': False, 'locked': False}, ...
test = {'name': 'q5g', 'points': 1, 'suites': [{'cases': [{'code': ">>> 'result_q5g' in globals()\nTrue", 'hidden': False, 'locked': False}, {'code': '>>> result_q5g.to_string(index=False) == df_usa.fillna(value=0).head().to_string(index=False)\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 't...
# ======================== # Information # ======================== # Direct Link: https://www.hackerrank.com/challenges/s10-poisson-distribution-2/problem # Difficulty: Easy # Max Score: 30 # Language: Python # ======================== # Solution # ======================== AVERAGE_X, AVERAGE_Y = [floa...
(average_x, average_y) = [float(num) for num in input().split(' ')] cost_x = 160 + 40 * (AVERAGE_X + AVERAGE_X ** 2) cost_y = 128 + 40 * (AVERAGE_Y + AVERAGE_Y ** 2) print(round(COST_X, 3)) print(round(COST_Y, 3))
def cap_11(packet): # your code here try: if packet["RTMPT"]["string"] == '_result': packet["RTMPT"]["string"] = '_123456' print("cambiado") return packet except: print("fallo") return None
def cap_11(packet): try: if packet['RTMPT']['string'] == '_result': packet['RTMPT']['string'] = '_123456' print('cambiado') return packet except: print('fallo') return None
''' Hardcoded string input no filtering sink: check if a file exists ''' class Class_351: def __init__(self, param): self.var_351 = param def get_var_351(self): return self.var_351
""" Hardcoded string input no filtering sink: check if a file exists """ class Class_351: def __init__(self, param): self.var_351 = param def get_var_351(self): return self.var_351
class LiveDataFeed(object): """ A simple "live data feed" abstraction that allows a reader to read the most recent data and find out whether it was updated since the last read. Interface to data writer: add_data(data): Add new data to the feed...
class Livedatafeed(object): """ A simple "live data feed" abstraction that allows a reader to read the most recent data and find out whether it was updated since the last read. Interface to data writer: add_data(data): Add new data to the feed. ...
inv_count = 0 def sorter(l_res , r_res): global inv_count i = 0 r = 0 results = [] while i < len(l_res) and r < len(r_res): if l_res[i] > r_res[r]: results.append(r_res[r]) inv_count += len(l_res) - i r += 1 else: results.append(l_res...
inv_count = 0 def sorter(l_res, r_res): global inv_count i = 0 r = 0 results = [] while i < len(l_res) and r < len(r_res): if l_res[i] > r_res[r]: results.append(r_res[r]) inv_count += len(l_res) - i r += 1 else: results.append(l_res[i...
# -*- coding: utf-8 -*- """ ENERPIPLOT - Common constants & color palettes """ ROUND_W = 500 ROUND_KWH = .5 COLOR_REF_RMS = '#FF0077' # summary (consumption) var plots COLS_DATA_KWH = ['kWh', 'p_max', 'p_min', 't_ref'] COLORS_DATA_KWH = ['#8C27D3', '#972625', '#f4af38', '#8C27D3'] UNITS_DATA_KWH = ['kWh', 'W', 'W', ...
""" ENERPIPLOT - Common constants & color palettes """ round_w = 500 round_kwh = 0.5 color_ref_rms = '#FF0077' cols_data_kwh = ['kWh', 'p_max', 'p_min', 't_ref'] colors_data_kwh = ['#8C27D3', '#972625', '#f4af38', '#8C27D3'] units_data_kwh = ['kWh', 'W', 'W', ''] labels_data_kwh = ['Consumption', 'Max Power', 'Min Pow...
# # @lc app=leetcode.cn id=133 lang=python3 # # [133] clone-graph # None # @lc code=end
None
def add_node(v): if v in graph: print(v,"already present") else: graph[v]=[] def add_edge(v1,v2): if v1 not in graph: print(v1," not present in graph") elif v2 not in graph: print(v2,"not present in graph") else: graph[v1].append(v2) graph[v2].append(...
def add_node(v): if v in graph: print(v, 'already present') else: graph[v] = [] def add_edge(v1, v2): if v1 not in graph: print(v1, ' not present in graph') elif v2 not in graph: print(v2, 'not present in graph') else: graph[v1].append(v2) graph[v2].a...
# ================================================================ def total_packet_size_bytes (s): return (s ['packet_len'] + s ['num_credits'] + s ['channel_id'] + s ['payload']) def this_packet_size_bytes (s, n): return (s ['packet_len'] + s ['num_credits'] +...
def total_packet_size_bytes(s): return s['packet_len'] + s['num_credits'] + s['channel_id'] + s['payload'] def this_packet_size_bytes(s, n): return s['packet_len'] + s['num_credits'] + s['channel_id'] + n def subst(template, substs): s = '\n'.join(template) for (var, val) in substs: s = s.repl...
class S(str): # Symbol class: the only important difference between S and str is that S has a __substitute__ method # Note that S('a') == 'a' is True. This lets us use strings as shorthand in certain places. def __str__(self): return "S('" + super(S, self).__str__() + "')" def __repr__(self): ...
class S(str): def __str__(self): return "S('" + super(S, self).__str__() + "')" def __repr__(self): return 'S(' + super(S, self).__repr__() + ')' def __substitute__(self, values): return values[self] def identity(x): return x class Transsymbol(object): def __init__(self...
def randomized_partition(arr, low, high): """Partition the array into two halfs according to the last element (pivot) loop invariant: [low, i] <= pivot [i+1, j) > pivot """ i = low - 1 j = low pivot = arr[high] while j < high: if arr[j] <= pivot: i = i...
def randomized_partition(arr, low, high): """Partition the array into two halfs according to the last element (pivot) loop invariant: [low, i] <= pivot [i+1, j) > pivot """ i = low - 1 j = low pivot = arr[high] while j < high: if arr[j] <= pivot: i = i + ...
class SwampyException(Exception): pass class ExWelcomeTimeout(SwampyException): pass class ExAbort(SwampyException): pass class ExInvocationError(SwampyException): pass
class Swampyexception(Exception): pass class Exwelcometimeout(SwampyException): pass class Exabort(SwampyException): pass class Exinvocationerror(SwampyException): pass
""" aiida_abinit The AiiDA plugin for ABINIT. """ __version__ = "0.1.0a0"
""" aiida_abinit The AiiDA plugin for ABINIT. """ __version__ = '0.1.0a0'
class CableTrayConduitBase(MEPCurve,IDisposable): """ The CableTrayConduitBase class is implemented as the base class for cable tray or conduit """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def getBoundingBox(self,*args): """ getBoundingBox(self: Element,view: View) -> BoundingBoxX...
class Cabletrayconduitbase(MEPCurve, IDisposable): """ The CableTrayConduitBase class is implemented as the base class for cable tray or conduit """ def dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def get_bounding_box(self, *args): """ getBoundingBox(self: Element,...
#!/usr/bin/python3 def new_in_list(my_list, idx, element): new_list = my_list[:] if idx >= 0 and idx < len(my_list): new_list[idx] = element return new_list
def new_in_list(my_list, idx, element): new_list = my_list[:] if idx >= 0 and idx < len(my_list): new_list[idx] = element return new_list
# https://leetcode.com/problems/bitwise-ors-of-subarrays/ # # algorithms # Medium (32.02%) # Total Accepted: 5,616 # Total Submissions: 17,538 class Solution(object): def subarrayBitwiseORs(self, A): """ :type A: List[int] :rtype: int """ cur, res = set(), set() ...
class Solution(object): def subarray_bitwise_o_rs(self, A): """ :type A: List[int] :rtype: int """ (cur, res) = (set(), set()) for n in A: cur = {i | n for i in cur} | {n} res |= cur return len(res)
""" Class to parse and validate command-line arguments required by train, classify and evaluate. """ class ArgumentHandler: def __init__(self): #I/O #data.py: DataHandler self.logdir = None self.max_tokens = 200 self.labels = "" self.num_labels = 3 ...
""" Class to parse and validate command-line arguments required by train, classify and evaluate. """ class Argumenthandler: def __init__(self): self.logdir = None self.max_tokens = 200 self.labels = '' self.num_labels = 3 self.feature_input_dims = self.num_labels + 1 ...
class Body(object): """An class which is used to store basic properties about a body""" def __init__(self, xPos, yPos, xVel, yVel, mass): """Create a new body xPos - The x component of the position yPos - The y component of the position xVel - The x component of the velocity ...
class Body(object): """An class which is used to store basic properties about a body""" def __init__(self, xPos, yPos, xVel, yVel, mass): """Create a new body xPos - The x component of the position yPos - The y component of the position xVel - The x component of the velocity ...
def main(type): x = 0 print(type) if type=="wl": #a while loop while (x <5): print(x) x = x + 1 elif type=="fl": #a for loop for x in range(5,10): print(x) elif type=="cl": #a for loop over a collection days = ["Mon", "Tue", "Wed", "Thurs", "Fri", "Sat", "Sun"] for ...
def main(type): x = 0 print(type) if type == 'wl': while x < 5: print(x) x = x + 1 elif type == 'fl': for x in range(5, 10): print(x) elif type == 'cl': days = ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'] for d in days: ...
# Constants in FlexRay spec cdCycleMax = 16000 cCycleCountMax = 63 cStaticSlotIDMax = 1023 cSlotIDMax = 2047 cPayloadLengthMax = 127 cSamplesPerBit = 8 cSyncFrameIDCountMax = 15 cMicroPerMacroNomMin = 40 cdMinMTNom = 1 cdMaxMTNom = 6 cdFES = 2 cdFSS = 1 cChannelIdleDelimiter = 11 cClockDeviationMax = 0.0015 cStrobeOffs...
cd_cycle_max = 16000 c_cycle_count_max = 63 c_static_slot_id_max = 1023 c_slot_id_max = 2047 c_payload_length_max = 127 c_samples_per_bit = 8 c_sync_frame_id_count_max = 15 c_micro_per_macro_nom_min = 40 cd_min_mt_nom = 1 cd_max_mt_nom = 6 cd_fes = 2 cd_fss = 1 c_channel_idle_delimiter = 11 c_clock_deviation_max = 0.00...
""" 1. 187_XXX -> Self define exception """ class NameIsError(Exception): pass class AgeIsError(Exception): pass class HahaIsError(Exception): pass def check_name(name): if name.find("li") >= 0: raise NameIsError("Collision with my king's ", name) def check_age(age): if age >= ...
""" 1. 187_XXX -> Self define exception """ class Nameiserror(Exception): pass class Ageiserror(Exception): pass class Hahaiserror(Exception): pass def check_name(name): if name.find('li') >= 0: raise name_is_error("Collision with my king's ", name) def check_age(age): if age >= 50 ...
class Triple: def __init__(self, subject, predicate, object): self.subject = subject self.predicate = predicate self.object = object
class Triple: def __init__(self, subject, predicate, object): self.subject = subject self.predicate = predicate self.object = object
def main(): return 0 if __name__ == "__main__": for case in range(1, int(input()) + 1): print(f"Case #{case}:", main())
def main(): return 0 if __name__ == '__main__': for case in range(1, int(input()) + 1): print(f'Case #{case}:', main())
file = open('input.txt', 'r') Lines = file.readlines() count = 0 # Strips the newline character for line in Lines: line_parts = line.strip().split(' ') rule_part = line_parts[0].split('-') min_rule = int(rule_part[0]) max_rule = int(rule_part[1]) password = line_parts[2] char = line_parts[1][0] char_count = pa...
file = open('input.txt', 'r') lines = file.readlines() count = 0 for line in Lines: line_parts = line.strip().split(' ') rule_part = line_parts[0].split('-') min_rule = int(rule_part[0]) max_rule = int(rule_part[1]) password = line_parts[2] char = line_parts[1][0] char_count = password.count...
# Roman numeral/Decimal converter # Roman to decimal conversion table RomanValue = { 'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000 } def RomanValueList (RomanNumber): number = [] for i in RomanNumber: number.append(RomanValue[i]) return number # Convert Roman number stri...
roman_value = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000} def roman_value_list(RomanNumber): number = [] for i in RomanNumber: number.append(RomanValue[i]) return number def to_decimal(number): answer = number[-1] for i in range(len(number) - 1, 0, -1): right ...
# Python Program To Handle Multiple Exceptions def avg(list): tot = 0 for x in list: tot += x avg = tot/len(list) return tot, avg # Call The avg() And Pass A List try: t, a = avg([1,2,3,4,5,'a']) # Here Give Empty List And try print('Total = {}, Average = {}'....
def avg(list): tot = 0 for x in list: tot += x avg = tot / len(list) return (tot, avg) try: (t, a) = avg([1, 2, 3, 4, 5, 'a']) print('Total = {}, Average = {}'.format(t, a)) except TypeError: print('Type Error, Please Provide Numbers.') except ZeroDivisionError: print('Ze...
# -*- coding: utf-8 -*- # # Copyright 2014-2022 BigML # # 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 ...
"""Options for BigMLer test files processing """ def get_test_options(defaults=None): """Test files-related options """ if defaults is None: defaults = {} options = {'--test': {'action': 'store', 'dest': 'test_set', 'nargs': '?', 'default': defaults.get('test', None), 'help': 'Test set path.'...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
class Measureunit(object): """ Const Class These constants are used to specify a measure. A component using these constants may not support all units. See Also: `API MeasureUnit <https://api.libreoffice.org/docs/idl/ref/namespacecom_1_1sun_1_1star_1_1util_1_1MeasureUnit.html>`_ ""...
def dataset(): pass def model(): pass def loss(): pass def opt(): pass
def dataset(): pass def model(): pass def loss(): pass def opt(): pass
class Response: def __init__(self, message=None, data=None): self.message = message self.data = data def build(self): return { "message": self.message, "data": self.data }
class Response: def __init__(self, message=None, data=None): self.message = message self.data = data def build(self): return {'message': self.message, 'data': self.data}
def main(): double_letters = 0 triple_letters = 0 input_file = open('input', 'r') for line in input_file: double_letters_found = False triple_letters_found = False characters = set(line.replace('\n', '')) for character in characters: if not double_letters_foun...
def main(): double_letters = 0 triple_letters = 0 input_file = open('input', 'r') for line in input_file: double_letters_found = False triple_letters_found = False characters = set(line.replace('\n', '')) for character in characters: if not double_letters_foun...
coordinates_E0E1E1 = ((129, 120), (129, 122), (129, 124), (130, 124), (131, 124), (132, 124), (133, 124), (134, 124), (135, 124), (136, 123), (136, 132), (137, 119), (137, 123), (138, 119), (138, 122), (139, 120), (139, 122), (140, 121), (140, 123), (141, 121), (141, 126), (142, 113), (142, 115), (142, 121), (142, 12...
coordinates_e0_e1_e1 = ((129, 120), (129, 122), (129, 124), (130, 124), (131, 124), (132, 124), (133, 124), (134, 124), (135, 124), (136, 123), (136, 132), (137, 119), (137, 123), (138, 119), (138, 122), (139, 120), (139, 122), (140, 121), (140, 123), (141, 121), (141, 126), (142, 113), (142, 115), (142, 121), (142, 12...
num = int(input('digite um numero pra daber sua tabuada: ')) for rep in range(0, 11): print('{} x {:2} = {}'.format(rep, num, num*rep))
num = int(input('digite um numero pra daber sua tabuada: ')) for rep in range(0, 11): print('{} x {:2} = {}'.format(rep, num, num * rep))
class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: if len(preorder)==0: return None tn=TreeNode(preorder[0]) l=[] r=[] for i in preorder: if i<preorder[0]: l.append(i) elif i>preorder[0]: ...
class Solution: def bst_from_preorder(self, preorder: List[int]) -> TreeNode: if len(preorder) == 0: return None tn = tree_node(preorder[0]) l = [] r = [] for i in preorder: if i < preorder[0]: l.append(i) elif i > preorder...
n = int(input('digite um numero de 1 a 9999: ')) u = n % 10 d = n // 10 % 10 c = n // 100 % 10 m = n // 1000 % 10 print('A unidade', u) print('A dezena', d) print('A centena', c) print('A milhar', m)
n = int(input('digite um numero de 1 a 9999: ')) u = n % 10 d = n // 10 % 10 c = n // 100 % 10 m = n // 1000 % 10 print('A unidade', u) print('A dezena', d) print('A centena', c) print('A milhar', m)
def stair(n): if n == 0 or n == 1: return 1 elif n == 2: return 2 elif n == 3: return 4 else: return stair(n-3) + stair(n-2) + stair(n-1) n = int(input()) print(stair(n))
def stair(n): if n == 0 or n == 1: return 1 elif n == 2: return 2 elif n == 3: return 4 else: return stair(n - 3) + stair(n - 2) + stair(n - 1) n = int(input()) print(stair(n))
# # PySNMP MIB module CADANT-CMTS-EXPORTIMPORT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CADANT-CMTS-EXPORTIMPORT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:27:10 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python vers...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, value_size_constraint, constraints_intersection, constraints_union) ...
class Problem: """ Given a string of different arrows designating to four directions. Then we can rotate arrows so that they designate the same direction. Example "^^<>vvv" -> "^^^^^^^" -> 5 operations "^^<>vvv" -> "vvvvvvv" -> 4 operations "^^<>vvv" -> ">>>>>>>" -> 6 operations Find t...
class Problem: """ Given a string of different arrows designating to four directions. Then we can rotate arrows so that they designate the same direction. Example "^^<>vvv" -> "^^^^^^^" -> 5 operations "^^<>vvv" -> "vvvvvvv" -> 4 operations "^^<>vvv" -> ">>>>>>>" -> 6 operations Find t...
#!/home/jepoy/anaconda3/bin/python ## at terminal which python #simple fibonacci series # the sum of two elements defines the next set a, b = 0, 1 while b < 1000: print(b, end = ' ', flush = True) a, b = b, a + b print() # line ending
(a, b) = (0, 1) while b < 1000: print(b, end=' ', flush=True) (a, b) = (b, a + b) print()
def create(type): switcher = { "L": LPiece(), "O": OPiece(), "I": IPiece(), "J": JPiece(), "S": SPiece(), "T": TPiece(), "Z": ZPiece() } return switcher.get(type.upper()) class Piece: def __init__(self): self._rotateIndex...
def create(type): switcher = {'L': l_piece(), 'O': o_piece(), 'I': i_piece(), 'J': j_piece(), 'S': s_piece(), 'T': t_piece(), 'Z': z_piece()} return switcher.get(type.upper()) class Piece: def __init__(self): self._rotateIndex = 0 self._rotations = [] def turn_left(self, times=1): ...
class HelperBase: def __init__(self, app): self.app = app def type(self, locator, text): wd = self.app.wd if text is not None: wd.find_element_by_name(locator).click() wd.find_element_by_name(locator).clear() wd.find_element_by_name(locator).send_k...
class Helperbase: def __init__(self, app): self.app = app def type(self, locator, text): wd = self.app.wd if text is not None: wd.find_element_by_name(locator).click() wd.find_element_by_name(locator).clear() wd.find_element_by_name(locator).send_key...
#!/usr/bin/python3 print("Hello World") x=4 y="ok,google" z=[4,77,x,y] print(y) print(z) print(x,y)
print('Hello World') x = 4 y = 'ok,google' z = [4, 77, x, y] print(y) print(z) print(x, y)
major = 1 minor = 0 micro = None pre_release = ".alpha" post_release = None dev_release = None __version__ = '{}'.format(major) if minor is not None: __version__ += '.{}'.format(minor) if micro is not None: __version__ += '.{}'.format(micro) if pre_release is not None: __version__ += '{}'.format(pre_re...
major = 1 minor = 0 micro = None pre_release = '.alpha' post_release = None dev_release = None __version__ = '{}'.format(major) if minor is not None: __version__ += '.{}'.format(minor) if micro is not None: __version__ += '.{}'.format(micro) if pre_release is not None: __version__ += '{}'.format(pre_release...
############################# #PROJECT : ENCODER-DECODER #Language :English #basic encode and decode #Contact me on ; #Telegram : Zafiyetsiz0 #Instagram : Zafiyetsiz #Discord : Zafiyetsiz#4172 ############################## print("1-Encoder ; 2-Decoder") choise=int(input("Please type the number of transacti...
print('1-Encoder ; 2-Decoder') choise = int(input('Please type the number of transaction you want :')) print('-----------------------------------------------------------------------------') if choise == 1: letters = 'abcdefghijklmnopqrstuvwxyz' print('key should be between 1-9999 and do not forget it ;') ke...
def fib(a,b,n): if(n==1): return a elif(n==2): return b else: return fib(a,b,n-2)+fib(a,b,n-1)*fib(a,b,n-1) r = input(); r = r.split(' ') a = int(r[0]) b = int(r[1]) n = int(r[2]) print(fib(a,b,n))
def fib(a, b, n): if n == 1: return a elif n == 2: return b else: return fib(a, b, n - 2) + fib(a, b, n - 1) * fib(a, b, n - 1) r = input() r = r.split(' ') a = int(r[0]) b = int(r[1]) n = int(r[2]) print(fib(a, b, n))
#Actividad 2 a=1+2**-53 print(a) b=a-1 print(b) a=1+2**-52 print(a) b=a-1
a = 1 + 2 ** (-53) print(a) b = a - 1 print(b) a = 1 + 2 ** (-52) print(a) b = a - 1
a = [{'001': '001', '002': '002'}] print(a, type(a)) a = a.__str__() print(a, type(a)) print(['------------------']) init_list = [0 for n in range(10)] init_list2 = [0] * 10 print(init_list) print(init_list2) # list - replace a = ['110', '111', '112', '113'] for i in a: print(i, a.index(i)) ...
a = [{'001': '001', '002': '002'}] print(a, type(a)) a = a.__str__() print(a, type(a)) print(['------------------']) init_list = [0 for n in range(10)] init_list2 = [0] * 10 print(init_list) print(init_list2) a = ['110', '111', '112', '113'] for i in a: print(i, a.index(i)) if i == '112': id = a.index(i...
# Check whether the string is palindrome or not considering # only Alpha-Numeric Characters ignoring cases s = input(); t = ''.join([i.lower() if i.isalnum() else '' for i in s]) if t==''.join(reversed(t)): print("It is a Palindrome String") else: print("It is not a Palindrome String")
s = input() t = ''.join([i.lower() if i.isalnum() else '' for i in s]) if t == ''.join(reversed(t)): print('It is a Palindrome String') else: print('It is not a Palindrome String')
# cannot be changed by user: coinbaseReward = 5000000000 #50 bitcoins halvingInterval = 150 maxOutputsPerTx = 1000 scalingUnits = .000001 # units of cap confirmations = 6 onchainSatoshiMinimum = 100 maxTxPerBlock = 20 # 200 transactions in a block plus coinbase (which is at index 0) iCoinbasePriv = 100000000 # so...
coinbase_reward = 5000000000 halving_interval = 150 max_outputs_per_tx = 1000 scaling_units = 1e-06 confirmations = 6 onchain_satoshi_minimum = 100 max_tx_per_block = 20 i_coinbase_priv = 100000000 b_coinbase_priv = bytearray(iCoinbasePriv.to_bytes(32, 'big'))
"""Formatter to extract the output files from a target.""" def format(target): provider_map = providers(target) if not provider_map: return "" outputs = dict() # Try to resolve in order. files_to_run = provider_map.get("FilesToRunProvider", None) default_info = provider_map.get("Defaul...
"""Formatter to extract the output files from a target.""" def format(target): provider_map = providers(target) if not provider_map: return '' outputs = dict() files_to_run = provider_map.get('FilesToRunProvider', None) default_info = provider_map.get('DefaultInfo', None) output_group_i...
__all__ = [ 'base_controller', 'basic_api_controller', 'advanced_api_controller', 'enterprise_only_controller', ]
__all__ = ['base_controller', 'basic_api_controller', 'advanced_api_controller', 'enterprise_only_controller']
""" Definition of exceptions thrown by arrus functions. """ class ArrusError(Exception): pass class IllegalArgumentError(ArrusError, ValueError): pass class DeviceNotFoundError(ArrusError, ValueError): pass class IllegalStateError(ArrusError, RuntimeError): pass class TimeoutError(ArrusError, T...
""" Definition of exceptions thrown by arrus functions. """ class Arruserror(Exception): pass class Illegalargumenterror(ArrusError, ValueError): pass class Devicenotfounderror(ArrusError, ValueError): pass class Illegalstateerror(ArrusError, RuntimeError): pass class Timeouterror(ArrusError, Timeo...