content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def encrypt(text,s):
# Cipher(n) = De-cipher(26-n)
s=s
text =text.replace(" ","")
result="" #empty string
for i in range(len(text)):
char=text[i]
if(char.isupper()): #if the text[i] is in upper case
result=result+chr((ord(char)+s-65)%26+65)
else... | def encrypt(text, s):
s = s
text = text.replace(' ', '')
result = ''
for i in range(len(text)):
char = text[i]
if char.isupper():
result = result + chr((ord(char) + s - 65) % 26 + 65)
else:
result = result + chr((ord(char) + s - 97) % 26 + 97)
return r... |
class Contact:
def __init__(self, first_name=None, last_name=None, id=None, all_phones_from_home_page=None,
all_emails_from_home_page=None, address=None, email=None, email2=None, email3=None,
home_phone=None, mobile_phone=None, work_phone=None, secondary_phone=None):
sel... | class Contact:
def __init__(self, first_name=None, last_name=None, id=None, all_phones_from_home_page=None, all_emails_from_home_page=None, address=None, email=None, email2=None, email3=None, home_phone=None, mobile_phone=None, work_phone=None, secondary_phone=None):
self.first_name = first_name
se... |
tags = db.Table('tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
db.Column('page_id', db.Integer, db.ForeignKey('page.id'), primary_key=True)
)
class Page(db.Model):
id = db.Column(db.Integer, primary_key=True)
tags = db.relationship('Tag', secondary=tags, lazy='sub... | tags = db.Table('tags', db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True), db.Column('page_id', db.Integer, db.ForeignKey('page.id'), primary_key=True))
class Page(db.Model):
id = db.Column(db.Integer, primary_key=True)
tags = db.relationship('Tag', secondary=tags, lazy='subquery', bac... |
# -*- mode:python; coding:utf-8 -*-
# Copyright (c) 2020 IBM Corp. All rights reserved.
#
# 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
#
#... | """Core constants module containing all constants."""
package_oscal = 'trestle.oscal'
trestle_config_dir = '.trestle'
trestle_dist_dir = 'dist'
trestle_config_file = 'config.ini'
trestle_keep_file = '.keep'
'Map of plural form of a model type to the oscal module that contains the classes related to it.'
model_type_to_m... |
# import pytest
# import calculator_cha2ds2 as cal
# import validation_cha2ds2 as val
# import fetch_data_cha2ds2 as fd
class TestCalculator:
def test_calculate(self):
assert True
class TestFetchData:
def test_fetch_data(self):
assert True
def test_create_connection(self):
asser... | class Testcalculator:
def test_calculate(self):
assert True
class Testfetchdata:
def test_fetch_data(self):
assert True
def test_create_connection(self):
assert True
def test_query_data(self):
assert True
def test_clean_data(self):
assert True
class Tes... |
allPoints = []
epsilon = 0
def setup():
global rdp
size(400, 400)
for x in range(width):
xval = map(x, 0, width, 0, 5);
yval = exp(-xval) * cos(TWO_PI*xval);
y = map(yval, -1, 1, height, 0);
allPoints.append(PVector(x, y));
def draw():
global epsilon
bac... | all_points = []
epsilon = 0
def setup():
global rdp
size(400, 400)
for x in range(width):
xval = map(x, 0, width, 0, 5)
yval = exp(-xval) * cos(TWO_PI * xval)
y = map(yval, -1, 1, height, 0)
allPoints.append(p_vector(x, y))
def draw():
global epsilon
background(51)
... |
#
# PySNMP MIB module HP-ICF-BRIDGE (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-ICF-BRIDGE
# Produced by pysmi-0.3.4 at Mon Apr 29 19:20:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) ... |
rows = int(input("Enter number of rows: "))
k = 0
count=0
count1=0
for i in range(1, rows+1):
for space in range(1, (rows-i)+1):
print(" ", end="")
count+=1
while k!=((2*i)-1):
if count<=rows-1:
print(i+k, end=" ")
count+=1
else:
... | rows = int(input('Enter number of rows: '))
k = 0
count = 0
count1 = 0
for i in range(1, rows + 1):
for space in range(1, rows - i + 1):
print(' ', end='')
count += 1
while k != 2 * i - 1:
if count <= rows - 1:
print(i + k, end=' ')
count += 1
else:
... |
#!/usr/bin/env python
#
# Copyright (C) 2017 ShadowMan
#
class MaxSubSequenceSum(object):
def __init__(self, sequence: list):
self._sequence = sequence
self._sum = sequence[0]
self._left_index = 0
self._right_index = 0
def brute_force(self):
for start_i... | class Maxsubsequencesum(object):
def __init__(self, sequence: list):
self._sequence = sequence
self._sum = sequence[0]
self._left_index = 0
self._right_index = 0
def brute_force(self):
for (start_i, start_v) in enumerate(self._sequence):
for end_i in range(s... |
def factorial(num):
sum = 1
for i in range(1,num+1):
sum=sum*i
print(sum)
num = int(input("enter the number"))
factorial(num)
| def factorial(num):
sum = 1
for i in range(1, num + 1):
sum = sum * i
print(sum)
num = int(input('enter the number'))
factorial(num) |
class Solution:
def filterRestaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
res = []
for restaurant in restaurants:
i, r, v, p, d = restaurant
if veganFriendly == 1:
if v == 1 and p <= maxPrice a... | class Solution:
def filter_restaurants(self, restaurants: List[List[int]], veganFriendly: int, maxPrice: int, maxDistance: int) -> List[int]:
res = []
for restaurant in restaurants:
(i, r, v, p, d) = restaurant
if veganFriendly == 1:
if v == 1 and p <= maxPri... |
if __name__ == '__main__':
zi = int(input('Enter a number:\n'))
n1 = 1
c9 = 1
m9 = 9
sum = 9
while n1 != 0:
if sum % zi == 0:
n1 = 0
else:
m9 *= 10
sum += m9
c9 += 1
print('%d \'9\' could to be divisible by %d' % (c9, zi))
r ... | if __name__ == '__main__':
zi = int(input('Enter a number:\n'))
n1 = 1
c9 = 1
m9 = 9
sum = 9
while n1 != 0:
if sum % zi == 0:
n1 = 0
else:
m9 *= 10
sum += m9
c9 += 1
print("%d '9' could to be divisible by %d" % (c9, zi))
r =... |
# A. donuts
def donuts(count):
if count < 10:
st="Number of donuts: " + str(count)
else:
st="Number of donuts: many"
return st
# B. both_ends
def both_ends(s):
if len(s) < 2:
st=""
else:
st=s[0]+s[1]+s[-2]+s[-1]
return st
# C. fix_start
def fix_start(s):
i=... | def donuts(count):
if count < 10:
st = 'Number of donuts: ' + str(count)
else:
st = 'Number of donuts: many'
return st
def both_ends(s):
if len(s) < 2:
st = ''
else:
st = s[0] + s[1] + s[-2] + s[-1]
return st
def fix_start(s):
i = 1
st = s[0] + s.replace... |
def FreqToArfcn(band, tech, freq):
LTE_arfcn_table = {
'Band1':{'FDL_low':2110, 'NOffs-DL':0, 'FUL_low': 1920, 'NOffs-UL':18000, 'spacing': 190},
'Band2':{'FDL_low':2110, 'NOffs-DL':0, 'FUL_low': 1920, 'NOffs-UL':18000, 'spacing': 80},
'Band3':{'FDL_low':2110, 'NOffs-DL':0, 'FUL_low': 1920,... | def freq_to_arfcn(band, tech, freq):
lte_arfcn_table = {'Band1': {'FDL_low': 2110, 'NOffs-DL': 0, 'FUL_low': 1920, 'NOffs-UL': 18000, 'spacing': 190}, 'Band2': {'FDL_low': 2110, 'NOffs-DL': 0, 'FUL_low': 1920, 'NOffs-UL': 18000, 'spacing': 80}, 'Band3': {'FDL_low': 2110, 'NOffs-DL': 0, 'FUL_low': 1920, 'NOffs-UL': ... |
# Function chunks sourced from
# https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks
def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
def portfolio_input():
global port... | def chunks(lst, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(lst), n):
yield lst[i:i + n]
def portfolio_input():
global portfolio_size
portfolio_size = input('Enter the value of your portfolio:')
try:
val = float(portfolio_size)
except ValueError:
... |
def rawify_url(url):
if url.startswith("https://github.com"):
urlparts = url.replace("https://github.com", "", 1).strip('/').split('/') + [None] * 5
ownername, reponame, _, refvalue, *filename_parts = urlparts
filename = '/'.join([p for p in filename_parts if p is not None])
assert o... | def rawify_url(url):
if url.startswith('https://github.com'):
urlparts = url.replace('https://github.com', '', 1).strip('/').split('/') + [None] * 5
(ownername, reponame, _, refvalue, *filename_parts) = urlparts
filename = '/'.join([p for p in filename_parts if p is not None])
assert... |
vertical_tile_number = 14
tile_size = 16
screen_height = vertical_tile_number*tile_size *2
screen_width = 800 | vertical_tile_number = 14
tile_size = 16
screen_height = vertical_tile_number * tile_size * 2
screen_width = 800 |
# -*- coding: ascii -*-
u"""
:Copyright:
Copyright 2006 - 2017
Andr\xe9 Malo or his licensors, as applicable
:License:
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.... | u"""
:Copyright:
Copyright 2006 - 2017
André Malo or his licensors, as applicable
:License:
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
... |
def test_pythagorean_triplet(a, b, c):
return a**2 + b**2 - c**2 == 0
for a in range(1, 1000):
for b in range(1, 1000):
if test_pythagorean_triplet(a, b, 1000-(a+b)):
print("Product of a*b*c:", a*b*(1000-a-b))
| def test_pythagorean_triplet(a, b, c):
return a ** 2 + b ** 2 - c ** 2 == 0
for a in range(1, 1000):
for b in range(1, 1000):
if test_pythagorean_triplet(a, b, 1000 - (a + b)):
print('Product of a*b*c:', a * b * (1000 - a - b)) |
def cavityMap(grid):
m, n = len(grid[0]), len(grid)
if n < 3 or m < 3:
return grid
for i in range(1, m-1):
for j in range(1, n-1):
adjacent = [grid[i-1][j], grid[i+1][j],
grid[i][j+1], grid[i][j-1]]
if "X" in adjacent:
continue... | def cavity_map(grid):
(m, n) = (len(grid[0]), len(grid))
if n < 3 or m < 3:
return grid
for i in range(1, m - 1):
for j in range(1, n - 1):
adjacent = [grid[i - 1][j], grid[i + 1][j], grid[i][j + 1], grid[i][j - 1]]
if 'X' in adjacent:
continue
... |
"""
Custom Exception module.
This module contains custom exceptions used throughout the wappsto module.
"""
class DeviceNotFoundException(Exception):
"""
Exception to signify Device not being found.
This custom Exception extends the Exception class and implements no
custom methods.
Attributes:
... | """
Custom Exception module.
This module contains custom exceptions used throughout the wappsto module.
"""
class Devicenotfoundexception(Exception):
"""
Exception to signify Device not being found.
This custom Exception extends the Exception class and implements no
custom methods.
Attributes:
... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
new_head, ... | class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def remove_elements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
(new_head, prev, curr) = (None, None, head)
... |
for row in range(7):
for col in range(4):
if col==3 or row==3 and col in {0,1,2} or row in {0,1,2} and col<1:
print('*',end=' ')
else:
print(' ',end=' ')
print()
### Method-4
for i in range(6):
for j in range(6):
if j==3 or i+j==3 or i==3:
print('*',end=... | for row in range(7):
for col in range(4):
if col == 3 or (row == 3 and col in {0, 1, 2}) or (row in {0, 1, 2} and col < 1):
print('*', end=' ')
else:
print(' ', end=' ')
print()
for i in range(6):
for j in range(6):
if j == 3 or i + j == 3 or i == 3:
... |
try:
type('abc', None, None)
except TypeError:
print(True)
else:
print(False)
try:
type('abc', (), None)
except TypeError:
print(True)
else:
print(False)
try:
type('abc', (1,), {})
except TypeError:
print(True)
else:
print(False)
| try:
type('abc', None, None)
except TypeError:
print(True)
else:
print(False)
try:
type('abc', (), None)
except TypeError:
print(True)
else:
print(False)
try:
type('abc', (1,), {})
except TypeError:
print(True)
else:
print(False) |
def mergeSort(myList):
if len(myList) > 1:
mid = len(myList) // 2
left = myList[:mid]
right = myList[mid:]
mergeSort(left)
mergeSort(right)
i,j,k = 0,0,0
while i < len(left) and j < len(right):
if left[i] < right[j]:
... | def merge_sort(myList):
if len(myList) > 1:
mid = len(myList) // 2
left = myList[:mid]
right = myList[mid:]
merge_sort(left)
merge_sort(right)
(i, j, k) = (0, 0, 0)
while i < len(left) and j < len(right):
if left[i] < right[j]:
myLi... |
#pylint: disable=unnecessary-pass
class Error(Exception):
"""Base class for exceptions in this module."""
class StatusCodeNotEqualException(Error):
"""Raises if status_code of url is not equal to 200"""
pass
class DriverVersionInvalidException(Error):
"""Raises if current driver version is not equal t... | class Error(Exception):
"""Base class for exceptions in this module."""
class Statuscodenotequalexception(Error):
"""Raises if status_code of url is not equal to 200"""
pass
class Driverversioninvalidexception(Error):
"""Raises if current driver version is not equal to its latest version"""
pass
... |
# Dictionary labels
txtTitle = "Who\'s talking"
txtBot = "Bot name"
txtAuth= "OAUTH token"
txtChannel = "Channel name"
txtNotConnd = "Not Connected"
txtListChat = "\nList of chatters"
txtIgnore = "Ignore"
txtConnd = "Connected"
txtStart = "Start"
txtStop = "Stop"
txtClear = "Clear"
txtConnect = "Connect"
txtDisconnect ... | txt_title = "Who's talking"
txt_bot = 'Bot name'
txt_auth = 'OAUTH token'
txt_channel = 'Channel name'
txt_not_connd = 'Not Connected'
txt_list_chat = '\nList of chatters'
txt_ignore = 'Ignore'
txt_connd = 'Connected'
txt_start = 'Start'
txt_stop = 'Stop'
txt_clear = 'Clear'
txt_connect = 'Connect'
txt_disconnect = 'Di... |
class Solution:
def largestAltitude(self, gain: List[int]) -> int:
altitude = 0; maxAltitude = 0
for g in gain:
altitude += g
maxAltitude = max(maxAltitude, altitude)
return maxAltitude | class Solution:
def largest_altitude(self, gain: List[int]) -> int:
altitude = 0
max_altitude = 0
for g in gain:
altitude += g
max_altitude = max(maxAltitude, altitude)
return maxAltitude |
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
},
'targets': [
{
'target_name': 'extensions_common',
'type': 'static_library',
'depende... | {'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'extensions_common', 'type': 'static_library', 'dependencies': ['../chrome/chrome_resources.gyp:chrome_resources', '../components/components.gyp:url_matcher', '../content/content.gyp:content_common', '../crypto/crypto.gyp:crypto', '../ipc/ipc.gyp:ipc', '..... |
def write(query):
query_list = filter(None, query.decode("utf-8").split('\r\n'))
for q in query_list:
print(q)
return str()
| def write(query):
query_list = filter(None, query.decode('utf-8').split('\r\n'))
for q in query_list:
print(q)
return str() |
# -*- coding: utf-8 -*-
description = 'GALAXI motors'
group = 'optional'
tango_base = 'tango://phys.galaxi.kfa-juelich.de:10000/galaxi/'
s7_motor = tango_base + 's7_motor/'
devices = dict(
detz = device('nicos.devices.entangle.MotorAxis',
description = 'Detector Z axis',
tangodevice = s7_motor +... | description = 'GALAXI motors'
group = 'optional'
tango_base = 'tango://phys.galaxi.kfa-juelich.de:10000/galaxi/'
s7_motor = tango_base + 's7_motor/'
devices = dict(detz=device('nicos.devices.entangle.MotorAxis', description='Detector Z axis', tangodevice=s7_motor + 'detz', precision=0.01), detx=device('nicos.devices.en... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 28 14:43:21 2018
@author: USER
"""
# global control atomic form factor
global_atomic_form_factor = 'factor' | """
Created on Tue Aug 28 14:43:21 2018
@author: USER
"""
global_atomic_form_factor = 'factor' |
class Solution:
def majorityElement(self, nums: List[int]) -> int:
a=int(len(nums)/2)
b=list(set(nums))
for x in b:
if nums.count(x)>a:
return x
| class Solution:
def majority_element(self, nums: List[int]) -> int:
a = int(len(nums) / 2)
b = list(set(nums))
for x in b:
if nums.count(x) > a:
return x |
class TimeOutSettings(object):
"""Manages timeout settings for different work states:
- pending : work has not yet started and is waiting for resources
- starting : resources have been allocated and the work is being launched
- progress : work is active and computing"""
def __init__(sel... | class Timeoutsettings(object):
"""Manages timeout settings for different work states:
- pending : work has not yet started and is waiting for resources
- starting : resources have been allocated and the work is being launched
- progress : work is active and computing"""
def __init__(sel... |
DEPOSIT_TYPE = 'deposit'
WITHDRAW_TYPE = 'withdraw'
TRANSFER_TYPE = 'transfer'
S3_SERVICE = 's3'
AWS_REGION = 'us-east-1'
| deposit_type = 'deposit'
withdraw_type = 'withdraw'
transfer_type = 'transfer'
s3_service = 's3'
aws_region = 'us-east-1' |
# Copyright 2017 Istio Authors. All Rights Reserved.
#
# 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... | istio_api_sha = '93848bb1c495ff6ebc1a938e2e0a403d52d345c1'
def go_istio_api_repositories(use_local=False):
istio_api_build_file = '\n# build protos from istio.io/api repo\n\npackage(default_visibility = ["//visibility:public"])\n\nload("@io_bazel_rules_go//go:def.bzl", "go_prefix", "go_library")\n\ngo_prefix("isti... |
# Time: O(n) | Space: O(1)
def validateSubsequence(array, sequence):
seqIdx = 0
arrIdx = 0
while arrIdx < len(array) and seqIdx < len(sequence):
if array[arrIdx] == sequence[seqIdx]:
seqIdx += 1
arrIdx += 1
return seqIdx == len(sequence)
# Time: O(n) | Space: O(1)
def vali... | def validate_subsequence(array, sequence):
seq_idx = 0
arr_idx = 0
while arrIdx < len(array) and seqIdx < len(sequence):
if array[arrIdx] == sequence[seqIdx]:
seq_idx += 1
arr_idx += 1
return seqIdx == len(sequence)
def validate_subsequence2(array, sequence):
seq_idx = 0... |
# 1.1 Is Unique:
# Implement an algorithm to determine if a string has all unique characters.
# What if you cannot use additional data structures?
# O(n)
# Assuming ASCII - American Standard Code for Information Interchange
def isUniqueChars(string):
if len(string) > 128:
return False
char_set = [Fal... | def is_unique_chars(string):
if len(string) > 128:
return False
char_set = [False for _ in range(128)]
for char in string:
val = ord(char)
if char_set[val]:
return False
char_set[val] = True
return True
def in_unique(string):
checker = 0
for char in s... |
#
# PySNMP MIB module Sentry3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Sentry3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:07:04 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, 0... | (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_intersection, constraints_union, value_size_constraint) ... |
class Solution:
def minPathSum(self, grid: List[List[int]]) -> int:
dp=[[0 for _ in range(len(grid[0]))] for _ in range(len(grid))]
for row in range(len(grid)):
for col in range(len(grid[0])):
dp[row][col]=grid[row][col]
if row==0 and col==0:
... | class Solution:
def min_path_sum(self, grid: List[List[int]]) -> int:
dp = [[0 for _ in range(len(grid[0]))] for _ in range(len(grid))]
for row in range(len(grid)):
for col in range(len(grid[0])):
dp[row][col] = grid[row][col]
if row == 0 and col == 0:
... |
class Stack:
def __init__(self):
self._elems = []
def isEmpty(self):
return self._elems == []
def top(self):
if self._elems == []:
raise Exception('Stack is empty when using top()!')
else:
return self._elems[-1]
def push(self, elem):
self... | class Stack:
def __init__(self):
self._elems = []
def is_empty(self):
return self._elems == []
def top(self):
if self._elems == []:
raise exception('Stack is empty when using top()!')
else:
return self._elems[-1]
def push(self, elem):
s... |
a = int(input())
if a < 10 :
print("small")
| a = int(input())
if a < 10:
print('small') |
#!/usr/bin/env python3
n = int(input())
i = 0
while i < n:
print(n - i)
i = i + 1
| n = int(input())
i = 0
while i < n:
print(n - i)
i = i + 1 |
"""
Converter between Unix and WIndows line endings.
"""
class EOLFixer:
"""
Converter between Unix and WIndows line endings.
"""
CRLF = "\r\n"
LF = "\n"
@classmethod
def is_crlf(cls, text: str) -> bool:
"""
Check whether text has `\r\n` characters.
Arguments:
... | """
Converter between Unix and WIndows line endings.
"""
class Eolfixer:
"""
Converter between Unix and WIndows line endings.
"""
crlf = '\r\n'
lf = '\n'
@classmethod
def is_crlf(cls, text: str) -> bool:
"""
Check whether text has `\r
` characters.
Arguments:
... |
class Solution:
def canThreePartsEqualSum(self, arr: List[int]) -> bool:
total = sum(arr)
if total % 3 != 0:
return False
avg, count, currentSum = total // 3, 0, 0
for i in arr:
currentSum += i
if currentSum == avg:
count += 1
... | class Solution:
def can_three_parts_equal_sum(self, arr: List[int]) -> bool:
total = sum(arr)
if total % 3 != 0:
return False
(avg, count, current_sum) = (total // 3, 0, 0)
for i in arr:
current_sum += i
if currentSum == avg:
count... |
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__()
return cls._instances[cls]
class ResourceManagerExample(metaclass=SingletonMeta):
def __init__(self, resource=100):
se... | class Singletonmeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__()
return cls._instances[cls]
class Resourcemanagerexample(metaclass=SingletonMeta):
def __init__(self, resource=100):
sel... |
"""
Tool for Multi-Ancestor Hypergraphs
Copyright: (c) 2010-2021 Sahana Software Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including ... | """
Tool for Multi-Ancestor Hypergraphs
Copyright: (c) 2010-2021 Sahana Software Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including ... |
class ListNode:
def __init__(self, val, next, *args, **kwargs):
self.val = val
self.next = None
# return super().__init__(*args, **kwargs)
def reverse(self, head):
prev = None
while head:
temp = head.next
h... | class Listnode:
def __init__(self, val, next, *args, **kwargs):
self.val = val
self.next = None
def reverse(self, head):
prev = None
while head:
temp = head.next
head.next = prev
prev = head
head = temp... |
"""Mixin for Metadata.
Adds methods ``add_metadata()``, ``extend_metadata()`` and
``fetch_metadata_as_attrs()`` to the class.
Metadata will be extracted into Sink. So created feature datasets
contain metadata for e.g. features and sources.
"""
class MetadataMixin:
"""MetadataMixin class
Adding metadata fun... | """Mixin for Metadata.
Adds methods ``add_metadata()``, ``extend_metadata()`` and
``fetch_metadata_as_attrs()`` to the class.
Metadata will be extracted into Sink. So created feature datasets
contain metadata for e.g. features and sources.
"""
class Metadatamixin:
"""MetadataMixin class
Adding metadata func... |
"""
= Features wanted =
* When not moving it can take only update parts of the screen.
* update(dirty_rects) can be used to speed up drawing.
* by only updating areas which are dirty.
* if the map is not moving we can make it lots speedier.
* Offscreen buffer. Blit all smaller tiles to an offscreen buffer th... | """
= Features wanted =
* When not moving it can take only update parts of the screen.
* update(dirty_rects) can be used to speed up drawing.
* by only updating areas which are dirty.
* if the map is not moving we can make it lots speedier.
* Offscreen buffer. Blit all smaller tiles to an offscreen buffer th... |
'''All of the below settings apply only within the level that this config file
is situated. However, some of these options can also be applied at a
project-level within settings.py (see the docs for info on which options
transfer). Note that any inconsistencies are resolved in favour of the more
'local' settings, unle... | """All of the below settings apply only within the level that this config file
is situated. However, some of these options can also be applied at a
project-level within settings.py (see the docs for info on which options
transfer). Note that any inconsistencies are resolved in favour of the more
'local' settings, unle... |
class dotEnumerator_t(object):
# no doc
AdditionalId=None
aFilterName=None
aObjects=None
aObjectTypes=None
ClientId=None
Filter=None
MaxPoint=None
MinPoint=None
ModificationStamp=None
MoreObjectsLeft=None
nObjects=None
nObjectToStart=None
ReturnAlsoIfObjectIsCreatedAndDeletedAfterEvent=None
SubFilter=Non... | class Dotenumerator_T(object):
additional_id = None
a_filter_name = None
a_objects = None
a_object_types = None
client_id = None
filter = None
max_point = None
min_point = None
modification_stamp = None
more_objects_left = None
n_objects = None
n_object_to_start = None
... |
def pattern(n):
k = 2 * n - 2
for i in range(0, n-1):
for j in range(0, k):
print(end=" ")
k = k - 2
for j in range(0, i + 1):
print("* ", end="")
print(" ")
k = -1
for i in range(n-1,-1,-1):
for j in range(k,-1,-1):
print(end="... | def pattern(n):
k = 2 * n - 2
for i in range(0, n - 1):
for j in range(0, k):
print(end=' ')
k = k - 2
for j in range(0, i + 1):
print('* ', end='')
print(' ')
k = -1
for i in range(n - 1, -1, -1):
for j in range(k, -1, -1):
pri... |
class Solution:
def __init__(self):
self.f = defaultdict(int)
def findFrequentTreeSum(self, root: TreeNode) -> List[int]:
self._post_order(root)
res = []
maxf = 0
for k, v in self.f.items():
if v > maxf:
maxf = v
res =... | class Solution:
def __init__(self):
self.f = defaultdict(int)
def find_frequent_tree_sum(self, root: TreeNode) -> List[int]:
self._post_order(root)
res = []
maxf = 0
for (k, v) in self.f.items():
if v > maxf:
maxf = v
res = [k... |
# -*- coding:utf-8 -*-
class Level:
id = ''
word_id = ''
name = ''
| class Level:
id = ''
word_id = ''
name = '' |
class User:
'''
Class that generates new instances of users
'''
users = []
def __init__(self, login_username, password):
'''
___init___ method that helps us define properties for our objects.
Args:
name: New user name
password: New user password
'''
self.login_username = lo... | class User:
"""
Class that generates new instances of users
"""
users = []
def __init__(self, login_username, password):
"""
___init___ method that helps us define properties for our objects.
Args:
name: New user name
password: New user password
"""
self.login_u... |
def __main__( deadlinePlugin ):
job = deadlinePlugin.GetJob()
cpus = list(deadlinePlugin.CpuAffinity())
cpus_linux = [str(x) for x in cpus]
cpus_linux = ','.join(cpus_linux)
# Edwin hex math for building the CPU affinity
cpus_windows = 0
for cpu in cpus:
cpus_windows |= 1 << int(... | def __main__(deadlinePlugin):
job = deadlinePlugin.GetJob()
cpus = list(deadlinePlugin.CpuAffinity())
cpus_linux = [str(x) for x in cpus]
cpus_linux = ','.join(cpus_linux)
cpus_windows = 0
for cpu in cpus:
cpus_windows |= 1 << int(cpu)
cpus_windows = hex(cpus_windows)[2:].upper()
... |
#
# @lc app=leetcode id=448 lang=python3
#
# [448] Find All Numbers Disappeared in an Array
#
# @lc code=start
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
list = [0] * len(nums)
result = []
for n in nums:
list[n-1] = list[n-1] + 1
... | class Solution:
def find_disappeared_numbers(self, nums: List[int]) -> List[int]:
list = [0] * len(nums)
result = []
for n in nums:
list[n - 1] = list[n - 1] + 1
for (i, c) in enumerate(list):
if c == 0:
result.append(i + 1)
return res... |
#!/usr/bin/env python3
"""
Common errors defined here:
"""
class WrongFormatError(BaseException):
"""Raised when the input file is not in the correct format"""
def __init__(self, *args, **kwargs):
default_message = (
"The file you passed is not supported! Only .txt files are accepted."
... | """
Common errors defined here:
"""
class Wrongformaterror(BaseException):
"""Raised when the input file is not in the correct format"""
def __init__(self, *args, **kwargs):
default_message = 'The file you passed is not supported! Only .txt files are accepted.'
if args:
super().__i... |
'''
Created on Feb 5, 2017
@author: safdar
'''
# from operations.vehicledetection.entities import Vehicle
# class VehicleManager(object):
# def __init__(self, lookback_frames, clusterer):
# self.__lookback_frames__ = lookback_frames
# self.__vehicles__ = []
# self.__clusterer__ = clusterer
... | """
Created on Feb 5, 2017
@author: safdar
""" |
with open("Input.txt") as f:
lines = f.readlines()
# remove whitespace characters like `\n` at the end of each line
lines = [x.strip() for x in lines]
num_lines = len(lines)
width = len(lines[0])
print(f"{num_lines} lines of width {width}")
diffs = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
hits = []
for diff in d... | with open('Input.txt') as f:
lines = f.readlines()
lines = [x.strip() for x in lines]
num_lines = len(lines)
width = len(lines[0])
print(f'{num_lines} lines of width {width}')
diffs = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]
hits = []
for diff in diffs:
hit_count = 0
(x, y) = (0, 0)
while y < num_lines ... |
def pairwise_slow(iterable):
it = iter(iterable)
while True:
yield it.next(), it.next()
| def pairwise_slow(iterable):
it = iter(iterable)
while True:
yield (it.next(), it.next()) |
#
# PySNMP MIB module ASCEND-MIBATMQOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBATMQOS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:26:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | (configuration,) = mibBuilder.importSymbols('ASCEND-MIB', 'configuration')
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_const... |
class Screen(object):
"""docstring for Screen"""
@property
def width(self):
return self._width
@width.setter
def width(self,width):
if not isinstance(width,int):
raise ValueError('width must be an integer!')
elif width < 0:
raise ValueError('width must be positive number!')
else:
self._width = wid... | class Screen(object):
"""docstring for Screen"""
@property
def width(self):
return self._width
@width.setter
def width(self, width):
if not isinstance(width, int):
raise value_error('width must be an integer!')
elif width < 0:
raise value_error('widt... |
""" Advent of Code, 2020: Day 07, a """
with open(__file__[:-5] + "_input") as f:
inputs = [line.strip() for line in f]
bags = dict()
def count_bags(bag):
""" Recursively count bags """
if bag not in bags:
return 1
return 1 + sum(b[0] * count_bags(b[1]) for b in bags[bag])
def run():
"... | """ Advent of Code, 2020: Day 07, a """
with open(__file__[:-5] + '_input') as f:
inputs = [line.strip() for line in f]
bags = dict()
def count_bags(bag):
""" Recursively count bags """
if bag not in bags:
return 1
return 1 + sum((b[0] * count_bags(b[1]) for b in bags[bag]))
def run():
"""... |
#
# @lc app=leetcode id=464 lang=python3
#
# [464] Can I Win
#
# @lc code=start
class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int):
# first player must win
if maxChoosableInteger > desiredTotal:
return True
nums = [num for num in range(1, maxChoosable... | class Solution:
def can_i_win(self, maxChoosableInteger: int, desiredTotal: int):
if maxChoosableInteger > desiredTotal:
return True
nums = [num for num in range(1, maxChoosableInteger + 1)]
if sum(nums) < desiredTotal:
return False
self.seen = {}
ret... |
def top_level_function1() -> None:
return
class TopLevelClass1:
def __init__(self) -> None:
return
def instance_method1(self) -> None:
return
@classmethod
def class_method1(cls) -> None:
return
def instance_method2(self) -> None:
return
def top_level_func... | def top_level_function1() -> None:
return
class Toplevelclass1:
def __init__(self) -> None:
return
def instance_method1(self) -> None:
return
@classmethod
def class_method1(cls) -> None:
return
def instance_method2(self) -> None:
return
def top_level_functio... |
def zero_matrix(matrix):
rows = set()
cols = set()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)
for row in rows:
for i in range(len(matrix[row])):
matrix[row][i] = 0
... | def zero_matrix(matrix):
rows = set()
cols = set()
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == 0:
rows.add(i)
cols.add(j)
for row in rows:
for i in range(len(matrix[row])):
matrix[row][i] = 0
... |
class Order:
def __init__(self):
self.items = []
self.quantities = []
self.prices = []
self.status = "open"
def add_item(self, name, quantity, price):
self.items.append(name)
self.quantities.append(quantity)
self.prices.append(price)
def total_price... | class Order:
def __init__(self):
self.items = []
self.quantities = []
self.prices = []
self.status = 'open'
def add_item(self, name, quantity, price):
self.items.append(name)
self.quantities.append(quantity)
self.prices.append(price)
def total_price... |
class Guerra():
def __init__(self, numTerricolas=3, numMarcianos=3):
self.__terricolasNave = Nave(Guerreros.TERRICOLA, "Millenium Falcon", numTerricolas)
self.__marcianosNave = Nave(Guerreros.MARCIANO, "Wing X", numTerricolas)
def start_war(self):
numTerricolasInNave = self.__terricolasN... | class Guerra:
def __init__(self, numTerricolas=3, numMarcianos=3):
self.__terricolasNave = nave(Guerreros.TERRICOLA, 'Millenium Falcon', numTerricolas)
self.__marcianosNave = nave(Guerreros.MARCIANO, 'Wing X', numTerricolas)
def start_war(self):
num_terricolas_in_nave = self.__terricol... |
class EnvConstants:
EUREKA_SERVER = "EUREKA_SERVER"
APP_IP = "APP_IP"
FLUENTD_IP_PORT = "FLUENTD_IP_PORT"
HTTP_AUTH_USER = "HTTP_AUTH_USER"
HTTP_AUTH_PASSWORD = "HTTP_AUTH_PASSWORD"
TEMPLATES_DIR = "TEMPLATES_DIR"
VARS_DIR = "VARS_DIR"
TEMPLATE = "TEMPLATE"
VARIABLES = "VARIABLES"
... | class Envconstants:
eureka_server = 'EUREKA_SERVER'
app_ip = 'APP_IP'
fluentd_ip_port = 'FLUENTD_IP_PORT'
http_auth_user = 'HTTP_AUTH_USER'
http_auth_password = 'HTTP_AUTH_PASSWORD'
templates_dir = 'TEMPLATES_DIR'
vars_dir = 'VARS_DIR'
template = 'TEMPLATE'
variables = 'VARIABLES'
... |
def add(a,b):
return a+b
def subtraction(a,b):
return a-b
def multiply(a,b):
return a*b
def division(a,b):
return a/b
def modulas(a,b):
return a%b | def add(a, b):
return a + b
def subtraction(a, b):
return a - b
def multiply(a, b):
return a * b
def division(a, b):
return a / b
def modulas(a, b):
return a % b |
{
'targets': [
{
'target_name': 'mysys_ssl',
'type': 'static_library',
'standalone_static_library': 1,
'includes': [ '../config/config.gypi' ],
'cflags!': [ '-O3' ],
'cflags_cc!': [ '-O3' ],
'cflags_c!': [ '-O3' ],
'cflags+': [ '-O2', '-g' ],
'cflags_c+': [ '-... | {'targets': [{'target_name': 'mysys_ssl', 'type': 'static_library', 'standalone_static_library': 1, 'includes': ['../config/config.gypi'], 'cflags!': ['-O3'], 'cflags_cc!': ['-O3'], 'cflags_c!': ['-O3'], 'cflags+': ['-O2', '-g'], 'cflags_c+': ['-O2', '-g'], 'cflags_cc+': ['-O2'], 'sources': ['my_aes.cc', 'my_md5.cc', '... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
################################################################################
#
# Copyright (c) 2018, WeBank Inc. All Rights Reserved
#
################################################################################
# ====================================================... | class Variable(object):
def __init__(self, name, auth):
self.name = name
self.auth = auth
class Basetransfervariable(object):
def __init__(self, flowid=0):
self.flowid = flowid
self.define_transfer_variable()
def set_flowid(self, flowid):
self.flowid = flowid
... |
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
print(nums)
result =[]
for i in range(len(nums)):
if i> 0 and nums[i] == nums[i-1]:
continue
# print('4sum',nums[i],target- nums[i])
tmp... | class Solution:
def four_sum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
print(nums)
result = []
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
tmp = self.threeSum(i + 1, nums, target - nums[i]... |
class BufferedStream(Stream,IDisposable):
"""
Adds a buffering layer to read and write operations on another stream. This class cannot be inherited.
BufferedStream(stream: Stream)
BufferedStream(stream: Stream,bufferSize: int)
"""
def BeginRead(self,buffer,offset,count,callback,state):
""" BeginRea... | class Bufferedstream(Stream, IDisposable):
"""
Adds a buffering layer to read and write operations on another stream. This class cannot be inherited.
BufferedStream(stream: Stream)
BufferedStream(stream: Stream,bufferSize: int)
"""
def begin_read(self, buffer, offset, count, callback, state):
... |
'''
Recall from the video that a pivot table allows you to see all of your variables as a function of two other variables. In this exercise, you will use the .pivot_table() method to see how the users DataFrame entries appear when presented as functions of the 'weekday' and 'city' columns. That is, with the rows indexe... | """
Recall from the video that a pivot table allows you to see all of your variables as a function of two other variables. In this exercise, you will use the .pivot_table() method to see how the users DataFrame entries appear when presented as functions of the 'weekday' and 'city' columns. That is, with the rows indexe... |
"""Specify colors of an othello bpard."""
class ColorPallet():
def __init__(self):
self.COLOR_BLACK_DISK = "#000000"
self.COLOR_WHITE_DISK = "#FFFFFF"
self.COLOR_BOARD = "#009600"
self.COLOR_BOARD_EDGE = "#000000"
self.COLOR_BOARD_LINE = "#000000"
self.COLOR_PANEL... | """Specify colors of an othello bpard."""
class Colorpallet:
def __init__(self):
self.COLOR_BLACK_DISK = '#000000'
self.COLOR_WHITE_DISK = '#FFFFFF'
self.COLOR_BOARD = '#009600'
self.COLOR_BOARD_EDGE = '#000000'
self.COLOR_BOARD_LINE = '#000000'
self.COLOR_PANEL_PLA... |
def chemical_precipitation_costs(wastewater_flowrate_m3_per_hour, n, i):
wastewater_flowrate_gpd = wastewater_flowrate_m3_per_hour * 264.1721 * 24 # [gpd] There are 264 gallons per cubic meter and 24 hours per day
capital_costs = 7040000 + (35.0 * wastewater_flowrate_gpd) # [$]
o_and_m_costs = 230000 + (4.... | def chemical_precipitation_costs(wastewater_flowrate_m3_per_hour, n, i):
wastewater_flowrate_gpd = wastewater_flowrate_m3_per_hour * 264.1721 * 24
capital_costs = 7040000 + 35.0 * wastewater_flowrate_gpd
o_and_m_costs = 230000 + 4.05 * wastewater_flowrate_gpd
pv_of_o_and_m_costs = o_and_m_costs * ((1 + ... |
# Copyright 2018 The Bazel Authors. All rights reserved.
#
# 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 la... | """Package file which defines npm_bazel_typescript dependencies
"""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def rules_typescript_dev_dependencies():
"""
Fetch dependencies needed for local development.
These are in this file to keep version information in one place, and make t... |
class ORMError(Exception):
"""Base class for all ORM-related errors"""
class UniqueKeyViolation(ORMError):
"""Raised when trying to save an entity without a distinct column value"""
class InvalidOperation(ORMError):
"""
Raised when trying to delete or modify a column that
cannot be deleted or mo... | class Ormerror(Exception):
"""Base class for all ORM-related errors"""
class Uniquekeyviolation(ORMError):
"""Raised when trying to save an entity without a distinct column value"""
class Invalidoperation(ORMError):
"""
Raised when trying to delete or modify a column that
cannot be deleted or modi... |
def validBraces(string):
buffer = []
for i in string:
if i == '(' or i == '[' or i == '{':
buffer.append(i)
else:
try:
a = buffer.pop()
except IndexError:
return False
if i == ')' and a != '(':
return... | def valid_braces(string):
buffer = []
for i in string:
if i == '(' or i == '[' or i == '{':
buffer.append(i)
else:
try:
a = buffer.pop()
except IndexError:
return False
if i == ')' and a != '(':
retur... |
point_1 = Point(IN1, IN2)
point_2 = Point(IN3, IN4)
point_1.switch_point(1)
print("Point 1 right")
point_2.switch_point(1)
print("Point 2 right")
train = Locomotive(1)
track_enable(1)
print("Throttle 0, 70")
while GPIO.input(T6) == GPIO.HIGH:
train.throttle(0, 70)
train.stop()
print("train stop")
print("Thr... | point_1 = point(IN1, IN2)
point_2 = point(IN3, IN4)
point_1.switch_point(1)
print('Point 1 right')
point_2.switch_point(1)
print('Point 2 right')
train = locomotive(1)
track_enable(1)
print('Throttle 0, 70')
while GPIO.input(T6) == GPIO.HIGH:
train.throttle(0, 70)
train.stop()
print('train stop')
print('Throttle 1,... |
class Solution:
def findFrequentTreeSum(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
count = Counter()
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
sum = root.val + dfs(root.left) + dfs(root.right)
count[sum] += 1
... | class Solution:
def find_frequent_tree_sum(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
count = counter()
def dfs(root: Optional[TreeNode]) -> int:
if root is None:
return 0
sum = root.val + dfs(root.left) + df... |
#
# Dutch National Flag
# in-place
def dutch_flag_sort(balls):
r = -1 # red pointer
g = -1 # green pointer
i = 0 # current pointer
while (i < len(balls)):
if balls[i] == 'G':
g += 1
balls[i], balls[g] = balls[g], balls[i]
elif (balls[i] == "R"):
... | def dutch_flag_sort(balls):
r = -1
g = -1
i = 0
while i < len(balls):
if balls[i] == 'G':
g += 1
(balls[i], balls[g]) = (balls[g], balls[i])
elif balls[i] == 'R':
g += 1
(balls[i], balls[g]) = (balls[g], balls[i])
r += 1
... |
load("//packages/bazel:index.bzl", "protractor_web_test_suite")
load("//tools:defaults.bzl", "ts_library")
def example_test(name, srcs, server, data = [], **kwargs):
ts_library(
name = "%s_lib" % name,
testonly = True,
srcs = srcs,
tsconfig = "//modules/playground:tsconfig-e2e.json"... | load('//packages/bazel:index.bzl', 'protractor_web_test_suite')
load('//tools:defaults.bzl', 'ts_library')
def example_test(name, srcs, server, data=[], **kwargs):
ts_library(name='%s_lib' % name, testonly=True, srcs=srcs, tsconfig='//modules/playground:tsconfig-e2e.json', deps=['//modules/e2e_util', '//packages/p... |
class Collectionitem:
collectionitemcnt = 0
def __init__(self, colldict):
self.colldict = colldict
Collectionitem.collectionitemcnt+=1
def birthyearcreator1(self):
if ("birth_year" in self.colldict['creators'][0]):
byear = self.colldict['creators'][0]['birth_year']
else:
... | class Collectionitem:
collectionitemcnt = 0
def __init__(self, colldict):
self.colldict = colldict
Collectionitem.collectionitemcnt += 1
def birthyearcreator1(self):
if 'birth_year' in self.colldict['creators'][0]:
byear = self.colldict['creators'][0]['birth_year']
... |
# Python Object Oriented Programming by Joe Marini course example
# Using the __str__ and __repr__ magic methods
class Book:
def __init__(self, title, author, price):
super().__init__()
self.title = title
self.author = author
self.price = price
self._discount = 0.1
# T... | class Book:
def __init__(self, title, author, price):
super().__init__()
self.title = title
self.author = author
self.price = price
self._discount = 0.1
def __str__(self):
return f'{self.title} by {self.author}, costs {self.price}'
def __getattribute__(self... |
TAPIERROR_LOGIN = 10001
TAPIERROR_LOGIN_USER = 10002
TAPIERROR_LOGIN_DDA = 10003
TAPIERROR_LOGIN_LICENSE = 10004
TAPIERROR_LOGIN_MODULE = 10005
TAPIERROR_LOGIN_FORCE = 10006
TAPIERROR_LOGIN_STATE = 10007
TAPIERROR_LOGIN_PASS = 10008
TAPIERROR_LOGIN_RIGHT = 10009
TAPIERROR_LOGIN_COUNT = 10010
TAPIERROR_LOGIN_NOTIN_SERVE... | tapierror_login = 10001
tapierror_login_user = 10002
tapierror_login_dda = 10003
tapierror_login_license = 10004
tapierror_login_module = 10005
tapierror_login_force = 10006
tapierror_login_state = 10007
tapierror_login_pass = 10008
tapierror_login_right = 10009
tapierror_login_count = 10010
tapierror_login_notin_serve... |
def can_channel_synchronize(channel):
return channel.mirror_channel_url and (channel.mirror_mode == "mirror")
def can_channel_reindex(channel):
return True
| def can_channel_synchronize(channel):
return channel.mirror_channel_url and channel.mirror_mode == 'mirror'
def can_channel_reindex(channel):
return True |
# output from elife04953.xml
expected = [
{
"xlink_href": "elife04953f001",
"type": "graphic",
"parent_type": "fig",
"parent_ordinal": 1,
"parent_sibling_ordinal": 1,
"parent_component_doi": "10.7554/eLife.04953.003",
"position": 1,
"ordinal": 1,
}... | expected = [{'xlink_href': 'elife04953f001', 'type': 'graphic', 'parent_type': 'fig', 'parent_ordinal': 1, 'parent_sibling_ordinal': 1, 'parent_component_doi': '10.7554/eLife.04953.003', 'position': 1, 'ordinal': 1}, {'xlink_href': 'elife04953fs001', 'type': 'graphic', 'parent_type': 'fig', 'parent_ordinal': 2, 'parent... |
encoded = "cvpbPGS{abg_gbb_onq_bs_n_ceboyrz}"
decoded = "".join([chr(ord('a') + (ord(c.lower())-ord('a')+13)%26) if c.isalpha() else c for c in encoded])
print(decoded) | encoded = 'cvpbPGS{abg_gbb_onq_bs_n_ceboyrz}'
decoded = ''.join([chr(ord('a') + (ord(c.lower()) - ord('a') + 13) % 26) if c.isalpha() else c for c in encoded])
print(decoded) |
def main():
with open('input.txt') as f:
ids = f.read().splitlines()
ids.sort()
for i in range(len(ids) - 1):
cur = ids[i]
nex = ids[i + 1]
diff = 0
diff_idx = 0
for j in range(len(cur)):
if diff > 1:
break
if cur[... | def main():
with open('input.txt') as f:
ids = f.read().splitlines()
ids.sort()
for i in range(len(ids) - 1):
cur = ids[i]
nex = ids[i + 1]
diff = 0
diff_idx = 0
for j in range(len(cur)):
if diff > 1:
break
if cur[j]... |
Images=[(0,255,0,255,0,255 ,
255,0,255,0,255,0,
0,255,0,255,0,255 ,
255,0,255,0,255,0,
0,255,0,255,0,255 ,
255,0,255,0,255,0),
(255,255,255,0,0,0,
0,0,0,255,255,255,
255,255,255,0,0,0,
255,255,255,0,0,0,
0,0,0,255,255,255,
255,255,255,0,0,0,),
(255,255,255,255,255,255,
... | images = [(0, 255, 0, 255, 0, 255, 255, 0, 255, 0, 255, 0, 0, 255, 0, 255, 0, 255, 255, 0, 255, 0, 255, 0, 0, 255, 0, 255, 0, 255, 255, 0, 255, 0, 255, 0), (255, 255, 255, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 0, 0, 0), (255, 255, 255, 25... |
# while True:
# pass
# keyboard interrupt.
class MyEmptyClass:
pass
def initLog(*args):
pass
# pass statement is ignore.
| class Myemptyclass:
pass
def init_log(*args):
pass |
def counting_sort(array, area, index):
counting_array = [0] * area
sorted_array = [0] * len(array)
for j in range(len(array)):
counting_array[ord(array[j][index]) - ord("a")] += 1
for j in range(1, area):
counting_array[j] += counting_array[j - 1]
for j in range(len(array) - 1, -1, ... | def counting_sort(array, area, index):
counting_array = [0] * area
sorted_array = [0] * len(array)
for j in range(len(array)):
counting_array[ord(array[j][index]) - ord('a')] += 1
for j in range(1, area):
counting_array[j] += counting_array[j - 1]
for j in range(len(array) - 1, -1, -... |
def GCD(a,b):
if b==0:
return a
else:
return GCD(b,a%b)
print("Enter A")
a=int(input())
print("Enter B")
b=int(input())
print("GCD = "+str(GCD(a,b))) | def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
print('Enter A')
a = int(input())
print('Enter B')
b = int(input())
print('GCD = ' + str(gcd(a, b))) |
''' For Loop Break Statement
'''
frui | """ For Loop Break Statement
"""
frui |
n=int(input("Enter n -> "))
res=0
while(n > 0):
temp = n % 10
res = res * 10 + temp
n = n // 10
print(res) | n = int(input('Enter n -> '))
res = 0
while n > 0:
temp = n % 10
res = res * 10 + temp
n = n // 10
print(res) |
class TrainingConfig:
def __init__(self, trainingConfig):
self.downloadStackoverflowEnabled = trainingConfig.get("downloadStackoverflowEnabled", False)
self.includeStackoverflow = trainingConfig.get("includeStackoverflow", True)
self.stackoverflowTags = trainingConfig.get("stackoverflowTags", [])
self.stackove... | class Trainingconfig:
def __init__(self, trainingConfig):
self.downloadStackoverflowEnabled = trainingConfig.get('downloadStackoverflowEnabled', False)
self.includeStackoverflow = trainingConfig.get('includeStackoverflow', True)
self.stackoverflowTags = trainingConfig.get('stackoverflowTags... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.