content
stringlengths
7
1.05M
class Solution: def isRectangleOverlap(self, rec1, rec2): """ :type rec1: List[int] :type rec2: List[int] :rtype: bool """ # [x1, y1, x2, y2] return not (rec2[2] <= rec1[0] or rec1[2] <= rec2[0] or rec2[3] <= rec1[1] or rec1[3] <= rec2[1])
#!/usr/bin/env python2.7 # Copyright (c) 2014 Franco Fichtner <franco@packetwerk.com> # Copyright (c) 2014 Tobias Boertitz <tobias@packetwerk.com> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and th...
# # PySNMP MIB module HPN-ICF-LI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-LI-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:27:25 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2...
def inorder(root): res = [] if not root: return res stack = [] while root and stack: while root: stack.append(root) root = root.left root = stack.pop() res.add(root.val) root = root.right return res
class Solution: def partition(self, s: str) -> list[list[str]]: # TODO: add explanation, make clearer if len(s) == 0: return [[]] result = [] def backtrack(current: list[str], prefix: str) -> None: if len(prefix) == 0: result.append(current) ...
def geobox2rect(geobox): x, y, w, h = geobox return x - int(w / 2), y - int(h / 2), w, h def geobox2ptrect(geobox): x, y, w, h = geobox2rect(geobox) return x, y, x + w, y + h def rect2geobox(x, y, w, h): return x + int(w / 2), y + int(h / 2), w, h def ptrect2geobox(x1, y1, x2, y2...
def pythag_triple(n): for a in range(1, n // 2): b = (n**2/2 - n*a)/(n - a) if b.is_integer(): return int(a*b*(n - a - b)) return None print(pythag_triple(1000)) # Copyright Junipyr. All rights reserved. # https://github.com/Junipyr
mylitta = [1, 2, 3, 4, 5] l2 = list([1, 2, 3, 4, 5]) l3 = list("casa de papel") l4 = "alberto torres".split() l5 = "alberto torres,carolina torres,mauricio torres".split(",") cadena = " - ".join(l5) mylitta = mylitta + [12, 13] mylitta += [15, 16] mylitta.append(9) mylitta.extend([10, 11]) print(mylitta) print(...
# open the fil2.txt in read mode. causes error if no such file exists. fileptr = open("file2.txt", "r") # stores all the data of the file into the variable content content = fileptr.readlines() # prints the content of the file print(content) # closes the opened file fileptr.close()
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class TypeSqlProtectionSourceEnum(object): """Implementation of the 'Type_SqlProtectionSource' enum. Specifies the type of the managed Object in a SQL Protection Source. Examples of SQL Objects include 'kInstance' and 'kDatabase'. 'kInstance' ind...
# Advent of Code 2017 # # From https://adventofcode.com/2017/day/4 # passwords = [row.strip().split() for row in open('../inputs/Advent2017_04.txt', 'r')] print(sum(len(row) == len(set(row)) for row in passwords)) print(sum(len(row) == len(set("".join(sorted(x)) for x in row)) for row in passwords))
''' Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Clarification: Confused why the returned value is an integer...
class Goals: """Represents scenario goals Attributes: conquest (int): 1 conquest unknown1 (int): unknown relics (int): number of relics required unknown2 (int): unknown exploration (int): map exploratino required in % all (int): all conditions mode (int)...
def findLargest(l): lo , hi = 0 , len(l) left , right = l[0] , l[-1] while(lo<hi): mid = (lo + hi)//2 if(left > l[mid]): hi = mid else: lo = mid +1 return l[lo-1]
""" http://pythontutor.ru/lessons/while/problems/seq_num_even/ Определите количество четных элементов в последовательности, завершающейся числом 0. """ count = 0 inp = int(input()) while inp != 0: if inp % 2 == 0: count += 1 inp = int(input()) print(count)
def rule(event): # Only check actions creating a new Network ACL entry if event['eventName'] != 'CreateNetworkAclEntry': return False # Check if this new NACL entry is allowing traffic from anywhere return (event['requestParameters']['cidrBlock'] == '0.0.0.0/0' and event['requestPar...
valor=int(input('Qual o valor que você quer sacar? R$')) cinquenta=valor//50 cinquentaresto=valor%50 vinte=0 dez=0 um=0 if cinquentaresto != 0: vinte=cinquentaresto//20 vinteresto=cinquentaresto%20 if vinteresto != 0: dez = vinteresto // 10 dezresto = vinteresto % 10 if dezresto != 0...
_base_ = [ './coco_data_pipeline.py' ] model = dict( type='MaskRCNN', backbone=dict( type='efficientnet_b2b', out_indices=(2, 3, 4, 5), frozen_stages=-1, pretrained=True, activation_cfg=dict(type='torch_swish'), norm_cfg=dict(type='BN', requires_grad=True)), ...
""" 编写一个程序,将两个文件合并为一个文件 """ def merge_file(file_list: list): file_format = file_list[0].split('.')[-1] # for file_ in file_list: # if file_.split('.')[-1] != file_format: # print("文件格式不一致,不进行合并") # return False file_new = open(f"../../file/new_file.{file_form...
class LayoutSettings(object): """ Provides a base class for collecting layout scheme characteristics. """ LayoutEngine=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the current table layout engine. Get: LayoutEngine(self: LayoutSettings) -> LayoutEngine """
def main() -> None: x0, y0 = map(int, input().split()) x1, y1 = map(int, input().split()) x2, y2 = map(int, input().split()) def calc(x0, y0, x1, y1, x2, y2): if y2 == y0: print(x2, y1) else: print(x2, y0) if x0 == x1: calc(x0, y0, x1, y1...
class FreqStack: def __init__(self): self.fmap = Counter() self.stack = [0] def push(self, x: int) -> None: self.fmap[x] += 1 freq = self.fmap[x] if (freq == len(self.stack)): self.stack.append([x]) else: self.stack[freq].append(x) def pop(self) -> int: ...
input_1 = int(input('Ingrese numero 1 = ')) input_2 = int(input('Ingrese numero 2 = ')) for x in range(input_1, input_2): print(x)
CERTIFICATE = { "type": "service_account", "project_id": "fir-orm-python", "private_key_id": "47246fe582a99774f4daf19fad21b97a09df8c70", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDMp79d08KEZPrn\nN0xZGULfM/eZwAJ+MytsPQhs+LVSqtx1c/oGHpQC5GiW9xwgnMpEh7xfX5NNjp6x...
MODEL_PATH = { "glove": "phrase-emb-storage/saved_models/glove/", "bert": "bert-base-uncased", "spanbert": "phrase-emb-storage/saved_models/span-bert-model/", "sentbert": "bert-base-nli-stsb-mean-tokens", "phrase-bert": "phrase-emb-storage/saved_models/phrase-bert-model/" } GLOVE_FILE_PATH = 'phra...
if __name__ == '__main__': mark = [] for _ in range(int(input())): name = input() score = float(input()) mark.append([name, score]) second_highest = sorted(set([score for name, score in mark]))[1] print('\n'.join(sorted([name for name, score in mark if score == second_highes...
""" HackerRank - Algorithms - Implementation Kangaroo """ #!/bin/python3 x1, v1, x2, v2 = input().strip().split(" ") x1, v1, x2, v2 = [int(x1), int(v1), int(x2), int(v2)] if ( v1 != v2 and (x1 - x2) % (v2 - v1) == 0 and (x1 - x2) / (v2 - v1) > 0 ): # Takes care of zero devision print("YES") else: print(...
# optimizer optimizer = dict(type='Lamb', lr=0.005, weight_decay=0.02) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='CosineAnnealing', min_lr=1.0e-6, warmup='linear', # For ImageNet-1k, 626 iters per epoch, warmup 5 epochs. warmup_iters=5 * 626, warmup_ratio...
# ATIVIDADE PRÁTICA SUPERVISIONADAS (APS) # Funções por tipos de materiais # Plasticos def MaterialEscolhidoPlastico(z): x = z if x >= -291 and x <= -150: print('', ['sacola de supermercado, saco de lixo, embalagem de leite', 'Tipo de plastico: PEBD (Polietileno de Baixa Densidade)', ' Ponto d...
""" This module provides functionality to work with images """ def overlay(background_image, foreground_image, x_offset, y_offset): """ Overlays a png image on another image. :param background_image: OpenCv image to be overlaid with foreground image :param foreground_image: OpenCv image to overlay ...
{ "targets": [ { "target_name": "ultradb", "sources": [ "src/ultradb.cc" ], "conditions": [ ["OS==\"linux\"", { "cflags_cc": [ "-fpermissive", "-Os" ] }] ] } ] }
VBA = \ r""" Function Base64ToStream(b) Dim enc, length, ba, transform, ms Set enc = CreateObject("System.Text.ASCIIEncoding") length = enc.GetByteCount_2(b) Set transform = CreateObject("System.Security.Cryptography.FromBase64Transform") Set ms = CreateObject("System.IO.MemoryStream") ms.Write transf...
class Solution: def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ s=s.strip() if len(s)==0: return 0 return len((s.split(" "))[-1])
""" http://www.yy.com/more/page.action?biz=chicken&subBiz=cjzc&page=2&moduleId=1776&pageSize=60 主播列表 ['data']-['data']-item-['desc'] 简介 ['data']-['data']-item-['id'] 用户id ['data']-['data']-item-['sid'] 直播间id ['data']-['data']-item-['ssid'] 直播间id ['data']-['data']-item-['name'] 昵称 ['data']-['data'...
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2010 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # Copyright 2011 Justin Santa Barbara # All Rights Reserved. # Copyright (c) 2010 Citrix Systems, Inc. # # Licensed under the Apache Licen...
DEBUG = False SQLALCHEMY_DATABASE_URI = 'postgresql:///logging' PORT = 5555 SERVER = 'production' #SSL_KEY = "/path/to/keyfile.key" #SSL_CRT = "/path/to/certfile.crt"
# Event: LCCS Python Fundamental Skills Workshop # Date: Dec 2018 # Author: Joe English, PDST # eMail: computerscience@pdst.ie # Breakout 6.4 Check digits # Solution to Exercise 1 - extract the ith digit from n # A function to extract digit i from number n def extractDigit(i, n): i = len(n) - i if i ...
##### Used Commands ##### # shutdown # rename 652530420524777493 # Militär Staubsauger#0668
st=input() k=list(st) print(k) def equal(s): n=len(s) sh=0 tr=0 for i in s: if(i=='s'): sh+=1 if(i=='t'): tr+=1 if(sh==tr): return 1 else: return 0 def equal_s_t(st): maxi=0 n=len(st) for i in range(n): for j in range(i,n): if(equal(st[i:j+1])...
""" .. module: onacol.base :synopsis: Basic utilities and exception classes. .. moduleauthor:: Josef Nevrly <josef.nevrly@gmail.com> """ class OnacolException(Exception): pass
def linha(): print() print('=' * 80) print() linha() num = 0 soma = 0 cont = 0 while not num == 999: num = int(input('Valor: ')) if num != 999: soma += num cont += 1 print() print(f'Valores digitados: {cont}') print(f'Soma dos valores: {soma}') linha()
CDNX_POS_PERMISSIONS = { 'operator': [ 'list_subcategory', 'list_productfinal', 'list_productfinaloption', ], }
#!/usr/bin/env python3 # MIT License # # Copyright (c) 2020 FABRIC Testbed # # 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 limitation the rights # to ...
#!/usr/bin/python3 def multiple_returns(sentence): if len(sentence) == 0: return (0, None) return (len(sentence), sentence[0])
#Instructions #Create an empty list named misspelled_words. #Write a for loop that: #iterates over tokenized_story, #uses an if statement that returns True if the current token is not in tokenized_vocabulary and if so, appends the current token to misspelled_words. #Print misspelled_words. #In this code, we're going t...
# slicing # my_list[start_index:end_index] # my_list[:] # This would be all of the items in my_list # my_list[:5] # This would be the items from index 0 to 4 # my_list[5:] # This would be the items from index 5 to the end of the list # guided """ Given an array of integers `nums`, define a function that returns the...
def escreva(texto): print('~' * (len(texto) + 4)) print(f' {texto}') print('~' * (len(texto) + 4)) # Programa Principal text = str(input('Digite: ')) escreva(text) escreva('Gustavo Guanabara') escreva('Curso de Python no Youtube') escreva('CeV')
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/shams3049/catkin_ws/install/include;/usr/local/cuda-9.0/include".split(';') if "/home/shams3049/catkin_ws/install/include;/usr/local/cuda-9.0/include" != "" else [] PROJECT_CATKIN_DEPENDS = "".re...
""" from https://github.com/keithito/tacotron """ ''' Defines the set of symbols used in text input to the model. ''' _pad = '_' _punctuation = ';:,.!?¡¿—…"«»“” ' _letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' _letters_ipa = "ɑɐɒæɓʙβɔɕçɗɖðʤəɘɚɛɜɝɞɟʄɡɠɢʛɦɧħɥʜɨɪʝɭɬɫɮʟɱɯɰŋɳɲɴøɵɸθœɶʘɹɺɾɻʀʁɽʂʃʈʧʉʊ...
def normalize( self, values, ): """Normalizes axis values Parameters ---------- self: Norm_ref a Norm_ref object values: ndarray axis values Returns ------- Vector of axis values """ return values / self.ref
PY_WRAPPER = """ import dash import dash_bootstrap_components as dbc app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP]) {snippet} app.layout = html.Div([{components}]) """ R_WRAPPER = """ library(dash) library(dashBootstrapComponents) library(dashHtmlComponents) app <- Dash$new(external_stylesheets = dbc...
""" 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 """ n= int(input()) for i in range(n): for j in range(0,n-i): print(" ",end=' ') for j in range(i+1): if j<i: print(i+1,end=" ") else: print(i+1,end="") if i<n: print() ...
''' .remove(x) This operation removes element from the set. If element does not exist, it raises a KeyError. The .remove(x) operation returns None. Example >>> s = set([1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> s.remove(5) >>> print s set([1, 2, 3, 4, 6, 7, 8, 9]) >>> print s.remove(4) None >>> print s set([1, 2, 3, 6, 7, 8...
ERR_SUCCESSFUL = 0 ERR_AUTHENTICATION_FAILED = 1 ERR_DUPLICATE_MODEL = 2 ERR_DOT_NOT_EXIST = 3 ERR_PERMISSION_DENIED = 4 ERR_INVALID_CREDENTIALS = 5 ERR_AUTHENTICATION_FAILED = 6 ERR_USER_IS_INACTIVE = 7 ERR_NOT_AUTHENTICATED = 8 ERR_INPUT_VALIDATION = 9 ERR_PARSE = 10 ERR_UNSUPPORTED_MEDIA = 11 ERR_METHOD_NOT_ALLOWED ...
if __name__ == '__main__': text = input('Write text: ') text = text.lower() res_text = '' for ind, ch in enumerate(text): if (ch == 'o' and ind % 2 == 0) or (ch == 'о' and ind % 2 == 0): continue else: res_text = res_text + ch print(f'Reformed text: {res_tex...
# setting.py ''' 此文件用来做车库管理系统中客户端的配置文件 包含客户端监听端口号等常规参数 ''' PORT = 8888 HOST = '127.0.0.1' ADDR = (HOST,PORT)
class CompteBancaire(): """ Gestion des Banques """ def __init__(self, nom = 'Dupont', solde = 1000 ): """ constructeur """ self.nom = nom self.solde = solde def depot(self, somme): """ ajouter somme au solde """ self...
# Bottom-Up Dynamic Programming (Tabulation) class Solution: def minCostClimbingStairs(self, cost: list[int]) -> int: # The array's length should be 1 longer than the length of cost # This is because we can treat the "top floor" as a step to reach minimum_cost = [0] * (len(cost) + 1) ...
nterms = int(input()) n1=0 n2=1 count=0 if nterms <= 0: print("please enter a positive integer") elif nterms==1: print("Fibonacci sequence upto",nterms,":") print(n1) else: print("Fibonacci sequence:") while count < nterms: print(n1) nth=n1+n2 n1=n2 n2=nth co...
class Solution: def maxProfit(self, k, prices): """ :type k: int :type prices: List[int] :rtype: int """ n = len(prices) if n == 0: return 0 if k >= n // 2: return sum(max(0, prices[i + 1] - prices[i]) for i in range(n - 1)) ...
def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Parcel lifted index (to 500 hPa)', 'units': 'K'}, {'abbr': 1, 'code': 1, 'title': 'Best lifted index (to 500 hPa)', 'units': 'K'}, {'abbr': 2, 'code': 2, 'title...
# channel.py # ~~~~~~~~~ # This module implements the Channel class. # :authors: Justin Karneges, Konstantin Bokarius. # :copyright: (c) 2015 by Fanout, Inc. # :license: MIT, see LICENSE for more details. # The Channel class is used to represent a channel in a GRIP proxy and # tracks the previous ID ...
def main(): st = input("") print(min(st)) main()
def sum_of_digits(digits) -> str: if not str(digits).isdecimal(): return '' else: return f'{" + ".join([i for i in str(digits)])} = {sum([int(i) for i in str(digits)])}'
"""Constants for the FiveM integration.""" ATTR_PLAYERS_LIST = "players_list" ATTR_RESOURCES_LIST = "resources_list" DOMAIN = "fivem" ICON_PLAYERS_MAX = "mdi:account-multiple" ICON_PLAYERS_ONLINE = "mdi:account-multiple" ICON_RESOURCES = "mdi:playlist-check" MANUFACTURER = "Cfx.re" NAME_PLAYERS_MAX = "Players Max"...
# encoding: utf-8 # module System.Windows.Navigation calls itself Navigation # from PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 # by generator 1.145 """ NamespaceTracker represent a CLS namespace. """ # no imports # no functions # classes class BaseUriHelper(object): ...
str = 'Hello World!' print(str) # Prints complete string print(str[0]) # Prints first character of the string print(str[2:5]) # Prints characters starting from 3rd to 5th print(str[2:]) # Prints string starting from 3rd character print(str * 2) # Prints string two times print(str + "TEST") ...
#D&D D12 die with 12 pentagonal faces af = 7 textH = 2 textD = 0.3 faces = {"1":(0,0), "2":(60,72), "3":(60,72*2), "4":(60,72*3), "5":(60,72*4), "6":(60,0), "C":(180,0),"B":(120,72*3+36),"A":(120,72*4+36),"9":(120,36),"8":(120,72+36),"7":(120,72*2+36)} a = cq.Workplane("XY").sphere(5) for ...
load("//:compile.bzl", "ProtoCompileInfo") RustProtoLibInfo = provider(fields = { "name": "rule name", "lib": "lib.rs file", }) def _basename(f): return f.basename[:-len(f.extension) - 1] def _rust_proto_lib_impl(ctx): """Generate a lib.rs file for the crates.""" compilation = ctx.attr.compilatio...
# noinspection PyUnusedLocal # friend_name = unicode string def hello(friend_name): """ Says hello world param[0] = a String. Ignore for now. @return = a String containing a message """ return "Hello, {}!".format(friend_name)
def escape_unicode(f): # Using *args, **kwargs to accept any arguments def wrap(*args, **kwargs): x = f(*args, **kwargs) return ascii(x) # Return wrap function, which call ascii(city()) return wrap class Trace: def __init__(self): self.enabled = True def __call__(self...
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ! Please change the following two path strings to you own one ! # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ELINA_PYTHON_INTERFACE_PATH = '/home/xxxxx/pkgs/ELINA/python_interface' DEEPG_CODE_PATH = '/home/xxxxx/pkgs/deepg/code' ...
def FlagsForFile( filename ): return { 'flags': [ '-Wall', '-Wextra', '-Werror', '-std=c++11', '-x', 'c++', '-isystem', '/usr/include/c++/10', '-isystem', '/usr/include/c++/10/backward', '-isystem', '/usr/local/include', '-isystem', '/usr/include', ] }
# Resources # https://www.geeksforgeeks.org/observer-method-python-design-patterns/ # https://docs.google.com/document/d/1jyrxxQyrVxBG9S_hXYI69ytUMdxQdApyM6MO2CwvYj4/edit class Subject: """Represents what is being observed""" def __init__(self): """create an empty observer list""" self._obser...
class Solution: def rotate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: void Do not return anything, modify nums in-place instead. 1,2,3,4,5 3 3,4,5,1,2 """ move = k % len(nums) nums[:] = nums[-move:] + nums[:-move]
# 遍历列表,指的就是将列表中的所有元素取出来 # 创建列表 stus = ['孙悟空', '猪八戒', '沙和尚', '唐僧', '白骨精', '蜘蛛精'] # 遍历列表 # print(stus[0]) # print(stus[1]) # print(stus[2]) # print(stus[3]) # 通过while循环来遍历列表 # i = 0 # while i < len(stus): # print(stus[i]) # i += 1 # 通过for循环来遍历列表 # 语法: # for 变量 in 序列 : # 代码块 # for循环的...
def increaseNumberRoundness(n): gotToSignificant = False while n > 0: if n % 10 == 0 and gotToSignificant: return True elif n % 10 != 0: gotToSignificant = True n /= 10 return False
fname = input('please enter a file name: ') fhand = open('romeo.txt') new_list = list() for line in fhand: word = line.split() for element in word: if element not in new_list: new_list.append(element) new_list.sort() print(new_list)
# Copyright 2015-2018 Camptocamp SA, Damien Crier # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Colorize field in tree views", "summary": "Allows you to dynamically color fields on tree views", "category": "Hidden/Dependency", "version": "14.0.1.0.0", "depends": ["w...
# EDA: Target - Q1 print("Number of unique cities in the data set:\n", df_tar['Target City'].nunique()) print("---------------------------------------") most_frequent_cities = df_tar['Target City'].value_counts().sort_values(ascending=False)[:15] print("Most frequent cities:\n", most_frequent_cities) print("----------...
class ScreenIdError(ValueError): pass class UssdNamespaceError(RuntimeError): pass
while True: print("Menu\n1 - Adição\n2 - Subtração\n3 - Multiplicação\n4 - Divisãoo \n5 - Sair") opção = int(input("Escolha uma opção do menu: ")) if opção == 5: break elif opção >=1 and opção <5: n = int(input("Qual a tabuada para o programa operar: ")) x = 1 while x <= ...
def matchParenthesis(string): parenthesis = 0 brackets = 0 curlyBrackets = 0 for i in range(len(string)): l = string[i] if l == '(': if i > 0: if not string[i-1] == ':' and not string[i-1] == ';': parenthesis += 1 else: ...
_base_ = [ '../_base_/datasets/imagenet_bs128.py', '../_base_/schedules/imagenet_bs1024.py', '../_base_/default_runtime.py' ] model = dict( type='ImageClassifier', backbone=dict( type='ResArch', arch='IRNet-18', num_stages=4, out_indices=(1,2,3), styl...
""" docstring """ def exp_lr(optimizer, epoch, init_lr=1e-3, lr_decay_epoch=30): """ Decay learning rate as epochs progress. Parameters: ---------- optimizer: torch.optim optimizer class epoch: int init_lr: float initial learning rate lr_decay_epoch: int number of epoch...
a = 2 b = 0 try: print(a/b) except ZeroDivisionError: print('Division by zero is not allowed')
# Problem Set 2, Question 3 # These hold the values of the balance. balance = 320000 origBalance = balance # These hold the values of the annual and monthly interest rates. annualInterestRate = 0.2 monthlyInterestRate = annualInterestRate / 12 lowerBound = balance / 12 upperBound = (balance * (1 + monthlyInterestRat...
# Advent of code 2018 # Antti "Waitee" Auranen # Day 4 # Example of the datetime part of the logs: # [1518-10-12 00:15] # # Examples of the message part of the logs: # Guard #1747 begins shift # falls asleep # wakes up def main(): inputs = [] guards = [] while(True): s = input("> ") #sp...
class Solution: def validMountainArray(self, arr: List[int]) -> bool: if len(arr) < 3: return False steps = 0 # Walk upwards, counting steps until first slope down while steps + 1 < len(arr) and arr[steps] < arr[steps + 1]: steps += 1 ...
def run(proj_path, target_name, params): return { "project_name": "Sample", "build_types": ["Debug", "Release"], "archs": [ { "arch": "x86_64", "conan_arch": "x86_64", "conan_profile": "ezored_windows_app_profile", } ...
def feature_extraction(cfg,Z,N) : #function Descriptors=feature_extraction(Z,N) # #% The features are the magnitude of the Zernike moments. ...
#!/usr/bin/env python3 ''' Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words ''' def palindrome_per...
# ../../../../goal/translate.py --gcrootfinder=asmgcc --gc=semispace src8 class A: pass def foo(rec, a1, a2, a3, a4, a5, a6): if rec > 0: b = A() foo(rec-1, b, b, b, b, b, b) foo(rec-1, b, b, b, b, b, b) foo(rec-1, a6, a5, a4, a3, a2, a1) # __________ Entry point __________ ...
# by Kami Bigdely # Split temporary variable patty = 70 # [gr] pickle = 20 # [gr] tomatoes = 25 # [gr] lettuce = 15 # [gr] buns = 95 # [gr] kimchi = 30 # [gr] mayo = 5 # [gr] golden_fried_onion = 20 # [gr] ny_burger_weight = (2 * patty + 4 * pickle + 3 * tomatoes + 2 * lettuce + 2 * buns) ...
def get_nonempty_wallets_number_query(): pipeline = [ {'$match': {'balance': {'$gt': 0}} }, {'$group': { '_id': 'null', 'count': {'$sum': 1} } }, {'$project': { '_id': 0, 'count': 1 } } ] return ...
# Crie um programa que mostre na tela todos os números pares # que estão no intervalo entre 1 e 50. for c in range(0, 51): #print('{}'.format(c), end=' ') #print(n, end=' ') print(c, end=' ') print('FIM')
class ship: name = "Unknown" maelstrom_location_data = None quadrant = '' sector = '' def __init__(self, name = "Unknown", maelstrom_location_data = None): self.name = name self.maelstrom_location_data = maelstrom_location_data def getMaelstromLocationData(self): retu...
def read_data(): with open ('input.txt') as f: data = f.readlines() return [d.strip() for d in data] def write_data(data): with open('output.txt','w') as f: for d in data: f.write(str(d)+'\n') ### class Instruction(object): """docstring for Instruction""" def __init__(self, text): super(Instruction, se...
def pow(x,y): if y==0: return 1 else: temp = pow(x,int(y/2)) mult = x if y>0 else 1/x if y%2==1: return mult * temp * temp else: return temp * temp if __name__ == "__main__": x = 2 y = 5 res = pow(x,y) print(res) x = 3 y =...
def terminate(): """Terminate this script. If defined, the module's 'stop' function will be called. If this module is debugging, the debugger is stopped. The script's module and any modules imported relative to this module are removed from sys.modules and released.""" pass def autoTerminate(value): ...