content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
------------------------------------------------------------------------------
WARPNet Transport
------------------------------------------------------------------------------
Authors: Chris Hunter (chunter [at] mangocomm.com)
Patrick Murphy (murphpo [at] mangocomm.com)
... |
lar = input('largura: ')
alt = input('altura: ')
area = float(lar)*float(alt)
tinta = area/2
print(tinta,' litros de tinta.') |
"""Event.py: stores a facebook event as a python object and calculates the
latitude and longitude of the event if available."""
class Event:
def __init__(self, title, timestamp, location, description):
self.title = title
self.timestamp = timestamp
self.location = location
self.latlo... |
'''Advent of Code - Day 7 2017'''
# Part 2
children = []
parents = []
weight = {}
tower = {}
total_weight = {}
total_parts = {}
with open('day07input.txt') as f:
for line in f:
group = line.strip('\n').split('->')
item = group[0].split(' (')
key = item[0]
value = item[1].strip(')... |
#!/usr/bin/env python3
FILE='test.txt' # sol: 26
FILE='input.txt' # sol: 504
def parse_input(file):
out = [];
with open(file, 'r') as f:
for line in f:
digits = line.rstrip().split(" | ")[1].split(' ')
#print(f'line digits: {digits}')
out.extend(digits)
#print(f... |
class Parrot:
species = 'bird'
vertebrae = True
def __init__(self, name, age):
self.name = name
self.age = age
def sing(self, song):
return f'{self.name} sings {song}.'
def dance(self):
return f'{self.name} is now dancing.'
tweety = Parrot('Tweety', 2)
print(tw... |
'''
Function to calculate the probability of getting married
By Dr. Raymond Hoogendoorn
Copyright 2020
'''
def calculateMarriageIntentionProbability(df_marriage2, baseyear):
year = int(baseyear)
df_current = df_marriage2[df_marriage2['Perioden'] == year]
marriageintentionprob = list()
for i in range(... |
# def solve(s):
# digits = ''
# letters = ''
# other = ''
# for ch in s:
# if ch.isdigit():
# digits += ch
# elif ch.isalpha():
# letters += ch
# else:
# other += ch
# print(digits)
# print(letters)
# print(other)
de... |
def threeNumberSort(array, order):
if len(array) == 0:
return []
first = 0
for num in order:
second = first + 1
while first < len(array):
while first < len(array) and array[first] == num:
first += 1
if first == len(array):
retur... |
# File: arcsight_consts.py
# Copyright (c) 2017-2021 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
#
# Action ID keys
ACTION_ID_CREATE_TICKET = "create_ticket"
ACTION_ID_UPDATE_TICKET = "update_ticket"
ACTION_ID_GET_TICKET = "get_ticket"
ACTION_ID_RUN_QUERY = "run_query"
... |
def partitions(cards, subtotal):
m = 0
# Hit
for i in range(0,10):
if (cards[i]>0):
total = subtotal+i+1
if (total < 21):
# Stand
m += 1
# Hit again
cards[i] -= 1
m += partitions(cards, total)
... |
class Locus(object):
def __init__(self, genome, contig, locus_from, locus_to, genes, cas8_cluster=None,
strand=None):
self.genome = genome
self.contig = contig
self.locus_from = locus_from
self.locus_to = locus_to
self.genes = genes
self.orders = ... |
class QueueInfo:
def __init__(self, celery_app):
self.control = celery_app.control
self.inspect = self.control.inspect()
self.channel = celery_app.connection().channel()
def active_queue_names(self):
"""
get all active queue name.
"""
return set(self.acti... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def preorderTraversal(self, root: TreeNode) -> List[int]:
if not root:
return []
... |
def loss_mean_reduction_function(loss, *_):
return loss.mean()
def loss_sum_reduction_function(loss, *_):
return loss.sum()
def loss_reduce_by_weight(loss, pred, label, context):
return (loss * context['sample_weight']).sum()
def build_loss_reduction_function(loss_parameters: dict):
if 'reduce' no... |
class CNode(object):
def __init__(self):
self._children = []
def add_children(self, child_node, *args):
self._children.append(child_node)
for node in args:
self._children.append(node)
def emit(self, emit_func=print):
pass
def children(self):
... |
#
# PySNMP MIB module LIGHTSTREAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LIGHTSTREAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:56: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... |
async def run(client, message, args, prefix, db):
if message.author.guild_permissions.manage_messages:
if len(args) > 0:
if args[0].isdigit():
msgs = list()
async for msg in message.channel.history(limit = int(args[0])+1):
msgs.append(msg)
... |
def slab_is_valid(slab_analyzed,dft_type):
if dft_type in ['Mixed DFTB', 'Mixed DFT']:
first_metal_atom=slab_analyzed['slabatoms'][0]
for el in slab_analyzed['slab_elements']:
if el not in ['Ag','Au','Cu','H']:
return (False, "Wrong slab composition")
if ... |
def rule_maker(raw_rules):
rules = {}
for rule in raw_rules:
key, value = rule.split(': ')
if value[0] == '"':
rules[int(key)] = value[1:-1]
else:
values = value.split(' | ')
temp_v = []
for v in values:
temp_v.append([int(v... |
__package_name__ = "{{package_name}}"
__description__ = '{{description}}'
__url__ = '{{url}}'
__version__ = '{{version}}'
__author__ = '{{author}}'
__author_email__ = '{{author_email}}'
__license__ = '{{license}}'
__copyright__ = '{{copyright}}'
|
"""
24. Faça um Programa que leia 2 números e em seguida pergunte ao usuário qual
operação ele deseja realizar. O resultado da operação deve ser acompanhado de
uma frase que diga se o número é:
a. par ou ímpar;
b. positivo ou negativo;
c. inteiro ou decimal.
"""
n1 = float(input("Informe um número: "))
n... |
prefixes = {
16: "initialLetterContraction_prefix",
24: "initialLetterContraction_prefix",
40: "finalLetterGroupSign_prefix",
48: "grade1_finalLetterGroupSign_prefix",
56: "initalLetterContraction_prefix",
}
prefix_16 = {
"(ch)": "character",
"d": "day",
"e": "ever",
"f": "father",
... |
f'''
struct {ANON_IDENTIFIER};
struct {{ ... }}
struct {IDENTIFIER} {{ ... }}
union {ANON_IDENTIFIER};
union {{ ... }}
union {IDENTIFIER} {{ ... }}
enum {ANON_IDENTIFIER};
enum {{ ... }}
enum {IDENTIFIER} {{ ... }}
typedef {VARTYPE} {IDENTIFIER};
typedef {IDENTIFIER};
... |
def bin_to_string(num):
cnt = 0
res = '.'
while num > 0:
if (cnt >= 32):
return 'ERROR'
cnt += 1
digit, num = divmod(num * 2, 1)
res += str(int(digit))
return res
bin_to_string(0.72)
bin_to_string(0.625)
|
def estCondicional01():
#Definir variables y otros
print("Ejemplo estructura Condicional en Python")
montoP=0
#Datos de entrada
cantidadX=int(input("Ingrese la cantidad de lapices:"))
#Proceso
if cantidadX>=1000:
montoP=cantidadX*0.80
else:
montoP=cantidadX*0.90
#Datos de salida
print("El mont... |
mahasiswa_list = ["Jojo", "Naruto", "Trump"]
mahasiswa_tuple = ("Jojo", "Naruto", "Trump")
print(mahasiswa_list)
print(mahasiswa_list[0])
print(type(mahasiswa_list))
print()
print(mahasiswa_tuple)
print(mahasiswa_tuple[0])
print(type(mahasiswa_tuple))
# yang membedakan tuple dengan list hanyalah hak akses
# list ... |
#vector 1
a = [1,2,3]
#vector 2
b = [2,3,4]
#obtain the product
dot_product = a[0]*b[0] + a[1]*b[1] + a[2]*b[2]
print(dot_product) |
class Factors(object):
@staticmethod
def mfa_providers():
return [
{
'id': 'GoogleAuthenticator',
'prompt': 'Google Authenticator',
'factor_type': 'token:software:totp',
'provider': 'GOOGLE'
}, {
'i... |
# game setup
WIDTH = 1280
HEIGTH = 720
FPS = 60
TILESIZE = 64
WORLD_MAP = [
['x','x','x','x','x','x','x','x','x','x','x','x','x','x','x','x','x','x','x','x'],
['x',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','x'],
['x',' ','p',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',... |
def areSimilar(a, b):
counter = 0
if sorted(a) != sorted(b):
return False
for i in range(len(a)):
if a[i] != b[i]:
counter += 1
if counter > 2:
return False
return True
|
class AuthException(Exception):
def __init__(self):
# Call the base class constructor with the parameters it needs
message = "Sorry, you do not have access to that app. Try passing the app name explicitly with the `-a` flag. If that doesn't work, try running `gigalixir login` or check your ~/.netrc ... |
class UnionFind:
def __init__(self, size):
if size < 0:
raise Exception("Invalid size.")
self.component_size = [0] * size
self.parent = [-1] * size
self.component_count = size
self.size = size
for ind in range(size):
self.parent[ind] = -1
... |
def EN_DistributionEntropy(y,histOrKS = 'hist',numBins = None,olremp = 0):
"""
EN_DistributionEntropy Distributional entropy.
Estimates of entropy from the distribution of a data vector. The
distribution is estimated either using a histogram with numBins bins, or as a
kernel-smoothed distrib... |
# encoding: utf-8
"""A fancy version of Python's builtin :func:`dir` function.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, di... |
a, b, c, d, e = map(int, input().split())
if a > b > c > d > e:
print("D")
elif a < b < c < d < e:
print("C")
else:
print("N") |
#!/usr/bin/env python3
############################################################################################
# #
# Program purpose: Prints letter 'L' to the console. #
# Program ... |
# Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
strings = ['a', 'b', 'c', 'd']
print(strings[2]) # O(1)
#push
strings.append('e') # O(1)
#pop
strings.pop()
#Add at first index
strings.insert(0, "x") # O(n)
#splice
strings.insert(2, 'x') # O(n)
print(strings)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
APP_KEY = '66994707'
APP_SECRET = '323631d3d46128ea30605a7732bb6dfd'
COOKIE_SECRET = '2$onW88^G6I=dB4@EwXN1X!QGc&$$tiY'
AUTHORIZE_REDIRECT = 'http://localhost.com/auth/authorize'
REVOKE_REDIRECT = 'http://localhost.com/'
MONGO_URL = 'localhost'
MONGO_PORT = 27017
MONGO... |
LABEL = [
"蒸笼",
"蚂蚁",
"篮球",
"苍蝇拍",
"菠萝",
"薯条",
"耳塞",
"剪纸",
"绿豆",
"蜥蜴",
"热水袋",
"红酒",
"红枣",
"漏斗",
"公交卡",
"红豆",
"金字塔",
"狮子",
"文具盒",
"棉棒",
"海鸥",
"开瓶器",
"沙拉",
"电线",
"盘子",
"网球拍",
"烛台",
"老虎",
"药片",
"订书机",
... |
csv = "Eric John Michael Terry Graham Terry Brian"
friend_list = csv.split()
friend_list2 = "-".join(friend_list)
print(friend_list)
print(friend_list2) |
class IncorrectParametersException(Exception):
pass
class APIErrorException(Exception):
pass
|
overview_response = {
"debug": None,
"error": None,
"status": "ok",
"data": [
{
"endpoint": "api/b2b/v3/general/contract/data/info/",
"is_active": True,
"is_debug_mode": False,
"is_limited": True,
"requests_number": 100,
"se... |
# -*- coding: utf-8 -*-
class Feature(object):
def __init__(self, key, enabled, rollout_progress=0, rollout_target=0, include_users=[], exclude_users=[], last_sync=None):
self._feature = {
'key': key,
'enabled': enabled,
'rollout_progress': rollout_progress,
... |
#
# PySNMP MIB module VMWARE-RESOURCES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VMWARE-RESOURCES-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:34:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
AUTOCOMPLETE_MAPPING = {
"index_patterns":["*"],
"settings":{
"index.mapper.dynamic": True,
"analysis": {
"analyzer": {
"autocomplete": {
"tokenizer": "edge_ngram_tokenizer",
"filter": [
"lowercase"
],
... |
class MockFile():
def read(self):
return False
class RequestHandler():
def __init__(self):
self.contentType = ""
self.contents = MockFile()
def getContents(self):
return self.contents.read()
def read(self):
return self.contents
def setStatus(self, status):... |
"""
Project information.
We use this module as __init__ is a generic module that django requires to be
specifically set up.
"""
LABELS = dict()
LABELS['class'] = 'LinkedItems'
LABELS['name'] = 'django_linked_items'
LABELS['verbose_name'] = 'Linked Items'
|
# Time: O(n)
# Space: O(h)
class Solution(object):
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def inorderTraversal(root, prev, result):
if not root:
return (result, prev)
result, prev = inorderTrav... |
#right riemann sum
#function x^3
def riemannSum(a,b,n):
funct = 0
deelint = (b-a)/n
for i in range(1,n):
funct += ((a+(i*deelint))**3)
funct += (b**3)
return deelint * funct
print(riemannSum(2,9,8)) |
##
# Used to hold a book in parse results after parsing
class Book:
def __init__(self, publisher_id, rights_id, language_id,
bookshelf_id, gutenberg_book_id,
date_issued, num_downloads,
titles_id, subjects_id, type_id, authors_id, files_id):
self.publisher_... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'includes': [
'../build/common_untrusted.gypi',
'url_srcs.gypi',
],
'targets': [
{
't... |
SUCCEED_STATUS_INDEX = "3"
FAILED_STATUS_INDEX = "900"
LOCAL_IMAGE_REGISTRY = "localhost:31112"
CLUSTER_IP = "ClusterIP"
NODE_PORT = "NodePort"
|
#
# PySNMP MIB module CISCO-IPSEC-PROVISIONING-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IPSEC-PROVISIONING-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:02:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... |
"""
Problem: server
Link: https://open.kattis.com/problems/server
Source: Rocky Mountain Regional Contest (RMRC) 2014
"""
n, T = list(map(int, input().split()))
A = list(map(int, input().split()))
sum = 0
counter = 0
for i in range(len(A)):
if sum + A[i] <= T:
sum += A[i]
counter += 1
... |
'''
2) Faça um programa que receba uma senha formada de quatro números inteiros,
verifique se a senha está correta e, caso não esteja, solicite novamente a senha.
Se a senha digitada for a correta, deverá ser apresentada a mensagem “Senha Correta”,
caso contrário, “Senha Incorreta”.
'''
x = 0
y = 0
print("Cadastr... |
lista = []
for c in range(0,5):
lista.append(int(input(f'Digite um valor para a posição {c}:')))
print(f'O maior valor foi {max(lista)} nas posições', end=' ')
for i,v in enumerate(lista):
if v == max(lista):
print(f'{i}...', end='')
print(f'\nO menor valor foi {min(lista)} na posições', end=' ')
for i,... |
"""
Description of library
----------------------
This header is being used to auto-generate documentation
""" |
pessoas = {'nome': 'Gustavo', 'sexo': 'M', 'idade': 22}
for k in pessoas.keys(): #MOSTRA SÓ O NOME DAS CHAVES
print(k)
print()
for v in pessoas.values():
print(v)
print()
for k, v in pessoas.items(): # SUBSTITUI O "ENUMERATE" DAS TUPLAS E LISTAS
print(f'{k} = {v}')
|
counter_letters = lambda list: [len(x) for x in list]
animals_list = ['dog', 'cat', 'elephant']
print(counter_letters(animals_list))
sum = lambda a, b: a + b
print(sum(5, 10))
# dictionary
calculator = {
'sum': lambda a, b: a + b,
'subtraction': lambda a, b: a - b,
'multiplication': lambda a, b: a * b,
... |
def isPrime_num(n):
if n > 1:
for i in range(2,n):
if (n % i == 0):
return False
break
else:
return True
else:
return False
|
class MonteCarloTreeSearchBasedPlayer():
def __init__(self, game, nnet, args):
self.game = game
self.nnet = nnet
self.args = args
self.mcts = MCTS(game, nnet, args)
def play(self, canonicalBoard, temp=1):
for i in range(self.args.numMCTSSims):
self.mcts.search(canonicalBoard)
s = sel... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 22 11:14:18 2022
@author: EIRU0001
"""
def multiplication(x,y):
z = x*y
return z
|
class Solution:
def combine(self, n: int, k: int):
if n < k:
return []
if n == k:
return [[i for i in range(1, n+1)]]
def doCombine(low, high, k, combination, results):
if k == 0:
results.append(combination)
return
... |
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1 + n2)/2
print(f'A sua média foi {m:.1f}')
if m >= 6.0:
print('Sua média foi boa! PARABÉNS!')
else:
print('Sua média foi ruim! ESTUDE MAIS!')
#OU
print('PARABÉNS!' if m >= 6.0 else 'ESTUDE MAIS!') |
# App configuration
CAMERA = False
# Model path
MODELPATH = "utils/model/"
WEIGHTS = "yolov3.weights"
CFG = "yolov3.cfg"
COCONAMES = "coco.names"
# Video path
FOLDERNAME = "videos/"
VIDEONAME = "TownCentre.mp4"
WIDTH = 1280
HEIGHT = 720
DISTANCE = 68.5
'''
# PETS2009
FOLDERNAME = "videos/"
VIDEONAME = "PETS2009.mp4"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by pat on 5/18/18
"""
.. currentmodule::dbgdb.db.targets
.. moduleauthor:: Pat Daburu <pat@daburu.net>
Custom targets for the dbgdb package.
"""
|
test = {
'name': 'lets-count',
'points': 0,
'suites': [
{
'cases': [
{
'code': r"""
sqlite> SELECT * from fa17favnum;
69|66
sqlite> SELECT * from fa17favpets;
dog|57
cat|33
dragon|14
panda|14
tiger|14
... |
MAIN_LOOP = 'Outer loop'
LATEST_RUN_DATE = 'latests_run_date'
SAVE_BINARY = False
"""
Files
"""
OUTPUT_FOLDER = 'output/'
LOCAL_BINARY_FILE = 'incident_numbers.msgpack'
LOCAL_JSON_FILE = 'incident_numbers.txt'
WORKBOOK = 'workBook.xlsx'
"""
Toolkit status
"""
NEW = 10
RECEIVED = 11
ANALYSED = 12
ESTIMATED = 13
APPROV... |
def entrada():
experimento = input().split(' ')
quant = int(experimento[0])
animal = experimento[1]
return quant, animal
def experiencias(numero_de_teste):
quantidade_de_cobaias = dict()
for teste in range(numero_de_teste):
quantidade, cobaia = entrada()
if cobaia not in quanti... |
# Converts an enumeration to a printable string.
#
def enumToString(constants, enum, elem):
all = constants.all_values(enum)
for e in all.keys():
if str(elem) == str(all[e]):
return e
return "<unknown>"
|
#! -*- coding: utf-8 -*-
class MlParams():
"""Class MlParams
* 環境設定や学習パラメータの基底クラス(パラメータテンプレート)
* 各パラメータは下記のキーで構成する
* description: パラメータの説明
* value: パラメータの値
* configurable: ブラウザ上での設定変更可否(True:変更可,False:変更不可)
* selectable: パラメータ変更時の選択可否(True:ドロップダウンで変更,False:テキストボックスで変更)
configurable=Tr... |
def disp_bot_thoughts(self,ball_prediction,target,car_location,target_future):
# Get Ball Prediction Line
ball_path = [0] * 300
for s in range(300):
slice_location = ball_prediction.slices[s]
ball_path[s] = slice_location.physics.location
# Draw s... |
# Copyright 2016-2022 The FEAGI 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 applica... |
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 19 11:04:49 2021
@author: Lakhan Kumawat
"""
def fibonacci(n):
s=1
const=n
mylist=[0,1]
#print(len(mylist)-1)
while(n!=0):
for i in range(len(mylist)-1):
s+=mylist[i]
if(s<const):
mylist.append... |
class Solution:
def myPow(self, x,n):
ans = x**n
if abs(ans) <= 10**4:
return ans |
"""
Funções
São rotinas que executam algo.
Podemos criar funções personalizadas de acordo com nossa necessidade.
Ex:
def mostraLinha():
print('-----------------------')
Onde def -> É Definir Função
Juntamente com a função temos o parâmetro.
Ex:
def mensagem(msg):
print('-----------------------')
print(msg)
... |
class Relatorio:
def gera_relatorio(self):
print('Relatório geral')
class RelatorioUsuarios(Relatorio):
def gera_relatorio(self):
print('Relatório dos usuários')
class RelatorioCustos(Relatorio):
def gera_relatorio(self):
print('Relatório de custos')
relatorio1 = RelatorioUsuarios... |
def render_result_codes(result_codes, timeout_count, connection_error_count):
rc = ""
for k, v in result_codes.iteritems():
rc += "%s: %s " % (k, v)
if timeout_count > 0:
rc += 'Timeouts: %s ' % timeout_count
if connection_error_count > 0:
rc += 'Connection Errors: %s... |
def add_e2e_args(parser):
parser.add_argument("--cuda", default=False, action="store_true")
parser.add_argument("--random_seed", default=6700417, type=int)
parser.add_argument("--model_name", type=str)
parser.add_argument("--load_from_pretrain_s2t", type=str)
parser.add_argument("--load_from_pretrai... |
__all__ = [
'ConfigItemRequiredException',
'ConfigItemValidationException'
]
class ConfigItemRequiredException(Exception):
def __init__(self, key):
super(ConfigItemRequiredException, self).__init__("Config item '{}' is required".format(key))
class ConfigItemValidationException(Exception):
... |
"""
14579. 덧셈과 곱셈
작성자: xCrypt0r
언어: Python 3
사용 메모리: 29,380 KB
소요 시간: 64 ms
해결 날짜: 2020년 9월 25일
"""
def main():
a, b = map(int, input().split())
acc = 0
res = 1
for i in range(1, a):
acc += i
for i in range(a, b + 1):
acc += i
res *= acc % 14579
res %= 14579
... |
f = list(map(int, input().split()))
x = int(input())
y = 0
for i in range(0, len(f) - 1):
y += f[i] * (len(f)-i-1) * x**(len(f)-i-2)
print(y) |
"""If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.
The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000."""
def problem(n):
result = 0
for i in range(0, 1000, n):
result = result+i
return result
def main():
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
lst1 = [11, 22, 33, 44]
lst2 = ['ok', 'hi', 'Candy', 'Zoo']
lst1.append(99)
lst1.extend(lst2)
lst1.remove(11)
print("lst1.pop(-2)==>", lst1.pop(-2))
lst1.reverse()
print("lst1==>", lst1)
lst2.insert(2, 'OK')
print("\ncount('ok')==>", lst2.count('ok'))
lst2.sort()
print(... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ViewIdMappingProtoProtocolAccessInfo(object):
"""Implementation of the 'ViewIdMappingProto_ProtocolAccessInfo' model.
TODO: type model description here.
Attributes:
iscsi_access (int): Access control for iSCSI protocol for this view.
... |
class Solution:
def canPlaceFlowers(self, flowerbed, n) -> bool:
# I spent lots of time on this question.
# there are two exception: leftest is zero and rightest is zero.
length = len(flowerbed)
if length < 1 or length < n:
return False
c = 0
... |
#!/usr/bin/env python
#####################################
# Installation module for Wifite2
#####################################
# AUTHOR OF MODULE NAME
AUTHOR="Dave Kennedy (@HackingDave)"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module will install/update wifite2 - a tool for wireless auditing"
# INSTALL TY... |
print("Test WHILE")
total = 0
while total <= 100:
print("%d Interação de Loop\n" %total)
total += 1
print("End")
|
class Config:
def config():
result ={
"mongoConnect":"mongodb+srv://bfxtest:bfxtest@bitfinextest.blkxg.mongodb.net/bfxtest?retryWrites=true&w=majority",
"frrBottoken":"1481397802:AAGDYZZ6OfEGQX4dCDI4eJooKdetdb2-Smc",
"apiBottoken":"",
"bfxKey":"xuhKUYB70yb... |
# This program displays the population for each of the next five years in the US given that
# One birth every 7 seconds
# One death every 13 seconds
# One new immigrant every 45 seconds
# 365 days = 31536000 seconds
numberOfYears = 5
currentPopulation = 312032486
numberOfSecondsIn1year = 31536000
birthsPerYear = num... |
# Copyright 2017 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... |
def sum_below(n: int, condition: callable) -> int:
return sum(filter(condition, range(1, n)))
def condition(whitelist_numbers: list) -> int:
def filter_condition(n: int, whitelist_numbers=whitelist_numbers) -> bool:
for whitelist_number in whitelist_numbers:
if n % whitelist_number == 0:
... |
#
# PySNMP MIB module CTRON-ENVIRONMENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-ENVIRONMENT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:26:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 12 19:43:35 2019
@author: Parikshith.H
"""
class customer:
__counter=1000
def __init__(self,NAME,NUM):
self.__id=customer.__counter+1
self.__name=NAME
self.__num=NUM
customer.__counter=customer.__counter+1
def get_id(s... |
# as found on reddit
get_vertical = lambda lst: [[y[x] for y in lst] for x in range(len(lst[0]))]
get_value = lambda x, n, m: n if x.count('0') > x.count('1') else m
calc_bin = lambda lst: int(''.join([str(x) for x in lst]), 2)
with open("day32021_puzzle_input.txt", 'r') as file:
data = file.read().splitlines() ... |
_base_ = "./ss_v1_dibr_mlBCE_FreezeBN_woCenter_refinePM10_ape.py"
OUTPUT_DIR = "output/self6dpp/ssLM/ss_v1_dibr_mlBCE_FreezeBN_woCenter_refinePM10/cat"
DATASETS = dict(
TRAIN=("lm_real_cat_train",), TRAIN2=("lm_pbr_cat_train",), TRAIN2_RATIO=0.0, TEST=("lm_real_cat_test",)
)
MODEL = dict(
WEIGHTS="output/gdrn/l... |
#https://leetcode.com/problems/maximum-product-of-three-numbers/
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums)
return max(a[0] * a[1] * a[2], b[0] * b[1] * a[0]) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 27 17:31:02 2018
@author: edanrein
"""
__version__ = "0.1.5.3"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.