content
stringlengths
7
1.05M
#!/usr/bin/env python for n in range(2, 10): print("== %d ==" % (n)) for x in range(2, n): print("x = ", x) if n % x == 0: print(n, 'equals', x, '*', n//x) break else: # loop fell through without finding a factor print(n, 'is a prime number')
# 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...
class Solution: # 注意深度和高度的区别 def XXX(self, root: TreeNode) -> bool: if self.get_height(root) == -1: return False return True def get_height(self, root): if not root: return 0 left_height = self.get_height(root.left) if left_height == -1: ...
class TvshowsData: def __init__(self): self.NetflixData=[] self.HBOData = [] self.DisneyData = [] def add_NetflixData(self,data): self.NetflixData.append(data) def get_NetflixData(self): return self.NetflixData def add_HBOData(self,data): self.H...
class ColumnAttachmentJustification(Enum,IComparable,IFormattable,IConvertible): """ Control the column extent in cases where the target is not a uniform height. enum ColumnAttachmentJustification,values: Maximum (2),Midpoint (1),Minimum (0),Tangent (3) """ def __eq__(self,*args): """ x.__eq__(y) <==>...
#!/usr/bin/env python admin_server_listen_address = os.environ['ADMIN_SERVER_LISTEN_ADDRESS'] admin_server_listen_port = os.environ['ADMIN_SERVER_LISTEN_PORT'] admin_username = os.environ['ADMIN_USERNAME'] admin_password = os.environ['ADMIN_PASSWORD'] managed_server_name = os.environ['MANAGED_SERVER_NAME'] ########...
''' 142. Linked List Cycle II https://leetcode.com/problems/linked-list-cycle-ii/ similar problem: "141. Linked List Cycle" https://leetcode.com/problems/linked-list-cycle/ Given a linked list, return the node where the cycle begins. If there is no cycle, return null. To represent a cycle in the given linked list, w...
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( arr , n ) : mpis = [ 0 ] * ( n ) for i in range ( n ) : mpis [ i ] = arr [ i ] for i in range (...
# -*- coding: utf-8 -*- """ Created on Wed Nov 24 20:14:29 2019 @author: nehap """ """ Input: 5 Output : 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 """ if __name__=="__main__": n = int(input("Input: ")) #Initial spaces k = 2*n-2 print("Output :") #Outer Loop - controlling number of row...
#!/usr/bin/python # -*- coding: utf-8 -*- CONTRASTA = [0.84, 0.37, 0, 1] # orange CONTRASTB = [0.53, 0.53, 1, 1] # lightblue CONTRASTC = [0.84, 1, 0, 1] CONTRASTA = [0, 0.7, 0.8, 1] CONTRASTB = [1, 1, 1, 0.5] def show_detail(render, edges_coordinates, fn=None): render.clear_canvas() render_circle = render...
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def mergeKLists(self, lists: 'List[ListNode]') -> 'ListNode': res = [] for l in lists: while l: res.append(l.val) ...
def find_sum(arr): ''' using divide and conquer technique to recursively find the sum of a list of numbers ''' result = 0 if len(arr) == 1 : result = arr[0] else: result = arr.pop() + find_sum(arr) return result def count_list(arr): ''' rec...
environment = 'test' preservica_base_url = 'https://test_preservica_url' input_stream_name = 'shared_services_output_test' invalid_stream_name = 'message_invalid_test' error_stream_name = 'message_error_test' adaptor_aws_region = 'eu-west-2' organisation_buckets = { '44': 's3://some_bucket', }
# EXERCÍCIO 35 # Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo. print('-=-' * 20) print('Analisador de Triângulo') print('-=-' * 20) a = float(input('Primeiro segmento: ')) b = float(input('Segundo segmento: ')) c = float(input('Terceiro segment...
# _*_ coding: utf-8 _*_ """ Created by Allen7D on 2018/11/26. """ __author__ = 'Allen7D' get_address = { "parameters": [], "security": [ { "basicAuth": [] } ], "responses": { "200": { "description": "用户地址信息", "examples": {} } } } update_address = { "parameters": [], "security": [ { "bas...
def soma_lista(x): soma = 0 for c in x: soma += c return soma print(soma_lista([1, 2, 3, 4, 5]))
with open("input.txt") as f: dat = f.readlines() dat = [line.strip() for line in dat] maxid = 0 for ele in dat: hr = 127 lr = 0 hc = 7 lc = 0 chrs = [ c for c in ele] chrsR = chrs[0:7] chrsC = chrs[7:] for c in chrsR: if(c == 'F'): hr = hr - ( hr - lr ) // 2 - 1 else: lr =...
# # PySNMP MIB module NSCPS32-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NSCPS32-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:15:28 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, 0...
def popen(command, mode='r', bufsize=-1): pass class _wrap_close: def close(self): pass
[ ## this file was manually modified by jt { 'functor' : { 'description' : ['Returns the exponent bits of the floating input as an integer value.', 'the other bits (sign and mantissa) are just masked.', '\par', 'The sign \\\...
a,b,c = [float(x) for x in input().split()] delta = ((b**2)-(4*a*c)) if a != 0 and delta > 0: sqrt_delta = (delta)**(1/2) r1 = (-b + sqrt_delta)/(2*a) r2 = (-b - sqrt_delta)/(2*a) print("R1 = {0:.5f}".format(r1)) print("R2 = {0:.5f}".format(r2)) else: print("Impossivel calcular")
'''Aprimore o defasio 0086, mostrando no final: A) A soma dos valores pares digitados. B) A soma dos valores da terceira coluna. C) O maior valor da segunda linha.''' m = [[0,0,0], [0,0,0], [0,0,0]] p = co = 0 for c in range(3): for i in range(3): m[c][i] = int(input(f'DIgie um valor para [{c},{i}]:...
def On(A, B): return ("On", A, B) def Clear(A): return ("Clear", A) def Smaller(A, B): return ("Smaller", A, B) class Towers(object): Pole1 = 'Pole1' Pole2 = 'Pole2' Pole3 = 'Pole3' POLES = ['Pole1', 'Pole2', 'Pole3'] @classmethod def On(cls, A, B): r...
class Solution: @staticmethod def naive(nums,target): dp = [0]*(target+1) dp[0]=1 for i in range(1,target+1): for n in nums: if i-n>=0: dp[i]+=dp[i-n] return dp[target]
mylist = [1,2,3] print(mylist) mylist.append(4) print(mylist) print(mylist.pop()) print(mylist) mylist.reverse() print(mylist) newlist = mylist mylist.reverse() print(newlist) print(mylist) mylist = mylist*3 print(mylist) mylist = mylist + newlist print(mylist) print(mylist[2:3]) print(mylist[4:5]) createlist = list([...
d1 = 14.85 d2 = 14.8 d3 = 14.79 d4 = 14.84 d5 = 14.81 d0 = 14.8 d_average = d0 + 1 / 5 * (d1 - d0 + d2 - d0 + d3 - d0 + d4 - d0 + d5 - d0) dispersion = 1 / (5 * (5 - 1)) * ((pow(d1 - d0, 2) + pow(d2 - d0, 2) + pow(d3 - d0, 2) + pow(d4 - d0, 2) + pow(...
class Container(object): """ Holds hashable objects. Objects may occur 0 or more times """ def __init__(self): """ Creates a new container with no objects in it. I.e., any object occurs 0 times in self. """ self.vals = {} def insert(self, e): """ assumes e is hashable ...
""" # UNIQUE PATHS II A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). Now consider if some obst...
class SimpleMean: def solution(self, value1, value2): mean = ((value1 * 3.5) + (value2 * 7.5)) / 11 return "MEDIA = " + "%.5f" % (mean)
#Basic Data Types Challenge 3: Temperature Conversion App print("Welcome to the Temperature Conversion App") #Gather user input temp_f = float(input("\nWhat is the given temperature in degrees Fahrenheit: ")) #Convert temps temp_c = (5/9)*(temp_f - 32) temp_k = temp_c + 273.15 #Round temps temp_f = round(temp_f, 4...
# compare class # print class # -*- coding:utf-8 -*- def key_func(n): return n.score class TestClass: def __init__(self, code, name, score): self.code = code self.name = name self.score = score # can be printed if define __str__ def __str__(self): return '({}, {}, ...
#!/usr/bin/python3 """ A rectangle class defination """ class Rectangle: """ A Rectangular class """ def __init__(self, width=0, height=0): """ Initialize the class""" self.width = width self.height = height @property def width(self): """ width getter method """ ...
# coding=utf8 ROOT_RULE = 'statement -> [mquery]' GRAMMAR_DICTIONARY = {} GRAMMAR_DICTIONARY["statement"] = ['(mquery ws)'] GRAMMAR_DICTIONARY["mquery"] = [ '(ws select_clause ws from_clause ws where_clause ws groupby_clause ws having_clause ws orderby_clause ws limit)', '(ws select_clause ws from_clause ws ...
""" Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. """ """ High level IB message info. """ # field types INT = 1 STR = 2 FLT = 3 # incoming msg id's class IN: ...
class SystemTopology(object): def __init__(self, topology, resolution="martini"): if resolution == "martini": lipid_indices = topology.select("all and not (name BB or (name =~ 'SC[1-9]'))") proteins_indices = topology.select("name BB or (name BB or (name =~ 'SC[1-9]'))") ...
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable ...
class ActionBatchSm(object): def __init__(self): super(ActionBatchSm, self).__init__() def deleteNetworkSmUserAccessDevice(self, networkId: str, userAccessDeviceId: str): """ **Delete a User Access Device** https://developer.cisco.com/meraki/api-v1/#!delete-network-sm-user-acc...
''' 09 - Facetting multiple regressions lmplot() allows us to facet the data across multiple rows and columns. In the previous plot, the multiple lines were difficult to read in one plot. We can try creating multiple plots by Region to see if that is a more useful visualization. Instructions - Use lmplot() to look ...
jovem = 0 adulto = 0 idoso = 0 media = 0 cont = 0 soma = 0 while True: idade = int(input('Digite a idade(0 para encerrar): ')) soma += idade cont += 1 if 0 < idade < 26: print('Jovem') jovem += 1 elif 26 <= idade < 60: print('Adulto') adulto += 1 elif idade >...
# coding: utf-8 """ Given two int values, return their sum. Unless the two values are the same, then return double their sum. sum_double(1, 2) → 3 sum_double(3, 2) → 5 sum_double(2, 2) → 8 """ def sum_double(a, b): return (a + b if a != b else (a+b) * 2)
# -*- coding: utf-8 -*- # vi: set ft=python sw=4 : """SLRD base exception classes. This module defines main types of exceptions raised in SLRD project. The base class SLRDException indicates that the exception is related to SLRD program and was a result of program-specific causes. SLRDRuntimeException is a base class...
def get_context_vars(): return {"entity_type": "user", "date": "2018-10-20", "batch_size": "daily"} def get_metadata(): return { "extractor": {"params": {"input_path": "user/p_year=2018/p_month=10/p_day=20"}, "name": "JSONExtractor"}, "transformers": [ {"params": {"exploded_elem_na...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2017-8-30 @author: generated by @lolobosse script ''' LOCALE = [ ["agora mesmo", "daqui um pouco"], ["há %s segundos", "em %s segundos"], ["há um minuto", "em um minuto"], ["há %s minutos", "em %s minutos"], ["há uma hora", "em uma hora"]...
def conv_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1): """ Utility function for computing output of convolutions takes a tuple of (h,w) and returns a tuple of (h,w) """ if type(h_w) is not tuple: h_w = (h_w, h_w) if type(kernel_size) is not tuple: kernel_size = ...
# ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ VERSION = "11.1.1" # type: str SDK_MONIKER = "search-documents/{}".format(VERSION) # type: str
class Solution: def lastStoneWeight(self, stones: List[int]) -> int: stones.sort() while len(stones) > 1: first = stones.pop() second = stones.pop() if first == second: continue else: diff = first - sec...
""" This file provides functions for converting deeprobust data to pytorch geometric data. """
def set_qmxgraph_debug(enabled): """ Enables/disables checks and other helpful debug features globally in QmxGraph. :param bool enabled: If enabled or not. """ global _QGRAPH_DEBUG _QGRAPH_DEBUG = bool(enabled) def is_qmxgraph_debug_enabled(): """ :rtype: bool :return: Are Qmx...
B = [['m', 'm', '_', '_', '_'], ['m', 'm', '_', '_', '_'], ['_', '_', 'm', '_', '_']] M = len(B); N = len(B[0]) answer = [] for row in range(M): new_row = [] for column in range(N): if B[row][column]=='m': new_row.append('m') else: mine_number=0 ...
def getPeople(): """ In practice, here I would have a reference of a collection in the database. The collection can be stored in a variable like config of the app, and later retrieved here using current_app module of Flask. Then on that collection we can perform a query. """ return 'Hello'
# DUNDER METHODS IS METHODS WITH __example___ class Number: def __init__(self, num): self.num = num def __add__(self, num2): print("lets add") return self.num + num2.num def __mul__(self, num2): print("lets multiply") return self.num * num2.num def __str__...
class RecipeScrapersExceptions(Exception): def __init__(self, message): self.message = message super().__init__(message) def __str__(self): return f"recipe-scrapers exception: {self.message}" class WebsiteNotImplementedError(RecipeScrapersExceptions): """Error when website is not ...
# -*- coding: utf-8 -*- """Functional tests using WebTest. See: http://webtest.readthedocs.org/ """ class TestHome: """Home page.""" def test_get_homepage_returns_200(self, testapp): """Get homepage successful.""" # Goes to homepage res = testapp.get('/') assert res.status_co...
def dfs(i): if visited[i]: return visited[i] = 1 for nbr in graph[i]: dfs(nbr) n,e = map(int,input().split()) graph = dict() visited = [0 for i in range(n+1)] for i in range(1,n+1): graph[i] = [] for i in range(e): u,v = map(int,input().split()) graph[u].append(v) graph[...
# # @lc app=leetcode id=88 lang=python # # [88] Merge Sorted Array # # https://leetcode.com/problems/merge-sorted-array/description/ # # algorithms # Easy (34.87%) # Total Accepted: 337K # Total Submissions: 962.2K # Testcase Example: '[1,2,3,0,0,0]\n3\n[2,5,6]\n3' # # Given two sorted integer arrays nums1 and nums...
""" A huge map of every Twitter API endpoint to a function definition in \ Twython. Parameters that need to be embedded in the URL are treated with mustaches,\ e.g: {{version}}, etc When creating new endpoint definitions, keep in mind that the name of the\ mustache will be replaced with the keyword t...
class Vote(object): def __init__(self, candidates_running, candidate_preferences): self.candidate_preferences = filter( lambda candidate: candidate in candidates_running, candidate_preferences ) self.value = 1 def is_exhausted(self): """ Returns t...
"""sci_analysis module: graph Classes: Graph - The super class all other sci_analysis graphing classes descend from. GraphHisto - Draws a histogram. GraphScatter - Draws an x-by-y scatter plot. GraphBoxplot - Draws box plots of the provided data as well as an optional probability plot. """ # TODO: Add ...
class Repeater: def __init__(self, value): self.value = value def __iter__(self): return RepeaterIterator(self) class RepeaterIterator: def __init__(self, source): self.source = source def __next__(self): return self.source.value
#### Init service_domain = data.get('service_domain') service = data.get('service') service_data_increase = data.get('service_data_increase') service_data_decrease = data.get('service_data_decrease') # fan speed data speed = data.get('fan_speed') speed_count = data.get('fan_speed_count') fan_speed_entity = hass...
class Error(Exception): """Base class for other exceptions""" def __init__(self, message): self.message = message super().__init__(self.message) def __str__(self): return self.message class ElasticSearchError(Error): """Raised when elasticsearch error"""
word = input() while word != "Stop": print(word) word = input()
# 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...
# -*- coding: utf-8 -*- ''' File name: code\number_mind\sol_185.py Author: Vaidic Joshi Date created: Oct 20, 2018 Python Version: 3.x ''' # Solution to Project Euler Problem #185 :: Number Mind # # For more information see: # https://projecteuler.net/problem=185 # Problem Statement ''' The game Nu...
# Copyright 2020 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # generates fennel_rev0 revs = [0] inas = [ ('ina3221', '0x40:0', 'ppvar_sys', 7.7, 0.020, 'rem', True), # R91200 ('ina3221', '0x40:1', ...
tx_zips = [] with open('../data/texas-zip-codes.csv', 'r') as fin: reader = fin.readlines() i = 0 for row in reader: newrow = row.split(',') state = newrow[4].strip('"') if state == 'TX': tx_zips.append(newrow[0].strip('"')) i += 1 with open('tx-zips.txt', 'w...
# Hello World program in Python print("Python Dictionaries\n") print("In Python dictionaries are written with curly brackets, and they have keys and values.\n") # Create and print a dictionary: thisdict = { "name": "Alex", "roll_number": "234566", "passing_year": 1964 } print(thisdict) # You can access t...
def convert_token(token): cursor = 0 converted_token = '' while cursor < len(token): if cursor > 0 and token[cursor].isupper() and token[cursor - 1] != '_': converted_token += '_' + token[cursor].lower() elif cursor > 0 and token[cursor - 1].isupper() and converted_token[-1].islo...
# Aula 28 - 17-12-2019 # Revisão de listas # Faça uma função que receba a lista como parametro e retorne uma # string em que cada linha seja uma pessoa. lista = [['1', 'Arnaldo', '23', 'm', 'alexcabeludo2@hotmail.com', '014908648117'], ['2', 'Haroldo', '44', 'f', 'baratarebelde@gmail.com', '050923172729'], ['3', 'Pi...
__author__ = 'fengyuyao' class Template(object): def __init__(self, source): pass def render(self, **kwargs): pass
# # PySNMP MIB module CNTAU-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CNTAU-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:09:32 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23...
class Location: __name: str = None def __init__(self, name: str) -> None: if type(name) != str: raise TypeError('name of Location must be a string') elif len(name) <= 0: raise ValueError("name of Location must be non-empty") self.__name = name @property ...
asset_permissions = {} asset_permissions["charge_market_fee"] = 0x01 asset_permissions["white_list"] = 0x02 asset_permissions["override_authority"] = 0x04 asset_permissions["transfer_restricted"] = 0x08 asset_permissions["disable_force_settle"] = 0x10 asset_permissions["global_settle"] = 0x20 asset_permissions["disable...
#!/usr/bin/env python # -*- coding: utf-8 -*- url = 'http://practiapinta.me/tepinta' sender = 'practiatepinta@practia.global' password = '' smtp = 'owa.pragmaconsultores.net' body = ''
def main(): with open('input.txt') as file: data = file.read().strip().split('\n') n = int(data[0]) symbols = data[1] number = int(data[2]) cleaned_sumbols = '' for symbol in symbols: if symbol != ' ': cleaned_sumbols += symbol outp...
test = { 'name': 'q3_3_1', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> # Fill in the row; >>> # time = ...; >>> # with something like:; >>> # time = 4.567; >>> # (except with the right number).; >>> time != .....
# File: windowsdefenderatp_consts.py # Copyright (c) 2019 Splunk Inc. # # Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) # DEFENDERATP_PHANTOM_BASE_URL = '{phantom_base_url}rest' DEFENDERATP_PHANTOM_SYS_INFO_URL = '/system_info' DEFENDERATP_PHANTOM_ASSET_INFO_URL = '/asset/{asset_id}' DEFE...
class Delete(object): def __init__(self, graphConnector, userPrincipalName='me'): """The Delete class deletes a message from a users mailbox. NOTE: Please note that this will do a soft delete and it is only recoverable via "Recoverable Items" feature on a mailbox. This a...
count=0 total=0 print('before', count,total) for numbers in [9,41,12,3,74,15]: count=count+1 total=total+numbers print (count,total,numbers) print('After', count, total, total/count)
def karatsuba_multiplication(x, y): x_digits = len(str(x)) y_digits = len(str(y)) # Base case for the recursion. if (x_digits == 1 or y_digits == 1): return x * y # Figure out where to split. n2 = max(x_digits, y_digits) / 2 factor = int(10 ** n2) # Break up the number into p...
#!/usr/bin/env python active = { 'url': 'https://<SUBDOMAIN>.carbonblack.io/api/v1/process', 'key': '<API KEY>' } # ====================================================================== # Place API key and URL in 'active' to use with the cmdline-search.py # ===================================================...
ctr = 1 while ctr != -1 : try: ctr = int(input('Enter a number ( -1 to exit) : ')) except ValueError: print("That was not a number") else: #Only executed when no exception happens print("No exception happened") finally: print("finally executed")
# # PySNMP MIB module CISCO-ATM-IF-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ATM-IF-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:33:08 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar ...
DEBUG = False LANGUAGES = (("en", "English"),) LANGUAGE_CODE = "en" USE_TZ = False USE_I18N = True SECRET_KEY = "fake-key" PASSWORD_EXPIRE_SECONDS = 10 * 60 # 10 minutes PASSWORD_EXPIRE_WARN_SECONDS = 5 * 60 # 5 minutes INSTALLED_APPS = [ "django.contrib.auth", "django.contrib.contenttypes", "django.con...
# Copyright (c) 2020 DDN. All rights reserved. # Use of this source code is governed by a MIT-style # license that can be found in the LICENSE file. """ Shell-based scheduler which records process name and user id. """ FIELDS = "name", "user" def fetch(ids): "Generate process names and user ids." for id in...
# @Title: 回文链表 (Palindrome Linked List) # @Author: 18015528893 # @Date: 2021-02-12 21:29:36 # @Runtime: 76 ms # @Memory: 24.8 MB # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def isPalindrome(s...
def test_image_name(add_product_with_image, find_product_image): print(type(find_product_image)) print(find_product_image) assert 'macbook_pro' in find_product_image
# yahoo.py # Trevor Pottinger # Fri Oct 18 22:57:23 PDT 2019 class Yahoo(object): @classmethod async def gen_s_and_p_history() -> None: url = 'https://finance.yahoo.com/quote/%5EGSPC/history?period1=1413529200&period2=1571295600&interval=1d&filter=history&frequency=1d'
# https://leetcode.com/problems/decode-string/ # Given an encoded string, return it's decoded string. # # The encoding rule is: k[encoded_string], where the encoded_string inside the square brackets is being repeated exactly k times. Note that k is guaranteed to be a positive integer. # # You may assume that the input ...
# OOBE Stages OOBE_ASK_PHONE_TYPE = 0 OOBE_DOWNLOAD_MESSAGE = 1 OOBE_WAITING_ON_PHONE_TO_ENTER_CODE = 2 OOBE_WAITING_ON_PHONE_TO_ACCEPT_PAIRING = 3 OOBE_PAIRING_SUCCESS = 4 OOBE_CHECKING_FOR_UPDATE = 5 OOBE_STARTING_UPDATE = 6 OOBE_UPDATE_COMPLETE = 7 OOBE_WAITING_ON_PHONE_TO_COMPLETE_OOBE = 8 OOBE_PRESS_ACTION_BUTTON ...
''' - Leetcode problem: 22 - Difficulty: Medium - Brief problem description: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] - Solution Summary: ...
""" Interface for swappable strategies used for dealing with transactions in QueryManager Based on the strategy pattern https://en.wikipedia.org/wiki/Strategy_patter """ class QueryManagerStrategy(object): def account_balances_for_dates(self, company_id, account_ids, dates, with_counterparties, excl_interco, excl_co...
""" Placeholders for missing VQ dependencies. """ C_INI_MEDIA_C_CODECS = None dictc01bit = {} v1_quant = None v2_quant = None v_codecs = None v_bits_sample = None def encode_vq(*args, **kwargs): return None def get_codebook_from_serial(*args, **kwargs): return None def get_vq_decoded_samples(*args, **kwargs...
class Solution: def isPerfectSquare(self, num: int) -> bool: left, right = 0, num while left <= right: mid = left + (right - left) // 2 if mid * mid == num: return True elif mid * mid > num: right = mid - 1 else: ...
# 1-2_find_num.py def solution(input_str): # - # - # - # - # - # - # - # - # - # - # - # - # - # - # # Write your code here. answer = "" for i in range(10): if str(i) in input_str: pass else: answer = str(i) break return answer # - # - # - # - # - # - # - # - # - # - # - # - # - # - # input_str1 ...
"""Library of helper classes of optimizer.""" class GradientsClipOption: """Gradients clip option for optimizer class. Attributes: clipnorm: float. If set, the gradient of each weight is individually clipped so that its norm is no higher than this value. clipvalue: float. If set, the gradient of ea...
# Total cheltuieli # De la tastatură se citește numele unui fișier. Acel fișier conține un text în care sunt specificate cheltuielile # efectuate de Ana într-o zi. Scrieți un program care să afișeze suma totală cheltuită de Ana în ziua respectivă. def isnumber(x): if x.isdecimal(): return True x = x.s...
"""Roaring Years.""" def reader(): return int(input()) def check_n(Y, n): if len(Y) == n: return True A = Y[-n:] Y = Y[:-n] if A[0] == "0": return False A = int(A) if len(str(A - 1)) != n: n -= 1 if len(Y) < n: return False B = int(Y[-n:]) if B...
class Person: def __init__(self, name, race): self.name = name self.race = race self.stamina = 100 self.agility = 100 self.strenght = 100 self.health = 100 self.intellegence = 100 self.level = 1 self.armor = 20 self.speed = 20 ...
# -*- coding: utf-8 -*- """ Created on Sun Oct 18 15:53:10 2020 Error Handling @author: Ashish """ try: number = float(input("Enter a number: ")) print("The number is: ", number) except: print("Invalid number")