content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# FLOYD TRIANGLE
limit = int(input("Enter the limit: "))
n = 1
for i in range(1, limit+1):
for j in range(1, i+1):
print(n, ' ', end='') # print on same line
n += 1
print('')
| limit = int(input('Enter the limit: '))
n = 1
for i in range(1, limit + 1):
for j in range(1, i + 1):
print(n, ' ', end='')
n += 1
print('') |
# 008: Make a program that reads a value in meter and convert to centimeter and millimeter
n = float(input('Write a number in meter: '))
print(f'{n} is: {n*100:.1f}cm and {n*1000:.1f}mm')
| n = float(input('Write a number in meter: '))
print(f'{n} is: {n * 100:.1f}cm and {n * 1000:.1f}mm') |
def restar(x,y):
resta = x-y
return resta
def multiplicar(x,y):
mult = x*y
return mult
def dividir(x,y):
div = x/y
return div
| def restar(x, y):
resta = x - y
return resta
def multiplicar(x, y):
mult = x * y
return mult
def dividir(x, y):
div = x / y
return div |
if 1:
print("1 is ")
else:
print("???")
| if 1:
print('1 is ')
else:
print('???') |
print('''
_ _ _ _ _
| || | __ _ _ _ ___ | |_ (_) | |_
| __ | / _` | | '_| (_-< | ' \ | | | _|
|_||_| \__,_| |_| /__/ |_||_| |_| \__|
''')
print("IP \t Date time \t Request \t")
with open("website.log... | print("\n _ _ _ _ _ \n | || | __ _ _ _ ___ | |_ (_) | |_ \n | __ | / _` | | '_| (_-< | ' \\ | | | _|\n |_||_| \\__,_| |_| /__/ |_||_| |_| \\__|\n ")
print('IP \t Date time \t Request \t')
with open('website.log', 'r... |
sumTotal = 0
nameNum = ''
a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
g = 7
h = 8
i = 9
j = 10
k = 11
l = 12
m = 13
n = 14
o = 15
p = 16
q = 17
r = 18
s = 19
t = 20
u = 21
v = 22
w = 23
x = 24
y = 25
z = 26
A = '1'
B = '2'
C = '3'
D = '4'
E = '5'
F = '6'
G = '7'
H = '8'
I = '9'
J = '10'
K = '11'
L = '12'
M = '13'
N ... | sum_total = 0
name_num = ''
a = 1
b = 2
c = 3
d = 4
e = 5
f = 6
g = 7
h = 8
i = 9
j = 10
k = 11
l = 12
m = 13
n = 14
o = 15
p = 16
q = 17
r = 18
s = 19
t = 20
u = 21
v = 22
w = 23
x = 24
y = 25
z = 26
a = '1'
b = '2'
c = '3'
d = '4'
e = '5'
f = '6'
g = '7'
h = '8'
i = '9'
j = '10'
k = '11'
l = '12'
m = '13'
n = '14'
o ... |
"""
Validate BST: Implement a function to check if a binary tree is a binary search tree.
"""
# idea: if BST, inorder traversal gives a nondecreasing sorted list
class BTNode:
def __init__(self, val: int, left=None, right=None):
self.val = val
self.left: BTNode = left
self.righ... | """
Validate BST: Implement a function to check if a binary tree is a binary search tree.
"""
class Btnode:
def __init__(self, val: int, left=None, right=None):
self.val = val
self.left: BTNode = left
self.right: BTNode = right
def is_bst(node: BTNode):
stack = []
'nodes = []'
... |
############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | source('../../shared/qtcreator.py')
def main():
start_application('qtcreator' + SettingsPath)
if not started_without_plugin_error():
return
available = ['5.6']
for qt_version in available:
working_dir = temp_dir()
project_name = create_new_qt_quick_ui(workingDir, qtVersion)
... |
#State Codes
area_codes = [("Alabama",[205, 251, 256, 334, 659, 938]),
("Alaska",[907]),
("Arizona",[480, 520, 602, 623, 928]),
("Arkansas",[327, 479, 501, 870]),
("California",[209, 213, 310, 323, 341, 369, 408, 415, 424, 442, 510, 530, 559, 562, 619, 626, 627, 628, 650, 657, 661, 669, 707, 714, 747, 760, 764, 805, 81... | area_codes = [('Alabama', [205, 251, 256, 334, 659, 938]), ('Alaska', [907]), ('Arizona', [480, 520, 602, 623, 928]), ('Arkansas', [327, 479, 501, 870]), ('California', [209, 213, 310, 323, 341, 369, 408, 415, 424, 442, 510, 530, 559, 562, 619, 626, 627, 628, 650, 657, 661, 669, 707, 714, 747, 760, 764, 805, 818, 831, ... |
#!/usr/bin/python
'''the -O turns off the assertions'''
def myFunc(a,b,c,d):
''' this is my function with
the formula
(2*a+b)/(c-d)
'''
assert c!=d, "c should not equal d"
return (2*a+b)/(c-d)
myFunc(1,2,3,3)
| """the -O turns off the assertions"""
def my_func(a, b, c, d):
""" this is my function with
the formula
(2*a+b)/(c-d)
"""
assert c != d, 'c should not equal d'
return (2 * a + b) / (c - d)
my_func(1, 2, 3, 3) |
#
# PySNMP MIB module H3C-IKE-MONITOR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-IKE-MONITOR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:09:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) ... |
"""Perform any setup needed here.
"""
__author__ = 'dmontemayor'
| """Perform any setup needed here.
"""
__author__ = 'dmontemayor' |
print("Hello World")
print("Hello again.\n")
print("Hello BCC!")
print("My name is Andy.\n")
print("single 'quotes' <-- in double quotes")
print('double "quotes" <-- in single quotes\n')
print("Python docs @ --> https://docs/python.org/3")
print("Type --> python3 ex1.py <-- in terminal to run this program.\n")
# print(... | print('Hello World')
print('Hello again.\n')
print('Hello BCC!')
print('My name is Andy.\n')
print("single 'quotes' <-- in double quotes")
print('double "quotes" <-- in single quotes\n')
print('Python docs @ --> https://docs/python.org/3')
print('Type --> python3 ex1.py <-- in terminal to run this program.\n') |
#
# PySNMP MIB module Wellfleet-QOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-QOS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:41:23 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint) ... |
class Solution:
"""
@param: nums: a list of integers
@return: find a majority number
"""
def majorityNumber(self, nums):
# write your code here
length = len(nums)
for i in range(int(length / 2) + 1):
count = 1
for j in range(i + 1, length):
... | class Solution:
"""
@param: nums: a list of integers
@return: find a majority number
"""
def majority_number(self, nums):
length = len(nums)
for i in range(int(length / 2) + 1):
count = 1
for j in range(i + 1, length):
if nums[i] == nums[j]:
... |
def main():
n = int(input('Number to count to: '))
fizzbuzz(n)
def fizzbuzz(n):
for number in range(1, n + 1):
if number % 5 == 0:
if number % 3 == 0:
print('FizzBuzz')
if number % 3 == 0:
print('Fizz')
elif number % 5 == 0:
p... | def main():
n = int(input('Number to count to: '))
fizzbuzz(n)
def fizzbuzz(n):
for number in range(1, n + 1):
if number % 5 == 0:
if number % 3 == 0:
print('FizzBuzz')
if number % 3 == 0:
print('Fizz')
elif number % 5 == 0:
print(... |
## setup MQTT
MQTT_BROKER = "" # Ip adress of the MQTT Broker
MQTT_USERNAME = "" # Username
MQTT_PASSWD = "" # Password
MQTT_TOPIC = "" # MQTT Topic
## setup RGB
NUMBER_OF_LEDS= 100 #int
| mqtt_broker = ''
mqtt_username = ''
mqtt_passwd = ''
mqtt_topic = ''
number_of_leds = 100 |
# Copyright 2021 Nate Gay
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, so... | """rules_kustomize"""
load('@bazel_skylib//lib:dicts.bzl', 'dicts')
load('@io_bazel_rules_docker//container:providers.bzl', 'PushInfo')
image_info = provider(doc='Image modification information', fields={'partial': 'A yaml file containing kustomize image replacement info'})
def _impl(ctx):
image_name = '{}/{}'.for... |
def parseFileTypes(rawTypes):
out = []
for rtype in rawTypes:
if isinstance(rtype, str):
out.append({'name': rtype, 'ext': rtype})
else:
assert 'name' in rtype
assert 'ext' in rtype
out.append({'name': rtype['name'], 'ext': rtype['ext']})
ret... | def parse_file_types(rawTypes):
out = []
for rtype in rawTypes:
if isinstance(rtype, str):
out.append({'name': rtype, 'ext': rtype})
else:
assert 'name' in rtype
assert 'ext' in rtype
out.append({'name': rtype['name'], 'ext': rtype['ext']})
ret... |
class Solution(object):
def threeConsecutiveOdds(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
# Runtime: 32 ms
# Memory: 13.4 MB
for idx in range(len(arr) - 2):
if arr[idx] % 2 == 1 and arr[idx + 1] % 2 == 1 and arr[idx + 2] % 2 == 1:
... | class Solution(object):
def three_consecutive_odds(self, arr):
"""
:type arr: List[int]
:rtype: bool
"""
for idx in range(len(arr) - 2):
if arr[idx] % 2 == 1 and arr[idx + 1] % 2 == 1 and (arr[idx + 2] % 2 == 1):
return True
return False |
def _syswrite(fh, scalar, length=None, offset=0):
"""Implementation of perl syswrite"""
if length is None and hasattr(scalar, 'len'):
length = len(scalar)-offset
if isinstance(scalar, str):
return os.write(fh.fileno(), scalar[offset:length+offset].encode())
elif isinstance(scalar... | def _syswrite(fh, scalar, length=None, offset=0):
"""Implementation of perl syswrite"""
if length is None and hasattr(scalar, 'len'):
length = len(scalar) - offset
if isinstance(scalar, str):
return os.write(fh.fileno(), scalar[offset:length + offset].encode())
elif isinstance(scalar, by... |
keycode = {
'up': 72,
'down': 80,
'left': 75,
'right': 77,
'P': 25
} | keycode = {'up': 72, 'down': 80, 'left': 75, 'right': 77, 'P': 25} |
'''
Given two strings, determine if they share a common substring. A
substring may be as small as one character.
For example, the words "a", "and", "art" share the common substring .
The words "be" and "cat" do not share a substring.
'''
#this has the best runtime out of initial coding varieties
def twoStrings(s1,... | """
Given two strings, determine if they share a common substring. A
substring may be as small as one character.
For example, the words "a", "and", "art" share the common substring .
The words "be" and "cat" do not share a substring.
"""
def two_strings(s1, s2):
s1 = list(set(s1))
cache = {}
for i in s1... |
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
ans = 0
for i in range(0, len(S)):
if(J.find(S[i])!=-1):
ans += 1
return ans | class Solution:
def num_jewels_in_stones(self, J: str, S: str) -> int:
ans = 0
for i in range(0, len(S)):
if J.find(S[i]) != -1:
ans += 1
return ans |
# This is an Adventure Game about The Digital Sweet Shop
# The program was written by Dr. Aung Win Htut
# Date: 04-03-2022
# Green Hackers Online Traing Courses
# 0-robot.py, 1-adgame3.py, 2-entershop.py, 3-ifelse2.py, 4-input.py, 5-ad62.py, 6-ad63.py
# The next few lines give the introduction
# Greetings m... | playerlives = 3
chocolate = 2
bonus = 0
numbercorrect = 0
print()
print()
print()
print(' Game Intro')
print(' ===========')
print('Greetings my friend. if you want to go to the Digital Sweet Shop you must walk across')
print('the long street and turn left a... |
class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
counter = 1
for i in range(len(nums)-1):
counter -= 1
counter = max(counter,nums[i])
if counter <= 0:
return False
... | class Solution(object):
def can_jump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
counter = 1
for i in range(len(nums) - 1):
counter -= 1
counter = max(counter, nums[i])
if counter <= 0:
return False
... |
class Solution:
def longestPalindrome(self, s: 'str') -> 'str':
if len(s) <= 1:
return s
start = end = 0
length = len(s)
for i in range(length):
max_len_1 = self.get_max_len(s, i, i + 1)
max_len_2 = self.get_max_len(s, i, i)
max_len = m... | class Solution:
def longest_palindrome(self, s: 'str') -> 'str':
if len(s) <= 1:
return s
start = end = 0
length = len(s)
for i in range(length):
max_len_1 = self.get_max_len(s, i, i + 1)
max_len_2 = self.get_max_len(s, i, i)
max_len =... |
class Patient:
def __init__(self, pathology, gender, weight, height, images):
self.pathology = pathology
self.gender = gender
self.weight = weight
self.height = height
self.images = images | class Patient:
def __init__(self, pathology, gender, weight, height, images):
self.pathology = pathology
self.gender = gender
self.weight = weight
self.height = height
self.images = images |
class Solution(object):
def numSpecialEquivGroups(self, A):
"""
:type A: List[str]
:rtype: int
"""
st = set()
for s in A:
lstA = []
lstB = []
for i in range(len(s)):
if i % 2 == 0:
lstA.append(s[i... | class Solution(object):
def num_special_equiv_groups(self, A):
"""
:type A: List[str]
:rtype: int
"""
st = set()
for s in A:
lst_a = []
lst_b = []
for i in range(len(s)):
if i % 2 == 0:
lstA.appe... |
def determinant_recursive(A, total=0):
# Store indices in list for row referencing
indices = list(range(len(A)))
# When at 2x2, submatrices recursive calls end
if len(A) == 2 and len(A[0]) == 2:
val = A[0][0] * A[1][1] - A[1][0] * A[0][1]
return val
# Define submatrix for ... | def determinant_recursive(A, total=0):
indices = list(range(len(A)))
if len(A) == 2 and len(A[0]) == 2:
val = A[0][0] * A[1][1] - A[1][0] * A[0][1]
return val
for fc in indices:
as = A
as = As[1:]
height = len(As)
for i in range(height):
As[i] = As... |
__all__ = [
"_is_ltag",
"_is_not_ltag",
"_is_rtag",
"_is_not_rtag",
"_is_tag",
"_is_not_tag",
"_is_ltag_of",
"_is_not_ltag_of",
"_is_rtag_of",
"_is_not_rtag_of",
"_is_pair_of",
"_is_not_pair_of",
"_is_not_ltag_and_not_rtag_of"
]
####
def _is_ltag(tag,tag_pairs):
... | __all__ = ['_is_ltag', '_is_not_ltag', '_is_rtag', '_is_not_rtag', '_is_tag', '_is_not_tag', '_is_ltag_of', '_is_not_ltag_of', '_is_rtag_of', '_is_not_rtag_of', '_is_pair_of', '_is_not_pair_of', '_is_not_ltag_and_not_rtag_of']
def _is_ltag(tag, tag_pairs):
cond = tag in tag_pairs
return cond
def _is_not_ltag(... |
int_const = 5
bool_const = True
string_const = 'abc'
unicode_const = u'abc'
float_const = 1.23 | int_const = 5
bool_const = True
string_const = 'abc'
unicode_const = u'abc'
float_const = 1.23 |
class Foo:
"""docstring"""
@property
def prop1(self) -> int:
"""docstring"""
@classmethod
@property
def prop2(self) -> int:
"""docstring"""
| class Foo:
"""docstring"""
@property
def prop1(self) -> int:
"""docstring"""
@classmethod
@property
def prop2(self) -> int:
"""docstring""" |
'''
https://practice.geeksforgeeks.org/problems/subarray-with-given-sum/0/?ref=self
Given an unsorted array of non-negative integers, find a
continuous sub-array which adds to a given number.
Input:
The first line of input contains an integer T denoting the number of test cases.
Then T test ... | """
https://practice.geeksforgeeks.org/problems/subarray-with-given-sum/0/?ref=self
Given an unsorted array of non-negative integers, find a
continuous sub-array which adds to a given number.
Input:
The first line of input contains an integer T denoting the number of test cases.
Then T test ... |
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and not (n & (n - 1))
class Solution2(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
... | class Solution(object):
def is_power_of_two(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and (not n & n - 1)
class Solution2(object):
def is_power_of_two(self, n):
"""
:type n: int
:rtype: bool
"""
return ... |
messageResources = {}
messageResources['it'] = {
'browse':'Sfoglia',
'play':'Play',
'open.file':'Apri file',
'file':'File',
'edit':'Modifica',
'audio':'Audio',
'video':'Video',
'open':'Apri...',
'quit':'Esci',
'clear.file.list':'Cancella la lista dei file',
'output.audio':'Uscita audio... | message_resources = {}
messageResources['it'] = {'browse': 'Sfoglia', 'play': 'Play', 'open.file': 'Apri file', 'file': 'File', 'edit': 'Modifica', 'audio': 'Audio', 'video': 'Video', 'open': 'Apri...', 'quit': 'Esci', 'clear.file.list': 'Cancella la lista dei file', 'output.audio': 'Uscita audio', 'hdmi': 'HDMI', 'loc... |
def simple(request):
return {
'simple': {
'boolean': True,
'list': [1, 2, 3],
}
}
def is_authenticated(request):
is_authenticated = request.user and request.user.is_authenticated
if callable(is_authenticated):
is_authenticated = is_authenticated()
r... | def simple(request):
return {'simple': {'boolean': True, 'list': [1, 2, 3]}}
def is_authenticated(request):
is_authenticated = request.user and request.user.is_authenticated
if callable(is_authenticated):
is_authenticated = is_authenticated()
return {'is_authenticated': is_authenticated} |
class Generating:
def __init__(self, node):
self._node = node
def generatetoaddress(self, nblocks, address, maxtries=1): # 01
return self._node._rpc.call("generatetoaddress", nblocks, address, maxtries)
| class Generating:
def __init__(self, node):
self._node = node
def generatetoaddress(self, nblocks, address, maxtries=1):
return self._node._rpc.call('generatetoaddress', nblocks, address, maxtries) |
"""Tools
"""
def _create_dirtree(a,chunksize=2):
"""create a directory tree from a single, long name
e.g. "12345" --> ["1", "23", "45"]
"""
b = a[::-1] # reverse
i = 0
l = []
while i < len(b):
l.append(b[i:i+chunksize])
i += chunksize
return [e[::-1] for e in l[::-1]]
... | """Tools
"""
def _create_dirtree(a, chunksize=2):
"""create a directory tree from a single, long name
e.g. "12345" --> ["1", "23", "45"]
"""
b = a[::-1]
i = 0
l = []
while i < len(b):
l.append(b[i:i + chunksize])
i += chunksize
return [e[::-1] for e in l[::-1]]
def _sh... |
"""Project metadata."""
package = "humilis_secrets_vault"
project = "humilis-secrets-vault"
version = '0.2.4'
description = "Humilis layer that deploys a secrets vault"
authors = ["German Gomez-Herrero"]
authors_string = ', '.join(authors)
emails = ["german@findhotel.net"]
license = "MIT"
copyright = "2016 FindHotel B... | """Project metadata."""
package = 'humilis_secrets_vault'
project = 'humilis-secrets-vault'
version = '0.2.4'
description = 'Humilis layer that deploys a secrets vault'
authors = ['German Gomez-Herrero']
authors_string = ', '.join(authors)
emails = ['german@findhotel.net']
license = 'MIT'
copyright = '2016 FindHotel BV... |
##
# \namespace cross3d.classes.valuerange
#
# \remarks This module holds the ValueRange class to handle value ranges.
#
# \author douglas
# \author Blur Studio
# \date 02/17/16
#
#----------------------------------------------------------------------------------------------------... | class Valuerange(list):
def __init__(self, *args):
"""
\remarks Initialize the class.
"""
args = list(args)
if not len(args) == 2:
raise type_error('ValueRange object takes two floats. You provided {} arguments.'.format(len(args)))
try:
args[0] = float(a... |
# -*- coding: utf-8 -*-
"""Top-level package for ebr-trackerbot."""
__project__ = "ebr-trackerbot"
__author__ = "Milan Hradil"
__email__ = "milan.hradil@tomtom.com"
__version__ = "0.1.5-dev"
| """Top-level package for ebr-trackerbot."""
__project__ = 'ebr-trackerbot'
__author__ = 'Milan Hradil'
__email__ = 'milan.hradil@tomtom.com'
__version__ = '0.1.5-dev' |
n_h1=100
n_h2=100
n_h3=100
batch_size=20
| n_h1 = 100
n_h2 = 100
n_h3 = 100
batch_size = 20 |
class URI:
prefix = {
'dbpedia': 'http://dbpedia.org/page/',
'dbr': 'http://dbpedia.org/resource/',
'dbo': 'http://dbpedia.org/ontology/',
'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
'xsd': 'http://www.w3.org/2001/XMLSchema#',
'dt': 'http://dbpedia.org/datatype/'... | class Uri:
prefix = {'dbpedia': 'http://dbpedia.org/page/', 'dbr': 'http://dbpedia.org/resource/', 'dbo': 'http://dbpedia.org/ontology/', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'xsd': 'http://www.w3.org/2001/XMLSchema#', 'dt': 'http://dbpedia.org/datatype/'}
def __init__(self, prefix, suffix):
... |
class Solution:
def myPow(self, x: float, n: int) -> float:
if n < 0:
val = 1 / self._myPow(x, -n)
else:
val = self._myPow(x, n)
return val
def _myPow(self, x: float, n: int) -> float:
if n == 1:
return x
if n == 0:
return ... | class Solution:
def my_pow(self, x: float, n: int) -> float:
if n < 0:
val = 1 / self._myPow(x, -n)
else:
val = self._myPow(x, n)
return val
def _my_pow(self, x: float, n: int) -> float:
if n == 1:
return x
if n == 0:
retu... |
#1. Idea is we use a stack, where each element in the stack is a list, the list contains the current string and current repeat value, we know it is the current string because we have not yet hit a closed bracket because once we hit the closed bracket we pop off.
#2. Initialize a stack which contains an empty string an... | def decode_string(self, s):
stack = [['', 1]]
k = 0
for i in s:
if i.isdigit():
k = k * 10 + int(i)
elif i == '[':
stack.append(['', k])
k = 0
elif i == ']':
(char_string, repeat_val) = stack.pop()
stack[-1][0] += char_strin... |
T = int(input())
for _ in range(T):
h = 1
for i in range(int(input())):
if i % 2 == 0:
h *= 2
else:
h += 1
print(h)
| t = int(input())
for _ in range(T):
h = 1
for i in range(int(input())):
if i % 2 == 0:
h *= 2
else:
h += 1
print(h) |
class Queue(object):
def __init__(self):
self.queue = []
self.size = 0
def isEmpty(self):
return self.queue == []
def enqueue(self, item):
self.queue.insert(0, item)
self.size += 1
def dequeu(self):
if not self.isEmpty():
self.size -= 1
... | class Queue(object):
def __init__(self):
self.queue = []
self.size = 0
def is_empty(self):
return self.queue == []
def enqueue(self, item):
self.queue.insert(0, item)
self.size += 1
def dequeu(self):
if not self.isEmpty():
self.size -= 1
... |
class HttpListenerTimeoutManager(object):
# no doc
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return HttpListenerTimeoutManager()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
DrainEntityBody=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get:... | class Httplistenertimeoutmanager(object):
def zzz(self):
"""hardcoded/mock instance of the class"""
return http_listener_timeout_manager()
instance = zzz()
'hardcoded/returns an instance of the class'
drain_entity_body = property(lambda self: object(), lambda self, v: None, lambda self:... |
#!/usr/bin/env python
ord_numbers = []
for i in range(1,50):
ord_numbers.append(i)
print(ord_numbers)
for j in ord_numbers:
if j == 13:
continue
elif j > 39:
break
else:
print(j)
| ord_numbers = []
for i in range(1, 50):
ord_numbers.append(i)
print(ord_numbers)
for j in ord_numbers:
if j == 13:
continue
elif j > 39:
break
else:
print(j) |
doc(title="PaddlePaddle Use-Cases",
underline_char="=",
entries=[
"resnet50/paddle-resnet50.rst",
"ssd/paddle-ssd.rst",
"tsm/paddle-tsm.rst",
])
| doc(title='PaddlePaddle Use-Cases', underline_char='=', entries=['resnet50/paddle-resnet50.rst', 'ssd/paddle-ssd.rst', 'tsm/paddle-tsm.rst']) |
def generate_worklist(n, n_process, generate_mode="random", time_weights=None):
works_type = {}
works = []
if generate_mode == "random":
minimum_time = 10
maximum_time = 300
reset_time_weights_prob = 0.05
time_weights = [random.randint(minimum_time, maximum_time) for i in range(n_process)]
type_name = ti... | def generate_worklist(n, n_process, generate_mode='random', time_weights=None):
works_type = {}
works = []
if generate_mode == 'random':
minimum_time = 10
maximum_time = 300
reset_time_weights_prob = 0.05
time_weights = [random.randint(minimum_time, maximum_time) for i in ran... |
class Node:
def __init__(self, item):
self.item = item
self.left = None
self.right = None
class BinaryTree:
def __init__(self, root):
self.root = root
def insert(self, root, node):
if node.item < root.item:
i... | class Node:
def __init__(self, item):
self.item = item
self.left = None
self.right = None
class Binarytree:
def __init__(self, root):
self.root = root
def insert(self, root, node):
if node.item < root.item:
if not root.left:
root.left =... |
API_STAGE = 'dev'
APP_FUNCTION = 'handler_for_events'
APP_MODULE = 'tests.test_event_script_app'
DEBUG = 'True'
DJANGO_SETTINGS = None
DOMAIN = 'api.example.com'
ENVIRONMENT_VARIABLES = {}
LOG_LEVEL = 'DEBUG'
PROJECT_NAME = 'test_event_script_app'
COGNITO_TRIGGER_MAPPING = {}
| api_stage = 'dev'
app_function = 'handler_for_events'
app_module = 'tests.test_event_script_app'
debug = 'True'
django_settings = None
domain = 'api.example.com'
environment_variables = {}
log_level = 'DEBUG'
project_name = 'test_event_script_app'
cognito_trigger_mapping = {} |
AVAILABLE_OUTPUTS = [
(20, 'out 1'),
(21, 'out 2')
]
| available_outputs = [(20, 'out 1'), (21, 'out 2')] |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isValidBST(self, root):
def util(root, low, high):
if not root:
return True
return low < root... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def is_valid_bst(self, root):
def util(root, low, high):
if not root:
return True
return low < root.val and root.val < high and util(... |
class Solution:
def reverseVowels(self, s):
"""
:type s: str
:rtype: str
"""
vow = ['a', 'e', 'i', 'o', 'u']
ch = [c for c in s]
low, high = 0, len(ch) - 1
while low < high:
while low < high and ch[low] not in vow:
print("l... | class Solution:
def reverse_vowels(self, s):
"""
:type s: str
:rtype: str
"""
vow = ['a', 'e', 'i', 'o', 'u']
ch = [c for c in s]
(low, high) = (0, len(ch) - 1)
while low < high:
while low < high and ch[low] not in vow:
pri... |
"""
Copyright 2019 Islam Elnabarawy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to ... | """
Copyright 2019 Islam Elnabarawy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to ... |
"""
ID: tony_hu1
PROG: milk3
LANG: PYTHON3
"""
filein = []
with open('milk3.in') as filename:
for line in filename:
filein.append(line.rstrip())
filein = filein[0].split(' ')
a = int(filein[0])
b = int(filein[1])
c = int(filein[2])
list_possibilities = [[[False]*c]*b]*a
m = get_possible(a,b,c)
outstring = ... | """
ID: tony_hu1
PROG: milk3
LANG: PYTHON3
"""
filein = []
with open('milk3.in') as filename:
for line in filename:
filein.append(line.rstrip())
filein = filein[0].split(' ')
a = int(filein[0])
b = int(filein[1])
c = int(filein[2])
list_possibilities = [[[False] * c] * b] * a
m = get_possible(a, b, c)
outst... |
#input
# 28
# RP PP RR PS RP
# PR PP SR PS SS RR RS RP
# PR SP PR RS RP PP RS
# RP PS PS PR SS RR PP PR SP SP RR PR PS PS SP
# RS PS RR PR RP PR RS SR SR RR PP PP SR RS RP
# RR RR RR SP PR RP RR PP SP PS RR RS SP
# SS RP RP PP SS RR RP PS SP RR RS SR RS RS SS PS
# SR SP SR RP RP SS SP PP SS SS SS SS RP
# SR PP RP PP RP... | def convert_sign(s):
if s == 'R':
return 0
elif s == 'P':
return 1
else:
return 2
def winner(seq):
a = convert_sign(seq[0])
b = convert_sign(seq[1])
res = (a - b + 3) % 3
if res == 0:
return -1
elif res == 1:
return 0
else:
return 1
d... |
"""Custom exceptions.
All the exceptions raised by the code in avazu_ctr_prediction.* should derive from Avazu-Ctr-PredictionException
"""
class AvazuCtrPredictionException(Exception):
"""Mother class for common avazu_ctr_prediction exceptions."""
pass
class MissingModelException(AvazuCtrPredictionExcepti... | """Custom exceptions.
All the exceptions raised by the code in avazu_ctr_prediction.* should derive from Avazu-Ctr-PredictionException
"""
class Avazuctrpredictionexception(Exception):
"""Mother class for common avazu_ctr_prediction exceptions."""
pass
class Missingmodelexception(AvazuCtrPredictionException)... |
sum =0
n = 99
while n>0:
sum = sum+n
n=n-2
if n<10:
break
print(sum)
#----------
for x in range(101):
if x%2==0:
continue
else:
print(x)
#----------
y = 0
while True:
print(y)
y=y+1
| sum = 0
n = 99
while n > 0:
sum = sum + n
n = n - 2
if n < 10:
break
print(sum)
for x in range(101):
if x % 2 == 0:
continue
else:
print(x)
y = 0
while True:
print(y)
y = y + 1 |
def imprimePorIdade(pDIct = dict()):
sortedDict = sorted(pDIct.items(), key = lambda x: x[1], reverse=False)
for i in sortedDict:
print(i[0], i[1])
pass
pass
testDict = { "narto": 29, "leo": 13, "antonia": 45, "mimosa": 27, }
imprimePorIdade(testDict) | def imprime_por_idade(pDIct=dict()):
sorted_dict = sorted(pDIct.items(), key=lambda x: x[1], reverse=False)
for i in sortedDict:
print(i[0], i[1])
pass
pass
test_dict = {'narto': 29, 'leo': 13, 'antonia': 45, 'mimosa': 27}
imprime_por_idade(testDict) |
#sublist
def sub_list(list):
return list[1:3]
result = sub_list([1,2,3,4,5])
print(result)
#concatenation
list1 = [1,2,4,5,6]
list2 = [5,6,7,8,9]
list3 = list1 + list2
print(list3)
#traverse
for element in list3:
print(element)
#list slicing
def get_sublist(list):
return [list[0:3], list[3:]]
print... | def sub_list(list):
return list[1:3]
result = sub_list([1, 2, 3, 4, 5])
print(result)
list1 = [1, 2, 4, 5, 6]
list2 = [5, 6, 7, 8, 9]
list3 = list1 + list2
print(list3)
for element in list3:
print(element)
def get_sublist(list):
return [list[0:3], list[3:]]
print(get_sublist([1, 4, 9, 10, 23]))
print()
de... |
# _*_ coding:utf-8 _*_
#!/usr/local/bin/python
encrypted = [6,3,1,7,5,8,9,2,4]
def decrypt(encryptedTxt):
head = 0
tail = len(encryptedTxt)-1
decrypted = []
while len(encryptedTxt)>0:
decrypted.append(encryptedTxt[0])
del encryptedTxt[0]
print(encryptedTxt)
if(len(encr... | encrypted = [6, 3, 1, 7, 5, 8, 9, 2, 4]
def decrypt(encryptedTxt):
head = 0
tail = len(encryptedTxt) - 1
decrypted = []
while len(encryptedTxt) > 0:
decrypted.append(encryptedTxt[0])
del encryptedTxt[0]
print(encryptedTxt)
if len(encryptedTxt) <= 0:
break
... |
# https://www.codewars.com/kata/550554fd08b86f84fe000a58/train/python
def in_array(array1, array2):
result = []
array1 = list(set(array1))
for arr1_element in array1:
for arr2_element in array2:
if arr2_element.count(arr1_element) != 0:
result.append(arr1_element)
... | def in_array(array1, array2):
result = []
array1 = list(set(array1))
for arr1_element in array1:
for arr2_element in array2:
if arr2_element.count(arr1_element) != 0:
result.append(arr1_element)
break
return sorted(result) |
#!/usr/bin/python
#https://practice.geeksforgeeks.org/problems/is-binary-number-multiple-of-3/0
def sol(x):
"""
If the diff. of even set bits and odd set bits is divisible by 3, then
the number is divisible by 3
"""
n = len(x)
oddCount = 0
evenCount = 0
for i in range(n):
i... | def sol(x):
"""
If the diff. of even set bits and odd set bits is divisible by 3, then
the number is divisible by 3
"""
n = len(x)
odd_count = 0
even_count = 0
for i in range(n):
if i % 2 == 0:
if x[i] == '1':
even_count += 1
elif x[i] == '1':
... |
class MyCircularQueue:
def __init__(self, k: int):
self.q = [None] * k
self.front_idx = -1
self.back_idx = -1
self.capacity = k
def display_elements(self):
print("The elements in the Queue are ")
print_str = ""
# add the elements to the print string
... | class Mycircularqueue:
def __init__(self, k: int):
self.q = [None] * k
self.front_idx = -1
self.back_idx = -1
self.capacity = k
def display_elements(self):
print('The elements in the Queue are ')
print_str = ''
for i in range(self.capacity):
... |
def binary_search(search_val, search_list):
midpoint = (len(search_list)-1) // 2
if search_val == search_list[midpoint]:
return True
elif len(search_list) == 1 and search_val != search_list[0]:
return False
elif search_val > search_list[midpoint]:
return binary_search(search_val... | def binary_search(search_val, search_list):
midpoint = (len(search_list) - 1) // 2
if search_val == search_list[midpoint]:
return True
elif len(search_list) == 1 and search_val != search_list[0]:
return False
elif search_val > search_list[midpoint]:
return binary_search(search_va... |
class CachedAccessor:
def __init__(self, name, accessor):
self._name = name
self._accessor = accessor
def __get__(self, obj, cls):
if obj is None:
return self._accessor
accessor_obj = self._accessor(obj)
setattr(obj, self._name, accessor_obj)
return... | class Cachedaccessor:
def __init__(self, name, accessor):
self._name = name
self._accessor = accessor
def __get__(self, obj, cls):
if obj is None:
return self._accessor
accessor_obj = self._accessor(obj)
setattr(obj, self._name, accessor_obj)
return ... |
matrix = [[0,0,0], [0,0,0], [0,0,0]]
for l in range(0,3):
for c in range(0,3):
matrix[l][c] = int(input(f'digite um numero [{l}][{c}]: '))
print('-='*30)
for l in range(0,3):
for c in range(0,3):
print(f'[{matrix[l][c]:^5}]', end='')
print() | matrix = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for l in range(0, 3):
for c in range(0, 3):
matrix[l][c] = int(input(f'digite um numero [{l}][{c}]: '))
print('-=' * 30)
for l in range(0, 3):
for c in range(0, 3):
print(f'[{matrix[l][c]:^5}]', end='')
print() |
# -*- coding: utf-8 -*-
# Scrapy settings for FinalProject project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
# http://scrapy.readthedocs.org/en/l... | bot_name = 'FinalProject'
spider_modules = ['FinalProject.spiders']
newspider_module = 'FinalProject.spiders'
dbkwargs = {'db': 'final_project', 'user': 'root', 'passwd': '', 'host': 'localhost', 'use_unicode': False, 'charset': 'utf8'}
db_table = 'HouseRent_58'
crawlera_enabled = True
crawlera_apikey = '0ccaed0e666542... |
def _try_composite(a, d, n, s):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n - 1:
return False
return True
def is_prime(n):
"""
Deterministic variant of the Miller-Rabin primality test to determine
whether a given number is prime... | def _try_composite(a, d, n, s):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2 ** i * d, n) == n - 1:
return False
return True
def is_prime(n):
"""
Deterministic variant of the Miller-Rabin primality test to determine
whether a given number is prim... |
class Solution:
def stringMatching(self, words: List[str]) -> List[str]:
words.sort(key=len)
res = []
lps = [self._compute_lps(w) for w in words[:-1]]
for i in range(len(words)):
for j in range(i + 1, len(words)):
if self._kmp(words[i], words[j], lps[i]):
... | class Solution:
def string_matching(self, words: List[str]) -> List[str]:
words.sort(key=len)
res = []
lps = [self._compute_lps(w) for w in words[:-1]]
for i in range(len(words)):
for j in range(i + 1, len(words)):
if self._kmp(words[i], words[j], lps[i])... |
def get_users(passwd: str) -> dict:
"""Split password output by newline,
extract user and name (1st and 5th columns),
strip trailing commas from name,
replace multiple commas in name with a single space
return dict of keys = user, values = name.
"""
output = {}
for line in passwd... | def get_users(passwd: str) -> dict:
"""Split password output by newline,
extract user and name (1st and 5th columns),
strip trailing commas from name,
replace multiple commas in name with a single space
return dict of keys = user, values = name.
"""
output = {}
for line in passwd... |
def char_concat(word):
string = ''
for i in range(int(len(word)/2)):
string += word[i] + word[-i-1] + str(i+1)
return string | def char_concat(word):
string = ''
for i in range(int(len(word) / 2)):
string += word[i] + word[-i - 1] + str(i + 1)
return string |
def transcribe(seq: str) -> str:
"""
transcribes DNA to RNA by generating
the complement sequence with T -> U replacement
"""
rna=""
for i in seq:
if i not in 'ATGC':
rna = "Invalid Input" ##only accepts ATGC as a input
break
##builds a rna string by con... | def transcribe(seq: str) -> str:
"""
transcribes DNA to RNA by generating
the complement sequence with T -> U replacement
"""
rna = ''
for i in seq:
if i not in 'ATGC':
rna = 'Invalid Input'
break
if i == 'A':
rna += 'U'
elif i == 'C':
... |
class KdcVendor(basestring):
"""
Kerberos Key Distribution Center (KDC) Vendor
Possible values:
<ul>
<li> "microsoft" ,
<li> "other"
</ul>
"""
@staticmethod
def get_api_name():
return "kdc-vendor"
| class Kdcvendor(basestring):
"""
Kerberos Key Distribution Center (KDC) Vendor
Possible values:
<ul>
<li> "microsoft" ,
<li> "other"
</ul>
"""
@staticmethod
def get_api_name():
return 'kdc-vendor' |
def test_chain_web3_is_preconfigured_with_default_from(project):
default_account = '0x0000000000000000000000000000000000001234'
project.config['web3.Tester.eth.default_account'] = default_account
with project.get_chain('tester') as chain:
web3 = chain.web3
assert web3.eth.defaultAccount ==... | def test_chain_web3_is_preconfigured_with_default_from(project):
default_account = '0x0000000000000000000000000000000000001234'
project.config['web3.Tester.eth.default_account'] = default_account
with project.get_chain('tester') as chain:
web3 = chain.web3
assert web3.eth.defaultAccount == d... |
#Ascending order
n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
for i in range(n):
for j in range(n-1):
if(a[j]>a[j+1]):
a[j],a[j+1]=a[j+1],a[j]
print(a)
#Descending order
Data = [75,3,73,7,6,23,89,8]
for i in range(len(Data)):
for j in range(len(Data)-1):
... | n = int(input().strip())
a = list(map(int, input().strip().split(' ')))
for i in range(n):
for j in range(n - 1):
if a[j] > a[j + 1]:
(a[j], a[j + 1]) = (a[j + 1], a[j])
print(a)
data = [75, 3, 73, 7, 6, 23, 89, 8]
for i in range(len(Data)):
for j in range(len(Data) - 1):
if Data[j] ... |
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
ans = []
self.dfs(S, 0, ans, [])
return ans
def dfs(self, S, i, ans, path):
if i == len(S):
ans.append(''.join(path))
return
self.dfs(S, i+1, ans, path + [S[i]]... | class Solution:
def letter_case_permutation(self, S: str) -> List[str]:
ans = []
self.dfs(S, 0, ans, [])
return ans
def dfs(self, S, i, ans, path):
if i == len(S):
ans.append(''.join(path))
return
self.dfs(S, i + 1, ans, path + [S[i]])
if... |
# Copyright (c) 2013-2017 by Ron Frederick <ronf@timeheart.net>.
# All rights reserved.
#
# This program and the accompanying materials are made available under
# the terms of the Eclipse Public License v1.0 which accompanies this
# distribution and is available at:
#
# http://www.eclipse.org/legal/epl-v10.html
#
#... | """SSH client protocol handler"""
class Sshclient:
"""SSH client protocol handler
Applications should subclass this when implementing an SSH client.
The functions listed below should be overridden to define
application-specific behavior. In particular, the method
:meth:`auth_completed`... |
#!/usr/bin/env python3
def validate_user(username, minlen):
if type(username) != str:
raise TypeError("username must be a string")
if len(username) < minlen:
return False
if not username.isalnum():
return False
# Username can't begin with a number
if username[0].isnumeric():... | def validate_user(username, minlen):
if type(username) != str:
raise type_error('username must be a string')
if len(username) < minlen:
return False
if not username.isalnum():
return False
if username[0].isnumeric():
return False
return True |
# Get balances queries
LIQUIDITY_POSITIONS_QUERY = (
"""
liquidityPositions
(
first: $limit,
skip: $offset,
where: {{
user_in: $addresses,
liquidityTokenBalance_gt: $balance,
}}) {{
id
liquidityTokenBalance
pair {{
... | liquidity_positions_query = '\n liquidityPositions\n (\n first: $limit,\n skip: $offset,\n where: {{\n user_in: $addresses,\n liquidityTokenBalance_gt: $balance,\n }}) {{\n id\n liquidityTokenBalance\n pair {{\n id\n rese... |
#
# PySNMP MIB module HPN-ICF-DHCPRELAY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-DHCPRELAY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:37:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (def... | (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, single_value_constraint, value_range_constraint) ... |
# =============================================================================
# Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/
# FileName: 10921.py
# Description: UVa Online Judge - 10921
# =============================================================================
source = li... | source = list('-1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ')
target = list('-123456789022233344455566677778889999')
mapping = dict(zip(source, target))
while True:
try:
line = input()
except EOFError:
break
print(''.join(list(map(lambda x: mapping[x], line)))) |
#!/usr/bin/python3
def words_count(filename):
with open(filename, 'r') as file:
strg = file.read()
number = len(strg.split())
return number
print(words_count("testscript.py"))
a = [1, 2, 3]
b = (4, 5, 8)
for i, j in zip(a,b):
print(i + j)
| def words_count(filename):
with open(filename, 'r') as file:
strg = file.read()
number = len(strg.split())
return number
print(words_count('testscript.py'))
a = [1, 2, 3]
b = (4, 5, 8)
for (i, j) in zip(a, b):
print(i + j) |
def main():
n, k = map(int, input().split())
h = list(map(int, input().split()))
cost = [float('inf')] * n
cost[0] = 0
for i in range(1, n):
for j in range(1, k + 1):
if i - j < 0:
break
else:
cost[i] = min(cost[i], cost[i - j] + abs(h[... | def main():
(n, k) = map(int, input().split())
h = list(map(int, input().split()))
cost = [float('inf')] * n
cost[0] = 0
for i in range(1, n):
for j in range(1, k + 1):
if i - j < 0:
break
else:
cost[i] = min(cost[i], cost[i - j] + abs(... |
grammar = """
nonzeroDigit = digit:x ?(x != '0')
digits = <'0' | nonzeroDigit digit*>:i -> int(i)
netstring = digits:length ':' <anything{length}>:string ',' -> string
receiveNetstring = netstring:string -> receiver.netstringReceived(string)
"""
class NetstringSender(object):
def __init__(self, transport):
... | grammar = "\n\nnonzeroDigit = digit:x ?(x != '0')\ndigits = <'0' | nonzeroDigit digit*>:i -> int(i)\n\nnetstring = digits:length ':' <anything{length}>:string ',' -> string\n\nreceiveNetstring = netstring:string -> receiver.netstringReceived(string)\n\n"
class Netstringsender(object):
def __init__(self, transport... |
"""
type ctrl+space
this executes this file
type ctrl+.
you see the result in a pane
to see the result in a file
type ctrl+.
select line 20 (g 20 g v $)
type ctrl+enter
this executes your selection
you see the result in a pane
to see the result in a file
type ctrl+.
"""
print('hello world!')
"""
... | """
type ctrl+space
this executes this file
type ctrl+.
you see the result in a pane
to see the result in a file
type ctrl+.
select line 20 (g 20 g v $)
type ctrl+enter
this executes your selection
you see the result in a pane
to see the result in a file
type ctrl+.
"""
print('hello world!')
'\nct... |
class SimApp(QWidget):
def __init__(self, env):
super().__init__()
self.env = env
self.initUI()
def initUI(self):
grid = QGridLayout()
self.setLayout(grid)
grid.addWidget(QLabel('pods_min:'), 0, 0)
grid.addWidget(QLabel('pods_max:'), 1, 0)
grid.a... | class Simapp(QWidget):
def __init__(self, env):
super().__init__()
self.env = env
self.initUI()
def init_ui(self):
grid = q_grid_layout()
self.setLayout(grid)
grid.addWidget(q_label('pods_min:'), 0, 0)
grid.addWidget(q_label('pods_max:'), 1, 0)
g... |
class ContentBasedFiltering:
def limit_number_of_recommendations(self,limit):
self.limit = limit
def __init__(self,db, regenerate = False):
self.db = db
self.table = 'content_based_recommendations'
if regenerate or not db.table_exists(self.table):
self.generate_sim... | class Contentbasedfiltering:
def limit_number_of_recommendations(self, limit):
self.limit = limit
def __init__(self, db, regenerate=False):
self.db = db
self.table = 'content_based_recommendations'
if regenerate or not db.table_exists(self.table):
self.generate_simi... |
#This code has conflicting attributes,
#but the documentation in the standard library tells you do it this way :(
#See https://discuss.lgtm.com/t/warning-on-normal-use-of-python-socketserver-mixins/677
class ThreadingMixIn(object):
def process_request(selfself, req):
pass
class HTTPServer(object):
... | class Threadingmixin(object):
def process_request(selfself, req):
pass
class Httpserver(object):
def process_request(selfself, req):
pass
class _Threadingsimpleserver(ThreadingMixIn, HTTPServer):
pass |
"""
1. Clarification
2. Possible solutions
- Backtracking + Bit manipulation
- Iterative + Bit manipulation
3. Coding
4. Tests
"""
# T=O(len(all letters in arr) + 2^n), S=O(n)
class Solution:
def maxLength(self, arr: List[str]) -> int:
masks = list()
for s in arr:
mask = 0
... | """
1. Clarification
2. Possible solutions
- Backtracking + Bit manipulation
- Iterative + Bit manipulation
3. Coding
4. Tests
"""
class Solution:
def max_length(self, arr: List[str]) -> int:
masks = list()
for s in arr:
mask = 0
for ch in s:
idx = o... |
def cap_text(text):
'''
Input a String
Output a Capitalized String
'''
# return text.capitalize()
return text.title() | def cap_text(text):
"""
Input a String
Output a Capitalized String
"""
return text.title() |
# test to make sure that every brand in our file is at least 3 characters long
with open('car-brands.txt') as f:
result = all(map(lambda row: len(row) >= 3, f))
print(result)
# => True
# test to see if any line is more than 10 characters
with open('car-brands.txt') as f:
result = any(map(lambda row: len(row... | with open('car-brands.txt') as f:
result = all(map(lambda row: len(row) >= 3, f))
print(result)
with open('car-brands.txt') as f:
result = any(map(lambda row: len(row) > 10, f))
print(result)
with open('car-brands.txt') as f:
result = any(map(lambda row: len(row) > 13, f))
print(result)
with open('car-brand... |
# from log_utils.remote_logs import (
# post_output_log, post_build_complete,
# post_build_error, post_build_timeout)
class TestPostOutputLog():
def test_post_output_log(self):
pass
class TestPostBuildComplete():
def test_post_build_complete(self):
pass
class TestPostBuildError():
... | class Testpostoutputlog:
def test_post_output_log(self):
pass
class Testpostbuildcomplete:
def test_post_build_complete(self):
pass
class Testpostbuilderror:
def test_post_build_error(self):
pass
class Testpostbuildtimeout:
def test_post_build_timeout(self):
pass |
"""
A simple stock analyzer that collects data from 3 stock-listed company files
(NASDAQ, NYSE, and AMEX), and parses it into a single delimited file where
a user can search company data from all 3 file sources.
Author: Oscar Lopez
"""
def clean_data(data):
"""
Removes any trailing new lines, replaces '"' wi... | """
A simple stock analyzer that collects data from 3 stock-listed company files
(NASDAQ, NYSE, and AMEX), and parses it into a single delimited file where
a user can search company data from all 3 file sources.
Author: Oscar Lopez
"""
def clean_data(data):
"""
Removes any trailing new lines, replaces '"' wit... |
# Small Pizza: $15
# Medium Pizza: $20
# Large Pizza: $25
# Pepperoni for Small Pizza: +$2
# Pepperoni for Medium or Large Pizza: +$3
# Extra cheese for any size pizza: + $1
print("Welcome to Python Pizza Deliveries!")
size = input("What size pizza do you want? S, M, or L ")
add_pepperoni = input("Do you want pepperon... | print('Welcome to Python Pizza Deliveries!')
size = input('What size pizza do you want? S, M, or L ')
add_pepperoni = input('Do you want pepperoni? Y or N ')
extra_cheese = input('Do you want extra cheese? Y or N ')
bill = 0
if size == 'S':
bill += 15
elif size == 'M':
bill += 20
elif size == 'L':
bill += 2... |
#
# PySNMP MIB module FMX1830 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FMX1830
# Produced by pysmi-0.3.4 at Mon Apr 29 19:00:22 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)... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint, constraints_union) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.