content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# Runtime: 32... | class Solution(object):
def delete_duplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
cur = head
while cur.next is not None:
if cur.next.val == cur.val:
ptr = cur.next.nex... |
print ("hola mundo/jhon")
a=45
b=5
print("Suma:",a+b)
print("Resta:",a-b)
print("Division:",a/b)
print("Multiplicacion:",a*b) | print('hola mundo/jhon')
a = 45
b = 5
print('Suma:', a + b)
print('Resta:', a - b)
print('Division:', a / b)
print('Multiplicacion:', a * b) |
class Interfaces:
def __init__(self, interface: dict):
self.screen = interface['screen']
self.account_linking = interface['account_linking']
class MetaData:
def __init__(self, meta: dict):
self.locale = meta['locale']
self.timezone = meta['timezone']
self.interfaces = I... | class Interfaces:
def __init__(self, interface: dict):
self.screen = interface['screen']
self.account_linking = interface['account_linking']
class Metadata:
def __init__(self, meta: dict):
self.locale = meta['locale']
self.timezone = meta['timezone']
self.interfaces = ... |
#!/usr/bin/env python3
# https://codeforces.com/problemset/problem/4/A
n = int(input())
print('YES' if (n>2 and n%2==0) else 'NO')
| n = int(input())
print('YES' if n > 2 and n % 2 == 0 else 'NO') |
class Submissions:
def __init__(self, client):
self.client = client
def list(self, groupId, assignmentId):
url = self.client.api_url + '/groups/' + groupId + '/assignments/' + assignmentId + '/submissions'
method = 'get'
return self.client.api_handler(url=url, method=method)
... | class Submissions:
def __init__(self, client):
self.client = client
def list(self, groupId, assignmentId):
url = self.client.api_url + '/groups/' + groupId + '/assignments/' + assignmentId + '/submissions'
method = 'get'
return self.client.api_handler(url=url, method=method)
... |
class NQ:
def __init__(self, size):
self.n = size
self.board = self.generateBoard()
def solve(self):
if self.__util(0) == False:
print("Solution does not exist")
self.printBoard()
def __util(self, col):
if col >= self.n:
return ... | class Nq:
def __init__(self, size):
self.n = size
self.board = self.generateBoard()
def solve(self):
if self.__util(0) == False:
print('Solution does not exist')
self.printBoard()
def __util(self, col):
if col >= self.n:
return False
... |
# %% [139. Word Break](https://leetcode.com/problems/word-break/)
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
@functools.lru_cache(None)
def check(s):
if not s:
return True
for word in wordDict:
if s.startswith(wor... | class Solution:
def word_break(self, s: str, wordDict: List[str]) -> bool:
@functools.lru_cache(None)
def check(s):
if not s:
return True
for word in wordDict:
if s.startswith(word) and check(s[len(word):]):
return True
... |
def wrapper(f):
def fun(l):
decorated_numbers = []
for number in l:
decorated_numbers.append("+91 " + number[-10:-5] + " " + number[-5:])
return f(decorated_numbers)
return fun
@wrapper
def sort_phone(l):
print(*sorted(l), sep='\n')
if __name__ == '__main__':
l =... | def wrapper(f):
def fun(l):
decorated_numbers = []
for number in l:
decorated_numbers.append('+91 ' + number[-10:-5] + ' ' + number[-5:])
return f(decorated_numbers)
return fun
@wrapper
def sort_phone(l):
print(*sorted(l), sep='\n')
if __name__ == '__main__':
l = [i... |
def reverse_text(string):
return (x for x in string[::-1])
# for x in string[::-1]:
# yield x
# idx = len(string) - 1
# while idx >= 0:
# yield string[idx]
# idx -= 1
for char in reverse_text("step"):
print(char, end='')
| def reverse_text(string):
return (x for x in string[::-1])
for char in reverse_text('step'):
print(char, end='') |
class Ticket:
def __init__(self, payload, yt_api, gh_api, users_dict):
self.payload = payload
self.action = payload["action"]
self.yt_api = yt_api
self.gh_api = gh_api
self.users_dict = users_dict
self.pr = payload["pull_request"]
self.url = self.pr["html_ur... | class Ticket:
def __init__(self, payload, yt_api, gh_api, users_dict):
self.payload = payload
self.action = payload['action']
self.yt_api = yt_api
self.gh_api = gh_api
self.users_dict = users_dict
self.pr = payload['pull_request']
self.url = self.pr['html_url... |
MULTI_SIGNAL_CSV_DATA = """
symbol,date,signal
ibm,1/1/06,1
ibm,2/1/06,0
ibm,3/1/06,0
ibm,4/1/06,0
ibm,5/1/06,1
ibm,6/1/06,1
ibm,7/1/06,1
ibm,8/1/06,1
ibm,9/1/06,0
ibm,10/1/06,1
ibm,11/1/06,1
ibm,12/1/06,5
ibm,1/1/07,1
ibm,2/1/07,0
ibm,3/1/07,1
ibm,4/1/07,0
ibm,5/1/07,1
dell,1/1/06,1
dell,2/1/06,0
dell,3/1/06,0
dell,4/... | multi_signal_csv_data = '\nsymbol,date,signal\nibm,1/1/06,1\nibm,2/1/06,0\nibm,3/1/06,0\nibm,4/1/06,0\nibm,5/1/06,1\nibm,6/1/06,1\nibm,7/1/06,1\nibm,8/1/06,1\nibm,9/1/06,0\nibm,10/1/06,1\nibm,11/1/06,1\nibm,12/1/06,5\nibm,1/1/07,1\nibm,2/1/07,0\nibm,3/1/07,1\nibm,4/1/07,0\nibm,5/1/07,1\ndell,1/1/06,1\ndell,2/1/06,0\nde... |
dna_seq1 = 'ACCTGATC'
gc_count = 0
for nucl in dna_seq1:
if nucl == 'G' or nucl == 'C':
gc_count += 1
print(gc_count / len(dna_seq1))
| dna_seq1 = 'ACCTGATC'
gc_count = 0
for nucl in dna_seq1:
if nucl == 'G' or nucl == 'C':
gc_count += 1
print(gc_count / len(dna_seq1)) |
class BaseLoadTester(object):
def __init__(self, config):
self.config = config
def before(self):
raise NotImplementedError()
def on_result(self):
raise NotImplementedError()
| class Baseloadtester(object):
def __init__(self, config):
self.config = config
def before(self):
raise not_implemented_error()
def on_result(self):
raise not_implemented_error() |
description = 'POLI monochromator devices'
group = 'lowlevel'
tango_base = 'tango://phys.poli.frm2:10000/poli/'
s7_motor = tango_base + 's7_motor/'
devices = dict(
chi_m = device('nicos.devices.tango.Motor',
description = 'monochromator tilt (chi axis)',
tangodevice = s7_motor + 'chi_m',
... | description = 'POLI monochromator devices'
group = 'lowlevel'
tango_base = 'tango://phys.poli.frm2:10000/poli/'
s7_motor = tango_base + 's7_motor/'
devices = dict(chi_m=device('nicos.devices.tango.Motor', description='monochromator tilt (chi axis)', tangodevice=s7_motor + 'chi_m', fmtstr='%.2f', abslimits=(0, 12.7), pr... |
# Advent of code 2021 : Day 1 | Part 1
# Author = Abhinav
# Date = 1st of December 2021
# Source = [Advent Of Code](https://adventofcode.com/2021/day/1)
# Solution :
inputs = open("input.txt", "rt")
inputs = list(map(int, inputs.read().splitlines()))
print(sum([1 for _ in range(1, len(inputs)) if inputs[_-1] < in... | inputs = open('input.txt', 'rt')
inputs = list(map(int, inputs.read().splitlines()))
print(sum([1 for _ in range(1, len(inputs)) if inputs[_ - 1] < inputs[_]])) |
# hello.py
"""
This is an demo of a python script in the `py` package.
"""
#import api # cythonized max c api
# basic examples
a = 10
b = 1.5
c = "HELLO WORLD!!!"
d = [1,2,3,4]
e = ['a','b', 'c']
f = lambda: "hello func"
g = lambda x: x+10
h = '"a"'
e = '"double-quoted"'
f = "'single-quoted'"
| """
This is an demo of a python script in the `py` package.
"""
a = 10
b = 1.5
c = 'HELLO WORLD!!!'
d = [1, 2, 3, 4]
e = ['a', 'b', 'c']
f = lambda : 'hello func'
g = lambda x: x + 10
h = '"a"'
e = '"double-quoted"'
f = "'single-quoted'" |
class Charge:
def __init__(self, vehicle):
self._vehicle = vehicle
self._api_client = vehicle._api_client
async def get_state(self):
return await self._api_client.get(
"vehicles/{}/data_request/charge_state".format(self._vehicle.id))
async def start_charging(self):
... | class Charge:
def __init__(self, vehicle):
self._vehicle = vehicle
self._api_client = vehicle._api_client
async def get_state(self):
return await self._api_client.get('vehicles/{}/data_request/charge_state'.format(self._vehicle.id))
async def start_charging(self):
return a... |
test = { 'name': 'q3_1_2',
'points': 1,
'suites': [ { 'cases': [ { 'code': ">>> #It looks like you didn't give anything the name;\n"
">>> # seconds_in_a_decade. Maybe there's a typo, or maybe you ;\n"
'>>> # ... | test = {'name': 'q3_1_2', 'points': 1, 'suites': [{'cases': [{'code': '>>> #It looks like you didn\'t give anything the name;\n>>> # seconds_in_a_decade. Maybe there\'s a typo, or maybe you ;\n>>> # just need to run the cell below Question 3.2 where you defined ;\n>>> # seconds_in_a_decade. Click that cell and then cli... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/ros/lidar_ws/src/geometry/kdl_conversions/include;/opt/ros/kinetic/share/orocos_kdl/../../include;/usr/include/eigen3".split(';') if "/home/ros/lidar_ws/src/geometry/kdl_conversions/include;/opt/... | catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/ros/lidar_ws/src/geometry/kdl_conversions/include;/opt/ros/kinetic/share/orocos_kdl/../../include;/usr/include/eigen3'.split(';') if '/home/ros/lidar_ws/src/geometry/kdl_conversions/include;/opt/ros/kinetic/share/orocos_kdl/../../include;/usr/include/e... |
if __name__ == '__main__':
n = int(input())
answer = ''
for i in range(n):
answer += str(i + 1)
print(answer)
| if __name__ == '__main__':
n = int(input())
answer = ''
for i in range(n):
answer += str(i + 1)
print(answer) |
def reset_io(buff):
buff.seek(0)
buff.truncate(0)
return buff
def truncate_io(buff, size):
# get the remainder value
buff.seek(size)
leftover = buff.read()
# remove the remainder
buff.seek(0)
buff.truncate(size)
return leftover
# def diesattheend(pool):
# import atexit
# ... | def reset_io(buff):
buff.seek(0)
buff.truncate(0)
return buff
def truncate_io(buff, size):
buff.seek(size)
leftover = buff.read()
buff.seek(0)
buff.truncate(size)
return leftover
class Fakepool:
def __init__(self, max_workers=None):
pass
def submit(self, func, *a, **k... |
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
"""Main package of BenchExec.
The following modules are the public entry points:
- benche... | """Main package of BenchExec.
The following modules are the public entry points:
- benchexec: for executing benchmark suites
- runexec: for executing single runs
- check_cgroups: for checking the availability of cgroups
- test_tool_info: for testing a tool-info module
Naming conventions used within BenchExec:
TOOL: ... |
'''
APDT: Ploting
--------------------------
Provide useful data visualizaton tools.
Check https://github.com/Zhiyuan-Wu/apdt for more information.
''' | """
APDT: Ploting
--------------------------
Provide useful data visualizaton tools.
Check https://github.com/Zhiyuan-Wu/apdt for more information.
""" |
dead_emcal = [128, 129, 131, 134, 139, 140, 182, 184, 188, 189, 385, 394, 397, 398, 399, 432, 434, 436, 440, 442, 5024, 5025, 5026, 5027, 5028, 5030, 5032, 5033, 5035, 5036, 5037, 5038, 5039, 5121, 5122, 5123, 5124, 5125, 5126, 5128, 5129, 5130, 5132, 5133, 5134, 5135, 5170, 5172, 5173, 5174, 5178, 5181, 6641, 6647, 66... | dead_emcal = [128, 129, 131, 134, 139, 140, 182, 184, 188, 189, 385, 394, 397, 398, 399, 432, 434, 436, 440, 442, 5024, 5025, 5026, 5027, 5028, 5030, 5032, 5033, 5035, 5036, 5037, 5038, 5039, 5121, 5122, 5123, 5124, 5125, 5126, 5128, 5129, 5130, 5132, 5133, 5134, 5135, 5170, 5172, 5173, 5174, 5178, 5181, 6641, 6647, 66... |
#!/usr/bin/python3
#---------------------- Begin Serializer Boilerplate for GAPS ------------------------
HHEAD='''#ifndef GMA_HEADER_FILE
#define GMA_HEADER_FILE
#pragma pack(1)
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <inttypes.h>
#include <arpa/in... | hhead = '#ifndef GMA_HEADER_FILE\n#define GMA_HEADER_FILE\n#pragma pack(1)\n\n#include <stdio.h>\n#include <stdint.h>\n#include <string.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <inttypes.h>\n#include <arpa/inet.h>\n#include <float.h>\n\n#include "float754.h"\n\n#define id(X) (X)\n\ntypedef struct _trailer... |
#!/usr/bin/env python
def add_multiply(x, y, z=1):
return (x + y) * z
add_multiply(1, 2) # x=1, y=2, z=1
| def add_multiply(x, y, z=1):
return (x + y) * z
add_multiply(1, 2) |
"""Errand gofers module
"""
class Gofers(object):
"""Errand gofers class
"""
def __init__(self, *sizes):
self._norm_sizes(*sizes)
def _norm_sizes(self, *sizes):
def _n(s):
if isinstance(s, int):
return ((s,1,1))
elif isinstance(s, ... | """Errand gofers module
"""
class Gofers(object):
"""Errand gofers class
"""
def __init__(self, *sizes):
self._norm_sizes(*sizes)
def _norm_sizes(self, *sizes):
def _n(s):
if isinstance(s, int):
return (s, 1, 1)
elif isinstance(s, (list, tuple))... |
'''
Write a function called my_func that takes two arguments---a list and a
substring---and returns a new list, containing only words that start with the
chosen substring. Make sure that your function is not case sensitive: meaning
that if you want to filter by words that start with 'a', both 'apple' and
'Apple' wo... | """
Write a function called my_func that takes two arguments---a list and a
substring---and returns a new list, containing only words that start with the
chosen substring. Make sure that your function is not case sensitive: meaning
that if you want to filter by words that start with 'a', both 'apple' and
'Apple' wo... |
# Copyright (c) 2015 Microsoft Corporation
"""
>>> from z3 import *
>>> x = Int('x')
>>> s = MCSatCore()
>>> s.add_tactic('solve-eqs')
>>> s.freeze(x)
>>> s.add(x == 1)
>>> s.push()
>>> s
[x == 1]
>>> s = MCSatCore()
>>> s.add_tactic('solve-eqs')
>>> s.add(x == 1)
>>> s.push()
>>> s
[]
>>> y = Int('y')
>>> s = MCSatCo... | """
>>> from z3 import *
>>> x = Int('x')
>>> s = MCSatCore()
>>> s.add_tactic('solve-eqs')
>>> s.freeze(x)
>>> s.add(x == 1)
>>> s.push()
>>> s
[x == 1]
>>> s = MCSatCore()
>>> s.add_tactic('solve-eqs')
>>> s.add(x == 1)
>>> s.push()
>>> s
[]
>>> y = Int('y')
>>> s = MCSatCore()
>>> s.add_tactic('solve-eqs')
>>> s.fre... |
def transpose_grid(grid):
grid_t = []
grid_line = []
for i in range(len(grid[0])):
for row in grid:
grid_line.append(row[i])
grid_t.append(grid_line)
grid_line = []
return grid_t
def verify_row(row, necessary_length):
if len(row) < necessary_length:
ret... | def transpose_grid(grid):
grid_t = []
grid_line = []
for i in range(len(grid[0])):
for row in grid:
grid_line.append(row[i])
grid_t.append(grid_line)
grid_line = []
return grid_t
def verify_row(row, necessary_length):
if len(row) < necessary_length:
retur... |
font = CurrentFont()
for glyph in font.selection:
glyph = font[name]
glyph.prepareUndo()
glyph.rotate(-5)
glyph.skew(5)
glyph.performUndo()
| font = current_font()
for glyph in font.selection:
glyph = font[name]
glyph.prepareUndo()
glyph.rotate(-5)
glyph.skew(5)
glyph.performUndo() |
"""
A reimplementation of some useful python utilities missing from RPython
"""
def zip(list1, list2):
"""
expects two lists of equal length
"""
assert len(list1) == len(list2)
for i in xrange(len(list1)):
yield list1[i], list2[i]
raise StopIteration
def all(ls):
"""
expects l... | """
A reimplementation of some useful python utilities missing from RPython
"""
def zip(list1, list2):
"""
expects two lists of equal length
"""
assert len(list1) == len(list2)
for i in xrange(len(list1)):
yield (list1[i], list2[i])
raise StopIteration
def all(ls):
"""
expects ... |
load("//elm/private:test.bzl", _elm_test = "elm_test")
elm_test = _elm_test
def _elm_make_impl(ctx):
elm_compiler = ctx.toolchains["@rules_elm//elm:toolchain"].elm
output_file = ctx.actions.declare_file(ctx.attr.output)
env = {}
inputs = [elm_compiler, ctx.file.elm_json] + ctx.files.srcs
if ctx.f... | load('//elm/private:test.bzl', _elm_test='elm_test')
elm_test = _elm_test
def _elm_make_impl(ctx):
elm_compiler = ctx.toolchains['@rules_elm//elm:toolchain'].elm
output_file = ctx.actions.declare_file(ctx.attr.output)
env = {}
inputs = [elm_compiler, ctx.file.elm_json] + ctx.files.srcs
if ctx.file.... |
x = [2,3,5,6,8]
y = [1,6,22,33,61]
x_2 = list()
x_3 = list()
x_4 = list()
x_carpi_y = list()
x_2_carpi_y = list()
for i in x:
x_2.append(int(pow(i,2)))
x_3.append(int(pow(i,3)))
x_4.append(int(pow(i,4)))
print("xi : ", x, sum(x))
print("xi^2 : ", x_2, sum(x_2))
print("xi^3 : ", x_3, sum(x_3))
print("xi^... | x = [2, 3, 5, 6, 8]
y = [1, 6, 22, 33, 61]
x_2 = list()
x_3 = list()
x_4 = list()
x_carpi_y = list()
x_2_carpi_y = list()
for i in x:
x_2.append(int(pow(i, 2)))
x_3.append(int(pow(i, 3)))
x_4.append(int(pow(i, 4)))
print('xi : ', x, sum(x))
print('xi^2 : ', x_2, sum(x_2))
print('xi^3 : ', x_3, sum(x_3))
pri... |
#############################################################################
# Copyright 2016 Mass KonFuzion
#
# 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/l... | class Collisiongeomtype:
aabb = 0 |
class Virus(object):
'''Properties and attributes of the virus used in Simulation.'''
def __init__(self, name, repro_rate, mortality_rate):
self.name = name
self.repro_rate = repro_rate
self.mortality_rate = mortality_rate
def test_virus_instantiation():
#TODO: Create your own tes... | class Virus(object):
"""Properties and attributes of the virus used in Simulation."""
def __init__(self, name, repro_rate, mortality_rate):
self.name = name
self.repro_rate = repro_rate
self.mortality_rate = mortality_rate
def test_virus_instantiation():
"""Check to make sure that ... |
def tail(sequence, n):
"""Returns the last n items of a given sequence."""
if n <= 0:
return []
return list(sequence[-n:])
| def tail(sequence, n):
"""Returns the last n items of a given sequence."""
if n <= 0:
return []
return list(sequence[-n:]) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
def message_check(message = str):
if len(message) < 160:
return message
else:
return message[:160]
longer = message_check("In certain chat programs or ... | """
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
def message_check(message=str):
if len(message) < 160:
return message
else:
return message[:160]
longer = message_check('In certain chat programs or messaging applications, there is a limit on the number of characte... |
def getInnerBlocks(string, begin, end, sep = [","]):
ret_list = []
if not isinstance(string, str):
return None
# read a name until depth 1. Store until depth 0, and append it along with
# the contents.
# at depth 0, ignore separators
cname = ""
depth = 0
last_name = ""
cstr = ""
clist = []
for char in ... | def get_inner_blocks(string, begin, end, sep=[',']):
ret_list = []
if not isinstance(string, str):
return None
cname = ''
depth = 0
last_name = ''
cstr = ''
clist = []
for char in string:
if char == end:
depth -= 1
if depth == 0:
cl... |
def solve(n):
a = []
for _ in range(n):
name, h = input().split()
h = float(h)
a.append((name, h))
a.sort(key = lambda t: t[1], reverse=True)
m = a[0][1]
for n, h in a:
if h != m: break
print(n, end = " ")
print()
while True:
n = int(input())
if ... | def solve(n):
a = []
for _ in range(n):
(name, h) = input().split()
h = float(h)
a.append((name, h))
a.sort(key=lambda t: t[1], reverse=True)
m = a[0][1]
for (n, h) in a:
if h != m:
break
print(n, end=' ')
print()
while True:
n = int(input(... |
# IDLE (Python 3.8.0)
# module_for_lists_of_terms
def termal_generator(lict):
length_of_termal_generator = 16
padding = length_of_termal_generator - len(lict)
count = padding
while count != 0:
lict.append([''])
count = count - 1
termal_lict = []
for first_inner in lict[0]:
... | def termal_generator(lict):
length_of_termal_generator = 16
padding = length_of_termal_generator - len(lict)
count = padding
while count != 0:
lict.append([''])
count = count - 1
termal_lict = []
for first_inner in lict[0]:
for second_inner in lict[1]:
for thi... |
"""Implementation for yq rule"""
_yq_attrs = {
"srcs": attr.label_list(
allow_files = [".yaml", ".json", ".xml"],
mandatory = True,
allow_empty = True,
),
"expression": attr.string(mandatory = False),
"args": attr.string_list(),
"outs": attr.output_list(mandatory = True),
}
... | """Implementation for yq rule"""
_yq_attrs = {'srcs': attr.label_list(allow_files=['.yaml', '.json', '.xml'], mandatory=True, allow_empty=True), 'expression': attr.string(mandatory=False), 'args': attr.string_list(), 'outs': attr.output_list(mandatory=True)}
def is_split_operation(args):
for arg in args:
i... |
# ------------------------------
# 331. Verify Preorder Serialization of a Binary Tree
#
# Description:
# One way to serialize a binary tree is to use pre-order traversal. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as #.
#
# _9_
# ... | class Solution:
def is_valid_serialization(self, preorder: str) -> bool:
nodes = preorder.split(',')
diff = 1
for n in nodes:
diff -= 1
if diff < 0:
return False
if n != '#':
diff += 2
return diff == 0
if __name__ =... |
class HsvFilter:
def __init__(self, hMin=None, sMin=None, vMin=None, hMax=None, sMax=None, vMax=None,
sAdd=None, sSub=None, vAdd=None, vSub=None):
self.hMin = hMin
self.sMin = sMin
self.vMin = vMin
self.hMax = hMax
self.sMax = sMax
self.vMax = vM... | class Hsvfilter:
def __init__(self, hMin=None, sMin=None, vMin=None, hMax=None, sMax=None, vMax=None, sAdd=None, sSub=None, vAdd=None, vSub=None):
self.hMin = hMin
self.sMin = sMin
self.vMin = vMin
self.hMax = hMax
self.sMax = sMax
self.vMax = vMax
self.sAdd ... |
class Solution:
def isHappy(self, n: int) -> bool:
def squaredSum(n: int) -> bool:
sum = 0
while n:
sum += pow(n % 10, 2)
n //= 10
return sum
slow = squaredSum(n)
fast = squaredSum(squaredSum(n))
while slow != fast:
slow = squaredSum(slow)
fast = squar... | class Solution:
def is_happy(self, n: int) -> bool:
def squared_sum(n: int) -> bool:
sum = 0
while n:
sum += pow(n % 10, 2)
n //= 10
return sum
slow = squared_sum(n)
fast = squared_sum(squared_sum(n))
while slow !=... |
def safeDict(elem, array_of_keys, default=""):
try:
for key in array_of_keys:
elem = elem[key]
return elem
except Exception as e:
return default | def safe_dict(elem, array_of_keys, default=''):
try:
for key in array_of_keys:
elem = elem[key]
return elem
except Exception as e:
return default |
# Those constants are used from the library only
BASE_PAL_URL = "https://pal-{}.adyen.com/pal/servlet"
PAL_LIVE_ENDPOINT_URL_TEMPLATE = "https://{}-pal-live" \
".adyenpayments.com/pal/servlet"
BASE_HPP_URL = "https://{}.adyen.com/hpp"
ENDPOINT_CHECKOUT_TEST = "https://checkout-test.adye... | base_pal_url = 'https://pal-{}.adyen.com/pal/servlet'
pal_live_endpoint_url_template = 'https://{}-pal-live.adyenpayments.com/pal/servlet'
base_hpp_url = 'https://{}.adyen.com/hpp'
endpoint_checkout_test = 'https://checkout-test.adyen.com'
endpoint_checkout_live_suffix = 'https://{}-checkout-live.adyenpayments.com/chec... |
__all__ = ['VERSION']
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
VIDEO = 'youtube#video'
YOUTUBE_VIDEO_URL = 'https://www.youtube.com/watch?v='
VERSION = '4.0.0'
| __all__ = ['VERSION']
youtube_api_service_name = 'youtube'
youtube_api_version = 'v3'
video = 'youtube#video'
youtube_video_url = 'https://www.youtube.com/watch?v='
version = '4.0.0' |
# mailbox_or_url_parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'mailbox_or_urlFWSP AT DOT COMMA SEMICOLON LANGLE RANGLE ATOM DOT_ATOM LBRACKET RBRACKET DTEXT DQUOTE QTEXT QPAIR LPAREN RPAREN CTEXT URLmailbox_or_url_list : mailbox_or_url_list... | _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'mailbox_or_urlFWSP AT DOT COMMA SEMICOLON LANGLE RANGLE ATOM DOT_ATOM LBRACKET RBRACKET DTEXT DQUOTE QTEXT QPAIR LPAREN RPAREN CTEXT URLmailbox_or_url_list : mailbox_or_url_list delim mailbox_or_url\n | mailbox_or_url_list delim\n ... |
"""
142. Linked List Cycle II
Medium
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote t... | """
142. Linked List Cycle II
Medium
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote t... |
def sum(a, b):
"""Returns sum
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
sum -- Sum
"""
return a + b
def difference(a, b):
"""Returns difference
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
... | def sum(a, b):
"""Returns sum
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
sum -- Sum
"""
return a + b
def difference(a, b):
"""Returns difference
Arguments:
a {int} -- Input 1
b {int} -- Input 2
Returns:
diff -- Differenc... |
print(add(5, 3))
def add(x, y):
return x+y
| print(add(5, 3))
def add(x, y):
return x + y |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def kthLargest(self, root: TreeNode, k: int) -> int:
def dfs(root):
if root:
dfs(root.left)
nu... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def kth_largest(self, root: TreeNode, k: int) -> int:
def dfs(root):
if root:
dfs(root.left)
nums.append(root.val)
... |
class Solution:
# O(n) time | O(1) space - where n is the length of the input list
def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
maxDuration, startTime, slowestKey = 0, 0, ''
for i in range(len(releaseTimes)):
pressTime = releaseTimes[i] - startTime
... | class Solution:
def slowest_key(self, releaseTimes: List[int], keysPressed: str) -> str:
(max_duration, start_time, slowest_key) = (0, 0, '')
for i in range(len(releaseTimes)):
press_time = releaseTimes[i] - startTime
if pressTime > maxDuration:
max_duration ... |
# -*- coding: utf-8 -*-
formatted_body_template = """<div id="vlivepy-post-html" style="width:728px;">
<p><a href="###LINK###">###LINK###</a></p>
<div style="padding:15px 0;border-bottom:1px solid #f2f2f2">
<span class="author" style="font-weight:600;color:#111;font-size:14px;display:block">###AUTHOR###</span>... | formatted_body_template = '<div id="vlivepy-post-html" style="width:728px;">\n <p><a href="###LINK###">###LINK###</a></p>\n<div style="padding:15px 0;border-bottom:1px solid #f2f2f2">\n <span class="author" style="font-weight:600;color:#111;font-size:14px;display:block">###AUTHOR###</span>\n <span class="creat... |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"run_params": "000_exp_02_pretrained.ipynb",
"experiment": "000_exp_02_pretrained.ipynb",
"DatasetBuilder": "01_dataset_builder.ipynb",
"StatementClassifier": "02_statement_classife... | __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'run_params': '000_exp_02_pretrained.ipynb', 'experiment': '000_exp_02_pretrained.ipynb', 'DatasetBuilder': '01_dataset_builder.ipynb', 'StatementClassifier': '02_statement_classifer.ipynb', 'Experiment': '03_experiment.ipynb', 'RunParams': '04_run_... |
A, B = map(int, input().split())
S = str(input())
flag = True
if not S[:A].isdecimal():
flag = False
elif S[A] != '-':
flag = False
elif not S[-B:].isdecimal():
flag = False
if flag:
print('Yes')
else:
print('No')
| (a, b) = map(int, input().split())
s = str(input())
flag = True
if not S[:A].isdecimal():
flag = False
elif S[A] != '-':
flag = False
elif not S[-B:].isdecimal():
flag = False
if flag:
print('Yes')
else:
print('No') |
def configure_tx_chains(txChains, streamNum, mcsIdx):
txChains = txChains.lower()
RATE_MCS_ANT_A_MSK = 0x04000
RATE_MCS_ANT_B_MSK = 0x08000
RATE_MCS_ANT_C_MSK = 0x10000
RATE_MCS_HT_MSK = 0x00100
mask = 0x0
usedAntNum = 0
if "a" in txChains:
mask |= RATE_MCS_ANT_A_MSK
... | def configure_tx_chains(txChains, streamNum, mcsIdx):
tx_chains = txChains.lower()
rate_mcs_ant_a_msk = 16384
rate_mcs_ant_b_msk = 32768
rate_mcs_ant_c_msk = 65536
rate_mcs_ht_msk = 256
mask = 0
used_ant_num = 0
if 'a' in txChains:
mask |= RATE_MCS_ANT_A_MSK
used_ant_num ... |
# 19. Remove Nth Node From End of List
# Time: O(n)
# Space: O(1)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
slow = head
fast ... | class Solution:
def remove_nth_from_end(self, head: ListNode, n: int) -> ListNode:
slow = head
fast = head
for i in range(n):
fast = fast.next
while fast:
prev = slow
slow = slow.next
fast = fast.next
if slow == head:
... |
"""
A particular zoo determines the price of admission based on the age of the guest.
Guests 2 years of age and less are admitted without charge.
Children between 3 and 12 years of age cost $14.00.
Seniors aged 65 years and over cost $18.00.
Admission for all other guests is $23.00.
Create a program that
begins by read... | """
A particular zoo determines the price of admission based on the age of the guest.
Guests 2 years of age and less are admitted without charge.
Children between 3 and 12 years of age cost $14.00.
Seniors aged 65 years and over cost $18.00.
Admission for all other guests is $23.00.
Create a program that
begins by read... |
# Cloud Automation Services SDK for Python
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
class Region(object):
"""
Class for Region methods.
Used to discover regions for all fabric constructs (images, mappings,
networks and storage.)
"""
def __in... | class Region(object):
"""
Class for Region methods.
Used to discover regions for all fabric constructs (images, mappings,
networks and storage.)
"""
def __init__(self, region):
self.external_region_id = region['externalRegionId']
self.id = region['id']
self.updated_at = ... |
'''
URL: https://leetcode.com/problems/find-lucky-integer-in-an-array/
Difficulty: Easy
Description: Find Lucky Integer in an Array
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky in... | """
URL: https://leetcode.com/problems/find-lucky-integer-in-an-array/
Difficulty: Easy
Description: Find Lucky Integer in an Array
Given an array of integers arr, a lucky integer is an integer which has a frequency in the array equal to its value.
Return a lucky integer in the array. If there are multiple lucky in... |
#string.py
str1 = "Hello"
str2 = 'John'
print(type(str1))
print("\"Good\\Job\"")
greet = "Hello John"
print(greet[1])
print(greet[-4])
print(greet[0:3])
print("bad" + "apple")
print("wt" + "d" * 5)
print(len("pine"))
print(type(str(123))) | str1 = 'Hello'
str2 = 'John'
print(type(str1))
print('"Good\\Job"')
greet = 'Hello John'
print(greet[1])
print(greet[-4])
print(greet[0:3])
print('bad' + 'apple')
print('wt' + 'd' * 5)
print(len('pine'))
print(type(str(123))) |
class DimensionError(Exception):
"""Represents an error involving matrix dimensions."""
class CoefficientError(Exception):
"""Represents an error involving transfer function coefficients."""
class StateSpaceError(Exception):
"""Represents a miscellaneous error involving `StateSpace`."""
class ResultEr... | class Dimensionerror(Exception):
"""Represents an error involving matrix dimensions."""
class Coefficienterror(Exception):
"""Represents an error involving transfer function coefficients."""
class Statespaceerror(Exception):
"""Represents a miscellaneous error involving `StateSpace`."""
class Resulterror... |
#!/usr/bin/env python
NAME = 'Reblaze (Reblaze)'
def is_waf(self):
if self.matchcookie(r'^rbzid='):
return True
if self.matchheader(('Server', 'Reblaze Secure Web Gateway')):
return True
# Now going for attack phase
for attack in self.attacks:
r = attack(self)
if r is... | name = 'Reblaze (Reblaze)'
def is_waf(self):
if self.matchcookie('^rbzid='):
return True
if self.matchheader(('Server', 'Reblaze Secure Web Gateway')):
return True
for attack in self.attacks:
r = attack(self)
if r is None:
return
(_, page) = r
if ... |
"""
Enumerated data types useful for data conversion
Created: 15 May 2018
Eva Berlot & Naveed Ejaz
"""
class BidsTags:
tSubj = 'sub-'
tSes = 'ses-'
tSesID = 'ses-id'
tParticipantID = 'participants-id'
tFunc = 'func'
tFuncEvents = 'tas... | """
Enumerated data types useful for data conversion
Created: 15 May 2018
Eva Berlot & Naveed Ejaz
"""
class Bidstags:
t_subj = 'sub-'
t_ses = 'ses-'
t_ses_id = 'ses-id'
t_participant_id = 'participants-id'
t_func = 'func'
t_func_events = 'task-{}_events'
t_func_run = 'task-{}_run-{}_bold'... |
#
# PySNMP MIB module TIME-AGGREGATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIME-AGGREGATE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:09:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) ... |
class ExtendedTextAttributes(object):
def __init__(
self,
text, matched_text, canonical_url, description, title, jpeg_thumbnail, context_info
):
self._text = text
self._matched_text = matched_text
self._canonical_url = canonical_url
self._description = des... | class Extendedtextattributes(object):
def __init__(self, text, matched_text, canonical_url, description, title, jpeg_thumbnail, context_info):
self._text = text
self._matched_text = matched_text
self._canonical_url = canonical_url
self._description = description
self._title ... |
#!/usr/bin/env python3
"""
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by
all of the numbers from 1 to 20?
https://projecteuler.net/problem=5
"""
| """
2520 is the smallest number that can be divided by each of the numbers
from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by
all of the numbers from 1 to 20?
https://projecteuler.net/problem=5
""" |
_V = {}
# Stages: game, rounds
# State: probability, probability of co-operating
# Action:
# V(t,p) gives maximum expected value from starting game t with probability p of cooperating
def V(game, probability):
if game is 10:
return 0, 0
else:
if (game, probability) not in _V:
coope... | _v = {}
def v(game, probability):
if game is 10:
return (0, 0)
elif (game, probability) not in _V:
cooperate = probability * (3 + v(game + 1, min(1, probability + 0.1))[0]) + (1 - probability) * (0 + v(game + 1, min(1, probability + 0.1))[0])
defect = probability * (5 + v(game + 1, max(... |
help = """
Your project has been created!
If you have not done so already, create a conda environment for your new
project with:
cd {{cookiecutter.repo_name}}
conda create --name {{cookiecutter.repo_name}} python=3.x
conda activate {{cookiecutter.repo_name}}
conda env export > environment.yml
Install your new proje... | help = "\nYour project has been created!\n\nIf you have not done so already, create a conda environment for your new \nproject with:\n\ncd {{cookiecutter.repo_name}}\nconda create --name {{cookiecutter.repo_name}} python=3.x\nconda activate {{cookiecutter.repo_name}}\nconda env export > environment.yml\n\nInstall your ... |
BASE_DIR = './'
environ = {
'KPK_DATA': '/home/kpk/data',
'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
}
KPK_DATA = environ.get('KPK_DATA')
# print(KPK_DATA)
# _KPK_DATA = environ['KPK_DATA']
# print(_KPK_DATA)
# os.environ.get('KPK_DATA') or BASE_DIR
#
# os.environ.get('KPK_DATA') ... | base_dir = './'
environ = {'KPK_DATA': '/home/kpk/data', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'}
kpk_data = environ.get('KPK_DATA')
pass
if KPK_DATA:
root = KPK_DATA
else:
root = BASE_DIR
print(ROOT)
pass
root = KPK_DATA if KPK_DATA else BASE_DIR
print(ROOT)
pass
root = KPK_DATA ... |
class Reference:
def __init__(self, id, campaign_id, name, details, created, modified):
self.id = id
self.campaign_id = campaign_id
self.name = name
self.details = details
self.created = created
self.modified = modified
| class Reference:
def __init__(self, id, campaign_id, name, details, created, modified):
self.id = id
self.campaign_id = campaign_id
self.name = name
self.details = details
self.created = created
self.modified = modified |
NONE = 0x000000000
# Posting Permissions
CREATE_POST = 0x000000001
EDIT_POST = 0x000000002
DELETE_POST = 0x000000004
# Documents Permissions
UPLOAD_DOCUMENT = 0x000000008
EDIT_DOCUMENT = 0x000000010
DELETE_DOCUMENT = 0x000000020
# User Account Permissions
CREATE_USER = 0x000000040
EDIT_USER = 0x000000080
DELETE_USER... | none = 0
create_post = 1
edit_post = 2
delete_post = 4
upload_document = 8
edit_document = 16
delete_document = 32
create_user = 64
edit_user = 128
delete_user = 256 |
class Car:
wheels = 4 # Class (Static) Variables before __init__
def __init__(self):
self.com = "BMW" # Instance Variables inside __init__
self.mil = "10"
c1 = Car()
c2 = Car()
Car.wheels = 5 # The value of all ... | class Car:
wheels = 4
def __init__(self):
self.com = 'BMW'
self.mil = '10'
c1 = car()
c2 = car()
Car.wheels = 5
print(c1.com, c1.mil, c1.wheels)
print(c2.com, c2.mil, c2.wheels) |
"""
author : @akash kumar
github : https://github/Akash671
string fun:
string.replace(sub_old_string,new_sub_string,count)
string.count(your_string)
"""
def solve():
#n,m=map(int,input().split())
#n=int(input())
#a=list(map(int,input().split()[:n]))
#s=str(input())
#a,b=input().split()
n=int(input(... | """
author : @akash kumar
github : https://github/Akash671
string fun:
string.replace(sub_old_string,new_sub_string,count)
string.count(your_string)
"""
def solve():
n = int(input())
a = list(map(int, input().split()[:n]))
b = list(map(int, input().split()[:n]))
ans = 1
for i in a:
for j ... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class ThrottlingConfiguration(object):
"""Implementation of the 'ThrottlingConfiguration' model.
Specifies the throttling configuration parameters.
Attributes:
fixed_threshold (long|int): Fixed baseline threshold for throttling. This is
... | class Throttlingconfiguration(object):
"""Implementation of the 'ThrottlingConfiguration' model.
Specifies the throttling configuration parameters.
Attributes:
fixed_threshold (long|int): Fixed baseline threshold for throttling. This is
mandatory for any other throttling type than kNoT... |
class Solution:
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
idx1, idx2 = len(words), len(words)
result = len(words)
for i in range(len(words)):
if wor... | class Solution:
def shortest_distance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
(idx1, idx2) = (len(words), len(words))
result = len(words)
for i in range(len(words)):
... |
'''
Discuss structure:
Getting input from user
Formatting the input (multiply by 100 then convert to integer)
Getting total amount of change (amount paid minus bill)
Getting dollars of change (divide by 100 then convert to integer)
Getting the amount of change leftover (either change minus dollars times 100 or ch... | """
Discuss structure:
Getting input from user
Formatting the input (multiply by 100 then convert to integer)
Getting total amount of change (amount paid minus bill)
Getting dollars of change (divide by 100 then convert to integer)
Getting the amount of change leftover (either change minus dollars times 100 or cha... |
class AzureCloudProviderResourceModel(object):
def __init__(self):
self.azure_application_id = '' # type: str
self.azure_mgmt_network_d = '' # type: str
self.azure_mgmt_nsg_id = '' # type: str
self.azure_application_key = '' # type: str
self.region = '' # type: str
... | class Azurecloudproviderresourcemodel(object):
def __init__(self):
self.azure_application_id = ''
self.azure_mgmt_network_d = ''
self.azure_mgmt_nsg_id = ''
self.azure_application_key = ''
self.region = ''
self.vm_size = ''
self.keypairs_location = ''
... |
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Copyright (c) 2021. by Daniel Barrejon, UC3M. +
# All rights reserved. This file is part of the Shi-VAE, and is released under the +
# "MIT License Agreement". Please see the LICE... | class Earlystopping(object):
"""
EarlyStopping scheme to finish training if model is not improving any more.
"""
def __init__(self, patience=15, min_delta=0.1):
"""
Args:
patience: (int) Patience value to stop training.
min_delta: (float) Minimum margin for impr... |
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
r, s, t = -1, 0, 0
for i in range(0, len(gas)):
t = t + gas[i] - cost[i]
s = s + gas[i] - cost[i]
... | class Solution(object):
def can_complete_circuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
(r, s, t) = (-1, 0, 0)
for i in range(0, len(gas)):
t = t + gas[i] - cost[i]
s = s + gas[i] - cost[i]
... |
# Given a binary matrix representing an image, we want to flip the image horizontally, then invert it.
# To flip an image horizontally means that each row of the image is reversed.
# For example, flipping [0, 1, 1] horizontally results in [1, 1, 0].
# To invert an image means that each 0 is replaced by 1, and each 1 ... | def flip_invert_image(matrix):
m = len(matrix)
n = len(matrix[0])
for i in range(m):
for j in range((n + 1) // 2):
(matrix[i][j], matrix[i][n - j - 1]) = (matrix[i][n - j - 1] ^ 1, matrix[i][j] ^ 1)
return matrix
print(flip_invert_image([[1, 0, 1], [1, 1, 1], [0, 1, 1]]))
print(flip_... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
_SNAKE_TO_CAMEL_CASE_TABLE = {
"availability_zones": "availabilityZones",
"backend_services": "backendServices",
"beanstalk... | _snake_to_camel_case_table = {'availability_zones': 'availabilityZones', 'backend_services': 'backendServices', 'beanstalk_environment_name': 'beanstalkEnvironmentName', 'block_devices_mode': 'blockDevicesMode', 'capacity_unit': 'capacityUnit', 'cluster_id': 'clusterId', 'cluster_zone_name': 'clusterZoneName', 'control... |
# guess file size : https://softwareengineering.stackexchange.com/q/204417
# https://stackoverflow.com/a/1094933
def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
... | def sizeof_fmt(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return '%3.1f%s%s' % (num, unit, suffix)
num /= 1024.0
return '%.1f%s%s' % (num, 'Yi', suffix) |
# Source : https://leetcode.com/problems/rectangle-overlap/
# Author : foxfromworld
# Date : 07/04/2021
# Second attempt
class Solution:
def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec1[0] == rec1[2] or rec2[0] == rec2[2] or\
rec2[1] == rec2[3] or rec1[1] == rec1[3]:
... | class Solution:
def is_rectangle_overlap(self, rec1: List[int], rec2: List[int]) -> bool:
if rec1[0] == rec1[2] or rec2[0] == rec2[2] or rec2[1] == rec2[3] or (rec1[1] == rec1[3]):
return False
up_bound = min(rec1[3], rec2[3])
lo_bound = max(rec1[1], rec2[1])
rt_bound = ... |
class Project():
def __init__(self, id_project, name, session_counter, token):
self.id_project = id_project
self.name = name
self.session_counter = session_counter
self.token = token
class Session():
def __init__(self, id_session, index, dt_start, dt_end, is_active, is_favorite,... | class Project:
def __init__(self, id_project, name, session_counter, token):
self.id_project = id_project
self.name = name
self.session_counter = session_counter
self.token = token
class Session:
def __init__(self, id_session, index, dt_start, dt_end, is_active, is_favorite, h... |
#=======================================================================
# Author: Isai Damier
# Title: Selection Sort
# Project: geekviewpoint
# Package: algorithm.sorting
#
# Statement:
# Given a disordered list of integers (or any other items),
# rearrange the integers in natural order.
#
# Sample Input: [18... | def selectionsort(aList):
for i in range(len(aList)):
least = i
for k in range(i + 1, len(aList)):
if aList[k] < aList[least]:
least = k
swap(aList, least, i)
def swap(A, x, y):
tmp = A[x]
A[x] = A[y]
A[y] = tmp |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
a = 3
if a > 2:
print("H")
else:
print("L") | a = 3
if a > 2:
print('H')
else:
print('L') |
"""
1720. Decode XORed Array
https://leetcode.com/problems/decode-xored-array/
There is a hidden integer array arr that consists of n non-negative integers.
It was encoded into another integer array encoded of length n - 1,
such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = ... | """
1720. Decode XORed Array
https://leetcode.com/problems/decode-xored-array/
There is a hidden integer array arr that consists of n non-negative integers.
It was encoded into another integer array encoded of length n - 1,
such that encoded[i] = arr[i] XOR arr[i + 1]. For example, if arr = [1,0,2,1], then encoded = ... |
# Enter your code here. Read input from STDIN. Print output to STDOUT
m = float(raw_input());
t = m * input() /100;
x = m * input() /100;
totalCost = round(m + x + t);
print ('The total meal cost is' " " + str(int(totalCost)) + " " 'dollars.') | m = float(raw_input())
t = m * input() / 100
x = m * input() / 100
total_cost = round(m + x + t)
print('The total meal cost is ' + str(int(totalCost)) + ' dollars.') |
# program to match key values in two dictionaries.
x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items()) & set(y.items()):
print('%s: %s is present in both x and y' % (key, value))
| x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items()) & set(y.items()):
print('%s: %s is present in both x and y' % (key, value)) |
class Number(object):
def __init__(self, value):
if value % 2 != 0:
self.even = self._odds_even
else:
self.even = self._even
def _even(self):
print("even")
return True
def _odds_even(self):
print("not odd")
return False
a = Number... | class Number(object):
def __init__(self, value):
if value % 2 != 0:
self.even = self._odds_even
else:
self.even = self._even
def _even(self):
print('even')
return True
def _odds_even(self):
print('not odd')
return False
a = number(2)... |
WIDTH = 87
HEIGHT = 87
FIRST = 0x20
LAST = 0x7f
_font =\
b'\x00\x4a\x5a\x02\x44\x60\x44\x52\x60\x52\x02\x44\x60\x44\x60'\
b'\x60\x44\x02\x52\x52\x52\x3e\x52\x66\x02\x44\x60\x44\x44\x60'\
b'\x60\x02\x44\x60\x44\x52\x60\x52\x02\x46\x5e\x46\x59\x5e\x4b'\
b'\x02\x4b\x59\x4b\x5e\x59\x46\x02\x52\x52\x52\x44\x52\x60\x02'\
b'... | width = 87
height = 87
first = 32
last = 127
_font = b'\x00JZ\x02D`DR`R\x02D`D``D\x02RRR>Rf\x02D`DD``\x02D`DR`R\x02F^FY^K\x02KYK^YF\x02RRRDR`\x02KYKFY^\x02F^FK^Y\x02KYKRYR\x02MWMWWM\x02RRRKRY\x02MWMMWW\x07GRRGPGMHJJHMGPGR\x07GRGRGTHWJZM\\P]R]\x07R]R]T]W\\ZZ\\W]T]R\x07R]]R]P\\MZJWHTGRG\x08D`DOGQKSPTTTYS]Q`O\x08PUUDSGQKP... |
#!/usr/bin/python
## Ejercicio 1 reverse Polish Notation
## Autor: Fabiola Tapara Quispe
## Description: Mediante el siguiente metodo recibe un string con datos y signos con operaciones basicas (+, -, *, /) usando una Pila como estructura.
## * Date: 15/11/21
def sum (a, b):
return a + b
def resta (a, b):
... | def sum(a, b):
return a + b
def resta(a, b):
return a - b
def multipli(a, b):
return a * b
def division(a, b):
return a // b
def polish_reverse(input):
operadores = '+-*/'
string = []
listado = input.split(' ')
for i in listado:
if i in operadores:
num2 = string.p... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 4 23:30:51 2017
@author: coskun
Problem 1 - Paying Debt off in a Year
10.0 points possible (graded)
Write a program to calculate the credit card balance after
one year if a person only pays the minimum monthly payment
required by the credit car... | """
Created on Sat Mar 4 23:30:51 2017
@author: coskun
Problem 1 - Paying Debt off in a Year
10.0 points possible (graded)
Write a program to calculate the credit card balance after
one year if a person only pays the minimum monthly payment
required by the credit card company each month.
The following variables ... |
def return_category_with_more_spending(transactions):
category_transactions = transactions.groupby(by=["column_category"])[
"column_installment_value"
].sum()
return category_transactions.idxmax(), category_transactions.max()
| def return_category_with_more_spending(transactions):
category_transactions = transactions.groupby(by=['column_category'])['column_installment_value'].sum()
return (category_transactions.idxmax(), category_transactions.max()) |
# Copyright (c) 2020 Thomas Holland (thomas@innot.de)
# All rights reserved.
#
# This code is licensed under the MIT License.
#
# Refer to the LICENSE file which is part of the AdvPiStepper distribution or
# to https://opensource.org/licenses/MIT for a text of the license.
#
#
"""
Definitions used by the AdvPiSte... | """
Definitions used by the AdvPiStepper
CW and CCW constants defining clockwise / couterclockwise motions.
The Keys which are used as parameters to describe a motor and the driver.
* DRIVER_NAME Human readable name of the driver.
* MAX_SPEED: Maximum speed in steps per second. This is not a li... |
def is_palindrome(n: int) -> bool:
s = str(n)
h = int(len(s) / 2)
s1 = s[:h]
s2 = s[h:][::-1]
is_palindrome = True
for i in range(h):
if s1[i] != s2[i]:
is_palindrome = False
return is_palindrome
def solution() -> int:
largest_palindrome = 0
for i in range(100, ... | def is_palindrome(n: int) -> bool:
s = str(n)
h = int(len(s) / 2)
s1 = s[:h]
s2 = s[h:][::-1]
is_palindrome = True
for i in range(h):
if s1[i] != s2[i]:
is_palindrome = False
return is_palindrome
def solution() -> int:
largest_palindrome = 0
for i in range(100, 1... |
''' Check valid age
Write a program that takes age fro the user and then decide whether the age is between 18 to 24. If so, then it will display the message "You can apply for youth festival program". Otherwise, display the message "Sorry, you cannot apply".
If age >= 18 and age <= 24 # Not correct
If age = 18 and ... | """ Check valid age
Write a program that takes age fro the user and then decide whether the age is between 18 to 24. If so, then it will display the message "You can apply for youth festival program". Otherwise, display the message "Sorry, you cannot apply".
If age >= 18 and age <= 24 # Not correct
If age = 18 and ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.