content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/python3 ## Solution 1: def to_rna(dna_strand): rna = [] for transcription in dna_strand: if transcription == "G": rna.append("C") elif transcription == "C": rna.append("G") elif transcription == "T": rna.append("A") elif transcriptio...
def to_rna(dna_strand): rna = [] for transcription in dna_strand: if transcription == 'G': rna.append('C') elif transcription == 'C': rna.append('G') elif transcription == 'T': rna.append('A') elif transcription == 'A': rna.append('...
filepath = 'Prometheus_Unbound.txt' with open(filepath) as fp: line = fp.readline() cnt = 1 while line: print("Line {}: {}".format(cnt, line.strip())) line = fp.readline() cnt += 1
filepath = 'Prometheus_Unbound.txt' with open(filepath) as fp: line = fp.readline() cnt = 1 while line: print('Line {}: {}'.format(cnt, line.strip())) line = fp.readline() cnt += 1
sum = 0 for i in range(1000): if i%3==0 or i%5==0: sum+=i print(sum)
sum = 0 for i in range(1000): if i % 3 == 0 or i % 5 == 0: sum += i print(sum)
# -*- coding: utf-8 -*- """ Created on Fri Feb 28 15:37:22 2020 @author: 766810 """ # Creates a dictionary called 'score' which takes each letter in scrabble as keys and assigns their respective points as values score = {"a": 1 , "b": 3 , "c": 3 , "d": 2 , "e": 1 , "f": 4 , "g": 2 , "h": 4 , ...
""" Created on Fri Feb 28 15:37:22 2020 @author: 766810 """ score = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10} def scrabble_score(word): total = 0...
""" Write a Python function to reverses a string if it's length is a multiple of 4. """ def reverse_string(str1): if len(str1) % 4 == 0: return "".join(reversed(str1)) return str1 print(reverse_string("Python")) print(reverse_string("abcd"))
""" Write a Python function to reverses a string if it's length is a multiple of 4. """ def reverse_string(str1): if len(str1) % 4 == 0: return ''.join(reversed(str1)) return str1 print(reverse_string('Python')) print(reverse_string('abcd'))
# -*- coding: utf-8 -*- """ Package of employer interfaces and implementations. """
""" Package of employer interfaces and implementations. """
# https://www.codingame.com/training/easy/lumen def get_neighbors(col, row, room_size): if room_size == 1: return if row > 0: yield col, row - 1 if col > 0: yield col - 1, row - 1 if col < room_size - 1: yield col + 1, row - 1 if row < room_size - 1: yield col, row + 1 ...
def get_neighbors(col, row, room_size): if room_size == 1: return if row > 0: yield (col, row - 1) if col > 0: yield (col - 1, row - 1) if col < room_size - 1: yield (col + 1, row - 1) if row < room_size - 1: yield (col, row + 1) if col...
neighborhoods = [ "Andersonville", "Archer Heights", "Ashburn", "Ashburn Estates", "Austin", "Avaondale", "Belmont Central", "Beverly", "Beverly Woods", "Brainerd", "Bridgeport", "Brighton Park", "Bronceville", "Bucktown", "Burnside", "Calumet Heights", ...
neighborhoods = ['Andersonville', 'Archer Heights', 'Ashburn', 'Ashburn Estates', 'Austin', 'Avaondale', 'Belmont Central', 'Beverly', 'Beverly Woods', 'Brainerd', 'Bridgeport', 'Brighton Park', 'Bronceville', 'Bucktown', 'Burnside', 'Calumet Heights', 'Canaryville', 'Clearing', 'Chatham', 'Chinatown', 'Cottage Grove H...
largura = int(input('digite a largura: ')) altura = int(input('digite a altura: ')) resetalargura = largura contador = largura print((largura) * '#', end='') while altura > 0: while contador < largura and contador > 0: print('#', end='') contador -= 1 print('#') altura -= 1 print((largu...
largura = int(input('digite a largura: ')) altura = int(input('digite a altura: ')) resetalargura = largura contador = largura print(largura * '#', end='') while altura > 0: while contador < largura and contador > 0: print('#', end='') contador -= 1 print('#') altura -= 1 print(largura * '#'...
""" Use recursion to write a Python function for determining if a string S has more vowels than consonants. """ def remove_whitespace(string: str) -> str: """ This function replace whitespaces for void string -> '' Input: string with (or without) whitespace Output: string wi...
""" Use recursion to write a Python function for determining if a string S has more vowels than consonants. """ def remove_whitespace(string: str) -> str: """ This function replace whitespaces for void string -> '' Input: string with (or without) whitespace Output: string without white...
def task_dis(size,task_list): task_num=len(task_list) task_dis_list=[] for i in range(size): task_dis_list.append([]) #print(str(task_dis_list)) for i in range(len(task_list)): for j in range(size): if i%size==j: task_dis_list[j].append(task_list[i]) #for i in range(size): # print("************"...
def task_dis(size, task_list): task_num = len(task_list) task_dis_list = [] for i in range(size): task_dis_list.append([]) for i in range(len(task_list)): for j in range(size): if i % size == j: task_dis_list[j].append(task_list[i]) return task_dis_list if...
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? ''' p_no = 0 def is_prime(x): if x >= 2: for y in range(2,x): if not( x % y ): #reverse the modulo operation retu...
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ p_no = 0 def is_prime(x): if x >= 2: for y in range(2, x): if not x % y: return False else: return False return Tru...
class Pendulum(): """ Pendulum class implements the parameters and differential equation for a pendulum using the notation from Taylor. The class will now have the solve_ode method removed...everything else will remain the same. Parameters ---------- omega_0 : float natural ...
class Pendulum: """ Pendulum class implements the parameters and differential equation for a pendulum using the notation from Taylor. The class will now have the solve_ode method removed...everything else will remain the same. Parameters ---------- omega_0 : float natural fr...
load("//third_party:repos/boost.bzl", "boost_repository") load("//third_party:repos/grpc.bzl", "grpc_rules_repository") load("//third_party:repos/gtest.bzl", "gtest_repository") def dependencies(excludes = []): ignores = native.existing_rules().keys() + excludes if "com_github_nelhage_rules_boost" not in igno...
load('//third_party:repos/boost.bzl', 'boost_repository') load('//third_party:repos/grpc.bzl', 'grpc_rules_repository') load('//third_party:repos/gtest.bzl', 'gtest_repository') def dependencies(excludes=[]): ignores = native.existing_rules().keys() + excludes if 'com_github_nelhage_rules_boost' not in ignores...
class EncodingEnum: BINARY_ENCODING = 0 BINARY_WITH_VARIABLE_LENGTH_STRINGS = 1 JSON_ENCODING = 2 JSON_COMPACT_ENCODING = 3 PROTOCOL_BUFFERS = 4
class Encodingenum: binary_encoding = 0 binary_with_variable_length_strings = 1 json_encoding = 2 json_compact_encoding = 3 protocol_buffers = 4
JS(""" __NULL_OBJECT__ = {} __concat_tables_array = function(t1, t2) for i=1,#t2 do t1[ #t1+1 ] = t2[i] end return t1 end __concat_tables = function(t1, t2) for k,v in pairs(t2) do t1[k] = v end return t1 end function table.shallow_copy(t) local t2 = {} for k,v in pairs(t) do t2[k] = v end return t2 ...
js("\n__NULL_OBJECT__ = {}\n\n__concat_tables_array = function(t1, t2)\n\tfor i=1,#t2 do\n\t\tt1[ #t1+1 ] = t2[i]\n\tend\n\treturn t1\nend\n\n__concat_tables = function(t1, t2)\n\tfor k,v in pairs(t2) do\n\t\tt1[k] = v\n\tend\n\treturn t1\nend\n\nfunction table.shallow_copy(t)\n\tlocal t2 = {}\n\tfor k,v in pairs(t) do...
num = int(input('Digite um numero [999 para parar]: ')) soma = 0 tot = 0 while num != 999: soma += num tot += 1 num = int(input('Digite um numero [999 para parar] : ')) print(f'{soma} e {tot}')
num = int(input('Digite um numero [999 para parar]: ')) soma = 0 tot = 0 while num != 999: soma += num tot += 1 num = int(input('Digite um numero [999 para parar] : ')) print(f'{soma} e {tot}')
_base_ = [ '../../_base_/models/faster_rcnn_r50_fpn.py', '../../_base_/datasets/waymo_detection_1280x1920.py', '../../_base_/schedules/schedule_1x.py', '../../_base_/default_runtime.py' ] # model model = dict( rpn_head=dict( anchor_generator=dict( type='AnchorGenerator', ...
_base_ = ['../../_base_/models/faster_rcnn_r50_fpn.py', '../../_base_/datasets/waymo_detection_1280x1920.py', '../../_base_/schedules/schedule_1x.py', '../../_base_/default_runtime.py'] model = dict(rpn_head=dict(anchor_generator=dict(type='AnchorGenerator', scales=[3], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64...
a = 5 b = 6 c = 7.5 result = multiply(a, b, c) print(result)
a = 5 b = 6 c = 7.5 result = multiply(a, b, c) print(result)
ch=input("Enter ch = ") for i in range (0,len(ch)-1,2): if(ch[i].isalpha()): print((ch[i])*int(ch[i+1]),end="") elif(ch[i+1].isalpha()): print((ch[i+1])*int(ch[i]),end="")
ch = input('Enter ch = ') for i in range(0, len(ch) - 1, 2): if ch[i].isalpha(): print(ch[i] * int(ch[i + 1]), end='') elif ch[i + 1].isalpha(): print(ch[i + 1] * int(ch[i]), end='')
class KalmanFilter: def __init__(self, errorMeasurement, errorEstimate, q): self.errorMeasurement = errorMeasurement self.errorEstimate = errorEstimate self.q = q #covariance error self.lastEstimate = 25.0 self.currentEstimate = 25.0 def updateEstimate(se...
class Kalmanfilter: def __init__(self, errorMeasurement, errorEstimate, q): self.errorMeasurement = errorMeasurement self.errorEstimate = errorEstimate self.q = q self.lastEstimate = 25.0 self.currentEstimate = 25.0 def update_estimate(self, measurement): k_gain...
''' Settings for generating synthetic images using code for Cut, Paste, and Learn Paper ''' # Paths BACKGROUND_DIR = '/scratch/jnan1/background/TRAIN' BACKGROUND_GLOB_STRING = '*.png' INVERTED_MASK = False # Set to true if white pixels represent background # Parameters for generator NUMBER_OF_WORKERS = 4 BLENDING_LIS...
""" Settings for generating synthetic images using code for Cut, Paste, and Learn Paper """ background_dir = '/scratch/jnan1/background/TRAIN' background_glob_string = '*.png' inverted_mask = False number_of_workers = 4 blending_list = ['gaussian', 'none', 'box', 'motion'] min_no_of_objects = 1 max_no_of_objects = 3 mi...
# https://adventofcode.com/2019/day/4 def is_valid_password(i: int, version: int = 1) -> bool: i_digits = [int(digit) for digit in str(i)] is_increasing, repeats = True, False for k in range(len(i_digits) - 1): if i_digits[k] > i_digits[k+1]: is_increasing = False elif version ...
def is_valid_password(i: int, version: int=1) -> bool: i_digits = [int(digit) for digit in str(i)] (is_increasing, repeats) = (True, False) for k in range(len(i_digits) - 1): if i_digits[k] > i_digits[k + 1]: is_increasing = False elif version == 1 and i_digits[k] == i_digits[k +...
""" Module: 'pybricks.uev3dev.sound' on LEGO EV3 v1.0.0 """ # MCU: sysname=ev3, nodename=ev3, release=('v1.0.0',), version=('0.0.0',), machine=ev3 # Stubber: 1.3.2 INT32 = 671088640 class Mixer: '' _attach = None _close = None _find_selem = None _load = None _open = None _selem_get_playback...
""" Module: 'pybricks.uev3dev.sound' on LEGO EV3 v1.0.0 """ int32 = 671088640 class Mixer: """""" _attach = None _close = None _find_selem = None _load = None _open = None _selem_get_playback_volume_range = None _selem_id_set_index = None _selem_id_set_name = None _selem_id_size...
""" Fill out the file src/visualization/visualize.py with this (as minimum, feel free to add more vizualizations) loads a pre-trained network, extracts some intermediate representation of the data (your training set) from your cnn. This could be the features just before the final classification layer Visualize feature...
""" Fill out the file src/visualization/visualize.py with this (as minimum, feel free to add more vizualizations) loads a pre-trained network, extracts some intermediate representation of the data (your training set) from your cnn. This could be the features just before the final classification layer Visualize feature...
def astore_url(package, uid, instance = "https://astore.corp.enfabrica.net"): """Returns a URL for a particular package version from astore.""" if not package.startswith("/"): package = "/" + package return "{}/d{}?u={}".format( instance, package, uid, ) def _astore_uplo...
def astore_url(package, uid, instance='https://astore.corp.enfabrica.net'): """Returns a URL for a particular package version from astore.""" if not package.startswith('/'): package = '/' + package return '{}/d{}?u={}'.format(instance, package, uid) def _astore_upload(ctx): push = ctx.actions.d...
# -*- coding: utf-8 -*- """ Datary Api python sdk Operations Limits files. """ class DataryOperationLimits(): """ Datary OperationLimits module class """ _DEFAULT_LIMITED_DATARY_SIZE = 9500000
""" Datary Api python sdk Operations Limits files. """ class Dataryoperationlimits: """ Datary OperationLimits module class """ _default_limited_datary_size = 9500000
#Function which finds 45 minutes before current time def alarm_clock(h, m): #Finding total minutes passed total_minutes = h * 60 + m ans = [] #Subtracting 45 minutes if total_minutes >= 45: answer_minutes = total_minutes - 45 else: answer_minutes = total_minutes - 45 + 1440 ...
def alarm_clock(h, m): total_minutes = h * 60 + m ans = [] if total_minutes >= 45: answer_minutes = total_minutes - 45 else: answer_minutes = total_minutes - 45 + 1440 ans += [answer_minutes // 60, answer_minutes % 60] return ans (h, m) = map(int, input().split()) answer_list = [...
# -*- coding: utf-8 -*- """ Created on Thu Oct 25 22:37:47 2018 @author: JinJheng """ def compute(): x=int(input()) if x<=1: print('Not Prime') else: for i in range(2,x+1): if x%i==0: print('Not Prime') else: print('Pr...
""" Created on Thu Oct 25 22:37:47 2018 @author: JinJheng """ def compute(): x = int(input()) if x <= 1: print('Not Prime') else: for i in range(2, x + 1): if x % i == 0: print('Not Prime') else: print('Prime') break compu...
# -*- coding: utf-8 -*- """ Created on Wed Dec 13 17:02:29 2017 @author: taichi """ file = open("sample_data\poem.txt", "a" ); file.write("How can a clam cram in a clean cream can?") file.close()
""" Created on Wed Dec 13 17:02:29 2017 @author: taichi """ file = open('sample_data\\poem.txt', 'a') file.write('How can a clam cram in a clean cream can?') file.close()
class TypeValidator(object): def __init__(self, *types, **options): self.types = types self.exclude = options.get('exclude') def __call__(self, value): if self.exclude is not None and isinstance(value, self.exclude): return False if not isinstance(value, self.types...
class Typevalidator(object): def __init__(self, *types, **options): self.types = types self.exclude = options.get('exclude') def __call__(self, value): if self.exclude is not None and isinstance(value, self.exclude): return False if not isinstance(value, self.types)...
class ImageArea: def __init__(self, width, height): self.width = width self.height = height def get_area(self): area = self.width * self.height return area def __gt__(self, other): return self.get_area() > other.get_area() def __ge__(self, other): retur...
class Imagearea: def __init__(self, width, height): self.width = width self.height = height def get_area(self): area = self.width * self.height return area def __gt__(self, other): return self.get_area() > other.get_area() def __ge__(self, other): retu...
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: found = {} max_length = 0 start_pos = -1 for pos, char in enumerate(s): if char in found and start_pos <= found[char]: start_pos = found[char] else: max_length =...
class Solution: def length_of_longest_substring(self, s: str) -> int: found = {} max_length = 0 start_pos = -1 for (pos, char) in enumerate(s): if char in found and start_pos <= found[char]: start_pos = found[char] else: max_le...
try: raise ArithmeticError except Exception: print("Caught ArithmeticError via Exception") try: raise ArithmeticError except ArithmeticError: print("Caught ArithmeticError") try: raise AssertionError except Exception: print("Caught AssertionError via Exception") try: raise AssertionError ...
try: raise ArithmeticError except Exception: print('Caught ArithmeticError via Exception') try: raise ArithmeticError except ArithmeticError: print('Caught ArithmeticError') try: raise AssertionError except Exception: print('Caught AssertionError via Exception') try: raise AssertionError exc...
# The directory where jobs are stored job_directory = "/fred/oz988/gwcloud/jobs/" # Format submission script for specified scheduler. scheduler = "slurm" # Environment scheduler sources during runtime scheduler_env = "/fred/oz988/gwcloud/gwcloud_job_client/bundles/unpacked/fbc9f7c0815f1a83b0de36f957351c93797b2049/ven...
job_directory = '/fred/oz988/gwcloud/jobs/' scheduler = 'slurm' scheduler_env = '/fred/oz988/gwcloud/gwcloud_job_client/bundles/unpacked/fbc9f7c0815f1a83b0de36f957351c93797b2049/venv/bin/activate'
# Node: Gate G102 (1096088604) # http://www.openstreetmap.org/node/1096088604 assert_has_feature( 16, 10487, 25366, 'pois', { 'id': 1096088604, 'kind': 'aeroway_gate' }) # Node: Gate 1 (2618197593) # http://www.openstreetmap.org/node/2618197593 assert_has_feature( 16, 10309, 22665, 'pois', { 'id': 2618...
assert_has_feature(16, 10487, 25366, 'pois', {'id': 1096088604, 'kind': 'aeroway_gate'}) assert_has_feature(16, 10309, 22665, 'pois', {'id': 2618197593, 'kind': 'gate', 'aeroway': type(None)}) assert_has_feature(16, 13462, 24933, 'pois', {'id': 2122898936, 'kind': 'ski_rental'}) assert_has_feature(16, 10566, 25429, 'la...
"""def splitText(text, lineLength, tabCount): lastSpace = 0 cnt = 0 if(len(text) <= lineLength): return text for(i in range(len(text))) if(cnt > lineLength) if(text[i] == ' '): last""" def writeBinaryData(file, data, length): itr = 0 for i in range(length): if itr % 16 == 0: file.writeNo...
"""def splitText(text, lineLength, tabCount): lastSpace = 0 cnt = 0 if(len(text) <= lineLength): return text for(i in range(len(text))) if(cnt > lineLength) if(text[i] == ' '): last""" def write_binary_data(file, data, length): itr = 0 for i in range(length): if itr % 16 == 0: ...
# Leo colorizer control file for io mode. # This file is in the public domain. # Properties for io mode. properties = { "commentStart": "*/", "indentCloseBrackets": ")", "indentOpenBrackets": "(", "lineComment": "//", "lineUpClosingBracket": "true", } # Attributes dict for io_main rule...
properties = {'commentStart': '*/', 'indentCloseBrackets': ')', 'indentOpenBrackets': '(', 'lineComment': '//', 'lineUpClosingBracket': 'true'} io_main_attributes_dict = {'default': 'null', 'digit_re': '', 'escape': '\\', 'highlight_digits': 'true', 'ignore_case': 'false', 'no_word_sep': ''} attributes_dict_dict = {'io...
# Copyright 2019 Open Source Robotics Foundation # Licensed under the Apache License, version 2.0 """Colcon event handler extensions for analyzing sanitizer outputs."""
"""Colcon event handler extensions for analyzing sanitizer outputs."""
x = int(input()) ar = list(map(int,input().split())) ar = sorted(ar) if(ar[0]<=0): print(False) else: chk = False for i in ar: s = str(i) if (s==s[::-1]): chk = True break print(chk)
x = int(input()) ar = list(map(int, input().split())) ar = sorted(ar) if ar[0] <= 0: print(False) else: chk = False for i in ar: s = str(i) if s == s[::-1]: chk = True break print(chk)
#!/bin/zsh ''' Extending the Multiclipboard Extend the multiclipboard program in this chapter so that it has a delete <keyword> command line argument that will delete a keyword from the shelf. Then add a delete command line argument that will delete all keywords. '''
""" Extending the Multiclipboard Extend the multiclipboard program in this chapter so that it has a delete <keyword> command line argument that will delete a keyword from the shelf. Then add a delete command line argument that will delete all keywords. """
""" 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignor...
""" 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignor...
# Copyright 2021 Google LLC # # 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, ...
"""Provides classes to ease writing snippets of javascript code in python. The JsSelector class allows generating selector code easily. """ class Jsselector(object): """Create javascript code for selecting DOM elements. This class generates javascript code that can chain calls on a root element ('document' b...
class CityNotFoundError(Exception): pass class ServerError(Exception): pass class OWMApiKeyIsNotCorrectError(ServerError): pass
class Citynotfounderror(Exception): pass class Servererror(Exception): pass class Owmapikeyisnotcorrecterror(ServerError): pass
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: l = 0 r = len(numbers) - 1 while l < r: sum = numbers[l] + numbers[r] if sum == target: return [l + 1, r + 1] if sum < target: l += 1 else: r -= 1
class Solution: def two_sum(self, numbers: List[int], target: int) -> List[int]: l = 0 r = len(numbers) - 1 while l < r: sum = numbers[l] + numbers[r] if sum == target: return [l + 1, r + 1] if sum < target: l += 1 ...
HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' REDEFINED = "\033[0;0m" PROCESS = "\033[1;37;42m" def message_information(text): print(OKBLUE + str(text) + REDEFINED) def message_sucess(text): pri...
header = '\x1b[95m' okblue = '\x1b[94m' okgreen = '\x1b[92m' warning = '\x1b[93m' fail = '\x1b[91m' endc = '\x1b[0m' bold = '\x1b[1m' underline = '\x1b[4m' redefined = '\x1b[0;0m' process = '\x1b[1;37;42m' def message_information(text): print(OKBLUE + str(text) + REDEFINED) def message_sucess(text): print(OKG...
class SensorStatusJob: on = 'ON' off = 'OFF' broken = 'BROKEN' charge_low = 'CHARGE_LOW' discharged = 'DISCHARGED' class SensorStatusSituation: null = 'NULL' stable = 'STABLE' fire = 'FIRE' warning = 'WARNING' class ObjectStatusJob: on = 'ON' off = 'OFF' defect = 'DEF...
class Sensorstatusjob: on = 'ON' off = 'OFF' broken = 'BROKEN' charge_low = 'CHARGE_LOW' discharged = 'DISCHARGED' class Sensorstatussituation: null = 'NULL' stable = 'STABLE' fire = 'FIRE' warning = 'WARNING' class Objectstatusjob: on = 'ON' off = 'OFF' defect = 'DEFEC...
""" # @Time : 2020/6/24 # @Author : Jimou Chen """ class Stack: def __init__(self): self.elem = [] def pop(self): self.elem.pop() def push(self, obj): self.elem.append(obj) def get_pop(self): return self.elem[-1] def is_empty(self): if len(self.ele...
""" # @Time : 2020/6/24 # @Author : Jimou Chen """ class Stack: def __init__(self): self.elem = [] def pop(self): self.elem.pop() def push(self, obj): self.elem.append(obj) def get_pop(self): return self.elem[-1] def is_empty(self): if len(self.ele...
"""Given two arrays a and b write a function comp(a, b) (orcompSame(a, b)) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order. Examples Valid arrays a = [121, 144, 19, 161, 19, 144,...
"""Given two arrays a and b write a function comp(a, b) (orcompSame(a, b)) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order. Examples Valid arrays a = [121, 144, 19, 161, 19, 144,...
# Misc general coloring tips # Color organization: highlighted, neutral, and low-lighted/background # Red and green in center of screen # Blue, black, white, and yellow in periphery of screen # http://www.awwwards.com/flat-design-an-in-depth-look.html # main actions such as "Submit," "Send," "See More," should have v...
titlefont1 = {'type': ('Segoe UI', 12, 'bold'), 'color': 'black'} titlefont1_contrast = {'type': ('Segoe UI', 12, 'bold'), 'color': 'white'} font1 = {'type': ('Segoe UI', 10), 'color': 'black'} font2 = {'type': ('Segoe UI', 10), 'color': 'Grey42'} color1 = 'Grey69' color2 = 'Grey79' color3 = 'Grey89' color4 = 'Grey99' ...
subprocess.Popen('/bin/ls *', shell=True) #nosec (on the line) subprocess.Popen('/bin/ls *', #nosec (at the start of function call) shell=True) subprocess.Popen('/bin/ls *', shell=True) #nosec (on the specific kwarg line)
subprocess.Popen('/bin/ls *', shell=True) subprocess.Popen('/bin/ls *', shell=True) subprocess.Popen('/bin/ls *', shell=True)
''' Single point of truth for version information ''' VERSION_NO = '1.1.7' VERSION_DESC = 'VAWS' + VERSION_NO
""" Single point of truth for version information """ version_no = '1.1.7' version_desc = 'VAWS' + VERSION_NO
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: if head is None: return None slow = fast = head meet = None while fast and fas...
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def detect_cycle(self, head: ListNode) -> ListNode: if head is None: return None slow = fast = head meet = None while fast and fast.next: slow = slow.ne...
# Create a string variable with your full name name = "Boris Johnson" # Split the string into a list names = name.split(" ") # Print out your surname surname = names[-1] print("Surname:", surname) # Check if your surname contains the letter 'e' pos = surname.find("e") print("Position of 'e':", pos) # or contains th...
name = 'Boris Johnson' names = name.split(' ') surname = names[-1] print('Surname:', surname) pos = surname.find('e') print("Position of 'e':", pos) pos = surname.find('o') print("Position of 'o':", pos)
""" Max() Function Write a program that can take two numbers from user and then pass these numbers as arguments to function called max(a, b) where a is the first number and b is the second number. This finction should print the maximum number. """ def Max(a, b): # He used 'M' capital in Max() because ...
""" Max() Function Write a program that can take two numbers from user and then pass these numbers as arguments to function called max(a, b) where a is the first number and b is the second number. This finction should print the maximum number. """ def max(a, b): if a > b: print(a, 'is the ...
# Bit Manipulation # Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). # # Example 1: # # Input: 11 # Output: 3 # Explanation: Integer 11 has binary representation 00000000000000000000000000001011 # Example 2: # # Input: 128 # Output: 1 # Expl...
class Solution(object): def hamming_weight(self, n): """ :type n: int :rtype: int """ return bin(n)[2:].count('1')
value = 'some' #modify this line if value == 'Y' or value == 'y': print('yes') elif value == 'N' or value == 'n': print('no') else: print('error')
value = 'some' if value == 'Y' or value == 'y': print('yes') elif value == 'N' or value == 'n': print('no') else: print('error')
class BasicBlock(object): def __init__(self): self.start_addr = 0 self.end_addr = 0 self.instructions = [] self.successors = [] def __str__(self): return "0x%x - 0x%x (%d) -> [%s]" % (self.start_addr, self.end_addr, len(self.instructions), ", ".join(["0x%x" % ref for ...
class Basicblock(object): def __init__(self): self.start_addr = 0 self.end_addr = 0 self.instructions = [] self.successors = [] def __str__(self): return '0x%x - 0x%x (%d) -> [%s]' % (self.start_addr, self.end_addr, len(self.instructions), ', '.join(['0x%x' % ref for re...
events = input().split("|") energy = 100 coins = 100 is_bankrupt = False for event in events: args = event.split("-") name = args[0] value = int(args[1]) if name == "rest": gained_energy = 0 if energy + value < 100: gained_energy = value energy += value ...
events = input().split('|') energy = 100 coins = 100 is_bankrupt = False for event in events: args = event.split('-') name = args[0] value = int(args[1]) if name == 'rest': gained_energy = 0 if energy + value < 100: gained_energy = value energy += value el...
to_name = { "TA": "TA", "D": "dependent", "TC": "tile coding", "RB": "random binary", "R": "random real-valued", "P": "polynomial", "F": "fourier", "RC": "state aggregation", }
to_name = {'TA': 'TA', 'D': 'dependent', 'TC': 'tile coding', 'RB': 'random binary', 'R': 'random real-valued', 'P': 'polynomial', 'F': 'fourier', 'RC': 'state aggregation'}
# https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/ # split a array into 3 equal subarray def canThreePartsEqualSum(self, A): """ :type A: List[int] :rtype: bool """ s= sum(A) if s%3!=0: return False each_sum = s/3 ...
def can_three_parts_equal_sum(self, A): """ :type A: List[int] :rtype: bool """ s = sum(A) if s % 3 != 0: return False each_sum = s / 3 result = [2 * each_sum, each_sum] temp = 0 for val in A: if not result: return True else: ...
# -*- coding:utf-8 -*- class Solution: def IsPopOrder(self, pushV, popV): # write code here imi = [pushV.pop(0)] while imi: cur = popV.pop(0) while imi[-1] != cur: if not pushV: return False imi.append(pushV.pop(0)) imi.pop(...
class Solution: def is_pop_order(self, pushV, popV): imi = [pushV.pop(0)] while imi: cur = popV.pop(0) while imi[-1] != cur: if not pushV: return False imi.append(pushV.pop(0)) imi.pop() return True s = ...
colors_file = None try: colors_file = open("colors2.txt", "r") for color in colors_file: print(color.rstrip()) except IOError as exc: print(exc) finally: if colors_file: colors_file.close() # print(dir(colors_file))
colors_file = None try: colors_file = open('colors2.txt', 'r') for color in colors_file: print(color.rstrip()) except IOError as exc: print(exc) finally: if colors_file: colors_file.close()
''' import html2text html = input('') text = html2text.html2text(html) print(text) input() ''' teste = input("Digite:") if teste == "1": print("1") elif teste == "2": print("2") else: print("3")
""" import html2text html = input('') text = html2text.html2text(html) print(text) input() """ teste = input('Digite:') if teste == '1': print('1') elif teste == '2': print('2') else: print('3')
d = {'name':'mari','age':19,'gender':'feminine'} del d['age'] print(d.values()) # .keys() # .items() for k,v in d.items(): print(f'[{k}]:[{v}]') print(d) e = {} br = [] for c in range(0,2): e['uf'] = str(input('estado: ')) e['cidade'] = str(input('cidade: ')) br.append(e.copy()) print(br)
d = {'name': 'mari', 'age': 19, 'gender': 'feminine'} del d['age'] print(d.values()) for (k, v) in d.items(): print(f'[{k}]:[{v}]') print(d) e = {} br = [] for c in range(0, 2): e['uf'] = str(input('estado: ')) e['cidade'] = str(input('cidade: ')) br.append(e.copy()) print(br)
class MultiplesOf3And5: def execute(self, top): result = 0 for multiple in [3, 5]: result += sum(self.get_multiples(multiple, top)) return result def get_multiples(self, multiple, top): value = 0 while value < top: yield value ...
class Multiplesof3And5: def execute(self, top): result = 0 for multiple in [3, 5]: result += sum(self.get_multiples(multiple, top)) return result def get_multiples(self, multiple, top): value = 0 while value < top: yield value value +...
# # PROBLEM INTERPRETATION | MY INTERPRETATION # | # West | West # _______ | ...
def resize(list_, radius, default): for _ in range((size(radius) - len(list_)) // 2): list_.append(safe_copy(default)) list_.insert(0, safe_copy(default)) def safe_copy(element): try: return element.copy() except AttributeError: return element def size(radius): return 2...
# Why does this file exist, and why not put this in `__main__`? # # You might be tempted to import things from __main__ later, # but that will cause problems: the code will get executed twice: # # - When you run `python -m poetry_issue_2369` python will execute # `__main__.py` as a script. That means there won't be a...
def main(args=None): return 1
class YRangeConfigurator: """ """ def __init__(self, config): """ :param config: The config parameter is a dictionary containing all of the Dataspot basic configurations. An example of the basic structure can be found in examples/dataspot_config_example.json ...
class Yrangeconfigurator: """ """ def __init__(self, config): """ :param config: The config parameter is a dictionary containing all of the Dataspot basic configurations. An example of the basic structure can be found in examples/dataspot_config_example.json ...
{ "task": "tabular", "core": { "data": { "bs": 64, #Default "val_bs": null, #Default "device": null, #Default "no_check": false, #Default "num_workers": 16, "validation": { "method": "none", # [spl...
{'task': 'tabular', 'core': {'data': {'bs': 64, 'val_bs': null, 'device': null, 'no_check': false, 'num_workers': 16, 'validation': {'method': 'none', 'rand_pct': {'valid_pct': 0.2, 'seed': null}, 'idx': {'csv_name': null, 'valid_idx': 20}, 'subsets': {'train_size': 0.08, 'valid_size': 0.2, 'seed': null}, 'files': {'va...
__author__ = 'saeedamen' # Saeed Amen / saeed@thalesians.com # # Copyright 2015 Thalesians Ltd. - http//www.thalesians.com / @thalesians # # 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://...
__author__ = 'saeedamen' '\nTechParams\n\nHolds parameters for calculation of technical indicators\n\n' class Techparams: pass
def find_best_step(v): """ Returns best solution for given value :param v: value :return: best solution or None when no any solutions available """ s = bin(v)[2:] r = s.find("0") l = len(s) - r if (r == -1) or ((l - 1) < 0): return None return 1 << (l - 1) def play_ga...
def find_best_step(v): """ Returns best solution for given value :param v: value :return: best solution or None when no any solutions available """ s = bin(v)[2:] r = s.find('0') l = len(s) - r if r == -1 or l - 1 < 0: return None return 1 << l - 1 def play_game_bool(tas...
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: seen = {} for i in nums: if i in seen: return True seen[i] = 1 return False
class Solution: def contains_duplicate(self, nums: List[int]) -> bool: seen = {} for i in nums: if i in seen: return True seen[i] = 1 return False
class Node(object): def __init__(self, val=None): self.val = val self.next = None class SinglyLinkedList(object): def __init__(self): self.head = None def traverse_list(self): """.""" root = self.head while root is not None: print(root.val)...
class Node(object): def __init__(self, val=None): self.val = val self.next = None class Singlylinkedlist(object): def __init__(self): self.head = None def traverse_list(self): """.""" root = self.head while root is not None: print(root.val) ...
d = {"a": 1, "b": 2, "c": 3} sum=0 for i in d: sum+=d.get(i) print(sum)
d = {'a': 1, 'b': 2, 'c': 3} sum = 0 for i in d: sum += d.get(i) print(sum)
def triple_sum(nums): result = [] for i in nums: for j in nums: for k in nums: j_is_unique = j != i and j != k k_is_unique = k != i sum_is_zero = (i + j + k) == 0 if j_is_unique and k_is_unique and sum_is_zero: ...
def triple_sum(nums): result = [] for i in nums: for j in nums: for k in nums: j_is_unique = j != i and j != k k_is_unique = k != i sum_is_zero = i + j + k == 0 if j_is_unique and k_is_unique and sum_is_zero: ...
class Solution: def tribonacci(self, n: int) -> int: # fib = [0]*41 # fib[0] = 0 # fib[1] = 1 # fib [2] = 1 # for i in range(n+1): # fib[i+3] = fib[i] + fib[i+1] + fib[i+2] # return fib[n] dp ...
class Solution: def tribonacci(self, n: int) -> int: dp = [0, 1, 1] for i in range(3, n + 1): dp[i % 3] = sum(dp) return dp[n % 3] '\n def tribonacci(self, n):\n a, b, c = 0, 1, 1\n for _ in range(n): a, b, c = b, c, a + b + c\n return c\n \nint trib...
s=str(input()) n1,n2=[int(e) for e in input().split()] j=0 for i in range(len(s)): if j<n1-1: print(s[j],end="") j+=1 elif j>=n1-1: j=n2 if j>=n1: print(s[j],end="") j-=1 elif j<=k: print(s[j],end="") j+=1 k=n2-1
s = str(input()) (n1, n2) = [int(e) for e in input().split()] j = 0 for i in range(len(s)): if j < n1 - 1: print(s[j], end='') j += 1 elif j >= n1 - 1: j = n2 if j >= n1: print(s[j], end='') j -= 1 elif j <= k: print(s[j], end='') ...
def mapDict(d, mapF): result = {} for key in d: mapped = mapF(key, d[key]) if mapped != None: result[key] = mapped return result withPath = mapDict(houseClosestObj, lambda house, obj: { "target": obj, "path": houseObjPaths[house][obj]}) with open("houseClose...
def map_dict(d, mapF): result = {} for key in d: mapped = map_f(key, d[key]) if mapped != None: result[key] = mapped return result with_path = map_dict(houseClosestObj, lambda house, obj: {'target': obj, 'path': houseObjPaths[house][obj]}) with open('houseClosestObj.json', 'w') a...
# rounds a number to the nearest even number # Author: Isabella Doyle num = float(input("Enter a number: ")) round = round(num) print('{} rounded is {}'.format(num, round))
num = float(input('Enter a number: ')) round = round(num) print('{} rounded is {}'.format(num, round))
def main(): print('This is printed from testfile.py') if __name__=='__main__': main()
def main(): print('This is printed from testfile.py') if __name__ == '__main__': main()
"""Lexicon exceptions module""" class ProviderNotAvailableError(Exception): """ Custom exception to raise when a provider is not available, typically because some optional dependencies are missing """
"""Lexicon exceptions module""" class Providernotavailableerror(Exception): """ Custom exception to raise when a provider is not available, typically because some optional dependencies are missing """
def _get_main(ctx): if ctx.file.main: return ctx.file.main.path main = ctx.label.name + ".py" for src in ctx.files.srcs: if src.basename == main: return src.path fail( "corresponding default '{}' does not appear in srcs. ".format(main) + "Add it or override de...
def _get_main(ctx): if ctx.file.main: return ctx.file.main.path main = ctx.label.name + '.py' for src in ctx.files.srcs: if src.basename == main: return src.path fail("corresponding default '{}' does not appear in srcs. ".format(main) + "Add it or override default file name w...
#---------------------------------------------------------------------------------------------------------- # # AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX # # NAME: Copy Hue/Sat # #---------------------------------------------------------------------------------------------------------- ns = nuke.selectedNode...
ns = nuke.selectedNodes() for n in ns: n.knob('hue').setValue(1) n.knob('sat').setValue(1) n.knob('lumaMix').setValue(0)
loader=""" d = dict(locals(), **globals()) exec(self.payload, d, d) """
loader = '\nd = dict(locals(), **globals())\nexec(self.payload, d, d)\n'
#!/usr/bin/env python temp = 24 Farenheint = temp * 1.8 + 32 print(Farenheint)
temp = 24 farenheint = temp * 1.8 + 32 print(Farenheint)
# Copyright 2013 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. class ProjectConfig(object): """Contains information about the benchmark runtime environment. Attributes: top_level_dir: A dir that contains benchm...
class Projectconfig(object): """Contains information about the benchmark runtime environment. Attributes: top_level_dir: A dir that contains benchmark, page test, and/or story set dirs and associated artifacts. benchmark_dirs: A list of dirs containing benchmarks. benchmark_aliases: A dict of...
expected_output = { 'id':{ 101: { 'connection': 0, 'name': 'grpc-tcp', 'state': 'Resolving', 'explanation': 'Resolution request in progress' } } }
expected_output = {'id': {101: {'connection': 0, 'name': 'grpc-tcp', 'state': 'Resolving', 'explanation': 'Resolution request in progress'}}}
dolares = input('Cuantos dolares tienes?: ') dolares = float(dolares) valor_dolar = 0.045 peso = dolares / valor_dolar peso = round(peso,2) peso = str(peso) print('Tienes $' + peso + ' Pesos')
dolares = input('Cuantos dolares tienes?: ') dolares = float(dolares) valor_dolar = 0.045 peso = dolares / valor_dolar peso = round(peso, 2) peso = str(peso) print('Tienes $' + peso + ' Pesos')
class dforest(object): """union-find with union-by-rank and path compression""" def __init__(self,cap=100): """creates a disjoint forest with the given capacity""" self.__parent = [ i for i in range(cap) ] self.__rank = [ 0 for i in range(cap) ] self.__count = [ 1 for i in range(cap) ] self.__c...
class Dforest(object): """union-find with union-by-rank and path compression""" def __init__(self, cap=100): """creates a disjoint forest with the given capacity""" self.__parent = [i for i in range(cap)] self.__rank = [0 for i in range(cap)] self.__count = [1 for i in range(cap...
load(":collect_export_declaration.bzl", "collect_export_declaration") load(":collect_header_declaration.bzl", "collect_header_declaration") load(":collect_link_declaration.bzl", "collect_link_declaration") load(":collect_umbrella_dir_declaration.bzl", "collect_umbrella_dir_declaration") load(":collection_results.bzl", ...
load(':collect_export_declaration.bzl', 'collect_export_declaration') load(':collect_header_declaration.bzl', 'collect_header_declaration') load(':collect_link_declaration.bzl', 'collect_link_declaration') load(':collect_umbrella_dir_declaration.bzl', 'collect_umbrella_dir_declaration') load(':collection_results.bzl', ...
# GEPPETTO SERVLET MESSAGES class Servlet: LOAD_PROJECT_FROM_URL = 'load_project_from_url' RUN_EXPERIMENT = 'run_experiment' CLIENT_ID = 'client_id' PING = 'ping' class ServletResponse: PROJECT_LOADED = 'project_loaded' GEPPETTO_MODEL_LOADED = 'geppetto_model_loaded' EXPERIMENT_LOADED ...
class Servlet: load_project_from_url = 'load_project_from_url' run_experiment = 'run_experiment' client_id = 'client_id' ping = 'ping' class Servletresponse: project_loaded = 'project_loaded' geppetto_model_loaded = 'geppetto_model_loaded' experiment_loaded = 'experiment_loaded' error_r...
# 2. Using the dictionary created in the previous problem, allow the user to enter a dollar amount # and print out all the products whose price is less than that amount. print('To stop any phase, enter an empty product name.') product_dict = {} while True: product = input('Enter a product name to assign with a pr...
print('To stop any phase, enter an empty product name.') product_dict = {} while True: product = input('Enter a product name to assign with a price: ') if product == '': break price = input('Enter the product price: ') while price == '': print('You must enter a price for the product.') ...
reservation_day = int(input()) reservation_month = int(input()) accommodation_day = int(input()) accommodation_month = int(input()) leaving_day = int(input()) leaving_month = int(input()) discount = 0 price_per_night = 0 discount_days = accommodation_day - 10 days_staying = abs(accommodation_day - leaving_day) if r...
reservation_day = int(input()) reservation_month = int(input()) accommodation_day = int(input()) accommodation_month = int(input()) leaving_day = int(input()) leaving_month = int(input()) discount = 0 price_per_night = 0 discount_days = accommodation_day - 10 days_staying = abs(accommodation_day - leaving_day) if reser...
# wordcount.py """Contains the wc(file) function.""" def wc(file): """Return the newline, word and character number.""" file = open(file, "r") nl, w, ch = 0, 0, 0 for line in file: nl += 1 w += line.count(" ") + 1 ch += len(line) return nl, w, ch
"""Contains the wc(file) function.""" def wc(file): """Return the newline, word and character number.""" file = open(file, 'r') (nl, w, ch) = (0, 0, 0) for line in file: nl += 1 w += line.count(' ') + 1 ch += len(line) return (nl, w, ch)
s, a, A = list(input()), list('abcdefghijklmnopqrstuvwxyz'), 26 s1, s2 = s[0:len(s) // 2], s[len(s) // 2:len(s)] s1_r, s2_r = sum([a.index(i.lower()) for i in s1]), sum([a.index(i.lower()) for i in s2]) for i in range(len(s1)): s1[i] = a[(s1_r + a.index(s1[i].lower())) % A] for i in range(len(s2)): s2[i] = a[(s2...
(s, a, a) = (list(input()), list('abcdefghijklmnopqrstuvwxyz'), 26) (s1, s2) = (s[0:len(s) // 2], s[len(s) // 2:len(s)]) (s1_r, s2_r) = (sum([a.index(i.lower()) for i in s1]), sum([a.index(i.lower()) for i in s2])) for i in range(len(s1)): s1[i] = a[(s1_r + a.index(s1[i].lower())) % A] for i in range(len(s2)): ...
def test(): print('hello world') c = color(1,0.2,0.2, 1) print(c) print(c.r) print(c.g) print(c.b) print(c.a) c.a = 0.5 print(c.a) c.b += 0.1 print(c.b) d = c.darkened( 0.9 ) print(d) test()
def test(): print('hello world') c = color(1, 0.2, 0.2, 1) print(c) print(c.r) print(c.g) print(c.b) print(c.a) c.a = 0.5 print(c.a) c.b += 0.1 print(c.b) d = c.darkened(0.9) print(d) test()
out = [] digits =[ "0000001", "1001111", #1 "0010010", "0000110", #3 "1001100", "0100100", #5 "1100000", "0001111", #7 "0000000", "0001100", #9 ] for i in range(10000): s = "{:04d}".format(i) out += ["{...
out = [] digits = ['0000001', '1001111', '0010010', '0000110', '1001100', '0100100', '1100000', '0001111', '0000000', '0001100'] for i in range(10000): s = '{:04d}'.format(i) out += ['{:21d} 0 0 {} {} {} {}'.format(i, digits[int(s[0])], digits[int(s[1])], digits[int(s[2])], digits[int(s[3])])] f = open('example...
def factorial(n): """Does this function work? Hint: no.""" n_fact = n while n > 1: n -= 1 n_fact *= n return n_fact
def factorial(n): """Does this function work? Hint: no.""" n_fact = n while n > 1: n -= 1 n_fact *= n return n_fact
def isIPv4Address(inputString): # Method 1 if len(inputString.split(".")) != 4: return False for x in inputString.split("."): if not x or not x.isnumeric() or (x.isnumeric() and int(x) > 255): return False return True # # Method 2 # # Same as method 1, but with Pyt...
def is_i_pv4_address(inputString): if len(inputString.split('.')) != 4: return False for x in inputString.split('.'): if not x or not x.isnumeric() or (x.isnumeric() and int(x) > 255): return False return True input_string = '172.16.254.1' print(is_i_pv4_address(inputString)) inp...