content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
X = []
Y = []
cont = 0
n = True
while n:
a,b = input().split(" ")
a = int(a)
b = int(b)
if a == b:
n = False
cont-=1
else:
X.append(a)
Y.append(b)
cont+=1
i = 0
while i < cont:
if X[i] > Y[i]:
print('Decrescente')
elif X[i] < ... | x = []
y = []
cont = 0
n = True
while n:
(a, b) = input().split(' ')
a = int(a)
b = int(b)
if a == b:
n = False
cont -= 1
else:
X.append(a)
Y.append(b)
cont += 1
i = 0
while i < cont:
if X[i] > Y[i]:
print('Decrescente')
elif X[i] < Y[i]:
p... |
def test_example():
num1 = 1
num2 = 3
if num2 > num1:
print("Working")
| def test_example():
num1 = 1
num2 = 3
if num2 > num1:
print('Working') |
class Node:
def __init__(self,v):
self.next=None
self.prev=None
self.value=v
class Deque:
def __init__(self):
self.front=None
self.tail=None
def addFront(self, item):
node=Node(item)
if self.front is None: #case of none items
se... | class Node:
def __init__(self, v):
self.next = None
self.prev = None
self.value = v
class Deque:
def __init__(self):
self.front = None
self.tail = None
def add_front(self, item):
node = node(item)
if self.front is None:
self.front = nod... |
# =============================================================================
# MISC HELPER FUNCTIONS
# =============================================================================
def push_backslash(stuff):
""" push a backslash before a word, dumbest function ever"""
stuff_url = ""
if stuff i... | def push_backslash(stuff):
""" push a backslash before a word, dumbest function ever"""
stuff_url = ''
if stuff is None:
stuff = ''
else:
stuff_url = '/' + stuff
return (stuff, stuff_url)
def replace_dict_value(dictionary, old_value, new_value):
""" Selectively replaces values i... |
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in nums:
if i == 0:
nums.append(i)
nums.remove(i) | class Solution:
def move_zeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
for i in nums:
if i == 0:
nums.append(i)
nums.remove(i) |
class Solution(object):
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
m, n = len(matrix), len(matrix[0])
col_zero = any(matrix[i][0] == 0 for i in range(m))
row_zero = an... | class Solution(object):
def set_zeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
(m, n) = (len(matrix), len(matrix[0]))
col_zero = any((matrix[i][0] == 0 for i in range(m)))
row_z... |
'''
A package to manipulate and display some random structures,
including meander systems, planar triangulations, and ribbon tilings
Created on May 8, 2021
@author: vladislavkargin
'''
'''
#I prefer blank __init__.py
from . import mndrpy
from . import pmaps
from . import ribbons
''' | """
A package to manipulate and display some random structures,
including meander systems, planar triangulations, and ribbon tilings
Created on May 8, 2021
@author: vladislavkargin
"""
'\n#I prefer blank __init__.py\n\nfrom . import mndrpy\nfrom . import pmaps\nfrom . import ribbons\n' |
#!/usr/bin/python3
'''Day 9 of the 2017 advent of code'''
def process_garbage(stream, index):
"""Traverse stream. Break on '>' as end of garbage,
return total as size of garbage and the new index
"""
total = 0
length = len(stream)
while index < length:
if stream[index] =... | """Day 9 of the 2017 advent of code"""
def process_garbage(stream, index):
"""Traverse stream. Break on '>' as end of garbage,
return total as size of garbage and the new index
"""
total = 0
length = len(stream)
while index < length:
if stream[index] == '>':
break
el... |
name = input('Please enter your name:\n')
age = int(input("Please enter your age:\n"))
color = input('Enter your favorite color:\n')
animal = input('Enter your favorite animal:\n')
print('Hello my name is' , name , '.')
print('I am' , age , 'years old.')
print('My favorite color is' , color ,'.')
print('My favorite... | name = input('Please enter your name:\n')
age = int(input('Please enter your age:\n'))
color = input('Enter your favorite color:\n')
animal = input('Enter your favorite animal:\n')
print('Hello my name is', name, '.')
print('I am', age, 'years old.')
print('My favorite color is', color, '.')
print('My favorite animal i... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/vis-02-curtailment.ipynb (unless otherwise specified).
__all__ = ['get_wf_ids', 'flatten_list', 'get_curtailed_wfs_df', 'load_curtailed_wfs',
'add_next_week_of_data_to_curtailed_wfs']
# Cell
flatten_list = lambda list_: [item for sublist in list_ for item in ... | __all__ = ['get_wf_ids', 'flatten_list', 'get_curtailed_wfs_df', 'load_curtailed_wfs', 'add_next_week_of_data_to_curtailed_wfs']
flatten_list = lambda list_: [item for sublist in list_ for item in sublist]
def get_wf_ids(dictionary_url='https://raw.githubusercontent.com/OSUKED/Power-Station-Dictionary/main/data/output... |
"""
0081. Search in Rotated Sorted Array II
Medium
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input... | """
0081. Search in Rotated Sorted Array II
Medium
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]).
You are given a target value to search. If found in the array return true, otherwise return false.
Example 1:
Input... |
"""Top-level package for sta-etl."""
__author__ = """Boris Bauermeister"""
__email__ = 'Boris.Bauermeister@gmail'
__version__ = '0.1.0'
#from sta_etl import *
| """Top-level package for sta-etl."""
__author__ = 'Boris Bauermeister'
__email__ = 'Boris.Bauermeister@gmail'
__version__ = '0.1.0' |
'''
No 2. Buatlah fungsi tanpa pengembalian nilai, yaitu fungsi segitigabintang.
Misal, jika dipanggil dg segitigabintang(4), keluarannya :
*
**
***
****
'''
def segitigabintang(baris):
for i in range(baris):
print('*' * (i+1))
| """
No 2. Buatlah fungsi tanpa pengembalian nilai, yaitu fungsi segitigabintang.
Misal, jika dipanggil dg segitigabintang(4), keluarannya :
*
**
***
****
"""
def segitigabintang(baris):
for i in range(baris):
print('*' * (i + 1)) |
api_output_for_empty_months = """"Usage Data Extract",
"",
"AccountOwnerId","Account Name","ServiceAdministratorId","SubscriptionId","SubscriptionGuid","Subscription Name","Date","Month","Day","Year","Product","Meter ID","Meter Category","Meter Sub-Category","Meter Region","Meter Name","Consumed Quantity","Reso... | api_output_for_empty_months = '"Usage Data Extract",\n "",\n "AccountOwnerId","Account Name","ServiceAdministratorId","SubscriptionId","SubscriptionGuid","Subscription Name","Date","Month","Day","Year","Product","Meter ID","Meter Category","Meter Sub-Category","Meter Region","Meter Name","Consumed Quantity","Reso... |
#!/usr/bin/python3
m1 = int(input("Enter no. of rows : \t"))
n1 = int(input("Enter no. of columns : \t"))
a = []
print("Enter Matrix 1:\n")
for i in range(n1):
row = list(map(int, input().split()))
a.append(row)
print(a)
m2 = int(n1)
print("\n Your Matrix 2 must have",n1,"rows and",m1,"columns \n")
n2 ... | m1 = int(input('Enter no. of rows : \t'))
n1 = int(input('Enter no. of columns : \t'))
a = []
print('Enter Matrix 1:\n')
for i in range(n1):
row = list(map(int, input().split()))
a.append(row)
print(a)
m2 = int(n1)
print('\n Your Matrix 2 must have', n1, 'rows and', m1, 'columns \n')
n2 = int(m1)
b = []
for i i... |
# =============================================================================
# TexGen: Geometric textile modeller.
# Copyright (C) 2015 Louise Brown
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Found... | textile = c_textile()
section = c_section_lenticular(0.3, 0.14)
Section.AssignSectionMesh(c_section_mesh_triangulate(30))
yarns = (c_yarn(), c_yarn(), c_yarn(), c_yarn())
Yarns[0].AddNode(c_node(xyz(0, 0, 0)))
Yarns[0].AddNode(c_node(xyz(0.35, 0, 0.15)))
Yarns[0].AddNode(c_node(xyz(0.7, 0, 0)))
Yarns[1].AddNode(c_node(... |
# -*- coding: UTF-8 -*-
logger.info("Loading 1 objects to table invoicing_plan...")
# fields: id, user, today, journal, max_date, partner, course
loader.save(create_invoicing_plan(1,6,date(2015,3,1),1,None,None,None))
loader.flush_deferred_objects()
| logger.info('Loading 1 objects to table invoicing_plan...')
loader.save(create_invoicing_plan(1, 6, date(2015, 3, 1), 1, None, None, None))
loader.flush_deferred_objects() |
power = {'BUSES': {'Area': 1.33155,
'Bus/Area': 1.33155,
'Bus/Gate Leakage': 0.00662954,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.0691322,
'Bus/Subthreshold Leakage with power gating': 0.0259246,
'Gate... | power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres... |
# Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree.
#
# For example, given the following Node class:
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
... | class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def serialize(root, string=''):
string += root.val
string += '('
if root.left != None:
string = serialize(root.left, string)
string += '|'
if root.righ... |
store.set_global_value('hotkey', '<meta>+r')
if re.match('.*(Hyper)', window.get_active_class()):
logging.debug('terminal refresh buffer')
engine.set_return_value('<ctrl>+<shift>+r')
else:
logging.debug('normal')
engine.set_return_value('<ctrl>+r')
engine.run_script('combo') | store.set_global_value('hotkey', '<meta>+r')
if re.match('.*(Hyper)', window.get_active_class()):
logging.debug('terminal refresh buffer')
engine.set_return_value('<ctrl>+<shift>+r')
else:
logging.debug('normal')
engine.set_return_value('<ctrl>+r')
engine.run_script('combo') |
# Defining the left function
def left(i):
return 2*i+1
# Defining the right function
def right(i):
return 2*i+2
# Defining the parent node function
def parent(i):
return (i-1)//2
# Max_Heapify
def max_heapify(arr,n,i):
l=left(i)
r=right(i)
largest=i
if n>l and arr[largest]<arr[l] :
... | def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2
def parent(i):
return (i - 1) // 2
def max_heapify(arr, n, i):
l = left(i)
r = right(i)
largest = i
if n > l and arr[largest] < arr[l]:
largest = l
if n > r and arr[largest] < arr[r]:
largest = r
if large... |
#num1=int(raw_input("Enter num #1:"))
#num2=int(raw_input("Enter num #2:"))
#total= num1 + num2
#print("The sum is: "+ str(total))
# need to be a string so computer can read it
# all strings can be integers but not all integers can be strings
# num = int(raw_input("Enter a number:"))
# if num>0:
# print("That's a p... | word = 'computerz'
print(word[:5])
print(word[:-1])
print(word[4:])
print(word[-3:]) |
class SinavroObject: pass
def init(self, val): self.value = val
gencls = lambda n: type(f'Sinavro{n.title()}', (SinavroObject,), {'__init__': init, 'type': n})
SinavroInt = gencls('int')
SinavroFloat = gencls('float')
SinavroString = gencls('string')
SinavroBool = gencls('bool')
SinavroArray = gencls('array'... | class Sinavroobject:
pass
def init(self, val):
self.value = val
gencls = lambda n: type(f'Sinavro{n.title()}', (SinavroObject,), {'__init__': init, 'type': n})
sinavro_int = gencls('int')
sinavro_float = gencls('float')
sinavro_string = gencls('string')
sinavro_bool = gencls('bool')
sinavro_array = gencls('arr... |
def lambda_handler(event):
try:
first_num = event["queryStringParameters"]["firstNum"]
except KeyError:
first_num = 0
try:
second_num = event["queryStringParameters"]["secondNum"]
except KeyError:
second_num = 0
try:
operation_type = event["queryStringParame... | def lambda_handler(event):
try:
first_num = event['queryStringParameters']['firstNum']
except KeyError:
first_num = 0
try:
second_num = event['queryStringParameters']['secondNum']
except KeyError:
second_num = 0
try:
operation_type = event['queryStringParamete... |
input1 = int(input("Enter the first number: "))
input2 = int(input("Enter the second number: "))
input3 = int(input("Enter the third number: "))
input4 = int(input("Enter the fourth number: "))
input5 = int(input("Enter the fifth number: "))
tuple_num = []
tuple_num.append(input1)
tuple_num.append(input2)
tuple_nu... | input1 = int(input('Enter the first number: '))
input2 = int(input('Enter the second number: '))
input3 = int(input('Enter the third number: '))
input4 = int(input('Enter the fourth number: '))
input5 = int(input('Enter the fifth number: '))
tuple_num = []
tuple_num.append(input1)
tuple_num.append(input2)
tuple_nu... |
# Time: O(n!)
# Space: O(n)
class Solution(object):
def constructDistancedSequence(self, n):
"""
:type n: int
:rtype: List[int]
"""
def backtracking(n, i, result, lookup):
if i == len(result):
return True
if result[i]:
... | class Solution(object):
def construct_distanced_sequence(self, n):
"""
:type n: int
:rtype: List[int]
"""
def backtracking(n, i, result, lookup):
if i == len(result):
return True
if result[i]:
return backtracking(n, i ... |
#Longest Common Prefix in python
#Implementation of python program to find the longest common prefix amongst the given list of strings.
#If there is no common prefix then returning 0.
#define the function to evaluate the longest common prefix
def longestCommonPrefix(s):
p = '' #declare an empty s... | def longest_common_prefix(s):
p = ''
for i in range(len(min(s, key=len))):
f = s[0][i]
for j in s[1:]:
if j[i] != f:
return p
p += f
return p
n = int(input('Enter the number of names in list for input:'))
print('Enter the Strings:')
s = [input() for i in r... |
#!/usr/bin/env python
P = int(input())
for _ in range(P):
N, n, m = [int(i) for i in input().split()]
print(f"{N} {(n - m) * m + 1}")
| p = int(input())
for _ in range(P):
(n, n, m) = [int(i) for i in input().split()]
print(f'{N} {(n - m) * m + 1}') |
def handler(event, context):
return {
"statusCode": 302,
"headers": {
"Location": "https://www.nhsx.nhs.uk/covid-19-response/data-and-covid-19/national-covid-19-chest-imaging-database-nccid/"
},
}
| def handler(event, context):
return {'statusCode': 302, 'headers': {'Location': 'https://www.nhsx.nhs.uk/covid-19-response/data-and-covid-19/national-covid-19-chest-imaging-database-nccid/'}} |
__name__ = 'factory_djoy'
__version__ = '2.2.0'
__author__ = 'James Cooke'
__copyright__ = '2021, {}'.format(__author__)
__description__ = 'Factories for Django, creating valid model instances every time.'
__email__ = 'github@jamescooke.info'
| __name__ = 'factory_djoy'
__version__ = '2.2.0'
__author__ = 'James Cooke'
__copyright__ = '2021, {}'.format(__author__)
__description__ = 'Factories for Django, creating valid model instances every time.'
__email__ = 'github@jamescooke.info' |
class CyclesMeshSettings:
pass
| class Cyclesmeshsettings:
pass |
l = ["+", "-"]
def backRec(x):
for j in l:
x.append(j)
if consistent(x):
if solution(x):
solutionFound(x)
backRec(x)
x.pop()
def consistent(s):
return len(s) < n
def solution(s):
summ = list2[0]
if not len(s) == n -... | l = ['+', '-']
def back_rec(x):
for j in l:
x.append(j)
if consistent(x):
if solution(x):
solution_found(x)
back_rec(x)
x.pop()
def consistent(s):
return len(s) < n
def solution(s):
summ = list2[0]
if not len(s) == n - 1:
return ... |
# block between mission & 6th and howard & 5th in SF.
# appears to have lots of buses.
# https://www.openstreetmap.org/way/88572932 -- Mission St
# https://www.openstreetmap.org/relation/3406710 -- 14X to Daly City
# https://www.openstreetmap.org/relation/3406709 -- 14X to Downtown
# https://www.openstreetmap.org/relat... | (z, x, y) = (16, 10484, 25329)
while z >= 12:
assert_has_feature(z, x, y, 'roads', {'is_bus_route': True})
(z, x, y) = (z - 1, x / 2, y / 2)
assert_no_matching_feature(z, x, y, 'roads', {'is_bus_route': True}) |
class Zoo:
def __init__(self, name, locations):
self.name = name
self.stillActive = True
self.locations = locations
self.currentLocation = self.locations[1]
def changeLocation(self, direction):
neighborID = self.currentLocation.neighbors[direction]
self.currentLo... | class Zoo:
def __init__(self, name, locations):
self.name = name
self.stillActive = True
self.locations = locations
self.currentLocation = self.locations[1]
def change_location(self, direction):
neighbor_id = self.currentLocation.neighbors[direction]
self.curren... |
UNKNOWN = u''
def describe_track(track):
"""
Prepare a short human-readable Track description.
track (mopidy.models.Track): Track to source song data from.
"""
title = track.name or UNKNOWN
# Simple/regular case: normal song (e.g. from Spotify).
if track.artists:
artist = next(it... | unknown = u''
def describe_track(track):
"""
Prepare a short human-readable Track description.
track (mopidy.models.Track): Track to source song data from.
"""
title = track.name or UNKNOWN
if track.artists:
artist = next(iter(track.artists)).name
elif track.album and track.album.a... |
# -*- coding: utf-8 -*-
class Tile(int):
TILES = '''
1s 2s 3s 4s 5s 6s 7s 8s 9s
1p 2p 3p 4p 5p 6p 7p 8p 9p
1m 2m 3m 4m 5m 6m 7m 8m 9m
ew sw ww nw
wd gd rd
'''.split()
def as_data(self):
return self.TILES[self // 4]
class TilesConverter(object):
@stat... | class Tile(int):
tiles = '\n 1s 2s 3s 4s 5s 6s 7s 8s 9s\n 1p 2p 3p 4p 5p 6p 7p 8p 9p\n 1m 2m 3m 4m 5m 6m 7m 8m 9m\n ew sw ww nw\n wd gd rd\n '.split()
def as_data(self):
return self.TILES[self // 4]
class Tilesconverter(object):
@staticmethod
def to_one_l... |
def test_get_news(sa_session, sa_backend, sa_child_news):
assert(sa_child_news == sa_backend.get_news(sa_child_news.id))
assert(sa_backend.get_news(None) is None)
def test_get_news_list(sa_session, sa_backend, sa_child_news):
assert(sa_child_news in sa_backend.get_news_list())
assert(sa_child_news in ... | def test_get_news(sa_session, sa_backend, sa_child_news):
assert sa_child_news == sa_backend.get_news(sa_child_news.id)
assert sa_backend.get_news(None) is None
def test_get_news_list(sa_session, sa_backend, sa_child_news):
assert sa_child_news in sa_backend.get_news_list()
assert sa_child_news in sa_b... |
# Implemented from: https://stackoverflow.com/questions/9501337/binary-search-algorithm-in-python
def binary_search(sequence, value):
lo, hi = 0, len(sequence) - 1
while lo <= hi:
mid = (lo + hi) // 2
if sequence[mid] < value:
lo = mid + 1
elif value < sequence[mid]:
... | def binary_search(sequence, value):
(lo, hi) = (0, len(sequence) - 1)
while lo <= hi:
mid = (lo + hi) // 2
if sequence[mid] < value:
lo = mid + 1
elif value < sequence[mid]:
hi = mid - 1
else:
return mid
return None
def dfs(graph, node, vi... |
'''
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to... | """
Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
Example:
Given array nums = [-1, 2, 1, -4], and target = 1.
The sum that is closest to... |
"""An extension for workspace rules."""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("//:dependencies.bzl", "dependencies")
def _workspace_dependencies_impl(ctx):
platform = ctx.os.name if ctx.os.name != "mac os x" else "darwin"
for dependency in dependencies:
ctx.download(
executabl... | """An extension for workspace rules."""
load('@bazel_skylib//lib:paths.bzl', 'paths')
load('//:dependencies.bzl', 'dependencies')
def _workspace_dependencies_impl(ctx):
platform = ctx.os.name if ctx.os.name != 'mac os x' else 'darwin'
for dependency in dependencies:
ctx.download(executable=True, output... |
def print_lol(arr):
for row in arr:
if (isinstance(row, list)):
print_lol(row)
else:
print
row
| def print_lol(arr):
for row in arr:
if isinstance(row, list):
print_lol(row)
else:
print
row |
class Source:
"""Source class to define News Source Objects"""
def __init__(self,id,name,description,url,category,country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
self.country = country
class Article:... | class Source:
"""Source class to define News Source Objects"""
def __init__(self, id, name, description, url, category, country):
self.id = id
self.name = name
self.description = description
self.url = url
self.category = category
self.country = country
class Ar... |
def cwinstart(callobj, *args, **kwargs):
print('cwinstart')
print(' args', repr(args))
for arg in args:
print(' ', arg)
print(' kwargs', len(kwargs))
for k, v in kwargs.items():
print(' ', k, v)
w = callobj(*args, **kwargs)
print(' callobj()->', w)
return w
def cwincall(req1, req2, ... | def cwinstart(callobj, *args, **kwargs):
print('cwinstart')
print(' args', repr(args))
for arg in args:
print(' ', arg)
print(' kwargs', len(kwargs))
for (k, v) in kwargs.items():
print(' ', k, v)
w = callobj(*args, **kwargs)
print(' callobj()->', w)
return w
de... |
#!/usr/bin/env python3
# Copyright (C) 2020-2021 The btclib developers
#
# This file is part of btclib. It is subject to the license terms in the
# LICENSE file found in the top-level directory of this distribution.
#
# No part of btclib including this file, may be copied, modified, propagated,
# or distributed except... | """__init__ module for the btclib package."""
name = 'btclib'
__version__ = '2021.1'
__author__ = 'The btclib developers'
__author_email__ = 'devs@btclib.org'
__copyright__ = 'Copyright (C) 2017-2021 The btclib developers'
__license__ = 'MIT License' |
for num in range(1,6):
#code inside for loop
if num == 4:
continue
#code inside for loop
print(num)
#code outside for loop
print("continue statement executed on num = 4")
| for num in range(1, 6):
if num == 4:
continue
print(num)
print('continue statement executed on num = 4') |
def get_remain(cpf: str, start: int, upto: int) -> int:
total = 0
for count, num in enumerate(cpf[:upto]):
try:
total += int(num) * (start - count)
except ValueError:
return None
remain = (total * 10) % 11
remain = remain if remain != 10 else 0
... | def get_remain(cpf: str, start: int, upto: int) -> int:
total = 0
for (count, num) in enumerate(cpf[:upto]):
try:
total += int(num) * (start - count)
except ValueError:
return None
remain = total * 10 % 11
remain = remain if remain != 10 else 0
return remain
... |
class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
def get_name(self):
return self.name
def get_hours(self):
return self.hours
def get_qpoints(self):
return self.qpoints
... | class Student:
def __init__(self, name, hours, qpoints):
self.name = name
self.hours = float(hours)
self.qpoints = float(qpoints)
def get_name(self):
return self.name
def get_hours(self):
return self.hours
def get_qpoints(self):
return self.qpoints
... |
class Solution:
def firstUniqChar(self, s):
table = {}
for ele in s:
table[ele] = table.get(ele, 0) + 1
# for i in range(len(s)):
# if table[s[i]] == 1:
# return i
for ele in s:
if table[ele] == 1:
return s.index(ele... | class Solution:
def first_uniq_char(self, s):
table = {}
for ele in s:
table[ele] = table.get(ele, 0) + 1
for ele in s:
if table[ele] == 1:
return s.index(ele)
return -1
if __name__ == '__main__':
s = 'leetcode'
print(solution().firstU... |
#program to compute and print sum of two given integers (more than or equal to zero).
# If given integers or the sum have more than 80 digits, print "overflow".
print("Input first integer:")
x = int(input())
print("Input second integer:")
y = int(input())
if x >= 10 ** 80 or y >= 10 ** 80 or x + y >= 10 ** 80:
pri... | print('Input first integer:')
x = int(input())
print('Input second integer:')
y = int(input())
if x >= 10 ** 80 or y >= 10 ** 80 or x + y >= 10 ** 80:
print('Overflow!')
else:
print('Sum of the two integers: ', x + y) |
{
"targets": [
{
"target_name": "allofw",
"include_dirs": [
"<!@(pkg-config liballofw --cflags-only-I | sed s/-I//g)",
"<!(node -e \"require('nan')\")"
],
"libraries": [
"<!@(pkg-config liballofw --libs)",
"<!@(pkg-config glew --libs)",
],
"cflag... | {'targets': [{'target_name': 'allofw', 'include_dirs': ['<!@(pkg-config liballofw --cflags-only-I | sed s/-I//g)', '<!(node -e "require(\'nan\')")'], 'libraries': ['<!@(pkg-config liballofw --libs)', '<!@(pkg-config glew --libs)'], 'cflags!': ['-fno-exceptions', '-fno-rtti'], 'cflags_cc!': ['-fno-exceptions', '-fno-rtt... |
TOKEN_PREALTA_CLIENTE = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InJhdWx0ckBnbWFpbC5jb20iLCJleHAiOjQ3MzM1MTA0MDAsIm93bmVyX25hbWUiOiJSYXVsIEVucmlxdWUgVG9ycmVzIFJleWVzIiwidHlwZSI6ImVtYWlsX2NvbmZpcm1hdGlvbl9uZXdfY2xpZW50In0.R-nXh1nXvlBABfEdV1g81mdIzJqMFLvFV7FAP7PQRCM'
TOKEN_PREALTA_CLIENTE_CADUCO = 'eyJ0eXAiOiJ... | token_prealta_cliente = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJlbWFpbCI6InJhdWx0ckBnbWFpbC5jb20iLCJleHAiOjQ3MzM1MTA0MDAsIm93bmVyX25hbWUiOiJSYXVsIEVucmlxdWUgVG9ycmVzIFJleWVzIiwidHlwZSI6ImVtYWlsX2NvbmZpcm1hdGlvbl9uZXdfY2xpZW50In0.R-nXh1nXvlBABfEdV1g81mdIzJqMFLvFV7FAP7PQRCM'
token_prealta_cliente_caduco = 'eyJ0eXAiOiJKV... |
SRM_TO_HEX = {
"0": "#FFFFFF",
"1": "#F3F993",
"2": "#F5F75C",
"3": "#F6F513",
"4": "#EAE615",
"5": "#E0D01B",
"6": "#D5BC26",
"7": "#CDAA37",
"8": "#C1963C",
"9": "#BE8C3A",
"10": "#BE823A",
"11": "#C17A37",
"12": "#BF7138",
"13": "#BC6733",
"14": "#B26033",
... | srm_to_hex = {'0': '#FFFFFF', '1': '#F3F993', '2': '#F5F75C', '3': '#F6F513', '4': '#EAE615', '5': '#E0D01B', '6': '#D5BC26', '7': '#CDAA37', '8': '#C1963C', '9': '#BE8C3A', '10': '#BE823A', '11': '#C17A37', '12': '#BF7138', '13': '#BC6733', '14': '#B26033', '15': '#A85839', '16': '#985336', '17': '#8D4C32', '18': '#7C... |
# ------ [ API ] ------
API = '/api'
# ---------- [ BLOCKCHAIN ] ----------
API_BLOCKCHAIN = f'{API}/blockchain'
API_BLOCKCHAIN_LENGTH = f'{API_BLOCKCHAIN}/length'
API_BLOCKCHAIN_BLOCKS = f'{API_BLOCKCHAIN}/blocks'
# ---------- [ BROADCASTS ] ----------
API_BROADCASTS = f'{API}/broadcasts'
API_BROADCASTS_NEW_BLOCK =... | api = '/api'
api_blockchain = f'{API}/blockchain'
api_blockchain_length = f'{API_BLOCKCHAIN}/length'
api_blockchain_blocks = f'{API_BLOCKCHAIN}/blocks'
api_broadcasts = f'{API}/broadcasts'
api_broadcasts_new_block = f'{API_BROADCASTS}/new_block'
api_broadcasts_new_transaction = f'{API_BROADCASTS}/new_transaction'
api_t... |
#tables or h5py
libname="h5py" #tables"
#libname="tables"
def setlib(name):
global libname
libname = name
| libname = 'h5py'
def setlib(name):
global libname
libname = name |
if __name__ == "__main__":
pages = [5, 4, 3, 2, 1, 4, 3, 5, 4, 3, 2, 1, 5]
faults = {3: 0, 4: 0}
for frames in faults:
memory = []
for page in pages:
out = None
if page not in memory:
if len(memory) == frames:
out =... | if __name__ == '__main__':
pages = [5, 4, 3, 2, 1, 4, 3, 5, 4, 3, 2, 1, 5]
faults = {3: 0, 4: 0}
for frames in faults:
memory = []
for page in pages:
out = None
if page not in memory:
if len(memory) == frames:
out = memory.pop(0)
... |
a={'a':'hello','b':'1','c':'jayalatha','d':[1,2]}
d={}
val=list(a.values())
val.sort(key=len)
print(val)
for i in val:
for j in a:
if(i==a[j]):
d.update({j:a[j]})
print(d)
| a = {'a': 'hello', 'b': '1', 'c': 'jayalatha', 'd': [1, 2]}
d = {}
val = list(a.values())
val.sort(key=len)
print(val)
for i in val:
for j in a:
if i == a[j]:
d.update({j: a[j]})
print(d) |
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 04 17:37:37 2015
@author: Kevin
"""
| """
Created on Wed Nov 04 17:37:37 2015
@author: Kevin
""" |
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_library", "core_resx", "core_xunit_test")
core_resx(
name = "core_resource",
src = ":src/Moq/Properties/Resources.resx",
identifier = "Moq.Properties.Resources.resources",
)
core_library(
name = "Moq.dll",
srcs = glob(["src/Moq/**/*.cs"]),
... | load('@io_bazel_rules_dotnet//dotnet:defs.bzl', 'core_library', 'core_resx', 'core_xunit_test')
core_resx(name='core_resource', src=':src/Moq/Properties/Resources.resx', identifier='Moq.Properties.Resources.resources')
core_library(name='Moq.dll', srcs=glob(['src/Moq/**/*.cs']), defines=['NETCORE'], keyfile=':Moq.snk',... |
# Time: O(n^2)
# Space: O(n)
# Given an array of unique integers, each integer is strictly greater than 1.
# We make a binary tree using these integers and each number may be used for
# any number of times.
# Each non-leaf node's value should be equal to the product of the values of
# it's children.
# How many binary... | try:
xrange
except NameError:
xrange = range
class Solution(object):
def num_factored_binary_trees(self, A):
"""
:type A: List[int]
:rtype: int
"""
m = 10 ** 9 + 7
A.sort()
dp = {}
for i in xrange(len(A)):
dp[A[i]] = 1
... |
class reversor:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __lt__(self, other):
"""
Inverted it to be able to sort in descending order.
"""
return self.value >= other.value
if __name__ == '__... | class Reversor:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
def __lt__(self, other):
"""
Inverted it to be able to sort in descending order.
"""
return self.value >= other.value
if __name__ == '__m... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Yue-Wen FANG'
__maintainer__ = "Yue-Wen FANG"
__email__ = 'fyuewen@gmail.com'
__license__ = 'Apache License 2.0'
__creation_date__= 'Dec. 25, 2018'
"""
This example shows the functionality
of positional arguments and keyword ONLY arguments.
The positional a... | __author__ = 'Yue-Wen FANG'
__maintainer__ = 'Yue-Wen FANG'
__email__ = 'fyuewen@gmail.com'
__license__ = 'Apache License 2.0'
__creation_date__ = 'Dec. 25, 2018'
'\nThis example shows the functionality\nof positional arguments and keyword ONLY arguments.\n\nThe positional arguments correspond to tuple,\nthe keyword ON... |
"""
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ \
1 0
/ \
1 0
/ \
1 1
"""
class Node... | """
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
0
/ 1 0
/ 1 0
/ 1 1
"""
class Node:
def __init__(self... |
# Iterations: Definite Loops
'''
Use the 'for' word
there is a iteration variable like 'i' or 'friend'
'''
# for i in [5, 4, 3, 2, 1] :
# print(i)
# print('Blastoff!')
# friends = ['matheus', 'wataru', 'mogli']
# for friend in friends :
# print('happy new year:', friend)
# print('Done!')
| """
Use the 'for' word
there is a iteration variable like 'i' or 'friend'
""" |
class formstruct():
name = str()
while True:
name = input("\n.bot >> enter your first name:")
if not name.isalpha():
print(".bot >> your first name must have alphabets only!")
continue
else:
name = name.upper()
break
city = str()
while True:
c... | class Formstruct:
name = str()
while True:
name = input('\n.bot >> enter your first name:')
if not name.isalpha():
print('.bot >> your first name must have alphabets only!')
continue
else:
name = name.upper()
break
city = str()
whil... |
#
# @lc app=leetcode id=719 lang=python3
#
# [719] Find K-th Smallest Pair Distance
#
# https://leetcode.com/problems/find-k-th-smallest-pair-distance/description/
#
# algorithms
# Hard (30.99%)
# Likes: 827
# Dislikes: 30
# Total Accepted: 29.9K
# Total Submissions: 96.4K
# Testcase Example: '[1,3,1]\n1'
#
# Gi... | class Solution:
def smallest_distance_pair(self, nums: List[int], k: int) -> int:
n = len(nums)
nums = sorted(nums)
low = 0
high = nums[n - 1] - nums[0]
while low < high:
mid = int((low + high) / 2)
(left, count) = (0, 0)
for right in rang... |
def chess_knight(start, moves):
def knight_can_move(from_pos, to_pos):
return set(map(lambda x: abs(ord(x[0]) - ord(x[1])), zip(from_pos, to_pos))) == {1, 2}
def knight_moves(pos):
return {f + r for f in 'abcdefgh' for r in '12345678' if knight_can_move(pos, f + r)}
# till ... | def chess_knight(start, moves):
def knight_can_move(from_pos, to_pos):
return set(map(lambda x: abs(ord(x[0]) - ord(x[1])), zip(from_pos, to_pos))) == {1, 2}
def knight_moves(pos):
return {f + r for f in 'abcdefgh' for r in '12345678' if knight_can_move(pos, f + r)}
res = knight_moves(star... |
n = str(input())
if("0000000" in n):
print("YES")
elif("1111111" in n):
print("YES")
else:
print("NO")
| n = str(input())
if '0000000' in n:
print('YES')
elif '1111111' in n:
print('YES')
else:
print('NO') |
list = ['a','b','c']
print(list)
| list = ['a', 'b', 'c']
print(list) |
#
# Copyright 2017 ABSA Group Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | sc._jvm.za.co.absa.spline.harvester.SparkLineageInitializer.enableLineageTracking(spark._jsparkSession)
spark.read.option('header', 'true').option('inferschema', 'true').csv('data/input/batch/wikidata.csv').write.mode('overwrite').csv('data/output/batch/python-sample.csv') |
""" Darshan Error classes and functions. """
class DarshanBaseError(Exception):
"""
Base exception class for Darshan errors in Python.
"""
pass
class DarshanVersionError(NotImplementedError):
"""
Raised when using a feature which is not provided by libdarshanutil.
"""
min_version = ... | """ Darshan Error classes and functions. """
class Darshanbaseerror(Exception):
"""
Base exception class for Darshan errors in Python.
"""
pass
class Darshanversionerror(NotImplementedError):
"""
Raised when using a feature which is not provided by libdarshanutil.
"""
min_version = Non... |
file = open("input.txt", "r")
num_valid = 0
for line in file:
# policy = part before colon
policy = line.strip().split(":")[0]
# get min/max number allowed for given letter
min_max = policy.split(" ")[0]
letter = policy.split(" ")[1]
min = int(min_max.split("-")[0])
max = int(min_max.split("-")[1])
... | file = open('input.txt', 'r')
num_valid = 0
for line in file:
policy = line.strip().split(':')[0]
min_max = policy.split(' ')[0]
letter = policy.split(' ')[1]
min = int(min_max.split('-')[0])
max = int(min_max.split('-')[1])
password = line.strip().split(':')[1]
if password.count(letter) >= ... |
# Problem code
def search(nums, target):
return search_helper(nums, target, 0, len(nums) - 1)
def search_helper(nums, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
# right part is good
if nums[mid] <= nums[right]:
# we fall for it
if target >= ... | def search(nums, target):
return search_helper(nums, target, 0, len(nums) - 1)
def search_helper(nums, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
if nums[mid] <= nums[right]:
if target >= nums[mid] and target <= nums[right]:
return binary_sear... |
#
# PySNMP MIB module CISCO-EMBEDDED-EVENT-MGR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EMBEDDED-EVENT-MGR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:39:13 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python vers... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_range_constraint, constraints_union, value_size_constraint) ... |
screen_resX=1920
screen_resY=1080
img_id=['1.JPG_HIGH_',
'2.JPG_HIGH_',
'7.JPG_HIGH_',
'12.JPG_HIGH_',
'13.JPG_HIGH_',
'15.JPG_HIGH_',
'19.JPG_HIGH_',
'25.JPG_HIGH_',
'27.JPG_HIGH_',
'29.JPG_HIGH_',
'41.JPG_HIGH_',
'42.JPG_HIGH_',... | screen_res_x = 1920
screen_res_y = 1080
img_id = ['1.JPG_HIGH_', '2.JPG_HIGH_', '7.JPG_HIGH_', '12.JPG_HIGH_', '13.JPG_HIGH_', '15.JPG_HIGH_', '19.JPG_HIGH_', '25.JPG_HIGH_', '27.JPG_HIGH_', '29.JPG_HIGH_', '41.JPG_HIGH_', '42.JPG_HIGH_', '43.JPG_HIGH_', '44.JPG_HIGH_', '48.JPG_HIGH_', '49.JPG_HIGH_', '51.JPG_HIGH_', '... |
def create_matrix(rows_count):
matrix = []
for _ in range(rows_count):
matrix.append([int(x) for x in input().split(', ')])
return matrix
def get_square_sum(row, col, matrix):
square_sum = 0
for r in range(row, row + 2):
for c in range(col, col + 2):
square_sum += matri... | def create_matrix(rows_count):
matrix = []
for _ in range(rows_count):
matrix.append([int(x) for x in input().split(', ')])
return matrix
def get_square_sum(row, col, matrix):
square_sum = 0
for r in range(row, row + 2):
for c in range(col, col + 2):
square_sum += matrix... |
#!/usr/bin/env python3
# Diodes
"1N4148"
"1N5817G"
"BAT43" # Zener
"1N457"
# bc junction of many transistors can also be used as dioded, i.e. 2SC1815, 2SA9012, etc. with very small leakage current (~1pA at -4V).
| """1N4148"""
'1N5817G'
'BAT43'
'1N457' |
clientId = 'CLIENT_ID'
clientSecret = 'CLIENT_SECRET'
geniusToken = 'GENIUS_TOKEN'
bitrate = '320' | client_id = 'CLIENT_ID'
client_secret = 'CLIENT_SECRET'
genius_token = 'GENIUS_TOKEN'
bitrate = '320' |
'''
Created on Jun 15, 2016
@author: eze
'''
class NotFoundException(Exception):
'''
classdocs
'''
def __init__(self, element):
'''
Constructor
'''
self.elementNotFound = element
def __str__(self, *args, **kwargs):
return "NotFoundException(%s)" %... | """
Created on Jun 15, 2016
@author: eze
"""
class Notfoundexception(Exception):
"""
classdocs
"""
def __init__(self, element):
"""
Constructor
"""
self.elementNotFound = element
def __str__(self, *args, **kwargs):
return 'NotFoundException(%s)' % self.ele... |
# Solution to the practise problem
# https://automatetheboringstuff.com/chapter6/
# Table Printer
def printTable(tableList):
"""Prints the list of list of strings with each column right justified"""
colWidth = 0
for row in tableList:
colWidth = max(colWidth, max([len(x) for x in row]))
col... | def print_table(tableList):
"""Prints the list of list of strings with each column right justified"""
col_width = 0
for row in tableList:
col_width = max(colWidth, max([len(x) for x in row]))
col_width += 1
printed_table = ''
table_list = [[row[i] for row in tableList] for i in range(len... |
class Contact:
def __init__(self, first_name = None, last_name = None, mobile_phone = None):
self.first_name = first_name
self.last_name = last_name
self.mobile_phone = mobile_phone | class Contact:
def __init__(self, first_name=None, last_name=None, mobile_phone=None):
self.first_name = first_name
self.last_name = last_name
self.mobile_phone = mobile_phone |
class Solution(object):
def shortestToChar(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
pl = []
ret = [0] * len(S)
for i in range(0, len(S)):
if S[i] == C:
pl.append(i)
for i in range(... | class Solution(object):
def shortest_to_char(self, S, C):
"""
:type S: str
:type C: str
:rtype: List[int]
"""
pl = []
ret = [0] * len(S)
for i in range(0, len(S)):
if S[i] == C:
pl.append(i)
for i in range(0, len(S)... |
# Optional solution with tidy data representation (providing x and y)
monthly_victim_counts_melt = monthly_victim_counts.reset_index().melt(
id_vars="datetime", var_name="victim_type", value_name="count"
)
sns.relplot(
data=monthly_victim_counts_melt,
x="datetime",
y="count",
hue="victim_type",
... | monthly_victim_counts_melt = monthly_victim_counts.reset_index().melt(id_vars='datetime', var_name='victim_type', value_name='count')
sns.relplot(data=monthly_victim_counts_melt, x='datetime', y='count', hue='victim_type', kind='line', palette='colorblind', height=3, aspect=4) |
def findSmallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
newarr = []
for i in range(len(arr)):
smallest... | def find_smallest(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
newarr = []
for i in range(len(arr)):
smallest_index = find... |
{
'Hello World':'Salve Mondo',
'Welcome to web2py':'Ciao da wek2py',
}
| {'Hello World': 'Salve Mondo', 'Welcome to web2py': 'Ciao da wek2py'} |
domain='https://monbot.hopto.org'
apm_id='admin'
apm_pw='New1234!'
apm_url='https://monbot.hopto.org:3000'
db_host='monbot.hopto.org'
db_user='izyrtm'
db_pw='new1234!'
db_datadbase='monbot' | domain = 'https://monbot.hopto.org'
apm_id = 'admin'
apm_pw = 'New1234!'
apm_url = 'https://monbot.hopto.org:3000'
db_host = 'monbot.hopto.org'
db_user = 'izyrtm'
db_pw = 'new1234!'
db_datadbase = 'monbot' |
def norm(x, ord=None, axis=None):
# TODO(beam2d): Implement it
raise NotImplementedError
def cond(x, p=None):
# TODO(beam2d): Implement it
raise NotImplementedError
def det(a):
# TODO(beam2d): Implement it
raise NotImplementedError
def matrix_rank(M, tol=None):
# TODO(beam2d): Implemen... | def norm(x, ord=None, axis=None):
raise NotImplementedError
def cond(x, p=None):
raise NotImplementedError
def det(a):
raise NotImplementedError
def matrix_rank(M, tol=None):
raise NotImplementedError
def slogdet(a):
raise NotImplementedError
def trace(a, offset=0, axis1=0, axis2=1, dtype=None,... |
def load():
with open("input") as f:
yield next(f).strip()
next(f)
for x in f:
yield x.strip().split(" -> ")
def pair_insertion():
data = list(load())
polymer, rules = list(data[0]), dict(data[1:])
for _ in range(10):
new_polymer = [polymer[0]]
for... | def load():
with open('input') as f:
yield next(f).strip()
next(f)
for x in f:
yield x.strip().split(' -> ')
def pair_insertion():
data = list(load())
(polymer, rules) = (list(data[0]), dict(data[1:]))
for _ in range(10):
new_polymer = [polymer[0]]
fo... |
def compChooseWord(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
This word should be calculated by considering all the words
in the wordList.
If no words in the wordList can be made from the hand, return None.
hand: ... | def comp_choose_word(hand, wordList, n):
"""
Given a hand and a wordList, find the word that gives
the maximum value score, and return it.
This word should be calculated by considering all the words
in the wordList.
If no words in the wordList can be made from the hand, return None.
hand... |
class Colors:
END = '\033[0m'
ERROR = '\033[91m[ERROR] '
INFO = '\033[94m[INFO] '
WARN = '\033[93m[WARN] '
def get_color(msg_type):
if msg_type == 'ERROR':
return Colors.ERROR
elif msg_type == 'INFO':
return Colors.INFO
elif msg_type == 'WARN':
return Colors.WARN
else:
return Colors.END... | class Colors:
end = '\x1b[0m'
error = '\x1b[91m[ERROR] '
info = '\x1b[94m[INFO] '
warn = '\x1b[93m[WARN] '
def get_color(msg_type):
if msg_type == 'ERROR':
return Colors.ERROR
elif msg_type == 'INFO':
return Colors.INFO
elif msg_type == 'WARN':
return Colors.WARN
... |
def naive_string_matching(t, w, n, m):
for i in range(n - m + 1):
j = 0
while j < m and t[i + j + 1] == w[j + 1]:
j = j + 1
if j == m:
return True
return False | def naive_string_matching(t, w, n, m):
for i in range(n - m + 1):
j = 0
while j < m and t[i + j + 1] == w[j + 1]:
j = j + 1
if j == m:
return True
return False |
# Leo colorizer control file for kivy mode.
# This file is in the public domain.
# Properties for kivy mode.
properties = {
"ignoreWhitespace": "false",
"lineComment": "#",
}
# Attributes dict for kivy_main ruleset.
kivy_main_attributes_dict = {
"default": "null",
"digit_re": "",
"esc... | properties = {'ignoreWhitespace': 'false', 'lineComment': '#'}
kivy_main_attributes_dict = {'default': 'null', 'digit_re': '', 'escape': '', 'highlight_digits': 'true', 'ignore_case': 'true', 'no_word_sep': ''}
attributes_dict_dict = {'kivy_main': kivy_main_attributes_dict}
kivy_main_keywords_dict = {'app': 'keyword2',... |
"""
Information on the Rozier Cipher can be found at:
https://www.dcode.fr/rozier-cipher
ROZIER.py
Written by: MrLukeKR
Updated: 16/10/2020
"""
# The Rozier cipher needs a string based key, which can be constant for ease
# or changed for each message, for better security
constant_key = "DCODE"
def encrypt(plaintext:... | """
Information on the Rozier Cipher can be found at:
https://www.dcode.fr/rozier-cipher
ROZIER.py
Written by: MrLukeKR
Updated: 16/10/2020
"""
constant_key = 'DCODE'
def encrypt(plaintext: str, key: str=constant_key):
"""
Encrypts a plaintext string using the Rozier cipher and a constant key.
Optionally,... |
"""
Title: 0035 - Search Insert Position
Tags: Binary Search
Time: O(logn)
Space: O(1)
Source: https://leetcode.com/problems/search-insert-position/
Difficulty: Easy
"""
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype:... | """
Title: 0035 - Search Insert Position
Tags: Binary Search
Time: O(logn)
Space: O(1)
Source: https://leetcode.com/problems/search-insert-position/
Difficulty: Easy
"""
class Solution(object):
def search_insert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtyp... |
"""Class static method test"""
class TestClass():
"""Test class"""
def __init__(self, a=1, b=2):
self.a = a
self.b = b
def add(self):
return self.a + self.b
@staticmethod
def static_add(a, b):
return 2 * a + 2 * b
def add2(self):
return self.static_a... | """Class static method test"""
class Testclass:
"""Test class"""
def __init__(self, a=1, b=2):
self.a = a
self.b = b
def add(self):
return self.a + self.b
@staticmethod
def static_add(a, b):
return 2 * a + 2 * b
def add2(self):
return self.static_add(... |
# -*- coding: utf-8 -*-
def case_insensitive_string(string, available, default=None):
if string is None:
return default
_available = [each.lower() for each in available]
try:
index = _available.index(f"{string}".lower())
except ValueError:
raise ValueError(f"unrecognised in... | def case_insensitive_string(string, available, default=None):
if string is None:
return default
_available = [each.lower() for each in available]
try:
index = _available.index(f'{string}'.lower())
except ValueError:
raise value_error(f"unrecognised input ('{string}') - must be in... |
begin_unit
comment|'# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory'
nl|'\n'
comment|'# All Rights Reserved'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with t... | begin_unit
comment | '# Copyright (c) 2014 The Johns Hopkins University/Applied Physics Laboratory'
nl | '\n'
comment | '# All Rights Reserved'
nl | '\n'
comment | '#'
nl | '\n'
comment | '# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl | '\n'
comment | '# not use this file except in... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2019/5/5 12:39 AM
@Author : sweetcs
@Site :
@File : config.py
@Software: PyCharm
"""
DEBUG=True
HOST="0.0.0.0"
PORT=9292 | """
@Time : 2019/5/5 12:39 AM
@Author : sweetcs
@Site :
@File : config.py
@Software: PyCharm
"""
debug = True
host = '0.0.0.0'
port = 9292 |
# What should be printing the next snippet of code?
intNum = 10
negativeNum = -5
testString = "Hello "
testList = [1, 2, 3]
print(intNum * 5)
print(intNum - negativeNum)
print(testString + 'World')
print(testString * 2)
print(testString[-1])
print(testString[1:])
print(testList + testList)
# The sum of each three fir... | int_num = 10
negative_num = -5
test_string = 'Hello '
test_list = [1, 2, 3]
print(intNum * 5)
print(intNum - negativeNum)
print(testString + 'World')
print(testString * 2)
print(testString[-1])
print(testString[1:])
print(testList + testList)
matrix = [[1, 1, 1, 3], [2, 2, 2, 7], [3, 3, 3, 9], [4, 4, 4, 13]]
matrix[1][... |
# THIS FILE IS GENERATED FROM NUMPY SETUP.PY
short_version = '1.9.0'
version = '1.9.0'
full_version = '1.9.0'
git_revision = '07601a64cdfeb1c0247bde1294ad6380413cab66'
release = True
if not release:
version = full_version
| short_version = '1.9.0'
version = '1.9.0'
full_version = '1.9.0'
git_revision = '07601a64cdfeb1c0247bde1294ad6380413cab66'
release = True
if not release:
version = full_version |
"""Given a string and a pattern, find all anagrams of the pattern in the given string.
Write a function to return a list of starting indices of the anagrams of the pattern
in the given string."""
"""Example: String="ppqp", Pattern="pq", Output = [1, 2] """
def find_string_anagrams(str1, pattern):
result... | """Given a string and a pattern, find all anagrams of the pattern in the given string.
Write a function to return a list of starting indices of the anagrams of the pattern
in the given string."""
'Example: String="ppqp", Pattern="pq", Output = [1, 2] '
def find_string_anagrams(str1, pattern):
result_index... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.