content stringlengths 7 1.05M |
|---|
# libnatacalc.py
class Calculator:
def __init__(self, d, h, m, s):
self.distance = float(d)
self.hours = float(h)
self.minutes = float(m)
self.seconds = float(s)
self.kmsh = 0.0
self.t100m = 0.0
self.t1000m = 0.0
@staticmethod
def cnvt_to_seconds(h, m, s):
return s + (m * 60) + (h * 3600)
@stat... |
N = int(input())
a = []
b = []
dp = [0 for i in range(N)]
#겹치지 않는 최대 전깃줄 수 구해서 N에서 뺌(LIS문제)
for i in range(N):
a.append(list(map(int, input().split())))
a.sort(key = lambda x:x[0])
#A전봇대 기준으로 sort->b수열에서 가장 긴 증가하는 부분수열 구하면됨
for i in range(N):
b.append(a[i][1])
for i in range(N):
for j in range(i):
... |
# -*- coding: utf-8 -*-
# @Author: zengjq
# @Date: 2020-03-02 16:11:53
# @Last Modified by: zengjq
# @Last Modified time: 2020-03-02 16:23:40
class Solution:
# 结果会浮动
# Runtime: 24 ms, faster than 91.28% of Python3 online submissions for Implement strStr().
# Memory Usage: 12.8 MB, less than 100.00% of... |
names = "Julian Bob PyBites Dante Martin Rodolfo".split()
countries = "Australia Spain Global Argentina USA Mexico".split()
def enumerate_names_countries():
"""Outputs:
1. Julian Australia
2. Bob Spain
3. PyBites Global
4. Dante Argentina
5. Martin ... |
'''
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
'''
for b in range(5):
for a in range(5):
print("*",end=" ")
print()
|
# coding: utf-8
# In[18]:
# https://leetcode.com/problems/longest-substring-without-repeating-characters/description/
# Status:
# Percentile:
# Author: Shreyas Padhye
# Approach:
def lengthOfLongestSubstring(s):
"""
:type s: str
:rtype: int
"""
if len(s) == 0:
return 0
maxVal = 1... |
#!/usr/bin/env python3
terms = set()
for a in range(2, 101):
for b in range(2, 101):
terms.add(a**b)
print(len(terms))
|
marks = int(input("Input Your Marks In Programming: "))
def your_grade(grade):
print(f"You Got: {grade}")
# if marks >= 80:
# your_grade("A+")
# elif 80 >= marks >= 70:
# your_grade('A')
# elif 70 > marks >= 60:
# your_grade("A-")
# elif marks >= 33:
# your_grade('Passed')
# else:
# your_gra... |
class TrainStates:
def __init__(self):
self.EXECUTING = False
self.MOTOR_RUNNING = False
self.MOTOR_WAITING = False
self.MOTOR_SPEED = 0
self.CRANE_LOADED = False
self.CRANE_LOADING = False
self.COMMUNICATION_RUNNING = False
self.SIGNALER_RUNNIN... |
eve = lambda x: x & 1 == 0
def f(x):
division = 1
ret = 0
while division * division < x:
if x % division == 0:
if eve(division):
ret += 1
if eve(x // division):
ret += 1
division += 1
if division * division == x and eve(division):
... |
class Config:
def __init__(self):
self.db_config = 'DRIVER={FreeTDS};SERVER=SDAQWGDWM4;DATABASE=GWCC_ProdCopy;UID=ClaimAnalyticsETLUser;PWD=jU' \
'&ruwrUde4aSpAt;TDS_Version=8.0;Port=1433 '
self.input_folder = 'data/Production/Output'
self.output_folder = 'dat... |
"""
Faça uma função que receba dois números e retorne qual deles é o maior.
Doctests:
>>> maior_menor(5,3)
5
>>> maior_menor(7,9)
9
>>> maior_menor(95756,5516)
95756
>>> maior_menor(875,875)
875
"""
def maior_menor(a: int, b: int):
if a > b:
return a
else:
return b
|
"""
A simple/basic graph structure designed to help group together annuli.
:Copyright: Smithsonian Astrophysical Observatory (2018)
:Author: Douglas Burke (dburke@cfa.harvard.edu)
"""
__all__ = ("SimpleGraph", )
class SimpleGraph:
"""A graph where links are bi-directional
The identifiers must be hashable (... |
"""
Tendo como dados de entrada a altura de uma pessoa, construa um algoritmo que calcule seu peso
ideal, usando a seguinte fórmula: (72.7*altura) - 58
"""
altura = float(input("Altura: "))
x = 77.7*altura
r = x - 58
print(r)
|
abbreviations = {
'ARI':'Arizona Cardinals','ATL':'Atlanta Falcons','BAL':'Baltimore Ravens',
'BUF':'Buffalo Bills','CAR':'Carolina Panthers','CHI':'Chicago Bears',
'CIN':'Cincinnati Bengals','CLE':'Cleveland Browns','DAL':'Dallas Cowboys',
'DEN':'Denver Broncos','DET':'Detroit Lions','GB' :'Green B... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
def add_n_ext(attrs):
return {}
|
"""
In this example, we try to assign the sorted list to a variable. However, when
you call the sort() method on a list, it sorts the list in-place. So if you try
to assign the result to another variable, then you’ll find out that you’ll get a
None object, which is like a Null in other languages. Thus when you want... |
price = [10,20,30]
sum = 0
for i in price:
sum = sum + i
print(f"total price in shop is : {sum}")
|
#!/usr/bin/env python3
"""
https://www.reddit.com/r/dailyprogrammer/comments/6jr76h/20170627_challenge_321_easy_talking_clock/
Given a 5-character input of the format HH:MM, convert the 24-hour timestamp
into natural language.
"""
def timeFormatNatural(timestamp):
output = ["It's"]
# get components
milHo... |
class addTwoNum:
def __init__(self, l1, l2):
self.l1 = l1
self.l2 = l2
self.l3 = []
self.carry = 0
self.sum = 0
self.sum_list = []
def addTwoNum(self):
while self.l1 or self.l2:
if self.l1:
self.sum = self.l1.val + self.carry
... |
class Label(object):
def __init__(self):
self.label = LabelGenerator.get_next()
def __str__(self):
return self.label
def __eq__(self, other):
return self.label == other.label
class LabelGenerator(object):
_next_label = 0
@classmethod
def get_next(cls):
next_l... |
def validPalindrome(string):
left, right = 0, len(string) - 1
while left < right:
if string[left] != string[right]:
return isPalindrome(string, left + 1, right) or \
isPalindrome(string, left, right - 1)
left += 1
right -= 1
return True
def isPalindrom... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Main text area
font = "Consolas"
fontsize = 10
# Message area
messagefont = "Consolas"
messagefontsize = 9
debug = True
|
number = 23
guess = int(input('Enter an integer : '))
if guess == number:
print('Congratulations, bingo!') # New block starts here
print('(but you do not win any prizes!)') # New block ends here
elif guess < number:
print('No, it is a litter higher than that')
# you can do whatever you want in a ... |
""" 2. Crie uma classe Agenda que pode armazenar 10 pessoas e seja capas de realizar as
seguintes operações:
* void armazenaPessoa(String nome, int idade, float altura);
* void removePessoa(String nome);
* int buscaPessoa(String nome); informa em que posição da agenda está a
pessoa
* void imprimeAgenda... |
#
# PySNMP MIB module CISCOSB-TUNNEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-TUNNEL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:07:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
# If th... |
lista = ("Lápis", 1.00, "Borracha", 2.50, "Caneta BIC", 1.00, "Resma de papel", 20.00, "Elásticos", 0.50)
print("")
for g in range(0, len(lista), 2):
print(f"{lista[g]:.<40}", end=" ")
print("R$", end="")
print(f"{lista[g + 1]:>6.2f}")
|
a = input("Type something")
print("The class of what you type is", type (a) )
print("Has only spaces?", a.isspace())
print("Is it a number?", a.isnumeric())
print("Is it alphabetic?",a.isalpha()) |
# if statements
# if statements are used to test for particular conditions and respond appropriately.
# Conditional test
"""
equals: x == 42
not equals: x != 42
greater than: x > 42
greater than or equal to: x >= 42
less than: x < 42
less than or equal to: x <= 42
"""
# conditional checks in the list
bikes = ['trek... |
# -*- python -*-
#
# $Id: generators.py,v 1.1 2010-02-19 18:41:28 wirawan Exp $
#
# Created: 20100218
# Wirawan Purwanto
#
"""
Various generators
"""
def all_combinations(seq):
"""Generates stream of tuples containing all possible
combinations of items (where order matters).
This is useful e.g. for generating... |
input = """
1 2 0 0
1 3 0 0
1 4 0 0
1 5 0 0
1 6 0 0
1 7 0 0
1 8 0 0
1 9 0 0
1 10 0 0
1 11 0 0
1 12 0 0
1 13 0 0
1 14 0 0
1 15 0 0
1 16 0 0
1 17 0 0
1 18 0 0
1 19 0 0
1 20 0 0
1 21 0 0
1 22 0 0
1 23 0 0
1 24 0 0
1 25 0 0
1 26 0 0
1 27 0 0
1 28 0 0
1 29 0 0
1 30 0 0
1 31 0 0
1 32 0 0
1 33 1 1 34
1 35 1 1 36
1 37 1 0 33
1... |
# Function dependencies, for example:
# package>=version
google-cloud-bigquery
pydub
google-cloud-storage
google-cloud-speech
|
error_whitelist = ['ModuleNotFoundError: No module named']
other_error_count = 0
module_not_found_count = 0
module_not_found_list = []
num_of_notebooks = 10000
filter_out_count = 0
executable_count = 0
non_executable_count = 0
for i in range(1, num_of_notebooks+1):
file_name = str(i)+'.txt'
# Dump txt file to... |
expected_output = {
"CUST123-PIN-T5/0/0.20": {
"service_policy": {
"input": {
"policy_name": {
"CUST123-PIN-T5/0/0.20": {
"class_map": {
"class-default": {
"match_evaluation": ... |
def get_repository_id(repository_info, api_root, repository_name=None):
"""Get the repository ID from the server.
This will compare the paths returned by the SCM client
with those on the server, and return the id of the first
match.
"""
detected_paths = repository_info.path
if not isinstan... |
def pre_delete_interface(sender, instance, using, **kwargs):
instance.a_records.all().delete()
instance.aaaa_records.all().delete()
instance.cname_records.all().delete()
instance.ptr_records.all().delete()
instance.firewall_layer2.all().delete()
instance.firewall_layer3.all().delete()
instan... |
def main(tuple):
i=0
while len(tuple)>i:
if not isinstance(tuple[i], dict):
main(tuple[i])
i+=1
continue
out = None
value = None
if "in" in tuple[i]:
if "out" in tuple[i]:
out = tuple[i]["out"]
value ... |
#LAURA MAMBRILLA MORENO
#Ej 2 Cuaderno 3
"""
Escribe un subprograma que calcule el producto de dos números enteros leídos
desde el teclado sin utilizar el operador de multiplicación *. Ej: si recibe 2 y 3
devuelve 6; si recibe 2 y 0 devuelve 0; si recibe -3 y 2 dará -6. El programa no
asumirá que los números son mayor... |
# 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
#
# 设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
#
# 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution:
def maxProfit(self, prices: List[int]) -> int... |
"""An API for managing Vumi Go opt outs."""
__version__ = "0.1.2"
__all__ = []
|
"""
for future extension:
8-bit (256 colors):
fg: 38:5:<c>m
bg: 48:5:<c>m
0-7 std equiv: 30–37
8-15 std equiv: 90–97
16-213 is 6x6 cube (216 colors); 16 + 36 × r + 6 × g + b (0 ≤ r, g, b ≤ 5)
232-255 is grayscale (24 steps)
rgb ('true color'):
fg: 38;2;<r>;<g>;<b>m
bg: 48;2;<r>;<g>;<b>m
"""
COLORS = (
'black',
... |
# You are given the root node of a binary search tree(BST) and a value to insert into the tree.Return
# the root node of the BST after the insertion.It is guaranteed that the new value does not exist in the
# original BST.
# Notice that there may exist multiple valid ways
# for the insertion, as long as the tree remain... |
def part1():
positions = {int(i.split("#")[1][0]): int(i.split("position ")[1][:-1]) for i in open("input.txt").read().split("\n")[:-1]}
possiblePositions = {int(i.split("#")[1][0]): int(i.replace("positions;","has").split("has ")[1]) for i in open("input.txt").read().split("\n")}
time = 0
while True:
... |
#!/usr/bin/env python
# -*- coding: latin-1 -*-
#
def check_calls(self, calls, values):
self.assertEqual(len(calls), len(values))
r = {}
for call in calls:
name = call[0][0]
value = call[0][1]
r[name] = value
for name, value in values:
self.assertEqual(r.pop(name), va... |
# _*_ encoding: utf-8 _*_
class SQD(object):
__elements = []
__length = 0
@property
def first(self):
if not self.is_empty():
return self.elements[0]
return None
@property
def last(self):
if not self.is_empty():
return self.elements[-1]
... |
# MIT LICENSE Copyright (c) 2018 David Longnecker
# 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 use, copy, modify, merge, ... |
T = int(input())
def match(A, B):
i = j = 1
while True:
if i > len(A):
return True
if j > len(B):
return False
if A[i - 1] == B[j - 1]:
i += 1
j += 1
elif i == 1:
j += 1
else:
i = 1
def solve(s):
... |
mock_get_instance_metadata = """
{
"ami-manifest-path": "(unknown)",
"instance-action": "none",
"ami-launch-index": "0",
"instance-type": "t2.small",
"local-ipv4": "123.45.67.89",
"services": {
"domain": "amazonaws.com",
"partition": "aws"
},
"placement": {
"avail... |
class ExcecaoParaguai(Exception):
pass
class ExcecaoRegraDeNegocio(ExcecaoParaguai):
pass
class ExcecaoNivelAcessoInvalido(ExcecaoParaguai):
pass
class ExcecaoUsuarioJaExistente(ExcecaoParaguai):
pass
class ExcecaoEntidadeInexistente(ExcecaoParaguai):
pass
class ExcecaoUsuarioInexistente(Exceca... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = "Robin 'r0w' Weiland"
__credits__ = ["Robin Weiland", ]
__copyright__ = "Copyright 2019, Robin Weiland"
__date__ = "2019-06-17"
__version__ = "0.0.1"
__license__ = "MIT"
__all__ = ['check_star_imports']
__doc__ = """compares globals() before and after the import... |
# 1003. 检查替换后的词是否有效
#
# 20200801
# huao
# python处理字符串就是舒适
class Solution:
def isValid(self, S: str) -> bool:
while S != "":
if "abc" in S:
S = S.replace("abc", "")
else:
return False
return True
sol = Solution()
print(sol.isValid("cababc"))
|
x =int(input('digite a largura: '))
y= int(input('digite a altura: '))
#x=10
#y=3
x1=x
y1=y
while y>=1:
while x>0:
print("#",end="")
x=x-1
print()
y=y-1
x=x1
|
# Complete the mergeLists function below.
#
# For your reference:
#
# SinglyLinkedListNode:
# int data
# SinglyLinkedListNode next
#
#
def mergeLists(head1, head2):
li3 = SinglyLinkedList()
while(head1 or head2):
if(head1 and head2):
if(head1.data<=head2.data):
li3.i... |
"""
@no 8
@name String to Integer
"""
class Solution:
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
l = []
p = []
tmp_str = ''
start = False
for c in str:
if start:
tmp_str += c
if not start ... |
# Resize cropped image to the following shape
IMG_RESIZE_SHAPE = (64, 64)
# Shift camera when taking left or right image
SHIFT_CAMERA = 0.25
# Extra logging
VERBOSE = False
# Brightness adjustment strenght
BRIGHTNESS_STRENGHT = 0.2
# Crpping
# Leave only 1/img_crop_param of the image
IMG_CROP_PARAM = 5.5
# Crop pix... |
# LinkedList 데이터 추가 원리
# 중간에 데이터를 삽입하려고 이전의 pointer에 새로운 노드의 주소값을 넣어주고
# 새로운 노드의 포인터에 다음 노드의 주소값을 넣어준다.
class MakeNode:
def __init__(self, data, pointer=None):
self.data = data
self.pointer = pointer
class Node:
def __init__(self,data):
self.head = MakeNode(data)
def add(self,data... |
# 運転No.
MotionNum_Min = 0 # Dec:6144, Hex:0x1800
MotionNum_Default = 0
MotionNum_Max = 255 # Dec:22464, Hex:0x57c0 255*64+6144
MotionNumAdress_Min = 6144
MotionNumAdress_Max = 22464
MotionNumAdress_Pitch = 64
# 方式(基準アドレス+0,1): default:2
ControlMethod = {
"AbsolutePosition" : 1, # 1:絶対位置決め
"RelativePositionBas... |
numbers = [1, 2, 5, 7, 89, 90, 10, 20]
evens = []
for n in numbers:
if n % 2 == 0:
evens.append(n * n)
# list comprehension
evens = [
n * n # add value
for n in numbers # set to draw from
if n % 2 == 0 # test for inclusion
]
print(evens)
results = [
(1, 2, 70.1),
(2, 2, 80.0),
... |
class Loggable:
def __init__(self):
self.title = ''
def log(self):
print('Log message from ' + self.title)
class Connection:
def __init__(self):
self.server = ''
def connect(self):
print('Connecting to data base on ' + self.server)
class Sqldatabase(Connection , Loggabl... |
# -*- coding: utf-8 -*-
NOT_FOUND = -1
class SortedSet(object):
def __init__(self):
self.keys = []
self.keys_to_index = {}
def get(self, key):
if key in self.keys_to_index:
return self.keys_to_index[key]
else:
return NOT_FOUND
def add(self, key):... |
print('====== DESAFIO 61 ======')
n = int(input('Digite um número: '))
valor = 1
while valor < n:
guardar = valor |
def leiaDinheiro(txt):
ok = False
while ok is False:
n = input(txt).replace(',', '.').strip()
if n.isalpha() or n == '':
print(f'\033[0;31mERRO! "{n}" INVÁLIDO.\033[m')
else:
ok = True
return float(n)
def leiaInt(msg):
ok = False
num = 0
... |
class Solution:
def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]:
result = []
for start, end in intervals:
if start < toBeRemoved[0]:
result.append([start, min(end, toBeRemoved[0])])
if toBeRemoved[1] < end:
... |
"""
Store all Spulsa API URL PATH here
______________________________
"""
URLS = {
"PRODUCTS": "/product.json",
"BALANCE": "/getBalance",
"TRANSACTIONS": "/transaction.json",
"TRANSACTION": "/transaction/{}.json",
"MOBILE_PREPAID": "/transaction/mobile.json",
"MOBILE_DETAIL": "/transacti... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 11 18:21:39 2015
@author: jmalinchak
"""
#localoutputfolder = 'C:\Batches\AutomationProjects\Investment Strategy\ETL\Uploads\Ready'
#serverwatcherdestination = '\\\\ipc-vsql01\\DATA\\Batches\\prod\\WatchFolder\\incoming'
#mycachefolder = 'C:\\Batches\\GitStuff\\websites... |
#
# @lc app=leetcode.cn id=1221 lang=python3
#
# [1221] 分割平衡字符串
#
# https://leetcode-cn.com/problems/split-a-string-in-balanced-strings/description/
#
# algorithms
# Easy (80.39%)
# Likes: 111
# Dislikes: 0
# Total Accepted: 43.2K
# Total Submissions: 53.2K
# Testcase Example: '"RLRRLLRLRL"'
#
# 在一个 平衡字符串 中,'L' ... |
N,M = map(int,input().split())
A = [[] for _ in range(N)]
for i in range(N):
A[i].extend(map(int,input().split()))
moves = []
for _ in range(M):
moves.append(list(map(int,input().split())))
cloud = [[N-2,0],[N-2,1],[N-1,0],[N-1,1]]
def move_cloud(cloud,direction,s,n):
moved = []
dx,dy = direction[0... |
#
# PySNMP MIB module BW-ClientManagementAccessServerFault (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BW-ClientManagementAccessServerFault
# Produced by pysmi-0.3.4 at Mon Apr 29 17:25:02 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# U... |
numbers = [] # [7, 8, 10, 13, 15, 19, 20, 23, 25]
for _ in range(9):
numbers.append(int(input()))
summation = sum(numbers)
for i in range(len(numbers)):
is_hundred = False
for j in range(1, (len(numbers))):
if i == j:
continue
if summation - (numbers[i] + numbers[j]) == 100:
... |
"""Kata url: https://www.codewars.com/kata/53da3dbb4a5168369a0000fe."""
def even_or_odd(number: int) -> str:
return 'Odd' if number % 2 else 'Even'
|
name=None
description=None
args_and_kwargs = (
(("--embed", ), {
"help":"Drop to an IPython shell at the end of optimization to inpsect variables.",
"action" : "store_true",
"default" : False,
}),
(("--mc-samples",), {
"help":"This is the number of samples to take per grad... |
"""
Author: Maneesh Divana <mdaneeshd77@gmail.com>
Interpreter: Python 3.6.8
Count occurrences of a string that can be constructed
from another given string.
Given two strings str1 and str2 where str1 being the parent string.
The task is to find out the number of string as str2 that can be
constructed using letters o... |
name1_1_1_0_1_1_0 = None
name1_1_1_0_1_1_1 = None
name1_1_1_0_1_1_2 = None
name1_1_1_0_1_1_3 = None
name1_1_1_0_1_1_4 = None |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
可继承单例
需要指定类常量字典 _SINGLE
每当创建一个类,则更新到字典里面
"""
class SingleDog(object):
_SINGLE = {}
def __new__(cls,*args,**kwargs):
if cls not in cls._SINGLE:
cls._SINGLE[cls] = object.__new__(cls, *args, **kwargs)
return cls._SINGLE[cls]
def _... |
data = [
['2020-05-01',20.5],
['2020-05-02',21.5],
['2020-05-03',22.5],
]
dic = dict(data)
print(dic)
data2 = list(dic)
print(data2) |
# http://rosalind.info/problems/iprb/
f = open("rosalind_iprb.txt", "r")
for content in f:
dominant, hetero, recessive = [float(x) for x in content.split()]
total = dominant + hetero + recessive
# Two recessive organisms
doubleRecessive = (recessive / total) * ((recessive - 1) / (total - 1))
# Two heterozygous o... |
"""
677. Map Sum Pairs
Implement a MapSum class with insert, and sum methods.
For the method insert, you'll be given a pair of (string, integer). The string represents the key and the integer represents the value. If the key already existed, then the original key-value pair will be overridden to the new one.
For the ... |
# Write a program that categorizes each mail message by which day of the week the commit was
# done. To do this look for lines that start with "From", then look for the third word and keep
# a running count of each of the days of the week. At the end of the program print out the
# contents of your dictionary (order do... |
def bb_intersection_over_union(box_a, box_b):
"""Thank you pyimagesearch!
https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/
:param box_a: Rect
:param box_b: Rect
"""
# determine the (x, y)-coordinates of the intersection rectangle
xA = max(box_a[0],... |
class Genotype:
"""Make string representation of cyvcf2 genotype"""
def __init__(self, li):
self.alleles = li[:-1]
self.phased = li[-1]
def __str__(self):
sep = "/|"[int(self.phased)]
return sep.join("0123."[a] for a in self.alleles)
__repr__ = __str__
# Conversion f... |
# -*- coding: utf-8 -*-
# =============================================================================
def config(settings):
"""
BRCMS: Sahana Beneficiary Registry and Case Management System
"""
# PrePopulate data
settings.base.prepopulate.append("BRCMS/Standard")
settings.base.prepopulat... |
#!/usr/bin/python
""" Author: Radar-Lei
topological sort implementation for the lecture
"""
class Graph:
def __init__(self):
self.vertex = {}
# for printing the Graph vertices
def print_graph(self) -> None:
print(self.vertex)
# for adding the edge between two vertices
def ad... |
def primo(k):
fator = 2
while k%fator !=0 and fator<=k/2:
fator=fator+1
if k%fator==0:
return False
else:
return True
def maior_primo(k):
while k<2:
k = int(input( " Digite número inteiro maior ou igual a 2: "))
d= éPrimo(k)
return d
def éPrimo(z):
b... |
"""Host custom exceptions."""
class DesktopAutomatorError(Exception):
"""Base exception."""
class UnsopportedSystemError(DesktopAutomatorError):
"""Unsupported system error."""
|
#ASCII graphic for the logo of the project
def getAscii():
print("e88~~\\ ,e, d8 d8 ")
print("d888 \" _d88__ _d88__ 888-~\\ /~~~8e ")
print("8888 __ 888 888 888 888 88b")
print("8888 | 888 888 888 888 e88~-888")
prin... |
class DiskName(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_disk_name(idx_name)
class DiskNameColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_disks()
|
# Rescreva a função leiaInt() que fizemos no desafio 104, incluindo
# agora a possibiliade da digitação de um número de tipo inválido.
# Aproveite e rie também uma função leiaFloat() com a mesma funcionalidade.
def leiaInt(msg):
while True:
try:
num = int(input(f'{msg}'))
except (ValueE... |
DEFAULT_BRANCH_OFFSET = 50
DEFAULT_BURN_RESERVE = 100
DEFAULT_GAS_RESERVE = 100
DEFAULT_OPERATIONS_TTL = 5
MAX_OPERATIONS_TTL = 60
|
#test2.py
if __name__=="__main__":
print("this is module test2")
def test2Function():
print("this is a function in module test2")
if __name__=="__main__":
print("this is test2 module name:"+__name__) |
#!/usr/bin/env python
# Day 14 solution of Advent Of Code 2020 by Riccardo Negri
# First part answer: 14954914379452
# Second part answer: 3415488160714
def replace_bit(number, bit, position):
mask = 1 << position # shift
return (number & ~mask) | ((bit << position) & mask)
def get_sum(dictionary):
sum ... |
# plotting the asset value change of the portfolio
def profit(portfolio):
fig = plt.figure()
bx = fig.add_subplot(111)
portfolio["total asset"].plot(label="Total Asset")
# long/short position markers related to the portfolio
# the same mechanism as the previous one
# replace close price with ... |
__copyright__ = """\
(c). Copyright 2008-2020, Vyper Logix Corp., All Rights Reserved.
Published under Creative Commons License
(http://creativecommons.org/licenses/by-nc/3.0/)
restricted to non-commercial educational use only.,
http://www.VyperLogix.com for details
THE AUTHOR VYPER LOGIX CORP DISCLAIMS ALL WARRA... |
# I'm going to use the filter method
listNumber = [12, 34, 45, 6, 6, 8, 12, 79]
def number_pair(num):
if num % 2 == 0:
return True
print(list(filter(number_pair, listNumber)))
# using the lambda expression
listNumberTwo = [12, 34, 45, 6, 6, 8, 12, 79]
print(list(filter(lambda x: x % 2 == 0, listNumberT... |
input = """
% This would (have) trigger(ed) inferences from dynamic constraints.
x | y.
a :- not x.
b :- not x.
c :- b.
a :- not c.
"""
output = """
% This would (have) trigger(ed) inferences from dynamic constraints.
x | y.
a :- not x.
b :- not x.
c :- b.
a :- not c.
"""
|
print("hello world")
name="akanksha"
middlename=("sanjay")
surname=("waghmare")
print(name,middlename,surname)
print(name[0:9:2]) #slicing
a="program"
b= type (a)
print(b) #type of the variable |
'''
Created on Mar 7, 2016
@author: dj
'''
class MyException(Exception):
pass
def method1(x, y):
try:
a = x / y
except Exception as e:
print("method1:Exception = {0}".format(e))
raise
else:
print("method1:No exception.")
finally:
print... |
def calculate_dist_in_mile(dist_km):
convert_factor = 0.621371
dist_miles = convert_factor * dist_km
return dist_miles
|
PHONE_CODES_CHOICES = (
("+93", "Afganistán (+93)"),
("+355", "Albania (+355)"),
("+213", "Argelia (+213)"),
("+1", "Samoa Americana (+1)"),
("+376", "Andorra (+376)"),
("+244", "Angola (+244)"),
("+1", "Anguila (+1)"),
("+1", "Antigua y Barbuda (+1)"),
("+54", "Argen... |
def elapsed_time(start_time, end_time):
delta_time = end_time - start_time
days, seconds = divmod(delta_time.total_seconds(), 86400)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
return days, hours, int(minutes), int(seconds)
def parse_time(seconds):
days, secon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.