content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Solution:
def smallestEqual(self, nums: List[int]) -> int:
smallest = -1
for i in range(0, len(nums)):
if i % 10 == nums[i]:
if smallest == -1:
smallest = i
else:
if i < smallest:
smalle... | class Solution:
def smallest_equal(self, nums: List[int]) -> int:
smallest = -1
for i in range(0, len(nums)):
if i % 10 == nums[i]:
if smallest == -1:
smallest = i
elif i < smallest:
smallest = i
return smal... |
#!/usr/bin/env python
# coding: utf-8
"""
Implement a MyCalendar class to store your events. A new event can be added if
adding the event will not cause a double booking.
Your class will have the method, book(int start, int end). Formally, this
represents a booking on the half open interval [start, end), the range of... | """
Implement a MyCalendar class to store your events. A new event can be added if
adding the event will not cause a double booking.
Your class will have the method, book(int start, int end). Formally, this
represents a booking on the half open interval [start, end), the range of real
numbers x such that start <= x < ... |
PROTO = {
'spaceone.monitoring.api.plugin.webhook': ['Webhook'],
'spaceone.monitoring.api.plugin.event': ['Event'],
}
| proto = {'spaceone.monitoring.api.plugin.webhook': ['Webhook'], 'spaceone.monitoring.api.plugin.event': ['Event']} |
def do_twice_mod(func, value):
'''
Input
func: Un objeto funcion.
value: valor que se le pasa al objeto funcion.
'''
func(value)
func(value)
def print_twice(arg):
'''
Input
arg: argumento a imprimir.
'''
print(arg)
print(arg)
#do_twice_mod(print_twice, 'spam')
de... | def do_twice_mod(func, value):
"""
Input
func: Un objeto funcion.
value: valor que se le pasa al objeto funcion.
"""
func(value)
func(value)
def print_twice(arg):
"""
Input
arg: argumento a imprimir.
"""
print(arg)
print(arg)
def do_four(func, value):
"""
In... |
# The MIT License (MIT)
#
# Copyright (c) 2014-2016 Benedikt Schmitt <benedikt@benediktschmitt.de>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without lim... | __all__ = ['Recipe', 'Ingredient']
class Ingredient(object):
def __init__(self, name, measure, amount, db_id):
self.name = name
self.measure = measure
self.amount = amount
self.db_id = db_id
def __str__(self):
return str(self.amount) + ' ' + str(self.measure) + ' ' + s... |
# pylint: disable=invalid-name,used-before-assignment,missing-docstring
if xeo > 5: # [cond-expr]
xeo = 5
else:
xeo = 6
if xeo > 5:
xeo = 5
else:
beo = 6
| if xeo > 5:
xeo = 5
else:
xeo = 6
if xeo > 5:
xeo = 5
else:
beo = 6 |
# Scrapy settings for sydney project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'sydney'
SPIDER_MODULES = ['sydney.spiders']
NEWSPIDER_MODULE = 'sydney.spide... | bot_name = 'sydney'
spider_modules = ['sydney.spiders']
newspider_module = 'sydney.spiders'
download_delay = 1
httpcache_enabled = True |
def addition():
a = 10
b = 45
print(a + b)
addition()
def addition():
a = int(input("Enter a number "))
b = int(input("Please enter another number "))
print(a + b)
addition()
def user_info(name, age, info):
'''This function print name age and city from an argument provided '''
p... | def addition():
a = 10
b = 45
print(a + b)
addition()
def addition():
a = int(input('Enter a number '))
b = int(input('Please enter another number '))
print(a + b)
addition()
def user_info(name, age, info):
"""This function print name age and city from an argument provided """
print('... |
a=[]
e=a
b=''
while True:
b=input('Enter Number(Use String To Break):')
if b.isalpha():
break
else:
a.append(int(b))
while len(a)>0:
c=a[0]
for x in a:
d=0
if c==x:
d+=1
a.remove(x)
else:
continue
print ("Number:",c)... | a = []
e = a
b = ''
while True:
b = input('Enter Number(Use String To Break):')
if b.isalpha():
break
else:
a.append(int(b))
while len(a) > 0:
c = a[0]
for x in a:
d = 0
if c == x:
d += 1
a.remove(x)
else:
continue
p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
spinMultiplicity = 2
energy = {
'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('energy.out'),
#'CCSD(T)-F12/cc-pVTZ-F12':-382.9466871191517,
}
frequencies = GaussianLog('ts5-freq.log')
rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), pivots=[1,2], top=[2,9,10,11... | spin_multiplicity = 2
energy = {'CCSD(T)-F12/cc-pVTZ-F12': molpro_log('energy.out')}
frequencies = gaussian_log('ts5-freq.log')
rotors = [hindered_rotor(scanLog=scan_log('scan_0.log'), pivots=[1, 2], top=[2, 9, 10, 11], symmetry=3, fit='best')] |
actionHandlers = { }
toolTipHandlers = { }
resultProvidersCached = { }
resultProvidersUncached = { }
# name : string
# getItemGroupsCached: () -> [itemGroup]
# getItemGroupsUncached: () -> [itemGroup]
def registerResultProvider(name, getItemGroupsCached, getItemGroupsUncached):
resultProvidersCached[name] = getItemG... | action_handlers = {}
tool_tip_handlers = {}
result_providers_cached = {}
result_providers_uncached = {}
def register_result_provider(name, getItemGroupsCached, getItemGroupsUncached):
resultProvidersCached[name] = getItemGroupsCached
resultProvidersUncached[name] = getItemGroupsUncached
def register_result_ha... |
"""
https://leetcode.com/problems/merge-two-sorted-lists/
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
@staticmethod
def to_list(node, result=[]):
"""
Recursive method to represent linked lis... | """
https://leetcode.com/problems/merge-two-sorted-lists/
"""
class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
@staticmethod
def to_list(node, result=[]):
"""
Recursive method to represent linked list chain as a python list
:par... |
"""
Link - https://leetcode.com/problems/valid-parentheses/
Problem Description :
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be... | """
Link - https://leetcode.com/problems/valid-parentheses/
Problem Description :
Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be... |
"""
Heap representation of priority queue as described in Section 2.4, pg 313
Python has its own implementation:
https://docs.python.org/3.6/library/heapq.html
https://github.com/python/cpython/blob/master/Lib/heapq.py
"""
class MaxHeap:
def __init__(self, keys=[]):
self._size = 0
self._heap = [N... | """
Heap representation of priority queue as described in Section 2.4, pg 313
Python has its own implementation:
https://docs.python.org/3.6/library/heapq.html
https://github.com/python/cpython/blob/master/Lib/heapq.py
"""
class Maxheap:
def __init__(self, keys=[]):
self._size = 0
self._heap = [N... |
class UserNotifyEvent:
ACCOUNT_CONFIRMATION = "account_confirmation"
ACCOUNT_PASSWORD_RESET = "account_password_reset"
ACCOUNT_CHANGE_EMAIL_REQUEST = "account_change_email_request"
ACCOUNT_CHANGE_EMAIL_CONFIRM = "account_change_email_confirm"
ACCOUNT_DELETE = "account_delete"
ACCOUNT_SET_CUSTOME... | class Usernotifyevent:
account_confirmation = 'account_confirmation'
account_password_reset = 'account_password_reset'
account_change_email_request = 'account_change_email_request'
account_change_email_confirm = 'account_change_email_confirm'
account_delete = 'account_delete'
account_set_custome... |
"""Constants for the kmtronic integration."""
DOMAIN = "kmtronic"
CONF_HOSTNAME = "host"
CONF_USERNAME = "username"
CONF_PASSWORD = "password"
DATA_HUB = "hub"
DATA_HOST = "host"
DATA_COORDINATOR = "coordinator"
MANUFACTURER = "KMtronic"
ATTR_MANUFACTURER = "manufacturer"
ATTR_IDENTIFIERS = "identifiers"
ATTR_NAME ... | """Constants for the kmtronic integration."""
domain = 'kmtronic'
conf_hostname = 'host'
conf_username = 'username'
conf_password = 'password'
data_hub = 'hub'
data_host = 'host'
data_coordinator = 'coordinator'
manufacturer = 'KMtronic'
attr_manufacturer = 'manufacturer'
attr_identifiers = 'identifiers'
attr_name = 'n... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Super:
def method(self):
print('in Super.method')
def delegate(self):
self.action()
class Inheritor(Super):
pass
class Replacer(Super):
def method(self):
print('in Replacer.method')
class Extender(Super):
def method(sel... | class Super:
def method(self):
print('in Super.method')
def delegate(self):
self.action()
class Inheritor(Super):
pass
class Replacer(Super):
def method(self):
print('in Replacer.method')
class Extender(Super):
def method(self):
print('starting Extender.method'... |
class MaxQueue(object):
def __init__(self):
self.queue = []
self.max_queue = []
def enqueue(self, num):
self.queue.append(num)
while self.max_queue and self.max_queue[-1] < num:
self.max_queue.pop()
self.max_queue.append(num)
def dequeue(self):
... | class Maxqueue(object):
def __init__(self):
self.queue = []
self.max_queue = []
def enqueue(self, num):
self.queue.append(num)
while self.max_queue and self.max_queue[-1] < num:
self.max_queue.pop()
self.max_queue.append(num)
def dequeue(self):
... |
def v(arr):
i = n - 2
while (i >= 0) and\
(arr[i] >= arr[i + 1]):
i -= 1
if i >= 0:
j = i + 2
while (j < n) and\
(arr[j] > arr[i]):
j += 1
arr[i], arr[j - 1] = \
arr[j - 1], arr[i]
return [*arr[:i + 1],
... | def v(arr):
i = n - 2
while i >= 0 and arr[i] >= arr[i + 1]:
i -= 1
if i >= 0:
j = i + 2
while j < n and arr[j] > arr[i]:
j += 1
(arr[i], arr[j - 1]) = (arr[j - 1], arr[i])
return [*arr[:i + 1], *reversed(arr[i + 1:n])]
else:
return [0] * n
n =... |
print("-"*17)
print(" Meters to cm/mm ")
print("-"*17)
meters = float(input("Type a value: "))
cm = meters*100
mm = meters*1000
print("{} meters in centimeters is: {} centimeters \nIn millimeters is: {} millimeters".format(meters,cm,mm)) | print('-' * 17)
print(' Meters to cm/mm ')
print('-' * 17)
meters = float(input('Type a value: '))
cm = meters * 100
mm = meters * 1000
print('{} meters in centimeters is: {} centimeters \nIn millimeters is: {} millimeters'.format(meters, cm, mm)) |
# encoding: utf-8
# module Autodesk.Gis.Map.Platform.Utils.Globalization calls itself Globalization
# from Autodesk.Map.Platform.Utils, Version=24.0.30.14, Culture=neutral, PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class EnumTypeConverter(EnumConverter):
""" EnumTypeC... | class Enumtypeconverter(EnumConverter):
""" EnumTypeConverter(type: Type, resourceManager: ResourceManager) """
def convert_from(self, *__args):
""" ConvertFrom(self: EnumTypeConverter, context: ITypeDescriptorContext, culture: CultureInfo, value: object) -> object """
pass
def convert_to(... |
init = int(input("Start index: "))
end = int(input("End index: "))
def sr(integer):
x = -1
while x < integer:
s = None
if x * x == integer:
s = str(x)
break
x += 1
return s
m = init
ps = []
while m <= end:
if sr(m) != None:
ps.... | init = int(input('Start index: '))
end = int(input('End index: '))
def sr(integer):
x = -1
while x < integer:
s = None
if x * x == integer:
s = str(x)
break
x += 1
return s
m = init
ps = []
while m <= end:
if sr(m) != None:
ps.append(m)
m += 1... |
class temporal:
'''This is an abstract class'''
class MensajeOut:
tipo='normal'
mensaje=''
codigo=''
class MensajeTs:
instruccion=''
identificador=''
tipo=''
referencia=''
dimension=''
class Tabla_run:
def __init__(self, basepadre, nombre, atributos=[]):
self.basepadr... | class Temporal:
"""This is an abstract class"""
class Mensajeout:
tipo = 'normal'
mensaje = ''
codigo = ''
class Mensajets:
instruccion = ''
identificador = ''
tipo = ''
referencia = ''
dimension = ''
class Tabla_Run:
def __init__(self, basepadre, nombre, atributos=[]):
... |
# Given a collection of intervals, merge all overlapping intervals.
# Example 1:
# Input: [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
# Example 2:
# Input: [[1,4],[4,5]]
# Output: [[1,5]]
# Explanation: Intervals [1,4] ... | class Solution:
def merge(self, intervals: 'list[list[int]]') -> 'list[list[int]]':
merged = []
intervals.sort()
for interval in intervals:
if merged == [] or interval[0] > merged[-1][1]:
merged.append(interval)
else:
merged[-1][1] = m... |
num = 10
while num:
print(num)
num = num - 1
| num = 10
while num:
print(num)
num = num - 1 |
a = int(input())
b = int(input())
if a < b:
for i in range(a, b + 1):
print(i, end=' ')
else:
for i in range(a, b - 1, -1):
print(i, end=' ')
| a = int(input())
b = int(input())
if a < b:
for i in range(a, b + 1):
print(i, end=' ')
else:
for i in range(a, b - 1, -1):
print(i, end=' ') |
#
# PySNMP MIB module ERI-DNX-APS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ERI-DNX-APS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:51:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, constraints_union, value_size_constraint, value_range_constraint) ... |
#!/usr/bin/python3
""" 5. Raise exception """
def raise_exception():
""" raise_exception """
raise TypeError
| """ 5. Raise exception """
def raise_exception():
""" raise_exception """
raise TypeError |
__all__ = [
'admins', 'aliases', 'alternatives', 'base', 'domains', 'fetches',
'managers', 'users', 'relays', 'tokens', 'api'
]
| __all__ = ['admins', 'aliases', 'alternatives', 'base', 'domains', 'fetches', 'managers', 'users', 'relays', 'tokens', 'api'] |
"""
Return the smallest possible int that is not already in the list
"""
def solution(A):
#print('---')
#print(A)
l = filter(lambda x: x>0, A)
l_st = set(l)
l = list(l_st)
#print (l)
if not l:
return 1
l.sort()
#if 1 not in l:
#return 1
if l[0] > 1:
... | """
Return the smallest possible int that is not already in the list
"""
def solution(A):
l = filter(lambda x: x > 0, A)
l_st = set(l)
l = list(l_st)
if not l:
return 1
l.sort()
if l[0] > 1:
return 1
if len(l) == max(l):
return max(l) + 1
l.reverse()
whil... |
###############################################################################
#
# Copyright (c) 2016 Wi-Fi Alliance
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear... | class Testprogramfeaturemanager:
"""The class that manages the test program feature.
Attributes:
sll (object): The object of SingleLinkedList class.
prog_name (str): The program name.
test_mngr_initr (object): The object of TestManagerInitializer class.
"""
def __init__(self, ... |
__author__ = 'davidl'
def set_status(execution_id, process_id, uut, test, verdict):
pass
def set_results(execution_id, process_id, uut, test, results):
pass
| __author__ = 'davidl'
def set_status(execution_id, process_id, uut, test, verdict):
pass
def set_results(execution_id, process_id, uut, test, results):
pass |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 17 12:50:48 2020
@author: Cliff
"""
#Generator/Filter
#-------------------------------------------------------
#Generator using the filter function
#The gererator prints a list of all numerical value and filters out the
#strings.
my_list = [1,"x",2,"y","3","z",3]
def my... | """
Created on Sat Oct 17 12:50:48 2020
@author: Cliff
"""
my_list = [1, 'x', 2, 'y', '3', 'z', 3]
def my_int(x):
new_int = isinstance(x, int)
return new_int
filter_list = filter(my_int, my_list)
print(list(filter_list))
my_list = [1, 'x', 2, 'y', '3', 'z', 3]
def my_int(x):
return isinstance(x, int)
fil... |
# Given two strings, check if one is a permutation of the other
def check_permutation(str1, str2):
freq1 = {}
freq2 = {}
for char in str1:
if freq1.get(char):
freq1[char] += 1
else:
freq1[char] = 1
for char in str2:
if freq2.get(char):
freq2[char] += 1
else:
freq2[char... | def check_permutation(str1, str2):
freq1 = {}
freq2 = {}
for char in str1:
if freq1.get(char):
freq1[char] += 1
else:
freq1[char] = 1
for char in str2:
if freq2.get(char):
freq2[char] += 1
else:
freq2[char] = 1
for (char... |
__example_payload__ = "SELECT FIELD FROM information_schema.tables"
__type__ = "changing specific payload characters into their Unicode equivalent"
def tamper(payload, **kwargs):
unicode_changes = {
'1': 'B9', '2': 'B2', '3': 'B3', 'D': 'D0',
'T': 'DE', 'Y': 'DD', 'a': 'AA', 'e': 'F0',
'o'... | __example_payload__ = 'SELECT FIELD FROM information_schema.tables'
__type__ = 'changing specific payload characters into their Unicode equivalent'
def tamper(payload, **kwargs):
unicode_changes = {'1': 'B9', '2': 'B2', '3': 'B3', 'D': 'D0', 'T': 'DE', 'Y': 'DD', 'a': 'AA', 'e': 'F0', 'o': 'BA', 't': 'FE', 'y': 'F... |
def calcAQI(cp, ih, il, bph, bpl):
a = (ih - il)
b = (bph - bpl)
c = (cp - bpl)
return int((a /b) * c + il)
def aqi_from_pm(pm):
if (pm > 350.5):
return calcAQI(pm, 500, 401, 500, 350.5)
elif (pm > 250.5):
return calcAQI(pm, 400, 301, 350.4, 250.5)
elif (pm > 150.5):
... | def calc_aqi(cp, ih, il, bph, bpl):
a = ih - il
b = bph - bpl
c = cp - bpl
return int(a / b * c + il)
def aqi_from_pm(pm):
if pm > 350.5:
return calc_aqi(pm, 500, 401, 500, 350.5)
elif pm > 250.5:
return calc_aqi(pm, 400, 301, 350.4, 250.5)
elif pm > 150.5:
return ca... |
def swap(a: int, b: int, arr: list):
"""swap elements of array
Args:\n
a (int): index 1
b (int): index 2
arr (list): list of elements
"""
if a != b:
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def partition(elements: list, start: int, end: int) -> int:
... | def swap(a: int, b: int, arr: list):
"""swap elements of array
Args:
a (int): index 1
b (int): index 2
arr (list): list of elements
"""
if a != b:
temp = arr[a]
arr[a] = arr[b]
arr[b] = temp
def partition(elements: list, start: int, end: int) -> int:
... |
class VocabDictionary:
def __init__(self, unk="<unk>", pad="<pad>"):
self.dictionary = {}
self.tokens = []
self.unk = unk
self.pad = pad
self.pad_index = self.add_symbol(self.pad)
self.unk_index = self.add_symbol(self.unk)
def __len__(self):
return len(se... | class Vocabdictionary:
def __init__(self, unk='<unk>', pad='<pad>'):
self.dictionary = {}
self.tokens = []
self.unk = unk
self.pad = pad
self.pad_index = self.add_symbol(self.pad)
self.unk_index = self.add_symbol(self.unk)
def __len__(self):
return len(s... |
'''
James Halladay
Copyright (c) 2021
Multi-Layer Grid (MLG) Neural Network
An improvement on the Feed-Forward Neural Network Multi-Layer Perceptron (MLP) model.
The MLP model is a simple feed-forward neural network that is trained to classify
the input data into a set of categories.
The MLG model... | """
James Halladay
Copyright (c) 2021
Multi-Layer Grid (MLG) Neural Network
An improvement on the Feed-Forward Neural Network Multi-Layer Perceptron (MLP) model.
The MLP model is a simple feed-forward neural network that is trained to classify
the input data into a set of categories.
The MLG model... |
##
## ROOT Module
##
## This is a sample dynamic module for the system.
##
def do(n,b):
# Declare Keyword (important)
keyword = "root"
# Check if Keyword in Body (important)
if keyword in b:
return "Ok"
else:
# Returns a False if Keyword not in Body (important)
return False... | def do(n, b):
keyword = 'root'
if keyword in b:
return 'Ok'
else:
return False |
N = int(input())
arr = []
for _ in range(N):
arr.append(int(input()))
arr.sort()
for attr in arr:
print(attr) | n = int(input())
arr = []
for _ in range(N):
arr.append(int(input()))
arr.sort()
for attr in arr:
print(attr) |
# File: microsoftscom_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 ... | msscom_config_server_url = 'server_url'
msscom_config_username = 'username'
msscom_config_password = 'password'
msscom_config_verify_ssl = 'verify_server_cert'
msscom_server_url = '{url}/wsman'
msscom_connecting_endpoint_msg = 'Connecting to endpoint'
msscom_err_server_connection = 'Connection failed'
msscom_transport_... |
compra = []
#error linia 30
while True:
print("0. Salir")
print("1. Ver lista de la compra")
print("2. Agregar producto a la lista")
print("3. Modificar producto de la lista")
print("4. Quitar producto de la lista")
try:
elegir_opcion = input()
elegir_opcion= int(elegir_opcion)
... | compra = []
while True:
print('0. Salir')
print('1. Ver lista de la compra')
print('2. Agregar producto a la lista')
print('3. Modificar producto de la lista')
print('4. Quitar producto de la lista')
try:
elegir_opcion = input()
elegir_opcion = int(elegir_opcion)
except Value... |
''' Master class for payments '''
class BasePayments(object):
''' Base class for payments and interfacing with external subscription systems '''
def __init__(self, user=None, config=None, rdb=None):
''' Initialize the Payments Class '''
self.user = user
self.config = config
sel... | """ Master class for payments """
class Basepayments(object):
""" Base class for payments and interfacing with external subscription systems """
def __init__(self, user=None, config=None, rdb=None):
""" Initialize the Payments Class """
self.user = user
self.config = config
sel... |
class Solution(object):
def firstMissingPositive(self, nums):
i = 0
while i < len(nums):
if 0 < nums[i] <= len(nums) and nums[nums[i] - 1] != nums[i]:
nums[nums[i] - 1], nums[i] = nums[i], nums[nums[i] - 1]
else:
i += 1
for i in range(0, len(nums)):
if nums[i] != i + 1:
... | class Solution(object):
def first_missing_positive(self, nums):
i = 0
while i < len(nums):
if 0 < nums[i] <= len(nums) and nums[nums[i] - 1] != nums[i]:
(nums[nums[i] - 1], nums[i]) = (nums[i], nums[nums[i] - 1])
else:
i += 1
for i in ... |
class BYUJWTError(Exception):
"""Error handling BYU JWT"""
class JWTVerifyError(BYUJWTError):
"""Error Verifing JWT"""
class JWTHandlerError(BYUJWTError):
"""Error while handling JWT"""
| class Byujwterror(Exception):
"""Error handling BYU JWT"""
class Jwtverifyerror(BYUJWTError):
"""Error Verifing JWT"""
class Jwthandlererror(BYUJWTError):
"""Error while handling JWT""" |
def print_hi(name):
print(f'hi, {name}')
if __name__ =='__main__':
print_hi('PyCharm')
| def print_hi(name):
print(f'hi, {name}')
if __name__ == '__main__':
print_hi('PyCharm') |
#!/usr/bin/python3
"""Create Terraform Modules."""
def create_vpc(region, pbsubnet, pvsubnet, source):
"""Create Terraform Module for AWS VPC."""
tf_module_vpc = {
"source": "%s/m-aws-vpc" % source,
"awsRegion": region,
"public_subnet_cidr": pbsubnet,
"private_subnet_... | """Create Terraform Modules."""
def create_vpc(region, pbsubnet, pvsubnet, source):
"""Create Terraform Module for AWS VPC."""
tf_module_vpc = {'source': '%s/m-aws-vpc' % source, 'awsRegion': region, 'public_subnet_cidr': pbsubnet, 'private_subnet_cidr': pvsubnet}
return tf_module_vpc
def create_vm_aws(vp... |
# Title : Print square of number, limit specified by the user.
# Author : Kiran raj R.
# Date : 24:10:2020
userInput = input(
"Enter the limit till you need to print the sqaure of numbers :")
square_list = []
for i in range(1, int(userInput)+1):
square_list.append(i**2)
print(square_list)
| user_input = input('Enter the limit till you need to print the sqaure of numbers :')
square_list = []
for i in range(1, int(userInput) + 1):
square_list.append(i ** 2)
print(square_list) |
# -----------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# -----------------------------------------------------------------------------
""... | """Commands related to Service Fabric Mesh secret value commands and operations"""
def get_secret_value(client, secret_resource_name, secret_value_resource_name, show_value=False):
"""Retrieve the value of a specified version of a secret resource"""
secret_value = None
if show_value:
secret_value =... |
#!/usr/bin/python
def outlierCleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple ... | def outlier_cleaner(predictions, ages, net_worths):
"""
Clean away the 10% of points that have the largest
residual errors (difference between the prediction
and the actual net worth).
Return a list of tuples named cleaned_data where
each tuple is of the form (age, net_wort... |
class Solution:
no_remove = True
def validPalindrome(self, s: str) -> bool:
lp = 0
rp = len(s)-1
no_remove = True
while lp < rp:
if s[lp] == s[rp]:
lp += 1
rp -= 1
elif self.no_remove:
self.no_remove = False... | class Solution:
no_remove = True
def valid_palindrome(self, s: str) -> bool:
lp = 0
rp = len(s) - 1
no_remove = True
while lp < rp:
if s[lp] == s[rp]:
lp += 1
rp -= 1
elif self.no_remove:
self.no_remove = Fa... |
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
OneDec = False
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
if OneDec:
return False
OneDec = True
if i > 1 and nums[i - 2] > nums[i] and i <... | class Solution:
def check_possibility(self, nums: List[int]) -> bool:
one_dec = False
for i in range(1, len(nums)):
if nums[i] < nums[i - 1]:
if OneDec:
return False
one_dec = True
if i > 1 and nums[i - 2] > nums[i] and... |
text = input()
save_odd = []
save_even = []
receve = text.split("|")
while True:
command = input().split()
if command[0] == "Done":
final = "".join(map(str, receve))
print(f"You crafted {final}!")
break
if command[0] == "Move" and command[1] == "Left":
position = int(comm... | text = input()
save_odd = []
save_even = []
receve = text.split('|')
while True:
command = input().split()
if command[0] == 'Done':
final = ''.join(map(str, receve))
print(f'You crafted {final}!')
break
if command[0] == 'Move' and command[1] == 'Left':
position = int(command[... |
while True:
print("Options:")
print("Enter 'add' to add two numbers")
print("Enter 'subtract' to subtract two numbers")
print("Enter 'multiply' to multiply two numbers")
print("Enter 'divide' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input... | while True:
print('Options:')
print("Enter 'add' to add two numbers")
print("Enter 'subtract' to subtract two numbers")
print("Enter 'multiply' to multiply two numbers")
print("Enter 'divide' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(': ')
if use... |
# You are given a list containing letters of a name. Print them out
# as a string with these chars separated by hyphens and with an
# exclamation point in the end. Do so using arguments of the
# print() function!
# So, if the letters in the list name are ['K', 'A', 'T', 'E'], your
# program should print the string 'K-... | name = ['M', 'A', 'R', 'C', 'O']
print(*name, sep='-', end='!') |
cite = clipboard.get_selection().encode('ascii', 'ignore')
keyboard.send_key("<delete>")
try:
cite = "(" + cite.replace(" (", ", ")
cite = re.sub("[., ]*$", ".", cite)
keyboard.send_keys(cite)
except Exception as ex:
val = type(ex).__name__ + " " + ex.args[0]
keyboard.send_keys(val) | cite = clipboard.get_selection().encode('ascii', 'ignore')
keyboard.send_key('<delete>')
try:
cite = '(' + cite.replace(' (', ', ')
cite = re.sub('[., ]*$', '.', cite)
keyboard.send_keys(cite)
except Exception as ex:
val = type(ex).__name__ + ' ' + ex.args[0]
keyboard.send_keys(val) |
class Solution:
def minIncrementForUnique(self, A: List[int]) -> int:
A.sort()
sum_ = sum(A)
for k in range(1, len(A)):
if A[k] <= A[k-1]:
A[k] = A[k-1] + 1
return sum(A) - sum_ | class Solution:
def min_increment_for_unique(self, A: List[int]) -> int:
A.sort()
sum_ = sum(A)
for k in range(1, len(A)):
if A[k] <= A[k - 1]:
A[k] = A[k - 1] + 1
return sum(A) - sum_ |
#The classic
print("Hello World")
#Print more things
print("Hello New World") | print('Hello World')
print('Hello New World') |
with open('input', 'r') as fh:
data = fh.readlines()
for i, line in enumerate(data):
data[i] = list(line.rstrip())
bits = list(zip(*data))
gamma_bits = list()
eps_bits = list()
for bit in bits:
if bit.count('1') > bit.count('0'):
gamma_bits.append('1')
eps_bits.append('0')
else:
... | with open('input', 'r') as fh:
data = fh.readlines()
for (i, line) in enumerate(data):
data[i] = list(line.rstrip())
bits = list(zip(*data))
gamma_bits = list()
eps_bits = list()
for bit in bits:
if bit.count('1') > bit.count('0'):
gamma_bits.append('1')
eps_bits.append('0')
else:
... |
fname= 'romeo.txt'
fh = open(fname)
slist = []
for line in fh:
lsl = line.split()
for str in lsl:
if str not in slist:
slist.append(str)
slist.sort()
print(slist)
| fname = 'romeo.txt'
fh = open(fname)
slist = []
for line in fh:
lsl = line.split()
for str in lsl:
if str not in slist:
slist.append(str)
slist.sort()
print(slist) |
class Issues:
def __init__(self):
self.issue_types = {}
self.issues = {}
def add_issue_type(self, issue_type_id, issue_type_info):
self.issue_types[issue_type_id] = issue_type_info
def add_issue_obj(self, issue_type_id, obj_type, obj_id):
if issue_type_id not in self.issue_... | class Issues:
def __init__(self):
self.issue_types = {}
self.issues = {}
def add_issue_type(self, issue_type_id, issue_type_info):
self.issue_types[issue_type_id] = issue_type_info
def add_issue_obj(self, issue_type_id, obj_type, obj_id):
if issue_type_id not in self.issue... |
# -*- coding: utf-8 -*-
def get_client_ip(request):
"""
Returns client ip from request.
Source: http://stackoverflow.com/a/4581997/821594
"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.... | def get_client_ip(request):
"""
Returns client ip from request.
Source: http://stackoverflow.com/a/4581997/821594
"""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
... |
def readHeaderFromFile(filename):
#datafile = open(filename, "r")
#headers=[]
#for line in datafile:
# entry = line.strip().split(";")
# #print(entry);
# if entry[0] == "Anz_Kunden":
# headers = entry
# return headers;
return ["Anz_Kunden", "Gesamtkosten"]
def... | def read_header_from_file(filename):
return ['Anz_Kunden', 'Gesamtkosten']
def read_datasets_from_file(filename):
dataset = []
datafile = open(filename, 'r')
for line in datafile:
entry = line.strip().split(';')
result = []
if entry[0] == 'Anz_Kunden':
continue
... |
"""DFS.py
Algorithms for depth first search in Python.
We need to search iteratively rather than recursively in
order to avoid Python's low recursion limit.
D. Eppstein, July 2004.
"""
# Types of edges in DFS traversal.
# The numerical values are used in DepthFirstSearcher, change with care.
forward = 1 # traver... | """DFS.py
Algorithms for depth first search in Python.
We need to search iteratively rather than recursively in
order to avoid Python's low recursion limit.
D. Eppstein, July 2004.
"""
forward = 1
reverse = -1
nontree = 0
whole_graph = object()
def search(G, initial_vertex=whole_graph):
"""
Generate sequence... |
class Contract(object):
def __init__(self, ticker_index, ticker, exchange, name, size, price_tick):
self.ticker_index = ticker_index
self.ticker = ticker
self.exchange = exchange
self.name = name
self.size = size
self.price_tick = price_tick
class ContractTable(obj... | class Contract(object):
def __init__(self, ticker_index, ticker, exchange, name, size, price_tick):
self.ticker_index = ticker_index
self.ticker = ticker
self.exchange = exchange
self.name = name
self.size = size
self.price_tick = price_tick
class Contracttable(obje... |
# Default Settings File
APP_SESSION_KEY = 'fitbit2influx-test-session-key'
# Fitbit Web Hosts
FITBIT_WEB_HOST = 'www.fitbit.com'
FITBIT_API_HOST = 'api.fitbit.com'
# Fitbit Application Information
# CLIENT_ID = None
# CLIENT_SECRET = None
CALLBACK_URL = '/authorize'
# Token Validity in ms (default: 1 hr per Fitbit)
... | app_session_key = 'fitbit2influx-test-session-key'
fitbit_web_host = 'www.fitbit.com'
fitbit_api_host = 'api.fitbit.com'
callback_url = '/authorize'
token_validity = 604800
shelve_filename = 'instance/shelf.db' |
def count_sheep(n):
sheep=""
for i in range(1, n+1):
sheep+=str(i) + " sheep..."
return sheep
| def count_sheep(n):
sheep = ''
for i in range(1, n + 1):
sheep += str(i) + ' sheep...'
return sheep |
# by Kami Bigdely
# Split temporary variable
patty_weight = 70 # [gr]
pickle_weight = 20 # [gr]
tomatoes_weight = 25 # [gr]
lettuce_weight = 15 # [gr]
buns_weight = 95 # [gr]
sandwich_weight = (2 * patty_weight + 4 * pickle_weight + 3 * tomatoes_weight + 2 * lettuce_weight
+ 2 * buns_weight)
print("NY ... | patty_weight = 70
pickle_weight = 20
tomatoes_weight = 25
lettuce_weight = 15
buns_weight = 95
sandwich_weight = 2 * patty_weight + 4 * pickle_weight + 3 * tomatoes_weight + 2 * lettuce_weight + 2 * buns_weight
print('NY Burger Weight', sandwich_weight)
kimchi_weight = 30
mayo_weight = 5
golden_fried_onion = 20
sandwic... |
class PDB:
def __init__(self, in_pdb, chain="L", resname="LIG", resnum=" 1"):
"""
Class to read and process PDB files.
:param in_pdb: pdb file path
:type in_pdb: str
:param chain: label of the chain of interest
:type chain: str
:param resname: label of the r... | class Pdb:
def __init__(self, in_pdb, chain='L', resname='LIG', resnum=' 1'):
"""
Class to read and process PDB files.
:param in_pdb: pdb file path
:type in_pdb: str
:param chain: label of the chain of interest
:type chain: str
:param resname: label of the ... |
_base_ = ['./twins_pcpvt-s_fpn_fpnhead_8x4_512x512_80k_ade20k.py']
checkpoint = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/twins/pcpvt_base_20220308-0621964c.pth' # noqa
model = dict(
backbone=dict(
init_cfg=dict(type='Pretrained', checkpoint=checkpoint),
depths=[3, 4, 18, 3]), ... | _base_ = ['./twins_pcpvt-s_fpn_fpnhead_8x4_512x512_80k_ade20k.py']
checkpoint = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/twins/pcpvt_base_20220308-0621964c.pth'
model = dict(backbone=dict(init_cfg=dict(type='Pretrained', checkpoint=checkpoint), depths=[3, 4, 18, 3])) |
"""
Following are the topics we will cover today.
1) Recursive Function
2) Built-in Functions: min, max, count, len, split, zip, types, sum, sorted
"""
# #############################################################################
# 1) Recursive Function
# ###########################################################... | """
Following are the topics we will cover today.
1) Recursive Function
2) Built-in Functions: min, max, count, len, split, zip, types, sum, sorted
"""
def prime(limit):
for no in range(1, limit + 1):
flag = True
for divider in range(2, no):
if no % divider == 0:
flag =... |
serverko.trace('INFO: layout.py')
def layout_script_userJoined(userID) :
serverko.trace("JS:layout_script_userJoined " + userID)
#layout.send(userID)
# define layout area
class LayoutArea:
type = 'dummy'
id = 'dummy'
x = -111111
y = -111111
w = -111111
h = -111111
layout = 'hor'
state = 'dummy'
owner... | serverko.trace('INFO: layout.py')
def layout_script_user_joined(userID):
serverko.trace('JS:layout_script_userJoined ' + userID)
class Layoutarea:
type = 'dummy'
id = 'dummy'
x = -111111
y = -111111
w = -111111
h = -111111
layout = 'hor'
state = 'dummy'
owner = 'dummy'
opac... |
'''
Exercise 2:
1. Write a script that takes a sentence from the user without any punctuation and prints
the sentence without any white spaces. Note a white space is represented by ' ', and
an empty string is represented by ''.
>>> enter a sentence: this is a SHORT sentence
thisisaSHORTsentence
2. Same as above except ... | """
Exercise 2:
1. Write a script that takes a sentence from the user without any punctuation and prints
the sentence without any white spaces. Note a white space is represented by ' ', and
an empty string is represented by ''.
>>> enter a sentence: this is a SHORT sentence
thisisaSHORTsentence
2. Same as above except ... |
"""
The Collatz Conjecture states that for any natural number n, if n is even, divide it by 2.
If n is odd, multiply it by 3 and add 1. If you repeat the process continously for n, n will eventually reach 1.
For example, if n = 20, the resulting sequence will be:
[20, 10, 5, 16, 8, 4, 2, 1]
Write a program that will... | """
The Collatz Conjecture states that for any natural number n, if n is even, divide it by 2.
If n is odd, multiply it by 3 and add 1. If you repeat the process continously for n, n will eventually reach 1.
For example, if n = 20, the resulting sequence will be:
[20, 10, 5, 16, 8, 4, 2, 1]
Write a program that will... |
print("Welcome to Band Name Generator")
yourName = input("What's your name?\n")
cityName = input("What's the name of the city you grew up in?\n")
carCompany = input("What's the name of your car company? \n")
birthMonth = input("What's your birth month? \n")
nameGenerator = cityName + yourName[4] + carCompany + birthMon... | print('Welcome to Band Name Generator')
your_name = input("What's your name?\n")
city_name = input("What's the name of the city you grew up in?\n")
car_company = input("What's the name of your car company? \n")
birth_month = input("What's your birth month? \n")
name_generator = cityName + yourName[4] + carCompany + bir... |
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
"""
Base class for CLI command. All CLI commands are modules in
scarab.commands.* packag and should implement scarab.commands.Base
interface: register and run methods.
"""
class Base(object):
"""A base command."""
def __init__(self):
pass
def... | """
Base class for CLI command. All CLI commands are modules in
scarab.commands.* packag and should implement scarab.commands.Base
interface: register and run methods.
"""
class Base(object):
"""A base command."""
def __init__(self):
pass
def register(self, subparsers):
"""
Create... |
"""
Polity Module.
"""
class Polity(object):
"""
Polity class.
Args:
communities (list[Community]): A list of communities which belong to
the polity.
Attributes:
communities (list[Community]): A list of communities which belong to
the polity.
"""
def _... | """
Polity Module.
"""
class Polity(object):
"""
Polity class.
Args:
communities (list[Community]): A list of communities which belong to
the polity.
Attributes:
communities (list[Community]): A list of communities which belong to
the polity.
"""
def _... |
with open("col1.txt") as f1, open("col2.txt") as f2:
ret = ['{}\t{}'.format(p, c) for p, c in zip(f1.read().split('\n'), f2.read().split('\n'))]
with open("col3.txt", 'w') as f3:
f3.write('\n'.join(ret))
| with open('col1.txt') as f1, open('col2.txt') as f2:
ret = ['{}\t{}'.format(p, c) for (p, c) in zip(f1.read().split('\n'), f2.read().split('\n'))]
with open('col3.txt', 'w') as f3:
f3.write('\n'.join(ret)) |
def move(i, j):
if i == 20 or j == 20:
return 1
else:
return move(i+1, j) + move(i, j+1)
if __name__ == "__main__":
print(move(0, 0))
| def move(i, j):
if i == 20 or j == 20:
return 1
else:
return move(i + 1, j) + move(i, j + 1)
if __name__ == '__main__':
print(move(0, 0)) |
###
#
# @package py.fileio
### Function to read file.
#
# @function read
# @param filename
def read(filename, encoding='utf-8'):
BUFFER = open(filename, 'rt', encoding=encoding)
text = BUFFER.read()
BUFFER.close()
# force LF line endings (\n)
text.replace('\r\n', '\n').replace('\r', '\n')
return text
### Fu... | def read(filename, encoding='utf-8'):
buffer = open(filename, 'rt', encoding=encoding)
text = BUFFER.read()
BUFFER.close()
text.replace('\r\n', '\n').replace('\r', '\n')
return text
def write(filename, text, encoding='utf-8'):
text = bytes(text, encoding)
text.replace(b'\r\n', b'\n').replac... |
class pyarmstrongnum():
def __init__(self):
return None
def armstrong(self,num):
num = [int(i) for i in str(num)]
answer = [num[x]**len(num) for x in range(len(num))]
num = int(''.join(str(y) for y in num))
if sum(answer) ==num:
return str(num) + " is ... | class Pyarmstrongnum:
def __init__(self):
return None
def armstrong(self, num):
num = [int(i) for i in str(num)]
answer = [num[x] ** len(num) for x in range(len(num))]
num = int(''.join((str(y) for y in num)))
if sum(answer) == num:
return str(num) + ' is an... |
##########################################################
# Contains variables shared across owping tool components
##########################################################
#Version of the latency schema used
LATENCY_SCHEMA_VERSION = 1
# Default time between packets (in seconds) if not specified by user
DEFAULT_P... | latency_schema_version = 1
default_packet_interval = 0.1
default_packet_count = 100
default_packet_timeout = 0
default_fudge_factor = 10
default_client_sleep = 1
default_early_server_stop = 2
default_owampd_port = 861
default_owampd_ctrl_ports = list(range(5601, 5900))
default_owampd_data_ports = list(range(8760, 9960)... |
__author__ = "Prikly Grayp"
__license__ = "MIT"
__version__ = "1.0.0"
__email__ = "priklygrayp@gmail.com"
__status__ = "Development"
students = []
class Student():
def get_students_titlecase(self):
students_titlecase = []
for student in students:
students_titlecase.append(student['name'].title())
return s... | __author__ = 'Prikly Grayp'
__license__ = 'MIT'
__version__ = '1.0.0'
__email__ = 'priklygrayp@gmail.com'
__status__ = 'Development'
students = []
class Student:
def get_students_titlecase(self):
students_titlecase = []
for student in students:
students_titlecase.append(student['name']... |
'''
Aggregation Helper Functions
'''
def aggregation_insol(normalized_energy, insolation, frequency='D'):
'''
Insolation weighted aggregation
Parameters
----------
normalized_energy: Pandas series (numeric)
Normalized energy time series
insolation: Pandas series (numeric)
Time ... | """
Aggregation Helper Functions
"""
def aggregation_insol(normalized_energy, insolation, frequency='D'):
"""
Insolation weighted aggregation
Parameters
----------
normalized_energy: Pandas series (numeric)
Normalized energy time series
insolation: Pandas series (numeric)
Time ... |
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( seq ) :
n = len ( seq )
if ( n >= 9 ) :
return "-1"
result = [ None ] * ( n + 1 )
count = 1... | def f_gold(seq):
n = len(seq)
if n >= 9:
return '-1'
result = [None] * (n + 1)
count = 1
for i in range(n + 1):
if i == n or seq[i] == 'I':
for j in range(i - 1, -2, -1):
result[j + 1] = int('0' + str(count))
count += 1
if j... |
class TemplateNotFoundError(FileNotFoundError):
def __init__(self, template_id, *args, **kwargs):
super().__init__(*args, **kwargs)
self.template_id = template_id
self.detail = f'Template not found with Template ID - "{template_id}"'
def __str__(self):
return self.detail
| class Templatenotfounderror(FileNotFoundError):
def __init__(self, template_id, *args, **kwargs):
super().__init__(*args, **kwargs)
self.template_id = template_id
self.detail = f'Template not found with Template ID - "{template_id}"'
def __str__(self):
return self.detail |
DEFAULT_DATA_ROOT = "/data"
# Default perception schema version
DEFAULT_PERCEPTION_VERSION = "0.0.1"
# Default Timing text for codetiming.Timer decorator
TIMING_TEXT = "[{name}] elapsed time: {:0.4f} seconds."
# Click CLI context settings
CONTEXT_SETTINGS = {
"help_option_names": ["-h", "--help"],
"show_def... | default_data_root = '/data'
default_perception_version = '0.0.1'
timing_text = '[{name}] elapsed time: {:0.4f} seconds.'
context_settings = {'help_option_names': ['-h', '--help'], 'show_default': True, 'ignore_unknown_options': True, 'allow_extra_args': True} |
"""Another example module, this time inside of a subpackage."""
def concat_2(a):
"""Concatenate the string "2" to to the end of an existing string object.
Parameters
----------
a : string
The string to be concatenated to.
Returns
-------
a+"2" : string
The resulting strin... | """Another example module, this time inside of a subpackage."""
def concat_2(a):
"""Concatenate the string "2" to to the end of an existing string object.
Parameters
----------
a : string
The string to be concatenated to.
Returns
-------
a+"2" : string
The resulting string... |
n = input()
n = int(n)
arr = list(map(int, input().split()))
arr.sort()
if(arr[n-1] < 0) :
# 0 0
print("{} {}".format(arr[n-1], 1))
elif(arr[n-1] is 0) :
count = 0
for i in range(n-1, -1, -1) :
if(arr[i] is 0) :
count = count + 1
# 0 count
print("0 {}".format(count))
else :
... | n = input()
n = int(n)
arr = list(map(int, input().split()))
arr.sort()
if arr[n - 1] < 0:
print('{} {}'.format(arr[n - 1], 1))
elif arr[n - 1] is 0:
count = 0
for i in range(n - 1, -1, -1):
if arr[i] is 0:
count = count + 1
print('0 {}'.format(count))
else:
count = 0
max_sum... |
load("@cldr_json_data//:index.bzl", _ALL_CLDR_LOCALES = "LOCALES")
# List of locales the tool can generate files for.
LOCALES = _ALL_CLDR_LOCALES
# Labels resolving to the individual `generate-locale-tool` entry-points
GENERATE_LOCALES_TOOL_BIN = "//packages/common/locales/generate-locales-tool/bin"
GET_BASE_CURRENCI... | load('@cldr_json_data//:index.bzl', _ALL_CLDR_LOCALES='LOCALES')
locales = _ALL_CLDR_LOCALES
generate_locales_tool_bin = '//packages/common/locales/generate-locales-tool/bin'
get_base_currencies_file_bin = '%s:get-base-currencies-file' % GENERATE_LOCALES_TOOL_BIN
get_base_locale_file_bin = '%s:get-base-locale-file' % G... |
n = int(input())
n1 = int(input())
def fact(a, b):
f1 = a
f2 = b
for i in range(a - 1, 0, -1):
f1 *= i
for j in range(b - 1, 0, -1):
f2 *= j
result = f1 / f2
return f'{result:.2f}'
print(fact(n, n1))
| n = int(input())
n1 = int(input())
def fact(a, b):
f1 = a
f2 = b
for i in range(a - 1, 0, -1):
f1 *= i
for j in range(b - 1, 0, -1):
f2 *= j
result = f1 / f2
return f'{result:.2f}'
print(fact(n, n1)) |
# Perfect numbers are numbers with the property such that the sum of all their factors equals themselves.
perfectNumbers = []
factors = []
for n in range(1, 10000, 1):
count = 1
for w in range(0, n):
if n%count == 0:
factors.append(count)
if count < n:
count+= 1
sum ... | perfect_numbers = []
factors = []
for n in range(1, 10000, 1):
count = 1
for w in range(0, n):
if n % count == 0:
factors.append(count)
if count < n:
count += 1
sum = 0
for item in factors[:-1]:
sum += item
factors = []
if sum == n:
perfect... |
ENTRY_POINT = 'sort_even'
FIX = """
Remove sort helper function
"""
#[PROMPT]
def sort_even(l: list):
"""This function takes a list l and returns a list l' such that
l' is identical to l in the odd indicies, while its values at the even indicies are equal
to the values of the even indicies of l, but sor... | entry_point = 'sort_even'
fix = '\nRemove sort helper function\n'
def sort_even(l: list):
"""This function takes a list l and returns a list l' such that
l' is identical to l in the odd indicies, while its values at the even indicies are equal
to the values of the even indicies of l, but sorted.
>>> so... |
# -*- coding: utf-8 -*-
N = int(input())
dic = { 'C': 0, 'R': 0, 'S': 0 }
for i in range(N):
amount, animal = input().split()
dic[animal] += int(amount)
total = dic['C'] + dic['R'] + dic['S']
print("Total: %d cobaias" % total)
print("Total de coelhos: %d" % dic['C'])
print("Total de ratos: %d" % dic['R'])
pri... | n = int(input())
dic = {'C': 0, 'R': 0, 'S': 0}
for i in range(N):
(amount, animal) = input().split()
dic[animal] += int(amount)
total = dic['C'] + dic['R'] + dic['S']
print('Total: %d cobaias' % total)
print('Total de coelhos: %d' % dic['C'])
print('Total de ratos: %d' % dic['R'])
print('Total de sapos: %d' % ... |
class Config(object):
def __init__(self):
# model params
self.model = "AR_mem"
self.nsteps = 3 # equivalent to x_len
self.msteps = 5
self.attention_size = 32
self.l2_lambda = 1e-3
self.ar_lambda = 1e-1
self.ar_g = 1
# data params
... | class Config(object):
def __init__(self):
self.model = 'AR_mem'
self.nsteps = 3
self.msteps = 5
self.attention_size = 32
self.l2_lambda = 0.001
self.ar_lambda = 0.1
self.ar_g = 1
self.data_path = './data/MS_scaled_data.csv'
self.nfeatures = 6
... |
# API identifiers
# https://github.com/aeternity/protocol/blob/14db60b7db4d51618ebad539aaf6a0b40b72e633/epoch/api/api_encoding.md#encoding-scheme-for-api-identifiers-and-byte-arrays
# base58
ACCOUNT_ID = "ak" # base58 Account pubkey
BLOCK_PROOF_OF_FRAUD_HASH = "bf" # base58 Block Proof of Fraud hash
BLOCK_STATE_HASH... | account_id = 'ak'
block_proof_of_fraud_hash = 'bf'
block_state_hash = 'bs'
block_transaction_hash = 'bx'
channel = 'ch'
commitment = 'cm'
contract_id = 'ct'
key_block_hash = 'kh'
micro_block_hash = 'mh'
name = 'nm'
oracle_id = 'ok'
oracle_query_id = 'oq'
peer_id = 'pp'
signature = 'sg'
transaction_hash = 'th'
contract_... |
header = """Executable = /usr/bin/matlab
Universe = vanilla
RequestMemory = 6000
RequestCPUs = 16
getenv = True
logdir = logs
output = $(logdir)/$(Cluster)-$(Process).o
error = $(logdir)/$(Cluster)-$(Process).e
log = $(logdir)/$(Cluster)-$(Process).log
args = -nodisplay -singleCompThread
"""
for subj in [1, 2, 3]:
... | header = 'Executable = /usr/bin/matlab\nUniverse = vanilla\nRequestMemory = 6000\nRequestCPUs = 16\ngetenv = True\nlogdir = logs\noutput = $(logdir)/$(Cluster)-$(Process).o\nerror = $(logdir)/$(Cluster)-$(Process).e\nlog = $(logdir)/$(Cluster)-$(Process).log\n\nargs = -nodisplay -singleCompThread\n\n'
for subj in [1, 2... |
"""Utilities for reading/writing our data."""
def SavePairs(pairs, filename):
with open(filename,'w') as f:
for pair in pairs:
f.write("{}\t{}\n".format(pair[0],pair[1]))
return
def ReadPairs(filename):
pairs = set()
with open(filename,'r') as f:
for line in f.readlines():
... | """Utilities for reading/writing our data."""
def save_pairs(pairs, filename):
with open(filename, 'w') as f:
for pair in pairs:
f.write('{}\t{}\n'.format(pair[0], pair[1]))
return
def read_pairs(filename):
pairs = set()
with open(filename, 'r') as f:
for line in f.readline... |
p_paths = {"videodownloader": "C:\\Program Files\\4KDownload\\4kvideodownloader\\4kvideodownloader.exe",
"androidstudio": "C:\\Program Files\\Android\\Android Studio\\bin\\studio64.exe" ,
"anydesk" : "C:\\Program Files (x86)\\AnyDesk\\AnyDesk.exe" ,
"alexa" : "C:\\Program Files\\WindowsApps\\57540AMZNMobileLLC.Am... | p_paths = {'videodownloader': 'C:\\Program Files\\4KDownload\\4kvideodownloader\\4kvideodownloader.exe', 'androidstudio': 'C:\\Program Files\\Android\\Android Studio\\bin\\studio64.exe', 'anydesk': 'C:\\Program Files (x86)\\AnyDesk\\AnyDesk.exe', 'alexa': 'C:\\Program Files\\WindowsApps\\57540AMZNMobileLLC.AmazonAlexa_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.