content stringlengths 7 1.05M |
|---|
def print_array(a):
print('===')
print(f'a: {a}')
print(f'a[:-1]: {a[:-1]}')
print(f'a[1:]: {a[1:]}')
print(f'a[:2]: {a[:2]}')
print(f'a[2:]:{a[2:]}')
print('===')
def main():
print_array([0, 1, 2, 3, 4, 5])
print_array([2,3])
print_array([64, 16, 10])
if __name__ == "__main_... |
#Faça um programa que mostre ao usuário um menu com 4 opções
#de operações matemáticas (as básicas, por exemplo).
#O usuário escolhe uma das opções e o seu programa então
#pede dois valores numéricos e realiza a operação, mostrando
#o resultado e saindo.
menu=int(input("\tMENU\n1-Adição\n2-Subtração\n3-Multiplicação\n... |
"""
for two input arrays, find the closest two elements
"""
def smallestDifference(arrayOne, arrayTwo):
# Write your code here.
smallest = float("inf")
res = []
for eleone in arrayOne:
for eletwo in arrayTwo:
if abs(eleone -eletwo) < smallest:
smallest = abs(eleone-eletwo)
res = [eleone, eletwo]
re... |
d = {}
n = int(input())
cnt = 0
while True:
cnt +=1
N = "%04d" % n
middle = int(N[1:3])
square = middle * middle
n = square
try:
d[square] +=1
except:
d[square] = 1
else:
break
print(cnt) |
# Copyright (C) 2018 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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
def suggest_work_out (backpain, history, age, gender, height, weight, skeletal_muscle, body_fat, smoke ):
bmi = (weight)/((height*0.01)**2)
body_fat_percent = (body_fat/weight)*100
skeletal_muscle_percent = (skeletal_muscle/weight)*100
if smoke == 'YES':
return(["흡연을 하고도 허리왕이 될수있을거라 생각하십니까?","흡연자는 허리왕이... |
classmates = ['yang', 'wang', 'han']
print('classmates=', classmates)
print('classmates[0]=', classmates[0])
print('classmates[1]=', classmates[1])
print('classmates[2]=', classmates[2])
print('classmates[-1]=', classmates[-1]) # 用-1做索引,直接获取最后一个元素
classmates.pop()
print("classmates=", classmates)
classmates.append('li... |
'''
Microsoft has come to hire interns from your college. N students got shortlisted out of which few were males and a few females. All the students have been assigned talent levels. Smaller the talent level, lesser is your chance to be selected. Microsoft wants to create the result list where it wants the candidates ... |
"""Dummy objects."""
class DummyProgress(object):
def __enter__(self):
return self
def __exit__(self, *args):
pass
def update(self, value):
pass
def close(self):
pass
|
# Find the last element of a list.
# a = [1, 4, 6, 2, 0, -3]
# print(a[-1])
# Find the second to last element of a list.
# a = [1, 4, 6, 2, 0, -3]
# print(a[-2])
# Find all elements from the third to last element of a list to the last one.
# a = [1, 4, 6, 2, 0, -3]
# print(a[-3:])
# Find the k'th e... |
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
res=0
left=0
right = 0
while right<len(nums):
if nums[right]==1:
res=max(res,right-left+1)
else:
left=right+1
right+=1
return res... |
# -*- coding: utf-8 -*-
################################################################################
# Object Returned from vision
################################################################################
class RecognizedObject:
def __init__(self, category=None, posi... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
class OSSecurityGroupsV2(object):
def on_get(self, req, resp, tenant_id, instance_id=None):
resp.body = {
'security_groups': [{
'description': 'default',
'id': 1,
'name': 'default',
'rules': {},
'tenant_id': tenant... |
#! /usr/bin/env python
# coding: utf-8
__author__ = 'ZhouHeng'
class IPManager(object):
def __init__(self):
self.ip_1a = 256
self.ip_2a = self.ip_1a * self.ip_1a
self.ip_3a = self.ip_1a * self.ip_2a
self.ip_4a = self.ip_1a * self.ip_3a
def ip_value_str(self, ip_str=None, ip_v... |
#string
s = "I am a string."
print(type(s)) #returns str
#Boolean ...these are specifically true or false. NO possibility you would have the wrong precision.
yes = True #Boolean True, "True" is a protected term in python
print(type(yes)) #boolean
no = False
print(type(no))
#List -- ordered and changeable ... |
"""
Utilidades del front
"""
# Clase abstracta de la que heredaran mis fronts
class Board:
def init(self, data):
pass
def print_board(self, size):
pass
|
def eleva_potencia_cc(a,b):
'''
Eleva número "a" a la "b" potencia.
Insumo (input):
a: número
b: número
Producto (output):
resultado: un número
'''
z_var = 11
c = 10 + z_var
resultado = a**b + c
return resultado
def eleva_potencia_dd(a,b):
'''
Elev... |
# coding: utf-8
s = input()
k = int(input())
w = [int(i) for i in input().split()]
li = []
for ch in s:
li.append(w[ord(ch)-ord('a')])
li.extend([max(w)]*k)
ans = 0
for i in range(0,len(li)):
ans += (i+1)*li[i]
print(ans)
|
"""
International Morse Code defines a standard encoding where each letter is mapped to
a series of dots and dashes, as follows: "a" maps to ".-", "b" maps to "-...", "c"
maps to "-.-.", and so on.
For convenience, the full table for the 26 letters of the English alphabet is given below:
'a':".-",
'b':... |
answer_filename='g0pA_taskb.txt'
n=3
answer_row = complete_df.loc[complete_df['File'] == answer_filename]
task = answer_row['Task'].values[0]
answer = answer_row['Text'].values[0]
source = complete_df.loc[(complete_df['Datatype'] == 'orig') &
(complete_df['Task'] == task... |
#!/usr/bin/python3.5
# Solves the magic hexagon problem for n = 3 by brute force
# https://en.wikipedia.org/wiki/Magic_hexagon
line_jumps = [3, 4, 5, 4, 3]
lines = [
[0, 1, 2],
[3, 4, 5, 6],
[7, 8, 9, 10, 11],
[12, 13, 14, 15],
[16, 17, 18],
[7, 3, 0],
[12, 8, 4, 1],
[16, 13, 9, 5, 2],
[17, 14, 10, 6],
[18,... |
#2. d = {"name":"python", “age”:18, “fun”:"all"},生成一个列表["name=python", “age=18”, “fun=all”]
mydic = {"name":"python", "age":18, "fun":"all"}
l = []
for k, v in mydic.items():
l.append(str(k)+"="+str(v))
print(l)
|
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
Escribir un algoritmo que sume los números ingresados por el usuario y
cuando la suma sea superior a 100 deje de pedir números y muestre el
total.
"""
suma = 0
while True:
numero = input("Ingrese un número: ")
try:
numero = int(numero)
... |
class TransactionData():
def __init__(self):
self.data_frame = None
self.train_df = None
self.test_df = None
self.validation_df = None
self.train_indexes = {}
self.test_indexes = {}
self.validation_indexes = {}
self.all_indexes = {}
self.co... |
class Edge:
def __init__(self, start, end, cost, length, direction):
self.start = start
self.end = end
self.cost = cost
self.length = length
self.direction = direction
self.is_visited = False
self.length_by_cost = length/cost
# making global variables
def... |
def get_attribute(attributes, attribute_name, default_value=None):
attribute = next(item for item in attributes if item.Name == attribute_name)
if attribute:
return attribute.Value
if default_value:
return default_value
raise ValueError('Attribute {0} is missing'.format(attribute_name)... |
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class HttpClient(object):
"""Represent a http client for sending request to a http[s] server.
If cookies need to be sent, they should be in a file p... |
# This simple calculator calculates the sum, the difference, the quotient and the product of two integers.
def calculator(input1,input2):
summe = input1+input2
difference=input1-input2
quotient=input1/input2
product=input1*input2
results = [summe,difference,quotient,product]
return ... |
"""
Faça um programa que leia um número indeterminado de idades de indivíduos (pare quando for informado a idade 0), e
calcule a idade média desse grupo.
"""
soma = 0
soma2 = 0
while True:
n1 = int(input('Digite a idade da pessoa: '))
if n1 > 0:
soma += n1
soma2 += 1
elif n1 == 0:
m... |
# CPU: 0.14 s
leg_a, leg_b, leg_c, total = map(int, input().split())
possible = False
for a in range(total // leg_a + 1):
for b in range(total // leg_b + 1):
for c in range(total // leg_c + 1):
if leg_a * a + leg_b * b + leg_c * c == total:
print(a, b, c)
possible = True
if not possible:
print("impossibl... |
i = 29 # ratio
z1 = 29 # disc teeth number
m = 3.5 # module
x = 0.2857 # correction coefficient
rc_star = 1 # fixed teeth radius coefficient
n = 600 # motor rotation speed [rpm]
T1 = 4000 # motor torque [Nmm]
T2 = 116000 # output... |
class Solution:
def recoverTree(self, root: TreeNode) -> None:
"""
Do not return anything, modify root in-place instead.
"""
container = []
def traverse(node):
if not node:
return
traverse(node.left)
container.a... |
CURR_USD, CURR_EUR = range(1, 3)
CURRENCY_CHOICES = (
(CURR_USD, 'USD'),
(CURR_EUR, 'EUR'),
)
SR_PRIVAT, SR_MONO, SR_VKURSE, SR_OTP, SR_TAS, = range(1, 6)
SOURCE_CHOICES = (
(SR_PRIVAT, 'PrivetBank'),
(SR_MONO, 'MonoBank'),
(SR_VKURSE, 'Vkurse'),
(SR_OTP, 'OTP-bank'),
(SR_TAS, 'TasCom-ban... |
n=int(input())
s=[]
s2=[]
for i in range(n):
s.append(input())
for i in range(n-1):
s2.append(input())
s.sort()
s2.sort()
for i in range(n-1):
if s[i]!=s2[i]:
print(s[i])
break
else:
print(s[-1]) |
''' setting global variables/constants '''
GAP_SCORE = -0.9
MISMATCH_SCORE = -1.0
MATCH_SCORE = 0
|
class Constants(object):
HISTORY_FILE = "~/.spanner-cli-history"
MAX_RESULT = 1000
PYGMENT_STYLE = "monokai"
LOGFILE = "~/.spanner-cli.log"
LESS_FLAG = "-RXF"
|
# Main Bot Strings
#
# Invalid IVLE API token
authenticate='Please authenticate by logging in to IVLE and sending me your token. [/help]'
# /help
help='To get started, please get a token by logging in to IVLE: /login and send it to me: /setup <token>.'
# Describes available commands
helpcmd='Available commands:\n/login... |
class BinTreeNode():
def __init__(self, element=None, left=None, right=None):
self.element = element
self.left = left
self.right = right
class BinaryTree(object): # Linked structure binary tree
def __init__(self):
self.root = None
# self.size = 0
def populate_tree... |
class NotReceived(Exception):
"""
Message has not been recieved by anyone
"""
class WrappedException(Exception):
"""
Exception raised when an exception raised
by RPC call could not be resolved, the innermessage
shows the exception raised on the RPC server.
"""
class RPCTimeoutError(E... |
# Python3
# 有限制修改區域
def mergingVines(vines, n):
def nTimes(n):
def decorator(func):
def wrapper(vines):
for i in range(n):
vines = func(vines)
return vines
return wrapper
return decorator
@nTimes(n)
def sumOnce(vin... |
# Solutions for Deblurring tutorial - PyData Global 2020 Tutorial
def Unsharp_Mask():
"""Unsharp Mask operator
"""
# load image from scikit-image
image = data.microaneurysms()
ny, nx = image.shape
# %load -s Diagonal_timing solutions/intro_sol.py
# Define matrix kernel
kernel_unsharp ... |
"""
PASSENGERS
"""
numPassengers = 30593
passenger_arriving = (
(5, 7, 6, 7, 7, 0, 5, 3, 5, 0, 1, 0, 0, 7, 8, 4, 6, 4, 6, 4, 2, 2, 3, 2, 2, 0), # 0
(5, 16, 13, 11, 2, 2, 1, 5, 6, 3, 2, 0, 0, 10, 9, 10, 2, 4, 5, 4, 1, 3, 3, 1, 1, 0), # 1
(8, 14, 7, 7, 2, 3, 2, 2, 6, 4, 0, 2, 0, 14, 10, 4, 4, 6, 2, 4, 4, 0, 0, 0,... |
class FrameHeader:
fin: int
rsv1: int
rsv2: int
rsv3: int
opcode: int
masked: int
length: int
# Opcode
# https://tools.ietf.org/html/rfc6455#section-5.2
# Non-control frames
# %x0 denotes a continuation frame
OPCODE_CONTINUATION = 0x0
# %x1 denotes a text frame
O... |
def is_one_to_one(df, col1, col2):
first = df.drop_duplicates([col1, col2]).groupby(col1)[col2].count().max()
second = df.drop_duplicates([col1, col2]).groupby(col2)[col1].count().max()
return first + second == 2
|
class Color(object): # subclass color of nodes
def __init__(self):
self._RED = True
self._BLACK = False
@property
def RED(self):
return self._RED
@property
def BLACK(self):
return self._BLACK
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 30 20:22:50 2020
@author: mm
"""
preco =0.00
pizza = "muçarela"
ingrediente_extra =True
num_ingredientes_extra = 3
borda_recheada = True
if pizza == "muçarela" :
preco = 25.50
if num_ingredientes_extra > 0:
preco = preco +... |
#
# PySNMP MIB module CISCO-CIPCMPC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CIPCMPC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:53:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# @Author: Merack
# @Email: merack@qq.com
baseLoginURL = 'http://10.10.9.4'
loginToURL = 'http://10.10.9.4/eportal/InterFace.do?method=login'
serviceLoginURL = 'http://10.10.9.2:8080/selfservice/module/scgroup/web/login_judge.jsf'
serviceIndexURl = 'http://10.10.9.2:8080/... |
pwNextLetters = "abcdefghjkmnpqrstuvwxyz" # The next letter after a valid letter
pwInvalidNextLetters = "ijlmop" # The next letter after an invalid letter
pwInvalidLetters = "ilo"
def nextLetter(letter):
sequenceForNext = pwNextLetters if letter not in pwInvalidLetters else pwInvalidNextLetters
letterPos = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__all__ = ["cli", "influx", "udp", "routines", "helper", "sample_dump", "colormap"]
|
class Version():
def __init__(self, major, minor, patch, revision, beta, protocol):
self.major = major
self.minor = minor
self.patch = patch
self.revision = revision
self.beta = beta
self.protocol = protocol
def __str__(self):
return 'Version: %d.%d.%... |
for _ in range(int(input())):
N = input()
result = 0
while True:
if N == "6174":
print(result)
break
b = ''.join(sorted(N))
a = ''.join(sorted(N, reverse=True))
sub = str(int(a) - int(b))
sub += "0" * (4 - len(sub))
N = sub
resu... |
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
for i in range(3):
d=""
for j in range(3):
d+=board[i*3][j*3]+board[i*3+1][j*3+1]+board[i*3+2][j*3+2]
for k in range(1,10):
if d.count(str(k))>1:
... |
number = int(input()) # number of letters
a = 0
for i in range(0, number):
for k in range(0, number):
for h in range(0, number):
print(f"{chr(97 + i)}{chr(97 + k)}{chr(97 + h)}")
for f in range(0, 900000):
a += 1 |
def runner(
input_iterable=None,
transform_function=lambda x: x,
post_method=None
):
for item in input_iterable:
post_method(transform_function(item)) |
class Low_Memory_Aligner:
"""An aligner which can align two letter strings optimally in linear memory
A score matrix which has all possible match-ups of letters must be given.
find_midddle_edge: find the middle edge in the current alignment graph
"""
def __init__(self, one, two, score... |
n = {'total':[],'soma':0,'mult':1}
for x in range(1,6):
n['total'].append(int(input('digite o {}° numero: '.format(x))))
n['soma']+=n['total'][-1]
n['mult']*=n['total'][-1]
else:
print('''
numeros: {}
soma: {}
mult: {}'''.format(n['total'],n['soma'],n['mult'])) |
'''
chitragoopt: Test module.
Meant for use with py.test.
Write each test as a function named test_<something>.
Read more here: http://pytest.org/
Copyright 2015, Venkatesh Rao
Licensed under MIT
'''
def test_example():
assert True
|
__about__ = """
FIRST CONDITION : The Array should be sorted.
REAL TIME: The Data is Jumbled up so this is time consuming.
""" |
# Задание 9.1
def generate_access_config(access):
'''
access - словарь access-портов,
для которых необходимо сгенерировать конфигурацию, вида:
{ 'FastEthernet0/12':10,
'FastEthernet0/14':11,
'FastEthernet0/16':17}
Возвращает список всех портов в режиме access
с конфигур... |
#
# PySNMP MIB module IEEE8021-BRIDGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IEEE8021-BRIDGE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:52:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... |
"""
File: boggle.py
Name: Kevin Chen
----------------------------------------
Thank a lot for Sean's hint :D
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE = 'dictionary.txt'
dictionary = []
total = []
def main():
# creating boggle grid
g... |
def print_upper_words(words, must_start_with):
"""For a list of words, print out each word on a separate line, but in all uppercase. How can you change a word to uppercase? Ask Python for help on what you can do with strings!
Turn that into a function, print_upper_words. Test it out. (Don’t forget to add a doc... |
paths = [
'LDRLDLRDUURULDDDRLLUULUDRDLRRD', # level "1".
'UDLLDDRUDDRRRRDUURUULLUURLULDRUDLLDRRUUR', # level "2".
'UUULRUULRRURRRUDRDLUULLLLLUDRDLLDDDDDRRRRRUULDDLLLLLDU', # level "3".
# level "4"; looks like '21'.
'LDDRLDLLDULURDDRRRDULRDUURULUDLUDRLDDLLURRDURRDURUDL',
# level "5"; top (of 2) sausage is... |
example = [int(age) for age in open('./day 07/Xavier - Python/example.txt').readline().strip().split(',')]
input = [int(age) for age in open('./day 07/Xavier - Python/input.txt').readline().strip().split(',')]
def part_one(positions):
fuels = [sum([abs(i-x) for x in positions]) for i in range(min(positions), max(p... |
#!/usr/bin/env python
def inner_iter(iterations):
for i in range(0, iterations):
yield i * iterations
def outer_iter(iterations):
for i in range(0, iterations):
yield from inner_iter(i)
if __name__ == '__main__':
for i in outer_iter(10):
print(i)
|
#
# PySNMP MIB module ALCATEL-IND1-MAC-ADDRESS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ALCATEL-IND1-MAC-ADDRESS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:02:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... |
# apply a value to functions
def applyFuns(L, x):
'''
assumes L is a list of functions
x is an int
'''
for f in L:
print(f(x)) |
# coding: utf-8
class ClassPropertyDescriptor(object):
"""类属性"""
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, obj, obj_type=None):
if obj_type is None:
obj_type = type(obj)
return self.fget.__get__(obj, obj_type)()
... |
# Copyright (c) 2019 The Felicia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
load("@local_config_python//:py.bzl", "PYTHON_BIN")
load("@local_config_env//:env.bzl", "ROS_DISTRO")
load("//bazel:felicia.bzl", "if_has_ros")
def _ros_... |
class _BotCommands:
def __init__(self):
self.StartCommand = 'start'
self.ListCommand = 'list'
self.AuthorizeCommand = 'authorize'
self.UnAuthorizeCommand = 'unauthorize'
self.PingCommand = 'ping'
self.StatsCommand = 'stats'
self.HelpCommand = 'help'
se... |
# https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/
# Source: https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence/discuss/720200/Clean-Python-3-O(N)
class Solution(object):
def canMakeArithmeticProgression(self, arr):
"""
:type arr: List[int]
... |
class Calculator(object):
num1 = None
num2 = None
def sum(self):
return self.num1 + self.num2 |
# The problem has asked for longest contiguous subarray that contains only 1s. What makes this problem a little trickier
# is the K flips allowed from 0 --> 1. This means a contiguous subarray of 1's might not just contain 1's but also
# may contain some 0's. The number of 0's allowed in a given subarray is given by ... |
a = list(input().split())
for i in a:
if int(i) == 0:
a.remove(i)
a.append(i)
print(*a) |
# Commands/methods
TURNON = 1
TURNOFF = 2
BELL = 4
TOGGLE = 8
DIM = 16
LEARN = 32
UP = 128
DOWN = 256
STOP = 512
RGBW = 1024
THERMOSTAT = 2048
# Sensor types
TEMPERATURE = "temp"
HUMIDITY = "humidity"
RAINRATE = "rrate"
RAINTOTAL = "rtot"
WINDDIRECTION = "wdir"
WINDAVERAGE = "wavg"
WINDGUST = "wgust"
UV = "uv"
POWER =... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 6 22:10:06 2020
@author: stemonitis
"""
"""
Look-uptables LUTs
#getextraterrestial sun
The MODTRAN extraterrestrial spectra are high-resolution, with approximately 50,000 data points at 1 wavenumber (1 cm-1) resolution.
The MODTRAN ETR sp... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CreatedApiKey(object):
"""Implementation of the 'CreatedApiKey' model.
Specifies a created API key.
Attributes:
created_time_msecs (int|long): Specifies the API key created time in
milli seconds.
created_user_sid (... |
class ContentResult(object):
def __init__(self, content_type, content_item):
"""
:param content_type: a string indicating the type
:param content_item: a rule, transformer, or hook
"""
self.content_type = content_type
self.content_item = content_item
|
l = ['a', 'b', 'c']
try:
print("1. Inside try")
print("2. About to do something bad")
l[3]
print("3. After doing something bad")
except:
print("4. Caught the exception")
print("5. And exiting") |
# Set Data Type Demo
class SetDataTypeDemo:
Instances = 0
def __init__(self):
SetDataTypeDemo.Instances += 1
def displaySetValues(self, title, value):
print(f"----- {title} -----")
print(f'SetDataTypeDemo.Instances: {self.Instances}')
print(f'{value}')
def main():
tit... |
"""
Results for SARIMAX tests
Results from Stata using script `test_sarimax_stata.do`.
See also Stata time series documentation.
Data from:
https://www.stata-press.com/data/r12/wpi1
https://www.stata-press.com/data/r12/air2
https://www.stata-press.com/data/r12/friedman2
Author: Chad Fulton
License: Simplified-BSD
"... |
# -*- coding: utf-8 -*-
def test_workflows_step_completed(slack_time):
assert slack_time.workflows.step_completed
def test_workflows_step_failed(slack_time):
assert slack_time.workflows.step_failed
def test_workflows_update_step(slack_time):
assert slack_time.workflows.update_step
|
_base_ = [
'../_base_/models/fast_scnn.py', '../_base_/datasets/publaynet.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_320k.py'
]
# Re-config the data sampler.
data = dict(samples_per_gpu=16, workers_per_gpu=4)
# Re-config the optimizer.
optimizer = dict(type='SGD', lr=0.12, momentum=0.9... |
class DNSQuery:
def __init__(self, data):
self.data=data
self.dominio=''
#print("Reading datagram data...")
m = data[2] # ord(data[2])
tipo = (m >> 3) & 15 # Opcode bits
if tipo == 0: # Standard query
ini=12
lon=data[ini] # ord(data[ini])
while lon !=... |
#import stuff here
__version__ = '0.2'
|
class Solution:
def longestConsecutive(self, nums: 'List[int]') -> 'int':
if len(nums) < 1: return 0
nums.sort()
longest, tmp = 1, 1
for i in range(1, len(nums)):
if nums[i] != nums[i - 1]:
if nums[i] == nums[i - 1] + 1:
tmp += 1
... |
#!/bin/python3
def check_trap(prev_row, i, row_len):
if i - 1 < 0:
left = "."
else:
left = prev_row[i - 1]
if i + 1 > row_len - 1:
right = "."
else:
right = prev_row[i + 1]
if (left == "." and right == "^") or (left == "^" and right == "."):
return "^"
e... |
# task type can be either 'classification' or 'regression', based on the target feature in the dataset
TASK_TYPE = ''
# the header (all column names) of the input data file(s)
HEADERS = []
# the default values of all the columns of the input data, to help TF detect the data types of the columns
HEADER_DEFAULTS = []
... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def sumOfLeftLeaves(self, root):
def sumOfLeftLeavesHelper(root, is_left):
if not root:
return 0
if not root.left and n... |
"""
poglavje 5 - Seznami (angl. Lists)
"""
# INDEXI SEZNAMA
# poz 0 1 2 3
# neg -4 -3 -2 -1
dolzine = [121.4, 143.1, 105.2, 99.3]
print(dolzine)
dolzine.sort(reverse = True)
print(dolzine)
# novi_skoki = [120,130,150]
# # dodamo nov skok
# # dolzine.append(novi_skoki)
# dolzine.extend(novi_skoki)
# print(dolzi... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2012 Dag Wieers <dag@wieers.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the Lice... |
replace_rules = {'"s':'ß','"a':'ä','"u':'ü', '"o':'ö', '"A':'Ä','"U':'Ü', '"O':'Ö', '<':'', '>':'', '-$':'', '$-':'', '$':'', '-':'' , '\'' : '' }
wordlist = []
with open('data/vm_lexicon_ids.txt', 'r') as lexicon_ids:
for line in lexicon_ids:
if line[-1] == '\n':
line = line[:-1]
prin... |
#In Python, a dictionary can only hold a single value for a given key.
#To workaround this, our single value can be a list containing multiple values.
#Here we have a dictionary called "wardrobe" with items of clothing and their colors.
#Fill in the blanks to print a line for each item of clothing with each color,
... |
#1. Reverse the order of the items in an array.
#Example:
#a = [1, 2, 3, 4, 5]
#Result:
#a = [5, 4, 3, 2, 1]
a = [1,2,3,4,5]
list.reverse(a)
print ('Ex1: Inverted list is:', a)
#2. Get the number of occurrences of var b in array a.
#Example:
#a = [1, 1, 2, 2, 2, 2, 3, 3, 3]
#b = 2
#Result:
#4
a = [1, 1, 2, 2, 2, 2, ... |
def spin(step):
mem = [0]
pos = 0
for i in range(1, 2018):
pos = (pos + step) % i + 1
mem.insert(pos, i)
return mem
my_spin = spin(349)
print("Part 1: {}".format(my_spin[my_spin.index(2017) + 1]))
def spin_2(step):
pos = 0
res = 0
for i in range(1, 50000000):
pos = ... |
#https://leetcode.com/problems/linked-list-cycle-ii/
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
#basially you want to see if a pointer is pointing to someth... |
# -*- coding: utf-8 -*-
def main():
a, b, x = map(int, input().split())
# KeyInsight
# 二分探索
# 単調増加であるときに,特定の値を高速に調べることができる
# See:
# https://atcoder.jp/contests/abc146/submissions/8608718
# 両端の値は必ず条件を満たす・満たさないものを初期値として与える
left, right = 0, 10 ** 9 + 1
def can_buy(va... |
"""
Mybuild.
TODO docs. -- Eldar
"""
__author__ = "Eldar Abusalimov"
__copyright__ = "Copyright 2012-2013, The Embox Project"
__license__ = "New BSD"
__version__ = "0.5"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.