content stringlengths 7 1.05M |
|---|
# create the __init__ function for class car
class Car:
def __init__(self, make, model, year, weight):
self.make = make
self.model = model
self.year = year
self.weight = weight
# initialise the car with attributes for make, model, year and weight
my_car = Car('mazda', '6', 2010, 15... |
def get_OP_matrix(self):
"""Return the OP matrix
Parameters
----------
self : VarLoadCurrent
A VarLoadCurrent object
Returns
-------
OP_matrix : ndarray
Operating Points matrix
"""
return self.OP_matrix
|
DEBUG = True
SECRET_KEY = "fake-key"
INSTALLED_APPS = [
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.staticfiles",
"graphql_auth",
]
|
range(10) # stores the value of all numbers 0- 1 less than selected
range(2,8) # stores the value of all numbers first to 1 less than that selected
range(2,18,2) # stores the value of the first number - 1 less than the 2nd number, at the interval of the 3rd
# num1, starting number
# num2, number it will not pass (o... |
class Solution:
def wordPattern(self, pattern, str):
"""
:type pattern: str
:type str: str
:rtype: bool
"""
if len(pattern) != len(str.split(" ")):
return False
pmap = {}
smap = {}
for i in range(len(pattern)):
ppreIndex = pma... |
n = int(input())
l = list(map(int, input().split()))
l.sort()
print(" ".join(map(str, l))) |
'''
Distribution Statement A: Approved for public release: distribution unlimited. ; May 3, 2016
This software was developed under the authority of SPAWAR Systems Center
Atlantic by employees of the Federal Government in the course of their official
duties. Pursuant to title 17 Section 105 of the United States Code th... |
mat1 = [[1,2,3],[4,5,6]]
mat2 = [[7,8,9],[6,7,3]]
result= [[0,0,0],[0,0,0]]
for i in range(len(mat1)):
for j in range(len(mat2[0])):
for k in range(len(mat2)):
result[i][j]+= mat1[i][k]*mat2[j][k]
for r in result:
print(r)
|
#
# PySNMP MIB module FILTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FILTER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:00:00 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, 09:... |
colors = {
"dark-blue": "#0F2080",
"pink": "#A95AA1",
"medium-blue": "#607381",
"orange": "#C47A4F",
"green": "#194D31",
"purple": "#601A4A",
"light-blue": "#7C9BA5",
"tan": "#AE9C45",
"grey": "#646464",
"black": "#000000",
}
color_arr = [
"#0F2080",
"#A95AA1",
"#607... |
"""
Автор: Моисеенко Павел, группа № 1, подгруппа № 2.
Задание: реализовать программу шифрующую строку, задаваемую
пользователем, с помощью алгоритма шифрования ROT13.
"""
def rot13(letter):
if ord("a") + 13 > ord(letter) >= ord("a"):
return chr(ord(letter) + 13)
elif ord("z") >= ord(let... |
# --------------
##File path for the file
file_path
def read_file(path):
file = open(path,'r')
sentence = file.readline()
file.close()
return sentence
sample_message = read_file(file_path)
#Code starts here
# --------------
#Code starts here
message_1 = read_file(file_path_1)
message_2 =... |
# coding=utf-8
class Constant(object):
NEW_LINE = "\n"
TAB_LINE = "\t"
DEFAULT_DEBUG_ID = "debug_0"
NPU_DEBUG_ID_1 = "debug_1"
GRAPH = "graph"
DUMP = "dump"
class Suffix(object):
JSON = '.json'
CSV = '.csv'
H5 = '.h5'
class Pattern(object):
GE_PROTO_GR... |
class FSANode:
"""
Class for Finite State Automaton(FSA) Node. Trie node definitions inherit from this class.
"""
__slots__ = 'id', 'val', 'children', 'eow', 'count'
def __init__(self, _id, val):
""" Initialize a Finite State Automaton(FSA) Node.
Parameters
----------
... |
"""Download command exceptions."""
class DownloadTemplateError(Exception):
"""Error that indicates an issue with the template.
Caused by download overwriting previously downloaded files.
"""
|
class NetworkXZeroOne:
def reconstruct(self, message):
for e in 'xo':
s = list(message)
for i, w in enumerate(s):
if w == '?':
s[i] = e
elif w != e:
break
e = 'o' if e == 'x' else 'x'
... |
''' this will raise a type erro we can't iterate int object'''
'''for i in 25:
print(i)'''
''' first way it will give 1 to 25'''
print("First way")
for i in range(1,26):
print(i)
''' second way ForLoop Iterate Over List of One Element and it will print only 25'''
print("Second way")
for i in [25]:
print(i... |
class DisjSet:
def __init__(self, n):
# Constructor to create and
# initialize sets of n items
self.rank = [1] * n
self.parent = [i for i in range(n)]
# Finds set of given item x
def find(self, x):
# Finds the representative of the set
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
def find(string = str,
substring = str,
start_indx = int,
stop_indx = int):
"""
Find the first occurence of 'substring' in 'string'
... |
"""Custom errors for mssql_dataframe."""
class EnvironmentODBCDriverNotFound(Exception):
"""Exception for not automatically determining ODBC driver."""
pass
class UndefinedConversionRule(Exception):
"""Exception for undefined conversion rule between pandas, ODBC, and SQL."""
pass
class SQLTableD... |
"""
:copyright: Michael Yusko
:license: MIT, see LICENSE for more details.
"""
__author__ = 'Michael Yusko'
__version__ = '0.1.1'
|
Token = ""
# Perm role. If you want use !w clear command, take this role on server.
mod_role = "moderation"
welcomeChannelName="💬┃boş-muhabbet" #channel name which welcome message will send.
goodbyeChannelName="💬┃boş-muhabbet" #channel name which goodbye message will send.
logChannelName="│log" #channel na... |
class Point:
def __init__(self):
self.x = 0
self.y = 0
def prompt_for_point(self):
self.x = int(input('Enter x: '))
self.y = int(input('Enter y: '))
def display(self):
print('Center:')
print('({}, {})'.format(self.x, self.y))
class Circle:
def __init__... |
"""API messages"""
SIGNUP_MSG = "New account created: %s"
LOGOUT = "Logged out successfully!"
LOGIN = "You are now logged in as %s"
REDIRECT_AFTER_LOGIN = "Redirecting user back to %s"
INVALID_LOGIN = "Invalid username or password."
NO_ITEM_IN_CATEGORY = "Oops.. Category %s does not contain any item!"
MSG_404 = "Oops... |
"""
This is Data access layer.
Describe here your Django models and
Django custom model managers.
Split your models module as it will grow up.
Classes from this package describe how to
access, store and manipulate on data.
DO NOT implement here business logic, only
operations with data storages.
As recommendation,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def hello_world():
return 'Hola es una aplicación de Python!'
|
#escape sequence character
def escapeChar():
return "\t lorem Ipsum is simply dummy text of the printing and typesetting industry.\n \t Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,\n \t when an unknown printer took a galley of type and scrambled it to make a type specimen book."
pr... |
class HnExportException(Exception):
path = "log.txt"
def __init__(self,place, arg):
self.place = place
self.arg = arg
mstr = ''
for i in arg :
mstr += str(i)
self.WriteLog(place+":"+mstr)
def __init__(self,_str):
self.WriteLog(_str)
... |
#create shipping_detail class
class shipping_detail:
# define the components of the shipping class with default function
def __init__(self):
# defining components of shipping_detail class as variables
self.shipping_id = "<shipping_id>"
self.delivery_address = "<delivery_addres... |
# PB method с изваждане на променлива:
# word = input()
#
# repeated_word = ""
#
# for i in word:
# current_char = i * 2
# repeated_word = repeated_word + current_char
# print(repeated_word)
# new method с директно принтиране:
word = input()
for i in word:
print(i * 2, end="") |
### =======================================
"""Looping over lists in Python"""
### =======================================
# define the network part of our IP Add
network_part = "192.168.2."
# define the host part for each device as list
host_parts = [20, 40, 60]
# Now, we can use a for loop to iterate and combine the... |
class configure():
accessKeyId = 'LTAIYHvPO8sqr1Ud'
accessKeySecret = 'V80aGhmoAgjZcISiZFt9LScnBlTs8u'
endPoint = 'oss-cn-beijing.aliyuncs.com'
bucket = 'testactive'
host = 'http://testactive.oss-cn-beijing.aliyuncs.com';
cosAppId = "1256005526";
cosAccessId = "AKIDO5fE7n80MWTsKiJujk2DMRL5... |
#
# Display DMD frames on console
#
# Translate bits to characters for different bits/pixel
# 4 bit is really only 3 bit
symbols = {
"wpc": [" ","*"],
"whitestar": [" ",".","o","O","*","?","?","?","?","?","?","?","?","?","?","?"],
"spike": [" "," ",".",".",".","o","o","o","O","O","O","*","*","*","#","#"]
}
class C... |
n = int(input())
left_chairs = 0
enough_chairs = True
for i in range(1, n + 1):
tokens = input().split(" ")
chairs = len(tokens[0])
people = int(tokens[1])
if chairs >= people:
left_chairs += chairs - people
else:
enough_chairs = False
print(f"{people - chairs} more chairs n... |
#!/usr/bin/env python3
"""
Write a function called cumsum that takes a list of numbers and returns
the cumulative sum; that is, a new list where the ith element is the sum
of the first i + 1 elements from the original list
"""
def cumsum(t):
new_t = []
for i in range(len(t)):
new_t += [sum(t[:i+1]... |
#!/usr/bin/env python3
def minswap (arr):
count = 0
pos = dict ()
# ~ print ('ARR:', arr)
for i in range (len (arr)):
pos[arr[i]] = i
# ~ print ('POS:', pos)
xi = 0
for n in sorted (pos):
i = pos[n]
# ~ print ('N:', n, 'XI:', xi, 'I:', i)
if xi != i:
... |
nome = str(input("Digite seu nome completo: ")).strip().capitalize()
primeiro_nome = nome.split()
print(f"Seu nome com letras maiúsculas: {nome.upper()}")
print(f"Seu nome com letras minúsculas: {nome.lower()}")
print(f"Seu nome possui {len(nome)-nome.count(' ')} letras.")
print(f"Seu primeiro nome é {primeiro_nome[0]}... |
# coding: utf-8
with open("test.txt", mode="r") as f:
f.read(12)
print(f.tell())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of tornadis library released under the MIT license.
# See the LICENSE file for more information.
class TornadisException(Exception):
"""Base Exception class."""
pass
class ConnectionError(TornadisException):
"""Exception raised when the... |
#
# PySNMP MIB module CISCO-IF-LINK-CONFIG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IF-LINK-CONFIG-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:01:21 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
'''Try It Yourself'''
'''6-7. People: Start with the program you wrote for Exercise 6-1 (page 102).
Make two new dictionaries representing different people, and store all three
dictionaries in a list called people. Loop through your list of people. As you
loop through the list, print everything you know about each pers... |
#
# PySNMP MIB module CISCO-HC-RMON-CAPABILITY (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-HC-RMON-CAPABILITY
# Produced by pysmi-0.3.4 at Mon Apr 29 17:42:31 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
pattern_zero=[0.0, 0.062222222222, 0.115555555556, 0.133333333333, 0.16, 0.195555555556, 0.222222222222, 0.24, 0.248888888889, 0.266666666667, 0.293333333333, 0.328888888889, 0.355555555556, 0.373333333333, 0.382222222222, 0.4, 0.426666666667, 0.462222222222, 0.488888888889, 0.506666666667, 0.515555555556, 0.5333333333... |
class Solution:
def maxPower(self, s: str) -> int:
max_count = 1
count = 1
for i in range(len(s) - 1):
if s[i] == s[i + 1]:
count += 1
if count > max_count:
max_count = count
if s[i] != s[i + 1]:
count = 1
... |
"""
Day 5: Poisson Distribution I
A random variable,X, follows Poisson distribution with mean of 2.5.
Find the probability with which the random variable X is equal to 5.
Author: Eda AYDIN
"""
def factorial(n):
if n == 1 or n == 0:
return 1
if n > 1:
return factorial(n - 1) *... |
class payload:
def __init__(self):
self.name = "openurl"
self.description = "open url through the default browser"
self.type = "native"
self.id = 117
def run(self,session,server,command):
return self.name
|
a = float(input("Введите начало интервала: "))
b = float(input("Введите конец интервала: "))
N = int(input("Введите количество отрезков: "))
if not N%2:
def f(x):
return 3 * x**2 + 6
h = (b-a)/2/N
S = f(a) + f(b)
for i in range(1,2*N):
if i%2:
S += 4*f(a+h*i)
... |
def aumentar(num=0, por=0, form=False,):
"""
Função que aumenta um valor de acordo com uma porcentagem
:param num: Valor a ser aumentado
:param por: Porcentagem do valor a ser adicionada
:param form: Se o número vai ser formatado ou não
:return: O valor com a porcentagem adicionada, se o param f... |
num1 = int(input())
num2 = int(input())
num3 = int(input())
if num1 < num2 and num2 < num3:
print("crescente")
else:
print("não está em ordem crescente") |
"""
Method Resolution Order
In the multiple inheritance scenario, any specified attribute is searched first
in the current class.If not found, the search continues into parent class in depth first
left-right fashion without searching same class twice.
class LandLive():
def LandLife(self):
print("It ca... |
ref = {"A": 10, "B": 11, "C": 12, "D": 13, "E": 14, "F": 15}
def hex_to_decimal_integer(number):
if "." in number:
number = number.split('.')[0]
result = 0
for index, multiplier in enumerate(range(len(number) - 1, -1, -1)):
value = number[index]
if value in ref.keys():
... |
#You can return a range of characters by using the slice syntax.
#Specify the start index and the end index, separated by a colon, to return a part of the string.
#Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
b = "Hello, World!"
print(b[5:8])
#by leaving out th... |
class Person:
"This is a person class"
age = 10
def greet(self):
print("Hello")
# create a new object of Person class
harry = Person()
# Output: <function Person.greet>
print(Person.greet)
# Output: <bound method Person.greet of <__main__.Person object>>
print(harry.greet)
# Calling object's gr... |
#!/usr/bin/env python3.7
# -*- coding:utf-8 # -*-
"""
@File : guess_age.py
@Author : NIE ZIYU
@Email : ziyuwill@gmail.com
@IDE : PyCharm
@Create_Time : 2019-01-18 15:33
"""
real_age = 33
guess_age = int(input("Aeg:"))
if real_age > guess_age:
print("猜小了")
elif real_age < guess_age:
print("猜到了")... |
# Time: O(n)
# Space: O(1)
class Solution(object):
def averageWaitingTime(self, customers):
"""
:type customers: List[List[int]]
:rtype: float
"""
avai = wait = 0.0
for a, t in customers:
avai = max(avai, a)+t
wait += avai-a
return wa... |
font = CurrentFont()
for name in font.selection:
# get source glyph
source = font[name]
# get smallcap name
gn = source.name + ".num"
# make sc glyph object
glyph = font.newGlyph(gn)
# add source to sc glyph
glyph.appendGlyph(source)
# scale
glyph.prepareUndo... |
api = {
'base_url_net': 'https://babelnet.io/v6',
'base_url_fy': 'https://babelfy.io/v1/',
'disambiguate_url': 'https://babelfy.io/v1/disambiguate',
'synsets_given_word_url': 'https://babelnet.io/v6/getSynsetIds',
'senses_given_word_url': 'https://babelnet.io/v6/getSenses',
'information_given_... |
#Difinicion de variables y otros
print ( "ejercicio 01: area de un triangulo" )
#datos de entrada mediente dispositivos de entrada
b = int ( input ( "Base Ingrese:" ))
h = int ( input ( "ingrese altura:" ))
#proceso
área = ( b * h ) / 2
#datos de salida en dispositivos de salida
print ( "area de triangulo es: [" , are... |
class Module(AlfredModule):
def __init__(self):
self.name = "mod_name"
self.menu_name = "📟 Pretty Mod Name"
self.commands = [
('💰 Balance', "get_balance_detailed"),
]
def get_balance_detailed(self):
return "Anything you want"
|
# Move the first letter of each word to the end of it,
# then add "ay" to the end of the word.
# Leave punctuation marks untouched.
# My Solution
def pig_it(text):
workString = text.split(" ")
resString = []
for word in workString:
if word.isalpha():
newWord = word[1:] + wor... |
'''1. Write a Python program to count the number of arguments in a given function.
Sample Output:
0
1
2
3
4
1'''
def num_of_args(*args):
return(len(args))
print(num_of_args())
print(num_of_args(1))
print(num_of_args(1, 2))
print(num_of_args(1, 2, 3))
print(num_of_args(1, 2, 3, 4))
print(num_of_args([1, 2, 3, 4]))
#Re... |
# -*- coding: utf-8 -*-
{
"name" : "InfoSaone - Moules pour Injection Plastique",
"version" : "0.1",
"author" : "Tony Galmiche / InfoSaone",
'category' : 'InfoSaône\Plastigray',
"description": "InfoSaone / Moules pour Injection Plastique",
"maintainer": 'InfoSaone',
"website": 'http://www.in... |
# The following has been generated automatically from src/core/geometry/qgsgeometry.h
QgsGeometry.BufferSide.baseClass = QgsGeometry
QgsGeometry.EndCapStyle.baseClass = QgsGeometry
QgsGeometry.JoinStyle.baseClass = QgsGeometry
|
'''
给定二叉搜索树(BST),将其转换为更大的树,使原始BST上每个节点的值都更改为在原始树中大于等于该节点值的节点值之和(包括该节点)。
样例
样例1:
输入 : {5,2,13}
5
/ \
2 13
输出 : {18,20,13}
18
/ \
20 13
样例2:
输入 : {5,3,15}
5
/ \
3 15
输出 : {20,23,15}
... |
def add(src,links,wei=1):
for a in range(len(mat[src])):
if a!=src:
if a == links:
mat[src][a]=1*wei
elif mat[src][a]!=0 and mat[src][a]!=None:
pass
else:
mat[src][a]=0
def call(a,b,w=1):
add(a,b,w)
add(b,a,w) ... |
#
# PySNMP MIB module H3C-SYS-MAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-SYS-MAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:24:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
"""
RawIO for reading data from Neuralynx files.
This IO supports NCS, NEV, NSE and NTT file formats.
NCS contains the sampled signal for one channel
NEV contains events
NSE contains spikes and waveforms for mono electrodes
NTT contains spikes and waveforms for tetrodes
"""
|
'''
The MIT License (MIT)
Copyright (c) 2016 WavyCloud
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, p... |
class Solution:
def superEggDrop(self, K: int, N: int) -> int:
# @functools.lru_cache(None)
# def dfs(k,n):
# if k==1:return n
# if n==1:return 1
# return dfs(k,n-1)+dfs(k-1,n-1)+1
# for i in range(1,N+1):
# if dfs(K,i)>=N:return i
dp... |
"""
date: 2019-02-25 10:01
排序代码集合
"""
def quick_sort(array, l, r):
if l < r:
q = partition(array, l, r)
quick_sort(array, l, q)
quick_sort(array, q + 1, r)
def partition(array, l, r):
i = l - 1
for j in range(l, r):
if array[j] <= array[r]:
i += 1
... |
__all__ = [
'doc_matching_rules',
]
doc_matching_rules = '''
Ship transforms will commonly use a group of matching rules
to determine which ships get modified, and by how much.
* Matching rules:
- These are tuples pairing a matching rule (string) with transform
defined args, eg. ... |
fixtures = [
{"name": "+5 Dexterity Vest", "sell_in": 10,
"quality": 20, "category": "normal"},
{"name": "Aged Brie", "sell_in": 2, "quality": 0, "category": "aged_brie"},
{"name": "Elixir of the Mongoose", "sell_in": 5,
"quality": 7, "category": "normal"},
{"name": "Sulfuras, Hand of Ra... |
def strategy(history, memory):
if history.shape[1] % 2 == 0: # even, cooperate in odd
return 1, None
else:
return 0, None |
n = int(input())
cnt = 0
l = [int(i) for i in input().split()]
for i in range(1,n):
if l[i] < l[i-1]:
cnt = cnt + (l[i-1] - l[i])
l[i] = l[i-1]
print(cnt) |
class class0:
var0 = ''
def __init__(self):
var1 = 0
def fun1():
return var0
def fun2():
print('useless print')
return var1 |
def handshake(code):
pass
def secret_code(actions):
pass
|
class VulnerableBySeveritySplunk:
"""Format `vulnerable_by_severity.json` for Splunk"""
def __init__(self, data):
"""
:param data: a dict() created from `data/vulnerable_by_severity.json`
"""
self.data = data
def splunk_format(self):
"""Format for splunk: Split out ... |
def generate_functions(function_name):
return "def {}(chat_id, message):\n\
bot = Bot(token=TELEGRAM_TOKEN)\
bot.sendMessage(chat_id=chat_id, text=message)\n\n".format(function_name)
def generate_callback(function_name):
return "def {}(ch, method, properties, body):\n\tpass\n\n".format(function_name)
... |
# Aula 13 - Estrutura de repetição for
for c in range(5, 0, -1):
print(c)
print('-=' * 10)
for i in range(1, 6, 2):
print(i)
print('-=' * 10)
i = int(input('Inicio: '))
f = int(input('Fim: '))
p = int(input('Passo: '))
for c in range(i, f+1, p):
print(c)
print('FIM')
|
CHARACTERS = {
0: 'Ryu',
1: 'Dictator',
2: 'Chun Li',
3: 'Ken',
4: 'Karin',
5: 'Zangief',
6: 'Dhalsim',
7: 'Nash',
8: 'Claw',
10: 'Birdie',
11: 'R. Mika',
12: 'Rashid',
13: 'Fang',
14: 'Laura',
15: 'Necalli',
16: 'Cammy',
21: 'Alex',
17: 'Guile',
... |
def _print_option_help( op, names, detailed_help, prefix, help_justification ):
help = ''
if detailed_help:
for name in names[:-1]:
help += prefix + name + ':\n'
name = names[-1]
tmp = prefix + name + ':'
help += tmp
help += ' ' * (len( help_justifica... |
class Solution:
def divisorGame(self, N: int) -> bool:
return not N%2
N = 2
res = Solution().divisorGame(N)
print(res) |
def insertionsort(ar,m):
i=m-1
temp=ar[i]
while(ar[i-1]>temp and i>0):
ar[i]=ar[i-1]
print(' '.join(map(str,ar)))
i-=1
ar[i]=temp
print(' '.join(map(str,ar)))
return ar
m = int(input())
ar = [int(i) for i in input().split()]
ar=insertionsort(ar,m) |
"""
htmlx.webapi.websocket
====================================
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
"""
|
# 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 in writing, software
# distributed under the Li... |
class FilterParamsMissing(Exception):
"""
When some parameters are missing while initializing the Filter Node,
this exception will be raised asking for the completion of the missing
parameters
"""
def __str__(self):
return "Filter node has missing arguments. \n Use like :: " \
... |
def add(a=1, b=2):
return a+b
def sub(a=5, b=2):
return a-b
|
def pagify(text, delims=["\n"], *, escape_mass_mentions=True, shorten_by=8, page_length=2000):
in_text = text
if escape_mass_mentions:
num_mentions = text.count("@here") + text.count("@everyone")
shorten_by += num_mentions
page_length -= shorten_by
while len(in_text) > page_length:
closest_delim = m... |
'''
Say you have an array for which the ith element
is the price of a given stock on day i.
If you were only permitted to complete
at most one transaction (i.e., buy one and sell
one share of the stock), design an algorithm
to find the maximum profit.
Note that you cannot sell a stock before you buy one.
The points ... |
class BaseProduct(object):
params: dict = {}
def __init__(self):
pass
def get_cashflows(self, *args, **kwargs):
return None
def pv(self, *args, **kwargs):
return 0
|
def sieve(total):
totallist = range(1,total+1)
ret = []
if len(totallist) == 1:
return ret
for num in totallist[1:]:
if num in [2,3,5,7,11,13]:
ret.append(num)
else:
insert = True
for prime in ret:
if num % prime == 0:
... |
'''
Pack consecutive duplicates of list elements into sublists.
If a list contains repeated elements they should be placed in separate
sublists.
Example:
* (pack '(a a a a b c c a a d e e e e))
((A A A A) (B) (C C) (A A) (D) (E E E E))
'''
#taking input of list elements at a single time seperating by space and... |
class SnowyWinter:
def snowyHighwayLength(self, startPoints, endPoints):
road = [False] * 10001
for s, e in zip(startPoints, endPoints):
for i in xrange(s, e):
road[i] = True
return len([e for e in road if e])
|
###############################################################################
# Metadata
'''
LC_PATROL_MTD_START
{
"description" : "Collection of all core LimaCharlie detections.",
"author" : "maximelb@google.com",
"version" : "1.0"
}
LC_PATROL_MTD_END
'''
#################################################... |
def getNameToDataDict(peopleData):
nameToData = {}
for ppl in peopleData:
nameToData[ppl['name']] = ppl
return nameToData
def getUniversalAverageMetersPerDay(workoutsData, numberOfPeople, DateManager):
chronologicalData = DateManager.getWorkoutsDataChronologically(workoutsData)
ergMetersPe... |
"""
Function:处理数组
Author:lzb
Date:2021.01.30
"""
def handle_arr(arr, f, *args):
"""
功能:递归处理数组\n
参数:\n
arr:待处理的数组\n
f:处理函数\n
*args:变参
返回值:NULL\n
"""
# 数组的维度
shape = arr.shape
dim = len(shape)
# 第1维元素的个数
count = shape[0]
# 如果是1维,则开始处理
if 1 == dim:
f... |
# -*- coding: utf-8 -*-
"""Data types considered in OnTask and its relation with Pandas data types"""
class TypeDict(dict):
"""Class to detect multiple datetime types in Pandas."""
def get(self, key):
"""Detect if given key is equal to any stored value."""
return next(
otype for ... |
# 17th Nov '19
# 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 plusOne(self, head: ListNode) -> ListNode:
dummy_head = ListNode(0)
dummy_head.next = head
n... |
def readFile(path):
with open(path, 'r') as file:
return [line.strip() for line in file.readlines()]
def gcContent(sequence):
return round(((sequence.count('C') + sequence.count('G')) / len(sequence) * 100), 6)
# Define uma variável com o conteúdo da lista
FASTAfile = readFile('4-computing-gc-content... |
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
def anagrams(word, words):
"""
A function that will find all the anagrams of a word
from a list. You will be given two inputs a word and
an array with words. You should return an arra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.