content stringlengths 7 1.05M |
|---|
"""
module for creating generic constants used by multiple modules
"""
"""
The cloudwatch dashboard grid positioning system will automatically set x and y coordinates of every widget
in the list, based on the next available x,y on the dashboard, from left to right, then top to bottom. As long
as we specif... |
# %% [1128. Number of Equivalent Domino Pairs](https://leetcode.com/problems/number-of-equivalent-domino-pairs/)
class Solution:
def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
c = collections.Counter(tuple(sorted(i)) for i in dominoes)
return sum(n * (n - 1) // 2 for n in c.values(... |
print("hi\nmyname is : abdullah")
print("And in this code we will do ")
#Files
print("Files")
#______________________#
with open("information.txt" , "r") as f:
print(f.read()) |
"""
DESCRIPTION
Gerald Appel developed Moving Average Convergence/Divergence as an indicator
of the change in a security's underlying price trend. The theory suggests that
when a price is trending, it is expected, from time to time, that speculative
forces "test" the trend. MACD shows characteristics of both a trendi... |
def canTransform1(start, end):
startX = "".join([c for c in start if c != "X"])
endX = "".join([c for c in end if c != "X"])
if startX != endX: return False
startR = [i for i in range(len(start)) if start[i] == "R"]
startL = [i for i in range(len(start)) if start[i] == "L"]
endR = [i for i... |
n = int(input())
lst = sorted([int(input()) for i in range(n)])
ans = sorted(set(range(lst[0], lst[len(lst) - 1])).difference(lst))
if lst[0] > 1:
for i in range(1, lst[0]):
ans.append(i)
if (len(ans) != 0):
print(*sorted(ans), sep='\n')
else:
print("good job")
|
#
# PySNMP MIB module HH3C-RCR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-RCR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:29:21 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,... |
# Painter's Partition Problem
# https://www.interviewbit.com/problems/painters-partition-problem/
#
# You have to paint N boards of length {A0, A1, A2, A3 … AN-1}. There are K painters available
# and you are also given how much time a painter takes to paint 1 unit of board. You have to get
# this job done as soon as p... |
# Copyright 2019-2020 The ASReview 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 appl... |
"""
0 = possible pathway
1 = wall
2 = rat's path
"""
board = [
[0, 0, 0, 0, 0],
[1, 1, 0, 1, 0],
[0, 0, 0, 1, 0],
[0, 1, 1, 1, 1],
[0, 0, 0, 0, 0],
]
moves = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def main():
if solve(board, 0, 0, 0):
print("Solvable")
[print(row) for row in board... |
# -*- coding: utf-8 -*-
__version__ = '0.1.0'
__author__ = 'Ramiro Gómez <code@ramiro.org>'
__name__ = 'procrust'
__description__ = 'Limit the time you procrastinate by blocking websites via the hosts file'
__all__ = [] |
# x_5_5
#
# 「while文」を使って鬼退治のメンバーを1行づつ表示するコードを追加してください
members = ['桃太郎', 'いぬ', 'さる', 'きじ']
number = 0
while number < 10:
print(number)
number += 1
|
DATA_DIR = "/path/your_data_path"
IDX_DIR = "/path/your_index_path"
FILE_ROOT = "./test"
CALIB_FILE = "./imagenet_int8_cache"
MODEL_FILE = "./resnet_imagenet.uff" |
search_success_response = {'timestamp': 1579714500, 'articleCount': 10, 'articles': [
{'title': 'Recovering Lost Sales with Facebook Messenger Marketing',
'description': 'With Facebook Messenger marketing, ecommerce companies can connect with shoppers and site visitors directly through Facebook chatbots, crea... |
#Vimos que n = 42 é legal. E 42 = n?
"""Não é legal porque estariamos forçando a maquina a reservar o espaço 42 para N.
No caso de um IDE, ele não permitirá, o nome da variável terá erro. Não pode ser númérica e nem começar com número."""
#Ou x = y = 1?
"""Se for apenas parâmetros simples, é correto. Listas, tuplas e ... |
APP_DIRECTORY_NAME = "APP"
SRC_DIRECTORY_NAME = "src"
TEMPLATES_DIRECTORY_NAME = "templates"
# Production React Js Template files having Github Repository Links
REACTJS_TEMPLATES_URLS_DICT = {
"package.json-tpl": "https://raw.githubusercontent.com/Jitensid/django-webpack-dev-server/main/assets/reactjs/package.json... |
# SPDX-License-Identifier: GPL-3.0-only
def make_definitions(f, ecpp, bcpp, all_enums, all_bitfields, all_structs_arranged):
f.write("// SPDX-License-Identifier: GPL-3.0-only\n\n// This file was auto-generated.\n// If you want to edit this, edit the .json definitions and rerun the generator script, instead.\n\n")
... |
def run_gbrt(d, r, t, ne=0, lr=0.1, md=3, trs=0, frs=0, mf=7):
X_train, X_test, y_train, y_test = train_test_split(
np.append(r, d, 1), t, random_state=trs)
gbrt = GradientBoostingClassifier(
n_estimators=ne, learning_rate=lr, max_depth=md, max_features=mf, random_state=frs)
gbrt.fit(X_train... |
class Solution:
def buildArray(self, target: List[int], n: int) -> List[str]:
res = []
n = min(max(target), n)
for i in range(1, n+1):
if i in target:
res += ["Push"]
else:
res += ["Push","Pop"]
return res
|
expected_output = {
"vrf": {
"default": {
"source_address": "172.16.10.13",
"path": {
"172.16.121.10 BRI0": {
"neighbor_address": "172.16.121.10",
"neighbor_host": "sj1.cisco.com",
"distance_preferred_lookup"... |
a = True
b = False
if a == b:
print(1)
else:
print(0)
|
#!/usr/bin/env python3
i = 1
for x in range(-10000, 10000):
for y in range(-10000, 10000):
if (abs(x)+abs(y)) < 100:
i += 1
print(i)
|
class BaseChild:
payload = {
"patient": {
"lastName": "Deeererederepwswdwewwdw",
"firstName": "Allakirillohldldwwwlflrereeeded",
"middleName": "Ballerffffff",
"birthDate": "2011-05-29",
"sex": True,
"isAutoPhone": True
},
... |
ENTRY_POINT = 'smallest_change'
#[PROMPT]
def smallest_change(arr):
"""
Given an array arr of integers, find the minimum number of elements that
need to be changed to make the array palindromic. A palindromic array is an array that
is read the same backwards and forwards. In one change, you can change ... |
# Write a dictionary or list to hdfs
best_params = {
"Key1": 123,
"Key2": "hello"
}
save_path = "hdfs://nameservice1/user/duc.nguyenv3/projects/01_lgbm_modeling/data/output/best_params.json"
sdf = (
spark
.sparkContext
.parallelize([best_params])
.toDF()
.coalesce(1)
... |
"""
Test module for learning python packaging.
"""
NAME = "pybinson"
|
'''
Title : sWAP cASE
Subdomain : Strings
Domain : Python
Author : Kalpak Seal
Created : 29 September 2016
'''
__author__ = 'Kalpak Seal'
inputString = raw_input()
finalString = ""
for i in range(0, len(inputString)):
currentChar = inputString[i]
if currentChar.islower() or currentChar... |
class Singleton(object):
def __init__(self, func):
self._func = func
def Instance(self,*a,**k):
try:
return self._instance
except AttributeError:
self._instance = self._func(*a,**k)
return self._instance
def __call__(self):
raise TypeError(... |
FILE_TEMPLATE = "19C_{0:05d}.xml"
header = """<?xml version="1.0" encoding="UTF-8" ?><marc:collection xmlns:marc="http://www.loc.gov/MARC21/slim" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.loc.gov/MARC21/slim http://www.loc.gov/standards/marcxml/schema/MARC21slim.xsd">
"""
fo... |
#
# PySNMP MIB module BLUECOAT-AV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BLUECOAT-AV-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:22:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
"""
A set of helpers functions and constants for supporting the bot engine.
"""
_LANG_SET = {
'ar': ' Arabic',
'bg': 'Bulgarian',
'ca': 'Catalan',
'zh-CHS': 'Chinese (Simplified)',
'zh-CHT': 'Chinese (Traditional)',
'cs': 'Czech',
'da': 'Danish',
'nl': 'Dutch',
'en': 'Inglês',
'... |
def notas(* n, sit=False):
"""[Função para analisar notas e situações de cários alunos]
Args:
n (float): [Uma ou mais notas dos alunos (aceita várias)]
sit (bool, optional): [Indica se deve ou não adicionar a situação]. Defaults to False.
Returns:
[dict]: [Dicionário com várias infor... |
class PartialFillHandlingEnum:
PARTIAL_FILL_UNSET = 0
PARTIAL_FILL_HANDLING_REDUCE_QUANTITY = 1
PARTIAL_FILL_HANDLING_IMMEDIATE_CANCEL = 2
|
'''Exercício Python 015: Escreva um programa que pergunte a quantidade de Km percorridos
por um carro alugado e a quantidade de dias pelos quais ele foi alugado.
Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$0,15 por Km rodado.
'''
msg = f'{"Aluguel de Veículos":^30}'
print('*'*len(msg))
print(m... |
SKILL_SAMPLE_TYPES = (
("dc", "DC"),
("mod", "Modifier"),
)
|
def emulate(instructions):
# did we already run a specific instruction?
previous = [False for _ in range(len(instructions))]
acc, i = 0, 0
while i < len(instructions):
# infinite loop detected
if previous[i]:
return None
previous[i] = True
instr, value = instructions[i]
... |
flowerpot_price = 4.00
flower_seeds_price = 1.00
soil_price = 5.00
tax_rate = 0.06
number_of_pots = int(input('How many flowerpots? '))
number_of_seeds = int(input('How many packs of seeds? '))
number_of_bags = int(input('How many bags of soil? '))
cost_of_items = (number_of_pots * flowerpot_price)
+ (number_of_seeds... |
class Field:
cells = ()
def __init__(self, w, h):
print('Game Field Created!')
|
# Given an input string (s) and a pattern (p),
# implement regular expression matching with support for '.' and '*'.
# '.' Matches any single character.
# '*' Matches zero or more of the preceding element.
# The matching should cover the entire input string (not partial).
# Note:
# s could be empty and contains only l... |
class Entry(object):
def __init__(self, record, value):
self.record = record
self.value = value
def __lt__(self, other):
# to make a max-heap
return self.value > other.value
def to_json(self):
return {"record": self.record.to_json(), "value": self.value}
|
#
# PySNMP MIB module HUAWEI-TASK-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-TASK-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:37:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
# keyword param for the ProfileHandler
KEY_DATASET_OBJECT_ID = 'dataset_object_id'
KEY_SAVE_ROW_COUNT = 'save_row_count'
KEY_DATASET_IS_DJANGO_FILEFIELD = 'dataset_is_django_filefield'
KEY_DATASET_IS_FILEPATH = 'dataset_is_filepath'
VAR_TYPE_BOOLEAN = 'Boolean'
VAR_TYPE_CATEGORICAL = 'Categorical'
VAR_TYPE_NUMERICAL ... |
"""
day22-part1.py
Created on 2020-12-22
Updated on 2020-12-22
Copyright © Ryan Kan
"""
# INPUT
with open("input.txt", "r") as f:
content = f.read()[:-1]
f.close()
# Split the content into player 1's cards and player 2's cards
sections = content.split("\n\n")
player1Cards = [int(x) for x in sections[0][10:... |
#! /usr/bin/env python3
# check if a word is palindromic without reversing it
def isPalindrome(word):
end = len(word)
start = 0
retval = True
while start < end+1:
left = word[start]
right = word[end-1]
if left != right:
retval = False
break
start... |
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return matrix
rcnt = len(matrix)
ccnt = len... |
class Pessoa:
olhos = 2
def __init__(self, *filhos, nome=None, idade=46):
self.idade = idade
self.nome = nome
self.filhos = list(filhos)
def cumprimentar(self):
return f'Ola {id(self)}'
if __name__ == '__main__':
nilton = Pessoa(nome='Nilton')
roberto = Pessoa(nil... |
AIRTABLE_EXPORT_JOB_DOWNLOADING_PENDING = "pending"
AIRTABLE_EXPORT_JOB_DOWNLOADING_FAILED = "failed"
AIRTABLE_EXPORT_JOB_DOWNLOADING_FINISHED = "finished"
AIRTABLE_EXPORT_JOB_DOWNLOADING_BASE = "downloading-base"
AIRTABLE_EXPORT_JOB_CONVERTING = "converting"
AIRTABLE_EXPORT_JOB_DOWNLOADING_FILES = "downloading-files"
... |
#!/usr/bin/env python3
"""Advent of Code 2020 Day 06 - Custom Customs."""
with open ('inputs/day_06.txt', 'r') as forms:
groups = [group_answers.strip() for group_answers in forms.read().split('\n\n')]
overall_yes = 0
for group in groups:
group_yes = set()
for member_yes in group.split('\n'):
fo... |
print("Rathinn")
print("AM.EN.U4AIE19052")
print("AIE")
print("Anime Rocks")
|
"""Constants about physical keg shell."""
# Most common shell sizes, from smalles to largest.
MINI = "mini"
CORNY_25 = "corny-2_5-gal"
CORNY_30 = "corny-3-gal"
CORNY = "corny"
SIXTH_BARREL = "sixth"
EURO_30_LITER = "euro-30-liter"
EURO_HALF_BARREL = "euro-half"
QUARTER_BARREL = "quarter"
EURO = "euro"
HALF_BARREL = "h... |
"""Consts used by rpi_camera."""
DOMAIN = "rpi_camera"
CONF_HORIZONTAL_FLIP = "horizontal_flip"
CONF_IMAGE_HEIGHT = "image_height"
CONF_IMAGE_QUALITY = "image_quality"
CONF_IMAGE_ROTATION = "image_rotation"
CONF_IMAGE_WIDTH = "image_width"
CONF_OVERLAY_METADATA = "overlay_metadata"
CONF_OVERLAY_TIMESTAMP = "overlay_t... |
# Desafio 097: Faça um programa que tenha uma função chamada escreva(), que
# receba um texto qualquer como parâmetro e mostre uma mensagem com tamanho
# adaptável.
def escreva(texto):
tamanho = len(texto) + 4
print('~' * tamanho)
print(f'{texto:^{tamanho}}')
print('~' * tamanho)
texto = inp... |
# Backtracking
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
if not candidates:
return
candidates.sort()
paths = []
results = []
index = 0
cursum = 0
# paths, results,... |
# final
def sum_of_args(args):
result = 0
for i in args:
result += i
return result
print(sum_of_args(args=[1,2,3,4]))
|
'''
https://leetcode.com/contest/weekly-contest-182/problems/find-lucky-integer-in-an-array/
'''
class Solution:
def findLucky(self, arr: List[int]) -> int:
for a in sorted(arr)[::-1]:
if a == arr.count(a):
return a
return -1
|
####Use the loop 'while'
# input a and b
a = int(input())
b = int(input())
if a > b :
print('it is not the total')
else :
i = a
total = 0
while i <= b :
total += i
i += 1
print(total) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def file():
print('step1')
yield 1
print('step2')
yield 2
return '应该停止了'
print('2')
yield 123
m = 0
while m < 10:
try:
x = file()
j = next(x)
print('数据:', j)
except StopIteration as e:
print('数据是:', e.va... |
# Write your solution for 1.3 here!
x=0
i=0
while x<10000:
i+=1
x+=i
print(i)
|
# This is the Python adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
#
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 ... |
tile_size = 25
# size of tiles in the board
screen_width = 400
# width of the screen
screen_height = 400
# height of the screen
|
class Queue:
def __init__(self,list = None):
if list == None:
self.item =[]
else :
self.item = list
def enQueue(self,i):
self.item.append(i)
def size(self):
return len(self.item)
def isEmpty(self):
return len(self.item)==0
def deQueue... |
def test_signup_new_account(app):
username = "user1"
password = "test"
app.james.ensure_user_exists(username, password) |
list_var = [1, 2]
dict_var = {
"key1": "value1"
}
setVar = {1, 2, 3} |
n = int(input())
cnt1, cnt2 = {}, {}
for i in range(n):
x, y = map(int, input().split())
cnt1[x+y] = cnt1.get(x+y, 0) + 1
cnt2[x-y] = cnt2.get(x-y, 0) + 1
ans = 0
for t in cnt1.values():
ans += t*(t-1)//2
for t in cnt2.values():
ans += t*(t-1)//2
print(ans)
|
#No python podemos fazer de três maneiras uma tupla: (), Uma lista: [], e um dicionário:{}
lanche = ('Hamburger','Suco','Pizza','Pudim')
print(lanche)# Vai aparecer todos, ou mostrar a tupla inteira
print(lanche[1])# Vai aparecer o seleciondo
print(lanche[-2])# Vai mostrar o que está atrás do selecionado
print(lanche[1... |
def valid_oci_group(parser):
add_oci_group(parser)
def add_oci_group(parser):
oci_group = parser.add_argument_group(title="OCI arguments")
oci_group.add_argument("--oci-profile-name", default="")
oci_group.add_argument("--oci-profile-compartment-id", default="")
# HACK to extract the set provider... |
def sievePrimeGen(n):
primes = [True] * (n + 1)
ans = []
for i in range(2, int(n * (1 / 2) + 1)):
if primes[i] == True:
for j in range(i * 2, n + 1, i):
primes[j] = False
for i in range(2, n + 1):
if primes[i] == True:
ans.appe... |
class Card:
def __repr__(self):
return str((self.name, self.rules, self.value))
class Batman(Card):
def __init__(self):
self.name = 'Batman'
self.value = 1
self.rules = "Guess a player's hand"
self.action = 'guess'
class Catwoman(Card):
def __init__(self):
... |
#Escreva um programa qye converat uma temperatura digitada em °C e converta para °F.
c=float(input('Informe a temperatura em °C: '))
f=9*c/5+32
print('A temperatura de {}°C corresponde a {}°F'.format(c,f))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode':
'''
in-order traversal
'''
sel... |
db_host_name="127.0.0.1"
db_name="TestDB"
db_user="testuser"
db_password="test123"
db_table_name="brady"
|
#
# This file is part of BDC-DB.
# Copyright (C) 2020 INPE.
#
# BDC-DB is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Define mock of flask app that extends BDC-DB."""
SCHEMA = 'myapp'
|
'''
Created on 13 Jun 2016
@author: a
'''
class InvalidPasswords():
BAD_PASSWORDS = ['1234567890','qwertyuiop','123456789','password1','photoshop',
'11111111','12345678','1qaz2wsx','access14','adobe123','baseball',
'bigdaddy','butthead','cocacola','comp... |
# None datatype
a = None
print(a)
# Numeric datatype (int,float,complex,bool)
b = 4
print(type(b))
c = 2.5
print(type(c))
d = 4 + 5j
print(type(d))
bool = b > c
print(type(bool))
e = int(c)
print(e)
f = complex(e, b)
print(f)
print(int(True))
# List datatype
lst = [1, 2, 3, 4, 5]
print(lst)
# Set datatype
s = {4, 8,... |
# this menu.py only installs the SetLoop examples.
# get script location (necessaary for loading toolsets)
dirName = os.path.dirname( os.path.abspath(__file__)).replace('\\', '/')
# get node toolbar
nodes = nuke.menu('Nodes')
# make group entry for examples in toolsets menu
group = nodes.addMenu('ToolSets/SetLoop... |
_base_ = ["./FlowNet512_1.5AugCosyAAEGray_Flat_Pbr_01_ape.py"]
OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_Flat_lmPbr_SO/camera"
DATASETS = dict(TRAIN=("lm_pbr_camera_train",), TEST=("lm_real_camera_test",))
# bbnc7
# objects camera Avg(1)
# ad_2 26.86 26.86
# ad_5 84.41 84.41
# a... |
# Function to square every digit of a number.
# Eg. 9119 will become 811181, because 9^2 is 81 and 1^2 is 1.
def square_each_number(num):
result= ''
list = [int(d) for d in str(num)]
square_list = [i ** 2 for i in list]
for i in square_list:
result += str(i)
return float(result)
test.assert... |
# QUESTION:
#
# This problem was asked by Google.
#
# Given the root to a binary tree, implement serialize(root), which serializes
# the tree into a string, and deserialize(s), which deserializes the string
# back into the tree.
#
# For example, given the following Node class
#
# class Node:
# def __init__(self, va... |
def reverseBits(n):
head = 15
tail = 0
while head > tail:
headBit = (n >> head) & 1
tailBit = (n >> tail) & 1
if headBit != tailBit:
bitMask = (1 << head) | (1 << tail)
n ^= bitMask
head -= 1
tail += 1
return n
|
class MolGraphInterface:
r"""The `MolGraphInterface` defines the base class interface to handle a molecular graph. The method implementation
to generate a mol-instance from smiles etc. can be obtained from different backends like `rdkit`. The mol-instance
of a chemical informatics package like `rdkit` is tr... |
# from Data Structures, Spring 2019
class Graph:
"""Representation of a simple graph using an adjacency map."""
#------------------------- nested Vertex class -------------------------
class Vertex:
"""Lightweight vertex structure for a graph."""
# __slots__ = '_element'
def __... |
""".. Ignore pydocstyle D400.
===============
Resolwe Toolkit
===============
This module includes general processes, schemas, tools and docker image
definitions.
"""
|
def get(s, register):
if s in 'abcdefghijklmnopqrstuvwxyz':
return register[s]
return int(s)
def solveQuestion(inputPath):
fileP = open(inputPath, 'r')
instVals = [line.split() for line in fileP.read().strip().split("\n")]
fileP.close()
registers = {}
registers[0] = {}
... |
class ColumnWidthChangingEventArgs(CancelEventArgs):
"""
Provides data for the System.Windows.Forms.ListView.ColumnWidthChanging event.
ColumnWidthChangingEventArgs(columnIndex: int,newWidth: int,cancel: bool)
ColumnWidthChangingEventArgs(columnIndex: int,newWidth: int)
"""
@staticmethod
... |
# import standard modules
# import third party modules
# import third party modules
class Layer(object):
"""
Parent class for all layer classes used for a model. For this framework is does only have one attribute
which all layers share, however, it is important to keep things sorted in case of future en... |
"""
URL lookup for common views
"""
common_urls = [
]
|
PRECISION = 100
class PiCalculator(object):
def __init__(self, precision):
self.precision = precision
def divide_one_by(self, b):
divider = 1
result = ""
for x in range(self.precision):
if divider // b == 0:
divider *= 10
result += ... |
def area(a, b):
return (a * b) / 2
print(area(6, 9))
print(area(5, 8))
|
class Notify():
def __get__(self, instance, owner):
print('正在读取资料')
def __set__(self, instance, value):
print('正在设置')
def __delete__(self, instance):
print('正在删除')
class MyDes():
x = Notify()
|
'''1. Написать программу, которая будет складывать, вычитать, умножать или
делить два числа. Числа и знак операции вводятся пользователем. После
выполнения вычисления программа не должна завершаться, а должна запрашивать
новые данные для вычислений. Завершение программы должно выполняться при вводе
символа '0' в качест... |
# returns the classification or None if no classification could be determined
def calcClass(arr):
sel0 = arr[0] > 0.0
sel1 = arr[1] > 0.0
if sel0 and sel1: # is selection valid? if not then we just ignore the result!
n = 2
maxSelVal = float("-inf")
maxSelIdx = None
for iIdx i... |
"""
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwis... |
'''
Leetcode problem No 301 Remove Invalid Parentheses
Solution written by Xuqiang Fang on 5 July, 2018
'''
class Solution(object):
def removeInvalidParentheses(self, s):
"""
:type s: str
:rtype: List[str]
"""
l = 0; r = 0
for c in s:
if c == '(':
... |
# -*- coding: utf-8 -*-
"""Implementation of the ``tcell_crg_report`` step
This step collects all of the calls and information gathered for the BIH T cell CRG and generates
an Excel report for each patient.
.. note::
Status: not implemented yet
==========
Step Input
==========
The BIH T cell CRG report generat... |
#Tipo string
n = str(input('Digite um valor'))
print(n)
#tipo inteiro
n1 = int(input('Digite um valor'))
print(n1)
#tipo float
n2 = float(input('Digite um valor real'))
print(n2)
#tipo booleano
v = bool(input('Insira um número'))
print('Quando o tipo e bool a pergunta se {} é verdadeiro ou falto'.format(v))
#Tipo m... |
def MAD(data : np.array):
"""
returns the median absolute deviation of a distribution
useful for non-normal distributions, etc.
"""
return np.median(abs(data - np.median(data)))
|
class Solution:
def search(self, arr, target) -> int:
"""O(logn) time | O(1) space"""
l, h = 0, len(arr)-1
while l <= h:
mid = (l+h)//2
if arr[mid] == target:
return mid
elif target < arr[mid]:
if arr[l] <= target or arr[l] ... |
__doc__ = """Just a sketch for now.
"""
__author__ = "Rui Campos"
class Element(dict):
def __init__(self, Z):
self.__dict__[Z] = 1
self.Z = Z
def __mul__(self, other):
#usual checks
if not (isinstance(other, float) or isinstance(other, int)):
... |
"""
utils.py
Copyright 2011 Andres Riancho
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that it wi... |
_base_ = './faster_rcnn_obb_r50_fpn_1x_dota2.0.py'
# fp16 settings
fp16 = dict(loss_scale=512.)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.