content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
print("---------------------Status Kelulusan Mahasiswa----------------------")
a= (input("Nama : "))
m= int(input("Nilai Matematika : "))
Ind= int(input("Nilai Bahasa Indonesia : "))
IPA= int(input("Nilai IPA : "))
if(m < 0) or (Ind < 0) or (IPA<0) or (m > 100) or (Ind > 100) or (IPA > 100):
print("Maaf input... | print('---------------------Status Kelulusan Mahasiswa----------------------')
a = input('Nama : ')
m = int(input('Nilai Matematika : '))
ind = int(input('Nilai Bahasa Indonesia : '))
ipa = int(input('Nilai IPA : '))
if m < 0 or Ind < 0 or IPA < 0 or (m > 100) or (Ind > 100) or (IPA > 100):
print('Maaf input ada ya... |
def iou_box(box_1, box_2):
# "left bottom" means (left, bottom)
left_bottom_1 = box_1[0]
right_top_1 = box_1[1]
left_bottom_2 = box_2[0]
right_top_2 = box_2[1]
# if no "I"
if left_bottom_1[1] >= right_top_2[1] or left_bottom_1[0] >= right_top_2[0] or left_bottom_2[1] >= right_top_1[1] or rig... | def iou_box(box_1, box_2):
left_bottom_1 = box_1[0]
right_top_1 = box_1[1]
left_bottom_2 = box_2[0]
right_top_2 = box_2[1]
if left_bottom_1[1] >= right_top_2[1] or left_bottom_1[0] >= right_top_2[0] or left_bottom_2[1] >= right_top_1[1] or (right_top_1[0] <= left_bottom_2[0]):
return 0
e... |
"""
This file is a configuration file that contains default directories for saving data
"""
HDF_DIR = "./data/hdf/"
FIGURES_DIR = "./data/figures/"
PYPET_LOGGING_CONFIG = "./neurolib/utils/pypet_logging.ini"
| """
This file is a configuration file that contains default directories for saving data
"""
hdf_dir = './data/hdf/'
figures_dir = './data/figures/'
pypet_logging_config = './neurolib/utils/pypet_logging.ini' |
p12 = machine.Pin(12)
servo = machine.PWM(p12,freq=50)
def degreeToDuty(value):
value = (((value/180)*110) + 25)
return int(value)
def setServo(angle):
global servo
dutyValue = degreeToDuty(angle)
servo.duty(int(dutyValue))
| p12 = machine.Pin(12)
servo = machine.PWM(p12, freq=50)
def degree_to_duty(value):
value = value / 180 * 110 + 25
return int(value)
def set_servo(angle):
global servo
duty_value = degree_to_duty(angle)
servo.duty(int(dutyValue)) |
def gcd(a, b):
while b != 0:
t = a % b
a = b
b = t
return a
def test():
print(gcd(1, 10) == 1)
print(gcd(2, 3) == 1)
print(gcd(12, 24) == 12)
print(gcd(21, 24) == 3)
test() | def gcd(a, b):
while b != 0:
t = a % b
a = b
b = t
return a
def test():
print(gcd(1, 10) == 1)
print(gcd(2, 3) == 1)
print(gcd(12, 24) == 12)
print(gcd(21, 24) == 3)
test() |
#
# PHASE: java wrapper
#
# DOCUMENT THIS
#
load(
"@io_bazel_rules_scala//scala/private:rule_impls.bzl",
"write_java_wrapper",
)
def phase_repl_java_wrapper(ctx, p):
args = struct(
args = " ".join(ctx.attr.scalacopts),
wrapper_preamble = """
# save stty like in bin/scala
saved_stty=$(stty -... | load('@io_bazel_rules_scala//scala/private:rule_impls.bzl', 'write_java_wrapper')
def phase_repl_java_wrapper(ctx, p):
args = struct(args=' '.join(ctx.attr.scalacopts), wrapper_preamble='\n# save stty like in bin/scala\nsaved_stty=$(stty -g 2>/dev/null)\nif [[ ! $? ]]; then\n saved_stty=""\nfi\nfunction finish() ... |
#!/usr/bin/python3
#filename:using_name.py
if __name__=='__main__':
print('This program is being run by itself')
else:
print('I am being imported form another module')
| if __name__ == '__main__':
print('This program is being run by itself')
else:
print('I am being imported form another module') |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
class GcpCredentials(object):
"""Implementation of the 'GcpCredentials' model.
Specifies the credentials to authenticate with Google Cloud Platform.
Attributes:
client_email_address (string): Specifies Client email address
assoc... | class Gcpcredentials(object):
"""Implementation of the 'GcpCredentials' model.
Specifies the credentials to authenticate with Google Cloud Platform.
Attributes:
client_email_address (string): Specifies Client email address
associated with the service account.
client_private_key... |
repeats = " VIRUS " * 9000000
input("installing virus...")
input("do you want to remove the virus?")
input("oh no i cant do anything")
print("deleting system files")
input("hahaha your device is now encrypted.")
input("sending personal files to Moscow Russia...")
print(repeats) | repeats = ' VIRUS ' * 9000000
input('installing virus...')
input('do you want to remove the virus?')
input('oh no i cant do anything')
print('deleting system files')
input('hahaha your device is now encrypted.')
input('sending personal files to Moscow Russia...')
print(repeats) |
def create_element(doc, parent, tag, value=None, attributes=None):
"""
Creates an XML element
"""
ele = doc.createElement(tag)
parent.appendChild(ele)
if value:
text = doc.createTextNode(u"%s" % value)
ele.appendChild(text)
if attributes:
[ele.setAttribute(k, str(v)) ... | def create_element(doc, parent, tag, value=None, attributes=None):
"""
Creates an XML element
"""
ele = doc.createElement(tag)
parent.appendChild(ele)
if value:
text = doc.createTextNode(u'%s' % value)
ele.appendChild(text)
if attributes:
[ele.setAttribute(k, str(v)) ... |
"""
LeetCode Problem: 539. Minimum Time Difference
Link: https://leetcode.com/problems/minimum-time-difference/
Written by: Mostofa Adib Shakib
Language: Python
Time Complexity: O(nlogn)
Space Complexity: O(n)
"""
class Solution:
def findMinDifference(self, timePoints: List[str]) -> int:
minTimes = [] ... | """
LeetCode Problem: 539. Minimum Time Difference
Link: https://leetcode.com/problems/minimum-time-difference/
Written by: Mostofa Adib Shakib
Language: Python
Time Complexity: O(nlogn)
Space Complexity: O(n)
"""
class Solution:
def find_min_difference(self, timePoints: List[str]) -> int:
min_times = []... |
class UserViewModel:
def __init__(self, user):
self.nickname = user.nickname
self.coins = user.coins
self.email = user.email
self.send_receive = '{}/{}'.format(user.send_count, user.receive_count) | class Userviewmodel:
def __init__(self, user):
self.nickname = user.nickname
self.coins = user.coins
self.email = user.email
self.send_receive = '{}/{}'.format(user.send_count, user.receive_count) |
"""
The format for defining the indicators:
Ideally there'd be a UI for this, but there isn't.
INDICATOR_DEFS = dict(
app="<mvp_app name>",
indicators=dict(
<couch_view in mvp_app>=dict(
<indicator_slug>=dict(
**init_kwargs
)
... | """
The format for defining the indicators:
Ideally there'd be a UI for this, but there isn't.
INDICATOR_DEFS = dict(
app="<mvp_app name>",
indicators=dict(
<couch_view in mvp_app>=dict(
<indicator_slug>=dict(
**init_kwargs
)
... |
cantidadnaranjas= float (input("Ingrese la cantidad de naranjas compradas:"))
valordocena= float (input("Ingrese el valor de cada docena:"))
ventas= float (input("Ingrese el valor obtenido en ventas:"))
pagoalagricultor=((cantidadnaranjas/12)*valordocena)
ganancia=(ventas-pagoalagricultor)
porcentaje=((ganancia*100)/pa... | cantidadnaranjas = float(input('Ingrese la cantidad de naranjas compradas:'))
valordocena = float(input('Ingrese el valor de cada docena:'))
ventas = float(input('Ingrese el valor obtenido en ventas:'))
pagoalagricultor = cantidadnaranjas / 12 * valordocena
ganancia = ventas - pagoalagricultor
porcentaje = ganancia * 1... |
# "Your BMI is 18, you are underweight."
# "Your BMI is 22, you have a normal weight."
# "Your BMI is 28, you are slightly overweight."
# "Your BMI is 33, you are obese."
# "Your BMI is 40, you are clinically obese."
height = float(input("enter your height in m: "))
weight = float(input("enter your weight in kg: "))
... | height = float(input('enter your height in m: '))
weight = float(input('enter your weight in kg: '))
bmi = weight / height ** 2
bmi = round(bmi)
if bmi < 18.5:
print(f'Your BMI is {bmi}, you are underweight.')
elif bmi < 25:
print(f'Your BMI is {bmi}, you have a normal weight.')
elif bmi < 30:
print(f'Your ... |
class BaseQueue:
DEFAULT_CAPACITY = 10
def __init__(self):
"""Create an empty queue."""
self._data = [None] * BaseQueue.DEFAULT_CAPACITY
self._size = 0
self._front = 0
def __len__(self):
"""Return the number of elements in the queue."""
return self._size
... | class Basequeue:
default_capacity = 10
def __init__(self):
"""Create an empty queue."""
self._data = [None] * BaseQueue.DEFAULT_CAPACITY
self._size = 0
self._front = 0
def __len__(self):
"""Return the number of elements in the queue."""
return self._size
... |
"""
This package aims to achieve database neutrality - we abstract database-client operations and database operations using interfaces so as to enable one to easily switch the database one uses.
:py:mod:`~sanskrit_data.db.interfaces` define these interfaces, while :py:mod:`~sanskrit_data_implementations.db` contain th... | """
This package aims to achieve database neutrality - we abstract database-client operations and database operations using interfaces so as to enable one to easily switch the database one uses.
:py:mod:`~sanskrit_data.db.interfaces` define these interfaces, while :py:mod:`~sanskrit_data_implementations.db` contain th... |
a, b = map(int, input().split())
for r in range(abs(b)):
if((a - r) % b) == 0:
q = int((a - r) / b)
break
print(q, r) | (a, b) = map(int, input().split())
for r in range(abs(b)):
if (a - r) % b == 0:
q = int((a - r) / b)
break
print(q, r) |
list_of_lists = [[1,'a',['cat'],2],[[[3]],'dog'],4,5]
flat_list = list()
def flatten_list(list_of_lists):
for item in list_of_lists:
if type(item) is list:
flatten_list(item)
else:
flat_list.append(item)
return flat_list
flatten_list(list_of_lists)
print(flat_list)
for i... | list_of_lists = [[1, 'a', ['cat'], 2], [[[3]], 'dog'], 4, 5]
flat_list = list()
def flatten_list(list_of_lists):
for item in list_of_lists:
if type(item) is list:
flatten_list(item)
else:
flat_list.append(item)
return flat_list
flatten_list(list_of_lists)
print(flat_list... |
"""
HF
This class shows sales of a specific product,
can be used to show overall, monthly, daily or yearly
"""
class CIndividualSales:
def __init__(self):
self.quantity_sold = 0
self.sales_earned = 0.0 | """
HF
This class shows sales of a specific product,
can be used to show overall, monthly, daily or yearly
"""
class Cindividualsales:
def __init__(self):
self.quantity_sold = 0
self.sales_earned = 0.0 |
parfile = 'metis_370P_35L.par'
sim_name = 'amp_v_gain_pyr74_mag=02.00_seeing=0.43_gain=0.50_calamp=000.25_regpar=0.010_threshold=0_loopfreq=1000_zenithdist=00'
seeing = 0.43
starmag = 2.00
optical_throughput = 0.2243
aosat_logfile ... | parfile = 'metis_370P_35L.par'
sim_name = 'amp_v_gain_pyr74_mag=02.00_seeing=0.43_gain=0.50_calamp=000.25_regpar=0.010_threshold=0_loopfreq=1000_zenithdist=00'
seeing = 0.43
starmag = 2.0
optical_throughput = 0.2243
aosat_logfile = None
aosat_loglevel = 'INFO'
loopfreq = 1000.0 |
n_window = 1024
"""int: Length of a frame used for silence detection."""
default_threshold = -48
"""int: Default threshold for silence."""
transients_threshold = -56
"""int: Threshold for transient audio signals."""
min_silence = 500
"""int: Minimum length of silence between two non-silent segments."""
keep_silence... | n_window = 1024
'int: Length of a frame used for silence detection.'
default_threshold = -48
'int: Default threshold for silence.'
transients_threshold = -56
'int: Threshold for transient audio signals.'
min_silence = 500
'int: Minimum length of silence between two non-silent segments.'
keep_silence = 400
'int: Amount ... |
def sum_even_fibonacci(max_fibo_term):
last2 = [1, 2]
index = 0
fibo = 3
evensum = 2
while fibo < max_fibo_term:
if (fibo & 0x1) == 0:
evensum += fibo
last2[index & 0x1] = fibo
index = ~index
fibo = last2[0] + last2[1];
return evensum
for i in range(... | def sum_even_fibonacci(max_fibo_term):
last2 = [1, 2]
index = 0
fibo = 3
evensum = 2
while fibo < max_fibo_term:
if fibo & 1 == 0:
evensum += fibo
last2[index & 1] = fibo
index = ~index
fibo = last2[0] + last2[1]
return evensum
for i in range(int(input... |
"""
binary_tree_diameter.py
Note: Diameter of a Binary Tree is the maximum distance between any two nodes
The diameter of a tree (sometimes called the width) is the number of nodes
on the longest path between two end nodes.
https://www.geeksforgeeks.org/diameter-of-a-binary-tree/
"""
# basic binary tree node
class... | """
binary_tree_diameter.py
Note: Diameter of a Binary Tree is the maximum distance between any two nodes
The diameter of a tree (sometimes called the width) is the number of nodes
on the longest path between two end nodes.
https://www.geeksforgeeks.org/diameter-of-a-binary-tree/
"""
class Node:
def __init__(s... |
#
# PySNMP MIB module JUNIPER-DFC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/JUNIPER-DFC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:48:04 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, constraints_intersection, value_size_constraint, value_range_constraint) ... |
n=int(input());a=[int(i) for i in input().split()];x=int(input());b=[int(i) for i in input().split()];r=""
d={}
for i in range(n):
t=a[i]
if t in d.keys():
d[t]+=1
else:
d[t]=1
for i in range(x):
t=b[i]
if t in d.keys():
r+=str(d[t])+" "
else:
r+="0 "
print(r,end=... | n = int(input())
a = [int(i) for i in input().split()]
x = int(input())
b = [int(i) for i in input().split()]
r = ''
d = {}
for i in range(n):
t = a[i]
if t in d.keys():
d[t] += 1
else:
d[t] = 1
for i in range(x):
t = b[i]
if t in d.keys():
r += str(d[t]) + ' '
else:
... |
"""
# !/usr/bin/env python
# -*- coding: utf-8 -*-
@Time : 2022/3/26 11:09
@File : xor_perceptron.py
"""
| """
# !/usr/bin/env python
# -*- coding: utf-8 -*-
@Time : 2022/3/26 11:09
@File : xor_perceptron.py
""" |
class Solution:
"""
@param A: a array
@return: is it monotonous
@Time : O(n) Space O(1)
"""
def isMonotonic(self, A):
if not A:
return True
increase = decrease = True
for i in range(1, len(A)):
#check increase
if A[i] ... | class Solution:
"""
@param A: a array
@return: is it monotonous
@Time : O(n) Space O(1)
"""
def is_monotonic(self, A):
if not A:
return True
increase = decrease = True
for i in range(1, len(A)):
if A[i] < A[i - 1]:
increase = False... |
#CalHamletV1.py
def getText():
txt = open("hamet.txt","r").read()
txt = txt.lower()
for ch in "!@#$%^&*()'_+:;.,/|~`":
txt = txt.replace(ch,"")
return txt
hamletTxt = getText()
words = hamletTxt.split()
counts = {}
for word in words:
counts[word] = counts.get(word,0) + 1
items = list(counts... | def get_text():
txt = open('hamet.txt', 'r').read()
txt = txt.lower()
for ch in "!@#$%^&*()'_+:;.,/|~`":
txt = txt.replace(ch, '')
return txt
hamlet_txt = get_text()
words = hamletTxt.split()
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
i... |
def main():
# input
Ss = [input() for _ in range(4)]
# compute
setSs = set(Ss)
# output
if 'H' in setSs and '2B' in setSs and '3B' in setSs and 'HR' in setSs:
print('Yes')
else:
print('No')
if __name__ == '__main__':
main()
| def main():
ss = [input() for _ in range(4)]
set_ss = set(Ss)
if 'H' in setSs and '2B' in setSs and ('3B' in setSs) and ('HR' in setSs):
print('Yes')
else:
print('No')
if __name__ == '__main__':
main() |
def activityNotifications(expenditure, d):
n = len(expenditure) #size of expenditure array
median = 0
notif = 0 #notifications
for i in range(d,n):
days = expenditure[i-d:i]
days.sort()
const = int(d/2)
if d % 2 == 0:
median = (days[const-1] + days[const... | def activity_notifications(expenditure, d):
n = len(expenditure)
median = 0
notif = 0
for i in range(d, n):
days = expenditure[i - d:i]
days.sort()
const = int(d / 2)
if d % 2 == 0:
median = (days[const - 1] + days[const]) / 2
else:
median ... |
class LiquidUniverseSelection(QCAlgorithm):
filteredByPrice = None
def Initialize(self):
self.SetStartDate(2019, 1, 11)
self.SetEndDate(2019, 7, 1)
self.SetCash(100000)
self.AddUniverse(self.CoarseSelectionFilter)
self.UniverseSettings.Resolution = Resoluti... | class Liquiduniverseselection(QCAlgorithm):
filtered_by_price = None
def initialize(self):
self.SetStartDate(2019, 1, 11)
self.SetEndDate(2019, 7, 1)
self.SetCash(100000)
self.AddUniverse(self.CoarseSelectionFilter)
self.UniverseSettings.Resolution = Resolution.Daily
... |
# Copyright 2020 The TensorStore Authors
#
# 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... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('//third_party:jpeg/workspace.bzl', repo_jpeg='repo')
load('//third_party:com_google_absl/workspace.bzl', repo_com_google_absl='repo')
load('//third_party:com_google_googletest/worksp... |
class MoveMyImageEvent():
def __init__(self, image, x, y):
self.image = image
self.x = x
self.y = y
class PlayerKeysSender():
def __init__(self, cursor: tuple, keys: list):
self.cursor = cursor
self.keys = keys
class MoveMyObjectEvent():
def __init__(self):
... | class Movemyimageevent:
def __init__(self, image, x, y):
self.image = image
self.x = x
self.y = y
class Playerkeyssender:
def __init__(self, cursor: tuple, keys: list):
self.cursor = cursor
self.keys = keys
class Movemyobjectevent:
def __init__(self):
pas... |
__author__ = 'David'
class Answer:
def __init__(self, question_id, value):
self.question_id = question_id
self.value = value | __author__ = 'David'
class Answer:
def __init__(self, question_id, value):
self.question_id = question_id
self.value = value |
# Program to Check Whether a String is Palindrome or Not.
string=str(input("Enter string to check :"))
if string==string[::-1]:
print("It's Palindrome.")
else:
print("It's not a palindrome.")
| string = str(input('Enter string to check :'))
if string == string[::-1]:
print("It's Palindrome.")
else:
print("It's not a palindrome.") |
__version__ = '1.1.1'
__license__ = 'BSD-3'
__copyright__ = '2022, Pearce Bergh <pearce@pearce.cool>'
__docformat__ = 'restructuredtext en'
| __version__ = '1.1.1'
__license__ = 'BSD-3'
__copyright__ = '2022, Pearce Bergh <pearce@pearce.cool>'
__docformat__ = 'restructuredtext en' |
class Solution(object):
def findWords(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
# hashmap for levels
dic = {'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 'y': 1, 'u': 1, 'i': 1, 'o': 1,
'p': 1, 'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 'h'... | class Solution(object):
def find_words(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
dic = {'q': 1, 'w': 1, 'e': 1, 'r': 1, 't': 1, 'y': 1, 'u': 1, 'i': 1, 'o': 1, 'p': 1, 'a': 2, 's': 2, 'd': 2, 'f': 2, 'g': 2, 'h': 2, 'j': 2, 'k': 2, 'l': 2, 'z': 3, 'x': 3... |
class Car:
def __init__(self,wheels=4):
self.wheels = wheels
# We'll say that all cars, no matter their engine, have four wheels by default.
class Gasoline(Car):
def __init__(self,engine='Gasoline',tank_cap=20):
Car.__init__(self)
self.engine = engine
self.tank_cap = tan... | class Car:
def __init__(self, wheels=4):
self.wheels = wheels
class Gasoline(Car):
def __init__(self, engine='Gasoline', tank_cap=20):
Car.__init__(self)
self.engine = engine
self.tank_cap = tank_cap
self.tank = 0
def refuel(self):
self.tank = self.tank_ca... |
def image_string( image, divider="," ):
'''this function will take as input a 2D array referred to by image and return
a string version of this 2D array that is separated by tabs'''
imageString = ""
count = 1
for row in image:
for col in row:
imageString = imageString + str(col... | def image_string(image, divider=','):
"""this function will take as input a 2D array referred to by image and return
a string version of this 2D array that is separated by tabs"""
image_string = ''
count = 1
for row in image:
for col in row:
image_string = imageString + str(col)... |
def aumentar(num=0, porcent=0):
aumento = num + (porcent/100*num)
return aumento
def diminuir(num=0, porcent=0):
diminuto = num - (porcent/100*num)
return diminuto
def dobro(num=0):
dob = num*2
return dob
def metade(num=0):
met = num/2
return met
def moedas(num=0, moeda='R$'):
... | def aumentar(num=0, porcent=0):
aumento = num + porcent / 100 * num
return aumento
def diminuir(num=0, porcent=0):
diminuto = num - porcent / 100 * num
return diminuto
def dobro(num=0):
dob = num * 2
return dob
def metade(num=0):
met = num / 2
return met
def moedas(num=0, moeda='R$')... |
expected_output = {
"statistics":{
"total_messages_sent":105702,
"message_send_failures":0,
"regular_updates_sent":105698,
"queries_responsed_to":0,
"rib_updates":2,
"total_packets_received":69147,
"packets_discarded":16295,
"routes_discarded":0,
"packets_receive... | expected_output = {'statistics': {'total_messages_sent': 105702, 'message_send_failures': 0, 'regular_updates_sent': 105698, 'queries_responsed_to': 0, 'rib_updates': 2, 'total_packets_received': 69147, 'packets_discarded': 16295, 'routes_discarded': 0, 'packets_received_at_standby': 0, 'routes_allocated': 3, 'paths_al... |
# problem name: Design Authentication Manager
# problem link: https://leetcode.com/contest/biweekly-contest-48/problems/design-authentication-manager/
# contest link: https://leetcode.com/contest/biweekly-contest-48/
# time: (?)
# author: reyad
# other_tags: ad hoc
# difficulty_level: beginner
class AuthenticationM... | class Authenticationmanager:
def __init__(self, timeToLive: int):
self.buf = dict()
self.ttl = timeToLive
def generate(self, tokenId: str, currentTime: int) -> None:
self.buf[tokenId] = currentTime + self.ttl
def renew(self, tokenId: str, currentTime: int) -> None:
if toke... |
def linear_search(arr,n):
search=int(input("ENTER THE ELEMENT YOU WANT TO SEARCH : "))
for i in range(n):
if search==arr[i]:
print("---------------------------------")
print("SUCCESSFUL SEARCH")
print("ELEMENT FOUND AT POSITION {}".format(i+1))
prin... | def linear_search(arr, n):
search = int(input('ENTER THE ELEMENT YOU WANT TO SEARCH : '))
for i in range(n):
if search == arr[i]:
print('---------------------------------')
print('SUCCESSFUL SEARCH')
print('ELEMENT FOUND AT POSITION {}'.format(i + 1))
prin... |
class Error(Exception):
"""Base class for `snapshotbackup` exceptions."""
def __init__(self, message):
super().__init__(message)
self.message = message
def __str__(self):
return self.message
class BackupDirError(Error):
"""backup directory related error with meaningful messag... | class Error(Exception):
"""Base class for `snapshotbackup` exceptions."""
def __init__(self, message):
super().__init__(message)
self.message = message
def __str__(self):
return self.message
class Backupdirerror(Error):
"""backup directory related error with meaningful message... |
seq=input()
times=[]
leftRacer=0; rightRacer=0
k=0
while k<len(seq):
val=""
if seq[k]!=" ":
for j in range(k,len(seq)):
if seq[j]!=" ":
val+=seq[j]
k+=1
else:
k+=1
break
val=int(val)
ti... | seq = input()
times = []
left_racer = 0
right_racer = 0
k = 0
while k < len(seq):
val = ''
if seq[k] != ' ':
for j in range(k, len(seq)):
if seq[j] != ' ':
val += seq[j]
k += 1
else:
k += 1
break
val = int(va... |
"""
Configurations of high performance schedules for conv2d_nchw
YOLO convolution layer 24
Target Intel CPU
====================================
**Author**: `Size Zheng`
the terms used below:
------------------------------------
method: fuse_and_bind --> only use parallel
spatial_order: flatten --> bo, ko, po, qo, bm... | """
Configurations of high performance schedules for conv2d_nchw
YOLO convolution layer 24
Target Intel CPU
====================================
**Author**: `Size Zheng`
the terms used below:
------------------------------------
method: fuse_and_bind --> only use parallel
spatial_order: flatten --> bo, ko, po, qo, bm... |
class Student:
def __init__(self):
self.name = input("Enter your name:")
self.roll = int(input("Enter your roll number:"))
self.marks=list()
for i in range (5):
self.marks.insert(i,int(input("enter %d th mark :"%(i+1))))
class Test(Student):
def check(self):
... | class Student:
def __init__(self):
self.name = input('Enter your name:')
self.roll = int(input('Enter your roll number:'))
self.marks = list()
for i in range(5):
self.marks.insert(i, int(input('enter %d th mark :' % (i + 1))))
class Test(Student):
def check(self):
... |
def aumentar(n=0, taxa=0, formato=False):
a = n + (n * taxa / 100)
return a if formato is False else moeda(a)
def diminuir(n=0, taxa=0, formato=False):
d = n - (n * taxa / 100)
return d if formato is False else moeda(d)
def dobro(n=0, formato=False):
dos = n + n
return dos if formato is Fals... | def aumentar(n=0, taxa=0, formato=False):
a = n + n * taxa / 100
return a if formato is False else moeda(a)
def diminuir(n=0, taxa=0, formato=False):
d = n - n * taxa / 100
return d if formato is False else moeda(d)
def dobro(n=0, formato=False):
dos = n + n
return dos if formato is False else... |
# File: tenablesc_consts.py
#
# Copyright (c) 2017-2022 Splunk Inc.
#
# 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 a... | ip_hostname = 'ip_hostname'
scan_policy = 'scan_policy_id'
datetime_format = 'TZID=UTC:%Y%m%dT%H%M%S'
repository_id = 'repository_id'
scan_delay = 3
page_size = 100
invalid_host_chars = ' !"\'@#$%^&*(){};[]|'
tenable_err_code_unavailable = 'Error code unavailable'
tenable_err_msg_unavailable = 'Error message unavailabl... |
words = ('apple', 'banana', 'cello', 'donut', 'elephant', 'fast', 'green',
'home', 'integer', 'jackson', 'kazoo', 'locomotive', 'microscope', 'nautical',
'ollie', 'patient', 'queen', 'race', 'sack', 'taut', 'ukelele', 'violin',
'water', 'xylophone', 'yellow', 'zac')
| words = ('apple', 'banana', 'cello', 'donut', 'elephant', 'fast', 'green', 'home', 'integer', 'jackson', 'kazoo', 'locomotive', 'microscope', 'nautical', 'ollie', 'patient', 'queen', 'race', 'sack', 'taut', 'ukelele', 'violin', 'water', 'xylophone', 'yellow', 'zac') |
# @author Huaze Shen
# @date 2020-03-27
def moving_count(m: int, n: int, k: int) -> int:
visited = [[0 for i in range(n)] for i in range(m)]
count = 0
q = [(0, 0)]
visited[0][0] = 1
count += 1
while len(q) > 0:
point = q.pop(0)
for neighbor in get_neighbors(point):
... | def moving_count(m: int, n: int, k: int) -> int:
visited = [[0 for i in range(n)] for i in range(m)]
count = 0
q = [(0, 0)]
visited[0][0] = 1
count += 1
while len(q) > 0:
point = q.pop(0)
for neighbor in get_neighbors(point):
if is_valid(neighbor, m, n, k, visited):
... |
"""
415. Valid Palindrome
https://www.lintcode.com/problem/valid-palindrome/description
"""
class Solution:
"""
@param s: A string
@return: Whether the string is a valid palindrome
"""
def isPalindrome(self, s):
# write your code here
n = len(s)
i, j = 0, n - 1
while ... | """
415. Valid Palindrome
https://www.lintcode.com/problem/valid-palindrome/description
"""
class Solution:
"""
@param s: A string
@return: Whether the string is a valid palindrome
"""
def is_palindrome(self, s):
n = len(s)
(i, j) = (0, n - 1)
while i < j:
while... |
#!/usr/bin/python3
#
## this file is part of cheap_pie, a python tool for chip validation
## author: Marco Merlin
## email: marcomerli@gmail.com
def cp_banner():
logo = (
" _..._ ",
" .-'_..._''. ... | def cp_banner():
logo = (' _..._ ', " .-'_..._''. ", " .' .' '.\\ . __.....__ _________ _...._ ", " / .' .'| .-... |
__title__ = 'deepomatic-api'
__description__ = 'Deepomatic API client'
__version__ = '0.9.4'
__author__ = 'deepomatic'
__author_email__ = 'support@deepomatic.com'
__url__ = 'https://github.com/deepomatic/deepomatic-client-python'
__license__ = 'MIT License'
__project_urls__ = {
'Product': 'https://www.deepomatic.co... | __title__ = 'deepomatic-api'
__description__ = 'Deepomatic API client'
__version__ = '0.9.4'
__author__ = 'deepomatic'
__author_email__ = 'support@deepomatic.com'
__url__ = 'https://github.com/deepomatic/deepomatic-client-python'
__license__ = 'MIT License'
__project_urls__ = {'Product': 'https://www.deepomatic.com', '... |
experiments = [
{"id": "0.1", "name": "Europarl Large\n(630K; cs-en)", "bpe-merges": "32k", "bpe": "Large subword vocab", "lang-pair": "cs-en", "sacrebleu_bleu": 42.5, "sacrebleu_chrf": 0.66, "sentences": 635498, "tokens": 17400566, "tokens/sentences": 28.275},
{"id": "0.2", "name": "Europarl Large\n(630K; cs-... | experiments = [{'id': '0.1', 'name': 'Europarl Large\n(630K; cs-en)', 'bpe-merges': '32k', 'bpe': 'Large subword vocab', 'lang-pair': 'cs-en', 'sacrebleu_bleu': 42.5, 'sacrebleu_chrf': 0.66, 'sentences': 635498, 'tokens': 17400566, 'tokens/sentences': 28.275}, {'id': '0.2', 'name': 'Europarl Large\n(630K; cs-en)', 'bpe... |
__all__ = [
"GstNotInitializedError",
"PipelineBuildError",
"ConnectionLostError",
]
class GstNotInitializedError(RuntimeError):
def __init__(self) -> None:
super().__init__("You must initialize Gst first. See document.")
class PipelineBuildError(RuntimeError):
pass
class ConnectionLos... | __all__ = ['GstNotInitializedError', 'PipelineBuildError', 'ConnectionLostError']
class Gstnotinitializederror(RuntimeError):
def __init__(self) -> None:
super().__init__('You must initialize Gst first. See document.')
class Pipelinebuilderror(RuntimeError):
pass
class Connectionlosterror(RuntimeErr... |
CODE = [
'@0',
'D=M',
'@INFINITE_LOOP',
'D;JLE',
'@counter',
'M=D',
'@SCREEN',
'D=A',
'@address',
'M=D',
'(LOOP)',
'@address',
'A=M',
'M=-1',
'@address',
'D=M',
'@32',
'D=D+A',
'@address',
'M=D',
'@counter',
'MD=M-1',
'@LOOP',
... | code = ['@0', 'D=M', '@INFINITE_LOOP', 'D;JLE', '@counter', 'M=D', '@SCREEN', 'D=A', '@address', 'M=D', '(LOOP)', '@address', 'A=M', 'M=-1', '@address', 'D=M', '@32', 'D=D+A', '@address', 'M=D', '@counter', 'MD=M-1', '@LOOP', 'D;JGT', '(INFINITE_LOOP)', '@INFINITE_LOOP', '0;JMP']
instructions = '0000000000000000\n11111... |
__all__ = ['stuff', 'stuff_scraper', 'stuff_charter', 'city_list']
__author__ = 'Fenimore Love'
__license__ = 'MIT'
__date__ = '2015-2016'
| __all__ = ['stuff', 'stuff_scraper', 'stuff_charter', 'city_list']
__author__ = 'Fenimore Love'
__license__ = 'MIT'
__date__ = '2015-2016' |
print("I did it")
#'''
#Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur tincidunt massa sem, quis porttitor sem suscipit in. Vestibulum suscipit dignissim turpis et pulvinar. Aenean efficitur fermentum sem, et dictum lacus finibus eget. Pellentesque sagittis odio elit, ut fermentum risus bibendum at.... | print('I did it') |
# Add the missing function call
uniforms = {'Thelma': '4', 'Twi': '21', 'Dottie': '9'}
thelma_number = uniforms['Thelma']
twi_number = uniforms['Twi']
sum = thelma_number + twi_number
print(sum)
| uniforms = {'Thelma': '4', 'Twi': '21', 'Dottie': '9'}
thelma_number = uniforms['Thelma']
twi_number = uniforms['Twi']
sum = thelma_number + twi_number
print(sum) |
"""Command line arguments shared variables across all modules."""
configfile = None
stdout = None
stderr = None
date = None
tel_id = None
nightsummary = True
reason = None
directory = None
log_directory = None
simulate = None
noninteractive = None
verbose = None
warning = None
nocheck = None
no_dl2 = None
prod_id = No... | """Command line arguments shared variables across all modules."""
configfile = None
stdout = None
stderr = None
date = None
tel_id = None
nightsummary = True
reason = None
directory = None
log_directory = None
simulate = None
noninteractive = None
verbose = None
warning = None
nocheck = None
no_dl2 = None
prod_id = Non... |
# -*- coding: utf-8 -*-
name = 'glew'
version = '2.0.0'
authors = ['fredrik.brannbacka']
variants = [["platform-linux"]]
def commands():
env.LD_LIBRARY_PATH.prepend("{root}/lib64")
if building:
env.CMAKE_MODULE_PATH.append("{root}/cmake")
| name = 'glew'
version = '2.0.0'
authors = ['fredrik.brannbacka']
variants = [['platform-linux']]
def commands():
env.LD_LIBRARY_PATH.prepend('{root}/lib64')
if building:
env.CMAKE_MODULE_PATH.append('{root}/cmake') |
# Copyright 2016 - Nokia 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 ... | def args_to_dict(args, attrs):
return {(attr, value) for (attr, value) in [(attr, getattr(args, attr)) for attr in attrs] if value is not None}
def list2cols(cols, objs):
return (cols, [tuple([o[k] for k in cols]) for o in objs])
def get_client(obj):
if hasattr(obj.app, 'client_manager'):
return o... |
class Loss:
def __init__(self,
return_all: bool=False
) -> None:
self.return_all = return_all
pass
| class Loss:
def __init__(self, return_all: bool=False) -> None:
self.return_all = return_all
pass |
# -*- encoding: utf-8 -*-
__all__ = [ 'DBusSessionError' ]
class DBusSessionError(BaseException) :
pass
| __all__ = ['DBusSessionError']
class Dbussessionerror(BaseException):
pass |
# This file is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distrib... | """SMV Provider API
This module allows user to declare/register providers.
"""
class Smvprovider(object):
"""Base class of all provider classes.
Each provider must inherit from this class and also define `provider_type()` static
method that returns the type as a string.
Note: there is n... |
# Python - 2.7.6
test.assert_equals(pascal(1), [[1]])
test.assert_equals(pascal(5), [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]])
| test.assert_equals(pascal(1), [[1]])
test.assert_equals(pascal(5), [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1]]) |
N, M = map(int, input().split())
X = [int(x) for x in input().split()]
if N >= M:
print(0)
quit()
X.sort()
dX = list()
for i in range(M - 1):
dX.append(X[i + 1] - X[i])
dX.sort(reverse=True)
print(sum(dX) - sum([dX[i] for i in range(N - 1)]))
| (n, m) = map(int, input().split())
x = [int(x) for x in input().split()]
if N >= M:
print(0)
quit()
X.sort()
d_x = list()
for i in range(M - 1):
dX.append(X[i + 1] - X[i])
dX.sort(reverse=True)
print(sum(dX) - sum([dX[i] for i in range(N - 1)])) |
""""A PROGRAM THAT PROMPTS THE USER FOR
THE NUMBER OF PEOPLE ATTENDING THEIR WEDDING AND PRINTS THE CORRESPONDING PRICE IN THE CONSOLE"""""
try:
a = int(input('Number of guests'))
if 0 < a <= 50:
print('price =$4000')
elif 50 < a <= 100:
print('price = $10000')
elif 100 < a <= 200:
... | """"A PROGRAM THAT PROMPTS THE USER FOR
THE NUMBER OF PEOPLE ATTENDING THEIR WEDDING AND PRINTS THE CORRESPONDING PRICE IN THE CONSOLE"""
try:
a = int(input('Number of guests'))
if 0 < a <= 50:
print('price =$4000')
elif 50 < a <= 100:
print('price = $10000')
elif 100 < a <= 200:
... |
def fibonacci(n):
if n==1 or n==2:
return 1
return fibonacci(n-1)+fibonacci(n-2)
n=3 #0,1,1,2,3,5,..
fibonacci(n)
| def fibonacci(n):
if n == 1 or n == 2:
return 1
return fibonacci(n - 1) + fibonacci(n - 2)
n = 3
fibonacci(n) |
"""This optimization gets rid of the loops completely. To see the details
visit https://projecteuler.net/overview=001 (you need to be logged in and pass
the problem to see the solution optimization spoilers).
"""
def sum_divisible_by(n: int, limit: int) -> int:
"""Computes the sum of all the multiples of n up to ... | """This optimization gets rid of the loops completely. To see the details
visit https://projecteuler.net/overview=001 (you need to be logged in and pass
the problem to see the solution optimization spoilers).
"""
def sum_divisible_by(n: int, limit: int) -> int:
"""Computes the sum of all the multiples of n up to t... |
driver_loc = 'LOC_CHROMEDRIVE'
user = 'EMAIL_HERE' # username for golfwang.com
password = 'PASSWORD_HERE' # password for golfwang.com
cred_num = 'CREDIT_CARD_NUMBER_HERE' # The card number which should be on the front of the card
cred_name = 'NAME_ON_CARD' # The first and last name on the card
cred_exp = 'EXP_DATE' #... | driver_loc = 'LOC_CHROMEDRIVE'
user = 'EMAIL_HERE'
password = 'PASSWORD_HERE'
cred_num = 'CREDIT_CARD_NUMBER_HERE'
cred_name = 'NAME_ON_CARD'
cred_exp = 'EXP_DATE'
cred_cvv = 'CCV_HERE' |
circle_width = 50
circle_x, circle_y = 0, 0
direction = 1
move_amount = 20
# This runs only once
def setup():
size(800, 800)
fill(255, 255, 0)
# This runs once per frame
def draw():
background(255)
draw_circle()
move_circle()
def draw_circle():
ellipse(circle_x, circle_y, circle_width, ci... | circle_width = 50
(circle_x, circle_y) = (0, 0)
direction = 1
move_amount = 20
def setup():
size(800, 800)
fill(255, 255, 0)
def draw():
background(255)
draw_circle()
move_circle()
def draw_circle():
ellipse(circle_x, circle_y, circle_width, circle_width)
def move_circle():
global circle... |
class Shirt:
def __init__(self):
self.size = input("Enter the shirt size: ")
self.color = input("Enter the shirts color: ")
self.name = input("Enter the Shirt name: ")
def __str__(self):
ret = "SHIRT\nSize: {}\nColor: {}\nName: {}\n".format(self.size, self.color, self.n... | class Shirt:
def __init__(self):
self.size = input('Enter the shirt size: ')
self.color = input('Enter the shirts color: ')
self.name = input('Enter the Shirt name: ')
def __str__(self):
ret = 'SHIRT\nSize: {}\nColor: {}\nName: {}\n'.format(self.size, self.color, self.... |
# https://www.acmicpc.net/problem/1427
def sort_number(n):
return "".join(sorted(n, reverse=True))
if __name__ == "__main__":
N = input()
print(sort_number(N))
| def sort_number(n):
return ''.join(sorted(n, reverse=True))
if __name__ == '__main__':
n = input()
print(sort_number(N)) |
questions = ['What is known about Covid-19 transmission?',
'What is known about Covid-19 incubation?',
'What is known about Covid-19 environmental stability?']
class TaskQuery:
@staticmethod
def questions():
return questions
| questions = ['What is known about Covid-19 transmission?', 'What is known about Covid-19 incubation?', 'What is known about Covid-19 environmental stability?']
class Taskquery:
@staticmethod
def questions():
return questions |
class FormatType:
XML = "xml"
JSON = "json"
FASTA = "fasta"
TAB = "tab" | class Formattype:
xml = 'xml'
json = 'json'
fasta = 'fasta'
tab = 'tab' |
_ = int(input())
arr = reversed(sorted([int(x) for x in input().split()]))
max_sum, min_sum = 0, 0
subset_pos, subset_neg = list(), list()
for i in range(len(arr)):
if arr[i] >= 0:
max_sum += arr[i]
subset_pos.append(arr[i])
else:
min_sum += arr[i]
subset_neg.append(arr[i])
... | _ = int(input())
arr = reversed(sorted([int(x) for x in input().split()]))
(max_sum, min_sum) = (0, 0)
(subset_pos, subset_neg) = (list(), list())
for i in range(len(arr)):
if arr[i] >= 0:
max_sum += arr[i]
subset_pos.append(arr[i])
else:
min_sum += arr[i]
subset_neg.append(arr[i... |
# A metaclass that disallows mixed case identifier names
class NoMixedCaseMeta(type):
def __new__(cls, clsname, bases, clsdict):
for name in clsdict:
if name.lower() != name:
raise TypeError('Bad attribute name: ' + name)
return super().__new__(cls, clsname, bases, clsdi... | class Nomixedcasemeta(type):
def __new__(cls, clsname, bases, clsdict):
for name in clsdict:
if name.lower() != name:
raise type_error('Bad attribute name: ' + name)
return super().__new__(cls, clsname, bases, clsdict)
class Root(metaclass=NoMixedCaseMeta):
pass
cl... |
class BaseRegressor:
def __init__(self):
pass
def train(self, dataset, labels):
pass
def predict(self, dataset):
pass
def error(self, predicted, actual):
pass
| class Baseregressor:
def __init__(self):
pass
def train(self, dataset, labels):
pass
def predict(self, dataset):
pass
def error(self, predicted, actual):
pass |
"""
Python 3.10 structure pattern matching feature
"""
def pattern_match(item):
"""
Example pattern matching
"""
match item:
case "Kofi":
print("Is a string")
case 90:
print("Is a integer")
case True | False:
print("Is a boolean")
case... | """
Python 3.10 structure pattern matching feature
"""
def pattern_match(item):
"""
Example pattern matching
"""
match item:
case 'Kofi':
print('Is a string')
case 90:
print('Is a integer')
case True | False:
print('Is a boolean')
case... |
class Solution(object):
def distinctSubseqII(self, S):
"""
:type S: str
:rtype: int
"""
# abb
# a, /b, ab, /abb
MOD = 10 ** 9 + 7
counter = [0] * 26
for ch in S:
idx = ord(ch) - ord('a')
counter[idx] = sum(count... | class Solution(object):
def distinct_subseq_ii(self, S):
"""
:type S: str
:rtype: int
"""
mod = 10 ** 9 + 7
counter = [0] * 26
for ch in S:
idx = ord(ch) - ord('a')
counter[idx] = sum(counter) + 1
return sum(counter) % MOD |
"""
ECG Pipeline
====================
.. warning:: Include code to show how to create a pipeline to
clean an ecg signal. It is probably in one of the
jupyter notebooks (maybe ecg_qc.ipynb).
""" | """
ECG Pipeline
====================
.. warning:: Include code to show how to create a pipeline to
clean an ecg signal. It is probably in one of the
jupyter notebooks (maybe ecg_qc.ipynb).
""" |
#
# PySNMP MIB module AGILENT-ENTERPRISE (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGILENT-ENTERPRISE
# Produced by pysmi-0.3.4 at Wed May 1 11:15:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
class Solution:
# @return a list of integers
def grayCode(self, n):
m = 1 << n
res = []
d = [(1 << (i + 1)) / 2 for i in range(n)]
for i in range(m):
num = 0
for j, e in enumerate(d):
if e / (1 << (j + 1)) % 2 == 1:
num ... | class Solution:
def gray_code(self, n):
m = 1 << n
res = []
d = [(1 << i + 1) / 2 for i in range(n)]
for i in range(m):
num = 0
for (j, e) in enumerate(d):
if e / (1 << j + 1) % 2 == 1:
num += 1 << j
d[j] +=... |
# HEAD
# Using `continue` and `break` keys
# DESCRIPTION
# Describes usage of 'continue' and 'break' keys
# 'continue' key skips execution of block
# below it and continues to next
# logical step after the continue statement
# PENDING: continue usage with functions to exit program
#
# RESOURCES
#
for i... | for i in range(0, 6, 1):
if i == 3:
continue
print('Will print two times using number of increments in the last ' + str(i)) |
for t in range(int(input())):
n,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
p,q=0,0
res=[]
if a[0]!=1:
p=a[0]-1
for i in range(1,n):
res.append(a[i]-a[i-1]-1)
if a[-1]!=k:
q=k-a[-1]
res1=max(p,q)
add1=0
for i in range(0,len(res... | for t in range(int(input())):
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
(p, q) = (0, 0)
res = []
if a[0] != 1:
p = a[0] - 1
for i in range(1, n):
res.append(a[i] - a[i - 1] - 1)
if a[-1] != k:
q = k - a[-1]
res1 = max(p, q... |
#
# PySNMP MIB module EdgeSwitch-TIMERANGE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EdgeSwitch-TIMERANGE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:56:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint) ... |
# https://www.hackerrank.com/challenges/find-a-string/problem
def count_substring(string, sub_string):
count = 0
for i in range(len(string)):
if string[i] == sub_string[0]:
if string[i:(i + len(sub_string))] == sub_string:
count += 1
i += len(sub_string) - 1... | def count_substring(string, sub_string):
count = 0
for i in range(len(string)):
if string[i] == sub_string[0]:
if string[i:i + len(sub_string)] == sub_string:
count += 1
i += len(sub_string) - 1
return count
string = input()
sub_string = input()
print(coun... |
#!/usr/bin/env python3
#
# Author : Vishwas K Singh
# Email : vishwasks32@gmail.com
class user:
'''A class for user in address book '''
version = 0.1
def __init__(self,name):
''' A Constructor '''
self.name = name
def getname(self):
''' R... | class User:
"""A class for user in address book """
version = 0.1
def __init__(self, name):
""" A Constructor """
self.name = name
def getname(self):
""" Returns the name of instance """
return self.name
def getver(self):
""" Returns the version """
... |
KS_SPOT = "00"
KS_DEFER = "10"
KS_FUTURES = "11"
KS_FORWARD = "01"
KS_DELIVERY = "AP"
KS_MIDDLE = "MD"
KS_I_INITING = '0'
KS_I_INIT = '1'
KS_I_BEGIN = '2'
KS_I_GRP_ORDER = '3'
KS_I_GRP_MATCH = '4'
KS_I_NORMAL = '5'
KS_I_PAUSE = '6'
KS_I_DERY_APP = '7'
KS_I_DERY_MATCH = '8'
KS_I_MID_APP = '9'
KS_I_MID_MATCH = 'A'
KS_I_E... | ks_spot = '00'
ks_defer = '10'
ks_futures = '11'
ks_forward = '01'
ks_delivery = 'AP'
ks_middle = 'MD'
ks_i_initing = '0'
ks_i_init = '1'
ks_i_begin = '2'
ks_i_grp_order = '3'
ks_i_grp_match = '4'
ks_i_normal = '5'
ks_i_pause = '6'
ks_i_dery_app = '7'
ks_i_dery_match = '8'
ks_i_mid_app = '9'
ks_i_mid_match = 'A'
ks_i_e... |
VERSION = "1.01"
GUI = "Tkinter"
NAME = "Li-ion capacity"
APPNAME = "li-ion"
AUTHOR = "IRD" | version = '1.01'
gui = 'Tkinter'
name = 'Li-ion capacity'
appname = 'li-ion'
author = 'IRD' |
ov5640_config = (
[0x3103, 0x11],
[0x3008, 0x82],
[0x3008, 0x42],
[0x3103, 0x03],
[0x3017, 0xff],
[0x3018, 0xff],
[0x3034, 0x1A],
[0x3037, 0x13],
[0x3108, 0x01],
[0x3630, 0x36],
[0x3631, 0x0e],
[0x3632, 0xe2],
[0x3633, 0x12],
[0x3621, 0xe0],
[0x3704, 0xa0],
[0x3703, 0x5a],
[0x3715, 0x78],
[0x3717, 0x01],
[0x370b, 0x60]... | ov5640_config = ([12547, 17], [12296, 130], [12296, 66], [12547, 3], [12311, 255], [12312, 255], [12340, 26], [12343, 19], [12552, 1], [13872, 54], [13873, 14], [13874, 226], [13875, 18], [13857, 224], [14084, 160], [14083, 90], [14101, 120], [14103, 1], [14091, 96], [14085, 26], [14597, 2], [14598, 16], [14593, 10], [... |
# ------------------------------
# 79. Word Search
#
# Description:
# Given a 2D board and a word, find if the word exists in the grid.
#
# The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells
# are those horizontally or vertically neighboring. The same letter cell may not b... | class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not board or not board[0] or (not word):
return False
first = word[0]
starts = []
m = len(board)
n =... |
# see "A Monotonic Superclass Linearization for Dylan",
# by Kim Barrett et al. (OOPSLA 1996)
# Testing consistency with EPG...
class Pane(object): pass
class ScrollingMixin(object): pass
class EditingMixin(object): pass
class ScrollablePane(Pane,ScrollingMixin): pass
class EditablePane(Pane,EditingMixin): pass
class E... | class Pane(object):
pass
class Scrollingmixin(object):
pass
class Editingmixin(object):
pass
class Scrollablepane(Pane, ScrollingMixin):
pass
class Editablepane(Pane, EditingMixin):
pass
class Editablescrollablepane(ScrollablePane, EditablePane):
pass
___assert_equal(EditableScrollablePane.... |
def combine_processors(processors):
def process(samples):
generated_samples = []
for sample in samples:
generated_samples.extend(augment_sample(sample))
return generated_samples
def augment_sample(sample):
generated_samples = [sample]
for processor in processors:
generated_sample... | def combine_processors(processors):
def process(samples):
generated_samples = []
for sample in samples:
generated_samples.extend(augment_sample(sample))
return generated_samples
def augment_sample(sample):
generated_samples = [sample]
for processor in proces... |
# Stack Implementation
# Stack Class (LIFO)
class Stack():
def __init__(self, initial_data=[]):
if isinstance(initial_data, int):
self.data = [initial_data]
return
self.data = list(initial_data)
# Inserts a element at the top of the stack
def push(self, element):
... | class Stack:
def __init__(self, initial_data=[]):
if isinstance(initial_data, int):
self.data = [initial_data]
return
self.data = list(initial_data)
def push(self, element):
self.data.append(element)
def pop(self):
if self.is_empty():
ra... |
# import newModule as any
# newModule.new("Dony")
# newModule.new("Ahmed")
# newModule.new("Ronaldo")
# x = any.player["name"]
# print(x)
# import platform
# op = dir(platform)
# print(op)
# import math
# print(math.log(10))
# from newModule import player
# print(player["name"])
print(help('modules')) | print(help('modules')) |
"""
[2015-01-14] Challenge #197 [Intermediate] Food Delivery Problem
https://www.reddit.com/r/dailyprogrammer/comments/2sfs8f/20150114_challenge_197_intermediate_food_delivery/
#Description:
You are owner of a new restaurant that is open 24 hours a day 7 days a week. To be helpful to your customers you
deliver. To ma... | """
[2015-01-14] Challenge #197 [Intermediate] Food Delivery Problem
https://www.reddit.com/r/dailyprogrammer/comments/2sfs8f/20150114_challenge_197_intermediate_food_delivery/
#Description:
You are owner of a new restaurant that is open 24 hours a day 7 days a week. To be helpful to your customers you
deliver. To ma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.