content stringlengths 7 1.05M |
|---|
'''
Given an integer, return its base 7 string representation.
Example 1:
Input: 100
Output: "202"
Example 2:
Input: -7
Output: "-10"
Note: The input will be in range of [-1e7, 1e7].
'''
class Solution(object):
def convertToBase7(self, num):
"""
:type num: int
:rtype: str
"""
... |
"""Code related to tokens, as defined in the EAG document.
See section 6, page 42, of the NIST document.
"""
|
"""
477 Leetcode. Total Hamming Distance
https://leetcode.com/problems/total-hamming-distance/
"""
"""
This program converts all the integers in the array to their 32bit binary representation then count the number of zeros in each tuple.
For each tuple we multiply the number of zeros with the difference of the l... |
class Queue:
"""Queue data structure.
Args:
elements(list): list of elements (optional)
Examples:
>>> q1 = Queue()
>>> q2 = Queue([1, 2, 3, 4, 5])
>>> print(q1)
[]
>>> print(q2)
[1, 2, 3, 4, 5]
"""
def __init__(self, elements=None):
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 27 23:16:02 2021
@author: Joshua Fung
"""
def tsai_wu(s, sigma_lp, sigma_ln, sigma_tp, sigma_tn, tau_lt):
s = s.A1
f11 = 1/(sigma_lp*sigma_ln)
f22 = 1/(sigma_tp*sigma_tn)
f1 = 1/sigma_lp - 1/sigma_ln
f2 = 1/sigma_tp - 1/sigma_tn
f66 = 1/tau_lt**2
... |
person_1 = {
'first_name': 'Tony',
'last_name': 'Macaroni',
'age': 26,
'state': 'PA',
}
person_2 = {
'first_name': 'Betsy',
'last_name': 'Bolognese',
'age': 34,
'state': 'KS',
}
person_3 = {
'first_name': 'Peter',
'last_name': 'Pepperoni',
'age': 24,
'state': 'NY',
}
f... |
# @author:leacoder
# @des: 双指针 移动零
'''
i:用于遍历 整个数组
j: 指向非0数位置
遍历数组,将非0数填入j所在位置j后移,将 j位置到最后补0
'''
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
length = len(nums)
j = 0
for i in range(0,length): # 遍历数组
if 0!=nums[i]:
nums[j],j = nums[i],j + 1 ... |
input_ = [int(element) for element in input().split(" ")]
# print(input_)
n = input_[0]
acceptable_lengths = input_[1:]
#print(n)
#print(acceptable_lengths)
acceptable_lengths.sort()
max_possible_pieces = n // acceptable_lengths[0]
print(max_possible_pieces) |
class ApplicationError(Exception):
"""Base class for all application errors."""
class NotFoundError(ApplicationError):
"""Raised when an entity does not exists."""
|
## The modelling for generations
# define bus types
AC = 1 # Critical AC generators
UAC = 2 # Non-critical AC generators
DC = 3 # Critical DC generators
UDC = 4 # Critical DC generators
# define the indices
GEN_BUS = 0 # bus number
GEN_TYPE = 1 # type of generators
PG = 2 # Pg, real power output (W)
QG = 3 # ... |
def addition (a,b):
return a + b
def substraction (a,b):
return a - b
def multiplication (a,b):
return a * b
def division (a,b):
return a / b
first_number=int(input("Enter the first number: "))
second_number=int(input("Enter the second number: "))
print("The sum of your two numbers is: " + str(... |
#!/usr/bin/env python
# coding: utf-8
"""
Exception classes used in smtplibaio package.
The exhaustive hierarchy of exceptions that might be raised in the smtplibaio
package is as follows:
BaseException
|
+ Exception
|
+ SMTPException
| |
| + SMTPCommandNot... |
# coding:utf-8
class LgbWrapper(object):
def __init__(self, *, clf, dataset_params, train_params, seed=7):
self.__dataset_params = dataset_params
self.__categorical_feature = self.__dataset_params.pop("categorical_feature")
self.__train_params = train_params
self.__train_params["f... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
else:
... |
def wordcloud(df_sentence, stopwords={}):
# 形態素解析の準備
t = Tokenizer()
noun_list = []
for sentence in list(df_sentence):
for token in t.tokenize(sentence):
split_token = token.part_of_speech.split(',')
# 名詞・形容詞を抽出(好きな品詞に変更できる)
if split_token[0] == '名詞' or split... |
CHAR_VECTOR ="天仙子张先时为嘉禾小倅以病眠不赴府会水调数声持酒听,午醉醒来愁未。送春去几回?临晚镜伤流景往事后期空记省沙上并禽池暝云破月花弄影重帘幕密遮灯风定人初静明落红应满径喜迁莺刘一生晓行光催角宿鸟惊邻鸡觉迤逦烟村马嘶起残尚穿林薄泪痕带霜微凝力冲寒犹弱叹倦客悄禁染尘京洛追念别心万难觅孤鸿托翠幌娇深曲屏香暖争岁华飘泊怨恨烦恼是曾经著者情味、望成消减新还恶江陈与义高咏楚词酬日涯节序匆榴似舞裙无知此意歌罢身老矣戎葵笑墙东杯浅年同试浇桥下今夕到湘中采桑欧阳修群芳过西湖好狼籍飞絮蒙垂柳阑干尽笙散游始栊双燕归细雨贺郎李玉篆缕金鼎沉庭阴转画堂草王孙何处惟有杨糁渐枕腾外已透镇聊殢厌鬓乱忺整南旧休遍寻问息断倩楼凭久依又只恐瓶井骑银... |
# Function to do insertion sort
def insertionSort(arr):
# Traverse through 1 to len(arr)
for main_index in range(1, len(arr)):
reference_value = arr[main_index]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position... |
def broken_function_with_message(error):
a_message = ""
try:
raise error("A message ?")
except error as err:
a_message += str(err)
finally:
a_message += "All good"
a_message += "I continue running !"
return a_message
def broken_function_without_message(error):
a_me... |
"""
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
====
Assume we are dealing with an environment which could only hold integers within the 32-bit signed
integer ra... |
#TEMA:IF
###########################################################################
def evalucion(nota):
valoracion = "Aprobado"
if nota<5:
valoracion="Suspenso"
return valoracion
###########################################################################
#Llamada de la funcion
print("Ejemplo #1")
print(4)
p... |
# Excepciones => try ... except ... finally
try:
numero = int(input("Ingrese un numero"))
# numero/0
except ValueError :
print('Tiene que ser un numero')
# except ZeroDivisionError:
# print('No se puede hacer la division entre cero')
except:
print('Hubo un error')
# else => solamente va a funcionar ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 19 16:14:38 2016
@author: zhengzhang
"""
def run(self):
for i in range(self.num_steps):
direction = self.dice.roll()
if direction == 0:
self.x_pos += 1
elif direction == 1:
self.x_pos -= 1
elif direction ==... |
valores = [0, 1, 5, 7, 8, 15, 19, 1, 23, 12]
for c, v in enumerate(valores):
print(f'Encontrei na posição {c+1} o valor {v}.')
print('FIM DA LISTA.')
|
MONGO_HOST = 'localhost'
MONGO_PORT = 27017
DB_NAME = 'ugc_db'
BENCHMARK_ITERATIONS = 10
|
data = input().split("\\")
name, extension = data[-1].split(".")
print(f"File name: {name}")
print(f"File extension: {extension}")
|
"""Shared configuration flags."""
HIDDEN_TRACEBACK = True
HOOKS_ENABLED = True
MINIMAL_DIFFS = True
WRITE_DELAY = 0.0 # seconds
|
WIN_SIZE = 25
def valid_number(window, number):
for n in window:
dif = abs(number-n)
if n != dif and dif in window:
return True
return False
def find_wrong(input):
window = input[:WIN_SIZE]
i = 1
for number in input[WIN_SIZE:]:
if not valid_number(window, numb... |
class CustomTextSummarizer(BaseTextSummarizer):
def __init__ (self, model_key, language):
self._tokenizer = AutoTokenizer.from_pretrained(model_key)
self._language = language
self._model = AutoModelForSeq2SeqLM.from_pretrained(model_key)
self._device = 'cuda' if bool(strtobool(os.... |
class Solution:
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
m, n = len(matrix), len(matrix[0])
queue = collections.deque()
for i, row in enumerate(matrix):
for j, val in enumerate(row):
if val:
matrix[i][j] = math.inf
... |
# Copyright 2015 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.
DEPS = [
'depot_tools/bot_update',
'depot_tools/gclient',
'depot_tools/git',
'recipe_engine/context',
'recipe_engine/path',
'recipe_engine/prope... |
"""Mobjects used to display Text using Pango or LaTeX.
Modules
=======
.. autosummary::
:toctree: ../reference
~code_mobject
~numbers
~tex_mobject
~text_mobject
"""
|
MODEL_BUCKET = 'clothing-08-04-2019'
MODEL_PATH = 'classifier/net.p'
PATH_DATA = 'data'
PORT = 8080
LABELS = ('back', 'front', 'other', 'packshot', 'side') |
class Entity(dict):
identity: int = 0
def __repr__(self):
return f"<Entity-{self.identity}:{super().__repr__()}>"
|
# odc module, used to simulate the C++ functions exported by PyPort
# "LIs:log"
def log(guid, level, message):
print("Log - Guid - {} - Level {} - Message - {}".format(guid, level, message))
return
# "LsIss:PublishEvent"
# Same format as Event
def PublishEvent(guid, EventType, ODCIndex, Quality, PayLoad ):
... |
"""Module containing the `AnalysisError` exception class."""
class AnalysisError(Exception):
"""
Exception representing an error during a repository analysis.
Attributes:
message {string} -- Message explaining what went wrong.
"""
def __init__(self, message):
"""
Initial... |
class Solution:
def transformArray(self, arr: List[int]) -> List[int]:
diff = True
while diff:
curr = arr[:]
diff = False
for i in range(1, len(arr) - 1):
if arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
curr[i] += 1
... |
class Solution:
def threeSum(self, nums) :
ans=[]
nums.sort()
if nums==[]:
return []
for i in range(len(nums)-1):
j=i+1
k=len(nums)-1
while j<k:
x = nums[i]+nums[j]+nums[k]
if x==0:
y=... |
class DomainException(Exception):
pass
class DomainIdError(DomainException):
pass
class DomainNotFoundError(DomainException):
pass
def domain_id_error(domainname, id):
if (id == None):
return get_id_error(domainname, "None", "ID is missing!")
else:
return get_id_error(domainname, ... |
""" 该代码仅为演示函数签名和所用方法,并不能实际运行
"""
torch.nn.utils.rnn.pack_padded_sequence(input, lengths,
batch_first=False, enforce_sorted=True)
torch.nn.utils.rnn.pad_packed_sequence(sequence, batch_first=False,
padding_value=0.0, total_length=None) |
# Python Resources
# The purpose of this document is to direct you to resources that you may find useful if you decide to do a deeper dive into Python.
# This course is not meant to be an introduction to programming, nor an introduction to Python, but if you find yourself interested
# in exploring Python further, or fe... |
#while loop
# while [condition]:
# [statements]
#else:
count =1
sum = 0
while count <=20:
sum=sum + count
count=count+1
print(sum)
sum1=0
for value in range(1,21):
pass
|
"""
This is the docstring for an empty init file, to support testing packages besides PyTest such as Nose that may look for
such a file
"""
|
def allow_tags(func):
"""Allows HTML tags to be returned from resource without escaping"""
if isinstance(func, property):
func = func.fget
func.allow_tags = True
return func
def humanized(humanized_func, **humanized_func_kwargs):
"""Sets 'humanized' function to method or property."""
d... |
# -*- coding: utf-8 -*-
# Author:William Zhang
# Email:quanpower@gmail.com
# Wechat:252527676
# Created:18-4-21 下午9:13
command = '/root/ENV/smartlink2/bin/gunicorn'
pythonpath = '/root/ENV/smartlink2/bin/'
bind = 'unix:/tmp/smartlink2.sock'
# bind = '0.0.0.0:8000'
workers = 5
user = 'root' |
class NewsStyleUriParser(UriParser):
"""
A customizable parser based on the news scheme using the Network News Transfer Protocol (NNTP).
NewsStyleUriParser()
"""
|
class Blueberry (object):
app_volume = 1.0
break_loop = False
@staticmethod
def sel_local_vol(new_vol):
Blueberry.app_volume = new_vol
@staticmethod
def gel_local_vol():
return Blueberry.app_volume
@staticmethod
def set_break_status(new_status):
Blueberry.br... |
# Contains many tic tac toe positions to test the solver
x_move_1 = [['X', '_', '_'],
['_', '_', '_'],
['_', '_', '_']]
x_move_2 = [['_', 'X', '_'],
['_', '_', '_'],
['_', '_', '_']]
x_move_3 = [['_', '_', '_'],
['_', 'X', '_'],
... |
class Solution:
circle_id = 0
def next_circle_id(self):
self.circle_id += 1
return self.circle_id
def findCircleNum(self, M):
"""
:type M:list[list[int]]
:rtype: int0
"""
m_length = len(M)
circle_map = [-1 for i in range(m_length)] # type: ... |
''' IMPLEMENTATION METHOD 2 (less common but easier)
HEAD TAIL
________ ________ ________ ________
| | | | | | | | | | | |
| None | |--->| a | |--->| b | |--->| c | |--->None
|______|_| |______|_| |______|_| |___... |
"Talk."
# https://www.jetbrains.com/help/pycharm/part-1-debugging-python-code.html#7bf477d0 - IDE
# https://wiki.python.org/moin/PythonDebuggingTools - debug
print('sds') |
def obtener_ganadores(lista_ganadores):
lista_unica=[]
for i in lista_ganadores:
if i not in lista_unica:
lista_unica.append(i)
return lista_unica
def obtener_posiciones_premio_doble(lista_carreras_con_premio,lista_ganadores,caballo ):
lista_final_premio=[]
c=0
for i in lista_carreras_con_premio:... |
#
# PySNMP MIB module CHIPDOT1D-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHIPDOT1D-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:48:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... |
"""
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should
be O(log (m+n)).
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]
nums2 = [3, 4]
The median is (2 +... |
class Memory():
def __init__(self):
#Depricate
self.stack = {}
self.heap = {}
#Depricate
self.variableNames = []
self.Env = [{}]
def malloc(self,x,v):
l = len(self.Env)
(self.Env[l-1])[x] = v
def requestVar(self,x):
l = len(se... |
#Buris Mateo - Nuñez Matias
#import random
def QuicksortRe(lista,inf,sup):
if (inf<sup):
I=inf
J=sup
pivot=lista[inf]
while (I<J):
while (lista[I]<=pivot) and (I<J):
I+=1
while (lista[J]>pivot):
J-=1
if (I<J):
... |
name = "David"
if name == "David":
print(name)
elif name == "Artur":
print(name)
else:
print("Nothing found") |
a = 15
# print(1 & 15)
# print(2 & 15)
# print(4 & 15)
|
def extractKoreanNovelTrans(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag):
return False
if 'Novel: Kill the Lights' in item['tags']:
return buildReleaseMessageWithType(item, 'Kill the Lights', vol, chp, frag=frag, postfix=postfix)
if 'Nov... |
class float_range(object):
def __init__(self, start, stop=None, step=1):
if stop is None:
start, stop = 0, start
if not step:
raise ValueError
(self.start, self.stop, self.step) = (start, stop, step)
def __iter__(self):
i = self.start
if self.step... |
entrada1 = int(input('Número de frases a serem registradas: '))
for k in range(0, entrada1):
normal = 0
reverso = -1
entrada = str(input(f'{k+1}°- Frase: '))
entrada = entrada.replace('"', '')
entrada = entrada.replace("'", '')
entrada = entrada.upper()
print('```')
for i in range(0, le... |
class ThreeIncreasing:
def minEaten(self, a, b, c):
candies_eaten = 0
while(c <= b):
b -= 1
candies_eaten += 1
while(b <= a):
a -= 1
candies_eaten += 1
if(a <= 0 or b <= 0 or c <= 0):
return -1
el... |
#!/usr/bin/env python3
# Copyright (C) Alibaba Group Holding Limited.
""" Registry class. """
class Registry(object):
"""
The Registry class provides a registry for all things
To initialize:
REGISTRY = Registry()
To register a tracker:
@REGISTRY.register()
class Model():
... |
# ------------------------------
# 777. Swap Adjacent in LR String
#
# Description:
# In a string composed of 'L', 'R', and 'X' characters, like "RXXLRXRXL", a move consists of either replacing one occurrence of "XL" with "LX", or replacing one occurrence of "RX" with "XR". Given the starting string start and the endi... |
type = 'SMPLify'
verbose = True
body_model = dict(
type='SMPL',
gender='neutral',
num_betas=10,
keypoint_src='smpl_45',
# keypoint_dst='smpl_45',
keypoint_dst='smpl',
model_path='data/body_models/smpl',
batch_size=1)
stages = [
# stage 0: optimize `betas`
dict(
num_iter... |
def sum_integer(a, b):
sum_no = a + b
if (sum_no >= 15) and (sum_no <= 20):
sum_no = 20
return sum_no
print (sum_integer(23, 5)) |
soma = cont = media = maior = menor = 0
resposta = ''
while resposta != 'N':
n = int(input('Digite um número : '))
resposta = input('Quer continuar ? [S/N] ').strip().upper()
cont += 1
soma = soma + n
if cont == 1:
maior = menor = n
else:
if n > maior:
maior = n
... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/aref/test/q3at/install/include;/usr/include".split(';') if "/home/aref/test/q3at/install/include;/usr/include" != "" else []
PROJECT_CATKIN_DEPENDS = "geometry_msgs;hector_uav_msgs;roscpp".replac... |
# convert a supplied string to a usable integer
def string_to_num(str : str):
return sum([ord(str[index]) for index in range(len(str))])
def xor(n1, n2):
# remove the 0b string from the beggining of the binary string
n1_binary, n2_binary = bin(n1)[2:], bin(n2)[2:]
# make sure both strings are the same... |
default_configs = [{'type': 'integer', 'name': 'num_clones', 'value': 1, 'description': 'Number of clones to deploy.'},
{'type': 'boolean', 'name': 'clone_on_cpu', 'value': False,
'description': 'Use CPUs to deploy clones.'},
{'type': 'integer', 'name': 'num_rep... |
alien_0 = {
'color':'green',
'points':'5'
}
print(alien_0)
print(alien_0['color'])
new_points = alien_0['points']
print(f"You just earned {new_points} points")
alien_0['x_position'] = 0
alien_0['y_position'] = 35
alien_0['my_name'] = 'Mareedu' # adding
alien_0['color'] = 'blue' # modify
del alien_0['my_name']... |
class graph:
def __init__(self):
self.graph={}
self.visited=set()
def dfs(self,node):
if node not in self.visited:
print(node)
self.visited.add(n... |
secret_word = "fart"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
while guess != secret_word and not(out_of_guesses):
if guess_count < guess_limit:
guess = input("Guess a word: ")
guess_count += 1
else:
out_of_guesses = True
if out_of_guesses:
print("Out of gu... |
def transfer_money(from_addr, to_addr, value):
"""
A simple stub to show that money is being transferred
"""
print("Transferring {} UNITS From {} TO {}".format(value, from_addr, to_addr))
|
class payload:
__payload = ''
def __init__(self, version, sender_name, session_id, country_code,
ip_type, domain, ip_address, media_type, protocol_id,
media_transfer_type, protocol, port, modulation_type,
modulation_port, session_name='SESSION SDP'):
s... |
# Indexing dan subset string di python
a = "Hello, World!"
H = a[0] #dalam python indexing dimulai dari 0
o = a[4]
Hello = a[0:5]
print(Hello)
Hello_ = a[:5]
print(Hello_)
World = a[7:12]
print(World)
World_ = a[-6:-1]
print(World_)
# Merge string
b = "I'm ready for python!"
c = a+b
print(c)
c = a+ " " +b
prin... |
"""
@no 46
@name Permutations
"""
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 0:
return []
if len(nums) == 1:
return [[nums[0]]]
ans = []
for i in range(len(nums... |
# 第 37 题:序列化二叉树
# 传送门:序列化二叉树,牛客网 online judge 地址。
# 请实现两个函数,分别用来序列化和反序列化二叉树。
# 您需要确保二叉树可以序列化为字符串,并且可以将此字符串反序列化为原始树结构。
# 样例:
# 你可以序列化如下的二叉树 8 / \ 12 2 / \ 6 4 为:"[8, 12, 2, null, null, 6, 4, null, null, null, null]"
# 注意:
class TreeNode:
def __init__(self,val):
self.val = val
self.left = None... |
__author__ = 'Owais Lone'
__version__ = '0.6.0'
default_app_config = 'webpack_loader.apps.WebpackLoaderConfig'
|
a = int(input('a = ', )) # запрашиваем первый коэффициент
b = int(input('b = ', )) # запрашиваем второй коэффициент
c = int(input('c = ', )) # запрашиваем третий коэффициент
if a!= 0 and b % 2 == 0 and c!= 0: # решение по сокращенной формуле, т.к. b - четное
k = b / 2
d1 = k ** 2 - a * c
k1 = (-... |
'''from django.contrib.auth import get_user_model
from django.test import TestCase #an extension of Python’s TestCase
from django.urls import reverse, resolve
from django.test import Client
from .models import PremiumBlog
from .views import (
BlogListView,
BlogDetailView,
)
class CustomUserTests(TestCa... |
# https://stackoverflow.com/questions/443885/python-callbacks-delegates-what-is-common
# Listeners, callbacks, delegates
class Foo(object):
def __init__(self):
self._bar_observers = []
def add_bar_observer(self, observer):
self._bar_observers.append(observer)
def notify_bar(self, param):... |
for i in range(int(input())):
word=input()
if word==word[::-1]:
print(f"#{i+1} 1")
else :
print(f"#{i+1} 0") |
def teste (b):
a=8
b+=4
c=2
print(f'A dentro vale {a}')
print(f'B dentro vale {b}')
print(f'C dentro vale {c}')
a=5
teste(a)
print(f'A fora vale {a}')
|
def maxRec2(vetor, ini, fim):
if ini == fim:
return vetor[ini];
meio = round((ini + fim)/2);
max1 = maxRec2(vetor, ini, meio);
max2 = maxRec2(vetor, meio+1, fim);
if max1 > max2:
return max1;
else:
return max2;
print("Valor máximo em um vetor. Versão recursiva");
vetor =... |
# -*- coding: utf-8 -*-
dataStr='''
Montana Birth Data 2016;State;Rank*;U.S.**
Percent of Births to Unmarried Mothers;36.4;34th;39.8
Cesarean Delivery Rate;29.1;34th;31.9
Preterm Birth Rate;8.8;42nd (tie);9.9
Teen Birth Rate ‡;23.7;15th (tie);20.3
Low Birthweight Rate;7.9;29th (tie);8.2
"¹ Excludes data from U.S. terri... |
# This is day22 - works for part 1, minor change needed for day 2
spells = {
"missile": 53, # It instantly does 4 damage.
"drain": 73, # It instantly does 2 damage and heals you for 2 hit points.
"shield": 113, # Effect: 6 turns. While it is active, your armor is increased by 7.
"poison": 173, # Effect... |
X, Y = [int(x) for x in input().split()]
if 2 * X <= Y <= 4 * X and Y % 2 == 0:
print("Yes")
else:
print("No")
|
#Empty List to contain user input
UserChoice = []
#Goes through C Branch options
def Cdecision(RootChoice):
opsC = True #variable was global, but made it local due to "UnboundLocalError"
while opsC:
choice = input("You can choose 'c': ")
if choice == "c":
UserChoice.append(choice)
... |
test = { 'name': 'q1a',
'points': 11,
'suites': [ { 'cases': [ { 'code': '>>> '
'round(get_mape(pd.Series(np.linspace(1, '
'3, 4)), '
'pd.Series(np.linspace(1, 1... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
slow, fast = head, head
if not slow and not fast: return True
while fast and ... |
#
# PySNMP MIB module NOVELL-IPX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOVELL-IPX-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:14:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
# -*- coding: utf-8 -*-
# @Time : 2019-08-06 18:20
# @Author : Kai Zhang
# @Email : kai.zhang@lizhiweike.com
# @File : ex4-circularDeque.py
# @Software: PyCharm
class MyCircularDeque:
def __init__(self, k: int):
"""
Initialize your data structure here. Set the size of the deque to be k.
... |
async def issue_opened_event(event, gh, *args, **kwargs):
"""
Whenever an issue is opened, greet the author and say thanks.
"""
url = event.data["issue"]["comments_url"]
author = event.data["issue"]["user"]["login"]
message = f"Thanks for the report @{author}! I will look into it ASAP! (... |
# coding: utf-8
utf8_migration = u"""
SQL_UP = u\"\"\"
CREATE TABLE keyword (global_id varchar(255) null, name_txt varchar(255) null);
INSERT INTO keyword (global_id,name_txt) values ('7a77acb8-306c-4ce2-8fbc-e1567e49b149','G1');
INSERT INTO keyword (global_id,name_txt) values ('42aaa103-5832-44c4-a364-0f723187e1d6'... |
def ShoeStoreThingy(PairOfShoes, PairOfSocks, Money, time):
#shoes#
shoeBuy1 = int(input("How many Pairs of Shoe Would you like to buy, 1 pair of shoes = $800 ??? >>"))
countshoe = PairOfShoes + shoeBuy1
sureshoes = int(input("How Many shoes would you like to remove???, 0 for none >>"))
countshoe =... |
FNAME = 'submit'
def main():
output = ''
for p, problem in enumerate(load_input(), 1):
output += 'Case #%d: %s\n' % (p, solve(problem))
with open('%sOutput.txt' % FNAME, 'w', encoding='utf-8') as fp:
fp.write(output)
def load_input():
with open('%sInput.txt' % FNAME, 'r', encoding='utf-8') as fp:
problems =... |
__author__ = 'Matt'
class PathSelection:
def __init__(self):
return
def drawPath(self, canvas, x, y, size):
ARENA_WIDTH = 100
ARENA_HEIGHT = 300
TRANSPORT_WIDTH = 10
TRANSPORT_HEIGHT = 15
EXCAVATOR_WIDTH = 10
EXCAVATOR_HEIGHT = 10
return |
"""
Check if Two Rectangles Overlap
Given two rectangles, find if the given two rectangles overlap or not.
Note that a rectangle can be represented by two coordinates, top left and bottom right.
So mainly we are given following four coordinates (min X and Y and max X and Y).
- l1: Bottom Left coordinate of first r... |
version = '1.6.4'
version_cmd = 'haproxy -v'
depends = ['build-essential', 'libpcre3-dev', 'zlib1g-dev', 'libssl-dev']
download_url = 'http://www.haproxy.org/download/1.6/src/haproxy-VERSION.tar.gz'
upstart = """
start on runlevel [2345]
stop on runlevel [016]
expect fork
pre-start exec haproxy -t
pre-stop exec hapr... |
"""
.. currentmodule:: cockatoo.exception
.. autosummary::
:nosignatures:
CockatooException
CockatooImportException
RhinoNotPresentError
SystemNotPresentError
NetworkXNotPresentError
NetworkXVersionError
KnitNetworkError
KnitNetworkGeometryError
MappingNetworkError
KnitNetw... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.