content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Given an array, cyclically rotate the array clockwise by one.
def rotateCyclic(a):
start = 0
end = 1
while(end != len(a)):
temp = a[start]
a[start] = a[end]
a[end] = temp
end += 1
a = [1,2,3,4,5,6]
rotateCyclic(a)
print(a)
| def rotate_cyclic(a):
start = 0
end = 1
while end != len(a):
temp = a[start]
a[start] = a[end]
a[end] = temp
end += 1
a = [1, 2, 3, 4, 5, 6]
rotate_cyclic(a)
print(a) |
s = 'hello world'
y =[]
for i in s.split(' '):
x=i[0].upper() + i[1:]
y.append(x)
z= ' '.join(y)
print(z)
| s = 'hello world'
y = []
for i in s.split(' '):
x = i[0].upper() + i[1:]
y.append(x)
z = ' '.join(y)
print(z) |
def removeTheLoop(head):
##Your code here
if detectloop(head)==0:
return
one=head
two=head
while(one and two and two.next):
one=one.next
two=two.next.next
#print(one.data,two.data)
if one==two:
f=one
break
#print(f.data)
... | def remove_the_loop(head):
if detectloop(head) == 0:
return
one = head
two = head
while one and two and two.next:
one = one.next
two = two.next.next
if one == two:
f = one
break
temp = head
while temp != f:
if temp.next == f.next:
... |
#!usr/bin/env python3
def main():
print('Reading text files')
f = open('lines.txt') # open returns a file object, that's an iterator. by default it opens in read & text mode
for line in f:
print(line.rstrip()) # Return a copy of the string with trailing whitespace removed
print('\nWriting t... | def main():
print('Reading text files')
f = open('lines.txt')
for line in f:
print(line.rstrip())
print('\nWriting text files')
infile = open('lines.txt', 'rt')
outfile = open('lines-copy.txt', 'wt')
for line in infile:
print(line.rstrip(), file=outfile)
print('.', en... |
def mcd(a, b):
if a > b:
small = b
else:
small = a
for i in range(1, small+1):
if((a % i == 0) and (b % i == 0)):
mcd1 = i
return mcd1
a = int(input("intrduzca un numero:"))
b = int(input("intrduzca un segundo numero:"))
print ("The mcd is : ",end="... | def mcd(a, b):
if a > b:
small = b
else:
small = a
for i in range(1, small + 1):
if a % i == 0 and b % i == 0:
mcd1 = i
return mcd1
a = int(input('intrduzca un numero:'))
b = int(input('intrduzca un segundo numero:'))
print('The mcd is : ', end='')
print(mcd(a, b)) |
"""
entradas
cantidadmetros-->m-->float
salidas
metrosapulgadas-->pu-->float
mmetrosapies-->pi-->float
"""
#entradas
m=float(input("Ingrese la cantidad de metros: "))
#caja negra
pu=round((m*39.27), 2)
pi=round((pu/12), 2)
#salidas
print(m, " metros equivalen a ", pu, " pulgadas y ", pi, " pies") | """
entradas
cantidadmetros-->m-->float
salidas
metrosapulgadas-->pu-->float
mmetrosapies-->pi-->float
"""
m = float(input('Ingrese la cantidad de metros: '))
pu = round(m * 39.27, 2)
pi = round(pu / 12, 2)
print(m, ' metros equivalen a ', pu, ' pulgadas y ', pi, ' pies') |
# MenuTitle: Display all kerning group members
# -*- coding: utf-8 -*-
__doc__ = """
Opens a tab containing all the members of the currently selected glyphs kerning groups.
"""
Glyphs.clearLog()
# Glyphs.showMacroWindow()
lefts = dict((g.parent.leftKerningGroup, []) for g in Glyphs.font.selectedLayers if g.parent.lef... | __doc__ = '\nOpens a tab containing all the members of the currently selected glyphs kerning groups.\n'
Glyphs.clearLog()
lefts = dict(((g.parent.leftKerningGroup, []) for g in Glyphs.font.selectedLayers if g.parent.leftKerningGroup))
rights = dict(((g.parent.rightKerningGroup, []) for g in Glyphs.font.selectedLayers i... |
#!/usr/bin/env python3
# encoding: utf-8
# author: cappyclearl
# 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... | class Solution:
def remove_element(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
remove_count = nums.count(val)
for i in range(remove_count):
nums.remove(val)
return len(nums) |
# Link: https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
class Solution:
# @return an integer
def lengthOfLongestSubstring(self, s):
d = {}
start = 0
maxlen = 0
for i, c in enumerate(s):
if c not in d.keys():
if (i - sta... | class Solution:
def length_of_longest_substring(self, s):
d = {}
start = 0
maxlen = 0
for (i, c) in enumerate(s):
if c not in d.keys():
if i - start + 1 > maxlen:
maxlen = i - start + 1
d[c] = i
else:
... |
class Number_Pad_To_Words():
let_to_num = {
'a': '2',
'b': '2',
'c': '2',
'd': '3',
'e': '3',
'f': '3',
'g': '4',
'h': '4',
'i': '4',
'j': '5',
'k': '5',
'l': '5',
'm': '6',
'n': '6',
'o': '6',
... | class Number_Pad_To_Words:
let_to_num = {'a': '2', 'b': '2', 'c': '2', 'd': '3', 'e': '3', 'f': '3', 'g': '4', 'h': '4', 'i': '4', 'j': '5', 'k': '5', 'l': '5', 'm': '6', 'n': '6', 'o': '6', 'p': '7', 'q': '7', 'r': '7', 's': '7', 't': '8', 'u': '8', 'v': '8', 'w': '9', 'x': '9', 'y': '9', 'z': '9'}
def __init... |
JOB_TYPES = [
('Delivery driver'),
('Web developer'),
('Lecturer'),
]
| job_types = ['Delivery driver', 'Web developer', 'Lecturer'] |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 30 18:05:06 2017
@author: pfduc
"""
class BookingError(Exception):
def __init__(self, arg):
self.message = arg
class TimeSlotError(BookingError):
def __init__(self, arg):
self.message = arg | """
Created on Fri Jun 30 18:05:06 2017
@author: pfduc
"""
class Bookingerror(Exception):
def __init__(self, arg):
self.message = arg
class Timesloterror(BookingError):
def __init__(self, arg):
self.message = arg |
class Shazam:
pass
def foo(p):
"""
@param p: the magic word
@type p: Shazam
@return:
""" | class Shazam:
pass
def foo(p):
"""
@param p: the magic word
@type p: Shazam
@return:
""" |
'''
mymod.py - counts the number of lines and chars in the file.
'''
def countLines(name):
'''
countLines(name) - counts the number of lines in the file "name".
Example: countLines("/home/test_user1/test_dir1/test.txt")
'''
file = open(name)
return len(file.readlines())
d... | """
mymod.py - counts the number of lines and chars in the file.
"""
def count_lines(name):
"""
countLines(name) - counts the number of lines in the file "name".
Example: countLines("/home/test_user1/test_dir1/test.txt")
"""
file = open(name)
return len(file.readlines())
d... |
#!/usr/bin/env python3
# Parse input
with open("14/input.txt", "r") as fd:
seq = list(fd.readline().rstrip())
fd.readline()
line = fd.readline().rstrip()
instr = dict()
while line:
i = tuple([x for x in line.split(" -> ")])
instr[i[0]] = i[1]
line = fd.readline().rstrip()
... | with open('14/input.txt', 'r') as fd:
seq = list(fd.readline().rstrip())
fd.readline()
line = fd.readline().rstrip()
instr = dict()
while line:
i = tuple([x for x in line.split(' -> ')])
instr[i[0]] = i[1]
line = fd.readline().rstrip()
counts = dict()
for (i, k) in zip(seq, s... |
x=5
while x < 10:
print(x)
x += 1
| x = 5
while x < 10:
print(x)
x += 1 |
src = Split('''
prov_app.c
''')
if aos_global_config.get("ERASE") == 1:
component.add_macros(CONFIG_ERASE_KEY);
component = aos_component('prov_app', src)
component.add_comp_deps('kernel/yloop', 'tools/cli', 'security/prov', 'security/prov/test')
component.add_global_macros('AOS_NO_WIFI')
| src = split('\n prov_app.c\n')
if aos_global_config.get('ERASE') == 1:
component.add_macros(CONFIG_ERASE_KEY)
component = aos_component('prov_app', src)
component.add_comp_deps('kernel/yloop', 'tools/cli', 'security/prov', 'security/prov/test')
component.add_global_macros('AOS_NO_WIFI') |
#!/usr/bin/env python3
# https://agc001.contest.atcoder.jp/tasks/agc001_a
n = int(input())
l = [int(x) for x in input().split()]
l.sort()
print(sum(l[::2]))
| n = int(input())
l = [int(x) for x in input().split()]
l.sort()
print(sum(l[::2])) |
"""
This module provides basic methods for unit conversion and calculation of basic wind plant variables
"""
def convert_power_to_energy(power_col, sample_rate_min="10T"):
"""
Compute energy [kWh] from power [kw] and return the data column
Args:
df(:obj:`pandas.DataFrame`): the existing data fram... | """
This module provides basic methods for unit conversion and calculation of basic wind plant variables
"""
def convert_power_to_energy(power_col, sample_rate_min='10T'):
"""
Compute energy [kWh] from power [kw] and return the data column
Args:
df(:obj:`pandas.DataFrame`): the existing data frame... |
"""
Pattern Matching: You are given two strings, pattern and value. The pattern string consists of
just the letters a and b, describing a pattern within a string. For example, the string "catcatgocatgo"
matches the pattern "aabab" (where cat is a and go is b). It also matches patterns like a, ab, and b.
Write a met... | """
Pattern Matching: You are given two strings, pattern and value. The pattern string consists of
just the letters a and b, describing a pattern within a string. For example, the string "catcatgocatgo"
matches the pattern "aabab" (where cat is a and go is b). It also matches patterns like a, ab, and b.
Write a method ... |
"""
This program repeatedly asks a user to guess a number. The program ends
when they're geussed correctly.
"""
# Secret number
my_number = 10
# Ask the user to guess
guess = int(input("Enter a guess: "))
# Keep asking until the guess becomes equal to the secret number
while guess != my_number:
prin... | """
This program repeatedly asks a user to guess a number. The program ends
when they're geussed correctly.
"""
my_number = 10
guess = int(input('Enter a guess: '))
while guess != my_number:
print('Guess again!')
guess = int(input('Enter a guess: '))
print('Good job, you got it!') |
N,*H = [int(x) for x in open(0).read().split()]
def solve(l, r):
if l>r:
return 0
min_=min(H[l:r+1])
for i in range(l,r+1):
H[i]-=min_
count=min_
i=l
while i<r:
while i<=r and H[i]==0: i+=1
s=i
while i<=r and H[i]>0: i+=1
count+=solve(s,i-1)
re... | (n, *h) = [int(x) for x in open(0).read().split()]
def solve(l, r):
if l > r:
return 0
min_ = min(H[l:r + 1])
for i in range(l, r + 1):
H[i] -= min_
count = min_
i = l
while i < r:
while i <= r and H[i] == 0:
i += 1
s = i
while i <= r and H[i]... |
# FizzBuzz
# Getting input from users for the max number to go to for FizzBuzz
ip = input("Enter the max number to go for FizzBuzz: \n")
# If user inputs a number this is executed
if (ip != ""):
for i in range(1, int(ip) + 1):
if (i % 3 == 0 and i%5 == 0):
print("FizzBuzz")
elif (i % 3... | ip = input('Enter the max number to go for FizzBuzz: \n')
if ip != '':
for i in range(1, int(ip) + 1):
if i % 3 == 0 and i % 5 == 0:
print('FizzBuzz')
elif i % 3 == 0:
print('Fizz')
elif i % 5 == 0:
print('Buzz')
else:
print(i)
else:
... |
town = input().lower()
sell_count = float(input())
if 0<=sell_count<=500:
if town == "sofia":
comission = sell_count*0.05
print(f'{comission:.2f}')
elif town=="varna":
comission = sell_count * 0.045
print(f'{comission:.2f}')
elif town == "plovdiv":
comission = sell_c... | town = input().lower()
sell_count = float(input())
if 0 <= sell_count <= 500:
if town == 'sofia':
comission = sell_count * 0.05
print(f'{comission:.2f}')
elif town == 'varna':
comission = sell_count * 0.045
print(f'{comission:.2f}')
elif town == 'plovdiv':
comission =... |
class Keyword(object):
"""
Represents a keyword that can be intercepted from a message.
"""
def __init__(self, keyword, has_args, handler):
self.keyword = keyword
self.has_args = has_args
self.handler = handler
def handle(self, args=None):
"""
Calls the hand... | class Keyword(object):
"""
Represents a keyword that can be intercepted from a message.
"""
def __init__(self, keyword, has_args, handler):
self.keyword = keyword
self.has_args = has_args
self.handler = handler
def handle(self, args=None):
"""
Calls the hand... |
class Compass(object):
def __init__(self, spacedomains):
self.categories = tuple(spacedomains)
self.spacedomains = spacedomains
# check time compatibility between components
self._check_spacedomain_compatibilities(spacedomains)
def _check_spacedomain_compatibilities(self, spa... | class Compass(object):
def __init__(self, spacedomains):
self.categories = tuple(spacedomains)
self.spacedomains = spacedomains
self._check_spacedomain_compatibilities(spacedomains)
def _check_spacedomain_compatibilities(self, spacedomains):
for category in spacedomains:
... |
"""
LeetCode Problem 801. Minimum Swaps To Make Sequences Increasing
Link: https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/
Written by: Mostofa Adib Shakib
Language: Python
Time complexity: O(n)
Space complexity: O(n)
Explanation:
1) A[i - 1] < A[i] && B[i - 1] < B[i].
In this case, if ... | """
LeetCode Problem 801. Minimum Swaps To Make Sequences Increasing
Link: https://leetcode.com/problems/minimum-swaps-to-make-sequences-increasing/
Written by: Mostofa Adib Shakib
Language: Python
Time complexity: O(n)
Space complexity: O(n)
Explanation:
1) A[i - 1] < A[i] && B[i - 1] < B[i].
In this case, if ... |
time1 = int(input())
time2 = int(input())
time3 = int(input())
sum = time1 + time2 + time3
minutes = int(sum / 60)
seconds = sum % 60
if seconds <= 9:
print('{0}:0{1}'.format(minutes, seconds))
else:
print('{0}:{1}'.format(minutes, seconds))
| time1 = int(input())
time2 = int(input())
time3 = int(input())
sum = time1 + time2 + time3
minutes = int(sum / 60)
seconds = sum % 60
if seconds <= 9:
print('{0}:0{1}'.format(minutes, seconds))
else:
print('{0}:{1}'.format(minutes, seconds)) |
"""packer_builder/release.py"""
# Version tracking for package.
__author__ = 'Larry Smith Jr.'
__version__ = '0.1.0'
__package_name__ = 'packer_builder'
| """packer_builder/release.py"""
__author__ = 'Larry Smith Jr.'
__version__ = '0.1.0'
__package_name__ = 'packer_builder' |
#
# @lc app=leetcode id=908 lang=python3
#
# [908] Smallest Range I
#
# @lc code=start
class Solution:
def smallestRangeI(self, A: List[int], K: int) -> int:
mi, ma = min(A), max(A)
return 0 if ma - mi - 2*K <= 0 else ma - mi - 2*K
# @lc code=end
| class Solution:
def smallest_range_i(self, A: List[int], K: int) -> int:
(mi, ma) = (min(A), max(A))
return 0 if ma - mi - 2 * K <= 0 else ma - mi - 2 * K |
class RandomizedSet(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = {} # key - position in list
self.l = [] # numbers
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contai... | class Randomizedset(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.d = {}
self.l = []
def insert(self, val):
"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:t... |
a = [[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0],[10,0]]
step=30
def setup():
size(500,500)
smooth()
noStroke()
myInit()
def myInit():
for i in range(len(a)):
a[i]=[random(0,10)]
for j in range(len(a[i])):
a[i][j]=random(0,30)
def draw():
global ste... | a = [[10, 0], [10, 0], [10, 0], [10, 0], [10, 0], [10, 0], [10, 0], [10, 0], [10, 0], [10, 0]]
step = 30
def setup():
size(500, 500)
smooth()
no_stroke()
my_init()
def my_init():
for i in range(len(a)):
a[i] = [random(0, 10)]
for j in range(len(a[i])):
a[i][j] = random(... |
# porownania
print('----------')
print((1, 2, 3) < (1, 2, 4))
print([1, 2, 3] < [1, 2, 4])
print('ABC' < 'C' < 'Pascal' < 'Python')
print((1, 2, 3, 4) < (1, 2, 4))
print((1, 2) < (1, 2, -1))
print((1, 2, 3) == (1.0, 2.0, 3.0))
print((1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4))
print('--- inne ---')
print(list((1, ... | print('----------')
print((1, 2, 3) < (1, 2, 4))
print([1, 2, 3] < [1, 2, 4])
print('ABC' < 'C' < 'Pascal' < 'Python')
print((1, 2, 3, 4) < (1, 2, 4))
print((1, 2) < (1, 2, -1))
print((1, 2, 3) == (1.0, 2.0, 3.0))
print((1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4))
print('--- inne ---')
print(list((1, 2, 3)) < [1, 2,... |
# Error handler
class GeneralError(Exception):
"""
This is for general error
"""
def __init__(self, error, severity, status_code):
self.error = error
self.severity = severity
self.status_code = status_code
| class Generalerror(Exception):
"""
This is for general error
"""
def __init__(self, error, severity, status_code):
self.error = error
self.severity = severity
self.status_code = status_code |
################################### SERVER'S SIDE ###################################
#const
mask = 0xffffffff
#bitwise operations have the least priority
#Note 1: all variables are unsigned 32-bit quantities and wrap modulo 2**32 when calculating, except for
#ml, message length: 64-bit quantity, and
... | mask = 4294967295
key = b'SuPeR_sEcReT_kEy,_NoT_tO_bE_gUeSsEd_So_EaSiLy'
def big_endian_64_bit(num):
num = hex(num).replace('0x', '').rjust(16, '0')
return bytes([int(num[i:i + 2], 16) for i in range(0, len(num), 2)])
def leftrot(num):
return (num << 1 & mask) + (num >> 31)
def bytes2int(block):
retu... |
# DOCUMENTATION
# main
def main():
canadian = {"red", "white"}
british = {"red", "blue", "white"}
italian = {"red", "white", "green"}
if canadian.issubset(british):
print("canadian flag colours occur in british")
if not italian.issubset(british):
print("not all italian flag colors... | def main():
canadian = {'red', 'white'}
british = {'red', 'blue', 'white'}
italian = {'red', 'white', 'green'}
if canadian.issubset(british):
print('canadian flag colours occur in british')
if not italian.issubset(british):
print('not all italian flag colors occur in british')
fr... |
# @desc Predict the returned value
# @desc by Savonnah '23
def calc(num):
if num <= 10:
result = num * 2
else:
result = num * 10
return result
def main():
print(calc(1))
print(calc(41))
print(calc(-5))
print(calc(3))
print(calc(10))
if __name__ == '__main__':
main... | def calc(num):
if num <= 10:
result = num * 2
else:
result = num * 10
return result
def main():
print(calc(1))
print(calc(41))
print(calc(-5))
print(calc(3))
print(calc(10))
if __name__ == '__main__':
main() |
### PROBLEM 3
degF = 40.5
degC = (5/9) * (degF - 32)
print(degC)
#when degF is -40.0, degC is -40.0
##when degF is 40.5, degC is 4.72 | deg_f = 40.5
deg_c = 5 / 9 * (degF - 32)
print(degC) |
#
# @lc app=leetcode id=1290 lang=python3
#
# [1290] Convert Binary Number in a Linked List to Integer
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def getDecimalValue(self, ... | class Solution:
def get_decimal_value(self, head: ListNode) -> int:
decimal = 0
while head:
decimal <<= 1
decimal |= head.val
head = head.next
return decimal |
#!/usr/bin/python3
def palindrome(num):
if num == num[::-1]:
return True
return False
def addOne(num):
num = int(num) + 1
return str(num)
def isPalindrome(num):
num = str(num)
num = num.zfill(6)
value = palindrome(num[2:])
if value:
num = num.zfill(6)
value... | def palindrome(num):
if num == num[::-1]:
return True
return False
def add_one(num):
num = int(num) + 1
return str(num)
def is_palindrome(num):
num = str(num)
num = num.zfill(6)
value = palindrome(num[2:])
if value:
num = num.zfill(6)
value2 = palindrome(num[1:]... |
a = int(input())
b = int(a/5)
if (a%5 == 0):
print(b)
else:
print(b+1)
| a = int(input())
b = int(a / 5)
if a % 5 == 0:
print(b)
else:
print(b + 1) |
# Day8 of my 100DaysOfCode Challenge
# Program to open a file in append mode
file = open('Day8/new.txt', 'a')
file.write("This is a really great experience")
file.close()
| file = open('Day8/new.txt', 'a')
file.write('This is a really great experience')
file.close() |
#!/usr/bin/python
def max_in_list(list_of_numbers):
'''
Finds the largest number in a list
'''
biggest_num = 0
for i in list_of_numbers:
if i > biggest_num:
biggest_num = i
return(biggest_num)
| def max_in_list(list_of_numbers):
"""
Finds the largest number in a list
"""
biggest_num = 0
for i in list_of_numbers:
if i > biggest_num:
biggest_num = i
return biggest_num |
{
"targets":[
{
"target_name": "accessor",
"sources": ["accessor.cpp"]
}
]
} | {'targets': [{'target_name': 'accessor', 'sources': ['accessor.cpp']}]} |
# terrascript/data/Trois-Six/sendgrid.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:26:45 UTC)
__all__ = []
| __all__ = [] |
__author__ = 'arobres, jfernandez'
# PUPPET WRAPPER CONFIGURATION
PUPPET_MASTER_PROTOCOL = 'https'
PUPPET_WRAPPER_IP = 'puppet-master.dev-havana.fi-ware.org'
PUPPET_WRAPPER_PORT = 8443
PUPPET_MASTER_USERNAME = 'root'
PUPPET_MASTER_PWD = '**********'
PUPPET_WRAPPER_MONGODB_PORT = 27017
PUPPET_WRAPPER_MONGODB_DB_NAME = ... | __author__ = 'arobres, jfernandez'
puppet_master_protocol = 'https'
puppet_wrapper_ip = 'puppet-master.dev-havana.fi-ware.org'
puppet_wrapper_port = 8443
puppet_master_username = 'root'
puppet_master_pwd = '**********'
puppet_wrapper_mongodb_port = 27017
puppet_wrapper_mongodb_db_name = 'puppetWrapper'
puppet_wrapper_m... |
'''
A simple programme to print hex grid on terminal screen.
Tip: I have used `raw` strings.
Author: Sunil Dhaka
'''
GRID_WIDTH=20
GRID_HEIGHT=16
def main():
for _ in range(GRID_HEIGHT):
for _ in range(GRID_WIDTH):
print(r'/ \_',end='')
print()
for _ in range(GRID_WIDTH):
... | """
A simple programme to print hex grid on terminal screen.
Tip: I have used `raw` strings.
Author: Sunil Dhaka
"""
grid_width = 20
grid_height = 16
def main():
for _ in range(GRID_HEIGHT):
for _ in range(GRID_WIDTH):
print('/ \\_', end='')
print()
for _ in range(GRID_WIDTH):
... |
'''
Order the following functions by asymptotic growth rate.
4nlog n+2n 210 2log n
3n+100log n 4n 2n
n2 +10n n3 nlog n
'''
'''
2^10 O(1)
3n+100log(n) O(log(n))
4n O(n)
4nlog(n)+2n and O(nlog(n))
n^2+10n and O(n^2)
n^3 O(n^3... | """
Order the following functions by asymptotic growth rate.
4nlog n+2n 210 2log n
3n+100log n 4n 2n
n2 +10n n3 nlog n
"""
'\n2^10 O(1)\n3n+100log(n) O(log(n))\n4n O(n)\n4nlog(n)+2n and O(nlog(n))\nn^2+10n and O(n^2)\nn^3 O... |
# encoding = utf-8
class GreekGetter:
def get(self, msgid):
return msgid[::-1]
class EnglishGetter:
def get(self, msgid):
return msgid[:]
def get_localizer(language="English"):
languages = dict(English=EnglishGetter, Greek=GreekGetter)
return languages[language]()
# Create our localizers
e, g = get_l... | class Greekgetter:
def get(self, msgid):
return msgid[::-1]
class Englishgetter:
def get(self, msgid):
return msgid[:]
def get_localizer(language='English'):
languages = dict(English=EnglishGetter, Greek=GreekGetter)
return languages[language]()
(e, g) = (get_localizer('English'), ge... |
print("Enter the number of terms:")
n=int(input())
a=0
b=1
for i in range(n+1):
c=a+b
a=b
b=c
print(c,end=" ")
| print('Enter the number of terms:')
n = int(input())
a = 0
b = 1
for i in range(n + 1):
c = a + b
a = b
b = c
print(c, end=' ') |
class Foo:
def __init__(self):
self.tmp = False
def extract_method(self, condition1, condition2, condition3, condition4):
list = (1, 2, 3)
a = 6
b = False
if a in list or self.tmp:
if condition1:
print(condi... | class Foo:
def __init__(self):
self.tmp = False
def extract_method(self, condition1, condition2, condition3, condition4):
list = (1, 2, 3)
a = 6
b = False
if a in list or self.tmp:
if condition1:
print(condition1)
if b is not cond... |
# Escape Sequences
# \\
# \'
# \"
# \n
course_name = "Pyton Mastery \n with Mosh"
print(course_name)
| course_name = 'Pyton Mastery \n with Mosh'
print(course_name) |
class VolumeRaidLevels(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_lun_raid_type(idx_name)
class VolumeRaidLevelsColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_luns()
| class Volumeraidlevels(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_lun_raid_type(idx_name)
class Volumeraidlevelscolumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_luns() |
NORTH = 0
EAST = 1
SOUTH = 2
WEST = 3
X_MOD = [0,1,0,-1]
Y_MOD = [1,0,-1,0]
num_states = 0
state_trans = []
infected_state = 0
class Node:
def __init__(self, state, x, y):
self.x = x
self.y = y
self.state = state
def updateDir(self, dir):
'''
Directions can be anyth... | north = 0
east = 1
south = 2
west = 3
x_mod = [0, 1, 0, -1]
y_mod = [1, 0, -1, 0]
num_states = 0
state_trans = []
infected_state = 0
class Node:
def __init__(self, state, x, y):
self.x = x
self.y = y
self.state = state
def update_dir(self, dir):
"""
Directions can be a... |
class Node:
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def __str__(self):
p = self
nums = []
while p:
nums.append(p.data)
p = p.next_node
return "[" + ", ".join(map(str, nums)) + "]"
@st... | class Node:
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
def __str__(self):
p = self
nums = []
while p:
nums.append(p.data)
p = p.next_node
return '[' + ', '.join(map(str, nums)) + ']'
@s... |
# uncompyle6 version 3.2.0
# Python bytecode 2.4 (62061)
# Decompiled from: Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)]
# Embedded file name: pirates.makeapirate.MakeAPirateGlobals
BODYSHOP = 0
HEADSHOP = 1
MOUTHSHOP = 2
EYESSHOP = 3
NOSESHOP = 4
EARSHOP = 5
HAIRSHOP = 6
CLOTHE... | bodyshop = 0
headshop = 1
mouthshop = 2
eyesshop = 3
noseshop = 4
earshop = 5
hairshop = 6
clothesshop = 7
nameshop = 8
tattooshop = 9
jewelryshop = 10
avatar_pirate = 0
avatar_skeleton = 1
avatar_navy = 2
avatar_cast = 3
shop_names = ['BodyShop', 'HeadShop', 'MouthShop', 'EyesShop', 'NoseShop', 'EarShop', 'HairShop', ... |
def bubble_sort(nums: list[float]) -> list[float]:
is_sorted = True
for loop in range(len(nums) - 1):
for indx in range(len(nums) - loop - 1):
if nums[indx] > nums[indx + 1]:
is_sorted = False
nums[indx], nums[indx + 1] = nums[indx + 1], nums[indx]
i... | def bubble_sort(nums: list[float]) -> list[float]:
is_sorted = True
for loop in range(len(nums) - 1):
for indx in range(len(nums) - loop - 1):
if nums[indx] > nums[indx + 1]:
is_sorted = False
(nums[indx], nums[indx + 1]) = (nums[indx + 1], nums[indx])
... |
#
# PySNMP MIB module MPLS-LSR-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MPLS-LSR-STD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:43:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint, constraints_union) ... |
n = int(input('How many sides the convex polygon have: '))
nd = (n * (n - 3)) / 2
print(f'The convex polygon have {nd} sides.')
| n = int(input('How many sides the convex polygon have: '))
nd = n * (n - 3) / 2
print(f'The convex polygon have {nd} sides.') |
# Minimal django settings to run tests
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = ()
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': './sqlite3.db',
}
}
SECRET_KEY = 'alksjdf93jqpijsdaklfjq;3lejqklejlakefjas'
TEMPLATE_LOADERS = (
'django.tem... | debug = True
template_debug = DEBUG
admins = ()
managers = ADMINS
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': './sqlite3.db'}}
secret_key = 'alksjdf93jqpijsdaklfjq;3lejqklejlakefjas'
template_loaders = ('django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Lo... |
#!/usr/bin/env python
TOOL = "tool"
PRECISION = "precision"
RECALL = "recall"
AVG_PRECISION = "avg_precision"
STD_DEV_PRECISION = "std_dev_precision"
SEM_PRECISION = "sem_precision"
AVG_RECALL = "avg_recall"
STD_DEV_RECALL = "std_dev_recall"
SEM_RECALL = "sem_recall"
RI_BY_BP = "rand_index_by_bp"
RI_BY_SEQ = "rand_ind... | tool = 'tool'
precision = 'precision'
recall = 'recall'
avg_precision = 'avg_precision'
std_dev_precision = 'std_dev_precision'
sem_precision = 'sem_precision'
avg_recall = 'avg_recall'
std_dev_recall = 'std_dev_recall'
sem_recall = 'sem_recall'
ri_by_bp = 'rand_index_by_bp'
ri_by_seq = 'rand_index_by_seq'
ari_by_bp = ... |
# parameters used in experiment
# ==============================================================================
# optitrack communication ip (win10 is the server, the ubuntu receiving data is client)
# ==============================================================================
ip_win10 = '192.168.1.5'
ip_ubuntu_pc... | ip_win10 = '192.168.1.5'
ip_ubuntu_pc = '192.168.1.3'
lidar_port1 = '/dev/ttyUSB0'
lidar_port2 = '/dev/ttyUSB1'
lidar_port3 = '/dev/ttyUSB2'
lidar_port4 = '/dev/ttyUSB3'
lidar_por_ts = [LIDAR_PORT1, LIDAR_PORT2, LIDAR_PORT3]
car_to_lidar1_fo_v = dict(FoVs=[[0, 40], [320, 360]], rmax=1400)
car_to_lidar2_fo_v = dict(FoVs... |
Vocales = ("a","e","i","o","u", " ")
texto = input("Ingresar el texto: ")
texto_nuevo = 0
for letters in texto:
if letters not in Vocales:
texto_nuevo = texto_nuevo + 1
print("El numero de consonantes es: ", texto_nuevo) | vocales = ('a', 'e', 'i', 'o', 'u', ' ')
texto = input('Ingresar el texto: ')
texto_nuevo = 0
for letters in texto:
if letters not in Vocales:
texto_nuevo = texto_nuevo + 1
print('El numero de consonantes es: ', texto_nuevo) |
FILE_PATH = "data/cows.mp4"
MODEL_PATH = "model/mobilenet_v2_ssd_coco_frozen_graph.pb"
CONFIG_PATH = "model/mobilenet_v2_ssd_coco_config.pbtxt"
LABEL_PATH = "model/coco_class_labels.txt"
WINDOW_NAME = "detection"
MIN_CONF = 0.4
MAX_IOU = 0.5 | file_path = 'data/cows.mp4'
model_path = 'model/mobilenet_v2_ssd_coco_frozen_graph.pb'
config_path = 'model/mobilenet_v2_ssd_coco_config.pbtxt'
label_path = 'model/coco_class_labels.txt'
window_name = 'detection'
min_conf = 0.4
max_iou = 0.5 |
'''
data structures that used executive architecture
'''
class Command(object):
def __init__(self, Name, Payload):
self.Name = Name
self.Payload = Payload
class Gesture(object):
def __init__(self, ID, NAME, LastTimeSync,
IterableGesture, NumberOfGestureRepetitions,
... | """
data structures that used executive architecture
"""
class Command(object):
def __init__(self, Name, Payload):
self.Name = Name
self.Payload = Payload
class Gesture(object):
def __init__(self, ID, NAME, LastTimeSync, IterableGesture, NumberOfGestureRepetitions, NumberOfMotions, ListA... |
class Pattern:
"""
This class is used for N:M conversions.
"""
def __init__(self, name=""):
"""
Patterns are described by the components which make up the pattern
and the connections between those components.
"""
#
# Pattern name is used in the conversio... | class Pattern:
"""
This class is used for N:M conversions.
"""
def __init__(self, name=''):
"""
Patterns are described by the components which make up the pattern
and the connections between those components.
"""
self.name = name.strip()
self.components =... |
# Description: Count number of *.mtz files in current directory.
# Source: placeHolder
"""
cmd.do('print("Count the number of mtz structure factor files in current directory.");')
cmd.do('print("Usage: cntmtzs");')
cmd.do('myPath = os.getcwd();')
cmd.do('mtzCounter = len(glob.glob1(myPath,"*.mtz"));')
cmd.do('print(... | """
cmd.do('print("Count the number of mtz structure factor files in current directory.");')
cmd.do('print("Usage: cntmtzs");')
cmd.do('myPath = os.getcwd();')
cmd.do('mtzCounter = len(glob.glob1(myPath,"*.mtz"));')
cmd.do('print("Number of number of mtz structure factor files in the current directory: ", mtzCounter);... |
'''FreeProxy exceptions module'''
class FreeProxyException(Exception):
'''Exception class with message as a required parameter'''
def __init__(self, message) -> None:
self.message = message
super().__init__(self.message)
| """FreeProxy exceptions module"""
class Freeproxyexception(Exception):
"""Exception class with message as a required parameter"""
def __init__(self, message) -> None:
self.message = message
super().__init__(self.message) |
__all__ = ["SENTINEL1_COLLECTION_ID", "VV", "VH", "IW", "ASCENDING", "DESCENDING"]
SENTINEL1_COLLECTION_ID = "COPERNICUS/S1_GRD_FLOAT"
VV = "VV"
VH = "VH"
IW = "IW"
ASCENDING = "ASCENDING"
DESCENDING = "DESCENDING"
GEE_PROPERTIES = [
"system:id",
"sliceNumber",
"system:time_start",
"relativeOrbitNumber... | __all__ = ['SENTINEL1_COLLECTION_ID', 'VV', 'VH', 'IW', 'ASCENDING', 'DESCENDING']
sentinel1_collection_id = 'COPERNICUS/S1_GRD_FLOAT'
vv = 'VV'
vh = 'VH'
iw = 'IW'
ascending = 'ASCENDING'
descending = 'DESCENDING'
gee_properties = ['system:id', 'sliceNumber', 'system:time_start', 'relativeOrbitNumber_start', 'relative... |
def problem303():
"""
# This function computes and returns the smallest positive multiple of n such that the result
# uses only the digits 0, 1, 2 in base 10. For example, fmm(2) = 2, fmm(3) = 12, fmm(5) = 10.
As an overview, the algorithm has two phases:
# 0. Determine whether a k-digit solution is... | def problem303():
"""
# This function computes and returns the smallest positive multiple of n such that the result
# uses only the digits 0, 1, 2 in base 10. For example, fmm(2) = 2, fmm(3) = 12, fmm(5) = 10.
As an overview, the algorithm has two phases:
# 0. Determine whether a k-digit solution is... |
start = 1
end = 100
for x in range(start,end):
if (x % 2 == 0):
continue
print(x) | start = 1
end = 100
for x in range(start, end):
if x % 2 == 0:
continue
print(x) |
"""
You are given an n x n 2D matrix representing an image. Rotate the matrix 90 degrees clockwise in-place.
Example 1:
[[1, 2, 3], [[7, 4, 1],
[4, 5, 6], -> [8, 5, 2],
[7, 8, 9]], [9, 6, 3]]
Example 2:
[[ 5, 1, 9, 11], [[15, 13, 2, 5],
[ 2, 4, 8, 10], -> [14, 3, 4, 1],
[13, 3, 6, 7], ... | """
You are given an n x n 2D matrix representing an image. Rotate the matrix 90 degrees clockwise in-place.
Example 1:
[[1, 2, 3], [[7, 4, 1],
[4, 5, 6], -> [8, 5, 2],
[7, 8, 9]], [9, 6, 3]]
Example 2:
[[ 5, 1, 9, 11], [[15, 13, 2, 5],
[ 2, 4, 8, 10], -> [14, 3, 4, 1],
[13, 3, 6, 7], ... |
"""
1356. Sort Integers by The Number of 1 Bits
Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.
Return the sorted array... | """
1356. Sort Integers by The Number of 1 Bits
Given an integer array arr. You have to sort the integers in the array in ascending order by the number of 1's in their binary representation and in case of two or more integers have the same number of 1's you have to sort them in ascending order.
Return the sorted array... |
class AggResult:
def __init__(self, agg_key, result=None, return_counts=True):
self.return_counts = return_counts
if result is None:
self.total = 0
self._hits = []
else:
self.total = result['hits']['total']['value']
self._hits = result['aggrega... | class Aggresult:
def __init__(self, agg_key, result=None, return_counts=True):
self.return_counts = return_counts
if result is None:
self.total = 0
self._hits = []
else:
self.total = result['hits']['total']['value']
self._hits = result['aggreg... |
input = """
a(1).
a(2).
b(1,2).
c(2).
c(3).
q(X,Y) :- a(X), c(Y).
p(X,Y,Z) :- a(X), q(Y,Z), m(X,Z).
m(X,Y) :- a(Z), p(Z,X,Y).
m(X,Y) :- b(X,Y), not n(X,Y).
n(X,Y) :- q(X,Y).
n(X,Y) :- b(X,Y), m(X,Y).
"""
output = """
a(1).
a(2).
b(1,2).
c(2).
c(3).
q(X,Y) :- a(X), c(Y).
p(X,Y,Z) :- a(X)... | input = '\na(1).\na(2).\nb(1,2).\nc(2).\nc(3).\n\nq(X,Y) :- a(X), c(Y).\n\np(X,Y,Z) :- a(X), q(Y,Z), m(X,Z).\n\nm(X,Y) :- a(Z), p(Z,X,Y).\n\nm(X,Y) :- b(X,Y), not n(X,Y).\n\nn(X,Y) :- q(X,Y).\n\nn(X,Y) :- b(X,Y), m(X,Y).\n'
output = '\na(1).\na(2).\nb(1,2).\nc(2).\nc(3).\n\nq(X,Y) :- a(X), c(Y).\n\np(X,Y,Z) :- a(X), q(... |
class Solution:
def destCity(self, paths: List[List[str]]) -> str:
s = set()
for path in paths:
s.add(path[0])
s.add(path[1])
for path in paths:
s.remove(path[0])
return list(s).pop()
| class Solution:
def dest_city(self, paths: List[List[str]]) -> str:
s = set()
for path in paths:
s.add(path[0])
s.add(path[1])
for path in paths:
s.remove(path[0])
return list(s).pop() |
class Solution:
def checkString(self, s: str) -> bool:
flag = 0
for ch in s:
if flag == 0 and ch == 'b':
flag = 1
elif flag == 1 and ch == 'a':
return False
return True | class Solution:
def check_string(self, s: str) -> bool:
flag = 0
for ch in s:
if flag == 0 and ch == 'b':
flag = 1
elif flag == 1 and ch == 'a':
return False
return True |
class Node:
def __init__(self, data=None) -> None:
self.data = data
self.next = None
self.prev = None
class DoublyList:
def __init__(self) -> None:
self.front = None
self.back = None
self.size = 0
def add_back(self, data: int) -> None:
... | class Node:
def __init__(self, data=None) -> None:
self.data = data
self.next = None
self.prev = None
class Doublylist:
def __init__(self) -> None:
self.front = None
self.back = None
self.size = 0
def add_back(self, data: int) -> None:
node = node(... |
class AlmostPrimeNumbers:
def getNext(self, m):
sieve = [True]*(10**6+2)
for i in xrange(2, 10**6+2):
if sieve[i]:
for j in xrange(2*i, 10**6+2, i):
sieve[j] = False
def is_almost(n):
return not sieve[n] and not any(n%i == 0 for i i... | class Almostprimenumbers:
def get_next(self, m):
sieve = [True] * (10 ** 6 + 2)
for i in xrange(2, 10 ** 6 + 2):
if sieve[i]:
for j in xrange(2 * i, 10 ** 6 + 2, i):
sieve[j] = False
def is_almost(n):
return not sieve[n] and (not ... |
class LandingType(object):
# For choosing what the main landing page displays
KICKOFF = 1
BUILDSEASON = 2
COMPETITIONSEASON = 3
OFFSEASON = 4
INSIGHTS = 5
CHAMPS = 6
NAMES = {
KICKOFF: 'Kickoff',
BUILDSEASON: 'Build Season',
COMPETITIONSEASON: 'Competition Seas... | class Landingtype(object):
kickoff = 1
buildseason = 2
competitionseason = 3
offseason = 4
insights = 5
champs = 6
names = {KICKOFF: 'Kickoff', BUILDSEASON: 'Build Season', COMPETITIONSEASON: 'Competition Season', OFFSEASON: 'Offseason', INSIGHTS: 'Insights', CHAMPS: 'Championship'} |
#!/usr/bin/env python
polymer = input()
letters = [ord(c) for c in set(polymer.upper())]
polymer = [ord(c) for c in polymer]
def react(polymer, forbidden=set()):
stack = []
for unit in polymer:
if unit not in forbidden:
if stack and abs(unit - stack[-1]) == 32:
stack.po... | polymer = input()
letters = [ord(c) for c in set(polymer.upper())]
polymer = [ord(c) for c in polymer]
def react(polymer, forbidden=set()):
stack = []
for unit in polymer:
if unit not in forbidden:
if stack and abs(unit - stack[-1]) == 32:
stack.pop()
else:
... |
HANGMAN_ASCII_ART = ("""
_ _
| | | |
| |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __
| __ |/ _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_|... | hangman_ascii_art = "\n _ _ \n | | | | \n | |__| | __ _ _ __ __ _ _ __ ___ __ _ _ __ \n | __ |/ _` | '_ \\ / _` | '_ ` _ \\ / _` | '_ \\ \n | | | | (_| | | | | (_| | | | | | | (_| | | | |\n |_| |_|\\__,_|_| |_|\\__, |_| |_| |_|... |
#!/usr/bin/env python3
class colors:
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
RED = '\033[91m'
BOLD = '\033[1m'
RESET = '\033[0m' | class Colors:
green = '\x1b[92m'
yellow = '\x1b[93m'
blue = '\x1b[94m'
red = '\x1b[91m'
bold = '\x1b[1m'
reset = '\x1b[0m' |
nombre_usuario = input("Introduce tu nombre de usuario: ")
print("El nombre es:", nombre_usuario)
print("El nombre es:", nombre_usuario.upper())
print("El nombre es:", nombre_usuario.lower())
print("El nombre es:", nombre_usuario.capitalize())
| nombre_usuario = input('Introduce tu nombre de usuario: ')
print('El nombre es:', nombre_usuario)
print('El nombre es:', nombre_usuario.upper())
print('El nombre es:', nombre_usuario.lower())
print('El nombre es:', nombre_usuario.capitalize()) |
class Node:
def __init__(self, value=None):
self.value = value
self.next = None
def __str__(self):
return str(self.value)
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = self.head
while node != N... | class Node:
def __init__(self, value=None):
self.value = value
self.next = None
def __str__(self):
return str(self.value)
class Linkedlist:
def __init__(self):
self.head = None
self.tail = None
def __iter__(self):
node = self.head
while node !... |
RELEVANT_COLUMNS = [
"HONG KONG",
"JAPAN",
"CANADA",
"FINLAND",
"DENMARK",
"ESTONIA",
"POLAND",
"CZECH REPUBLIC",
"SLOVENIA and BALKANs",
"ITALY",
"SPAIN",
"SWITZERLAND",
"BENELUX",
"UK",
"ISLAND",
"USA Wholesale",
"Germany/ Austria",
"Sweden/ Norw... | relevant_columns = ['HONG KONG', 'JAPAN', 'CANADA', 'FINLAND', 'DENMARK', 'ESTONIA', 'POLAND', 'CZECH REPUBLIC', 'SLOVENIA and BALKANs', 'ITALY', 'SPAIN', 'SWITZERLAND', 'BENELUX', 'UK', 'ISLAND', 'USA Wholesale', 'Germany/ Austria', 'Sweden/ Norway', 'Store', 'Marketplaces (AZ+ ZA)', 'Webshop (INK US, CAN, FIN)']
def... |
'''
Author : MiKueen
Level : Hard
Company : Stripe
Problem Statement : First Missing Positive
Given an array of integers, find the first missing positive integer in linear time and constant space.
In other words, find the lowest positive integer that does not exist in the array.
The array can contain duplicates and ... | """
Author : MiKueen
Level : Hard
Company : Stripe
Problem Statement : First Missing Positive
Given an array of integers, find the first missing positive integer in linear time and constant space.
In other words, find the lowest positive integer that does not exist in the array.
The array can contain duplicates and ... |
#*****************************************************************************#
#* Copyright (c) 2004-2008, SRI International. *#
#* All rights reserved. *#
#* ... | def compute_cycles(root, successors):
finished = []
companions = {}
path = []
_process(successors, [], companions, path, root)
return companions
def _process(successors, complete, companions, path, node):
if node in path:
pos = path.index(node)
group = None
for cnode in ... |
API = "api"
API_DEFAULT_DESCRIPTOR = "default"
API_ERROR_MESSAGES = "errorMessages"
API_QUERY_STRING = "query_string"
API_RESOURCE = "resource_name"
API_RETURN = "on_return"
COLUMN_FORMATING = "column_formating"
COLUMN_CLEANING = "column_cleaning"
COLUMN_EXPANDING = "column_expending"
DEFAULT_COLUMNS_TO_EXPAND = ["chan... | api = 'api'
api_default_descriptor = 'default'
api_error_messages = 'errorMessages'
api_query_string = 'query_string'
api_resource = 'resource_name'
api_return = 'on_return'
column_formating = 'column_formating'
column_cleaning = 'column_cleaning'
column_expanding = 'column_expending'
default_columns_to_expand = ['chan... |
region = 'us-west-2'
default_vpc = dict(
enable_dns_hostnames=True,
cidr_block='10.0.0.0/16',
tags={'Name': 'default'},
)
default_gateway = dict(vpc_id='${aws_vpc.default.id}')
internet_access_route = dict(
route_table_id='${aws_vpc.default.main_route_table_id}',
destination_cidr_block='0.0.0.0/0',
g... | region = 'us-west-2'
default_vpc = dict(enable_dns_hostnames=True, cidr_block='10.0.0.0/16', tags={'Name': 'default'})
default_gateway = dict(vpc_id='${aws_vpc.default.id}')
internet_access_route = dict(route_table_id='${aws_vpc.default.main_route_table_id}', destination_cidr_block='0.0.0.0/0', gateway_id='${aws_intern... |
ants_picture = """
.`
/
`:`
.-` ... | ants_picture = '\n .` \n / \n `:` \n .-` ... |
class BlackjackWinner:
def winnings(self, bet, dealer, dealerBlackjack, player, blackjack):
if player > 21 or (player < dealer and dealer <= 21):
return -bet
if dealerBlackjack and blackjack:
return 0
if dealerBlackjack and not blackjack:
return -bet
... | class Blackjackwinner:
def winnings(self, bet, dealer, dealerBlackjack, player, blackjack):
if player > 21 or (player < dealer and dealer <= 21):
return -bet
if dealerBlackjack and blackjack:
return 0
if dealerBlackjack and (not blackjack):
return -bet
... |
# --------------------------------------
#! /usr/bin/python
# File: 977. Squared of a Sorted Array.py
# Author: Kimberly Gao
# My solution: (Run time: 132ms) (from website)
# Memory Usage: 15.6 MB
class Solution:
def _init_(self,name):
self.name = name
# Only for python. Using function sort()
# W... | class Solution:
def _init_(self, name):
self.name = name
def sorted_squares1(self, nums):
for i in range(nums):
nums[i] *= nums[i]
nums.sort()
return nums
def sorted_squares2(self, nums):
return sorted([v ** 2 for v in nums])
def sorted_squares3(se... |
class GameStatus:
OPEN = 'OPEN'
CLOSED = 'CLOSED'
READY = 'READY'
IN_PLAY = 'IN_PLAY'
ENDED = 'ENDED'
class Action:
MOVE_UP = 'MOVE_UP'
MOVE_LEFT = 'MOVE_LEFT'
MOVE_DOWN = 'MOVE_DOWN'
MOVE_RIGHT = 'MOVE_RIGHT'
ATTACK_UP = 'ATTACK_UP'
ATTACK_LEFT = 'ATTACK_LEFT'
ATTACK_D... | class Gamestatus:
open = 'OPEN'
closed = 'CLOSED'
ready = 'READY'
in_play = 'IN_PLAY'
ended = 'ENDED'
class Action:
move_up = 'MOVE_UP'
move_left = 'MOVE_LEFT'
move_down = 'MOVE_DOWN'
move_right = 'MOVE_RIGHT'
attack_up = 'ATTACK_UP'
attack_left = 'ATTACK_LEFT'
attack_do... |
__name__ = "restio"
__version__ = "1.0.0b5"
__author__ = "Eduardo Machado Starling"
__email__ = "edmstar@gmail.com"
| __name__ = 'restio'
__version__ = '1.0.0b5'
__author__ = 'Eduardo Machado Starling'
__email__ = 'edmstar@gmail.com' |
class Solution:
#Function to remove a loop in the linked list.
def removeLoop(self, head):
ptr1 = head
ptr2 = head
while ptr2!=None and ptr2.next!=None:
ptr1 = ptr1.next
ptr2 = ptr2.next.next
if ptr1 == ptr2 :
self.delete_loop(head,ptr1... | class Solution:
def remove_loop(self, head):
ptr1 = head
ptr2 = head
while ptr2 != None and ptr2.next != None:
ptr1 = ptr1.next
ptr2 = ptr2.next.next
if ptr1 == ptr2:
self.delete_loop(head, ptr1)
else:
return 1
def... |
class ConsoleGenerator:
def print_tree(self, indent=0, depth=99):
if depth > 0:
print(" " * indent, str(self))
self.descend_tree(indent, depth)
def descend_tree(self, indent=0, depth=99):
# do descent here, other classes may overload this
pass
@staticmet... | class Consolegenerator:
def print_tree(self, indent=0, depth=99):
if depth > 0:
print(' ' * indent, str(self))
self.descend_tree(indent, depth)
def descend_tree(self, indent=0, depth=99):
pass
@staticmethod
def output(py_obj):
print('#' * 80)
... |
"""BFS in Python."""
GRAPH = {"A": set(["B", "C", "E", "F"]),
"B": set(["A", "C", "D"]),
"C": set(["A", "B"]),
"D": set(["B"]),
"E": set(["B", "A"]),
"F": set(["A"])}
def bfs(graph, start):
"""Return visited nodes."""
visited = set()
queue = [start]
while ... | """BFS in Python."""
graph = {'A': set(['B', 'C', 'E', 'F']), 'B': set(['A', 'C', 'D']), 'C': set(['A', 'B']), 'D': set(['B']), 'E': set(['B', 'A']), 'F': set(['A'])}
def bfs(graph, start):
"""Return visited nodes."""
visited = set()
queue = [start]
while queue:
vertex = queue.pop(0)
if... |
#
# PySNMP MIB module HH3C-LswINF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-LswINF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:26:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, value_range_constraint, constraints_union, constraints_intersection) ... |
dt = 1/10
a = gamma.pdf( np.arange(0,10,dt), 2.5, 0 )
t = np.arange(0,10,dt)
# what should go into the np.cumsum() function?
v = np.cumsum(a*dt)
# this just plots your velocity:
with plt.xkcd():
plt.figure(figsize=(10,6))
plt.plot(t,a,label='acceleration [$m/s^2$]')
plt.plot(t,v,label='velocity [$m/s$]')
plt.... | dt = 1 / 10
a = gamma.pdf(np.arange(0, 10, dt), 2.5, 0)
t = np.arange(0, 10, dt)
v = np.cumsum(a * dt)
with plt.xkcd():
plt.figure(figsize=(10, 6))
plt.plot(t, a, label='acceleration [$m/s^2$]')
plt.plot(t, v, label='velocity [$m/s$]')
plt.xlabel('time [s]')
plt.ylabel('[motion]')
plt.legend(fac... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.