content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Use binary search to find the key in the list
def binarySearch(lst, key):
low = 0
high = len(lst) - 1
while high >= low:
mid = (high + low) // 2
if key < lst[mid]:
high = mid - 1
elif key == lst[mid]:
return mid
else:
low = mid + 1
... | def binary_search(lst, key):
low = 0
high = len(lst) - 1
while high >= low:
mid = (high + low) // 2
if key < lst[mid]:
high = mid - 1
elif key == lst[mid]:
return mid
else:
low = mid + 1
return -low - 1
def main():
lst = [2, 4, 7, ... |
#Alian Colors #2
alian_color = 'green'
if alian_color == 'green' or alian_color == 'yellow' or alian_color == 'red':
print("You just earned 5 points.")
else:
print("You just earned 10 points.") | alian_color = 'green'
if alian_color == 'green' or alian_color == 'yellow' or alian_color == 'red':
print('You just earned 5 points.')
else:
print('You just earned 10 points.') |
class Solution:
# @param {integer[]} nums
# @return {integer}
def removeDuplicates(self, nums):
n = len(nums)
if n <=1:
return n
i= 0
j = 0
while(j < n):
if nums[j]!=nums[i]:
nums[i+1] = nums[j]
i += 1
... | class Solution:
def remove_duplicates(self, nums):
n = len(nums)
if n <= 1:
return n
i = 0
j = 0
while j < n:
if nums[j] != nums[i]:
nums[i + 1] = nums[j]
i += 1
j += 1
return i + 1 |
canMega = [3,6,9,15,18,65,80,94,127,130,142,150,181,208,212,214,229,248,254,257,260,282,302,303,306,308,310,319,323,334,354,359,373,376,380,381,384,428,445,448,460,475,531,719]
megaForms = [6,150]
def findMega(dex):
if dex in canMega:
if dex in megaForms:
return "This Pokemon has multiple Mega Evolutions."
els... | can_mega = [3, 6, 9, 15, 18, 65, 80, 94, 127, 130, 142, 150, 181, 208, 212, 214, 229, 248, 254, 257, 260, 282, 302, 303, 306, 308, 310, 319, 323, 334, 354, 359, 373, 376, 380, 381, 384, 428, 445, 448, 460, 475, 531, 719]
mega_forms = [6, 150]
def find_mega(dex):
if dex in canMega:
if dex in megaForms:
... |
alien_color = 'green'
print("alien_color = " + alien_color)
if alien_color == 'green':
print("You earned 5 points!")
elif alien_color == 'yellow':
print("You earned 10 points!")
else:
print("You earned 15 points!")
alien_color = 'yellow'
print("\nalien_color = " + alien_color)
if alien_color == 'green':
... | alien_color = 'green'
print('alien_color = ' + alien_color)
if alien_color == 'green':
print('You earned 5 points!')
elif alien_color == 'yellow':
print('You earned 10 points!')
else:
print('You earned 15 points!')
alien_color = 'yellow'
print('\nalien_color = ' + alien_color)
if alien_color == 'green':
... |
COL_TIME = 0
COL_OPEN = 1
COL_HIGH = 2
COL_LOW = 3
COL_CLOSE = 4
def max_close(candles):
c = [x[COL_CLOSE] for x in candles]
return max(c) | col_time = 0
col_open = 1
col_high = 2
col_low = 3
col_close = 4
def max_close(candles):
c = [x[COL_CLOSE] for x in candles]
return max(c) |
# Author : Nekyz
# Date : 29/06/2015
# Project Euler Challenge 1
def sum_of_multiple_of_3_and_5(number: int) -> int:
result = 0
for num in range(0, number):
if num % 3 == 0:
result += num
elif num % 5 == 0:
result += num
return result
print("#################... | def sum_of_multiple_of_3_and_5(number: int) -> int:
result = 0
for num in range(0, number):
if num % 3 == 0:
result += num
elif num % 5 == 0:
result += num
return result
print('###################################')
print('Project Euler, multiple of 3 and 5.')
print('#... |
"""
idx 0 1 2 3 4 5 6 7 n = 8
elm 1 1 2 3 0 0 0 0
i
res 1 0 0 2 3 0 0 4 5 0 0 fake_len = n + zeros
j
"""
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
... | """
idx 0 1 2 3 4 5 6 7 n = 8
elm 1 1 2 3 0 0 0 0
i
res 1 0 0 2 3 0 0 4 5 0 0 fake_len = n + zeros
j
"""
class Solution:
def duplicate_zeros(self, arr: List[int]) -> Non... |
def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return [
"VoxelBuffer",
"VoxelMap",
"Voxel",
"VoxelLibrary",
"VoxelTerrain",
"VoxelLodTerrain",
"VoxelStream",
"VoxelStreamFile",
"VoxelStreamBlockFiles",
"VoxelStreamRegionFile... | def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return ['VoxelBuffer', 'VoxelMap', 'Voxel', 'VoxelLibrary', 'VoxelTerrain', 'VoxelLodTerrain', 'VoxelStream', 'VoxelStreamFile', 'VoxelStreamBlockFiles', 'VoxelStreamRegionFiles', 'VoxelGenerator', 'VoxelGeneratorHei... |
fields = [
["#bEasy#k", 211042402],
["Normal", 211042400],
["#rChaos#k", 211042401]
]
# Zakum door portal
s = "Which difficulty of Zakum do you wish to fight? \r\n"
i = 0
for entry in fields:
s += "#L" + str(i) + "#" + entry[0] + "#l\r\n"
i += 1
answer = sm.sendSay(s)
sm.warp(fields[answer][1])
sm.dispose()
| fields = [['#bEasy#k', 211042402], ['Normal', 211042400], ['#rChaos#k', 211042401]]
s = 'Which difficulty of Zakum do you wish to fight? \r\n'
i = 0
for entry in fields:
s += '#L' + str(i) + '#' + entry[0] + '#l\r\n'
i += 1
answer = sm.sendSay(s)
sm.warp(fields[answer][1])
sm.dispose() |
class MEAPIUrls:
COLLECTION_STATS = 'https://api-mainnet.magiceden.io/rpc/getCollectionEscrowStats/'
COLLECTION_INFO = 'https://api-mainnet.magiceden.io/collections/'
COLLECTION_LIST = 'https://api-mainnet.magiceden.io/all_collections'
COLLECTION_LIST_STATS = 'https://api-mainnet.magiceden.io/rpc/getAgg... | class Meapiurls:
collection_stats = 'https://api-mainnet.magiceden.io/rpc/getCollectionEscrowStats/'
collection_info = 'https://api-mainnet.magiceden.io/collections/'
collection_list = 'https://api-mainnet.magiceden.io/all_collections'
collection_list_stats = 'https://api-mainnet.magiceden.io/rpc/getAgg... |
# http://codeforces.com/problemset/problem/318/A
n, k = map(int, input().split())
if k <= (n + 1) / 2:
print(k * 2 - 1)
else:
print(int(k - n / 2) * 2)
| (n, k) = map(int, input().split())
if k <= (n + 1) / 2:
print(k * 2 - 1)
else:
print(int(k - n / 2) * 2) |
class Solution:
def isPerfectSquare(self, num: int) -> bool:
i = 1
while i * i < num:
i += 1
return i * i == num
| class Solution:
def is_perfect_square(self, num: int) -> bool:
i = 1
while i * i < num:
i += 1
return i * i == num |
'''
import math
r=input(">>")
s=2*r*math.sin(math.pi/5)
Area=5*s*s/(4*math.tan(math.pi/5))
print(Area)
'''
'''
import math
x1,y1,x2,y2=input(">>")
x3,y3,x4,y4=math.radians(x1),math.radians(y1),math.radians(x2),math.radians(y2)
d=6371.01*math.acos(math.sin(x3)*math.sin(x4)+math.cos(x3)*math.cos(x4)*math.cos(y3-y4))
prin... | """
import math
r=input(">>")
s=2*r*math.sin(math.pi/5)
Area=5*s*s/(4*math.tan(math.pi/5))
print(Area)
"""
'\nimport math\nx1,y1,x2,y2=input(">>")\nx3,y3,x4,y4=math.radians(x1),math.radians(y1),math.radians(x2),math.radians(y2)\nd=6371.01*math.acos(math.sin(x3)*math.sin(x4)+math.cos(x3)*math.cos(x4)*math.cos(y3-y4))\np... |
# --------------
# Code starts here
# creating lists
class_1 = [ 'Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio' ]
class_2 = [ 'Hilary Mason', 'Carla Gentry', 'Corinna Cortes' ]
# concatinating lists
new_class = class_1 + class_2
# looking at the resultant list
print(new_class)
# appending 'Pet... | class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio']
class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes']
new_class = class_1 + class_2
print(new_class)
new_class.append('Peter Warden')
print(new_class)
new_class.remove('Carla Gentry')
print(new_class)
courses = {'Math': 65, 'English... |
class OslotsFeature(object):
def __init__(self, api, metaData, data):
self.api = api
self.meta = metaData
self.data = data[0]
self.maxSlot = data[1]
self.maxNode = data[2]
def items(self):
maxSlot = self.maxSlot
data = self.data
maxNode = self... | class Oslotsfeature(object):
def __init__(self, api, metaData, data):
self.api = api
self.meta = metaData
self.data = data[0]
self.maxSlot = data[1]
self.maxNode = data[2]
def items(self):
max_slot = self.maxSlot
data = self.data
max_node = self.... |
class Solution:
# Function to remove 2 chars by given index of the first char
def del_substr(i, s):
return s[:i] + s[i+2:]
def romanToInt(self, s: str) -> int:
# Roman numeral mapping
roman = {'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000}
# S... | class Solution:
def del_substr(i, s):
return s[:i] + s[i + 2:]
def roman_to_int(self, s: str) -> int:
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
special = {'IV': 4, 'IX': 9, 'XL': 40, 'XC': 90, 'CD': 400, 'CM': 900}
output = 0
for i in ran... |
"""Integration of psycopg2 with coroutine framework
"""
# Copyright (C) 2010-2020 Daniele Varrazzo <daniele.varrazzo@gmail.com>
# All rights reserved. See COPYING file for details.
__version__ = '1.0.2'
| """Integration of psycopg2 with coroutine framework
"""
__version__ = '1.0.2' |
"""
This is the "fizzbuzz" module.
The module supplies one function, fizzbuzz(), which is the classic coding test looking for factors of 3 and 5.
For example:
>>>fizzbuzz(15)
"FizzBuzz!"
"""
def fizzbuzz(x):
assert int(x), "Must be a number"
assert (x >= 0), 'Number must be greater than or equal to 0'
i... | """
This is the "fizzbuzz" module.
The module supplies one function, fizzbuzz(), which is the classic coding test looking for factors of 3 and 5.
For example:
>>>fizzbuzz(15)
"FizzBuzz!"
"""
def fizzbuzz(x):
assert int(x), 'Must be a number'
assert x >= 0, 'Number must be greater than or equal to 0'
if x ... |
# Configuration file for jupyter-notebook.
## Whether to allow the user to run the notebook as root.
c.NotebookApp.allow_root = True
## The IP address the notebook server will listen on.
c.NotebookApp.ip = '*'
## Whether to open in a browser after starting. The specific browser used is
# platform dependent and dete... | c.NotebookApp.allow_root = True
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.password = ''
c.NotebookApp.port = 8888
c.NotebookApp.token = '' |
class Solution:
# Built-in function
'''
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2) + int(b, 2))[2:]
'''
# Think binary as decimal way
def addBinary(self, a, b):
"""
:type ... | class Solution:
'''
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2) + int(b, 2))[2:]
'''
def add_binary(self, a, b):
"""
:type a: str
:type b: str
"""
(res, i, j, c) = (... |
{
"targets": [
{
"target_name": "node-xed",
"cflags!": ["-fno-exceptions"],
"cflags_cc!": ["-fno-exceptions"],
"sources": [
"cpp/node-xed.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api')... | {'targets': [{'target_name': 'node-xed', 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'sources': ['cpp/node-xed.cpp'], 'include_dirs': ['<!@(node -p "require(\'node-addon-api\').include")', 'cpp/include'], 'conditions': [['OS in "linux"', {'libraries': ['../cpp/lib/linux/libxed.a']}], ['OS in "win... |
# Program to Add Two Integers
def isNumber(num):
if(type(num) == type(1)):
return True
else:
return False
def add(num1, num2):
if(isNumber(num1) & isNumber(num2)):
return num1 + num2
else:
return "we only accept numbers."
# Test cases
print(add(1, 2))
print(add("hola",... | def is_number(num):
if type(num) == type(1):
return True
else:
return False
def add(num1, num2):
if is_number(num1) & is_number(num2):
return num1 + num2
else:
return 'we only accept numbers.'
print(add(1, 2))
print(add('hola', 1)) |
def is_valid(r: int, c: int):
global n
return (-1 < r < n) and (-1 < c < n)
n = int(input())
matrix = [[int(x) for x in input().split()] for _ in range(n)]
tokens = input()
while tokens != "END":
tokens = tokens.split()
cmd = tokens[0]
row = int(tokens[1])
col = int(tokens[2])
val = int(... | def is_valid(r: int, c: int):
global n
return -1 < r < n and -1 < c < n
n = int(input())
matrix = [[int(x) for x in input().split()] for _ in range(n)]
tokens = input()
while tokens != 'END':
tokens = tokens.split()
cmd = tokens[0]
row = int(tokens[1])
col = int(tokens[2])
val = int(tokens[3... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/9/20 10:02
# @Author : Peter
# @Des :
# @File : Callback
# @Software: PyCharm
def msg(msg, *arg, **kw):
print("---" * 60)
print("callback -------> {}".format(msg))
print("---" * 60)
if __name__ == "__main__":
pass
| def msg(msg, *arg, **kw):
print('---' * 60)
print('callback -------> {}'.format(msg))
print('---' * 60)
if __name__ == '__main__':
pass |
class CounterStat:
new = int
@staticmethod
def apply_diff(x, y):
return x + y
class SetStat:
new = set
class Diff:
def __init__(self, added=set(), removed=set()):
self.added = added
self.removed = removed
def invert(self):
self.added, ... | class Counterstat:
new = int
@staticmethod
def apply_diff(x, y):
return x + y
class Setstat:
new = set
class Diff:
def __init__(self, added=set(), removed=set()):
self.added = added
self.removed = removed
def invert(self):
(self.added,... |
class Solution:
def heightChecker(self, heights: List[int]) -> int:
new_heights = sorted(heights)
count = 0
for i in range(len(heights)):
if heights[i] != new_heights[i]:
count += 1
return count
| class Solution:
def height_checker(self, heights: List[int]) -> int:
new_heights = sorted(heights)
count = 0
for i in range(len(heights)):
if heights[i] != new_heights[i]:
count += 1
return count |
# -*- coding: utf-8 -*-
A_INDEX = 0
B_INDEX = 1
C_INDEX = 2
D_INDEX = 3
def main():
values = input().split()
a = int(values[A_INDEX])
b = int(values[B_INDEX])
c = int(values[C_INDEX])
d = int(values[D_INDEX])
if b > c and d > a and c + d > a + b and c > 0 and d > 0 and a % 2 == 0:
pri... | a_index = 0
b_index = 1
c_index = 2
d_index = 3
def main():
values = input().split()
a = int(values[A_INDEX])
b = int(values[B_INDEX])
c = int(values[C_INDEX])
d = int(values[D_INDEX])
if b > c and d > a and (c + d > a + b) and (c > 0) and (d > 0) and (a % 2 == 0):
print('Valores aceito... |
"""
https://leetcode.com/problems/reverse-words-in-a-string-iii/
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string... | """
https://leetcode.com/problems/reverse-words-in-a-string-iii/
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string... |
# The realm, where users are allowed to login as administrators
SUPERUSER_REALM = ['super', 'administrators']
# Your database mysql://u:p@host/db
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:Pa55w0rd@localhost:5432/privacy_idea'
# This is used to encrypt the auth_token
SECRET_KEY = 't0p s3cr3t'
# This is used to en... | superuser_realm = ['super', 'administrators']
sqlalchemy_database_uri = 'postgresql://postgres:Pa55w0rd@localhost:5432/privacy_idea'
secret_key = 't0p s3cr3t'
pi_pepper = 'Never know...'
pi_encfile = '/opt/conda/envs/privacyidea/lib/python3.7/site-packages/enckey'
pi_audit_key_private = '/opt/conda/envs/privacyidea/lib... |
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
# https://discuss.leetcode.com/topic/5088/my-ac-is-o-1-space-o-n-running-time-solution-does-anybody-have-posted-this-solution
ls = l... | class Solution(object):
def can_complete_circuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
ls = len(gas)
(begin, end) = (0, ls - 1)
curr = gas[end] - cost[end]
while begin < end:
if curr >= 0:... |
# program to split email to username and domain name
# made by itsmeevil
print("***Email Splitter***")
email = input("\nEnter an email: ")
sliced = email.split("@") # split string at "@" which will put it in an array- ["username", "domain name"]
print(f"\nUsername: {sliced[0]}\nDomain name: {sliced[1]}")
| print('***Email Splitter***')
email = input('\nEnter an email: ')
sliced = email.split('@')
print(f'\nUsername: {sliced[0]}\nDomain name: {sliced[1]}') |
class SocialMedia:
def __init__(self):
pass
def GetSocialMediaSites_NiceNames(self):
return {
'add.this':'AddThis',
'blogger':'Blogger',
'buffer':'Buffer',
'diaspora':'Diaspora',
'douban':'Douban',
'email':'EMail',
... | class Socialmedia:
def __init__(self):
pass
def get_social_media_sites__nice_names(self):
return {'add.this': 'AddThis', 'blogger': 'Blogger', 'buffer': 'Buffer', 'diaspora': 'Diaspora', 'douban': 'Douban', 'email': 'EMail', 'evernote': 'EverNote', 'getpocket': 'Pocket', 'facebook': 'FaceBook'... |
"""QwikSwitch USB Modem library for Python.
See: http://www.qwikswitch.co.za/qs-usb.php
Currently supports relays, buttons and LED dimmers
Source: http://www.github.com/kellerza/pyqwikswitch
"""
| """QwikSwitch USB Modem library for Python.
See: http://www.qwikswitch.co.za/qs-usb.php
Currently supports relays, buttons and LED dimmers
Source: http://www.github.com/kellerza/pyqwikswitch
""" |
class ResistanceValue:
RESISTANCE_VALUES = [
(10, ["brown", "black"]),
(12, ["brown", "red"]),
(15, ["brown", "green"]),
(18, ["brown", "grey"]),
(22, ["red", "red"]),
(27, ["red", "purple"]),
(33, ["orange", "orange"]),
(39, ["orange", "white"]),
... | class Resistancevalue:
resistance_values = [(10, ['brown', 'black']), (12, ['brown', 'red']), (15, ['brown', 'green']), (18, ['brown', 'grey']), (22, ['red', 'red']), (27, ['red', 'purple']), (33, ['orange', 'orange']), (39, ['orange', 'white']), (47, ['yellow', 'purple']), (56, ['green', 'blue']), (68, ['green', '... |
"""
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
num = 2520
def divideby(numbers):
for div in range(1,11):
if not(numbers %div == 0):
... | """
2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
"""
num = 2520
def divideby(numbers):
for div in range(1, 11):
if not numbers % div == 0:
... |
def url(your_url):
root = 'https://sandboxapi.fsi.ng'
if your_url:
root = your_url
return root
| def url(your_url):
root = 'https://sandboxapi.fsi.ng'
if your_url:
root = your_url
return root |
N = int(input())
print("*"*N)
for i in range(N//2-1):
print("*"*((N//2-i)) + " "*(N-2*(N//2-i)) + "*"*((N//2-i)))
print("*" + " "*(N-2) + "*")
for i in range(N//2-2, -1, -1):
print("*"*((N//2-i)) + " "*(N-2*(N//2-i)) + "*"*((N//2-i)))
print("*"*N)
| n = int(input())
print('*' * N)
for i in range(N // 2 - 1):
print('*' * (N // 2 - i) + ' ' * (N - 2 * (N // 2 - i)) + '*' * (N // 2 - i))
print('*' + ' ' * (N - 2) + '*')
for i in range(N // 2 - 2, -1, -1):
print('*' * (N // 2 - i) + ' ' * (N - 2 * (N // 2 - i)) + '*' * (N // 2 - i))
print('*' * N) |
"""
LeetCode Problem: 692. Top K Frequent Words
Link: https://leetcode.com/problems/top-k-frequent-words/
Language: Python
Written by: Mostofa Adib Shakib
Approach:
Use dict to find count of words
Add words and count to heap with negative count[by-default its min-heap, and we want max heap]
For adding... | """
LeetCode Problem: 692. Top K Frequent Words
Link: https://leetcode.com/problems/top-k-frequent-words/
Language: Python
Written by: Mostofa Adib Shakib
Approach:
Use dict to find count of words
Add words and count to heap with negative count[by-default its min-heap, and we want max heap]
For adding... |
class Solution:
def isMatch(self, s: str, p: str) -> bool:
dp = [[False for _ in range(len(s) + 1)] for _ in range(len(p) + 1)]
dp[0][0] = True
for i in range(1,len(p)+1):
if p[i-1] == '*':
dp[i][0] = dp[i-1][0]
else:
break
... | class Solution:
def is_match(self, s: str, p: str) -> bool:
dp = [[False for _ in range(len(s) + 1)] for _ in range(len(p) + 1)]
dp[0][0] = True
for i in range(1, len(p) + 1):
if p[i - 1] == '*':
dp[i][0] = dp[i - 1][0]
else:
break
... |
class Solution:
"""
@param num: a string
@param k: an integer
@return: return a string
"""
def removeKdigits(self, num, k):
# write your code here
St = []
for c in num:
while St and c < St[-1] and k > 0:
St.pop()
k -= 1
... | class Solution:
"""
@param num: a string
@param k: an integer
@return: return a string
"""
def remove_kdigits(self, num, k):
st = []
for c in num:
while St and c < St[-1] and (k > 0):
St.pop()
k -= 1
St.append(c)
re... |
#!/usr/bin/env python
# encoding=utf-8
"""
Copyright (c) 2021 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFT... | """
Copyright (c) 2021 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
# Leo colorizer control file for md mode.
# This file is in the public domain.
# Properties for md mode.
# Important: most of this file is actually an html colorizer.
properties = {
"commentEnd": "-->",
"commentStart": "<!--",
"indentSize": "4",
"maxLineLen": "120",
"tabSize": "4",
}
... | properties = {'commentEnd': '-->', 'commentStart': '<!--', 'indentSize': '4', 'maxLineLen': '120', 'tabSize': '4'}
md_main_attributes_dict = {'default': 'null', 'digit_re': '', 'escape': '', 'highlight_digits': 'true', 'ignore_case': 'true', 'no_word_sep': ''}
md_inline_markup_attributes_dict = {'default': 'MARKUP', 'd... |
lista = ('APRENDER', 'PROGRAMA', 'LINGUAGES', 'PYTHON', 'CURSO',
'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCAADO',
'PROGRAMADOR', 'FUTURO')
for palavras in lista:
print(f'\nNa palavra {palavras} temos: ', end='')
for vogais in palavras:
if vogais in 'AEIOU':
pri... | lista = ('APRENDER', 'PROGRAMA', 'LINGUAGES', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCAADO', 'PROGRAMADOR', 'FUTURO')
for palavras in lista:
print(f'\nNa palavra {palavras} temos: ', end='')
for vogais in palavras:
if vogais in 'AEIOU':
print(vogais, end=' ') |
# Strings - this is how you type a comment in python
'Hello world using single quotes'
"Hello world using double quotes"
"""Hello world using
triple quotes, also known as
multi-line strings"""
# To print an object to the screen, use the print function
print('Hello world') # This will print Hello World in the terminal... | """Hello world using single quotes"""
'Hello world using double quotes'
'Hello world using\ntriple quotes, also known as\nmulti-line strings'
print('Hello world')
print("I'm using an apostrophe in this statement")
print('This is a "quote from a book" which I like')
message = "Hello! welcome to the Algorithm's course"
n... |
# -*- coding: utf-8 -*-
# package information.
INFO = dict(
name='coil',
description='Scheme interpreter written in Python',
author='coilo',
author_email='coilo.dev@gmail.com',
license='MIT License',
url='https://github.com/coilo/coil',
classifiers=[
'Programming Language :: Python... | info = dict(name='coil', description='Scheme interpreter written in Python', author='coilo', author_email='coilo.dev@gmail.com', license='MIT License', url='https://github.com/coilo/coil', classifiers=['Programming Language :: Python :: 3.4', 'License :: OSI Approved :: MIT License']) |
text = """
//---------------------------------Spheral++----------------------------------//
// HatKernel -- The B spline interpolation kernel.
//
// Created by JMO, Wed Dec 11 17:33:57 PST 2002
//----------------------------------------------------------------------------//
#include "Kernel.hh"
#include "HatKernel.hh"
... | text = '\n//---------------------------------Spheral++----------------------------------//\n// HatKernel -- The B spline interpolation kernel.\n//\n// Created by JMO, Wed Dec 11 17:33:57 PST 2002\n//----------------------------------------------------------------------------//\n#include "Kernel.hh"\n#include "HatKernel... |
def foo(x):
def bar(x, y):
return lambda y: y(x)
return lambda y: bar(x, y)
print(foo(lambda x: x**3)(lambda x: x**2)(lambda x: x)(4)) | def foo(x):
def bar(x, y):
return lambda y: y(x)
return lambda y: bar(x, y)
print(foo(lambda x: x ** 3)(lambda x: x ** 2)(lambda x: x)(4)) |
# 190. Reverse Bits
# ttungl@gmail.com
# Reverse bits of a given 32 bits unsigned integer.
# For example, given input 43261596 (represented in binary as 00000010100101000001111010011100),
# return 964176192 (represented in binary as 00111001011110000010100101000000).
# Follow up:
# If this function is called many ti... | class Solution:
def reverse_bits(self, n):
res = 0
for i in range(32):
res <<= 1
res |= n & 1
n >>= 1
return res
res = str(bin(n))
pad = int(32 - len(res) + 2) * '0'
return int(res[0:2] + res[2:][::-1] + pad, 2) |
class Movie:
def __init__(self,title,year,imdb_score,have_seen):
self.title = title
self.year = year
self.imdb_score = imdb_score
self.have_seen = have_seen
def nice_print(self):
print("Title: ", self.title)
print("Year of production: ", self.year)
pr... | class Movie:
def __init__(self, title, year, imdb_score, have_seen):
self.title = title
self.year = year
self.imdb_score = imdb_score
self.have_seen = have_seen
def nice_print(self):
print('Title: ', self.title)
print('Year of production: ', self.year)
p... |
#!/usr/bin/env python3
class AppException(Exception):
status_code = 400
def __init__(self, message):
Exception.__init__(self)
self.message = message
def to_dict(self):
return {'message': self.message}
class DeviceNotFoundException(AppException):
status_code = 404
class Ups... | class Appexception(Exception):
status_code = 400
def __init__(self, message):
Exception.__init__(self)
self.message = message
def to_dict(self):
return {'message': self.message}
class Devicenotfoundexception(AppException):
status_code = 404
class Upstreamapiexception(AppExcep... |
# Copyright Pincer 2021-Present
# Full MIT License can be found in `LICENSE` at the project root.
"""sent when the client's voice settings update"""
# TODO: Implement event
| """sent when the client's voice settings update""" |
saludo = "buenos dias"
for i in range(20):
print(saludo)
| saludo = 'buenos dias'
for i in range(20):
print(saludo) |
def test_spec_gui(specviz_gui):
"""
Generic test to ensure the pytest fixture is properly feeding an instance
of the specviz application.
"""
assert specviz_gui is not None
| def test_spec_gui(specviz_gui):
"""
Generic test to ensure the pytest fixture is properly feeding an instance
of the specviz application.
"""
assert specviz_gui is not None |
class ModuleBase():
# Invalid slot for modular chassis
MODULE_INVALID_SLOT = -1
# Possible card types for modular chassis
MODULE_TYPE_SUPERVISOR = "SUPERVISOR"
MODULE_TYPE_LINE = "LINE-CARD"
MODULE_TYPE_FABRIC = "FABRIC-CARD"
# Possible card status for modular chassis
# Module stat... | class Modulebase:
module_invalid_slot = -1
module_type_supervisor = 'SUPERVISOR'
module_type_line = 'LINE-CARD'
module_type_fabric = 'FABRIC-CARD'
module_status_empty = 'Empty'
module_status_offline = 'Offline'
module_status_present = 'Present'
module_status_fault = 'Fault'
module_st... |
#!/usr/bin/env python3
class Furnishings:
def __init__(self,room):
self.room = room
class Sofa(Furnishings):
pass
class Bookshelf(Furnishings):
pass
class Bed(Furnishings):
pass
class Table(Furnishings):
pass
def map_the_home(home):
home_map = {}
for fu... | class Furnishings:
def __init__(self, room):
self.room = room
class Sofa(Furnishings):
pass
class Bookshelf(Furnishings):
pass
class Bed(Furnishings):
pass
class Table(Furnishings):
pass
def map_the_home(home):
home_map = {}
for furniture in home:
if furniture.__dict__[... |
def setToken():
"""Authentication TOKEN for Telegram API
"""
token = ""
return token
| def set_token():
"""Authentication TOKEN for Telegram API
"""
token = ''
return token |
# -*- coding: utf-8 -*-
"""spear2sc.spear_utils: Utitlity methods to read SPEAR files"""
def process_line(line):
""" (list of str) -> list of list of float
Parses line, a line of time, frequency and amplitude data output by
SPEAR in the 'text - partials' format.
Returns a list of timepoints. Each ti... | """spear2sc.spear_utils: Utitlity methods to read SPEAR files"""
def process_line(line):
""" (list of str) -> list of list of float
Parses line, a line of time, frequency and amplitude data output by
SPEAR in the 'text - partials' format.
Returns a list of timepoints. Each timepoint is a list of float... |
inputstart = int(input('Enter the beginning of the interval: '))
inputend = int(input('Enter the end of the interval: '))
for i in range(inputstart, inputend): # Iterating over numbers from a given interval
firstnum = 0 # The sum of the divisors of the second number = The first number of the pair
... | inputstart = int(input('Enter the beginning of the interval: '))
inputend = int(input('Enter the end of the interval: '))
for i in range(inputstart, inputend):
firstnum = 0
secnum = 0
for x in range(1, i):
if i % x == 0:
secnum += x
for y in range(1, secnum):
if secnum % y ==... |
class QvaPayException(Exception):
def __init__(self, status_code: int, *args: object) -> None:
super().__init__(*args)
self.status_code = status_code
| class Qvapayexception(Exception):
def __init__(self, status_code: int, *args: object) -> None:
super().__init__(*args)
self.status_code = status_code |
def mutable_or_immutable(para):
para += '1'
a = 'a'
b = ['b']
mutable_or_immutable(a)
print(a)
mutable_or_immutable(b)
print(b) | def mutable_or_immutable(para):
para += '1'
a = 'a'
b = ['b']
mutable_or_immutable(a)
print(a)
mutable_or_immutable(b)
print(b) |
#
# PySNMP MIB module HPR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:42:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)... | (sna_control_point_name,) = mibBuilder.importSymbols('APPN-MIB', 'SnaControlPointName')
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, val... |
RESULT = "result"
SUCCESS = "success"
ERROR = "error"
MESSAGE = "message"
CODE = "code"
PROPERTIES = 'properties'
MISSED_KEYS = {
"format": {
"type": "string"
}, "$ref": {
"type": "string",
"format": "uri"
}
}
| result = 'result'
success = 'success'
error = 'error'
message = 'message'
code = 'code'
properties = 'properties'
missed_keys = {'format': {'type': 'string'}, '$ref': {'type': 'string', 'format': 'uri'}} |
# We just put it here to get the checks to shut up
MIDDLEWARE_CLASSES = []
INSTALLED_APPS = (
'django.contrib.sites',
'absoluteuri',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
}
}
SITE_ID = 1
ROOT_URLCONF = 'absoluteuri.tests'
TEMPLATES = [
{
'BACKEND':... | middleware_classes = []
installed_apps = ('django.contrib.sites', 'absoluteuri')
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3'}}
site_id = 1
root_urlconf = 'absoluteuri.tests'
templates = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True}] |
underworld_graph = {
992: {
"title": "Darkness",
"description": "You are standing on grass and surrounded by darkness.",
"terrain": "NORMAL",
"coordinates": "(75,61)",
"elevation": 0,
"w": 966
},
966: {
"title": "Darkness",
"description": "You ... | underworld_graph = {992: {'title': 'Darkness', 'description': 'You are standing on grass and surrounded by darkness.', 'terrain': 'NORMAL', 'coordinates': '(75,61)', 'elevation': 0, 'w': 966}, 966: {'title': 'Darkness', 'description': 'You are standing on grass and surrounded by darkness.', 'terrain': 'NORMAL', 'coordi... |
class Tape:
"""
Allows writing to end of a file-like object while maintaining the read pointer accurately.
The read operation actually removes characters read from the buffer.
"""
def __init__(self, initial_value:str=''):
"""
:param initial_value: initialize the Tape with a preset s... | class Tape:
"""
Allows writing to end of a file-like object while maintaining the read pointer accurately.
The read operation actually removes characters read from the buffer.
"""
def __init__(self, initial_value: str=''):
"""
:param initial_value: initialize the Tape with a preset ... |
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
'''
T: O(n!) and S: O(n!)
'''
def permute(nums):
n = len(nums)
if n <= 1: return [nums]
out = []
for i in range(n):
first = [nums[... | class Solution:
def permute_unique(self, nums: List[int]) -> List[List[int]]:
"""
T: O(n!) and S: O(n!)
"""
def permute(nums):
n = len(nums)
if n <= 1:
return [nums]
out = []
for i in range(n):
first = ... |
"""Constants for the Sure Petcare component."""
DOMAIN = "sureha"
SPC = "spc"
# platforms
TOPIC_UPDATE = f"{DOMAIN}_data_update"
# sure petcare api
SURE_API_TIMEOUT = 60
# device info
SURE_MANUFACTURER = "Sure Petcare"
# batteries
ATTR_VOLTAGE_FULL = "voltage_full"
ATTR_VOLTAGE_LOW = "voltage_low"
SURE_BATT_VOLTAG... | """Constants for the Sure Petcare component."""
domain = 'sureha'
spc = 'spc'
topic_update = f'{DOMAIN}_data_update'
sure_api_timeout = 60
sure_manufacturer = 'Sure Petcare'
attr_voltage_full = 'voltage_full'
attr_voltage_low = 'voltage_low'
sure_batt_voltage_full = 1.6
sure_batt_voltage_low = 1.25
sure_batt_voltage_di... |
__HEXCODE = "0123456789abcdef"
def byteToHex(someValue:int) -> str:
assert isinstance(someValue, int)
someValue = someValue & 255
return __HEXCODE[int(someValue / 16)] + __HEXCODE[someValue % 16]
def byteArrayToHexStr(someByteArray) -> str:
assert isinstance(someByteArray, (bytes, bytearray))
ret = ""
for... | __hexcode = '0123456789abcdef'
def byte_to_hex(someValue: int) -> str:
assert isinstance(someValue, int)
some_value = someValue & 255
return __HEXCODE[int(someValue / 16)] + __HEXCODE[someValue % 16]
def byte_array_to_hex_str(someByteArray) -> str:
assert isinstance(someByteArray, (bytes, bytearray))
... |
def trap(height):
'''Algo:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Output: Number of units of water trapped
Input: List of the brick walls position
Steps:
Observations:
find all subsequences s... | def trap(height):
"""Algo:
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Output: Number of units of water trapped
Input: List of the brick walls position
Steps:
Observations:
find all subsequences s... |
def combination(n, r):
if n < r:
return 0
if r == 0:
return 1
tmp_n = 1
for i in range(r):
tmp_n *= n - i
tmp_r = 1
for i in range(r):
tmp_r *= r - i
return tmp_n // tmp_r
n, r = map(int, input().split())
print(combination(n, r))
def cmb(n, r):
if n - r ... | def combination(n, r):
if n < r:
return 0
if r == 0:
return 1
tmp_n = 1
for i in range(r):
tmp_n *= n - i
tmp_r = 1
for i in range(r):
tmp_r *= r - i
return tmp_n // tmp_r
(n, r) = map(int, input().split())
print(combination(n, r))
def cmb(n, r):
if n - r... |
'''
Created on Apr 20, 2017
@author: simulant
'''
| """
Created on Apr 20, 2017
@author: simulant
""" |
def iSort(lst,newl = [],n=1):
if len(lst)>0:
# print(newl,lst)
compInsert(newl,lst.pop(0),len(newl)-1)
if len(newl)>1:
print(newl,end=" ")
if len(lst)>0:
print(lst)
else:
print('\n',"sorted\n",newl,sep="")
iSort(lst,... | def i_sort(lst, newl=[], n=1):
if len(lst) > 0:
comp_insert(newl, lst.pop(0), len(newl) - 1)
if len(newl) > 1:
print(newl, end=' ')
if len(lst) > 0:
print(lst)
else:
print('\n', 'sorted\n', newl, sep='')
i_sort(lst, newl, n ... |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 12930.py
# Description: UVa Online Judge - 12930
# =============================================================================
nt = 0
whil... | nt = 0
while True:
try:
line = input()
except EOFError:
break
nt += 1
line = line.split()
n_frac1 = len(line[0]) - line[0].find('.') - 1
n_frac2 = len(line[1]) - line[1].find('.') - 1
if n_frac1 < max(n_frac1, n_frac2):
line[0] += '0' * (max(n_frac1, n_frac2) - n_frac... |
consumer_key = '123456'
consumer_secret = '123456'
flickr_key = '123456'
flickr_secret = '123456'
| consumer_key = '123456'
consumer_secret = '123456'
flickr_key = '123456'
flickr_secret = '123456' |
class TerminalColours:
"""
Colours for displaying success or failure of
request on stdout
"""
GREEN = '\033[92m'
RED = '\033[91m'
PURPLE = '\033[95m'
YELLOW = '\033[33m'
BLUE = '\033[96m'
| class Terminalcolours:
"""
Colours for displaying success or failure of
request on stdout
"""
green = '\x1b[92m'
red = '\x1b[91m'
purple = '\x1b[95m'
yellow = '\x1b[33m'
blue = '\x1b[96m' |
'''69-crie um programa que leia a idade e o sexo de varias pessoas.a cada pessoa cadastrada, o programa devera perguntar se o usuario quer ou nao continuar.no final mostre:
A- quantas pessoas tem mais de 18 anos.
B- quantos homensforam cadastrados.
C- quantas mulheres tem menos de 20 anos. '''
tot18=toth=totm20=0
c... | """69-crie um programa que leia a idade e o sexo de varias pessoas.a cada pessoa cadastrada, o programa devera perguntar se o usuario quer ou nao continuar.no final mostre:
A- quantas pessoas tem mais de 18 anos.
B- quantos homensforam cadastrados.
C- quantas mulheres tem menos de 20 anos. """
tot18 = toth = totm20 ... |
# define variables
a = 10
b = 20
# swap numbers
a,b = b,a
# print result
print(a, b) | a = 10
b = 20
(a, b) = (b, a)
print(a, b) |
''' ATRIBUTOS DE UM ARQUIVO'''
arquivo = open('dados1.txt', 'r')
conteudo = arquivo.readlines()
print('tipo de conteudo, ', type (conteudo))
print('conteudo retornado pelo realines: ')
print(repr(conteudo))
arquivo.close()
| """ ATRIBUTOS DE UM ARQUIVO"""
arquivo = open('dados1.txt', 'r')
conteudo = arquivo.readlines()
print('tipo de conteudo, ', type(conteudo))
print('conteudo retornado pelo realines: ')
print(repr(conteudo))
arquivo.close() |
# Convert algebraic infix notation to revese polish notation (postfix)
def infixToPostfix(expr):
rpn = ""
stack = []
oper = "(+-*/^"
for e in expr:
if e.lower() >= "a" and e <= "z":
rpn += e
elif e == ")":
while len(stack) > 0:
op = stack.pop()
... | def infix_to_postfix(expr):
rpn = ''
stack = []
oper = '(+-*/^'
for e in expr:
if e.lower() >= 'a' and e <= 'z':
rpn += e
elif e == ')':
while len(stack) > 0:
op = stack.pop()
if op == '(':
break
... |
class Action_Keys():
def __init__(self, game_name):
self.game_name = game_name
def action_keys_Convert(self, key):
if self.game_name == 'Enduro':
return action_keys_Convert_Enduro(key)
elif self.game_name == 'SpaceInvaders':
return action_keys_C... | class Action_Keys:
def __init__(self, game_name):
self.game_name = game_name
def action_keys__convert(self, key):
if self.game_name == 'Enduro':
return action_keys__convert__enduro(key)
elif self.game_name == 'SpaceInvaders':
return action_keys__convert__space_i... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@build_bazel_rules_nodejs//:index.bzl", "yarn_install")
def rules_typescript_proto_dependencies():
"""
Installs rules_typescript_proto dependencies.
Usage:
# WORKSPACE
load("@rules_typescript_proto//:index.bzl", "rules_typ... | load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@build_bazel_rules_nodejs//:index.bzl', 'yarn_install')
def rules_typescript_proto_dependencies():
"""
Installs rules_typescript_proto dependencies.
Usage:
# WORKSPACE
load("@rules_typescript_proto//:index.bzl", "rules_typ... |
def prod(numbers):
"""
Find the product of a sequence
:param numbers: Sequence of numbers
:return: Their product
"""
ret = 1
for number in numbers:
ret *= number
return ret | def prod(numbers):
"""
Find the product of a sequence
:param numbers: Sequence of numbers
:return: Their product
"""
ret = 1
for number in numbers:
ret *= number
return ret |
class Slave:
""" define slaves in socket programing.
"""
def __init__(self, host_port: str):
if ":" not in host_port:
raise ValueError(
"The format of slave definition is incorrect, should be <host>:<port>")
splits = host_port.lstrip().rstrip().split(":")
... | class Slave:
""" define slaves in socket programing.
"""
def __init__(self, host_port: str):
if ':' not in host_port:
raise value_error('The format of slave definition is incorrect, should be <host>:<port>')
splits = host_port.lstrip().rstrip().split(':')
self.host = spl... |
def hex_to_rgb(hex_color, base=256):
return tuple(int(hex_color[i:i + 2], 16) for i in (1, 3, 5))
def rgb_to_hex(rgb, with_sharp=False, upper=True):
hex_code = ''.join([hex(one_channel)[2:] for one_channel in rgb])
if with_sharp:
hex_code = '#' + hex_code
if upper:
hex_code = hex_code... | def hex_to_rgb(hex_color, base=256):
return tuple((int(hex_color[i:i + 2], 16) for i in (1, 3, 5)))
def rgb_to_hex(rgb, with_sharp=False, upper=True):
hex_code = ''.join([hex(one_channel)[2:] for one_channel in rgb])
if with_sharp:
hex_code = '#' + hex_code
if upper:
hex_code = hex_code... |
# add two numbers using function without return
'''def add(x,y):
print("addition is : ",(x+y))
x = int(input("Enter a first number for addition : "))
y = int(input("Enter a second number for addition : "))
add(x,y)'''
# add two numbers using function with return
'''def add(x,y):
return (x+y)
x = int(input("Ent... | """def add(x,y):
print("addition is : ",(x+y))
x = int(input("Enter a first number for addition : "))
y = int(input("Enter a second number for addition : "))
add(x,y)"""
'def add(x,y):\n return (x+y)\nx = int(input("Enter a first number for addition : "))\ny = int(input("Enter a second number for addition : "))\... |
"""
blobcli
----
Command line interface for easy operation with blobs in Azure Blob Storage.
"""
__version__ = '0.0.6'
| """
blobcli
----
Command line interface for easy operation with blobs in Azure Blob Storage.
"""
__version__ = '0.0.6' |
string = input("Ingrese la palabra a enmarcar: ")
num = int(input("Ingrese la cantidad de espacios entre el marco y la palabra"))
arribaAbajo = "*" * (len(string) + (num*2)+2)+ "\n"
laterales = "*" + " " * (len(string) + num*2) + "*\n"
resultado = arribaAbajo
for i in range(num):
resultado += laterales
resultado +=... | string = input('Ingrese la palabra a enmarcar: ')
num = int(input('Ingrese la cantidad de espacios entre el marco y la palabra'))
arriba_abajo = '*' * (len(string) + num * 2 + 2) + '\n'
laterales = '*' + ' ' * (len(string) + num * 2) + '*\n'
resultado = arribaAbajo
for i in range(num):
resultado += laterales
result... |
# At each point 3 choice possible
# 1. ith element.
# 2. max -ve before ith * ith element
# 3. max +ve before ith * ith element
# TC: O(n) | SC: O(1)
def solution_1(arr):
max_product = arr[0]
min_product = arr[0]
answer = arr[0]
for i in range(1, len(arr)):
choice1 = min_product*... | def solution_1(arr):
max_product = arr[0]
min_product = arr[0]
answer = arr[0]
for i in range(1, len(arr)):
choice1 = min_product * arr[i]
choice2 = max_product * arr[i]
min_product = min(arr[i], choice1, choice2)
max_product = max(arr[i], choice1, choice2)
answer... |
# set of rules that are expected to work for all supported frameworks
# Supported Frameworks: Mxnet, Pytorch, Tensorflow, Xgboost
UNIVERSAL_RULES = {
"AllZero",
"ClassImbalance",
"Confusion",
"LossNotDecreasing",
"Overfit",
"Overtraining",
"SimilarAcrossRuns",
"StalledTrainingRule",
... | universal_rules = {'AllZero', 'ClassImbalance', 'Confusion', 'LossNotDecreasing', 'Overfit', 'Overtraining', 'SimilarAcrossRuns', 'StalledTrainingRule', 'UnchangedTensor'}
deep_learning_rules = {'DeadRelu', 'ExplodingTensor', 'PoorWeightInitialization', 'SaturatedActivation', 'TensorVariance', 'VanishingGradient', 'Wei... |
__author__ = 'surya'
prey="This will give the list of prey protein used in the experiment"
bait="This will give all information of the Bait protein used in the experiment"
molecule="This will give all information store in the database about small molecule, if used in the experiment"
SdFound="This will give the list o... | __author__ = 'surya'
prey = 'This will give the list of prey protein used in the experiment'
bait = 'This will give all information of the Bait protein used in the experiment'
molecule = 'This will give all information store in the database about small molecule, if used in the experiment'
sd_found = 'This will give the... |
#
# PySNMP MIB module CISCO-TCPOFFLOAD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TCPOFFLOAD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:14:11 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, constraints_intersection, value_range_constraint, single_value_constraint, constraints_union) ... |
'''given an array of integers, return indices of the two numbers such that they add up to a specific problem
given nums = [2, 7, 11, 15], target = 9
because nums[0] + nums[1] = 2 + 7 = 9
return [0, 1]
'''
#this is a great time to use a hash table
#class Solution(object):
def twoSum(nums, target):
index_mapping... | """given an array of integers, return indices of the two numbers such that they add up to a specific problem
given nums = [2, 7, 11, 15], target = 9
because nums[0] + nums[1] = 2 + 7 = 9
return [0, 1]
"""
def two_sum(nums, target):
index_mapping = {}
for i in range(len(nums)):
current = nums[i]
... |
def arrayMaximalAdjacentDifference(inputArray):
return max([abs(inputArray[x] - inputArray[x + 1]) for x in range(len(inputArray) - 1)])
# [2. 4, 1, 0] => 3
# [1, 1, 1, 1] => 1
# [-1, 4, 10, 3, -2] => 7
# [10, 11, 13] => 2
print(arrayMaximalAdjacentDifference([1, 1, 1, 1])) | def array_maximal_adjacent_difference(inputArray):
return max([abs(inputArray[x] - inputArray[x + 1]) for x in range(len(inputArray) - 1)])
print(array_maximal_adjacent_difference([1, 1, 1, 1])) |
[
{'base_name': 'PanSTARRS',
'service_type': 'xcone',
'adql': '',
'access_url': 'https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr2/'
'mean.votable?flatten_response=false&raw=false&sort_by=distance'
'&ra={}&dec={}&radius={}'
}
]
| [{'base_name': 'PanSTARRS', 'service_type': 'xcone', 'adql': '', 'access_url': 'https://catalogs.mast.stsci.edu/api/v0.1/panstarrs/dr2/mean.votable?flatten_response=false&raw=false&sort_by=distance&ra={}&dec={}&radius={}'}] |
"""
Question: Search in Rotated Sorted Array
Difficulty: Medium
Link: https://leetcode.com/problems/search-in-rotated-sorted-array/
Ref: https://xiaozhuanlan.com/topic/2039467185
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might ... | """
Question: Search in Rotated Sorted Array
Difficulty: Medium
Link: https://leetcode.com/problems/search-in-rotated-sorted-array/
Ref: https://xiaozhuanlan.com/topic/2039467185
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might ... |
# https://www.codewars.com/kata/5174a4c0f2769dd8b1000003
# Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array.
# For example:
# solution([1,2,3,10,5]) # should return [1,2,3,5,10]
# solution(None) # should ... | def solution(nums):
return sorted(nums) if nums != None else []
print(solution([1, 2, 3, 10, 5]), [1, 2, 3, 5, 10])
print(solution(None), [])
print(solution([]), [])
print(solution([20, 2, 10]), [2, 10, 20])
print(solution([2, 20, 10]), [2, 10, 20]) |
"""
File: similarity.py
Name:
----------------------------
This program compares short dna sequence, s2,
with sub sequences of a long dna sequence, s1
The way of approaching this task is the same as
what people are doing in the bio industry.
"""
def main():
"""
find the best match of the long DNA strand to th... | """
File: similarity.py
Name:
----------------------------
This program compares short dna sequence, s2,
with sub sequences of a long dna sequence, s1
The way of approaching this task is the same as
what people are doing in the bio industry.
"""
def main():
"""
find the best match of the long DNA strand to the... |
# File for describing the Cab entity.
class Cab:
def __init__(self, city:str, brand: str, hourly_price: int, is_available: bool = True, id=None) -> None:
self.city = city
self.brand = brand
self.hourly_price = hourly_price
self.is_available = is_available
self.id = id | class Cab:
def __init__(self, city: str, brand: str, hourly_price: int, is_available: bool=True, id=None) -> None:
self.city = city
self.brand = brand
self.hourly_price = hourly_price
self.is_available = is_available
self.id = id |
def get_sensor_bands(target_sensor):
"""
get_sensor_bands returns a list of the band definitions from
the PredfinedWavelengths function for a list of different sensors
availalbe definitions for target_sensor are:
custom, ali, aster, er2_mas, gli, landsat_etm, *_mss, *_oli, *_tm,
mer... | def get_sensor_bands(target_sensor):
"""
get_sensor_bands returns a list of the band definitions from
the PredfinedWavelengths function for a list of different sensors
availalbe definitions for target_sensor are:
custom, ali, aster, er2_mas, gli, landsat_etm, *_mss, *_oli, *_tm,
mer... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.