content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def general_poly (L):
""" L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """
#YOUR CODE HERE
def returnFunction(x):
listCopy = L
indexNum = len(L) - 1
polyValue = 0
... | def general_poly(L):
""" L, a list of numbers (n0, n1, n2, ... nk)
Returns a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0 """
def return_function(x):
list_copy = L
index_num = len(L) - 1
poly_value = 0
for item in li... |
#
# @lc app=leetcode id=209 lang=python3
#
# [209] Minimum Size Subarray Sum
#
# @lc code=start
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:
"""
Two pointers
Time complexity : O(n)
Space complexity: O(1)
"""
ans = float('inf')
... | class Solution:
def min_sub_array_len(self, target: int, nums: List[int]) -> int:
"""
Two pointers
Time complexity : O(n)
Space complexity: O(1)
"""
ans = float('inf')
left = 0
s = 0
for i in range(len(nums)):
s += nums[i]
... |
#
# PySNMP MIB module EQUIPMENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EQUIPMENT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:51:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) ... |
SOURCE_GOOGLE_DRIVE = "GoogleDrive"
SOURCE_HA = "HomeAssistant"
ERROR_PLEASE_WAIT = "please_wait"
ERROR_NOT_UPLOADABLE = "not_uploadable"
ERROR_NO_SNAPSHOT = "invalid_slug"
ERROR_CREDS_EXPIRED = "creds_bad"
ERROR_UPLOAD_FAILED = "upload_failed"
ERROR_BAD_PASSWORD_KEY = "password_key_invalid"
ERROR_SNAPSHOT_IN_PROGRES... | source_google_drive = 'GoogleDrive'
source_ha = 'HomeAssistant'
error_please_wait = 'please_wait'
error_not_uploadable = 'not_uploadable'
error_no_snapshot = 'invalid_slug'
error_creds_expired = 'creds_bad'
error_upload_failed = 'upload_failed'
error_bad_password_key = 'password_key_invalid'
error_snapshot_in_progress ... |
class _stream_iter:
def __init__(self, s):
self.stream = s
self.i = 0
def next(self):
try:
val = self.stream[self.i]
except IndexError: raise StopIteration
self.i += 1
return val
class stream(list):
def __init__(self, iterator):
list.__ini... | class _Stream_Iter:
def __init__(self, s):
self.stream = s
self.i = 0
def next(self):
try:
val = self.stream[self.i]
except IndexError:
raise StopIteration
self.i += 1
return val
class Stream(list):
def __init__(self, iterator):
... |
def sale(securities, M, K):
sorted_sec = sorted(securities, key=lambda x: x[0] * x[1], reverse=True)
res = 0
for i in range(M):
if K > 0:
x, _ = sorted_sec[i]
y = 1
else:
x, y = sorted_sec[i]
K -= 1
res += x * y
print(res)
# N, M... | def sale(securities, M, K):
sorted_sec = sorted(securities, key=lambda x: x[0] * x[1], reverse=True)
res = 0
for i in range(M):
if K > 0:
(x, _) = sorted_sec[i]
y = 1
else:
(x, y) = sorted_sec[i]
k -= 1
res += x * y
print(res)
def test... |
a = input()
if a.isupper():
print(a.lower())
elif a[0].islower() and a[1:].isupper():
print(a[0].upper() + a[1:].lower())
elif len(a) == 1:
print(a.upper())
else:
print(a)
| a = input()
if a.isupper():
print(a.lower())
elif a[0].islower() and a[1:].isupper():
print(a[0].upper() + a[1:].lower())
elif len(a) == 1:
print(a.upper())
else:
print(a) |
##https://www.hackerrank.com/challenges/max-array-sum/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dynamic-programming
# Complete the maxSubsetSum function below.
def maxSubsetSum(arr):
incl = 0
excl = 0
for i in arr:
# Current max excl... | def max_subset_sum(arr):
incl = 0
excl = 0
for i in arr:
new_excl = excl if excl > incl else incl
incl = excl + i
excl = new_excl
return excl if excl > incl else incl |
"""
http://www.geeksforgeeks.org/selection-sort/
Time Complexity O(n*n)
Selection sort algorithm is easy to use but, there are other sorting algorithm which perform better than selection sort.
Specially, selection sort shouldn't be used to sort large number of elements if the performance matters in that program.
"""
... | """
http://www.geeksforgeeks.org/selection-sort/
Time Complexity O(n*n)
Selection sort algorithm is easy to use but, there are other sorting algorithm which perform better than selection sort.
Specially, selection sort shouldn't be used to sort large number of elements if the performance matters in that program.
"""
... |
# OpenWeatherMap API Key
weather_api_key = "6956968996d9e0c5c5a9bac119faa2e7"
# Google API Key
g_key = "AIzaSyDvdrUOBRkNKwWnuOOQR6wEJER3I25tAUA"
| weather_api_key = '6956968996d9e0c5c5a9bac119faa2e7'
g_key = 'AIzaSyDvdrUOBRkNKwWnuOOQR6wEJER3I25tAUA' |
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
best_total = -math.inf
total = 0
for x in nums:
total += x
if best_total < total:
best_total = total
if total < 0:
... | class Solution:
def max_sub_array(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
best_total = -math.inf
total = 0
for x in nums:
total += x
if best_total < total:
best_total = total
if total < 0:
... |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplicates(self, head):
current = head
while(current and current.next):
if(current.val == current.nex... | class Solution(object):
def delete_duplicates(self, head):
current = head
while current and current.next:
if current.val == current.next.val:
current.next = current.next.next
else:
current = current.next
return head |
class Bitmap:
"""The image is loaded despite it's used or not."""
def __init__(self, filename):
self.filename = filename
print(f"Loading image from {filename}")
def draw(self):
print(f"Drawing image {self.filename}")
class LazyBitmap:
"""Avoid load the image if no d... | class Bitmap:
"""The image is loaded despite it's used or not."""
def __init__(self, filename):
self.filename = filename
print(f'Loading image from {filename}')
def draw(self):
print(f'Drawing image {self.filename}')
class Lazybitmap:
"""Avoid load the image if no draw."""
... |
def evaluate(board, fColor, fAntiColor):
def evaluateBoard(self, b):
score = 0
score += generalPosition(board, fColor, fAntiColor)
score += stableSides(board, fColor, fAntiColor)
return score
def generalPosition(board, fColor, fAntiColor):
score = 0
for row in range(0,8):
... | def evaluate(board, fColor, fAntiColor):
def evaluate_board(self, b):
score = 0
score += general_position(board, fColor, fAntiColor)
score += stable_sides(board, fColor, fAntiColor)
return score
def general_position(board, fColor, fAntiColor):
score = 0
for row in range(0, ... |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class _OptionalContextManager(object):
def __init__(self, manager, condition):
self._manager = manager
self._condition = condition
def __enter... | class _Optionalcontextmanager(object):
def __init__(self, manager, condition):
self._manager = manager
self._condition = condition
def __enter__(self):
if self._condition:
return self._manager.__enter__()
return None
def __exit__(self, exc_type, exc_val, exc_tb... |
send_message_parameters = {
"type": "object",
"properties": {
"title": {"type": "string"},
"raw": {"type": "string"},
"is_warning": {"type": "boolean"},
"topic_id": {"type": "integer"},
"target_usernames": {"type": "array", "items": {"type": "string"}},
},
"requir... | send_message_parameters = {'type': 'object', 'properties': {'title': {'type': 'string'}, 'raw': {'type': 'string'}, 'is_warning': {'type': 'boolean'}, 'topic_id': {'type': 'integer'}, 'target_usernames': {'type': 'array', 'items': {'type': 'string'}}}, 'required': ['raw', 'target_usernames']}
create_post_parameters = {... |
def srch(l,start,end,r):
if(end>=1):
mid=(start+end)//2
if(l[mid]==r):
print(l[mid],start,end)
return mid
elif(l[mid]>r):
return srch(start,mid-1,r)
elif(l[mid]<r):
return (mid+1,end,r)
else:
return -1
l=list(map... | def srch(l, start, end, r):
if end >= 1:
mid = (start + end) // 2
if l[mid] == r:
print(l[mid], start, end)
return mid
elif l[mid] > r:
return srch(start, mid - 1, r)
elif l[mid] < r:
return (mid + 1, end, r)
else:
return -1... |
class code:
def __init__(self, code = 0, cmd_bytes = 0, reply_bytes = 0):
self.code = code
self.cmd_bytes = cmd_bytes
self.reply_bytes = reply_bytes
# General Commands
NO_OP = code(0x00, 0, 0)
SET_DEFAULTS = code(0x01, 0, 0)
CAMERA_RESET = code(0x02, 0, 0)
RESTORE_FACTORY_DEFAULTS = code(0... | class Code:
def __init__(self, code=0, cmd_bytes=0, reply_bytes=0):
self.code = code
self.cmd_bytes = cmd_bytes
self.reply_bytes = reply_bytes
no_op = code(0, 0, 0)
set_defaults = code(1, 0, 0)
camera_reset = code(2, 0, 0)
restore_factory_defaults = code(3, 0, 0)
serial_number = code(4, 0, ... |
"""
domonic.webapi.webrtc
====================================
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
"""
| """
domonic.webapi.webrtc
====================================
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
""" |
class Account:
def __init__(self, cs_api, cmd_info):
self.cs_api = cs_api
self.uuid = cmd_info['account']
self._get_account()
def _get_account(self):
accounts = self.cs_api.listAccounts(id=self.uuid)
self.name = accounts['account'][0]['name'].lower()
self.network... | class Account:
def __init__(self, cs_api, cmd_info):
self.cs_api = cs_api
self.uuid = cmd_info['account']
self._get_account()
def _get_account(self):
accounts = self.cs_api.listAccounts(id=self.uuid)
self.name = accounts['account'][0]['name'].lower()
self.networ... |
print("Hello, ", end= ' ' )
print("My name is Sana Amir!")
print("\n")
print("Hey!", sep= '')
print("My name is Sana Amir!") | print('Hello, ', end=' ')
print('My name is Sana Amir!')
print('\n')
print('Hey!', sep='')
print('My name is Sana Amir!') |
#! /usr/bin/python3.2
# Note :
# I don't think that this program is *really* working for
# books > 8, but I don't have more tests to test it
#
class TooManyBooksException(Exception):
def __init__(self,*args):
super(*args)
# returns the price with as big discount as
# possible. Format: list of books, e.g.... | class Toomanybooksexception(Exception):
def __init__(self, *args):
super(*args)
def calculate_price(*books):
if len(books) > 5:
raise TooManyBooksException
coefs = [8, 7.2, 6.4, 4, 4.4]
books = [b for b in books if b]
if len(books) == 0:
return get_original_price(0)
if ... |
# Rename this file to config.py and fill out the fields
# Project Location (Latitude and Longitude - NYC is default)
GPS_LOCATION = [40.730610, -73.935242]
# Google Maps Time Zone API Auth
API_KEY = "AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXE"
# GMail settings
FROM_EMAIL = "SendersEmail@gmail.com"
TO_EMAIL = ["Recipien... | gps_location = [40.73061, -73.935242]
api_key = 'AXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXE'
from_email = 'SendersEmail@gmail.com'
to_email = ['Recipient1@EmailProviderA.com, Recipient2@EmailProviderB.com']
user = 'SendersEmail@gmail.com'
pass = 'tXXXXXXXXXXXXXXg'
stream_token = 'lXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX... |
"""
Author: Resul Emre AYGAN
"""
"""
Project Description: Fake Binary
Given a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'.
Return the resulting string.
"""
def fake_bin(x):
return ''.join(['0' if int(digit) < 5 else '1' for digit in x])
| """
Author: Resul Emre AYGAN
"""
"\nProject Description: Fake Binary\n\nGiven a string of digits, you should replace any digit below 5 with '0' and any digit 5 and above with '1'. \nReturn the resulting string.\n"
def fake_bin(x):
return ''.join(['0' if int(digit) < 5 else '1' for digit in x]) |
class Solution:
def sumEvenAfterQueries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
even_sum = sum([x for x in nums if x & 1==0])
res = []
for q in queries:
if nums[q[1]] & 1 ==0:
even_sum -= nums[q[1]]
nums[q[1]] += q[0]
... | class Solution:
def sum_even_after_queries(self, nums: List[int], queries: List[List[int]]) -> List[int]:
even_sum = sum([x for x in nums if x & 1 == 0])
res = []
for q in queries:
if nums[q[1]] & 1 == 0:
even_sum -= nums[q[1]]
nums[q[1]] += q[0]
... |
advancedSearch = [
{
"relevanceScore": "4",
"resourceType": "SoftLayer_Hardware",
"resource": {
"accountId": 307608,
"domain": "vmware.test.com",
"fullyQualifiedDomainName": "host14.vmware.test.com",
"hardwareStatusId": 5,
"hostname... | advanced_search = [{'relevanceScore': '4', 'resourceType': 'SoftLayer_Hardware', 'resource': {'accountId': 307608, 'domain': 'vmware.test.com', 'fullyQualifiedDomainName': 'host14.vmware.test.com', 'hardwareStatusId': 5, 'hostname': 'host14', 'id': 123456, 'manufacturerSerialNumber': 'AAAAAAAAA', 'notes': 'A test notes... |
""" utility module to transform data into html """
def wrap(content,tag,lf=False):
"""embeds content string with html tags"""
if lf is False:
return "<"+tag+">"+content+"</"+tag+">"
else:
return "<"+tag+">\n"+content+"\n"+"</"+tag+">"
def get_link(link,text):
"""gereates lin... | """ utility module to transform data into html """
def wrap(content, tag, lf=False):
"""embeds content string with html tags"""
if lf is False:
return '<' + tag + '>' + content + '</' + tag + '>'
else:
return '<' + tag + '>\n' + content + '\n' + '</' + tag + '>'
def get_link(link, text):
... |
#! /usr/bin/env python
'''
Andrew Till
Summer 2014
Gets ENDF vii1 XS from T2's site.
For thermal XS, see http://t2.lanl.gov/nis/data/data/ENDFB-VII-thermal/UinUO2' etc.
'''
class Nuclide:
def __init__(self, name, Z, A):
self.name = name
self.Z = Z
self.A = A
nuclideList = []
nuclideList... | """
Andrew Till
Summer 2014
Gets ENDF vii1 XS from T2's site.
For thermal XS, see http://t2.lanl.gov/nis/data/data/ENDFB-VII-thermal/UinUO2' etc.
"""
class Nuclide:
def __init__(self, name, Z, A):
self.name = name
self.Z = Z
self.A = A
nuclide_list = []
nuclideList.append(nuclide('Pu', 9... |
# Custom operators
# 25 nov 2018
# AR, AQ, Abdullah
def star_op (firstop, secondop):
return ( firstop * 2) + secondop
def squiggle_op (firstop,secondop):
return firstop**3 + secondop**2
def multidot (op1,op2):
return (op1*4)//op2
print ("8 starop 2 == ", star_op (8,2)) # == 18
print ("3 squiggle 2... | def star_op(firstop, secondop):
return firstop * 2 + secondop
def squiggle_op(firstop, secondop):
return firstop ** 3 + secondop ** 2
def multidot(op1, op2):
return op1 * 4 // op2
print('8 starop 2 == ', star_op(8, 2))
print('3 squiggle 2 == ', squiggle_op(3, 2))
print('2 multidot 2 == ', multidot(2, 2))
... |
def left(string,i=1):
i=string.index(i) if type(i)==str else i
return string[:i]
def right(string,i=1):
i=string[::-1].index(i[::-1]) if type(i)==str else i
return string[-i:] if i!=0 else "" | def left(string, i=1):
i = string.index(i) if type(i) == str else i
return string[:i]
def right(string, i=1):
i = string[::-1].index(i[::-1]) if type(i) == str else i
return string[-i:] if i != 0 else '' |
# /**
# * @author Sarath Chandra Asapu
# * @email sarath.chandra.asapu@accenture.com
# * @create date 2021-09-17 13:08:06
# * @modify date 2021-09-17 13:08:06
# * @desc [description]
# */
PROJECT_ID = 'peak-catbird-324206'
REGION = 'us-central1'
PIPELINE_NAME_TFX = 'pipelinetfxvertexai2-cicd'
DATASET = "LoanApp... | project_id = 'peak-catbird-324206'
region = 'us-central1'
pipeline_name_tfx = 'pipelinetfxvertexai2-cicd'
dataset = 'LoanApplyData-bank.csv'
data_path = 'gs://aivertex-bucket/TFX_Pipeline/data'
serving_model_dir = 'gs://aivertex-bucket/TFX_Pipeline/' + PIPELINE_NAME_TFX + '/serving_model_tfx'
pipeline_root = 'gs://aive... |
def validPass(s):
letters = 0
digits = 0
for c in s:
if c.isdigit():
digits += 1
elif c.isalpha():
letters += 1
else:
return False
return letters % 2 == 0 and digits % 2 == 1
def solution(S):
# write your code in Python 3.6
maxL = ... | def valid_pass(s):
letters = 0
digits = 0
for c in s:
if c.isdigit():
digits += 1
elif c.isalpha():
letters += 1
else:
return False
return letters % 2 == 0 and digits % 2 == 1
def solution(S):
max_l = -1
words = S.split(' ')
for wo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Question:
Given an array and a value, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be ... | """
Question:
Given an array and a value, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyon... |
# a=int(input("Enter any no"))
# if a==1 :
# print("composit number")
# elif a==2 :
# print("no is prime no")
# else :
# i=1
# c=1
# while i<a/2 :
# if a%i==0 :
# c=c+1
# i=i+1
# if c>1 :
# print("no is not prime")
# else:
# print("no is prime"... | def checkprime(num):
if num > 1:
for i in range(2, num):
if num % i == 0:
print(num, 'is not a prime number')
print(i, 'times', num // i, 'is', num)
break
else:
print(num, 'is a prime number')
break
e... |
expected_output = {
"line":{
"pts/0":{
"active":False,
"name":"admin",
"time":"Jan 28 13:44",
"idle":".",
"pid":"8096",
"comment":"adding some comments"
},
"pts/1":{
"active":False,
"name":"admin",
"time":"Jan 28 13:44... | expected_output = {'line': {'pts/0': {'active': False, 'name': 'admin', 'time': 'Jan 28 13:44', 'idle': '.', 'pid': '8096', 'comment': 'adding some comments'}, 'pts/1': {'active': False, 'name': 'admin', 'time': 'Jan 28 13:44', 'idle': '.', 'pid': '8096'}, 'pts/2': {'active': True, 'name': 'admin', 'time': 'Jan 28 13:4... |
class FeaturesNotInFeatureDictError(Exception):
pass
class RolePatternDoesNotMatchExample(Exception):
pass | class Featuresnotinfeaturedicterror(Exception):
pass
class Rolepatterndoesnotmatchexample(Exception):
pass |
''' 97.47% dp '''
class Solution:
"""
@param s: a string
@param t: a string
@return: true if they are both one edit distance apart or false
"""
def isOneEditDistance(self, s, t):
ls, lt = len(s), len(t)
if abs(ls - lt) > 1:
return False
d... | """ 97.47% dp """
class Solution:
"""
@param s: a string
@param t: a string
@return: true if they are both one edit distance apart or false
"""
def is_one_edit_distance(self, s, t):
(ls, lt) = (len(s), len(t))
if abs(ls - lt) > 1:
return False
d = [[0] * (lt... |
def solution(s):
word_dict = {}
for element in s.lower():
word_dict[element] = word_dict.get(element, 0) + 1
if word_dict.get('p', 0) == word_dict.get('y', 0):
return True
return False
if __name__ == '__main__':
s = 'pPoooyY'
print(solution(s))
"""
def solution... | def solution(s):
word_dict = {}
for element in s.lower():
word_dict[element] = word_dict.get(element, 0) + 1
if word_dict.get('p', 0) == word_dict.get('y', 0):
return True
return False
if __name__ == '__main__':
s = 'pPoooyY'
print(solution(s))
"\ndef solution(s):\n return s.l... |
# https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem
if __name__ == '__main__':
a = int(input())
l = list(map(int,input().strip().split()))[:a]
b = max(l)
while max(l) == b:
l.remove(max(l))
print (max(l))
| if __name__ == '__main__':
a = int(input())
l = list(map(int, input().strip().split()))[:a]
b = max(l)
while max(l) == b:
l.remove(max(l))
print(max(l)) |
# Usage: python3 placements.py
# Output: a list of placements for places, in a grid determined by the parameters.
#
# Run this script to generate the file placements.xml which can be used for substitution in Mapnik XML.
grid = {
'vertical': 30,
'horizontal': 50,
}
step = 5
# Generate a list of placement tuple... | grid = {'vertical': 30, 'horizontal': 50}
step = 5
placements = [(x, y) for x in range(-grid['horizontal'], grid['horizontal'] + 1, step) for y in range(-grid['vertical'], grid['vertical'] + 1, step)]
placements.sort(key=lambda p: abs(p[0]) + abs(p[1]))
output = ''.join(map(lambda p: "<Placement dx='%s' dy='%s'/>" % p,... |
# Question 2 - List union
# Asmit De
# 04/28/2017
# Input list data and form lists
user_input = input('Enter a numbers for the 1st list: ')
list1 = [int(e) for e in user_input.split()]
user_input = input('Enter a numbers for the 2nd list: ')
list2 = [int(e) for e in user_input.split()]
# Create empty union ... | user_input = input('Enter a numbers for the 1st list: ')
list1 = [int(e) for e in user_input.split()]
user_input = input('Enter a numbers for the 2nd list: ')
list2 = [int(e) for e in user_input.split()]
union = []
for e in list1 + list2:
if e not in union:
union.append(e)
print('The distinct numbers in bot... |
def my_encryption(some_string):
character_set = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 "
secret_key = "Dd18Abz2EqNPW hYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM"
encription = ""
for x in some_string:
count = 0
for i in character_set:
if i == x:
encription += secret_key... | def my_encryption(some_string):
character_set = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 '
secret_key = 'Dd18Abz2EqNPW hYTOjBvtVlpXaH6msFUICg4o0KZwJeryQx3f9kSinRu5L7cGM'
encription = ''
for x in some_string:
count = 0
for i in character_set:
if i == x:
... |
n = int(input())
arr = [int(e) for e in input().split()]
yoda = int(input())
yoda /= 2
for i in range(n):
if arr[i] >= yoda:
print(i, end=" ")
print()
| n = int(input())
arr = [int(e) for e in input().split()]
yoda = int(input())
yoda /= 2
for i in range(n):
if arr[i] >= yoda:
print(i, end=' ')
print() |
def up(database):
database.execute("""
CREATE SEQUENCE players_id_seq;
CREATE TABLE players (
id integer NOT NULL DEFAULT nextval('players_id_seq'),
firstname VARCHAR (50),
lastname VARCHAR (50)
);
ALTER SEQUENCE players_id_seq
OWNED BY players.id;
""")
def down(d... | def up(database):
database.execute("\n CREATE SEQUENCE players_id_seq;\n\n CREATE TABLE players (\n id integer NOT NULL DEFAULT nextval('players_id_seq'),\n firstname VARCHAR (50),\n lastname VARCHAR (50)\n );\n\n ALTER SEQUENCE players_id_seq\n OWNED BY players.id;\n ")
def ... |
r=float(input("Input the radius of a circle:" ))
pi=3.14
area=pi*r*r
print("The area of circle is: ",area)
| r = float(input('Input the radius of a circle:'))
pi = 3.14
area = pi * r * r
print('The area of circle is: ', area) |
cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print ("There are ", cars, "cars available");
print ("There are only ", drivers, " drivers... | cars = 100
space_in_a_car = 4.0
drivers = 30
passengers = 90
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
print('There are ', cars, 'cars available')
print('There are only ', drivers, ' drivers available')
pr... |
'''
import pytest
from seleniumbase import BaseCase
from qa327_test.conftest import base_url
from unittest.mock import patch
from qa327.models import db, User
from werkzeug.security import generate_password_hash, check_password_hash
"""
This file defines all unit tests for the frontend homepage.
The tests will only ... | '''
import pytest
from seleniumbase import BaseCase
from qa327_test.conftest import base_url
from unittest.mock import patch
from qa327.models import db, User
from werkzeug.security import generate_password_hash, check_password_hash
"""
This file defines all unit tests for the frontend homepage.
The tests will only ... |
names = ['jack', 'john', 'mark', 'bill']
numbers = [20, 44, 3, 14]
# for name in names:
# print(name)
# for number in numbers:
# print(number)
for i in range(len(names)):
print(names[i].title() + ': ' + str(numbers[i]))
# the zip function
for name, number in zip(names, numbers):
print(name.title() + ': ' + ... | names = ['jack', 'john', 'mark', 'bill']
numbers = [20, 44, 3, 14]
for i in range(len(names)):
print(names[i].title() + ': ' + str(numbers[i]))
for (name, number) in zip(names, numbers):
print(name.title() + ': ' + str(number)) |
result = {
'First Name': 'Mark',
'Last Name': 'Watney',
'Missions': ['Ares1', 'Ares3'],
}
| result = {'First Name': 'Mark', 'Last Name': 'Watney', 'Missions': ['Ares1', 'Ares3']} |
# Read in all 3 rules
rules = [input().split() for i in range(3)]
# Read in the next line
temp = input().split()
# Separate it into the number of steps, the initial state and the final state
steps = int(temp[0])
initial = temp[1]
final = temp[2]
# Applies the given rule to s at the index.
def apply_rule(s, rule, index... | rules = [input().split() for i in range(3)]
temp = input().split()
steps = int(temp[0])
initial = temp[1]
final = temp[2]
def apply_rule(s, rule, index):
if index + len(rule[0]) > len(s):
return False
for i in range(0, len(rule[0])):
if s[i + index] != rule[0][i]:
return False
r... |
##!FAIL: WrongReturnTypeError[int/float]@5:4
def floatint(x : int) -> int:
"""blabla"""
return min(x, 42.3)
| def floatint(x: int) -> int:
"""blabla"""
return min(x, 42.3) |
"""
Iterated-Depth Depth First Search
aka IDDFS
---------
"""
def dls_visit(
s,
adjacency_list,
depth,
max_depth,
parents,
):
"""
DFS visit checking depth
"""
if depth == max_depth:
return
for u in adjacency_list[s]:
if u in parents:
continue
parents[u] = s
dls_visit(
... | """
Iterated-Depth Depth First Search
aka IDDFS
---------
"""
def dls_visit(s, adjacency_list, depth, max_depth, parents):
"""
DFS visit checking depth
"""
if depth == max_depth:
return
for u in adjacency_list[s]:
if u in parents:
continue
parents[u] = s
dl... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class ChoiceFactoryOptions(object):
def __init__(
self,
inline_separator: str = None,
inline_or: str = None,
inline_or_more: str = None,
include_numbers: bool = None,
) -> None... | class Choicefactoryoptions(object):
def __init__(self, inline_separator: str=None, inline_or: str=None, inline_or_more: str=None, include_numbers: bool=None) -> None:
"""Initializes a new instance.
Refer to the code in the ConfirmPrompt for an example of usage.
:param object:
:type... |
# mudanca de tipo
x=1
y="abc"
y=x
| x = 1
y = 'abc'
y = x |
def timeConversion(country, t):
dict1 = {"usa": +9.30,
"canada": +9.30,
"russia": +2.30,
"japan": -3.30,
"malysia": -2.30,
"singapur": -2.30,
"dubai": +1.30,
"israel": -2.30,
"germany": +3.30,
"italy... | def time_conversion(country, t):
dict1 = {'usa': +9.3, 'canada': +9.3, 'russia': +2.3, 'japan': -3.3, 'malysia': -2.3, 'singapur': -2.3, 'dubai': +1.3, 'israel': -2.3, 'germany': +3.3, 'italy': +3.3, 'england': +4.3}
if country in dict1.keys():
print('india:', t + dict1[country])
else:
print... |
def power_nums(nums):
print("(", nums[0], " - ", nums[1], ") ^ 2 = ", (nums[0]-nums[1])**2, sep="")
print("(", nums[0], " + ", nums[1], ") ^ 3 = ", (nums[0]+nums[1])**3, sep="")
def main():
nums = input().split()
for index, value in enumerate(nums):
nums[index] = int(nums[index])
power_num... | def power_nums(nums):
print('(', nums[0], ' - ', nums[1], ') ^ 2 = ', (nums[0] - nums[1]) ** 2, sep='')
print('(', nums[0], ' + ', nums[1], ') ^ 3 = ', (nums[0] + nums[1]) ** 3, sep='')
def main():
nums = input().split()
for (index, value) in enumerate(nums):
nums[index] = int(nums[index])
... |
D = [1, 1, 2, 2]
for i in range(4, 100001):
a = 0
for j in range(2, min(i+1, 7), 2):
a += D[i-j]
a %= 1000000009
D.append(a)
for _ in range(int(input())):
print(D[int(input())]) | d = [1, 1, 2, 2]
for i in range(4, 100001):
a = 0
for j in range(2, min(i + 1, 7), 2):
a += D[i - j]
a %= 1000000009
D.append(a)
for _ in range(int(input())):
print(D[int(input())]) |
def findDecision(obj): #obj[0]: Driving_to, obj[1]: Passanger, obj[2]: Weather, obj[3]: Temperature, obj[4]: Time, obj[5]: Coupon, obj[6]: Coupon_validity, obj[7]: Gender, obj[8]: Age, obj[9]: Maritalstatus, obj[10]: Children, obj[11]: Education, obj[12]: Occupation, obj[13]: Income, obj[14]: Bar, obj[15]: Coffeehouse,... | def find_decision(obj):
if obj[20] <= 2:
if obj[14] > 0.0:
if obj[8] <= 2:
if obj[6] <= 0:
if obj[1] <= 1:
return 'True'
elif obj[1] > 1:
return 'False'
else:
... |
# -*- coding: utf-8 -*-
"""Top-level package for pyatlonajuno."""
__author__ = """Hugh Saunders"""
__email__ = 'hugh@wherenow.org'
__version__ = '1.1.1'
| """Top-level package for pyatlonajuno."""
__author__ = 'Hugh Saunders'
__email__ = 'hugh@wherenow.org'
__version__ = '1.1.1' |
STOPWORDS = [
'a',
'an',
'by',
'for',
'in',
'of',
'with',
'the',
]
| stopwords = ['a', 'an', 'by', 'for', 'in', 'of', 'with', 'the'] |
a=int(input("Enter A: "))
b=int(input("Enter B: "))
c=int(input("Enter C: "))
if a>b:
if a>c:
g=a
else:
g=c
else:
if b>c:
g=b
else:
g=c
print("Greater Number = ",g)
| a = int(input('Enter A: '))
b = int(input('Enter B: '))
c = int(input('Enter C: '))
if a > b:
if a > c:
g = a
else:
g = c
elif b > c:
g = b
else:
g = c
print('Greater Number = ', g) |
# https://leetcode.com/problems/balanced-binary-tree/
# Given a binary tree, determine if it is height-balanced.
# For this problem, a height-balanced binary tree is defined as:
# a binary tree in which the left and right subtrees of every node differ in
# height by no more than 1.
#################################... | class Solution:
def is_balanced(self, root: TreeNode) -> bool:
return self.max_depth(root) != -1
def max_depth(self, root):
if root == None:
return 0
l_depth = self.max_depth(root.left)
r_depth = self.max_depth(root.right)
if l_depth == -1 or r_depth == -1 o... |
class Node:
def __init__(self,data):
self.data=data
self.next=None #initialize next as null
class LinkedList:
def __init__(self):
self.head=None #pointer
#program to print content of the lsit
def printlist(self):
temp=self.head
while temp:
print(t... | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def printlist(self):
temp = self.head
while temp:
print(temp.data)
temp = temp.next
llist = linked_list()
llist.h... |
#!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
# A dictionary is a searchable set of key-value pairs.
x = { 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5 }
for i in x:
print('i is {}'.format(i))
# The above will only give us the keys.
# If we want to print key-value pairs,
# we can do th... | x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
for i in x:
print('i is {}'.format(i))
y = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
for (k, v) in y.items():
print('k: {}, v: {}'.format(k, v)) |
def restartable(func):
def wrapper(*args, **kwargs):
answer = "y"
while answer == "y":
func(*args, **kwargs)
while True:
answer = input("Restart?\ty/n:")
if answer in ("y", "n"):
break
else:
... | def restartable(func):
def wrapper(*args, **kwargs):
answer = 'y'
while answer == 'y':
func(*args, **kwargs)
while True:
answer = input('Restart?\ty/n:')
if answer in ('y', 'n'):
break
else:
... |
# Lists
# - declaration & length
# - accessing items
# - mutable with append, remove
# - sorting
# - sum, min, max
# supplies = ['crayons', 'pencils', 'paper', 'Kleenex', 'eraser']
# print(supplies)
# supplies.append('markers')
# print(supplies)
# supplies.remove('crayons')
# print(supplies)
# supplies.sort()
# pri... | colors = ['red', 'orange', 'blue', 'pink']
alphabetical = sorted(colors)
print(colors)
print(alphabetical)
alphabetical = sorted(colors, reverse=True)
print(alphabetical)
reverse_colors = reversed(colors)
reverse_alpha = reversed(alphabetical)
print(reverseColors)
print(reverseAlpha)
print(list(reverseColors))
print(li... |
width = 4.5
height = 7.9
area = width * height
print("Area: {}".format(area))
| width = 4.5
height = 7.9
area = width * height
print('Area: {}'.format(area)) |
def most_frequent(name):
unsorted_dic = {}
most_frequent_dic = {}
for intex in range(len(name)):
if name[intex] not in unsorted_dic.keys():
unsorted_dic[name[intex]] = name.count(name[intex])
sorted_values = reversed(sorted(unsorted_dic.values()))
for values in sorted_va... | def most_frequent(name):
unsorted_dic = {}
most_frequent_dic = {}
for intex in range(len(name)):
if name[intex] not in unsorted_dic.keys():
unsorted_dic[name[intex]] = name.count(name[intex])
sorted_values = reversed(sorted(unsorted_dic.values()))
for values in sorted_values:
... |
def PatternCount(Pattern, Text):
count = 0
for i in range(len(Text)-len(Pattern)+1):
if Text[i:i+len(Pattern)] == Pattern:
count = count+1
return count
| def pattern_count(Pattern, Text):
count = 0
for i in range(len(Text) - len(Pattern) + 1):
if Text[i:i + len(Pattern)] == Pattern:
count = count + 1
return count |
#-*- coding:utf-8 -*-
#--
# Copyright (c) 2012-2014 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
#--
"""
This engine does nothing but it works (i.e. it does not break)
It is he... | """
This engine does nothing but it works (i.e. it does not break)
It is here for documentation purpose.
For a basic effective engine, see SQLiteFTSEngine.
"""
class Dummysearchengine(object):
load_priority = 30
def __init__(self, index):
self.index = index
def add_document(self, document):
... |
"""
Make a program that reads six integer numbers
and returns the sum of those that are odd.
"""
sum = 0
for i in range(0,6):
num = int(input('Enter a integer number: '))
if num % 2 != 0:
sum += num
print('The sum of odd numbers is {}.'.format(sum))
| """
Make a program that reads six integer numbers
and returns the sum of those that are odd.
"""
sum = 0
for i in range(0, 6):
num = int(input('Enter a integer number: '))
if num % 2 != 0:
sum += num
print('The sum of odd numbers is {}.'.format(sum)) |
def check(row_idx, col_idx):
existing = []
if row_idx - 1 >= 0 and col_idx - 1 >= 0:
existing.append([row_idx - 1, col_idx - 1])
if row_idx - 1 >= 0:
existing.append([row_idx - 1, col_idx])
if row_idx - 1 >= 0 and col_idx + 1 < len(matrix):
existing.append([row_idx - 1, co... | def check(row_idx, col_idx):
existing = []
if row_idx - 1 >= 0 and col_idx - 1 >= 0:
existing.append([row_idx - 1, col_idx - 1])
if row_idx - 1 >= 0:
existing.append([row_idx - 1, col_idx])
if row_idx - 1 >= 0 and col_idx + 1 < len(matrix):
existing.append([row_idx - 1, col_idx +... |
#!/usr/bin/env python3
def mark(hits, distance):
standard_multiplier = 3 #std distance = 4 Meter
points = hits * 3
return points
def exists():
try:
f = open("marklist.csv", "r")
f.close()
except FileNotFoundError:
f = open("marklist.csv", "w")
f.write("name,hits,note_in_punkten\n")
def main():
try:
... | def mark(hits, distance):
standard_multiplier = 3
points = hits * 3
return points
def exists():
try:
f = open('marklist.csv', 'r')
f.close()
except FileNotFoundError:
f = open('marklist.csv', 'w')
f.write('name,hits,note_in_punkten\n')
def main():
try:
f... |
simType = 'sym_file'
symProps = [
{'name': 'non_exist', 'RBs': [
{'pred_name': 'non_exist', 'pred_sem': [], 'higher_order': False,
'object_name': 'testLine1', 'object_sem': [['length', 1, 'length', 'nil', 'state'], ['length1', 1, 'length', 1, 'value']], 'P': 'nil'}], 'set': 'driver', 'analog': 0},
{'name': 'non_ex... | sim_type = 'sym_file'
sym_props = [{'name': 'non_exist', 'RBs': [{'pred_name': 'non_exist', 'pred_sem': [], 'higher_order': False, 'object_name': 'testLine1', 'object_sem': [['length', 1, 'length', 'nil', 'state'], ['length1', 1, 'length', 1, 'value']], 'P': 'nil'}], 'set': 'driver', 'analog': 0}, {'name': 'non_exist',... |
def group_by_codons(refnas, seqnas):
refcodons = []
seqcodons = []
lastrefcodon = None
lastseqcodon = None
bp = -1
for refna, seqna in zip(refnas, seqnas):
if not refna.is_single_gap:
bp = (bp + 1) % 3
if bp == 0:
# begin new codon
... | def group_by_codons(refnas, seqnas):
refcodons = []
seqcodons = []
lastrefcodon = None
lastseqcodon = None
bp = -1
for (refna, seqna) in zip(refnas, seqnas):
if not refna.is_single_gap:
bp = (bp + 1) % 3
if bp == 0:
lastrefcodon = []
... |
#Vowels Extract
def ExtractVowels(str):
vowels = "aeiou"
for i in str:
if i in vowels:
print(i, end="")
print() | def extract_vowels(str):
vowels = 'aeiou'
for i in str:
if i in vowels:
print(i, end='')
print() |
class Hotel:
def __init__(self, name):
self.name: str = name
self.rooms = []
self.guests: int = 0
@classmethod
def from_stars(cls, stars_count):
name = f"{stars_count} stars Hotel"
return cls(name)
def add_room(self, room):
self.rooms.append(room)
... | class Hotel:
def __init__(self, name):
self.name: str = name
self.rooms = []
self.guests: int = 0
@classmethod
def from_stars(cls, stars_count):
name = f'{stars_count} stars Hotel'
return cls(name)
def add_room(self, room):
self.rooms.append(room)
... |
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
res = [[0 for _ in range(n)] for _ in range(n)]
tmp = list(range(1, n ** 2 + 1))
cnt = 0
while True:
for _ in range(cnt, n - cnt):
res[cnt][_] = tmp.pop(0)
if not tmp:
... | class Solution:
def generate_matrix(self, n: int) -> List[List[int]]:
res = [[0 for _ in range(n)] for _ in range(n)]
tmp = list(range(1, n ** 2 + 1))
cnt = 0
while True:
for _ in range(cnt, n - cnt):
res[cnt][_] = tmp.pop(0)
if not tmp:
... |
PING = {
'zen': 'Approachable is better than simple.',
'hook_id': 123456,
'hook': {
'type': 'Repository',
'id': 55866886,
'name': 'web',
'active': True,
'events': [
'pull_request',
],
'config': {
'content_type': 'json',
... | ping = {'zen': 'Approachable is better than simple.', 'hook_id': 123456, 'hook': {'type': 'Repository', 'id': 55866886, 'name': 'web', 'active': True, 'events': ['pull_request'], 'config': {'content_type': 'json', 'insecure_ssl': '0', 'secret': '********'}}, 'repository': {'id': 123456, 'name': 'filabel-testrepo-everyb... |
class Breakpoint(object):
"""Represent a breakpoint"""
def __init__(self, file_name, line_number, condition):
super(Breakpoint, self).__init__()
self.file_name = file_name
self.line_number = line_number
self.condition = condition
| class Breakpoint(object):
"""Represent a breakpoint"""
def __init__(self, file_name, line_number, condition):
super(Breakpoint, self).__init__()
self.file_name = file_name
self.line_number = line_number
self.condition = condition |
'''
Signal min, max, median
Now that you have the data read and cleaned, you can begin with statistical EDA. First, you will analyze the 2011 Austin weather data.
Your job in this exercise is to analyze the 'dry_bulb_faren' column and print the median temperatures for specific time ranges. You can do this using parti... | """
Signal min, max, median
Now that you have the data read and cleaned, you can begin with statistical EDA. First, you will analyze the 2011 Austin weather data.
Your job in this exercise is to analyze the 'dry_bulb_faren' column and print the median temperatures for specific time ranges. You can do this using parti... |
# Tree node class to get update about parents node too
class TreeNode:
def __init__(self, data):
self.data = data
self.parent=None
self.left = None
self.right = None
def __repr__(self):
return repr(self.data)
def add_left(self, node):
self.left = node
... | class Treenode:
def __init__(self, data):
self.data = data
self.parent = None
self.left = None
self.right = None
def __repr__(self):
return repr(self.data)
def add_left(self, node):
self.left = node
if node is not None:
node.parent = sel... |
length = int(input())
width = int(input())
height = int(input())
percent = float(input()) * 0.01
volume = length * width * height * 0.001
print(f'{volume*(1-percent):.3f}') | length = int(input())
width = int(input())
height = int(input())
percent = float(input()) * 0.01
volume = length * width * height * 0.001
print(f'{volume * (1 - percent):.3f}') |
class OpCode:
"""An EVM opcode."""
def __init__(self, name: str, code: int, pop: int, push: int, push_bytes: int = 0):
"""
Args:
name (str): Human-readable opcode.
code (int): The instruction byte itself.
pop (int): The number of stack elements this op pops.
... | class Opcode:
"""An EVM opcode."""
def __init__(self, name: str, code: int, pop: int, push: int, push_bytes: int=0):
"""
Args:
name (str): Human-readable opcode.
code (int): The instruction byte itself.
pop (int): The number of stack elements this op pops.
... |
#
# PySNMP MIB module HUAWEI-TUNNEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-TUNNEL-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:49:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) ... |
class EDA:
def __init__(self, directory, sr=22050):
self.directory = directory
self.wav_name = os.listdir(directory)
self.count = len(self.wav_name)
self.file_duration = []
for filename in tqdm(self.wav_name):
signal, sr = librosa.load(os.path.join(self.directory,filename))
duration... | class Eda:
def __init__(self, directory, sr=22050):
self.directory = directory
self.wav_name = os.listdir(directory)
self.count = len(self.wav_name)
self.file_duration = []
for filename in tqdm(self.wav_name):
(signal, sr) = librosa.load(os.path.join(self.directo... |
#!/usr/bin/env python3
densenet121 = __import__('7-densenet121').densenet121
if __name__ == '__main__':
model = densenet121(32, 0.5)
model.summary()
| densenet121 = __import__('7-densenet121').densenet121
if __name__ == '__main__':
model = densenet121(32, 0.5)
model.summary() |
# Problem Statement
# Given two strings s and t, return if they are equal when both are typed into empty text editors.
# "#" means a backspace character.
# Note that after backspacing an empty text, the text will continue empty.
class Solution:
@staticmethod
def backspace_compare(s: str, t: str) -> bool:
... | class Solution:
@staticmethod
def backspace_compare(s: str, t: str) -> bool:
return generate_final_string(s) == generate_final_string(t)
def generate_final_string(raw_input: str) -> str:
result = ''
for character in raw_input:
if character == '#':
result = result[:-1]
... |
class Node:
def __init__(self, value, children=None):
if children is None:
children = []
self.value: str = value
self.children = children # type: List[Node]
def __str__(self):
return f"{self.value}, {self.children}"
__repr__ = __str__
def longestPath(fileSyst... | class Node:
def __init__(self, value, children=None):
if children is None:
children = []
self.value: str = value
self.children = children
def __str__(self):
return f'{self.value}, {self.children}'
__repr__ = __str__
def longest_path(fileSystem):
filenames =... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def closestKValues(self, root, target, k):
"""
:type root: TreeNode
:type target: floa... | class Solution(object):
def closest_k_values(self, root, target, k):
"""
:type root: TreeNode
:type target: float
:type k: int
:rtype: List[int]
"""
ans = []
pre_stack = []
suc_stack = []
while root:
if root.val < target:
... |
load("//:third_party/javax_enterprise.bzl", javax_enterprise_deps = "dependencies")
load("//:third_party/com_github_scopt.bzl", com_github_scopt_deps = "dependencies")
load("//:third_party/velocity.bzl", velocity_deps = "dependencies")
load("//:third_party/oro.bzl", oro_deps = "dependencies")
load("//:third_party/o... | load('//:third_party/javax_enterprise.bzl', javax_enterprise_deps='dependencies')
load('//:third_party/com_github_scopt.bzl', com_github_scopt_deps='dependencies')
load('//:third_party/velocity.bzl', velocity_deps='dependencies')
load('//:third_party/oro.bzl', oro_deps='dependencies')
load('//:third_party/org_apache_ve... |
create_request_schema = {
"title": "JSON Schema for models request",
"type": "object",
"properties": {
"name": {
"description": "The name of the model",
"type": "string",
"minLength": 1,
},
"version": {
"description": "The version of th... | create_request_schema = {'title': 'JSON Schema for models request', 'type': 'object', 'properties': {'name': {'description': 'The name of the model', 'type': 'string', 'minLength': 1}, 'version': {'description': 'The version of the model', 'type': 'integer', 'minimum': 1}, 'id': {'description': 'The ID of the Google Dr... |
def initials(name: str):
names = name.split()
initials = ''.join(letter [0].upper() for letter in names)
return(initials)
| def initials(name: str):
names = name.split()
initials = ''.join((letter[0].upper() for letter in names))
return initials |
class Item():
def __init__(self,name,typez):
self._name = name
self._desc = None
self._type = typez
@property
def name(self):
return self._name
@name.setter
def name(self,namez):
self._name = namez
@property
def desc(self):
retur... | class Item:
def __init__(self, name, typez):
self._name = name
self._desc = None
self._type = typez
@property
def name(self):
return self._name
@name.setter
def name(self, namez):
self._name = namez
@property
def desc(self):
return self._de... |
def test_styleguide_can_render(app_):
response = app_.test_client().get('/_styleguide')
assert response.status_code == 200
| def test_styleguide_can_render(app_):
response = app_.test_client().get('/_styleguide')
assert response.status_code == 200 |
# Construct a tree with all functions mentioned. Do a pre-order traversal of the tree and only add alive people to the order.
class Person:
def __init__(self, childName):
self.name = childName
self.children = []
self.alive = True
class ThroneInheritance:
def __init__(self, ki... | class Person:
def __init__(self, childName):
self.name = childName
self.children = []
self.alive = True
class Throneinheritance:
def __init__(self, kingName: str):
self.king = person(kingName)
self.name2node = {kingName: self.king}
def birth(self, parentName: str,... |
HOURS = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']
TENS_MINUTES = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
MINUTES_ONES_PLACE = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', ... | hours = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']
tens_minutes = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
minutes_ones_place = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', ... |
class mobileEntity:
id=""
pseudonym = ""
trace = None
index_current_location = 0
in_mix_zone = False
mix_zone = None
number_of_anonymizations = 0
anon_history = None
def __init__(self,pseudonym,trace,id):
self.pseudonym = pseudonym
self.trace = [trace]
self.i... | class Mobileentity:
id = ''
pseudonym = ''
trace = None
index_current_location = 0
in_mix_zone = False
mix_zone = None
number_of_anonymizations = 0
anon_history = None
def __init__(self, pseudonym, trace, id):
self.pseudonym = pseudonym
self.trace = [trace]
s... |
def searchInsert(nums: list(), target: int) -> int:
start, end = 0, len(nums)
if len(nums) == 0:
return 0
while start < end:
mid = (start + end) // 2
if target == nums[mid]:
return mid
elif target < nums[mid]:
end = mid
else:
start ... | def search_insert(nums: list(), target: int) -> int:
(start, end) = (0, len(nums))
if len(nums) == 0:
return 0
while start < end:
mid = (start + end) // 2
if target == nums[mid]:
return mid
elif target < nums[mid]:
end = mid
else:
s... |
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
memo = set()
for a in arr:
if a in memo: return True
if a%2==0:
memo.add(a//2)
memo.add(a*2)
return False | class Solution:
def check_if_exist(self, arr: List[int]) -> bool:
memo = set()
for a in arr:
if a in memo:
return True
if a % 2 == 0:
memo.add(a // 2)
memo.add(a * 2)
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.