content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def create_sketch_from_image(img_lct,sketch_lct,outname,ext,n_sketches):
# img_lct --> It's the location of the images
# sketch_lct --> It's the location of the generated sketch image
# outname --> The name of the file
# ext --> The extension of the file 256FaceNewData
# n_sketches -->The numbe... | def create_sketch_from_image(img_lct, sketch_lct, outname, ext, n_sketches):
for i in range(0, n_sketches - 1):
img_rgb = cv2.imread(img_lct + '256_' + str(i) + '.jpg')
img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
img_gray_inv = 255 - img_gray
img_blur = cv2.GaussianBlur(img_... |
#!/usr/bin python
"""
:author: Fix Me
:date: Now
:contact: me@me.org
:license: GPL, v3
:copyright: Copyright (C) 2017 Fixme
:summary: Simple script to open a file, then read and print its content.
Use of this software is governed by the GNU Public License, version 3.
This is free so... | """
:author: Fix Me
:date: Now
:contact: me@me.org
:license: GPL, v3
:copyright: Copyright (C) 2017 Fixme
:summary: Simple script to open a file, then read and print its content.
Use of this software is governed by the GNU Public License, version 3.
This is free software: you can re... |
class Edge(object):
"""
Representation of an edge in the graph database.
"""
def __init__(self, uri: str):
self.uri = uri
| class Edge(object):
"""
Representation of an edge in the graph database.
"""
def __init__(self, uri: str):
self.uri = uri |
# Please provide the API key for the account made on the website 2factor.in
SMS_GATEWAY_API_KEY = 'SMS_GATEWAY_API_KEY'
# Provide the 2factor urls for each type of sms
SMS_GATEWAY_URL = {
'otp': 'http://2factor.in/API/V1/{api_key}/SMS/',
'transactional': 'http://2factor.in/API/V1/{api_key}/ADDON_SERVICES/SEND... | sms_gateway_api_key = 'SMS_GATEWAY_API_KEY'
sms_gateway_url = {'otp': 'http://2factor.in/API/V1/{api_key}/SMS/', 'transactional': 'http://2factor.in/API/V1/{api_key}/ADDON_SERVICES/SEND/TSMS', 'promotional': 'http://2factor.in/API/V1/{api_key}/ADDON_SERVICES/SEND/PSMS'} |
class Plotter:
pass
class PyplotPlotter(Plotter):
pass | class Plotter:
pass
class Pyplotplotter(Plotter):
pass |
# -*- coding: utf-8 -*-
'''
Management of Zabbix host groups.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
'''
def __virtual__():
'''
Only make these states available if Zabbix module is available.
'''
return 'zabbix.hostgroup_create' in __salt__
def present(name):
'''
Ensures that the... | """
Management of Zabbix host groups.
:codeauthor: Jiri Kotlin <jiri.kotlin@ultimum.io>
"""
def __virtual__():
"""
Only make these states available if Zabbix module is available.
"""
return 'zabbix.hostgroup_create' in __salt__
def present(name):
"""
Ensures that the host group exists, eventu... |
"""
LeetCode Problem: 412. Fizz Buzz
Link: https://leetcode.com/problems/fizz-buzz/
Language: Python
Written by: Mostofa Adib Shakib
Time Compplexity: O(n)
Space Complexity: O(n)
"""
class Solution:
def fizzBuzz(self, n: int) -> List[str]:
ans = []
for i in range (1, n+1):
if ... | """
LeetCode Problem: 412. Fizz Buzz
Link: https://leetcode.com/problems/fizz-buzz/
Language: Python
Written by: Mostofa Adib Shakib
Time Compplexity: O(n)
Space Complexity: O(n)
"""
class Solution:
def fizz_buzz(self, n: int) -> List[str]:
ans = []
for i in range(1, n + 1):
if i % 15... |
class Solution:
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
hold, not_hold = float('-inf'), 0
for price in prices:
hold, not_hold = max(hold, not_hold - price), max(not_hold, hold + price - fee)
... | class Solution:
def max_profit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
(hold, not_hold) = (float('-inf'), 0)
for price in prices:
(hold, not_hold) = (max(hold, not_hold - price), max(not_hold, hold + price - ... |
n = int(input())
l = [*map(int,input().split())]
ans = 0
for i in range(n):
l[i] = min(l[i], 7)
if i % 2 == 0:
ans += l[i] - 2
else:
ans += l[i] - 3
print(ans)
| n = int(input())
l = [*map(int, input().split())]
ans = 0
for i in range(n):
l[i] = min(l[i], 7)
if i % 2 == 0:
ans += l[i] - 2
else:
ans += l[i] - 3
print(ans) |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class TestOutputStream(object):
def __init__(self):
self._output_data = []
@property
def output_data(self):
return ''.join(self._output_data)... | class Testoutputstream(object):
def __init__(self):
self._output_data = []
@property
def output_data(self):
return ''.join(self._output_data)
def write(self, data):
self._output_data.append(data)
def flush(self):
pass |
#!/usr/bin/env python3
"""Module Line up"""
def add_arrays(arr1, arr2):
"""Adds two arrays element-wise"""
lenArr1 = len(arr1)
lenArr2 = len(arr2)
if lenArr1 != lenArr2:
return None
ans = []
for i in range(lenArr1):
ans.append(arr1[i] + arr2[i])
return ans
| """Module Line up"""
def add_arrays(arr1, arr2):
"""Adds two arrays element-wise"""
len_arr1 = len(arr1)
len_arr2 = len(arr2)
if lenArr1 != lenArr2:
return None
ans = []
for i in range(lenArr1):
ans.append(arr1[i] + arr2[i])
return ans |
# projecteuler.net/problem=8
num = "73167176531330624919225119674426574742355349194934969835203127745063262395783180169848018694788518438586156078911294949545950173795833195285320880551112540698747158523863050715693290963295227443043557668966489504452445231617318564030987111217223831136222989342338030813533627661428... | num = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629... |
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices or not k:
return 0
dp = [[0, 0] for _ in range(k)]
for i in range(k):
dp[i][0] = -prices[0]
... | class Solution(object):
def max_profit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices or not k:
return 0
dp = [[0, 0] for _ in range(k)]
for i in range(k):
dp[i][0] = -prices[0]
... |
# Mailing Address
print("Shubhangi Singh")
print("College of Computer Science")
print("Computer Science Building")
print("294 Farm Ln Rm 104")
print("East Lansing MI 48824") | print('Shubhangi Singh')
print('College of Computer Science')
print('Computer Science Building')
print('294 Farm Ln Rm 104')
print('East Lansing MI 48824') |
a=int(input('valor para A:',))
b=int(input('valor para B:',))
soma=a+b
print('a soma eh:',soma)
| a = int(input('valor para A:'))
b = int(input('valor para B:'))
soma = a + b
print('a soma eh:', soma) |
def f():
return 42
100
| def f():
return 42
100 |
seed = 1234
def random():
global seed
seed = seed * 0xda942042e4dd58b5
value = seed >> 64
value = seed % 2**64
return value
for i in range(10):
print(random())
for i in range(10):
print(random()%3)
# D. H. Lehmer, Mathematical methods in large-scale computing units.
# Proceedings of a Se... | seed = 1234
def random():
global seed
seed = seed * 15750249268501108917
value = seed >> 64
value = seed % 2 ** 64
return value
for i in range(10):
print(random())
for i in range(10):
print(random() % 3) |
def checkguess(request) :
guess = request.GET.get('guess','')
return guess == '42';
| def checkguess(request):
guess = request.GET.get('guess', '')
return guess == '42' |
# Python3 implementation to convert a binary number
# to octal number
# function to create map between binary
# number and its equivalent octal
def createMap(bin_oct_map):
bin_oct_map["000"] = '0'
bin_oct_map["001"] = '1'
bin_oct_map["010"] = '2'
bin_oct_map["011"] = '3'
bin_oct_map["100"] = '4'
... | def create_map(bin_oct_map):
bin_oct_map['000'] = '0'
bin_oct_map['001'] = '1'
bin_oct_map['010'] = '2'
bin_oct_map['011'] = '3'
bin_oct_map['100'] = '4'
bin_oct_map['101'] = '5'
bin_oct_map['110'] = '6'
bin_oct_map['111'] = '7'
def convert_bin_to_oct(bin):
l = len(bin)
t = -1
... |
"""SoCo-CLI is a command line control interface for Sonos systems.
It is a simplified wrapper around the SoCo python library, as well as providing
an extensive range of additional features.
It can be used as a command line program, as an interactive command shell, and
in other programs via its simple API. It can also... | """SoCo-CLI is a command line control interface for Sonos systems.
It is a simplified wrapper around the SoCo python library, as well as providing
an extensive range of additional features.
It can be used as a command line program, as an interactive command shell, and
in other programs via its simple API. It can also... |
"""
Stein's algorithm or binary GCD algorithm is an algorithm
that computes the greatest common divisor of
two non-negative integers. Stein's algorithm
replaces division with arithmetic shifts, comparisons, and subtraction.
"""
def gcd(first_number: int, second_number: int) -> int:
"""
gcd: Function which fin... | """
Stein's algorithm or binary GCD algorithm is an algorithm
that computes the greatest common divisor of
two non-negative integers. Stein's algorithm
replaces division with arithmetic shifts, comparisons, and subtraction.
"""
def gcd(first_number: int, second_number: int) -> int:
"""
gcd: Function which find... |
class Context(dict):
"""Object filled by resolvers when evaluating a rule
It's mainly used to store a corresponding value from a parameter.
Example:
resolver will receive a user_id, then look for the corresponding user in DB
and finally store the user into the context in order to let him be... | class Context(dict):
"""Object filled by resolvers when evaluating a rule
It's mainly used to store a corresponding value from a parameter.
Example:
resolver will receive a user_id, then look for the corresponding user in DB
and finally store the user into the context in order to let him be... |
line_list = list(map(int, input().split()))
line_list.sort()
print(" <= ".join(str(x) for x in line_list)) | line_list = list(map(int, input().split()))
line_list.sort()
print(' <= '.join((str(x) for x in line_list))) |
class Pegawai:
def __init__(self, nama, email, gaji):
self.namaPegawai = nama
self.emailPegawai = email + 'gmail.com'
self.gajiPegawai = gaji
# nama dari method tidak boleh sama dengan property
# contoh : method gajiPegawai()
def gajiPegawaiCalculate(self):
# parameter ... | class Pegawai:
def __init__(self, nama, email, gaji):
self.namaPegawai = nama
self.emailPegawai = email + 'gmail.com'
self.gajiPegawai = gaji
def gaji_pegawai_calculate(self):
self.gajiPegawai = self.gajiPegawai * 30
return self.gajiPegawai
pegawai = pegawai('Mohamad Fa... |
class Solution:
def avoidFlood(self, rains: List[int]) -> List[int]:
rainsLen = len(rains)
lastRains, dryDayIndices = {}, []
result = [-1] * rainsLen
def getDryingDayForLake(day, lake):
if len(dryDayIndices) == 0:
return None
else:
... | class Solution:
def avoid_flood(self, rains: List[int]) -> List[int]:
rains_len = len(rains)
(last_rains, dry_day_indices) = ({}, [])
result = [-1] * rainsLen
def get_drying_day_for_lake(day, lake):
if len(dryDayIndices) == 0:
return None
els... |
v = []
for i in range(20):
v.append(int(input("")))
for i in range(20):
print("N[%i] = %i" % (i, v[19 - i]))
| v = []
for i in range(20):
v.append(int(input('')))
for i in range(20):
print('N[%i] = %i' % (i, v[19 - i])) |
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
def spiral_coords(r1, c1, r2, c2):
for c in range(c1, c2 + 1):
yield r1, c
for r in range(r1 + 1, r2 + 1):
yield r, c2
if r1 < r2 and c1 < ... | class Solution:
def spiral_order(self, matrix: List[List[int]]) -> List[int]:
def spiral_coords(r1, c1, r2, c2):
for c in range(c1, c2 + 1):
yield (r1, c)
for r in range(r1 + 1, r2 + 1):
yield (r, c2)
if r1 < r2 and c1 < c2:
... |
"""Constants."""
N_MONTE = 1_000
DPI_IMAGE_RESOLUTION = 600
SHORT_NAME_TO_NAME = {
'IND': 'India',
'ENG': 'England',
'AUS': 'Australia',
'WI': 'West Indies',
'NZ': 'New Zealand',
'PAK': 'Pakistan',
'SA': 'South Africa',
'SL': 'Sri Lanka',
'BAN': 'Bangladesh',
'AFG': 'Afghanist... | """Constants."""
n_monte = 1000
dpi_image_resolution = 600
short_name_to_name = {'IND': 'India', 'ENG': 'England', 'AUS': 'Australia', 'WI': 'West Indies', 'NZ': 'New Zealand', 'PAK': 'Pakistan', 'SA': 'South Africa', 'SL': 'Sri Lanka', 'BAN': 'Bangladesh', 'AFG': 'Afghanistan', 'SCO': 'Scotland', 'NAM': 'Namibia'}
gro... |
## https://leetcode.com/problems/card-flipping-game/
## this problem comes down to finding the smallest number
## that we can put on the back of a card without putting
## that same number on the frong. i do this by finding all
## invalid numbers, then taking the minimum of the remaining
## numbers. invalid numbers ... | class Solution:
def flipgame(self, fronts: List[int], backs: List[int]) -> int:
invalid_nums = set((fronts[ii] for ii in range(len(fronts)) if fronts[ii] == backs[ii]))
all_numbers = set(fronts + backs)
valid_numbers = list(all_numbers.difference(invalid_nums))
if not len(valid_numb... |
print("Welcome to Treasure island.\nYour Mission is to find the treasure.")
inputs = ["right", "left", "swim", "wait", "red", "blue", "yellow"]
input1 = input2 = input3 = 0
input1 = input(
"You're at a crossroad. Where do you want to go? Type 'Left' or 'Right'\n"
).lower()
if input1 == "right":
pri... | print('Welcome to Treasure island.\nYour Mission is to find the treasure.')
inputs = ['right', 'left', 'swim', 'wait', 'red', 'blue', 'yellow']
input1 = input2 = input3 = 0
input1 = input("You're at a crossroad. Where do you want to go? Type 'Left' or 'Right'\n").lower()
if input1 == 'right':
print('You got hit by ... |
figures_black = {
"king": u"\u2654",
"queen": u"\u2655",
"rook": u"\u2656",
"bishop": u"\u2657",
"knight": u"\u2658",
"pawn": u"\u2659"
}
figures_white = {
"king": u"\u265A",
"queen": u"\u265B",
"rook": u"\u265C",
"bishop": u"\u265D",
"knight": u"\u265E",
"pawn": u"\... | figures_black = {'king': u'β', 'queen': u'β', 'rook': u'β', 'bishop': u'β', 'knight': u'β', 'pawn': u'β'}
figures_white = {'king': u'β', 'queen': u'β', 'rook': u'β', 'bishop': u'β', 'knight': u'β', 'pawn': u'β'}
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] |
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowestCommonAncestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:... | class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lowest_common_ancestor(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
... |
#!/usr/bin/env python
#
# Copyright 2012 8pen
"""Utility class for byte arrays"""
def to_int(byte_array, offset, chunk_size):
value = 0
for i in range(0, chunk_size):
value += byte_array[offset + i] << (chunk_size-i-1)*8
return value | """Utility class for byte arrays"""
def to_int(byte_array, offset, chunk_size):
value = 0
for i in range(0, chunk_size):
value += byte_array[offset + i] << (chunk_size - i - 1) * 8
return value |
DEBUG = True
SECRET_KEY = "secret"
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.staticfiles',
'django.contrib.contenttypes',
'django_app_lti',
]
MIDDLEWARE = []
ROOT_URLCONF = 'django_app_lti.urls'
DATABASES = {
'default': {
'ENGINE': 'd... | debug = True
secret_key = 'secret'
template_debug = True
allowed_hosts = []
installed_apps = ['django.contrib.auth', 'django.contrib.staticfiles', 'django.contrib.contenttypes', 'django_app_lti']
middleware = []
root_urlconf = 'django_app_lti.urls'
databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME'... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
Time convert functions
"""
__all__ = ["ymdhms2jd","doy2jd","jd2ymdhms","jd2gpst","gpst2jd"]
def ymdhms2jd(datetime):
"""
Datetime(ymdhms) to Julian date
"""
days_to_month = [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] # ignore index=0
... | """
Time convert functions
"""
__all__ = ['ymdhms2jd', 'doy2jd', 'jd2ymdhms', 'jd2gpst', 'gpst2jd']
def ymdhms2jd(datetime):
"""
Datetime(ymdhms) to Julian date
"""
days_to_month = [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]
(year, month, day) = datetime[0:3]
years_from_1600 = ye... |
class Solution:
def isPalindrome(self, x: int) -> bool:
if x<0:
return False
# solving with converting into str
s = str(x)
n = len(s)
i=0
j=n-1
while(i<j):
if s[i]!=s[j]:
return False
i+=1
j-=1
... | class Solution:
def is_palindrome(self, x: int) -> bool:
if x < 0:
return False
s = str(x)
n = len(s)
i = 0
j = n - 1
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
if __nam... |
# SHERLOCK AND DATES
for _ in range(int(input())):
date = input().strip().split()
if date[0]=='1':
if date[1]==('January'):
date[0]='31'
elif date[1]==('May'):
date[0]='30'
elif date[1]==('July'):
date[0]='30'
elif date[1]==('October'... | for _ in range(int(input())):
date = input().strip().split()
if date[0] == '1':
if date[1] == 'January':
date[0] = '31'
elif date[1] == 'May':
date[0] = '30'
elif date[1] == 'July':
date[0] = '30'
elif date[1] == 'October':
date[0] ... |
# File: skypeforbusiness_consts.py
#
# Copyright (c) 2019-2020 Splunk Inc.
#
# 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 requir... | skype4_b_login_base_url = 'https://login.microsoftonline.com'
skype4_b_authorize_url = '/{tenant_id}/oauth2/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type={response_type}&state={state}&resource={resource}'
skype4_b_server_token_url = '/{tenant_id}/oauth2/token'
skype4_b_first_hub_url_endpoint... |
"""High Scores exercise from exercism.io python path.
Manage a game player's High Score list.
Returns the highest score from the list, the last added score and
the three highest scores.
"""
def latest(scores):
"""Get last added score.
Args:
scores: list of positive integers
Returns:
An... | """High Scores exercise from exercism.io python path.
Manage a game player's High Score list.
Returns the highest score from the list, the last added score and
the three highest scores.
"""
def latest(scores):
"""Get last added score.
Args:
scores: list of positive integers
Returns:
An ... |
OVERLEAF_BASE_URL = "https://www.overleaf.com"
OVERLEAF_LOGIN = OVERLEAF_BASE_URL + "/login"
OVERLEAF_CSRF_REGEX = "window\.csrfToken = \"(.+)\""
def get_download_url(project_id):
return OVERLEAF_BASE_URL + ("/project/%s/download/zip" % str(project_id))
| overleaf_base_url = 'https://www.overleaf.com'
overleaf_login = OVERLEAF_BASE_URL + '/login'
overleaf_csrf_regex = 'window\\.csrfToken = "(.+)"'
def get_download_url(project_id):
return OVERLEAF_BASE_URL + '/project/%s/download/zip' % str(project_id) |
def test_add_pickle_job(sqs, queue_name):
messages = []
_queue = sqs.queue(queue_name)
@_queue.processor("say_hello")
def say_hello(username=None):
messages.append(username)
say_hello.delay(username="Homer")
result = sqs.queue(queue_name).process_batch(wait_seconds=0)
assert resul... | def test_add_pickle_job(sqs, queue_name):
messages = []
_queue = sqs.queue(queue_name)
@_queue.processor('say_hello')
def say_hello(username=None):
messages.append(username)
say_hello.delay(username='Homer')
result = sqs.queue(queue_name).process_batch(wait_seconds=0)
assert result.... |
__version__ = "HEAD"
__project__ = "sqlalchemy-rqlite"
__author__ = "Zac Medico"
__email__ = "zmedico@gmail.com"
__copyright__ = "Copyright (C) 2016 Zac Medico"
__license__ = "MIT"
__description__ = "A SQLAlchemy dialect for rqlite"
| __version__ = 'HEAD'
__project__ = 'sqlalchemy-rqlite'
__author__ = 'Zac Medico'
__email__ = 'zmedico@gmail.com'
__copyright__ = 'Copyright (C) 2016 Zac Medico'
__license__ = 'MIT'
__description__ = 'A SQLAlchemy dialect for rqlite' |
"""
from: http://adventofcode.com/2017/day/1
--- Day 1: Inverse Captcha ---
The night before Christmas, one of Santa's Elves calls you in a panic. "The printer's broken! We
can't print the Naughty or Nice List!" By the time you make it to sub-basement 17, there are only a
few minutes until midnight. "We have a big pro... | """
from: http://adventofcode.com/2017/day/1
--- Day 1: Inverse Captcha ---
The night before Christmas, one of Santa's Elves calls you in a panic. "The printer's broken! We
can't print the Naughty or Nice List!" By the time you make it to sub-basement 17, there are only a
few minutes until midnight. "We have a big pro... |
# (C) Copyright 2005-2021 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at... | def add_or_remove_notifiers(*, object, graph, handler, target, dispatcher, remove):
""" Add/Remove notifiers on objects following the description on an
ObserverGraph.
All nodes in ``ObserverGraph`` are required to be instances of
``IObserver``. The interface of ``IObserver`` supports this function.
... |
def test_py_config_defaults(py_config):
# driver settings
assert py_config.driver.browser == 'chrome'
assert py_config.driver.remote_url == ''
assert py_config.driver.wait_time == 10
assert py_config.driver.page_load_wait_time == 0
assert py_config.driver.options == []
assert py_config.drive... | def test_py_config_defaults(py_config):
assert py_config.driver.browser == 'chrome'
assert py_config.driver.remote_url == ''
assert py_config.driver.wait_time == 10
assert py_config.driver.page_load_wait_time == 0
assert py_config.driver.options == []
assert py_config.driver.version == 'latest'
... |
# -*- coding: utf-8 -*-
{
'name': 'test-assetsbundle',
'version': '0.1',
'category': 'Hidden/Tests',
'description': """A module to verify the Assets Bundle mechanism.""",
'maintainer': 'Odoo SA',
'depends': ['base'],
'installable': True,
'data': [
"views/views.xml",
],
'a... | {'name': 'test-assetsbundle', 'version': '0.1', 'category': 'Hidden/Tests', 'description': 'A module to verify the Assets Bundle mechanism.', 'maintainer': 'Odoo SA', 'depends': ['base'], 'installable': True, 'data': ['views/views.xml'], 'auto_install': False} |
class Solution(object):
def findMin(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s=set(nums)
return min(s)
| class Solution(object):
def find_min(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
s = set(nums)
return min(s) |
"""
JSON test OWM API responses
"""
COINDEX_JSON_DUMP = '{"reference_time": 1234567, "co_samples": [{"pressure": ' \
'1000, "value": 8.168363052618588e-08, "precision": ' \
'-4.999999987376214e-07}, {"pressure": 681.2920532226562, ' \
'"value": 8.686949115599... | """
JSON test OWM API responses
"""
coindex_json_dump = '{"reference_time": 1234567, "co_samples": [{"pressure": 1000, "value": 8.168363052618588e-08, "precision": -4.999999987376214e-07}, {"pressure": 681.2920532226562, "value": 8.686949115599418e-08, "precision": -4.999999987376214e-07}, {"pressure": 464.158874511718... |
description = 'Slit H2 using Beckhoff controllers'
group = 'lowlevel'
devices = dict(
h2_center = device('nicos.devices.generic.VirtualMotor',
description = 'Horizontal slit system: offset of the slit-center to the beam',
unit = 'mm',
abslimits = (-69.5, 69.5),
speed = 1.,
),
... | description = 'Slit H2 using Beckhoff controllers'
group = 'lowlevel'
devices = dict(h2_center=device('nicos.devices.generic.VirtualMotor', description='Horizontal slit system: offset of the slit-center to the beam', unit='mm', abslimits=(-69.5, 69.5), speed=1.0), h2_width=device('nicos.devices.generic.VirtualMotor', d... |
class SystemUnderTest(object):
"""This is an interface to a concrete implementation under test"""
def __init__(self):
super(SystemUnderTest, self).__init__()
# pass_input either forwards an input to the system under test, or if there is some output from the SUT that
# has not yet been forwarded to DT, it ignore... | class Systemundertest(object):
"""This is an interface to a concrete implementation under test"""
def __init__(self):
super(SystemUnderTest, self).__init__()
def pass_input(self, inp):
raise not_implemented_error('Abstract method not implemented!')
def receive_output(self):
ra... |
# op map for nova.
op_map = \
{(8774, '/v2', '/extensions', 'GET', ''): (),
(8774, '/v2', '/extensions/os-consoles', 'GET', ''): (),
(8774, '/v2', '/flavors', 'GET', ''): (),
(8774, '/v2', '/flavors', 'POST', ''): ('compute_extension:flavormanage',
'compute_extension:flavor_... | op_map = {(8774, '/v2', '/extensions', 'GET', ''): (), (8774, '/v2', '/extensions/os-consoles', 'GET', ''): (), (8774, '/v2', '/flavors', 'GET', ''): (), (8774, '/v2', '/flavors', 'POST', ''): ('compute_extension:flavormanage', 'compute_extension:flavor_swap', 'compute_extension:flavor_rxtx', 'compute_extension:flavor_... |
# -*- coding: utf-8 -*-
__author__ = 'Fabio Caccamo'
__copyright__ = 'Copyright (c) 2020-present Fabio Caccamo'
__description__ = 'file-system utilities for lazy devs.'
__email__ = 'fabio.caccamo@gmail.com'
__license__ = 'MIT'
__title__ = 'python-fsutil'
__version__ = '0.3.0'
| __author__ = 'Fabio Caccamo'
__copyright__ = 'Copyright (c) 2020-present Fabio Caccamo'
__description__ = 'file-system utilities for lazy devs.'
__email__ = 'fabio.caccamo@gmail.com'
__license__ = 'MIT'
__title__ = 'python-fsutil'
__version__ = '0.3.0' |
_WIT_ACCESS_TOKEN_FOR_BROWSER_TV = '3QTEIGPP4YXNRN6DKPDOLV46EQLSGIUJ'
_WIT_ACCESS_TOKEN_FOR_DEVICE_CONTROL = 'IEGTTI2YDCBYGF6ZYR7AVI2ZOVXLOSMI'
LISTENERS = [
( 'archspee.listeners.alsa_port_audio.AlsaPortAudioListener', {} )
]
TRIGGERS = [
(
'archspee.triggers.snowboy.SnowboyTrigger',
{
... | _wit_access_token_for_browser_tv = '3QTEIGPP4YXNRN6DKPDOLV46EQLSGIUJ'
_wit_access_token_for_device_control = 'IEGTTI2YDCBYGF6ZYR7AVI2ZOVXLOSMI'
listeners = [('archspee.listeners.alsa_port_audio.AlsaPortAudioListener', {})]
triggers = [('archspee.triggers.snowboy.SnowboyTrigger', {'decoder_model': ['third_party/snowboy/... |
"""Module generating ICMP payloads (with no header)"""
class PayloadProvider:
def __init__(self):
raise NotImplementedError('Cannot create instances of PayloadProvider')
def __iter__(self):
raise NotImplementedError()
def __next__(self):
raise NotImplementedError()
class List(P... | """Module generating ICMP payloads (with no header)"""
class Payloadprovider:
def __init__(self):
raise not_implemented_error('Cannot create instances of PayloadProvider')
def __iter__(self):
raise not_implemented_error()
def __next__(self):
raise not_implemented_error()
class L... |
def garland(word):
printy=0
i=0
while True:
if word[i:] == word[:-i]:
return len(word[:-i])
i+=1
if __name__ == "__main__":
assert garland("programmer") == 0
assert garland("ceramic") == 1
assert garland("onion") == 2
assert garland("alfalfa") == 4
| def garland(word):
printy = 0
i = 0
while True:
if word[i:] == word[:-i]:
return len(word[:-i])
i += 1
if __name__ == '__main__':
assert garland('programmer') == 0
assert garland('ceramic') == 1
assert garland('onion') == 2
assert garland('alfalfa') == 4 |
def array_count9(arr):
count = 0
for num in arr:
if num == 9:
count = count + 1
return count
count = array_count9([1, 2, 9])
print(count)
count = array_count9([1, 9, 9])
print(count)
count = array_count9([1, 9, 9, 3, 9])
print(count) | def array_count9(arr):
count = 0
for num in arr:
if num == 9:
count = count + 1
return count
count = array_count9([1, 2, 9])
print(count)
count = array_count9([1, 9, 9])
print(count)
count = array_count9([1, 9, 9, 3, 9])
print(count) |
{
"__additional_thread_unsafe__" :
[
"validate_idb_names",
]
}
| {'__additional_thread_unsafe__': ['validate_idb_names']} |
t1, t2, n = map(int, input().split(" "))
for i in range(2, n):
tn = t1 + t2**2
t1, t2 = t2, tn
print(tn)
| (t1, t2, n) = map(int, input().split(' '))
for i in range(2, n):
tn = t1 + t2 ** 2
(t1, t2) = (t2, tn)
print(tn) |
#
# PySNMP MIB module HH3C-SPB-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-SPB-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:29:43 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,... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, single_value_constraint, value_range_constraint, value_size_constraint) ... |
class Solution:
def canReorderDoubled(self, A):
"""
:type A: List[int]
:rtype: bool
"""
# array of doubled pairs
def valid(nums):
if len(nums) % 2 == 1:
return False
counts = collections.Counter(nums)
for num in sort... | class Solution:
def can_reorder_doubled(self, A):
"""
:type A: List[int]
:rtype: bool
"""
def valid(nums):
if len(nums) % 2 == 1:
return False
counts = collections.Counter(nums)
for num in sorted(nums):
if ... |
class Solution:
def frequencySort(self, s: str) -> str:
occ = dict()
result = ""
for i in s:
if i in occ:
occ[i] += 1
else:
occ[i] = 1
str_list = list(occ.items())
for i in range(len(oc... | class Solution:
def frequency_sort(self, s: str) -> str:
occ = dict()
result = ''
for i in s:
if i in occ:
occ[i] += 1
else:
occ[i] = 1
str_list = list(occ.items())
for i in range(len(occ.keys())):
max_str =... |
n = int(input())
check = n
new_number = 0
temp = 0
count = 0
while True:
count += 1
temp = n // 10 + n % 10
new_number = (n % 10) * 10 + temp % 10
n = new_number
if new_number == check:
break
print(count)
| n = int(input())
check = n
new_number = 0
temp = 0
count = 0
while True:
count += 1
temp = n // 10 + n % 10
new_number = n % 10 * 10 + temp % 10
n = new_number
if new_number == check:
break
print(count) |
secret = {
'url_oceny' : 'https://portal.wsb.pl/group/gdansk/oceny-wstepne',
'wsb_login' : '',
'wsb_password' : '',
'email_from' : '',
'email_to' : '',
'smtp_login' : '',
'smtp_password' : '',
'smtp_host' : '',
'smtp_port' : 587,
'fb_login' : '',
'fb_password' : '',
... | secret = {'url_oceny': 'https://portal.wsb.pl/group/gdansk/oceny-wstepne', 'wsb_login': '', 'wsb_password': '', 'email_from': '', 'email_to': '', 'smtp_login': '', 'smtp_password': '', 'smtp_host': '', 'smtp_port': 587, 'fb_login': '', 'fb_password': '', 'fb_thread_id': ''} |
def is_lucky(n):
s = str(n)
half = len(s)//2
left, right = s[:half], s[half:]
return sum(map(int, left)) == sum(map(int, right))
| def is_lucky(n):
s = str(n)
half = len(s) // 2
(left, right) = (s[:half], s[half:])
return sum(map(int, left)) == sum(map(int, right)) |
data = (
'Fu ', # 0x00
'Zhuo ', # 0x01
'Mao ', # 0x02
'Fan ', # 0x03
'Qie ', # 0x04
'Mao ', # 0x05
'Mao ', # 0x06
'Ba ', # 0x07
'Zi ', # 0x08
'Mo ', # 0x09
'Zi ', # 0x0a
'Di ', # 0x0b
'Chi ', # 0x0c
'Ji ', # 0x0d
'Jing ', # 0x0e
'Long ', # 0x0f
'[?] ', # 0x10
'Niao ', ... | data = ('Fu ', 'Zhuo ', 'Mao ', 'Fan ', 'Qie ', 'Mao ', 'Mao ', 'Ba ', 'Zi ', 'Mo ', 'Zi ', 'Di ', 'Chi ', 'Ji ', 'Jing ', 'Long ', '[?] ', 'Niao ', '[?] ', 'Xue ', 'Ying ', 'Qiong ', 'Ge ', 'Ming ', 'Li ', 'Rong ', 'Yin ', 'Gen ', 'Qian ', 'Chai ', 'Chen ', 'Yu ', 'Xiu ', 'Zi ', 'Lie ', 'Wu ', 'Ji ', 'Kui ', 'Ce ', 'C... |
# Copyright 2017 Internap.
#
# 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... | def form_encode(data):
exploded_data = {}
for (k, v) in data.items():
items = _explode_enumerable(k, v)
for (new_key, new_val) in items:
exploded_data[new_key] = new_val
return exploded_data
def form_encode_without_files(data):
return form_encode({k: v for (k, v) in data.ite... |
# -*- coding:utf-8 -*-
class Solution:
def FindNumbersWithSum(self, array, tsum):
# write code here
l, r = 0, len(array) - 1
while l < r:
if array[l] + array[r] < tsum: l += 1
elif array[l] + array[r] > tsum: r -= 1
else: return [array[l], array[r]]
... | class Solution:
def find_numbers_with_sum(self, array, tsum):
(l, r) = (0, len(array) - 1)
while l < r:
if array[l] + array[r] < tsum:
l += 1
elif array[l] + array[r] > tsum:
r -= 1
else:
return [array[l], array[r]]... |
filename_domain = 'ig_domain.iga'
regions = {
'Omega' : 'all',
'Omega_0' : 'vertices in (x > 1.5) & (y < 1.5)',
'Gamma1' : ('vertices of set xi10', 'facet'),
'Gamma2' : ('vertices of set xi11', 'facet'),
}
fields = {
'temperature' : ('real', 1, 'Omega', None, 'H1', 'iga'),
}
variables = {
'T'... | filename_domain = 'ig_domain.iga'
regions = {'Omega': 'all', 'Omega_0': 'vertices in (x > 1.5) & (y < 1.5)', 'Gamma1': ('vertices of set xi10', 'facet'), 'Gamma2': ('vertices of set xi11', 'facet')}
fields = {'temperature': ('real', 1, 'Omega', None, 'H1', 'iga')}
variables = {'T': ('unknown field', 'temperature', 0), ... |
def test_index_route(test_client):
response = test_client.get('/')
assert response.status_code == 200
assert '<title>Home | Flask-Startup</title>' in response
| def test_index_route(test_client):
response = test_client.get('/')
assert response.status_code == 200
assert '<title>Home | Flask-Startup</title>' in response |
"""Module contains helper methods used by other modules in the package."""
def env_exists(env_variable: str) -> bool:
"""Validates if env variable was provided and is not an empty string.
Args:
env_variable: str, name of the env variable
Returns:
True: if env provide and not an empty str... | """Module contains helper methods used by other modules in the package."""
def env_exists(env_variable: str) -> bool:
"""Validates if env variable was provided and is not an empty string.
Args:
env_variable: str, name of the env variable
Returns:
True: if env provide and not an empty stri... |
"""
Warnings used throughout the module. Exported and inhereited from a commmon
warning class so as to facilitate the filtering of warnings
"""
# pylint: disable=too-few-public-methods, missing-docstring
class SparseSCWarning(RuntimeWarning):pass
class UnpenalizedRecords(SparseSCWarning):pass
| """
Warnings used throughout the module. Exported and inhereited from a commmon
warning class so as to facilitate the filtering of warnings
"""
class Sparsescwarning(RuntimeWarning):
pass
class Unpenalizedrecords(SparseSCWarning):
pass |
class Motor:
def __init__(self):
self.velocidade = 0
def acelerar(self):
self.velocidade += 1
def frear(self):
self.velocidade -= 2
self.velocidade = max(0, self.velocidade)
motor = Motor()
velocidade = motor.velocidade
print(motor.velocidade)
motor.acelerar()
print(motor... | class Motor:
def __init__(self):
self.velocidade = 0
def acelerar(self):
self.velocidade += 1
def frear(self):
self.velocidade -= 2
self.velocidade = max(0, self.velocidade)
motor = motor()
velocidade = motor.velocidade
print(motor.velocidade)
motor.acelerar()
print(motor.... |
class MirrorModifier:
merge_threshold = None
mirror_object = None
mirror_offset_u = None
mirror_offset_v = None
use_clip = None
use_mirror_merge = None
use_mirror_u = None
use_mirror_v = None
use_mirror_vertex_groups = None
use_x = None
use_y = None
use_z = None
| class Mirrormodifier:
merge_threshold = None
mirror_object = None
mirror_offset_u = None
mirror_offset_v = None
use_clip = None
use_mirror_merge = None
use_mirror_u = None
use_mirror_v = None
use_mirror_vertex_groups = None
use_x = None
use_y = None
use_z = None |
# create a game the guesses users secret number using bisection search
input("Please think of a number between 0 and 100!")
low = 0
high = 100
solved = False
while not solved:
guess = (high+low)//2
print('Is your secret number ' + str(guess) + '?')
response = input("Enter 'h' to indicate the guess is too high. E... | input('Please think of a number between 0 and 100!')
low = 0
high = 100
solved = False
while not solved:
guess = (high + low) // 2
print('Is your secret number ' + str(guess) + '?')
response = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indica... |
"""c protobuf and grpc rules."""
load(":c_proto_compile.bzl", _c_proto_compile = "c_proto_compile")
load(":c_proto_library.bzl", _c_proto_library = "c_proto_library")
# Export c rules
c_proto_compile = _c_proto_compile
c_proto_library = _c_proto_library
| """c protobuf and grpc rules."""
load(':c_proto_compile.bzl', _c_proto_compile='c_proto_compile')
load(':c_proto_library.bzl', _c_proto_library='c_proto_library')
c_proto_compile = _c_proto_compile
c_proto_library = _c_proto_library |
class persona:
def __init__(self,a,b):
self.a=a
self.b=b
def saluda(self,c):
return f"hola {c.a},me llamo {self.a}"
david=persona("David",35)
erika=persona("Erika",32)
print(david.saluda(erika))
| class Persona:
def __init__(self, a, b):
self.a = a
self.b = b
def saluda(self, c):
return f'hola {c.a},me llamo {self.a}'
david = persona('David', 35)
erika = persona('Erika', 32)
print(david.saluda(erika)) |
schema = """
CREATE TABLE owners (
name TEXT PRIMARY KEY,
key TEXT
);
CREATE TABLE zones (
id TEXT PRIMARY KEY,
owner TEXT,
aws_access_key TEXT,
aws_secret_key TEXT,
name TEXT
);
CREATE TABLE domains (
zone_id TEXT,
name TEXT,
type TEXT,
value TEXT,
PRIMARY KEY (zone_id... | schema = '\nCREATE TABLE owners (\n name TEXT PRIMARY KEY,\n key TEXT\n);\n\nCREATE TABLE zones (\n id TEXT PRIMARY KEY,\n owner TEXT,\n aws_access_key TEXT,\n aws_secret_key TEXT,\n name TEXT\n);\n\nCREATE TABLE domains (\n zone_id TEXT,\n name TEXT,\n type TEXT,\n value TEXT,\n PRI... |
"""Python module to know if a number is prime"""
def is_prime(number: int) -> bool:
"""Returns True if number is prime or False if the number is not prime"""
results_list = [x for x in range(2, number) if number % x == 0]
return len(results_list) == 0
def run():
number: int = 'hola'
number_is_pr... | """Python module to know if a number is prime"""
def is_prime(number: int) -> bool:
"""Returns True if number is prime or False if the number is not prime"""
results_list = [x for x in range(2, number) if number % x == 0]
return len(results_list) == 0
def run():
number: int = 'hola'
number_is_prim... |
test = {
'name': 'Question 1',
'points': 2,
'suites': [
{
'cases': [
{
'answer': 'Domain is numbers. Range is numbers',
'choices': [
'Domain is numbers. Range is numbers',
'Domain is numbers. Range is strings',
'Domain is strings. Range is ... | test = {'name': 'Question 1', 'points': 2, 'suites': [{'cases': [{'answer': 'Domain is numbers. Range is numbers', 'choices': ['Domain is numbers. Range is numbers', 'Domain is numbers. Range is strings', 'Domain is strings. Range is numbers', 'Domain is strings. Range is strings'], 'hidden': False, 'question': 'What i... |
class ApplicationError(Exception):
pass
class FileNotFound(ApplicationError):
pass
| class Applicationerror(Exception):
pass
class Filenotfound(ApplicationError):
pass |
input_ = '6,19,0,5,7,13,1'
num_iterations = 30000000
starting_nums = list(map(int, input_.split(',')))
last_times_spoken_dict = dict(zip(starting_nums, range(1, len(starting_nums) + 1)))
last_time_spoken = None # assume that starting nums contain no duplicates
for turn in range(len(starting_nums) + 1, num_iterations +... | input_ = '6,19,0,5,7,13,1'
num_iterations = 30000000
starting_nums = list(map(int, input_.split(',')))
last_times_spoken_dict = dict(zip(starting_nums, range(1, len(starting_nums) + 1)))
last_time_spoken = None
for turn in range(len(starting_nums) + 1, num_iterations + 1):
spoken_num = 0 if last_time_spoken is None... |
inputString = input("\nEnter the string : \n")
position = int(input("\nEnter the position : \n"))
subString = input("\nEnter the Substring\n")
inputString = inputString[:position-1] + subString + inputString[position-1:]
print("\nThe new string becomes : \n")
print(inputString) | input_string = input('\nEnter the string : \n')
position = int(input('\nEnter the position : \n'))
sub_string = input('\nEnter the Substring\n')
input_string = inputString[:position - 1] + subString + inputString[position - 1:]
print('\nThe new string becomes : \n')
print(inputString) |
# global settings module for fortiwlc_exporter
DEBUG = False
ONE_OFF = []
NO_DEFAULT_COLLECTORS = True
TIMEOUT = 60
EXPORTER_PORT = 9118
WLC_USERNAME = None
WLC_PASSWORD = None
WLC_API_KEY = None
| debug = False
one_off = []
no_default_collectors = True
timeout = 60
exporter_port = 9118
wlc_username = None
wlc_password = None
wlc_api_key = None |
# Implement the function count_dict_difference below.
# You can define other functions if it helps you decompose and solve
# the problem.
# Do not import any module that you do not use!
# Remember that if this were an exam problem, in order to be marked
# this file must meet certain requirements:
# - it must contain ... | def count_dict_difference(A, B):
result_dict = {}
for key in A.keys():
if key in B.keys():
if A[key] - B[key] > 0:
result_dict[key] = A[key] - B[key]
else:
result_dict[key] = A[key]
return result_dict
def test_count_dict_difference():
"""
This... |
# This file is a part of Arjuna
# Copyright 2015-2021 Rahul Verma
# Website: www.RahulVerma.net
# 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... | class Httpcookie:
def __init__(self, session, cookie):
self.__cookie = cookie
@property
def _cookie(self):
return self.__cookie
@property
def value(self):
"""
Value stored in this cookie.
"""
return self._cookie.value
@property
def secure(s... |
def signum(a, b):
"""
Returns 1 if value of object a is greater than that of object b.
Returns 0 if objects are equivalent in value.
Returns -1 if value of object a is lesser than that of object b.
"""
return int(a > b) - int(a < b)
class Comparable:
"""
An abstract class that can be i... | def signum(a, b):
"""
Returns 1 if value of object a is greater than that of object b.
Returns 0 if objects are equivalent in value.
Returns -1 if value of object a is lesser than that of object b.
"""
return int(a > b) - int(a < b)
class Comparable:
"""
An abstract class that can be in... |
#!/usr/bin/python3
__author__ = "Mark H. Meng"
__copyright__ = "Copyright 2021, National University of S'pore and A*STAR"
__credits__ = ["G. Bai", "H. Guo", "S. G. Teo", "J. S. Dong"]
__license__ = "MIT"
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033... | __author__ = 'Mark H. Meng'
__copyright__ = "Copyright 2021, National University of S'pore and A*STAR"
__credits__ = ['G. Bai', 'H. Guo', 'S. G. Teo', 'J. S. Dong']
__license__ = 'MIT'
header = '\x1b[95m'
okblue = '\x1b[94m'
okcyan = '\x1b[96m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
endc = '\x1b[0m... |
# Complete the function below.
def arbitrage(quotes):
results = []
for quote in quotes:
# initial 100,000 dollars
initial = 100000
attrs = quote.split(' ')
attrs = list(map(float,attrs))
result = initial/attrs[0]/attrs[1]/attrs[2]
profit = int(result-initial)
... | def arbitrage(quotes):
results = []
for quote in quotes:
initial = 100000
attrs = quote.split(' ')
attrs = list(map(float, attrs))
result = initial / attrs[0] / attrs[1] / attrs[2]
profit = int(result - initial)
if profit <= 0:
results.append(0)
... |
class number:
def __init__(self):
self.a=10
self.b=20
class addition(number):
def add(self):
self.c=self.a+self.b
print('addition :',self.c)
class substraction(number):
def sub(self):
self.c=self.a-self.b
print('substraction :',self.c)
class multiplicat... | class Number:
def __init__(self):
self.a = 10
self.b = 20
class Addition(number):
def add(self):
self.c = self.a + self.b
print('addition :', self.c)
class Substraction(number):
def sub(self):
self.c = self.a - self.b
print('substraction :', self.c)
clas... |
class LogAndRaise:
def __init__(self, logger):
self.logger = logger
def logAndRaise(self, error, message, logMessage=None):
self.logger.error(message if not logMessage else logMessage)
raise error(message)
| class Logandraise:
def __init__(self, logger):
self.logger = logger
def log_and_raise(self, error, message, logMessage=None):
self.logger.error(message if not logMessage else logMessage)
raise error(message) |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/definition.set.ipynb (unless otherwise specified).
__all__ = []
# Cell
if __name__ == '__main__':
embed_markdown_file('definition.set.md',
origin=ORIGIN, destination=DESTINATION) | __all__ = []
if __name__ == '__main__':
embed_markdown_file('definition.set.md', origin=ORIGIN, destination=DESTINATION) |
{
'name': 'Website Form',
'category': 'Website/Website',
'summary': 'Build custom web forms',
'description': """
Customize and create your own web forms.
This module adds a new building block in the website builder in order to build new forms from scratch in any website page.
""",
... | {'name': 'Website Form', 'category': 'Website/Website', 'summary': 'Build custom web forms', 'description': '\n Customize and create your own web forms.\n This module adds a new building block in the website builder in order to build new forms from scratch in any website page.\n ', 'version': '1.0', 'd... |
class HashMap1(object):
def __init__(self, hashMap={}):
self.hashMap = hashMap
def add(self, key, value):
if (key not in self.hashMap):
self.hashMap[key] = value
return
raise Exception("Key is already within our data structure")
def update(se... | class Hashmap1(object):
def __init__(self, hashMap={}):
self.hashMap = hashMap
def add(self, key, value):
if key not in self.hashMap:
self.hashMap[key] = value
return
raise exception('Key is already within our data structure')
def update(self, key, value):
... |
# Copyright 2020 Google LLC
#
# 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, ... | def test_bincount(backends):
inputs = [1, 2, 3, 3, 5]
for b in backends:
t = B.tensor(inputs)
cnt = B.bincount(t, minlength=6)
assert cnt.shape[0] == 6
assert B.tensor_equal(cnt, B.tensor([0, 1, 1, 2, 0, 1])) |
'''
This mission is the first one of the series. Here you should find the length of the longest substring that consists of the same letter. For example, line "aaabbcaaaa" contains four substrings with the same letters "aaa", "bb","c" and "aaaa". The last substring is the longest one, which makes it the answer.
Input: ... | """
This mission is the first one of the series. Here you should find the length of the longest substring that consists of the same letter. For example, line "aaabbcaaaa" contains four substrings with the same letters "aaa", "bb","c" and "aaaa". The last substring is the longest one, which makes it the answer.
Input: ... |
class Solution:
def numRescueBoats(self, people: List[int], limit: int) -> int:
people.sort()
low = total = 0
high = len(people) - 1
while low <= high:
total += 1
if people[low] + people[high] <= limit:
low += 1
high -= 1
re... | class Solution:
def num_rescue_boats(self, people: List[int], limit: int) -> int:
people.sort()
low = total = 0
high = len(people) - 1
while low <= high:
total += 1
if people[low] + people[high] <= limit:
low += 1
high -= 1
... |
# -*- coding: utf-8 -*-
"""
This file is covered by the LICENSING file in the root of this project.
"""
__author__ = "rapidhere"
__all__ = ["ASYNC_OP_RESULT", "ASYNC_OP_QUERY_INTERVAL", "ASYNC_OP_QUERY_INTERVAL_LONG", "REMOTE_CREATED_RECORD"]
class ASYNC_OP_RESULT:
SUCCEEDED = "Succeeded"
IN_PROGRESS = "InPr... | """
This file is covered by the LICENSING file in the root of this project.
"""
__author__ = 'rapidhere'
__all__ = ['ASYNC_OP_RESULT', 'ASYNC_OP_QUERY_INTERVAL', 'ASYNC_OP_QUERY_INTERVAL_LONG', 'REMOTE_CREATED_RECORD']
class Async_Op_Result:
succeeded = 'Succeeded'
in_progress = 'InProgress'
async_op_query_int... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
curr_node = head
count = 1
prev = None
while... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverse_between(self, head: ListNode, left: int, right: int) -> ListNode:
curr_node = head
count = 1
prev = None
while curr_node:
if count == l... |
class RecordScore():
"""Class to track a game's maximum score"""
def __init__(self):
self.cache = []
def __call__(self, n):
if n not in self.cache:
self.cache.append(n)
return max(self.cache)
| class Recordscore:
"""Class to track a game's maximum score"""
def __init__(self):
self.cache = []
def __call__(self, n):
if n not in self.cache:
self.cache.append(n)
return max(self.cache) |
class Solution:
def minFlips(self, s: str) -> int:
n = len(s)
# count[0][0] := # of '0' in even indices
# count[0][1] := # of '0' in odd indices
# count[1][0] := # of '1' in even indices
# count[1][1] := # of '1' in odd indices
count = [[0] * 2 for _ in range(2)]
for i, c in enumera... | class Solution:
def min_flips(self, s: str) -> int:
n = len(s)
count = [[0] * 2 for _ in range(2)]
for (i, c) in enumerate(s):
count[ord(c) - ord('0')][i % 2] += 1
ans = min(count[1][0] + count[0][1], count[0][0] + count[1][1])
for (i, c) in enumerate(s):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.