content stringlengths 7 1.05M |
|---|
class Solution:
def isHappy(self, n: int) -> bool:
def squaredSum(n: int) -> bool:
sum = 0
while n:
sum += pow(n % 10, 2)
n //= 10
return sum
slow = squaredSum(n)
fast = squaredSum(squaredSum(n))
while slow != fast:
slow = squaredSum(slow)
fast = squar... |
def safeDict(elem, array_of_keys, default=""):
try:
for key in array_of_keys:
elem = elem[key]
return elem
except Exception as e:
return default |
# Those constants are used from the library only
BASE_PAL_URL = "https://pal-{}.adyen.com/pal/servlet"
PAL_LIVE_ENDPOINT_URL_TEMPLATE = "https://{}-pal-live" \
".adyenpayments.com/pal/servlet"
BASE_HPP_URL = "https://{}.adyen.com/hpp"
ENDPOINT_CHECKOUT_TEST = "https://checkout-test.adye... |
# -*- coding: utf-8 -*-
"""
@file
@brief Data from INSEE
**Source**
* ``irsocsd2014_G10.xlsx``: ?
* ``fm-fecondite-age-mere.csv``: `INSEE Bilan Démographique 2016 <https://www.insee.fr/fr/statistiques/1892259?sommaire=1912926>`_
* ``pop-totale-france.xlsx``: `INED Population totale
<https://www.ined.fr/fr/tout-savo... |
__all__ = ['VERSION']
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
VIDEO = 'youtube#video'
YOUTUBE_VIDEO_URL = 'https://www.youtube.com/watch?v='
VERSION = '4.0.0'
|
# mailbox_or_url_parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'mailbox_or_urlFWSP AT DOT COMMA SEMICOLON LANGLE RANGLE ATOM DOT_ATOM LBRACKET RBRACKET DTEXT DQUOTE QTEXT QPAIR LPAREN RPAREN CTEXT URLmailbox_or_url_list : mailbox_or_url_list... |
"""
142. Linked List Cycle II
Medium
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote t... |
# coding: utf8
{
'\n Ao clicar no botão "enviar" abaixo, você estará concordando com os termos de uso acima descritos': '\n Ao clicar no botão "enviar" abaixo, você estará concordando com os termos de uso acima descritos',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the r... |
def sum(a, b):
"""Returns sum
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
sum -- Sum
"""
return a + b
def difference(a, b):
"""Returns difference
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
... |
class UnionFind:
def __init__(self, n):
self.n = n
self.parent = [i for i in range(n + 2)]
def find(self, a):
path = []
while self.parent[a] != a:
path.append(a)
a = self.parent[a]
for p in path:
self.parent[p] = a
... |
class Produto:
def __init__(self, codigo, descricao, valorUni):
self.codigo = codigo
self.descricao = descricao
self.valorUni = valorUni
class NotaFiscal:
def __init__(self, nroNF, nomeCliente, itensNF):
self.nroNF = nroNF
self.nomeCliente = nomeCliente
... |
print(add(5, 3))
def add(x, y):
return x+y
|
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
def dfs(root):
if root:
dfs(root.left)
nu... |
print('----->DEAFIO 62<-----')
num = int(input('Digite o primeiro termo da PA: '))
rz = int(input('Qual a razão da PA: '))
cont = 0
while cont < 10:
num += rz
print(num)
cont += 1
mais = 1
while mais != 0:
mais = int(input('Deseja ver mais quantos termos: '))
while cont < 10 + mais:
num ... |
class Solution:
# O(n) time | O(1) space - where n is the length of the input list
def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
maxDuration, startTime, slowestKey = 0, 0, ''
for i in range(len(releaseTimes)):
pressTime = releaseTimes[i] - startTime
... |
# -*- coding: utf-8 -*-
formatted_body_template = """<div id="vlivepy-post-html" style="width:728px;">
<p><a href="###LINK###">###LINK###</a></p>
<div style="padding:15px 0;border-bottom:1px solid #f2f2f2">
<span class="author" style="font-weight:600;color:#111;font-size:14px;display:block">###AUTHOR###</span>... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"run_params": "000_exp_02_pretrained.ipynb",
"experiment": "000_exp_02_pretrained.ipynb",
"DatasetBuilder": "01_dataset_builder.ipynb",
"StatementClassifier": "02_statement_classife... |
A, B = map(int, input().split())
S = str(input())
flag = True
if not S[:A].isdecimal():
flag = False
elif S[A] != '-':
flag = False
elif not S[-B:].isdecimal():
flag = False
if flag:
print('Yes')
else:
print('No')
|
def configure_tx_chains(txChains, streamNum, mcsIdx):
txChains = txChains.lower()
RATE_MCS_ANT_A_MSK = 0x04000
RATE_MCS_ANT_B_MSK = 0x08000
RATE_MCS_ANT_C_MSK = 0x10000
RATE_MCS_HT_MSK = 0x00100
mask = 0x0
usedAntNum = 0
if "a" in txChains:
mask |= RATE_MCS_ANT_A_MSK
... |
# 19. Remove Nth Node From End of List
# Time: O(n)
# Space: O(1)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
slow = head
fast ... |
"""
A particular zoo determines the price of admission based on the age of the guest.
Guests 2 years of age and less are admitted without charge.
Children between 3 and 12 years of age cost $14.00.
Seniors aged 65 years and over cost $18.00.
Admission for all other guests is $23.00.
Create a program that
begins by read... |
# Cloud Automation Services SDK for Python
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
class Region(object):
"""
Class for Region methods.
Used to discover regions for all fabric constructs (images, mappings,
networks and storage.)
"""
def __in... |
'''
URL: https://leetcode.com/problems/find-lucky-integer-in-an-array/
Difficulty: Easy
Description: Find Lucky Integer in an Array
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky in... |
'''
给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not r... |
#string.py
str1 = "Hello"
str2 = 'John'
print(type(str1))
print("\"Good\\Job\"")
greet = "Hello John"
print(greet[1])
print(greet[-4])
print(greet[0:3])
print("bad" + "apple")
print("wt" + "d" * 5)
print(len("pine"))
print(type(str(123))) |
class DimensionError(Exception):
"""Represents an error involving matrix dimensions."""
class CoefficientError(Exception):
"""Represents an error involving transfer function coefficients."""
class StateSpaceError(Exception):
"""Represents a miscellaneous error involving `StateSpace`."""
class ResultEr... |
#!/usr/bin/env python
NAME = 'Reblaze (Reblaze)'
def is_waf(self):
if self.matchcookie(r'^rbzid='):
return True
if self.matchheader(('Server', 'Reblaze Secure Web Gateway')):
return True
# Now going for attack phase
for attack in self.attacks:
r = attack(self)
if r is... |
"""
Enumerated data types useful for data conversion
Created: 15 May 2018
Eva Berlot & Naveed Ejaz
"""
class BidsTags:
tSubj = 'sub-'
tSes = 'ses-'
tSesID = 'ses-id'
tParticipantID = 'participants-id'
tFunc = 'func'
tFuncEvents = 'tas... |
#
# PySNMP MIB module TIME-AGGREGATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIME-AGGREGATE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:09:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
class ExtendedTextAttributes(object):
def __init__(
self,
text, matched_text, canonical_url, description, title, jpeg_thumbnail, context_info
):
self._text = text
self._matched_text = matched_text
self._canonical_url = canonical_url
self._description = des... |
#!/usr/bin/env python3
"""
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by
all of the numbers from 1 to 20?
https://projecteuler.net/problem=5
"""
|
soma = 0
cont = 0
for impar in range(1,501,2):
if impar % 3 == 0:
cont = cont + 1
soma = soma + impar
print('\33[35mA soma de todos os {} valores solicitados é {}.'.format(cont,soma))
|
_V = {}
# Stages: game, rounds
# State: probability, probability of co-operating
# Action:
# V(t,p) gives maximum expected value from starting game t with probability p of cooperating
def V(game, probability):
if game is 10:
return 0, 0
else:
if (game, probability) not in _V:
coope... |
help = """
Your project has been created!
If you have not done so already, create a conda environment for your new
project with:
cd {{cookiecutter.repo_name}}
conda create --name {{cookiecutter.repo_name}} python=3.x
conda activate {{cookiecutter.repo_name}}
conda env export > environment.yml
Install your new proje... |
# -*- coding: utf-8 -*-
# Este programa usa um loop que itera por todos os valores de 1 a N e checa se o valor não está na lista de números,
# caso o valor não esteja ele é exibido.
# Input do N
n = int(input())
# Input da lista de números que representam as peças
v = list(map(int, input().split()))
# Loop para os ... |
PROPER_NOUNS = {
"Αγγ",
"Ἀθῆναι",
"Αἴγυπτος",
"Ἀλέξιον",
"Ἀλέξιος",
"Ἀλεξίου",
"Ἀντιοχεία",
"Ἀντιοχείᾳ",
"Ἀντιόχεια",
"Ἀντιόχειαν",
"Ἀντιοχείας",
"Ἀραβία",
"Ἀραβίᾳ",
"Ἀσία",
"Ἀσίᾳ",
"Ἀτλαντικόν",
"Ἀφρικῇ",
"Βρεταννία",
"Βρεττανία",
"Γαλλία"... |
BASE_DIR = './'
environ = {
'KPK_DATA': '/home/kpk/data',
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
}
KPK_DATA = environ.get('KPK_DATA')
# print(KPK_DATA)
# _KPK_DATA = environ['KPK_DATA']
# print(_KPK_DATA)
# os.environ.get('KPK_DATA') or BASE_DIR
#
# os.environ.get('KPK_DATA') ... |
class Reference:
def __init__(self, id, campaign_id, name, details, created, modified):
self.id = id
self.campaign_id = campaign_id
self.name = name
self.details = details
self.created = created
self.modified = modified
|
NONE = 0x000000000
# Posting Permissions
CREATE_POST = 0x000000001
EDIT_POST = 0x000000002
DELETE_POST = 0x000000004
# Documents Permissions
UPLOAD_DOCUMENT = 0x000000008
EDIT_DOCUMENT = 0x000000010
DELETE_DOCUMENT = 0x000000020
# User Account Permissions
CREATE_USER = 0x000000040
EDIT_USER = 0x000000080
DELETE_USER... |
class Car:
wheels = 4 # Class (Static) Variables before __init__
def __init__(self):
self.com = "BMW" # Instance Variables inside __init__
self.mil = "10"
c1 = Car()
c2 = Car()
Car.wheels = 5 # The value of all ... |
"""
author : @akash kumar
github : https://github/Akash671
string fun:
string.replace(sub_old_string,new_sub_string,count)
string.count(your_string)
"""
def solve():
#n,m=map(int,input().split())
#n=int(input())
#a=list(map(int,input().split()[:n]))
#s=str(input())
#a,b=input().split()
n=int(input(... |
lista = []
valor = lista.append(int(input('Digite um valor: ')))
while True:
continuação = str(input('Quer continuar? [S/N] ')).strip()[0].upper()
if continuação in 'N':
break
elif continuação in 'S':
valor = lista.append(int(input('Digite um valor: ')))
else:
continuação1 = str(... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ThrottlingConfiguration(object):
"""Implementation of the 'ThrottlingConfiguration' model.
Specifies the throttling configuration parameters.
Attributes:
fixed_threshold (long|int): Fixed baseline threshold for throttling. This is
... |
class Solution:
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
idx1, idx2 = len(words), len(words)
result = len(words)
for i in range(len(words)):
if wor... |
class HParams(object):
def __init__(self,**default_param):
temp_local=self.__dict__
for key in default_param.keys():
temp_local[key]=default_param[key]
def create_hparams():
"""Create model hyperparameters. Parse nondefault from given string."""
hparams = HParams(
... |
'''
Discuss structure:
Getting input from user
Formatting the input (multiply by 100 then convert to integer)
Getting total amount of change (amount paid minus bill)
Getting dollars of change (divide by 100 then convert to integer)
Getting the amount of change leftover (either change minus dollars times 100 or ch... |
class AzureCloudProviderResourceModel(object):
def __init__(self):
self.azure_application_id = '' # type: str
self.azure_mgmt_network_d = '' # type: str
self.azure_mgmt_nsg_id = '' # type: str
self.azure_application_key = '' # type: str
self.region = '' # type: str
... |
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2021. by Daniel Barrejon, UC3M. +
# All rights reserved. This file is part of the Shi-VAE, and is released under the +
# "MIT License Agreement". Please see the LICE... |
# Criando um set com elementos:
# Utiliza-se de chaves, entretanto não é um dicionário, visto que não possui chave nem um índice, possuindo apenas valores.
Set1 = {1, 2, 3, 4, 5}
# Criando um set vazio
Set2 = set()
# Pode ser utilizado para remover elementos duplicados de uma lista, visto que só pode conter element... |
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
r, s, t = -1, 0, 0
for i in range(0, len(gas)):
t = t + gas[i] - cost[i]
s = s + gas[i] - cost[i]
... |
# Given a binary matrix representing an image, we want to flip the image horizontally, then invert it.
# To flip an image horizontally means that each row of the image is reversed.
# For example, flipping [0, 1, 1] horizontally results in [1, 1, 0].
# To invert an image means that each 0 is replaced by 1, and each 1 ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
_SNAKE_TO_CAMEL_CASE_TABLE = {
"availability_zones": "availabilityZones",
"backend_services": "backendServices",
"beanstalk... |
# guess file size : https://softwareengineering.stackexchange.com/q/204417
# https://stackoverflow.com/a/1094933
def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
... |
# Source : https://leetcode.com/problems/rectangle-overlap/
# Author : foxfromworld
# Date : 07/04/2021
# Second attempt
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec1[0] == rec1[2] or rec2[0] == rec2[2] or\
rec2[1] == rec2[3] or rec1[1] == rec1[3]:
... |
class Project():
def __init__(self, id_project, name, session_counter, token):
self.id_project = id_project
self.name = name
self.session_counter = session_counter
self.token = token
class Session():
def __init__(self, id_session, index, dt_start, dt_end, is_active, is_favorite,... |
#=======================================================================
# Author: Isai Damier
# Title: Selection Sort
# Project: geekviewpoint
# Package: algorithm.sorting
#
# Statement:
# Given a disordered list of integers (or any other items),
# rearrange the integers in natural order.
#
# Sample Input: [18... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = 3
if a > 2:
print("H")
else:
print("L") |
"""
1720. Decode XORed Array
https://leetcode.com/problems/decode-xored-array/
There is a hidden integer array arr that consists of n non-negative integers.
It was encoded into another integer array encoded of length n - 1,
such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
m = float(raw_input());
t = m * input() /100;
x = m * input() /100;
totalCost = round(m + x + t);
print ('The total meal cost is' " " + str(int(totalCost)) + " " 'dollars.') |
# program to match key values in two dictionaries.
x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items()) & set(y.items()):
print('%s: %s is present in both x and y' % (key, value))
|
class Number(object):
def __init__(self, value):
if value % 2 != 0:
self.even = self._odds_even
else:
self.even = self._even
def _even(self):
print("even")
return True
def _odds_even(self):
print("not odd")
return False
a = Number... |
WIDTH = 87
HEIGHT = 87
FIRST = 0x20
LAST = 0x7f
_font =\
b'\x00\x4a\x5a\x02\x44\x60\x44\x52\x60\x52\x02\x44\x60\x44\x60'\
b'\x60\x44\x02\x52\x52\x52\x3e\x52\x66\x02\x44\x60\x44\x44\x60'\
b'\x60\x02\x44\x60\x44\x52\x60\x52\x02\x46\x5e\x46\x59\x5e\x4b'\
b'\x02\x4b\x59\x4b\x5e\x59\x46\x02\x52\x52\x52\x44\x52\x60\x02'\
b'... |
#!/usr/bin/python
## Ejercicio 1 reverse Polish Notation
## Autor: Fabiola Tapara Quispe
## Description: Mediante el siguiente metodo recibe un string con datos y signos con operaciones basicas (+, -, *, /) usando una Pila como estructura.
## * Date: 15/11/21
def sum (a, b):
return a + b
def resta (a, b):
... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author:nikan
@file: asyncio_utils.py
@time: 2018/5/18 下午6:06
"""
async def add_future_callback(fut, success_callback, fail_callback=None, need_fut_as_success_cb_args=True):
"""
adding a callback after future completed
:param fut:
:param callback:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 4 23:30:51 2017
@author: coskun
Problem 1 - Paying Debt off in a Year
10.0 points possible (graded)
Write a program to calculate the credit card balance after
one year if a person only pays the minimum monthly payment
required by the credit car... |
def return_category_with_more_spending(transactions):
category_transactions = transactions.groupby(by=["column_category"])[
"column_installment_value"
].sum()
return category_transactions.idxmax(), category_transactions.max()
|
# Copyright (c) 2020 Thomas Holland (thomas@innot.de)
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Refer to the LICENSE file which is part of the AdvPiStepper distribution or
# to https://opensource.org/licenses/MIT for a text of the license.
#
#
"""
Definitions used by the AdvPiSte... |
# Problem Statement
# Given an array of positive numbers and a positive number ‘S’,
# find the length of the smallest contiguous subarray
# whose sum is greater than or equal to ‘S’.
# Return 0, if no such subarray exists.
# Example 1:
# Input: [2, 1, 5, 2, 3, 2], S = 7
# Output: 2
# Explanation: The smallest subarra... |
def is_palindrome(n: int) -> bool:
s = str(n)
h = int(len(s) / 2)
s1 = s[:h]
s2 = s[h:][::-1]
is_palindrome = True
for i in range(h):
if s1[i] != s2[i]:
is_palindrome = False
return is_palindrome
def solution() -> int:
largest_palindrome = 0
for i in range(100, ... |
''' Check valid age
Write a program that takes age fro the user and then decide whether the age is between 18 to 24. If so, then it will display the message "You can apply for youth festival program". Otherwise, display the message "Sorry, you cannot apply".
If age >= 18 and age <= 24 # Not correct
If age = 18 and ... |
#!/usr/bin/python3
#-*- coding: utf-8 -*-
# This code is PEP8-compliant. See http://www.python.org/dev/peps/pep-0008/.
"""
Wyrd In: Time tracker and task manager
CC-Share Alike 2012 © The Wyrd In team
https://github.com/WyrdIn
This module implements the Deadline class.
"""
class Deadline():
"""
Deadline is... |
dtypes = {
'float32': 'float',
'float64': 'double',
'complex64': 'complex_float',
'complex128': 'complex_double'
}
""" Possible dptypes for spaces and c equivalents """
compatible_dtypes = { # name: (tuple of compatible dtypes)
'float32': ('float32', 'complex64'),
'float64': ('float64', 'compl... |
# M0_C4 - Peak Volumes
def get_peak_volumes(volumes):
# Write your code here
return "not implemented"
#### DO NOT TOUCH CODE BELOW THIS LINE ####
if __name__ == '__main__':
"""This code is for manual testing and is provided for your convenience."""
test_volumes = input("Input space-separated list of v... |
#Algorithm Case Study
def naive(a,b):
x=a; y=b
z =0
while(x > 0):
z = z+y
x = x-1
return z
def testnaive():
i=0
while(i < 10):
j=0
while(j < 10):
print(i,j)
print(naive(i,j))
j += 1
i += 1
... |
"""
Entradas
dia-->int
mes-->int
Salidas
singno zodiacal-->float
"""
dia = int (input ('Digite el numero de dia: '))
mes = int (input ("Digite el numero de mes: "))
if (dia>=21 and mes==3) or (dia<=20 and mes==4):
print ('Aries')
if (dia>=24 and mes==9) or (dia<=23 and mes==10):
print ('Libra')
if (dia>=21 and... |
capacity = int(input())
income = 0
command = input()
while command != "Movie time!":
group_count = int(command)
if group_count > capacity:
print("The cinema is full.")
print(f"Cinema income - {income} lv.")
exit()
capacity -= group_count
group_tax = group_count * 5
if gro... |
#pretty print method
def indent(elem, level=0):
i = "\n" + level*" "
j = "\n" + (level-1)*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for subelem in elem:
... |
# -*- coding: utf-8 -*-
# This work is licensed under the MIT License.
# To view a copy of this license, visit https://www.gnu.org/licenses/
# Written by Taher Abbasi
# Email: abbasi.taher@gmail.com
class WrongSide(Exception):
pass |
skywater_metal1 = {"layer": 68, "datatype": 20 }
skywater_metal2 = {"layer": 69, "datatype": 20 }
skywater_metal3 = {"layer": 70, "datatype": 20 }
skywater_metal4 = {"layer": 71, "datatype": 20 }
skywater_metal5 = {"layer": 72, "datatype": 20 }
|
rc = 0
def setup():
size(600, 600)
smooth()
background(0)
font = loadFont("Gadugi-Bold-48.vlw")
textFont(font, 48)
def draw():
global rc
translate(width/2, height/2)
pushMatrix()
rotate(rc)
fill(255)
text("Black", mouseX - width/4, mouseY - height/4)
popMa... |
"""
Hamming Numbers
URL: https://www.codewars.com/kata/526d84b98f428f14a60008da/python
A Hamming number is a positive integer of the form 2^i, 3^j, 5^k,
for some non-negative integers i, j, and k.
Write a function that computes the nth smallest Hamming number.
Specifically:
The first smallest Hamming number is 1... |
class MessagesSerializer:
fields = ['id', 'topic', 'payload', 'attributes', 'bulk']
def serialize(self, messages):
return [self._serialize_fields(message) for message in messages]
def _serialize_fields(self, message):
return {field: getattr(message, field, None) for field in self.fields}
|
# -*- coding: utf-8 -*-
# @Author: Anderson
# @Date: 2018-09-01 22:04:38
# @Last Modified by: Anderson
# @Last Modified time: 2018-09-14 15:55:53
class DS(object):
def __init__(self, N):
self.__id = list(range(0, N))
def is_connected(self, parent, child):
pid = ord(parent) - ord('A')
... |
#
# PySNMP MIB module Juniper-IPV6-PROFILE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Juniper-IPV6-PROFILE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:03:09 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
r'''
Copyright 2015 Google Inc. 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 law or agreed to i... |
print("My name is Jessica Bonnie Ayomide")
print("JJJJJJJJJJJJJ BBBBBBBBBB A")
print(" J B B A A")
print(" J B B A A")
print(" J B B A A")
print(" J B B A A")
print(" J BB... |
#!/usr/bin/env python3
def main():
arr = []
fname = sys.argv[1]
with open(fname, 'r') as f:
for line in f:
arr.append(int(line.rstrip('\r\n')))
quicksort(arr, start=0, end=len(arr)-1)
print('Sorted list is: ', arr)
return
def quicksort(arr, start, end):
if end - start <... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"test_eq": "00_core.ipynb",
"listify": "00_core.ipynb",
"test_in": "00_core.ipynb",
"test_err": "00_core.ipynb",
"configure_logging": "00_core.ipynb",
"setup_dataf... |
# -*- coding: utf-8 -*-
"""@package Methods.Machine.SlotWind.comp_surface_wind
Slot Winding Computation of surface (Numerical) method
@date Created on Wed Jul 25 14:22:33 2018
@copyright (C) 2014-2015 EOMYS ENGINEERING.
@author pierre_b
"""
def comp_surface_wind(self):
"""Compute the Slot winding surface (by nume... |
# code
'''python'''
class Solution(object):
def lengthOfLastWord(self, s):
self.s=s
string = self.s.strip().split(' ')[-1]
return len(string)
|
def clean_sentence(output, data_loader):
start_word = data_loader.dataset.vocab.start_word
end_word = data_loader.dataset.vocab.end_word
unk_word = data_loader.dataset.vocab.unk_word
words = []
for i in range(len(output)):
word_idx = output[i]
word = data_loader.dataset.vocab.idx2wo... |
#
# PySNMP MIB module TPLINK-SSH-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPLINK-SSH-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:25:53 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... |
REGULAR_MARGIN_REQUIREMENT = 0.25
LEVERAGED_MARGIN_REQUIREMENT = 0.75
def max_margin(leveraged_value, regular_value, percentage_of_leveraged_drop,
percentage_of_regular_drop, current_loan):
leveraged_value_after_drop = leveraged_value * (1 - percentage_of_leveraged_drop)
regular_value_after_dro... |
def trans_char_number(text, q2b=True):
table = {ord(u'\uff41'): ord('a'), ord(u'\uff42'): ord('b'), ord(u'\uff43'): ord('c'), ord(u'\uff44'): ord('d'),
ord(u'\uff45'): ord('e'), ord(u'\uff46'): ord('f'), ord(u'\uff47'): ord('g'), ord(u'\uff48'): ord('h'),
ord(u'\uff49'): ord('i'), ord(u'\u... |
class Node:
def __init__(self, idx):
self.idx = idx
self.out = set() # zbiór sąsiadów
def connect_to(self, v):
self.out.add(v)
def lex_bfs(graph):
lex_order = [1]
lex_unvisited_list = []
first_vertex_neighbours = set()
others = set()
for i in range(2, ... |
class Solution:
def __init__(self):
pass
# o(mn)
def print_lcs(self, str1, str2):
m = len(str1)
n = len(str2)
if n == 0 or m == 0:
return 0
# declare an two dimension array store calculated dp value of lcs(str1[i]
R = [[None] * (n + 1) for i in xr... |
lines = None
with open('day07/input.txt') as f:
lines = f.readlines()
line = lines[0]
arr = list(map(lambda s: int(s), line.split(",")))
cost = []
prev = 0
q = 0
for i in range(2000):
cost.append(prev + q)
prev = prev + q
q += 1
min = 99999999999999
for pos in range(1500):
sum = 0
for x in ar... |
target = "xilinx"
action = "synthesis"
syn_device = "xc7k325t"
syn_grade = "-2"
syn_package = "ffg900"
syn_top = "cm0_busy_wait_top"
syn_project = "cm0_busy_wait_top"
syn_tool = "vivado"
modules = {
"local" : [ "../../../top/kc705_busy_wait/verilog" ],
}
|
class DataObject:
def __init__(self, read_data=True):
if read_data:
self._run_methods('read')
self._run_methods('parse')
def _run_methods(self, method_type):
for method in [m for m in dir(self) if m.startswith('_{}_'.format(method_type))]:
getattr(self, me... |
def sumUpNumbers(inputString):
numbers = []
curr = ""
for i in inputString:
try:
x = int(i)
curr += i
except:
if curr != "":
numbers.append(curr)
curr = ""
if curr != "":
numbers.append(curr)
return sum([in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.