content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def table_pkey(table): query = f"""SELECT KU.table_name as TABLENAME,column_name as PRIMARYKEYCOLUMN FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME AND KU.table_n...
def table_pkey(table): query = f"SELECT KU.table_name as TABLENAME,column_name as PRIMARYKEYCOLUMN FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS TC \n INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KU ON TC.CONSTRAINT_TYPE = 'PRIMARY KEY' AND TC.CONSTRAINT_NAME = KU.CONSTRAINT_NAME \n AND KU.table_n...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: __init__.py.py Author: Scott Yang(Scott) Email: yangyingfa@skybility.com Copyright: Copyright (c) 2021, Skybility Software Co.,Ltd. All rights reserved. Description: """
""" File: __init__.py.py Author: Scott Yang(Scott) Email: yangyingfa@skybility.com Copyright: Copyright (c) 2021, Skybility Software Co.,Ltd. All rights reserved. Description: """
# # Copyright 2017 Vitalii Kulanov # class ClientException(Exception): """Base Exception for Dropme client All child classes must be instantiated before raising. """ pass class ConfigNotFoundException(ClientException): """ Should be raised if configuration for dropme client is not specif...
class Clientexception(Exception): """Base Exception for Dropme client All child classes must be instantiated before raising. """ pass class Confignotfoundexception(ClientException): """ Should be raised if configuration for dropme client is not specified. """ pass class Invalidfileexc...
# Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. # The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for c...
class Solution: def trap(self, height): """ :type height: List[int] :rtype: int """ if height == []: return 0 maximum = max(height) x = height.count(maximum) - 1 index = height.index(maximum) result = 0 if index > 1: ...
class Solution: def minRemoveToMakeValid(self, s: str) -> str: if not s : return "" s = list(s) st = [] for i,n in enumerate(s): if n == "(": st.append(i) elif n == ")" : if st : st.pop()...
class Solution: def min_remove_to_make_valid(self, s: str) -> str: if not s: return '' s = list(s) st = [] for (i, n) in enumerate(s): if n == '(': st.append(i) elif n == ')': if st: st.pop() ...
#Given a sorted array and a target value, return the index if the target is found. If not, return the index #where it would be if it were inserted in order. #You may assume no duplicates in the array. class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :...
class Solution(object): def search_insert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ self._nums = nums self._target = target if len(nums) == 0: return 0 return self.findPos(0, len(nums) - 1) ...
class PoolArgs: def __init__(self, bankerBufCap, bankerMaxBufNumber, signerBufCap, signerBufMaxNumber, broadcasterBufCap, broadcasterMaxNumber, stakingBufCap, stakingMaxNumber, distributionBufCap, distributionMaxNumber, errorBufCap, errorMaxNumber): self.BankerBufCap = bankerBufCap self.BankerMaxBuf...
class Poolargs: def __init__(self, bankerBufCap, bankerMaxBufNumber, signerBufCap, signerBufMaxNumber, broadcasterBufCap, broadcasterMaxNumber, stakingBufCap, stakingMaxNumber, distributionBufCap, distributionMaxNumber, errorBufCap, errorMaxNumber): self.BankerBufCap = bankerBufCap self.BankerMaxBu...
# Signal processing SAMPLE_RATE = 16000 PREEMPHASIS_ALPHA = 0.97 FRAME_LEN = 0.025 FRAME_STEP = 0.01 NUM_FFT = 512 BUCKET_STEP = 1 MAX_SEC = 10 # Model WEIGHTS_FILE = "data/model/weights.h5" COST_METRIC = "cosine" # euclidean or cosine INPUT_SHAPE=(NUM_FFT,None,1) # IO ENROLL_LIST_FILE = "cfg/enroll_list.csv" TEST_L...
sample_rate = 16000 preemphasis_alpha = 0.97 frame_len = 0.025 frame_step = 0.01 num_fft = 512 bucket_step = 1 max_sec = 10 weights_file = 'data/model/weights.h5' cost_metric = 'cosine' input_shape = (NUM_FFT, None, 1) enroll_list_file = 'cfg/enroll_list.csv' test_list_file = 'cfg/test_list.csv' result_file = 'res/resu...
class Mac_Address_Information: par_id = '' case_id = '' evd_id = '' mac_address = '' description = '' backup_flag = '' source_location = [] def MACADDRESS(reg_system): mac_address_list = [] mac_address_count = 0 reg_key = reg_system.find_key(r"ControlSet001\Control\Class\{4d3...
class Mac_Address_Information: par_id = '' case_id = '' evd_id = '' mac_address = '' description = '' backup_flag = '' source_location = [] def macaddress(reg_system): mac_address_list = [] mac_address_count = 0 reg_key = reg_system.find_key('ControlSet001\\Control\\Class\\{4d36...
"""Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string S1 of length 26. S1 is indexed from 0 to 25. Initially, your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken t...
"""Imagine you have a special keyboard with all keys in a single row. The layout of characters on a keyboard is denoted by a string S1 of length 26. S1 is indexed from 0 to 25. Initially, your finger is at index 0. To type a character, you have to move your finger to the index of the desired character. The time taken t...
# *************************************************************************************** # *************************************************************************************** # # Name : processcore.py # Author : Paul Robson (paul@robsons.org.uk) # Date : 22nd December 2018 # Purpose : Convert vocabulary.as...
h_out = open('__words.asm', 'w') for l in [x.rstrip() for x in open('vocabulary.asm').readlines()]: hOut.write(l + '\n') if l[:2] == ';;': name = '_'.join([str(ord(x)) for x in l[2:].strip()]) hOut.write('core_{0}:\n'.format(name)) hOut.close()
""" https://www.codewars.com/kata/56269eb78ad2e4ced1000013/train/python Given an int, return the next 'integral perfect square', which is an integer n such that sqrt(n) is also an int. If the given int is not an integral perfect square, return -1. """ def find_next_square(sq: int) -> int: sqrt_of_sq = sq ** (1/2...
""" https://www.codewars.com/kata/56269eb78ad2e4ced1000013/train/python Given an int, return the next 'integral perfect square', which is an integer n such that sqrt(n) is also an int. If the given int is not an integral perfect square, return -1. """ def find_next_square(sq: int) -> int: sqrt_of_sq = sq ** (1 / ...
class Ledfade: def __init__(self, *args, **kwargs): if 'start' in kwargs: self.start = kwargs.get('start') if 'end' in kwargs: self.end = kwargs.get('end') if 'action' in kwargs: self.action = kwargs.get('action') self.transit = self.end - self.start def ledpwm(self, p): c = 0.181+(0.0482*p)+(0.00...
class Ledfade: def __init__(self, *args, **kwargs): if 'start' in kwargs: self.start = kwargs.get('start') if 'end' in kwargs: self.end = kwargs.get('end') if 'action' in kwargs: self.action = kwargs.get('action') self.transit = self.end - self.st...
"""Foreign Key Solving base class.""" class ForeignKeySolver(): def fit(self, list_of_databases): """Fit this solver. Args: list_of_databases (list): List of tuples containing ``MetaData`` instnces and table dictinaries, which contain table names as in...
"""Foreign Key Solving base class.""" class Foreignkeysolver: def fit(self, list_of_databases): """Fit this solver. Args: list_of_databases (list): List of tuples containing ``MetaData`` instnces and table dictinaries, which contain table names as input...
""" predefined params for openimu """ JSON_FILE_NAME = 'openimu.json' def get_app_names(): ''' define openimu app type ''' app_names = ['Compass', 'IMU', 'INS', 'Leveler', 'OpenIMU', 'VG', 'VG_AHRS', ...
""" predefined params for openimu """ json_file_name = 'openimu.json' def get_app_names(): """ define openimu app type """ app_names = ['Compass', 'IMU', 'INS', 'Leveler', 'OpenIMU', 'VG', 'VG_AHRS'] return app_names app_str = ['INS', 'VG', 'VG_AHRS', 'Compass', 'Leveler', 'IMU', 'OpenIMU']
def read_paragraph_element(element): """Returns text in given ParagraphElement Args: element: ParagraphElement from Google Doc """ text_run = element.get('textRun') if not text_run: return '' return text_run.get('content') def read_structural_elements(elements): """...
def read_paragraph_element(element): """Returns text in given ParagraphElement Args: element: ParagraphElement from Google Doc """ text_run = element.get('textRun') if not text_run: return '' return text_run.get('content') def read_structural_elements(elements): """...
def average_speed(s1 : float, s0 : float, t1 : float, t0 : float) -> float: """ [FUNC] average_speed: Returns the average speed. Where: Delta Space = (space1[s1] - space0[s0]) Delta Time = (time1[t1] - time0[t0]) """ return ((s1-s0)/(t1-t0)); def average_acceleration(v1 : flo...
def average_speed(s1: float, s0: float, t1: float, t0: float) -> float: """ [FUNC] average_speed: Returns the average speed. Where: Delta Space = (space1[s1] - space0[s0]) Delta Time = (time1[t1] - time0[t0]) """ return (s1 - s0) / (t1 - t0) def average_acceleration(v1: float, v...
def set_material(sg_node, sg_material_node): '''Sets the material on a scenegraph group node and sets the materialid user attribute at the same time. Arguments: sg_node (RixSGGroup) - scene graph group node to attach the material. sg_material_node (RixSGMaterial) - the scene graph material ...
def set_material(sg_node, sg_material_node): """Sets the material on a scenegraph group node and sets the materialid user attribute at the same time. Arguments: sg_node (RixSGGroup) - scene graph group node to attach the material. sg_material_node (RixSGMaterial) - the scene graph material ...
# Debug or not DEBUG = 1 # Trackbar or not CREATE_TRACKBARS = 1 # Display or not DISPLAY = 1 # Image or Video, if "Video" is given as argument, program will use cv2.VideoCapture # If "Image" argument is given the program will use cv2.imread imageType = "Video" # imageType = "Image" # Image/Video source 0 or 1...
debug = 1 create_trackbars = 1 display = 1 image_type = 'Video' image_source = 0 ip_address = '10.99.99.2' os_script = 'v4l2-ctl --device /dev/video0 -c auto_exposure=1 -c exposure_auto_priority=0 -c exposure_time_absolute=20 --set-fmt-video=width=160,height=120,pixelformat=MJPG -p 15 && v4l2-ctl -d1 --get-fmt-video' c...
#! /usr/bin/env python3 """Context files must contain a 'main' function. The return from the main function should be the resulting text""" def main(params): if hasattr(params,'time'): # 1e6 steps per ns steps = int(params.time * 1e6) else: steps = 10000 return steps
"""Context files must contain a 'main' function. The return from the main function should be the resulting text""" def main(params): if hasattr(params, 'time'): steps = int(params.time * 1000000.0) else: steps = 10000 return steps
class NamingUtils(object): """ A collection of utilities related to element naming. """ @staticmethod def CompareNames(nameA, nameB): """ CompareNames(nameA: str,nameB: str) -> int Compares two object name strings using Revit's comparison rules. nameA: The first obje...
class Namingutils(object): """ A collection of utilities related to element naming. """ @staticmethod def compare_names(nameA, nameB): """ CompareNames(nameA: str,nameB: str) -> int Compares two object name strings using Revit's comparison rules. nameA: The first object name to co...
# Description: Class Based Decorators """ ### Note * If you want to maintain some sort of state and/or just make your code more confusing, use class based decorators. """ class ClassBasedDecorator(object): def __init__(self, function_to_decorate): print("INIT ClassBasedDecorator") self.function_...
""" ### Note * If you want to maintain some sort of state and/or just make your code more confusing, use class based decorators. """ class Classbaseddecorator(object): def __init__(self, function_to_decorate): print('INIT ClassBasedDecorator') self.function_to_decorate = function_to_decorate ...
# Task 09. Hello, France def validate_price(items_and_prices): item = items_and_prices.split('->')[0] prices = float(items_and_prices.split('->')[1]) if item == 'Clothes' and prices <= 50 or \ item == 'Shoes' and prices <= 35.00 or \ item == 'Accessories' and prices <= 20.50: ...
def validate_price(items_and_prices): item = items_and_prices.split('->')[0] prices = float(items_and_prices.split('->')[1]) if item == 'Clothes' and prices <= 50 or (item == 'Shoes' and prices <= 35.0) or (item == 'Accessories' and prices <= 20.5): return True return False items_and_prices = in...
{ 'name': 'Clean Theme', 'description': 'Clean Theme', 'category': 'Theme/Services', 'summary': 'Corporate, Business, Tech, Services', 'sequence': 120, 'version': '2.0', 'author': 'Odoo S.A.', 'depends': ['theme_common', 'website_animate'], 'data': [ 'views/assets.xml', ...
{'name': 'Clean Theme', 'description': 'Clean Theme', 'category': 'Theme/Services', 'summary': 'Corporate, Business, Tech, Services', 'sequence': 120, 'version': '2.0', 'author': 'Odoo S.A.', 'depends': ['theme_common', 'website_animate'], 'data': ['views/assets.xml', 'views/image_content.xml', 'views/snippets/s_cover....
class ValidationException(Exception): pass class NeedsGridType(ValidationException): def __init__(self, ghost_zones=0, fields=None): self.ghost_zones = ghost_zones self.fields = fields def __str__(self): return f"({self.ghost_zones}, {self.fields})" class NeedsOriginalGrid(Needs...
class Validationexception(Exception): pass class Needsgridtype(ValidationException): def __init__(self, ghost_zones=0, fields=None): self.ghost_zones = ghost_zones self.fields = fields def __str__(self): return f'({self.ghost_zones}, {self.fields})' class Needsoriginalgrid(NeedsG...
#import sys #file = sys.stdin file = open( r".\data\nestedlists.txt" ) data = file.read().strip().split()[1:] records = [ [data[i], float(data[i+1])] for i in range(0, len(data), 2) ] print(records) low = min([r[1] for r in records]) dif = min([r[1] - low for r in records if r[1] != low]) print(dif) names = [ r[0] for...
file = open('.\\data\\nestedlists.txt') data = file.read().strip().split()[1:] records = [[data[i], float(data[i + 1])] for i in range(0, len(data), 2)] print(records) low = min([r[1] for r in records]) dif = min([r[1] - low for r in records if r[1] != low]) print(dif) names = [r[0] for r in records if r[1] - dif == lo...
class ApiOperations: """ Class to extract defined parts from the OpenApiSpecs definition json """ def __init__(self, resource, parts=None): """ Extract defined parts out of paths/<endpoint> (resource) in the OpenApiSpecs definition :param resource: source to be extracted from ...
class Apioperations: """ Class to extract defined parts from the OpenApiSpecs definition json """ def __init__(self, resource, parts=None): """ Extract defined parts out of paths/<endpoint> (resource) in the OpenApiSpecs definition :param resource: source to be extracted from ...
""" MIRA API config """ MODELS = [ { "endpoint_name": "mira-large", "classes": ["fox", "skunk", "empty"] }, { "endpoint_name": "mira-small", "classes": ["rodent", "empty"] } ] HEADERS = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Content-Type", "Access-Cont...
""" MIRA API config """ models = [{'endpoint_name': 'mira-large', 'classes': ['fox', 'skunk', 'empty']}, {'endpoint_name': 'mira-small', 'classes': ['rodent', 'empty']}] headers = {'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type', 'Access-Control-Allow-Methods': 'POST'}
class Int_code: def __init__(self, s, inputs): memory = {} nrs = map(int, s.split(",")) for i, x in enumerate(nrs): memory[i] = x self.memory = memory self.inputs = inputs def set(self, i, x): self.memory[i] = x def one(self, a, b, c, mod...
class Int_Code: def __init__(self, s, inputs): memory = {} nrs = map(int, s.split(',')) for (i, x) in enumerate(nrs): memory[i] = x self.memory = memory self.inputs = inputs def set(self, i, x): self.memory[i] = x def one(self, a, b, c, modes): ...
# model settings model = dict( type='ImageClassifier', backbone=dict( type='OTEMobileNetV3', mode='small', width_mult=1.0), neck=dict(type='GlobalAveragePooling'), head=dict( type='NonLinearClsHead', num_classes=1000, in_channels=576, hid_channels=...
model = dict(type='ImageClassifier', backbone=dict(type='OTEMobileNetV3', mode='small', width_mult=1.0), neck=dict(type='GlobalAveragePooling'), head=dict(type='NonLinearClsHead', num_classes=1000, in_channels=576, hid_channels=1024, act_cfg=dict(type='HSwish'), loss=dict(type='CrossEntropyLoss', loss_weight=1.0)))
class BaseNode: pass class Node(BaseNode): def __init__(self, offset, name=None, **opts): self.offset = offset self.end_offset = None self.name = name self.nodes = [] self.opts = opts def __as_dict__(self): return {"name": self.name, "nodes": [node.__as_dict...
class Basenode: pass class Node(BaseNode): def __init__(self, offset, name=None, **opts): self.offset = offset self.end_offset = None self.name = name self.nodes = [] self.opts = opts def __as_dict__(self): return {'name': self.name, 'nodes': [node.__as_dic...
def foo(): print("I'm a lovely foo()-function") print(foo) # <function foo at 0x7f9b75de3f28> print(foo.__class__) # <class 'function'> bar = foo bar() # I'm a lovely foo()-function print(bar.__name__) # foo def do_something(what): """Executes a function :param what: name of the function to be executed...
def foo(): print("I'm a lovely foo()-function") print(foo) print(foo.__class__) bar = foo bar() print(bar.__name__) def do_something(what): """Executes a function :param what: name of the function to be executed """ what() do_something(foo) def try_me(self): print('I am ' + self.name) pri...
# Copyright 2019 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable la...
"""Implementation of tvOS test rules.""" load('@build_bazel_rules_apple//apple/internal/testing:apple_test_rule_support.bzl', 'apple_test_rule_support') load('@build_bazel_rules_apple//apple/internal:apple_product_type.bzl', 'apple_product_type') load('@build_bazel_rules_apple//apple/internal:rule_factory.bzl', 'rule_f...
n, m = [int(e) for e in input().split()] mat = [] for i in range(n): j = [int(e) for e in input().split()] mat.append(j) for i in range(n): for j in range(m): if mat[i][j] == 0: if i == 0: if mat[i][j+1] == 1 and mat[i][j-1] == 1 and mat[i+1][j] == 1: ...
(n, m) = [int(e) for e in input().split()] mat = [] for i in range(n): j = [int(e) for e in input().split()] mat.append(j) for i in range(n): for j in range(m): if mat[i][j] == 0: if i == 0: if mat[i][j + 1] == 1 and mat[i][j - 1] == 1 and (mat[i + 1][j] == 1): ...
CONNECTION_STRING = '/@' CHUNK_SIZE = 100 BORDER_QTY = 5 # minimun matches per year per player for reload player ATP_URL_PREFIX = 'http://www.atpworldtour.com' DC_URL_PREFIX = 'https://www.daviscup.com' ATP_TOURNAMENT_SERIES = ('gs', '1000', 'atp', 'ch') DC_TOURNAMENT_SERIES = ('dc',) DURATION_IN_DAYS = 18 ATP_CSV_PAT...
connection_string = '/@' chunk_size = 100 border_qty = 5 atp_url_prefix = 'http://www.atpworldtour.com' dc_url_prefix = 'https://www.daviscup.com' atp_tournament_series = ('gs', '1000', 'atp', 'ch') dc_tournament_series = ('dc',) duration_in_days = 18 atp_csv_path = '' dc_csv_path = '' sleep_duration = 10 country_code_...
def digitsProduct(product): """ Given an integer product, find the smallest positive (i.e. greater than 0) integer the product of whose digits is equal to product. If there is no such integer, return -1 instead. Time Complexity: O(inf) Space Complexity: O(1) """ number = 1 ...
def digits_product(product): """ Given an integer product, find the smallest positive (i.e. greater than 0) integer the product of whose digits is equal to product. If there is no such integer, return -1 instead. Time Complexity: O(inf) Space Complexity: O(1) """ number = 1 ...
# 15. replace() -> Altera determinado valor de uma string por outro. Troca uma string por outra. texto = 'vou Treinar todo Dia Python' print(texto.replace('vou','Vamos')) print(texto.replace('Python','Algoritmos'))
texto = 'vou Treinar todo Dia Python' print(texto.replace('vou', 'Vamos')) print(texto.replace('Python', 'Algoritmos'))
""" Singly linked lists ------------------- - is a list with only 1 pointer between 2 successive nodes - It can only be traversed in a single direction: from the 1st node in the list to the last node Several problems ---------------- It requires too much manual work by the programmer It is too error-prone (this is a ...
""" Singly linked lists ------------------- - is a list with only 1 pointer between 2 successive nodes - It can only be traversed in a single direction: from the 1st node in the list to the last node Several problems ---------------- It requires too much manual work by the programmer It is too error-prone (this is a ...
class Email: def __init__(self): self.from_email = '' self.to_email = '' self.subject = '' self.contents = '' def send_mail(self): print('From: '+ self.from_email) print('To: '+ self.to_email) print('Subject: '+ self.subject) print('Contents: '+ s...
class Email: def __init__(self): self.from_email = '' self.to_email = '' self.subject = '' self.contents = '' def send_mail(self): print('From: ' + self.from_email) print('To: ' + self.to_email) print('Subject: ' + self.subject) print('Contents: ...
n, x = map(int, input().split()) ll = list(map(int, input().split())) ans = 1 d_p = 0 d_c = 0 for i in range(n): d_c = d_p + ll[i] if d_c <= x: ans += 1 d_p = d_c print(ans)
(n, x) = map(int, input().split()) ll = list(map(int, input().split())) ans = 1 d_p = 0 d_c = 0 for i in range(n): d_c = d_p + ll[i] if d_c <= x: ans += 1 d_p = d_c print(ans)
def fill_the_box(*args): height = args[0] length = args[1] width = args[2] cube_size = height * length * width for i in range(3, len(args)): if args[i] == "Finish": return f"There is free space in the box. You could put {cube_size} more cubes." if cube_size < args[i]: ...
def fill_the_box(*args): height = args[0] length = args[1] width = args[2] cube_size = height * length * width for i in range(3, len(args)): if args[i] == 'Finish': return f'There is free space in the box. You could put {cube_size} more cubes.' if cube_size < args[i]: ...
#!/usr/bin/env python3 #Antonio Karlo Mijares # return_text_value function def return_text_value(): name = 'Terry' greeting = 'Good Morning ' + name return greeting # return_number_value function def return_number_value(): num1 = 10 num2 = 5 num3 = num1 + num2 return num3 # Main program if __name__ == '__ma...
def return_text_value(): name = 'Terry' greeting = 'Good Morning ' + name return greeting def return_number_value(): num1 = 10 num2 = 5 num3 = num1 + num2 return num3 if __name__ == '__main__': print('python code') text = return_text_value() print(text) number = return_numbe...
{ "variables": { "HEROKU%": '<!(echo $HEROKU)' }, "targets": [ { "target_name": "gif2webp", "defines": [ ], "sources": [ "src/gif2webp.cpp", "src/webp/example_util.cpp", "src/web...
{'variables': {'HEROKU%': '<!(echo $HEROKU)'}, 'targets': [{'target_name': 'gif2webp', 'defines': [], 'sources': ['src/gif2webp.cpp', 'src/webp/example_util.cpp', 'src/webp/gif2webp_util.cpp', 'src/webp/gif2webpMain.cpp'], 'conditions': [['OS=="mac"', {'include_dirs': ['/usr/local/include', 'src/webp'], 'libraries': ['...
with open("day6_input.txt") as f: initial_fish = list(map(int, f.readline().strip().split(","))) fish = [0] * 9 for initial_f in initial_fish: fish[initial_f] += 1 for day in range(80): new_fish = [0] * 9 for state in range(9): if state == 0: new_fish[...
with open('day6_input.txt') as f: initial_fish = list(map(int, f.readline().strip().split(','))) fish = [0] * 9 for initial_f in initial_fish: fish[initial_f] += 1 for day in range(80): new_fish = [0] * 9 for state in range(9): if state == 0: new_fish[...
# [Root Abyss] Guardians of the World Tree MYSTERIOUS_GIRL = 1064001 # npc Id sm.removeEscapeButton() sm.lockInGameUI(True) sm.setPlayerAsSpeaker() sm.sendNext("We need to find those baddies if we want to get you out of here.") sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext("But... they all left") sm.setPlayerAsSpeake...
mysterious_girl = 1064001 sm.removeEscapeButton() sm.lockInGameUI(True) sm.setPlayerAsSpeaker() sm.sendNext('We need to find those baddies if we want to get you out of here.') sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext('But... they all left') sm.setPlayerAsSpeaker() sm.sendNext('They had to have left some clues behin...
# 11 List Comprehensions products = [ ("Product1", 15), ("Product2", 50), ("Product3", 5) ] print(products) # prices = list(map(lambda item: item[1], products)) # print(prices) prices = [item[1] for item in products] # With list comprehensions we can achive the same result with a clenaer code print(pric...
products = [('Product1', 15), ('Product2', 50), ('Product3', 5)] print(products) prices = [item[1] for item in products] print(prices) filtered_price = [item for item in products if item[1] >= 10] print(filtered_price)
class orgApiPara: setOrg_POST_request = {"host": {"type": str, "default": ''}, "port": {"type": int, "default": 636}, "cer_path": {"type": str, "default": ''}, "use_sll": {"type": bool, "default": True}, "a...
class Orgapipara: set_org_post_request = ({'host': {'type': str, 'default': ''}, 'port': {'type': int, 'default': 636}, 'cer_path': {'type': str, 'default': ''}, 'use_sll': {'type': bool, 'default': True}, 'admin': {'type': str, 'default': ''}, 'admin_pwd': {'type': str, 'default': ''}, 'admin_group': {'type': str,...
#!/usr/bin/python3 #-----------------bot session------------------- UserCancel = 'You have cancel the process.' welcomeMessage = ('User identity conformed, please input gallery urls ' + 'and use space to separate them' ) denyMessage = 'You are not the admin of this bot, conversatio...
user_cancel = 'You have cancel the process.' welcome_message = 'User identity conformed, please input gallery urls ' + 'and use space to separate them' deny_message = 'You are not the admin of this bot, conversation end.' url_comform = 'Received {0} gallery url(s). \nNow begin to download the content. ' + 'Once the dow...
(n,m) = [int(x) for x in input().split()] loop_range = n + m set_m = set() set_n = set() for _ in range(n): set_n.add(int(input())) for _ in range(m): set_m.add(int(input())) uniques = set_n.intersection(set_m) [print(x) for x in (uniques)]
(n, m) = [int(x) for x in input().split()] loop_range = n + m set_m = set() set_n = set() for _ in range(n): set_n.add(int(input())) for _ in range(m): set_m.add(int(input())) uniques = set_n.intersection(set_m) [print(x) for x in uniques]
class bcolors(): HEADER = '\033[95m' OKBLUE = '\033[94m' OK = '\033[92m' WARNING = '\033[96m' FAIL = '\033[91m' TITLE = '\033[93m' ENDC = '\033[0m'
class Bcolors: header = '\x1b[95m' okblue = '\x1b[94m' ok = '\x1b[92m' warning = '\x1b[96m' fail = '\x1b[91m' title = '\x1b[93m' endc = '\x1b[0m'
nz = 512 # noize vector size nsf = 4 # encoded voxel size, scale factor nvx = 32 # output voxel size batch_size = 64 learning_rate = 2e-4 dataset_path_i = "/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_normalized.binvox.thinned" dataset_path_o = "/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_...
nz = 512 nsf = 4 nvx = 32 batch_size = 64 learning_rate = 0.0002 dataset_path_i = '/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_normalized.binvox.thinned' dataset_path_o = '/media/wangyida/D0-P1/database/ShapeNetCore.v2/*/*/*/model_normalized.binvox' params_path = 'params/voxel_dcgan_model.ckpt'
class Fiz_contact: def __init__(self, lastname, firstname, middlename, email, telephone, password, confirmpassword): self.lastname=lastname self.firstname=firstname self.middlename=middlename self.email=email self.telephone=telephone self.password=password sel...
class Fiz_Contact: def __init__(self, lastname, firstname, middlename, email, telephone, password, confirmpassword): self.lastname = lastname self.firstname = firstname self.middlename = middlename self.email = email self.telephone = telephone self.password = passwor...
""" igen stands for "invoice generator". The project is currently inactive. """
""" igen stands for "invoice generator". The project is currently inactive. """
def main(): with open("number.txt", "r") as file: data = file.read() data = data.split("\n") x = [row.split("\t") for row in data[:5]] print(function(x)) def function(x): sum=0 for el in x[0:]: sum += int(el[0]) return sum if __name__=="__main__": main();
def main(): with open('number.txt', 'r') as file: data = file.read() data = data.split('\n') x = [row.split('\t') for row in data[:5]] print(function(x)) def function(x): sum = 0 for el in x[0:]: sum += int(el[0]) return sum if __name__ == '__main__': main()
a = input() b= input() print(ord(a) + ord(b))
a = input() b = input() print(ord(a) + ord(b))
def prastevila_do_n(n): pra = [2,3,5,7] for x in range(8,n+1): d = True for y in range(2,int(x ** 0.5) + 1): if d == False: break elif x % y == 0: d = False if d == True: pra.append(x) return pra def ...
def prastevila_do_n(n): pra = [2, 3, 5, 7] for x in range(8, n + 1): d = True for y in range(2, int(x ** 0.5) + 1): if d == False: break elif x % y == 0: d = False if d == True: pra.append(x) return pra def euler_50...
args_global = ['server_addr', 'port', 'timeout', 'verbose', 'dry_run', 'conn_retries', 'is_server', 'rpc_plugin', 'called_rpc_name', 'func', 'client'] def strip_globals(kwargs): for arg in args_global: kwargs.pop(arg, None) def remove_null(kwargs): keys = [] for key, value in kwar...
args_global = ['server_addr', 'port', 'timeout', 'verbose', 'dry_run', 'conn_retries', 'is_server', 'rpc_plugin', 'called_rpc_name', 'func', 'client'] def strip_globals(kwargs): for arg in args_global: kwargs.pop(arg, None) def remove_null(kwargs): keys = [] for (key, value) in kwargs.items(): ...
datasetFile = open("datasets/rosalind_ba1e.txt", "r") genome = datasetFile.readline().strip() otherArgs = datasetFile.readline().strip() k, L, t = map(lambda x: int(x), otherArgs.split(" ")) def findClumps(genome, k, L, t): kmerIndex = {} clumpedKmers = set() for i in range(len(genome) - k + 1): km...
dataset_file = open('datasets/rosalind_ba1e.txt', 'r') genome = datasetFile.readline().strip() other_args = datasetFile.readline().strip() (k, l, t) = map(lambda x: int(x), otherArgs.split(' ')) def find_clumps(genome, k, L, t): kmer_index = {} clumped_kmers = set() for i in range(len(genome) - k + 1): ...
class Token: def __init__(self, word, line, start, finish, category, reason=None): self.__word__ = word self.__line__ = line self.__start__ = start self.__finish__ = finish self.__category__ = category self.__reason__ = reason @property def word(self): ...
class Token: def __init__(self, word, line, start, finish, category, reason=None): self.__word__ = word self.__line__ = line self.__start__ = start self.__finish__ = finish self.__category__ = category self.__reason__ = reason @property def word(self): ...
# Node types TYPE_NODE = b'\x10' TYPE_NODE_NR = b'\x11' # Gateway types TYPE_GATEWAY = b'\x20' TYPE_GATEWAY_TIME = b'\x21' # Special types TYPE_PROVISIONING = b'\xFF'
type_node = b'\x10' type_node_nr = b'\x11' type_gateway = b' ' type_gateway_time = b'!' type_provisioning = b'\xff'
#!/usr/bin/env python # encoding: utf-8 """ merge_intervals.py Created by Shengwei on 2014-07-07. """ # https://oj.leetcode.com/problems/merge-intervals/ # tags: medium, array, interval """ Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],...
""" merge_intervals.py Created by Shengwei on 2014-07-07. """ '\nGiven a collection of intervals, merge all overlapping intervals.\n\nFor example,\nGiven [1,3],[2,6],[8,10],[15,18],\nreturn [1,6],[8,10],[15,18].\n' class Solution: def merge(self, intervals): if intervals is None or len(intervals) <= 1: ...
class Node: def __init__(self, value): self.value = value self.next = None # Have no idea how to do this # import sys # sys.path.insert(0, '../../data_structures') # import node def intersection(l1: Node, l2: Node) -> Node: l1_end, len1 = get_tail(l1) l2_end, len2 = get_tail(l2) if l...
class Node: def __init__(self, value): self.value = value self.next = None def intersection(l1: Node, l2: Node) -> Node: (l1_end, len1) = get_tail(l1) (l2_end, len2) = get_tail(l2) if l1_end != l2_end: return None if len1 > len2: l1 = move_head(l1, len1 - len2) ...
# NAVI AND MATH def power(base, exp): res = 1 while exp>0: if exp&1: res = (res*base)%1000000007 exp = exp>>1 base = (base*base)%1000000007 return res%1000000007 mod = 1000000007 for i in range(int(input().strip())): ans = "Case #" + str(i+1) + ': ' N = int(inpu...
def power(base, exp): res = 1 while exp > 0: if exp & 1: res = res * base % 1000000007 exp = exp >> 1 base = base * base % 1000000007 return res % 1000000007 mod = 1000000007 for i in range(int(input().strip())): ans = 'Case #' + str(i + 1) + ': ' n = int(input()....
class Manifest: def __init__(self, definition: dict): self._definition = definition def exists(self): return self._definition is not None and self._definition != {} def _resolve_node(self, name: str): key = next((k for k in self._definition["nodes"].keys() if name == k.split(".")[-...
class Manifest: def __init__(self, definition: dict): self._definition = definition def exists(self): return self._definition is not None and self._definition != {} def _resolve_node(self, name: str): key = next((k for k in self._definition['nodes'].keys() if name == k.split('.')[...
load(":import_external.bzl", import_external = "import_external") def dependencies(): import_external( name = "commons_fileupload_commons_fileupload", artifact = "commons-fileupload:commons-fileupload:1.4", artifact_sha256 = "a4ec02336f49253ea50405698b79232b8c5cbf02cb60df3a674d77a749a1def7"...
load(':import_external.bzl', import_external='import_external') def dependencies(): import_external(name='commons_fileupload_commons_fileupload', artifact='commons-fileupload:commons-fileupload:1.4', artifact_sha256='a4ec02336f49253ea50405698b79232b8c5cbf02cb60df3a674d77a749a1def7', srcjar_sha256='2acfe29671daf8c9...
class Node: props = () def __init__(self, **kwargs): for prop in kwargs: if prop not in self.props: raise Exception('Invalid property %r, allowed only: %s' % (prop, self.props)) self.__dict__[prop] = kwargs[prop] for prop...
class Node: props = () def __init__(self, **kwargs): for prop in kwargs: if prop not in self.props: raise exception('Invalid property %r, allowed only: %s' % (prop, self.props)) self.__dict__[prop] = kwargs[prop] for prop in self.props: if pro...
sort = lambda array: [sublist for sublist in sorted(array, key=lambda x: x[1])] if __name__ == "__main__": print(sort([ ("English", 88), ("Social", 82), ("Science", 90), ("Math", 97) ]))
sort = lambda array: [sublist for sublist in sorted(array, key=lambda x: x[1])] if __name__ == '__main__': print(sort([('English', 88), ('Social', 82), ('Science', 90), ('Math', 97)]))
class Solution: def decompressRLElist(self, nums: List[int]) -> List[int]: de = [] for i in range(0, len(nums), 2): pair = [] pair.append(nums[i]) pair.append(nums[i + 1]) arr = [nums[i + 1]] * nums[i] de += arr return de
class Solution: def decompress_rl_elist(self, nums: List[int]) -> List[int]: de = [] for i in range(0, len(nums), 2): pair = [] pair.append(nums[i]) pair.append(nums[i + 1]) arr = [nums[i + 1]] * nums[i] de += arr return de
class SubCommand: def __init__(self, command, description="", arguments=[], mutually_exclusive_arguments=[]): self._command = command self._description = description self._arguments = arguments self._mutually_exclusive_arguments = mutually_exclusive_arguments def getCommand(self)...
class Subcommand: def __init__(self, command, description='', arguments=[], mutually_exclusive_arguments=[]): self._command = command self._description = description self._arguments = arguments self._mutually_exclusive_arguments = mutually_exclusive_arguments def get_command(se...
def read_file(filepath): with open(filepath,'r') as i: inst = [int(x) for x in i.read().replace(')','-1,').replace('(','1,').strip('\n').strip(',').split(',')] return inst def calculate(inst,floor=0): for i,f in enumerate(inst): floor += f if floor < 0: break ...
def read_file(filepath): with open(filepath, 'r') as i: inst = [int(x) for x in i.read().replace(')', '-1,').replace('(', '1,').strip('\n').strip(',').split(',')] return inst def calculate(inst, floor=0): for (i, f) in enumerate(inst): floor += f if floor < 0: break ...
"""Exceptions for the Luftdaten Wrapper.""" class LuftdatenError(Exception): """General LuftdatenError exception occurred.""" pass class LuftdatenConnectionError(LuftdatenError): """When a connection error is encountered.""" pass class LuftdatenNoDataAvailable(LuftdatenError): """When no dat...
"""Exceptions for the Luftdaten Wrapper.""" class Luftdatenerror(Exception): """General LuftdatenError exception occurred.""" pass class Luftdatenconnectionerror(LuftdatenError): """When a connection error is encountered.""" pass class Luftdatennodataavailable(LuftdatenError): """When no data is ...
def test_check_left_panel(app): app.login(username="admin", password="admin") app.main_page.get_menu_items_list() app.main_page.check_all_admin_panel_items()
def test_check_left_panel(app): app.login(username='admin', password='admin') app.main_page.get_menu_items_list() app.main_page.check_all_admin_panel_items()
# # PySNMP MIB module ALVARION-SMI (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALVARION-SMI # Produced by pysmi-0.3.4 at Mon Apr 29 17:06:07 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_intersection, constraints_union, value_size_constraint) ...
_QUEUED_JOBS_KEY = 'projects:global:jobs:queued' _ARCHIVED_JOBS_KEY = 'projects:global:jobs:archived' def list_jobs(redis): return {job_id.decode() for job_id in redis.smembers(_QUEUED_JOBS_KEY)} def remove_jobs(redis, job_id_project_mapping): for job_id, project_name in job_id_project_mapping.items(): ...
_queued_jobs_key = 'projects:global:jobs:queued' _archived_jobs_key = 'projects:global:jobs:archived' def list_jobs(redis): return {job_id.decode() for job_id in redis.smembers(_QUEUED_JOBS_KEY)} def remove_jobs(redis, job_id_project_mapping): for (job_id, project_name) in job_id_project_mapping.items(): ...
#!/usr/bin/env python3 a = [] b = [] s = input() while s != "end": n = int(s) if n % 2 == 1: a.append(n) else: print(n) s = input() i = 0 while i < len(a): print(a[i]) i = i + 1
a = [] b = [] s = input() while s != 'end': n = int(s) if n % 2 == 1: a.append(n) else: print(n) s = input() i = 0 while i < len(a): print(a[i]) i = i + 1
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- """config.py: Default configuration.""" # Server: SERVER = 'wsgiref' DOMAIN = 'localhost:7099' HOST = 'localhost' PORT = 7099 # Meta: # Note on making it work in localhost: # * Open a terminal, then do: # - sudo gedit /etc/hosts # * Enter the desired localhost alias for...
"""config.py: Default configuration.""" server = 'wsgiref' domain = 'localhost:7099' host = 'localhost' port = 7099 base_uri = 'http://mydomain.tld' google_base_uri = 'http://localhost' facebook_client_id = 'NULL' facebook_client_secret = 'NULL' twitter_client_id = 'NULL' twitter_client_secret = 'NULL' google_client_id...
# Copyright 2021 The XLS Authors # # 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 writ...
"""Build rules to compile with xlscc""" load('@bazel_skylib//lib:dicts.bzl', 'dicts') load('//xls/build_rules:xls_common_rules.bzl', 'append_default_to_args', 'args_to_string', 'get_output_filename_value', 'is_args_valid') load('//xls/build_rules:xls_config_rules.bzl', 'CONFIG', 'enable_generated_file_wrapper') load('/...
class InvalidBitstringError(BaseException): pass class InvalidQuantumKeyError(BaseException): pass
class Invalidbitstringerror(BaseException): pass class Invalidquantumkeyerror(BaseException): pass
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: if len(nums) < 3: return [] ans = [] nums.sort() for i in range(0, len(nums)-2): if nums[i] > 0: break if i > 0 and nums[i-1] == nums[i]: contin...
class Solution: def three_sum(self, nums: List[int]) -> List[List[int]]: if len(nums) < 3: return [] ans = [] nums.sort() for i in range(0, len(nums) - 2): if nums[i] > 0: break if i > 0 and nums[i - 1] == nums[i]: ...
def sum_all(ls): sum = 0 if(len(ls) != 2): print("Invalid input") else: ls.sort() start = ls[0] end = ls[1] if(start == end): sum = 2 * start else: for i in range(start, end+1): sum += i ret...
def sum_all(ls): sum = 0 if len(ls) != 2: print('Invalid input') else: ls.sort() start = ls[0] end = ls[1] if start == end: sum = 2 * start else: for i in range(start, end + 1): sum += i return sum
# Primitive reimplementation of the buildflag_header scripts used in the gn build def _buildflag_header_impl(ctx): content = "// Generated by build/buildflag_header.bzl\n" content += '// From "' + ctx.attr.name + '"\n' content += "\n#ifndef %s_h\n" % ctx.attr.name content += "#define %s_h\n\n" % ctx.at...
def _buildflag_header_impl(ctx): content = '// Generated by build/buildflag_header.bzl\n' content += '// From "' + ctx.attr.name + '"\n' content += '\n#ifndef %s_h\n' % ctx.attr.name content += '#define %s_h\n\n' % ctx.attr.name content += '#include "build/buildflag.h"\n\n' for key in ctx.attr.f...
# Space: O(n) # Time: O(n) # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def convertBST(self, root): if (root is None) or (root.left is None an...
class Solution: def convert_bst(self, root): if root is None or (root.left is None and root.right is None): return root def inorder_traversal(root): if root is None: return [] res = [] left = inorder_traversal(root.left) r...
# parsetab.py # This file is automatically generated. Do not edit. # pylint: disable=W,C,R _tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'statement_listleftPLUSMINUSleftMULTIPLYDIVIDEAND ATOM BANG BOOL COLON COMMA DIVIDE ELIF ELSE END EQUAL EXIT FUN GT ID IF IMPORT LBRACE LBRACKET LPAREN LT MAC MINUS MULT...
_tabversion = '3.10' _lr_method = 'LALR' _lr_signature = 'statement_listleftPLUSMINUSleftMULTIPLYDIVIDEAND ATOM BANG BOOL COLON COMMA DIVIDE ELIF ELSE END EQUAL EXIT FUN GT ID IF IMPORT LBRACE LBRACKET LPAREN LT MAC MINUS MULTIPLY NOT NULL NUMBER OR PLACEHOLDER PLUS RBRACE RBRACKET RETURN RPAREN SEMICOLON STRING WHILEs...
#!/usr/bin/env python3 NUMBER_OF_MARKS = 5 def avg(numbers): return sum(numbers) / len(numbers) def valid_mark(mark): return 0 <= mark <= 100 def read_marks(number_of_marks): marks_read = [] for count in range(number_of_marks): while True: mark = int(input(f'Enter mark #{coun...
number_of_marks = 5 def avg(numbers): return sum(numbers) / len(numbers) def valid_mark(mark): return 0 <= mark <= 100 def read_marks(number_of_marks): marks_read = [] for count in range(number_of_marks): while True: mark = int(input(f'Enter mark #{count + 1}: ')) if ...
class Vertex: '''This class will create Vertex of Graph, include methods add neighbours(v) and rem_neighbor(v)''' def __init__(self, n): # To initiate instance Graph Vertex self.name = n self.neighbors = list() self.color = 'black' def add_neighbor(self, v): # To add...
class Vertex: """This class will create Vertex of Graph, include methods add neighbours(v) and rem_neighbor(v)""" def __init__(self, n): self.name = n self.neighbors = list() self.color = 'black' def add_neighbor(self, v): if v not in self.neighbors: self.ne...
""" https://leetcode.com/contest/weekly-contest-281/problems/count-integers-with-even-digit-sum/ Tags: Weekly-Contest_281; Brute-Force; Easy """ class Solution: def countEven(self, num: int) -> int: ans = 0 for i in range(1, num + 1): s = str(i) # Digit Sum ...
""" https://leetcode.com/contest/weekly-contest-281/problems/count-integers-with-even-digit-sum/ Tags: Weekly-Contest_281; Brute-Force; Easy """ class Solution: def count_even(self, num: int) -> int: ans = 0 for i in range(1, num + 1): s = str(i) sm = sum(map(int, ...
"""191. Number of 1 Bits https://leetcode.com/problems/number-of-1-bits/ """ class Solution: def hammingWeight(self, n: int) -> int: def low_bit(x: int) -> int: return x & -x ans = 0 while n != 0: n -= low_bit(n) ans += 1 return ans
"""191. Number of 1 Bits https://leetcode.com/problems/number-of-1-bits/ """ class Solution: def hamming_weight(self, n: int) -> int: def low_bit(x: int) -> int: return x & -x ans = 0 while n != 0: n -= low_bit(n) ans += 1 return ans
input = [1, 1, 1, 1, 1, 1, 1, 4, 1, 2, 1, 1, 4, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 3, 1, 1, 2, 1, 2, 1, 3, 3, 4, 1, 4, 1, 1, 3, 1, 1, 5, 1, 1, 1, 1, 4, 1, 1, 5, 1, 1, 1, 4, 1, 5, 1, 1, 1, 3, 1, 1, 5, 3, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 4, 1, 2, 2, 1, 1, 1, 3, 1, 2, 5, 1, 4,...
input = [1, 1, 1, 1, 1, 1, 1, 4, 1, 2, 1, 1, 4, 1, 1, 1, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 1, 1, 1, 3, 1, 1, 2, 1, 2, 1, 3, 3, 4, 1, 4, 1, 1, 3, 1, 1, 5, 1, 1, 1, 1, 4, 1, 1, 5, 1, 1, 1, 4, 1, 5, 1, 1, 1, 3, 1, 1, 5, 3, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 2, 4, 1, 1, 1, 1, 4, 1, 2, 2, 1, 1, 1, 3, 1, 2, 5, 1, 4,...
def none_check(value): if value is None: return False else: return True def is_empty(any_type_value): if any_type_value: return False else: return True
def none_check(value): if value is None: return False else: return True def is_empty(any_type_value): if any_type_value: return False else: return True
""" Copyright 2020 Vadim Kholodilo <vadimkholodilo@gmail.com>, Iulia Durova <yulianna199820@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limit...
""" Copyright 2020 Vadim Kholodilo <vadimkholodilo@gmail.com>, Iulia Durova <yulianna199820@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitat...
"""lesson6/solution_simple_functions.py Contains solutions for simple functions. """ # Exercise 1: Write a function that prints your name and try calling it. # Work in this file and not in the Python shell. Defining functions in # a Python shell is difficult. Remember to name your function something # that indicat...
"""lesson6/solution_simple_functions.py Contains solutions for simple functions. """ def print_my_name(): print('Vinay Mayar') print_my_name() def print_my_name_ten_times(): for ctr in range(10): print_my_name() print_my_name_ten_times()
# Link class class Link: ## Constructor ## def __init__(self, text = "None", url = "None", status_code = 000): # Not the keyword 'None' so it will still print something # Dictionary of URL-related content self.text = text self.url = url self.status_code = status_code # ...
class Link: def __init__(self, text='None', url='None', status_code=0): self.text = text self.url = url self.status_code = status_code def trim_inner(self, text): return ' '.join([string.strip() for string in text.split()]) def __str__(self): text = self.trim_inner...
# -*- coding: utf-8 -*- """Manages custom event formatter helpers.""" class FormattersManager(object): """Custom event formatter helpers manager.""" _custom_formatter_helpers = {} @classmethod def GetEventFormatterHelper(cls, identifier): """Retrieves a custom event formatter helper. Args: id...
"""Manages custom event formatter helpers.""" class Formattersmanager(object): """Custom event formatter helpers manager.""" _custom_formatter_helpers = {} @classmethod def get_event_formatter_helper(cls, identifier): """Retrieves a custom event formatter helper. Args: identifier (s...
template_open = '{{#ctx.payload.aggregations.result.hits.hits.0._source}}' template_close = template_open.replace('{{#','{{/') kibana_url = ( "{{ctx.metadata.kibana_url}}/app/kibana#/discover?" "_a=(columns:!(_source),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f," "index:'metr...
template_open = '{{#ctx.payload.aggregations.result.hits.hits.0._source}}' template_close = template_open.replace('{{#', '{{/') kibana_url = "{{ctx.metadata.kibana_url}}/app/kibana#/discover?_a=(columns:!(_source),filters:!(('$state':(store:appState),meta:(alias:!n,disabled:!f,index:'metricbeat-*',key:query,negate:!f,t...
c = get_config() #Export all the notebooks in the current directory to the sphinx_howto format. c.NbConvertApp.notebooks = ['*.ipynb'] c.NbConvertApp.export_format = 'latex' c.NbConvertApp.postprocessor_class = 'PDF' c.Exporter.template_file = 'custom_article.tplx'
c = get_config() c.NbConvertApp.notebooks = ['*.ipynb'] c.NbConvertApp.export_format = 'latex' c.NbConvertApp.postprocessor_class = 'PDF' c.Exporter.template_file = 'custom_article.tplx'
class Solution: def twoSum(self, nums: List[int], target: int) -> List[List[int]]: complement = {} out = [] for i,n in enumerate(nums): complement[target-n] = i for i,n in enumerate(nums): idx = complement.get(n, None) if idx != None and idx !...
class Solution: def two_sum(self, nums: List[int], target: int) -> List[List[int]]: complement = {} out = [] for (i, n) in enumerate(nums): complement[target - n] = i for (i, n) in enumerate(nums): idx = complement.get(n, None) if idx != None and ...
#To solve Rat in a maze problem using backtracking #initializing the size of the maze and soution matrix N = 4 solution_maze = [ [ 0 for j in range(N) ] for i in range(N) ] def is_safe(maze, x, y ): '''A utility function to check if x, y is valid return true if it is valid move, return false otherwise ''' i...
n = 4 solution_maze = [[0 for j in range(N)] for i in range(N)] def is_safe(maze, x, y): """A utility function to check if x, y is valid return true if it is valid move, return false otherwise """ if x >= 0 and x < N and (y >= 0) and (y < N) and (maze[x][y] == 1): return True return False de...
for i in range(2): print(i) # print 0 then 1 for i in range(4,6): print (i) # print 4 then 5 """ Explanation: If only single argument is passed to the range method, Python considers this argument as the end of the range and the default start value of range is 0. So, it will print all the numbers starting from 0 an...
for i in range(2): print(i) for i in range(4, 6): print(i) '\nExplanation:\nIf only single argument is passed to the range method, \nPython considers this argument as the end of the range and the default start value of range is 0. \nSo, it will print all the numbers starting from 0 and before the supplied argum...
# called concatenation sometimes.. str1 = 'abra, ' str2 = 'cadabra. ' str3 = 'i wanna reach out and grab ya.' combo = str1 + str1 + str2 + str3 # you probably don't remember the song. print(combo) # you can also do it this way print('I heat up', '\n', "I can't cool down", '\n', 'my life is spinning', '\n', 'round...
str1 = 'abra, ' str2 = 'cadabra. ' str3 = 'i wanna reach out and grab ya.' combo = str1 + str1 + str2 + str3 print(combo) print('I heat up', '\n', "I can't cool down", '\n', 'my life is spinning', '\n', 'round and round') print('not sure why the space for lines 2,3,4 above.', '\n', "i guess there's more to learn... :)"...
#!/usr/bin/env python3 """Initialize. Turn full names into initials. Source: https://edabit.com/challenge/ANsubgd5zPGxov3u8 """ def __initialize(name: str, period: bool=False) -> str: """Turn full name string into a initials string. Private function used by initialize. Arguments: name {[str]}...
"""Initialize. Turn full names into initials. Source: https://edabit.com/challenge/ANsubgd5zPGxov3u8 """ def __initialize(name: str, period: bool=False) -> str: """Turn full name string into a initials string. Private function used by initialize. Arguments: name {[str]} -- Full name to be initi...