content stringlengths 7 1.05M |
|---|
# DESAFIO 009 - CRIANDO UMA TABUADA:
n = float(input('Digite um número para ver a sua tabuada: '))
print('='*10)
print('{:.0f} x 1 = {:.0f}'.format(n, (n*1)))
print('{:.0f} x 2 = {:.0f}'.format(n, (n*2)))
print('{:.0f} x 3 = {:.0f}'.format(n, (n*3)))
print('{:.0f} x 4 = {:.0f}'.format(n, (n*4)))
print('{:.0f} x 5 = {:... |
morningcall_msg = '''
[CQ:face,id=74] 早上好,
今天是 {date} 日,星期{weekday}
{weather},{tmp_min}~{tmp_max}℃
{comf}{drsg}
{class}
{one}
'''
morningcall_class_msg = '''
第 {class_num} 节:{class_name}'''
morningcall_love_msg = '''
[CQ:face,id=74] 早安[CQ:at,qq=1299903489],早安[CQ:at,qq=937734121]
今天是 {date} 日,星期{weekday}
我们在一起已经 {lo... |
print("Hai")
print("Hai")
print("Hai")
print("Hai")
print("Hai")
print("Hai")
print("Hai")
|
COUNTRIES = {
'colombia': 31,
'argentina': 45,
'venezuela': 12,
'peru': 22,
'ecuador': 55,
'mexico': 143,
}
while True:
country = str(input('Ingresa el nombre del pais: ')).lower()
try:
print('El numero de habiantes en {} es de {} millones de habitantes'. format(country , COUNTRIES[country]))
except ... |
"""Constant."""
IGNORE_REGEX_LIST = [
r'.*HOISS.*',
r'.*HHS.*',
r'.*semmbomeSaqQo.*',
r'.*Honomasenid.*',
r'.*SAwwwy.*',
r'.*\+94.*',
r'.*163, Borgen.*',
r'.*Age Group.*',
r'.*Anexirenen novelas.*',
r'.*ce.*mbme.*',
r'.*cermmboe*',
r'.*dasenrd.*',
r'.*dasombd.*',
... |
#!/usr/bin/env python
# coding: utf-8
# # Pachyderm-Seldon Integration: Version Controlled Models
#
# [Pachyderm](https://pachyderm.io/) is a data science platform that combines Data Lineage with End-to-End Pipelines. [Seldon-Core](https://www.seldon.io/tech/products/core/) is an open-source platform for rapidly depl... |
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
dirs = [(0, 1), (1, 0), (0, -1), (-1, 0)]
curr_dir, curr_pos = 0, (0, 0)
for instruction in instructions:
if instruction == "R":
curr_dir = (curr_dir + 1) % 4
elif instructio... |
# Created by Elshad Karimov
# Copyright © AppMillers. All rights reserved.
# Validate BST
# write an algorithm to find the in-order successor of a given node in a BST
class Node:
def __init__(self, key):
self.data = key
self.left = None
self.right = None
def insert(node, data):
if node is None:
... |
# Time: ctor: O(1)
# addText: O(l)
# deleteText: O(k)
# cursorLeft: O(k)
# cursorRight: O(k)
# Space: O(n)
# design, stack
class TextEditor(object):
def __init__(self):
self.__LAST_COUNT = 10
self.__left = []
self.__right = []
def addText(self... |
# 打印输出从文件读取的所有行的字符串(readlines方法)
f = open('hello.txt') # 打开(文本+读取模式)
lines = f.readlines()
for line in lines:
print(line, end='')
f.close() # 关闭
|
'''
Los generadores son exhaustivos, quiere decir que después de llamar los valores que necesita se agotan al llamarlos en un loop.
LLamar next en un generador exhausto hace un raise: stopIteration
'''
even = (n%2 for n in range(10))
# Loop for de un generador.
for n in (i for i in range(10)):
print(n)
# Pue... |
def distance(n, point1, point2):
point1_x, point1_y = point1
point2_x, point2_y = point2
if abs(point1_x) >= n or abs(point1_y) >= n or abs(point2_x) >= n or abs(point2_y) >= n:
raise ValueError("coords are not from given range")
dist_x = min(abs(point1_x - point2_x), point1_x + (n - point2_x)... |
"""
https://leetcode.com/problems/lru-cache/
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or in... |
def word(parola:str):
tratto = "_ "
trattini = tratto*len(parola)
return trattini
def continue_sostitution(original_parola:str, modified_parola:str, letter:str, index:int):
line = modified_parola[:index]
line += letter
line += modified_parola[index+1:]
return line
def initial_sostitution(... |
number = input("Input a number to invert its order:")
print("Printing using string: " + number[::-1])
inverted = 0
exponent = len(number)
number = int(number)
while number >= 1:
inverted += (number % 10) * (10 ** (exponent - 1))
exponent -= 1
number = number // 10 # the floor division // rounds t... |
__version_tuple__ = (0, 6, 0, 'dev.1')
__version__ = '0.6.0-dev.1'
__version_tuple_js__ = (0, 6, 0, 'dev.1')
__version_js__ = '0.6.0-dev.1'
# kept for embedding in offline mode, we don't care about the patch version since it should be compatible
__version_threejs__ = '0.97'
|
# 1. Реализовать класс Matrix (матрица). Обеспечить перегрузку конструктора класса (метод init()), который должен
# принимать данные (список списков) для формирования матрицы.
# Подсказка: матрица — система некоторых математических величин, расположенных в виде прямоугольной схемы.
# Примеры матриц вы найдете в методич... |
#===============================================================================
# Copyright 2022 Intel Corporation
#
# 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.a... |
class BubbleSort:
name = 'Bubble sort'
history = []
focus = []
def reset(self):
self.history = []
self.focus = []
def sort(self, unsorted_list):
self.bubble_sort(unsorted_list)
return unsorted_list
# stable
# O(1) space complexity
# O(n2) comparisons... |
"""
Event Calendar Module.
The event calendar channel is how the Events cog shows upcoming events
to users. It is configured per server, with two types of events - member
events, and recurring events.
Member events are initiated by members and approved by moderators in
an approval channel, while recurring events, whi... |
def hello() -> str:
"""
Used to test that the library is installed successfully.
Returns
----------
The string 'world'.
"""
return "world"
|
{
'includes': [
'../defaults.gypi',
],
'targets': [
{
'target_name':
'DirectZobEngine',
'type':
'static_library',
'dependencies': [
'../dependencies/minifb/minifb.gyp:minifb',
'../dependencies/tinyxml... |
"""
Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].
"""
class Solution():
# @param A : tuple of integers
# @return an integer
def maximumGap(self, A):
n = len(A)
index = dict()
for i in range(n):
if A[i] in index:
... |
msg1 = 'Qual é o salário do funcionário? R$'
salário1 = float(input(msg1))
pct = 15
salário2 = salário1 * (100 + pct) / 100
msg2 = 'Um funcionário que ganhava R${:.2f}, com {}% de aumento, passa a receber R${:.2f}.'.format(salário1, pct, salário2)
print(msg2)
|
# -----------------------------------------------------------------------
print('\033[32;1mDESAFIO 037 - Conversor de Bases Numéricas\033[m')
print('\033[32;1mALUNO:\033[m \033[36;1mJoaquim Fernandes\033[m')
print('-' * 50)
# -----------------------------------------------------------------------
def BasesConversor()... |
fruits = ["apple","orange","pear"]
for fruit in fruits:
print(fruit)
print(fruits[0])
print(fruits[1])
print(fruits[2])
for v in range(10):
print(v)
for v in range(5,10):
print(v)
for v in range(len(fruits)):
print(v)
print(fruits[v])
print(len(fruits)) |
# r/GlobalOffensive/comments/cjhcpy/game_state_integration_a_very_large_and_indepth
# Game state integration round descriptor
class Round(dict):
# The phase of the current round. Value is freezetime during the initial
# freeze time as well as team timeouts, live when the round is live, and
# over when the... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
web 应用
'''
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
body = '<h1>Hello, %s!</h1>' % (environ['USER'] or 'web')
print(environ)
return [body.encode('utf-8')] |
#!/usr/bin/env python
__all__ = (
'Goat',
'_Velociraptor'
)
class Goat:
@property
def name(self):
return "George"
class _Velociraptor:
@property
def name(self):
return "Cuddles"
class SecretDuck:
@property
def name(self):
return "None of your business"
|
#def basic(x, y):
# answer = x * y + 3
# # print(answer)
# # return f"{x} * {y} + 3 = {answer}"
# return answer
#
#
#print(basic(7, 10))
#grade = 25 + basic(7, 10)
#print(grade)
#
#
#def more_advanced(x, y, store_data=True, save_file="myanswer.txt"):
# ans = x ** (y-3)
# if store_data:
# with o... |
def LinearSearch(array, key):
for index, theValue in enumerate(array):
if(array[index] == key):
return index
return -1
def main():
theArray = [2, 5, 25, 6, 8, 9, 1, 0, 6, 8, 4, 5, 66, 548, 889]
print("The index of the 25 is: ", LinearSearch(theArray, 25))
print("The index of th... |
[x**2 for x in range(1, 10)]
[x**2 for x in range(1, 10) if x % 2 == 0]
powers_of_2 = []
for x in range(1, 10):
powers_of_2.append(x**2)
powers_of_2 = []
for x in range(1, 10):
if x % 2 == 0:
powers_of_2.append(x**2)
[x*y for x in range(1, 10) if x % 2 == 1 for y in range(10) if y % 2 == 1]
... |
# Given two strings A and B of lowercase letters, return true if and only if we can swap two letters in A so that the result equals B.
# Example 1:
# Input: A = "ab", B = "ba"
# Output: true
# Example 2:
# Input: A = "ab", B = "ab"
# Output: false
# Example 3:
# Input: A = "aa", B = "aa"
# Output: true
# Example 4:
#... |
S = [input() for _ in range(4)]
if sorted(S) == ['2B', '3B', 'H', 'HR']:
print('Yes')
else:
print('No')
|
# -*- coding: utf-8 -*-
DATABASE_TIMEZONE = 'UTC'
DEFAULT_TIMEZONE = 'Asia/Shanghai'
|
# https://bitbucket.org/dimagi/cc-apps/src/caab8f93c1e48d702b5d9032ef16c9cec48868f0/bihar/mockup/bihar_pnc.xml
# https://bitbucket.org/dimagi/cc-apps/src/caab8f93c1e48d702b5d9032ef16c9cec48868f0/bihar/mockup/bihar_del.xml
# https://bitbucket.org/dimagi/cc-apps/src/caab8f93c1e48d702b5d9032ef16c9cec48868f0/bihar/mockup/b... |
class A:
def y(self):
pass
a = A()
a.y()
|
a = int(input())
def match(p):
st = []
for c in p:
if c == '(':
st.append(c)
if c == ')':
if len(st) == 0:
print("NO")
return
else:
st.pop(0)
if len(st) == 0:
print("YES")
else:
print("NO... |
def moveZero(arr):
length = len(arr)
i = 0
k = 0
while k < length:
if arr[i] == 0:
temp = arr.pop(i)
arr.append(temp)
i -= 1
i += 1
k += 1
arr = [0, 1, 0, 3, 12, 0]
moveZero(arr)
print(arr) |
#
# PySNMP MIB module Dell-rldot1q-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Dell-rldot1q-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:57:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
# This Python file contains the constants used by any Python codes leveraged by the contact book application
# for ease of maintainability.
ROOT_DIR_CONTACTS_DICT_FILE = 'contact_book/src/contact_book/data/'
FILE_NAME_CONTACTS_DICT = 'contacts_dict.txt'
TEXT_FONT_AND_SIZE_FORMAT_WINDOW_FRAME = "*font"
TEXT_FONT_AND_S... |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def longestUnivaluePath(self, root: TreeNode) -> int:
if root == None:
return 0
self.max_count = 0
self.caller(... |
a = list(map(int, input().split()))
def kangaroo(x1, v1, x2, v2):
if x1>x2 and v1>v2:
return'NO'
elif x2>x1 and v2>v1:
return 'NO'
else:
result = 'NO'
for i in range(10000):
if x1+i*v1==x2+i*v2:
result = 'YES'
break
retu... |
"""tnz utility functions
Usage: from . import _util.py
Copyright 2021 IBM Inc. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
"""
__author__ = "Neil Johnson"
_SESSION_PS_SIZES = {
"2": (24, 80),
"3": (32, 80),
"4": (43, 80),
"5": (27, 132),
"6": (24, 132),
"7": (36, 80),
"8": ... |
def operator_insertor(n):
res=helper("123456789", 0, n)-1
return res if res!=float("inf") else None
def helper(s, index, n):
if index>=len(s):
return 0 if n==0 else float("inf")
res=float("inf")
cur=0
for i in range(index, len(s)):
cur=cur*10+int(s[i])
res=min(res, helper... |
{
"targets": [
{
"target_name": "rdiff",
"sources": [
"rdiff.cc"
],
"link_settings": {
"libraries": [
"-lrsync",
"-lz"
]
},
"include_dirs" : [
"<!(node -e \"require('nan')\")"
],
}
]
} |
class Solution:
def canJump(self, nums: List[int]) -> bool:
value = len(nums)-1 #그리디 방법 활용
for i in range(len(nums)-1, -1, -1):
if i + nums[i] >= value:
value = i
if value == 0:
return True
else:
return Fa... |
class UniformResourceLocatable:
"""
Represents an object with a URL.
"""
__slots__ = ()
_fields = {
"resource_path": "resourcePath",
"url": "url",
}
@property
def resource_path(self):
"""
An HTTP path to the resource.
:type: :class:`str`
... |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
pre = -100000
cnt = 0
i = -1
j = 0
while j < len(nums):
if nums[j] != pre:
i += 1
nums[i] = nums[j]
cnt = 1
elif cnt < 2:
i += 1
nums[i] = nums[j]
cnt += 1
pre = nu... |
class BaseArg:
@staticmethod
def read_argument(parser):
raise NotImplementedError()
@staticmethod
def add_argument(parser):
raise NotImplementedError()
|
"""Constants for Gafaelfawr."""
ALGORITHM = "RS256"
"""JWT algorithm to use for all tokens."""
COOKIE_NAME = "gafaelfawr"
"""Name of the state cookie."""
HTTP_TIMEOUT = 20.0
"""Timeout (in seconds) for outbound HTTP requests to auth providers."""
MINIMUM_LIFETIME = 5 * 60
"""Minimum expiration lifetime for a token ... |
#
# PySNMP MIB module CISCO-UNIFIED-COMPUTING-DUPE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-UNIFIED-COMPUTING-DUPE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:15:29 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
"""
File contains all needed constants for net file reading
"""
EDGE_SECTION_HEADER = "$STRECKE"
EDGE_NAME_HEADER = "NR"
EDGE_FROM_NAME_HEADER = "VONKNOTNR"
EDGE_TO_NAME_HEADER = "NACHKNOTNR"
LINE_SECTION_HEADER = "$LINE"
LINE_NAME_HEADER = "NAME"
LINE_VSYSCODE_HEADER = "TSYSCODE"
LINE_VEHICLE_COMBINATION_NUMBER_HEADER... |
"""
A group of code statements which can perform some specific task
Methods are reusable and can be called when needed in the code
"""
def sum_nums(n1, n2):
"""
Get sum of two numbers
:param n1:
:param n2:
:return:
"""
return n1 + n2
sum1 = sum_nums(2, 8)
sum2 = sum_nums(3, 3)
string_ad... |
MAIN_DISPLAY = "$显示字段$"
MAIN_AVATAR = "$显示头像$"
MAIN_PIC = "$显示图片$"
SYS_LABELS = ['contenttypes','auth']
INTENTION= ' ' |
"""
public, protected, private
_ privado/protected (public _)
__ privado (_NOMECLASSE__nomeatributo)
"""
class BaseDeDados:
def __init__(self):
self.__dados = {}
@property
def dados(self):
return self.__dados
def inserir_clientes(self, id, nome):
if 'clientes' not in self.__d... |
{
'name': 'Base Kanban',
'category': 'Hidden',
'description': """
OpenERP Web kanban view.
========================
""",
'version': '2.0',
'depends': ['web'],
'js': [
'static/src/js/kanban.js'
],
'css': [
'static/src/css/kanban.css'
],
'qweb' : [
'static/... |
"""
Extract the dictionary definition: Takes the third element s3 returned by `split_entry()`
>>> from GDLC.GDLC import *
>>> dml = '''\
... <blockquote class="calibre27">
... <p class="ps">Definition here.</p>
... <p class="p">More details here.</p>
... <p class="p">Even more details here.</p>
... </blockquote... |
# Find the cube root of a perfect cube
n = int(input("Enter an integer: "))
ans = 0
while ans ** 3 < abs(n):
ans += 1
if ans ** 3 != abs(n):
print(n, "is not a perfect cube")
else:
if n < 0:
ans = -ans
print("Cube root of", n, "is", ans) |
#camera_setting
########################################
bpy.ops.object.camera_add(location=(0, 0, 15.5),rotation=(math.pi/4, 0, math.pi/2))
camera=bpy.data.objects['Camera']
world=bpy.data.worlds['World']
d_camera=bpy.data.cameras['Camera']
world.light_settings.use_environment_light=True#環境光を使用
world.light_settings.... |
# coding: utf-8
# criamos um validador pré definido
notempty = IS_NOT_EMPTY(error_message=e_m['empty'])
# definição da tabela de marcas
db.define_table('marca',
Field('nome', unique=True, notnull=True),
format='%(nome)s'
)
# validadores da tabela de carros
db.marca.nome.requires=[notempty, IS_NOT_IN_DB(db, 'marca... |
A = float(input('Primeiro lado: '))
B = float(input('Segundo lado: '))
C = float(input('Terceiro lado: '))
if (A + C) > B > abs(A - C) and (A + B) > C > abs(A - B) and (B + C) > A > abs(B - C):
possível = True
else:
possível = False
if possível:
print('possível')
else:
print('impossível')
... |
#
# @lc app=leetcode.cn id=457 lang=python3
#
# [457] 环形数组是否存在循环
#
# https://leetcode-cn.com/problems/circular-array-loop/description/
#
# algorithms
# Medium (36.95%)
# Likes: 152
# Dislikes: 0
# Total Accepted: 25.9K
# Total Submissions: 59.7K
# Testcase Example: '[2,-1,1,2,2]'
#
# 存在一个不含 0 的 环形 数组 nums ,每个 nu... |
class Solution:
def replaceElements(self, arr: list[int]) -> list[int]:
largest_value = -1
for index, num in reversed(list(enumerate(arr))):
arr[index] = largest_value
largest_value = max(largest_value, num)
return arr
tests = [
(
([17, 18, 5, 4, 6, 1],... |
# nlantau, 2020-11-09
def evens_and_odds(n):
return f"{n:b}" if n % 2 == 0 else f"{n:x}"
print(evens_and_odds(1))
print(evens_and_odds(2))
print(evens_and_odds(3))
print(evens_and_odds(13))
|
# -*- coding: utf-8 -*-
'''
Given n non-negative integers a1, a2, ..., an,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container,
such that the container contains the ... |
a = 5
b = a
print(a,b)
a = 3
print(a,b)
|
# Activity Select
def printMaxActivity(s, f):
n = len(f)
print('The Following Activitices are selected.')
i = 0
print(i)
for j in range(n):
if (s[j] >= f[i]):
print(j)
i = j
s = [1, 3, 0, 5, 8, 5]
f = [2, 4, 6, 7, 9, 9]
printMaxActivity(s, f)
''... |
# Roman Ramirez, rr8rk@virginia.edu
# Advent of Code 2021, Day 09: Smoke Basin
#%% LONG INPUT
my_input = []
with open('input.txt', 'r') as f:
for line in f:
my_input.append(line.strip('\n'))
#%% EXAMPLE INPUT
my_input = [
'2199943210',
'3987894921',
'9856789892',
'8767896789',
'989... |
#
# @lc app=leetcode.cn id=1753 lang=python3
#
# [1753] 移除石子的最大得分
#
# @lc code=start
class Solution:
def maximumScore(self, a: int, b: int, c: int) -> int:
maxvale, sumup = max((a, b, c)), a + b + c
if sumup < maxvale * 2:
return sumup - maxvale
else:
return sumup /... |
#program that guess a number between 0 to 100
low=0
High=100
medium=(low+High) //2
state =True
print("please Enter a number between 0 to 100 ")
while state :
print("is your secret number:"+ str(medium))
guess=input("Enter h if indicates is high and enter 'l' is low ")
if guess=='c':
print("GAME OV... |
def adiciona_item(nome, lista):
backup=[]
if len(lista)==0:
lista.append(nome)
return
else:
for i in range(len(lista)-1, -1, -1):
if nome<lista[i]:
if nome<lista[i] and i == 0:
backup.append(lista.pop())
lista.append... |
# Currency FX rate settings
BASE_URL = 'https://www.x-rates.com/calculator/?from={}&to={}&amount=1'
BASE_CURRENCY = 'JPY'
TO_CURRENCY_LIST = ['AUD', 'CNY', 'USD', 'GBP']
# Alert threshold for sending push notification
ALERT_THRESHOLD = [
{'fx_pair': 'JPY/AUD', 'buy-threshold': 0.0134, 'sell-threshold': 0.0137},
... |
_base_ = [
'../_base_/models/resnet18.py',
'../_base_/datasets/imagenet_bs32.py',
'../_base_/schedules/imagenet_bs1024.py',
'../_base_/default_runtime.py'
]
actnn = True
data = dict(
samples_per_gpu=256, # 256*4 = 1024
workers_per_gpu=8,
)
log_config = dict(
interval=100,
hooks=[
... |
"""
.. _hosted_multi_images:
Multiple Container Images in a Single Workflow
----------------------------------------------
When working locally, it is typically preferable to install all requirements of your project locally (maybe in a single virtual environment). It gets complicated when you want to deploy your code... |
train_dataset_seed = 1234
test_dataset_seed = 4321
n_test_dataset = 100
is_subtype = mlprogram.languages.python.IsSubtype()
normalize_dataset = mlprogram.utils.transform.NormalizeGroundTruth(
normalize=mlprogram.functools.Sequence(
funcs=collections.OrderedDict(
items=[["parse", parser.parse], ... |
def c3():
global x1
global y1
global x2
global y2
global x3
global y3
global x4
global y4
x1=float(input("What are your x1?"))
y1=float(input("What are your y1?"))
x2=float(input("What are your x2?"))
y2=float(input("What are your y2?"))
x3=float(input("What are your x3?"))
y3=float(input("W... |
SHOW_FILM_NAMES = True
# SHOW_FILM_NAMES = False
# UPDATE_TEXT_BOX_LOC = False
UPDATE_TEXT_BOX_LOC = True
SHORTEN_FILM_NAMES = True
# READ_PARTIAL_DB = True
READ_PARTIAL_DB = False
# HIGH_RES = False
HIGH_RES = True
EXPIRE_FILM_NAMES = True
# EXPIRE_FILM_NAMES = False
#SLIDING_WINDOW = False
SLIDING_WINDOW = True... |
def monkey_trouble(a_smile, b_smile):
if a_smile is True and b_smile is True:
return True
elif a_smile is False and b_smile is False:
return True
else:
return False
|
class Queue:
def __init__(self):
self.elements = []
def __str__(self):
return f"{[element for element in self.elements]}"
def __repr__(self):
return f"{[element for element in self.elements]}"
def enqueue(self, element):
self.elements.append(element)
def dequeue(s... |
TEMP_ENV_VARS = {
'TELEGRAM_WEBHOOK_KEY': '',
}
ENV_VARS_TO_SUSPEND = [
] |
#
# PySNMP MIB module ALCATEL-IND1-TIMETRA-SERV-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-TIMETRA-SERV-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:19:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... |
spacy_model_names = {
"en": "en_core_web_md",
"fr": "fr_core_news_md",
"es": "es_core_news_md"
}
# 17 for English.
# 15 for French: replace "INTJ" (7 entries) or "SYM" with "X" (1296 entries).
# 16 for Spanish: Change "X" (1 entry) to "INTJ" (27 entries)
spacy_pos_dict = {
"en": ['ADJ', 'ADP', 'ADV',... |
class GeneratorStatus(Enum, IComparable, IFormattable, IConvertible):
"""
Used by System.Windows.Controls.ItemContainerGenerator to indicate the status of its item generation.
enum GeneratorStatus,values: ContainersGenerated (2),Error (3),GeneratingContainers (1),NotStarted (0)
"""
def __eq__(s... |
def reverse(value):
if not isinstance(value, str):
return None
result = ''
for i in reversed(range(len(value))):
result += value[i]
return result |
# ADDITION (plus signal)
print (5 + 5)
# SUBTRACTION (minus signal)
print (85 - 72)
# MULTIPLICATION (times signal)
print (8 * 7)
# DIVISION (split signal)
print (56 / 12)
print(5 / 2) # Quotient, number of times a division is completed fully
print(5 // 2) # Always return an integer number
# REMAINDER
print(6... |
#Escreva um programa que leia dois números inteiros e compare-os, mostrando na tela uma mensagem:
#O primeiro valor é maior
#O Segundo valor é maior
#Não existe valor maior, os dois são iguais
num= int(input("Digite um número: "))
num2= int(input("Digite outro número: "))
if num > num2:
print("O primeiro valor é ... |
class DataGridPreparingCellForEditEventArgs(EventArgs):
"""
Provides data for the System.Windows.Controls.DataGrid.PreparingCellForEdit event.
DataGridPreparingCellForEditEventArgs(column: DataGridColumn,row: DataGridRow,editingEventArgs: RoutedEventArgs,editingElement: FrameworkElement)
"""
@staticmet... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
##############################################################################
# Copyright 2020 AlexPDev
#
# 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 Lice... |
fileObj = open("words.txt")
array = []
for word in fileObj:
array.append(word.rstrip())
fileObj.close()
final = "var words = ["
for element in array:
final += "\"" + element + "\","
final = final[:-1]
final += "]"
fileOut = open("output.js", "w")
fileOut.write(final)
fileOut.close()
|
IMPALA_RESERVED_WORDS = (
"abs",
"acos",
"add",
"aggregate",
"all",
"allocate",
"alter",
"analytic",
"and",
"anti",
"any",
"api_version",
"are",
"array",
"array_agg",
"array_max_cardinality",
"as",
"asc",
"asensitive",
"asin",
"asymmetr... |
# Количество слов
def number_of_words(string):
return string.count(' ') + 1
if __name__ == '__main__':
string = input()
print(number_of_words(string))
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe")
load("@rules_foreign_cc//foreign_cc:repositories.bzl", "rules_foreign_cc_dependencies")
def deps(repo_mapping = {}):
rules_foreign_cc_dependencies()
maybe(
http_archive,
... |
jInicial = 7
iInicial = 1
for i in range (1, 10, +2):
iDaConta = i - iInicial
j = iDaConta + jInicial
print("I={} J={}".format(i, j))
print("I={} J={}".format(i, j-1))
print("I={} J={}".format(i, j-2))
|
# 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 isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(nd):
if not nd: retur... |
# Runs to perform
control = True
saltproc = True
linear_generation = False
cycle_time_decay = True
linear_isotope = False
# Basic model using ln(1 / (1 - X)) WIP
efficiency_based = False
saltproc_efficiency_based = False
# Separate core piping is WIP
separate_core_piping = False
# Options
plotting = True
ov... |
def normalize_start_end(x, inds=20):
mi = x[:inds, :].mean(axis=0)
ma = x[-inds:, :].mean(axis=0)
return (x - mi) / (ma - mi)
def normalize_end_start(x, inds=20):
ma = x[:inds, :].mean(axis=0)
mi = x[-inds:, :].mean(axis=0)
return (x - mi) / (ma - mi)
|
class SetUnionRank:
def __init__(self, arr):
self.parents = arr
self.ranks = [0] * self.size
@property
def size(self):
return len(self.parents)
def find(self, i):
while i != self.parents[i - 1]:
i = self.parents[i - 1]
return i
def union(self, ... |
# run with python 3
def binary_representation(number):
if number > 1:
binary_representation(number//2)
print(number%2, end="")
binary_representation(4)
print()
binary_representation(7)
print() |
# Copyright 2020 IBM Corporation
#
# 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, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.