content stringlengths 7 1.05M |
|---|
# |---------------------|
# <module> | |
# |---------------------|
#
# |---------------------|
# print_n | s--->'Hello' n--->2 | |
# |---------------------|
#
# |---------------------|
# print_n | s--->'Hello' n--->1 ... |
num_waves = 3
num_eqn = 3
# Conserved quantities
pressure = 0
x_velocity = 1
y_velocity = 2
|
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
... |
# Source and destination file names.
test_source = "compact_lists.txt"
test_destination = "compact_lists.html"
# Keyword parameters passed to publish_file.
reader_name = "standalone"
parser_name = "rst"
writer_name = "html"
# Settings
# local copy of stylesheets:
# (Test runs in ``docutils/test/``, we need relative p... |
#!/usr/bin/env python
dic = {'nome': 'Shirley Manson', 'banda': 'Garbage'}
print(dic['nome'])
del dic
dic = {'Yes': ['Close To The Edge', 'Fragile'],
'Genesis': ['Foxtrot', 'The Nursery Crime'],
'ELP': ['Brain Salad Surgery']}
print(dic['Yes'])
|
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
a = Student('xiaoqiang', 60)
a.print_score()
# error
# print(a.__score)
# 不规范的使用
print(a._Student__score)
|
#!/usr/bin/env python3
"""Configuration of builddataset."""
buildcfg = {}
# === Selection requirements === #
# Minimum clear pixel coverage in the constructed Source Mask
# Note: Due to water vapour, most rivers and lakes will be marked as not clear
buildcfg['min_clearance'] = 0.75
# Minimum number of LR images per ... |
class DictHelper:
@staticmethod
def split_path(path):
if isinstance(path, str):
path = path.split(" ")
elif isinstance(path, int):
path = str(path)
filename, *rpath = path
return (filename, rpath)
@staticmethod
def get_dict_by_path(dict_var, pa... |
coordinates = (1,2,3)
# bu değişkendeki ögeleri tek tek kullanalım
# kullanacağımız yerde ögeleri indeks numaralarına göre çağırabiliriz
coordinates[0],coordinates[1],coordinates[2]
print(coordinates[0])
# veya ögeleri değişkenlere atayabiliriz
x = coordinates[0]
y = coordinates[1]
z = coordinates[2]
print(y)
# veya... |
"""Support ODT formatting.
Part of the PyWriter project.
Copyright (c) 2020 Peter Triesberger
For further information see https://github.com/peter88213/PyWriter
Published under the MIT License (https://opensource.org/licenses/mit-license.php)
"""
def to_odt(text):
"""Convert yw7 raw markup to odt. Retu... |
'''
A program for warshall algorithm.It is a shortest path algorithm which is used to find the
distance from source node,which is the first node,to all the other nodes.
If there is no direct distance between two vertices then it is considered as -1
'''
def warshall(g,ver):
dist = list(map(lambda i: list(map(... |
class Solution:
"""
@param S: A set of numbers.
@return: A list of lists. All valid subsets.
"""
def subsetsWithDup(self, S):
# write your code here
# Revursive
if (not S):
return [[]]
S = sorted(S)
tmp = self.subsetsWithDup(S[:-1])
locked... |
#-------------------------------------------------------------------------------
# importation
#-------------------------------------------------------------------------------
# Main class Ml_tools
class ml_tools:
def __init__(self):
pass |
text = " I love apples very much "
# The number of characters in the text
text_size = len(text)
# Initialize a pointer to the position of the first character of 'text'
pos = 0
# This is a flag to indicate whether the character we are comparing
# to is a white space or not
is_space = text[0].isspace()
# Start toke... |
"""Issue.
"""
class Issue:
"""Issue.
Issue must not contain subelements and attributes.
@see RPCBase._parse_issue(element)
:param creator: element.attrib["creator"]
:param value: element.text
"""
def __init__(self, creator=None, value=None):
self.creator = creator
self... |
# PyJS does not support weak references,
# so this module provides stubs with usual references
typecls = __builtins__.TypeClass
class ReferenceType(typecls):
pass
class CallableProxyType(typecls):
pass
class ProxyType(typecls):
pass
ProxyTypes = (ProxyType, CallableProxyType)
WeakValueDictionary = dict
... |
#
# PySNMP MIB module TCP-ESTATS-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/TCP-ESTATS-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:31:06 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
... |
'''
Faça um Programa que peça um número e informe se o número é inteiro ou decimal.
Dica: utilize uma função de arredondamento.
'''
### ALGORITMO ###
num = float(input('Digite um número: '))
a = num // 1
if num - a == 0:
b = int(num)
print('{0} é INTEIRO'.format(b))
else:
... |
def solve(arr: list) -> int:
""" This function returns the difference between the count of even numbers and the count of odd numbers. """
even = []
odd = []
for item in arr:
if str(item).isdigit():
if item % 2 == 0:
even.append(item)
else:
... |
class Client:
def __init__(self, client_id):
self.client_id = client_id
self.available = 0
self.held = 0
self.total = 0
self.locked = False
def get_client_id(self):
return self.client_id
def get_available(self):
return self.available
def lock... |
description = 'W&T Box * 0-10V * Nr. 2'
includes = []
_wutbox = 'wut-0-10-02'
_wutbox_dev = _wutbox.replace('-','_')
devices = {
_wutbox_dev +'_1': device('nicos_mlz.sans1.devices.wut.WutValue',
hostname = _wutbox + '.sans1.frm2',
port = '1',
description = 'input 1 voltage',
fmtstr... |
#!/usr/bin/env python
CLIENT_ID = "zlrUKliWyT65ng"
CLIENT_SECRET = "GKZ4G2df_YZOZ5V9mF-J-lJDDDo"
USERNAME = "entsnack"
PASSWORD = "claustrophobic"
SUBREDDIT = "ChangeMyView"
FLAIR_HIDING_TEMPLATE_ID = "FLAIR_TEMPLATE_ID"
USER_GROUPS_FILENAME = "user_flair_group"
USER_AGENT = "web:zlrUKliWyT65ng:0.1 (by u/entsnack)"
MA... |
#!/usr/bin/env python
class ProxyAtom(object):
"""docstring for ProxyAtom"""
def __init__(self, ips, ports):
super(ProxyAtom, self).__init__()
result = dict(zip(ips, ports))
self.items = set([':'.join((host, port)) for host, port in result.items()])
|
#!/usr/bin/env python
NAME = 'FortiWeb (Fortinet)'
def is_waf(self):
if self.matchcookie(r'^FORTIWAFSID='):
return True
for attack in self.attacks:
r = attack(self)
if r is None:
return
_, responsepage = r
# Found a site running a tweaked version of Fortiweb... |
def checkResult(netSales, eps):
try:
crfo = float(netSales[0])
except:
crfo = 0.0
try:
prfo = float(netSales[1])
except:
prfo = 0.0
try:
lrfo = float(netSales[2])
except:
lrfo = 0.0
try:
cqe = float(eps[0])
except:
cqe = 0.0... |
'''
A centered decagonal number is a centered figurate number that represents
a decagon with a dot in the center and all other dots surrounding the center
dot in successive decagonal layers.
The centered decagonal number for n is given by the formula
5n^2+5n+1
'''
def centeredDecagonal (num):... |
# class Solution:
# def convert(self, s: str, numRows: int) -> str:
# lst = []
# N = len(s)
# print (N//(2*numRows-2))
# [lst.append([s[i]]) for i in range(numRows)]
# step = 2*numRows-2
# for k in range(N//step):
# if k:
# [lst[i].append(s... |
""" moe.py
A set of functions that can be used to select an item from a list using the
"Eeny, Meeny, Miny, Moe" method.
There are a few versions of the rhyme. The "regular" one is as follows:
Eeny, Meeny, Miny, Moe
Catch a tiger by his toe
If he hollers let him go
Eeny, Meeny, Miny, Moe
My mother told me
To pick the... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 4 16:01:51 2019
@author: Administrator
"""
class Solution:
def sortArray(self, nums: list) -> list:
# return self.heap_sort(nums)
self.heap_sort(nums)
return nums
# def adjust_heap(self, nums, size, k):
# lchild = 2*k+1
# ... |
def cpu_processing_time(cycles: int, freq: float):
"""
:param cycles
:param freq: MHz
:return: seconds
"""
return (cycles / (freq * pow(10, 6))) * pow(10, 3)
if __name__ == "__main__":
print(cpu_processing_time(1.05149 * pow(10, 6), 1300))
|
"""
21.25%
"""
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 1
nums = sorted(list(set(nums)))
n = 0
for index, num in enumerate(nums):
if num <= 0:
... |
class Solution(object):
def exclusiveTime(self, n, logs):
"""
:type n: int
:type logs: List[str]
:rtype: List[int]
"""
stack = []
overhead = [0]
res = [0 for i in range(n)]
for log_str in logs:
log = log_str.split(':')
... |
#!/usr/bin/env python
# encoding: utf-8
"""
remove_dups_from_sorted_list_ii.py
Created by Shengwei on 2014-07-05.
"""
# https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
# tags: medium, linked-list, pointer, dups, edge cases
"""
Given a sorted linked list, delete all nodes that have duplicate n... |
"""This question was asked by BufferBox.
Given a binary tree where all nodes are either 0 or 1, prune the tree so that subtrees containing all 0s are removed.
For example, given the following tree:
0
/ \
1 0
/ \
1 0
/ \
0 0
should be pruned to:
0
/ \
1 0
/
1
We do not remove the... |
NO_RESET = 0b0
BATCH_RESET = 0b1
EPOCH_RESET = 0b10
NONE_METER = 'none'
SCALAR_METER = 'scalar'
TEXT_METER = 'text'
IMAGE_METER = 'image'
HIST_METER = 'hist'
GRAPH_METER = 'graph'
AUDIO_METER = 'audio'
|
"""
2) Reverse a given integer number
"""
num = int(input("Digite um número inteiro: "))
texto = str(num)
num = texto[::-1]
print(int(num)) |
''' Crie um programa que tenha uma tupla com várias palavras
(não usar acentos). Depois disso, você deve mostrar, para cada palavra,
quais são as suas vogais. '''
palavras = (('aprender','programar','linguagem','python',
'curso','gratis','estudar','praticar',
'trabalhar','mercado','programador'... |
lower=100
upper=999
for num in range(lower,upper+1):
order=len(str(num))
sum=0
temp=num
while temp>0:
digit=temp%10
sum+=digit**order
temp//=10
if num==sum:
print(num)
|
def is_interesting(number, awesome_phrases):
if number<98: return 0
elif check(number, awesome_phrases) and number>=100: return 2
for i in range(number+1, number+3):
if i>=100 and check(i, awesome_phrases):
return 1
return 0
def check(n, awesome_phrases):
return equal(n) or all_z... |
with open('input', 'r') as expense_report:
expenses = [ int(a.strip()) for a in expense_report.readlines() ]
expenses = sorted(expenses)
def part1():
for a in expenses:
for b in expenses:
if a + b == 2020:
print(f"{a} + {b} = 2020, {a} * {b} = {a * b}")
... |
"""Migration for a given Submitty course database."""
def up(config, database, semester, course):
"""
Run up migration.
:param config: Object holding configuration details about Submitty
:type config: migrator.config.Config
:param database: Object for interacting with given database for environme... |
##
# \file exceptions.py
# \brief User-specific exceptions
#
# \author Michael Ebner (michael.ebner.14@ucl.ac.uk)
# \date June 2017
#
##
# Error handling in case the directory does not contain valid nifti file
# \date 2017-06-14 11:11:37+0100
#
class InputFilesNotValid(Exception):
##
# \... |
# Testing
with open("stuck_in_a_rut.in") as file1:
N = int(file1.readline().strip())
cows = [[value if index == 0 else int(value) for index, value in enumerate(i.strip().split())] for i in file1.readlines()]
# Actual
# N = int(input())
# cow_numbers = [input() for _ in range(N)]
# cows = [[value if index == ... |
__all__ = [
'DataFSError', 'UnsupportedOperation', 'InvalidOpenMode',
'DataFileNotExist', 'MetaKeyNotExist',
]
class DataFSError(Exception):
"""Base class for all :class:`DataFS` errors."""
class UnsupportedOperation(DataFSError):
"""
Class to indicate that a requested operation is not supported... |
'''
Este programa lê o número de dias, horas, minutos e segundos.
Calcula a quantidade de segundos que existem nesse intervalo.
'''
print("Este programa lê a quantidade de dias, horas, minutos e segundos e informa quantos segundos existem neles")
dias = int(input("Informe o número de dias: "))
horas = int(input... |
# Time: O(max(h, k))
# Space: O(h)
# 230
# Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
#
# Note:
# You may assume k is always valid, 1 <= k <= BST's total elements.
#
# Follow up:
# What if the BST is modified (insert/delete operations) often and
# you need to find... |
height = int(input("Height: "))
width = int(input("Width: "))
for i in range(height):
for j in range(width):
print("* ",end='')
print()
|
shader_assignment = []
for shadingEngine in renderPartition.inputs():
if not shadingEngine.members():
continue
if shadingEngine.name() == 'initialShadingGroup':
continue
nameSE = shadingEngine.name()
nameSH = shadingEngine.surfaceShader.inputs()[0].name()
shader_assignment.appe... |
# Python - 2.7.6
Test.assert_equals(calculate_tip(30, 'poor'), 2)
Test.assert_equals(calculate_tip(20, 'Excellent'), 4)
Test.assert_equals(calculate_tip(20, 'hi'), 'Rating not recognised')
Test.assert_equals(calculate_tip(107.65, 'GReat'), 17)
Test.assert_equals(calculate_tip(20, 'great!'), 'Rating not recognised')
|
class CNmoney:
cdict = {}
gdict = {}
xdict = {}
def __init__(self):
self.cdict = {1: u'', 2: u'拾', 3: u'佰', 4: u'仟'}
self.xdict = {1: u'元', 2: u'万', 3: u'亿', 4: u'兆'} # 数字标识符
self.gdict = {0: u'零', 1: u'壹', 2: u'贰', 3: u'叁',
4: u'肆', 5: u'伍', 6: u'陆', 7: ... |
# -*- coding: utf-8 -*-
#################################################################################
# Author : Webkul Software Pvt. Ltd. (<https://webkul.com/>)
# Copyright(c): 2015-Present Webkul Software Pvt. Ltd.
# All Rights Reserved.
#
#
#
# This program is copyright property of the author mentioned abo... |
# Aula passada:
'''for c in range(1, 10):
print(c)
print('Fim')'''
# Nessa aula:
# Sei o limite, pode usar ambos, dá no mesmo
c = 1
while c < 10:
print(c)
c = c + 1 # ie c+= 1
print('Fim')
# Não sei o limite: somente while
n = 1
while n != 0:
n = int(input('Digite um valor: '))
print('Fim')
r = 'S'
... |
#------------------------------------------------------------------------------
# simple_universe/room.py
# Copyright 2011 Joseph Schilz
# Licensed under Apache v2
#------------------------------------------------------------------------------
class SimpleRoom(object):
ID = [-1, -1]
exits = []
desc... |
# Time: O(n)
# Space: O(1)
# 751
# Given a start IP address ip and a number of ips we need to cover n,
# return a representation of the range as a list (of smallest possible length) of CIDR blocks.
#
# A CIDR block is a string consisting of an IP, followed by a slash,
# and then the prefix length. For example: "123.4... |
print('====== EX 015 ======')
dias = int(input('Quantos dias o carro foi alugado: '))
km = float(input('E quantos Km foram percorridos: '))
p = (dias * 60) + (km * 0.15)
print('O total a pagar é de R${:.2f}'.format(p))
|
def example_bytes_slice():
word = b'the lazy brown dog jumped'
for i in range(10):
# Memoryview slicing is 10x faster than bytes slicing
if word[0:i] == 'the':
return True
def example_bytes_slice_as_arg(word: bytes):
for i in range(10):
# Memoryview slicing is 10x faster... |
prve_stiri = [2, 3, 5, 7]
def je_prastevilo(n):
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return n > 1
def trunctable_z_desne(n):
for indeks in range(1, len(str(n))):
if not je_prastevilo(int(str(n)[0:indeks])):
return False
return n... |
low=1
high=2
third=0
sum=0
temp=0
while(third<4000000):
third=low+high
if(third%2==0):
sum+=third
low=high
high=third
print(sum+2)
|
#Skill: array iteration
#You are given an array of integers. Return the smallest positive integer that is not present in the array. The array may contain duplicate entries.
#For example, the input [3, 4, -1, 1] should return 2 because it is the smallest positive integer that doesn't exist in the array.
#Your solution... |
class Solution:
def maxProfit(self, inventory: List[int], orders: int) -> int:
# [5, 5, 2]
inventory.sort(reverse=True)
inventory.append(0)
ans = 0
idx = 0
n = len(inventory)
while orders:
# find the first index such that inv[j] < inv[i]
... |
# Copyright (c) 2014 Mirantis Inc.
# Copyright (c) 2016 Codethink 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 at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
"""
This module defines the AtlasMetaData container type.
"""
class AtlasMetaData(object):
"""
Container class for an Atlas's metadata.
Readable metadata fields:
number_of_points (long)
number_of_lines (long)
number_of_areas (long)
number_of_nodes (long)
number_of_edges (long)
num... |
"""
A Harness for creating and using GPs for inference.
-- kandasamy@cs.cmu.edu
"""
|
'''
A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.
For example, in array A such that:
A[0] = 9 A[1] = 3 A[2] = 9
A[3] = 3... |
def maven_dependencies(callback):
callback({"artifact": "antlr:antlr:2.7.6", "lang": "java", "sha1": "cf4f67dae5df4f9932ae7810f4548ef3e14dd35e", "repository": "https://repo.maven.apache.org/maven2/", "name": "antlr_antlr", "actual": "@antlr_antlr//jar", "bind": "jar/antlr/antlr"})
callback({"artifact": "aopalli... |
def solve(lines):
longest_intersec = []
for line in lines:
(r1, r2) = line.split("-")
(r1_start, r1_end) = map(int, r1.split(","))
(r2_start, r2_end) = map(int, r2.split(","))
current_longest_intersec = set(range(r1_start, r1_end + 1)) & set(range(r2_start, r2_end + 1))
i... |
valor_casa = float(input('QUAL O VALOR TOTAL DA CASA? '))
salario = float(input('QUAL O SEU SALARIO EM REAIS? '))
parcelas = int(input('QUANTOS ANOS QUER PAGAR A CASA ?? '))
parcelas = parcelas * 12
valor_parcela = valor_casa / parcelas
if salario > (valor_parcela * 100) / 30:
print('Emprestimo aprovado')
else:
... |
def make_dist():
return default_python_distribution(
python_version="3.8"
)
def make_exe(dist):
policy = dist.make_python_packaging_policy()
policy.extension_module_filter = "all"
# policy.file_scanner_classify_files = True
policy.allow_files = True
policy.file_scanner_emit_files = ... |
def double(num):
return num * 2
# way 1
multiply = lambda x,y: x*y
print(multiply(5,10))
# way 2
print((lambda x,y: x+y)(6, 82))
numbers = [23, 73, 62, 3]
added = [ x*2 for x in numbers]
print(added)
added = [double(x) for x in numbers]
print(added)
added = [ (lambda x: x*2)(x) for x in numbers]
print(added)
... |
class AspectManager(object):
def __init__(self):
super(AspectManager, self).__init__()
def get_module_hooker(self, name):
return None
def load_aspects(self):
pass
|
def percent(p):
return (p/soma)*100
def b_mb(r):
return float(r)/(1024**2)
arq = open('usuarios.txt','r')
cont = 0
l = [1,2,3,4,5,6]
for linha in arq:
linha= linha.strip()
l[cont] = linha
cont = cont + 1
p =[]
for n in range(0,6):
p.append(l[n].split())
arq.close()
e=[1,2,3,4,5,6]
soma = 0
for... |
SECRET_KEY = 'example'
TIME_ZONE = 'Asia/Shanghai'
DEFAULT_XFILES_FACTOR = 0
URL_PREFIX = '/'
LOG_DIR = '/var/log/graphite'
GRAPHITE_ROOT = '/opt/graphite'
CONF_DIR = '/etc/graphite'
DASHBOARD_CONF = '/etc/graphite/dashboard.conf'
GRAPHTEMPLATES_CONF = '/etc/graphite/graphTemplates.conf'
# STORAGE_DIR = '/opt/graphite/... |
n = int(input("Enter a number: "))
for x in range(1,16):
print(n,"x",x,"=",(n*x))
|
# there are two ways of representing a graph
# we can use an adjacency list
# the other way is to use an adjacency matrix
# its easier to represent weighted graphs using an adjacency matrix
# we can represent a directed graph using both structures
# so which is better
# dense graph is where number of Edges is Vertex sq... |
print('Digite três valores, para ver se é um trinângulo, e se forem se é um triânguulo escaleno, equilátero ou isóceles')
A = float(input('Lado A: '))
B = float(input('Lado B: '))
C = float(input('Lado C: '))
soma = A + B
soma1 = A + C
soma2 = B + C
if A and B and C < soma and soma1 and soma2:
if A == B == C:
... |
#
# PySNMP MIB module TIMETRA-LLDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-LLDP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:11:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
class kdtree:
def __init__(self, points, dimensions):
self.dimensions = dimensions
self.tree = self._build([(i, p) for i,p in enumerate(points)])
def closest(self, point):
return self._closest(self.tree, point)
def _build(self,points, depth=0):
n = len(point... |
def A_type_annotation(integer: int, boolean: bool, string: str):
pass
def B_annotation_as_documentation(argument: 'One of the usages in PEP-3107'):
pass
def C_annotation_and_default(integer: int=42, list_: list=None):
pass
def D_annotated_kw_only_args(*, kwo: int, with_default: str='value'):
pass
... |
class Solution:
def addSpaces(self, s: str, spaces: List[int]) -> str:
ans = ""
prev = 0
for sp in spaces:
ans += s[prev:sp] + " "
prev = sp
return ans + s[prev:]
|
print('Congratulations on running this script!!')
msg = 'hello world'
print(msg)
|
def test_post_sub_category(app, client):
mock_request_data = {
"category_fk": "47314685-54c1-4863-9918-09f58b981eea",
"name": "teste",
"description": "testado testando"
}
response = client.post('/sub_categorys', json=mock_request_data)
assert response.status_code == 201
expec... |
# %%
class WalletSwiss:
coversion_rates = {"usd" :1.10, "gpd": 0.81, "euro": 0.95, "yen": 123.84 }
#shows swiss conversion rates for each each currency starting at $1
def __init__(self,currency_amount):
self.currency_amount = currency_amount
self.currency_type = "franc"
def convert_currenc... |
#
# from src/whrnd.c
#
# void init_rnd(int, int, int) to whrnd; .init
# double rnd(void) to whrnd; .__call__
#
class whrnd:
def __init__(self, x=1, y=1, z=1):
self.init(x, y, z)
def init(self, x, y, z):
self.x, self.y, self.z = x, y, z
def __call__(self):
self.x = 171 * (self.x... |
# Copyright 2019 École Polytechnique
#
# Authorship
# Luciano Di Palma <luciano.di-palma@polytechnique.edu>
# Enhui Huang <enhui.huang@polytechnique.edu>
# Le Ha Vy Nguyen <nguyenlehavy@gmail.com>
# Laurent Cetinsoy <laurent.cetinsoy@gmail.com>
#
# Disclaimer
# THE SOFTWARE IS PROVIDED "AS IS", WITHOU... |
#
# PySNMP MIB module DNOS-DCBX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DNOS-DCBX-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:51:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
description = 'system setup'
group = 'lowlevel'
display_order = 90
sysconfig = dict(
cache = 'localhost',
instrument = 'NEUTRA',
experiment = 'Exp',
datasinks = ['conssink', 'dmnsink', 'livesink', 'asciisink', 'shuttersink'],
notifiers = ['email'],
)
requires = ['shutters']
modules = [
'nic... |
'''
给你一个字符串 s,由若干单词组成,单词之间用空格隔开。返回字符串中最后一个单词的长度。如果不存在最后一个单词,请返回 0 。
'''
class Solution:
def lengthOfLastWord(self, s: str) -> int:
length = 0
start = False
for i in range(len(s) - 1, -1, -1):
if not start and s[i] == ' ':
pass
elif not start:
... |
# 幸运N串,允许最多改变两个大写字母,求得最大的N串长度
tests = [
'NNNGN',
'NNNNNSSNN',
'NNNNXXNNXXNNNNNNN',
'NNNXNNNNNNXNNNNNNXXNNNNNNNNNNNNNNNNN'
]
def lucky(string):
# 存放最终结果
best = 0
# 记录可以改变的次数
chance = 0
# 记录回溯位置
back = [0, 0]
# 当前长度
length = 0
# 字符串索引
i = 0
while i < len(string... |
'''
Log in color from
https://stackoverflow.com/questions/287871/how-to-print-colored-text-in-terminal-in-python
usage :
import log
log.info("Hello World")
log.err("System Error")
'''
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD ... |
class SpecialError(Exception):
"""
Exception raised when there is an error while parsing a special.
"""
def __init__(self, attribute, content=None):
self.attribute = attribute
self.content = content
def __str__(self):
return (f"Unable to parse '{self.attribute}'\n"
... |
shema = """
-------------------
| {} | {} | {} |
| {} | {} | {} |
| {} | {} | {} |
-------------------
"""
print("""
---------------------------------
| Tik-Tac-Toe |
---------------------------------
| Yapımcı : Beetlejuicetr (MID) |
| Dil : Python 3.9.7 |
| Sürüm : v... |
#!/usr/bin/python
#
# Provides __ROR4__, __ROR8__, __ROL4__ and __ROL8__ functions.
#
# Author: Satoshi Tanda
#
################################################################################
# The MIT License (MIT)
#
# Copyright (c) 2014 tandasat
#
# Permission is hereby granted, free of charge, to any person obtaini... |
#crie um pgm q pergunte a dist de uma viagem em Km.
#Calcule o preço da passagem, cobrando R$0,50 por Km para viagens de até 200Km e R$0,45 para viagens mais longas.
viagem = int(input('Digite a distancia da viagem: Km'))
'''if viagem <= 200:
print('O valor da passagem esta R${:.2f}, boa viagem'.format(viagem * 0.5... |
'''
PARTITION PROBLEM
The problem is to identify if a given set of n elements can be divided
into two separate subsets such that sum of elements of both the subsets
is equal.
'''
def check(a, total, ind):
if total == 0:
return True
if ind == -1 or total < 0:
return False
if a[ind] > total:... |
n = int(input())
arr = list(map(str, input().split()))[:n]
ans = ""
for i in range(len(arr)):
ans += chr(int(arr[i], 16))
print(ans) |
# File: D (Python 2.4)
GAME_DURATION = 300
GAME_COUNTDOWN = 10
GAME_OFF = 0
GAME_ON = 1
COOP_MODE = 0
TEAM_MODE = 1
FREE_MODE = 2
SHIP_DEPOSIT = 0
AV_DEPOSIT = 1
AV_MAX_CARRY = 200
GameTypes = [
'Cooperative',
'Team vs. Team',
'Free For All']
TeamNames = [
'Red',
'Blue',
'Green',
'Orange',
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 19 13:58:37 2018
@author: Nihar
"""
sqr=[]
for i in range(10):
sq=(i+1)*(i+1)
sqr.append(sq)
print(sqr)
cube=[]
for i in range(10):
sq=(i+1)**3
cube.append(sq)
print(cube) |
"""
PredictGrade.py
================================================
This module contains the runner code for the predict grade package.
"""
# from DataSet import DataSet
# from Models import Models
# from Predictor import Predictor
# from ModelType import ModelType
# from Grade import Grade
# from TextInterface import... |
"""Coins.
Given an infinite supply of quarters dimes, nickels, and pennies,
wrote code to represent the number of ways to represent n cents.
"""
def calc_num_coins(n):
"""Calc the num of coins."""
def add_coin(total=0):
"""."""
if total > n:
return 0
if total == n:
... |
#!/usr/bin/python
class TaggedAttribute(object):
"""Simple container object to tag values with attributes.
Feel free to initialize any node with a TA instead of its actual
value only and it will then have the desired metadata. For example:
from pylink import TaggedAttribute as TA
tx_power = TA(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.