content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
'''
m18 - maiores de 18
h - homens
m20 - mulheres menos de 20
'''
m18 = h = m20 = 0
while True:
print('-'*25)
print('CADSTRE UMA PESSOA')
print('-'*25)
idade = int(input('Idade: '))
if idade > 18:
m18 += 1
while True:
sexo = str(input('Sexo: [M/F] ')).upper()
i... | """
m18 - maiores de 18
h - homens
m20 - mulheres menos de 20
"""
m18 = h = m20 = 0
while True:
print('-' * 25)
print('CADSTRE UMA PESSOA')
print('-' * 25)
idade = int(input('Idade: '))
if idade > 18:
m18 += 1
while True:
sexo = str(input('Sexo: [M/F] ')).upper()
if sexo... |
bootstrap_url="http://agent-resources.cloudkick.com/"
s3_bucket="s3://agent-resources.cloudkick.com"
pubkey="etc/agent-linux.public.key"
branding_name="cloudkick-agent"
| bootstrap_url = 'http://agent-resources.cloudkick.com/'
s3_bucket = 's3://agent-resources.cloudkick.com'
pubkey = 'etc/agent-linux.public.key'
branding_name = 'cloudkick-agent' |
def binary_search(arr, num):
lo, hi = 0, len(arr)-1
while lo <= hi:
mid = (lo+hi)//2
if num < arr[mid]:
hi = mid-1
elif num > arr[mid]:
lo = mid+1
elif num == arr[mid]:
print(num, 'found in array.')
break
if lo > hi:
pri... | def binary_search(arr, num):
(lo, hi) = (0, len(arr) - 1)
while lo <= hi:
mid = (lo + hi) // 2
if num < arr[mid]:
hi = mid - 1
elif num > arr[mid]:
lo = mid + 1
elif num == arr[mid]:
print(num, 'found in array.')
break
if lo > h... |
"""Configuration for HomeAssistant connection"""
# pylint: disable=too-few-public-methods
class HomeAssistantConfig:
"""Data structure for holding Home-Assistant server configuration."""
def __init__(self, url, token):
self.url = url
self.token = token
| """Configuration for HomeAssistant connection"""
class Homeassistantconfig:
"""Data structure for holding Home-Assistant server configuration."""
def __init__(self, url, token):
self.url = url
self.token = token |
# Copyright 2014 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.
# TODO(borenet): This module belongs in the recipe engine. Remove it from this
# repo once it has been moved.
DEPS = [
'recipe_engine/json',
'recipe_e... | deps = ['recipe_engine/json', 'recipe_engine/path', 'recipe_engine/python', 'recipe_engine/raw_io', 'recipe_engine/step'] |
command = '/home/billerot/Git/alexa-flask/venv/bin/gunicorn'
pythonpath = '/home/billerot/Git/alexa-flask'
workers = 3
user = 'billerot'
bind = '0.0.0.0:8088'
logconfig = "/home/billerot/Git/alexa-flask/conf/logging.conf"
capture_output = True
timeout = 90
| command = '/home/billerot/Git/alexa-flask/venv/bin/gunicorn'
pythonpath = '/home/billerot/Git/alexa-flask'
workers = 3
user = 'billerot'
bind = '0.0.0.0:8088'
logconfig = '/home/billerot/Git/alexa-flask/conf/logging.conf'
capture_output = True
timeout = 90 |
# def minsteps1(n):
# memo = [0] * (n + 1)
# def loop(n):
# if n > 1:
# if memo[n] != 0:
# return memo[n]
# else:
# memo[n] = 1 + loop(n - 1)
# if n % 2 == 0:
# memo[n] = min(memo[n], 1 + loop(n // 2))
# ... | def minsteps(n):
memo = [0] * (n + 1)
for i in range(1, n + 1):
memo[i] = 1 + memo[i - 1]
if i % 2 == 0:
memo[i] = min(memo[i], memo[i // 2] + 1)
if i % 3 == 0:
memo[i] = min(memo[i], memo[i // 3] + 1)
return memo[n] - 1
print(minsteps(10))
print(minsteps(317)... |
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
ans = ""
queue = [root]
while queue:
node = queue.pop(0)
if node:
ans += str(node.val) ... | class Treenode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Codec:
def serialize(self, root):
ans = ''
queue = [root]
while queue:
node = queue.pop(0)
if node:
ans += str(node.val)... |
def f(x):
return x, x + 1
for a in b, c:
f(a)
| def f(x):
return (x, x + 1)
for a in (b, c):
f(a) |
class Proxy:
def __init__(self, obj):
self._obj = obj
# Delegate attribute lookup to internal obj
def __getattr__(self, name):
return getattr(self._obj, name)
# Delegate attribute assignment
def __setattr__(self, name, value):
if name.startswith('_'):
super().__... | class Proxy:
def __init__(self, obj):
self._obj = obj
def __getattr__(self, name):
return getattr(self._obj, name)
def __setattr__(self, name, value):
if name.startswith('_'):
super().__setattr__(name, value)
else:
setattr(self._obj, name, value)
if... |
rolls = [6, 5, 3, 7, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
soma = 0
# for r in rolls:
# soma += r
# for twice in range(0, 3):
# soma +=rolls[twice]
# if soma == 10:
# rolls[2] *= 2
# print(rolls)
# # print(twice)
# print(rolls)
# print(rolls[0])
# row = [i for i in rolls]
# print(rolls)
for i... | rolls = [6, 5, 3, 7, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
soma = 0
for iterator in range(0, len(rolls)):
soma += rolls[iterator]
if soma == 10:
change = rolls[iterator + 1] * 2
rolls[iterator + 1] = change
print(rolls) |
def dfs(node,parent):
currsize=1
for child in tree[node]:
if child!=parent:
currsize+=dfs(child,node)
subsize[node]=currsize
return currsize
n=int(input())
tree=[[]for i in range(n)]
for i in range(n-1):
a,b=map(int,input().split())
a,b=a-1,b-1
tree[a].append(b)
tre... | def dfs(node, parent):
currsize = 1
for child in tree[node]:
if child != parent:
currsize += dfs(child, node)
subsize[node] = currsize
return currsize
n = int(input())
tree = [[] for i in range(n)]
for i in range(n - 1):
(a, b) = map(int, input().split())
(a, b) = (a - 1, b -... |
''' Contains Hades gamedata '''
# Based on data in Weaponsets.lua
HeroMeleeWeapons = {
"SwordWeapon": "Stygian Blade",
"SpearWeapon": "Eternal Spear",
"ShieldWeapon": "Shield of Chaos",
"BowWeapon": "Heart-Seeking Bow",
"FistWeapon": "Twin Fists of Malphon",
"GunWeapon": "Adamant Rail",
}
# B... | """ Contains Hades gamedata """
hero_melee_weapons = {'SwordWeapon': 'Stygian Blade', 'SpearWeapon': 'Eternal Spear', 'ShieldWeapon': 'Shield of Chaos', 'BowWeapon': 'Heart-Seeking Bow', 'FistWeapon': 'Twin Fists of Malphon', 'GunWeapon': 'Adamant Rail'}
aspect_traits = {'SwordCriticalParryTrait': 'Nemesis', 'SwordCons... |
class Property(object):
def __init__(self, **kwargs):
self.background = "#FFFFFF"
self.candle_hl = dict()
self.up_candle = dict()
self.down_candle = dict()
self.long_trade_line = dict()
self.short_trade_line = dict()
self.long_trade_tri = dict()
sel... | class Property(object):
def __init__(self, **kwargs):
self.background = '#FFFFFF'
self.candle_hl = dict()
self.up_candle = dict()
self.down_candle = dict()
self.long_trade_line = dict()
self.short_trade_line = dict()
self.long_trade_tri = dict()
self.... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehumancommunity.org/
**Github Code Home Page:** https://github.com/makehumancommunity/
**Authors:** Thanasis Papoutsidakis
**Copyright(c):** MakeHuman Team 2001-2019
**Licensi... | """
**Project Name:** MakeHuman
**Product Home Page:** http://www.makehumancommunity.org/
**Github Code Home Page:** https://github.com/makehumancommunity/
**Authors:** Thanasis Papoutsidakis
**Copyright(c):** MakeHuman Team 2001-2019
**Licensing:** AGPL3
This file is part of Ma... |
# Copyright 2017 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.
DEPS = [
'chromium',
'isolate',
'recipe_engine/properties',
]
def RunSteps(api):
api.chromium.set_config('chromium')
api.isolate.compare_build_a... | deps = ['chromium', 'isolate', 'recipe_engine/properties']
def run_steps(api):
api.chromium.set_config('chromium')
api.isolate.compare_build_artifacts('first_dir', 'second_dir')
def gen_tests(api):
yield (api.test('basic') + api.properties(buildername='test_buildername', buildnumber=123))
yield (api.t... |
'''
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
'''
# Write your code here
def arr():
return []
def bfs(g,a,b,n):
... | """
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
def arr():
return []
def bfs(g, a, b, n):
vis = []
q ... |
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1: return s
rows = [''] * min(numRows, len(s))
cur_row = 0
goind_down = False
for c in s:
rows[cur_row] += c
if cur_row == 0 or cur_row == numRows - 1:
goi... | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [''] * min(numRows, len(s))
cur_row = 0
goind_down = False
for c in s:
rows[cur_row] += c
if cur_row == 0 or cur_row == numRows - 1:
... |
class LowPassFilter(object):
def __init__(self, lpf_constants):
self.tau = lpf_constants[0]
self.ts = lpf_constants[1]
self.a = 1. / (self.tau / self.ts + 1.)
self.b = self.tau / self.ts / (self.tau / self.ts + 1.);
self.last_val = 0.
self.ready = False
def get... | class Lowpassfilter(object):
def __init__(self, lpf_constants):
self.tau = lpf_constants[0]
self.ts = lpf_constants[1]
self.a = 1.0 / (self.tau / self.ts + 1.0)
self.b = self.tau / self.ts / (self.tau / self.ts + 1.0)
self.last_val = 0.0
self.ready = False
def g... |
'''
Problem Statement : Write a function that returns the boolean True if the given number is zero, the string "positive" if the number is greater than zero or the string "negative" if it's smaller than zero.
Problem Link : https://edabit.com/challenge/2TdPmSpLpa8NWh6m9
'''
def equilibrium(x):
return not x or ('negati... | """
Problem Statement : Write a function that returns the boolean True if the given number is zero, the string "positive" if the number is greater than zero or the string "negative" if it's smaller than zero.
Problem Link : https://edabit.com/challenge/2TdPmSpLpa8NWh6m9
"""
def equilibrium(x):
return not x or ('ne... |
"""https://leetcode.com/problems/rectangle-area/
https://www.youtube.com/watch?v=zGv3hOORxh0&list=WL&index=6
You're given 2 overlapping rectangles on a plane (2 rectilinear rectangles in a 2D plane.)
For each rectangle, you're given its bottom-left and top-right points
How would you find the area of their overlap? (to... | """https://leetcode.com/problems/rectangle-area/
https://www.youtube.com/watch?v=zGv3hOORxh0&list=WL&index=6
You're given 2 overlapping rectangles on a plane (2 rectilinear rectangles in a 2D plane.)
For each rectangle, you're given its bottom-left and top-right points
How would you find the area of their overlap? (to... |
"""
Resource optimization functions.
"""
#from scipy.optimize import linprog
def allocate(reservations, total=1.0):
"""
Allocate resources among slices with specified and unspecified reservations.
Returns a new list of values with the following properties:
- Every value is >= the corresponding input... | """
Resource optimization functions.
"""
def allocate(reservations, total=1.0):
"""
Allocate resources among slices with specified and unspecified reservations.
Returns a new list of values with the following properties:
- Every value is >= the corresponding input value.
- The result sums to `tota... |
class Solution:
def findShortestSubArray(self, nums):
first, count, res, degree = {}, {}, 0, 0
for i, num in enumerate(nums):
first.setdefault(num, i)
count[num] = count.get(num, 0) + 1
if count[num] > degree:
degree = count[num]
re... | class Solution:
def find_shortest_sub_array(self, nums):
(first, count, res, degree) = ({}, {}, 0, 0)
for (i, num) in enumerate(nums):
first.setdefault(num, i)
count[num] = count.get(num, 0) + 1
if count[num] > degree:
degree = count[num]
... |
class StitchSubclusterSelectorBase(object):
""" Subclasses of this class are used to make choice which subclusters
will be stitched next based on criteria. """
def __init__(self, *args, **kwargs):
pass
def select(self, dst, src, stitched, is_intra=False):
raise NotImplementedError
... | class Stitchsubclusterselectorbase(object):
""" Subclasses of this class are used to make choice which subclusters
will be stitched next based on criteria. """
def __init__(self, *args, **kwargs):
pass
def select(self, dst, src, stitched, is_intra=False):
raise NotImplementedError
... |
DISCORD_API_BASE_URL = "https://discord.com/api"
DISCORD_AUTHORIZATION_BASE_URL = DISCORD_API_BASE_URL + "/oauth2/authorize"
DISCORD_TOKEN_URL = DISCORD_API_BASE_URL + "/oauth2/token"
DISCORD_OAUTH_ALL_SCOPES = [
"bot", "connections", "email", "identify", "guilds", "guilds.join",
"gdm.join", "messages.read",... | discord_api_base_url = 'https://discord.com/api'
discord_authorization_base_url = DISCORD_API_BASE_URL + '/oauth2/authorize'
discord_token_url = DISCORD_API_BASE_URL + '/oauth2/token'
discord_oauth_all_scopes = ['bot', 'connections', 'email', 'identify', 'guilds', 'guilds.join', 'gdm.join', 'messages.read', 'rpc', 'rpc... |
CSRF_ENABLED = True
SECRET_KEY = 'blabla'
DOCUMENTDB_HOST = 'https://mongo-olx.documents.azure.com:443/'
DOCUMENTDB_KEY = 'hJJaII1eaMs2wUHNqvjDkzRF3wOz24x8x/J7+Zfw2D91KM/LTjNXcVg8WgMV2JiaNGuTnsnInSmO8jrqDRGw/g=='
DOCUMENTDB_DATABASE = 'olxDB'
DOCUMENTDB_COLLECTION = 'rentals'
DOCUMENTDB_DOCUMENT = 'rent-doc' | csrf_enabled = True
secret_key = 'blabla'
documentdb_host = 'https://mongo-olx.documents.azure.com:443/'
documentdb_key = 'hJJaII1eaMs2wUHNqvjDkzRF3wOz24x8x/J7+Zfw2D91KM/LTjNXcVg8WgMV2JiaNGuTnsnInSmO8jrqDRGw/g=='
documentdb_database = 'olxDB'
documentdb_collection = 'rentals'
documentdb_document = 'rent-doc' |
class Solution:
def numMovesStones(self, a: int, b: int, c: int) -> List[int]:
temp = [a,b,c]
temp.sort()
d1, d2 = temp[1] - temp[0], temp[2] - temp[1]
if d1 == 1 and d2 == 1:
return [0, 0]
elif d1 == 1 or d2 == 1:
return [1, max(d1, ... | class Solution:
def num_moves_stones(self, a: int, b: int, c: int) -> List[int]:
temp = [a, b, c]
temp.sort()
(d1, d2) = (temp[1] - temp[0], temp[2] - temp[1])
if d1 == 1 and d2 == 1:
return [0, 0]
elif d1 == 1 or d2 == 1:
return [1, max(d1, d2) - 1]
... |
class EmptyLayerError(Exception):
"""
Represent empty layers accessing.
"""
def __init__(self, message="Unable to access empty layers."):
super(EmptyLayerError, self).__init__(message)
| class Emptylayererror(Exception):
"""
Represent empty layers accessing.
"""
def __init__(self, message='Unable to access empty layers.'):
super(EmptyLayerError, self).__init__(message) |
class GST_Company():
def __init__(self, gstno, rate,pos,st):
self.GSTNO = gstno
self.RATE = rate
self.POS=pos
self.ST=st
self.__taxable = 0.00
self.__cgst = 0.00
self.__sgst = 0.00
self.__igst = 0.00
self.__cess = 0
self.__total = 0.00
... | class Gst_Company:
def __init__(self, gstno, rate, pos, st):
self.GSTNO = gstno
self.RATE = rate
self.POS = pos
self.ST = st
self.__taxable = 0.0
self.__cgst = 0.0
self.__sgst = 0.0
self.__igst = 0.0
self.__cess = 0
self.__total = 0.0
... |
"""Results gathered from tests.
Copyright (c) 2019 Red Hat Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program ... | """Results gathered from tests.
Copyright (c) 2019 Red Hat Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program ... |
parameters = {
# Add entry for each state variable to check; number is tolerance
"alpha": 0.0,
"b": 0.0,
"d1c": 0.0,
"d1t": 0.0,
"d2": 0.0,
"fb1": 0.0,
"fb2": 0.0,
"fb3": 0.0,
"nstatev": 0,
"phi0_12": 0.0,
} | parameters = {'alpha': 0.0, 'b': 0.0, 'd1c': 0.0, 'd1t': 0.0, 'd2': 0.0, 'fb1': 0.0, 'fb2': 0.0, 'fb3': 0.0, 'nstatev': 0, 'phi0_12': 0.0} |
class Stack:
def __init__(self):
self.queue = []
def enqueue(self, element):
self.queue
# [3,2,1]
def dequeue(self):
queue_helper = []
while len(self.queue) != 1:
x = self.queue.pop()
queue_helper.append(x)
temp = self.queue.pop()
... | class Stack:
def __init__(self):
self.queue = []
def enqueue(self, element):
self.queue
def dequeue(self):
queue_helper = []
while len(self.queue) != 1:
x = self.queue.pop()
queue_helper.append(x)
temp = self.queue.pop()
while queue_... |
class SRTError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class SRTLoginError(SRTError):
def __init__(self, msg="Login failed, please check ID/PW"):
super().__init__(msg)
class SRTResponseError(SRTError):
def __init__(self, msg):
... | class Srterror(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Srtloginerror(SRTError):
def __init__(self, msg='Login failed, please check ID/PW'):
super().__init__(msg)
class Srtresponseerror(SRTError):
def __init__(self, msg):
... |
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
#
version_info = (0, 15, 0)
__version__ = '%s.%s.%s' % (version_info[0], version_info[1], version_info[2])
EXTENSION_VERSION = '^0.15.0'
| version_info = (0, 15, 0)
__version__ = '%s.%s.%s' % (version_info[0], version_info[1], version_info[2])
extension_version = '^0.15.0' |
"""File Handling."""
# my_file = open('data.txt', 'r')
"""
with open('data.txt', 'r') as data:
print(f'File name: {data.name}')
# for text_line in data.readlines():
# print(text_line, end='')
for line in data:
print(line, end='')
"""
"""
lines = ["This is line 1", "This is lin... | """File Handling."""
"\nwith open('data.txt', 'r') as data:\n print(f'File name: {data.name}')\n # for text_line in data.readlines():\n # print(text_line, end='')\n for line in data:\n print(line, end='')\n"
'\nlines = ["This is line 1", "This is line 2", "This is line 3", "This is line 4"]\nwith... |
#!/usr/bin/env python
log_dir = os.environ['LOG_DIR']
admin_server_listen_address = os.environ['ADMIN_SERVER_LISTEN_ADDRESS']
admin_server_listen_port = os.environ['ADMIN_SERVER_LISTEN_PORT']
admin_username = os.environ['ADMIN_USERNAME']
admin_password = os.environ['ADMIN_PASSWORD']
managed_server_name = os.environ[... | log_dir = os.environ['LOG_DIR']
admin_server_listen_address = os.environ['ADMIN_SERVER_LISTEN_ADDRESS']
admin_server_listen_port = os.environ['ADMIN_SERVER_LISTEN_PORT']
admin_username = os.environ['ADMIN_USERNAME']
admin_password = os.environ['ADMIN_PASSWORD']
managed_server_name = os.environ['MANAGED_SERVER_NAME']
d... |
test = {
'name': 'scheme-def',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
scm> (def f(x y) (+ x y))
f
scm> (f 2 3)
5
scm> (f 10 20)
30
""",
'hidden': False,
'locked': False
},
... | test = {'name': 'scheme-def', 'points': 1, 'suites': [{'cases': [{'code': '\n scm> (def f(x y) (+ x y))\n f\n scm> (f 2 3)\n 5\n scm> (f 10 20)\n 30\n ', 'hidden': False, 'locked': False}, {'code': '\n scm> (def factorial(x) (if (zero? x) 1 (* x (f... |
# -*- coding: utf-8 -*-
def env_comment(env,comment=''):
if env.get('fwuser_info') and not env['fwuser_info'].get('lock'):
env['fwuser_info']['comment'] = comment
env['fwuser_info']['lock'] = True | def env_comment(env, comment=''):
if env.get('fwuser_info') and (not env['fwuser_info'].get('lock')):
env['fwuser_info']['comment'] = comment
env['fwuser_info']['lock'] = True |
balance = 320000
annualInterestRate = 0.2
monthlyInterestRate = (annualInterestRate) / 12
epsilon = 0.01
lowerBound = balance / 12
upperBound = (balance * (1 + monthlyInterestRate)**12) / 12
ans = (upperBound + lowerBound)/2.0
newBalance = balance
while abs(0 - newBalance) >= epsilon:
newBalance = balance
for i... | balance = 320000
annual_interest_rate = 0.2
monthly_interest_rate = annualInterestRate / 12
epsilon = 0.01
lower_bound = balance / 12
upper_bound = balance * (1 + monthlyInterestRate) ** 12 / 12
ans = (upperBound + lowerBound) / 2.0
new_balance = balance
while abs(0 - newBalance) >= epsilon:
new_balance = balance
... |
# DO NOT LOAD THIS FILE. Targets from this file should be considered private
# and not used outside of the @envoy//bazel package.
load(":envoy_select.bzl", "envoy_select_google_grpc", "envoy_select_hot_restart")
# Compute the final copts based on various options.
def envoy_copts(repository, test = False):
posix_op... | load(':envoy_select.bzl', 'envoy_select_google_grpc', 'envoy_select_hot_restart')
def envoy_copts(repository, test=False):
posix_options = ['-Wall', '-Wextra', '-Werror', '-Wnon-virtual-dtor', '-Woverloaded-virtual', '-Wold-style-cast', '-Wvla', '-std=c++14']
msvc_options = ['-WX', '-Zc:__cplusplus', '-std:c++... |
class lazy_property(object):
"""
meant to be used for lazy evaluation of an object attribute.
property should represent non-mutable data, as it replaces itself.
From: http://stackoverflow.com/a/6849299
"""
def __init__(self, fget):
self.fget = fget
self.func_name = fget.__name__... | class Lazy_Property(object):
"""
meant to be used for lazy evaluation of an object attribute.
property should represent non-mutable data, as it replaces itself.
From: http://stackoverflow.com/a/6849299
"""
def __init__(self, fget):
self.fget = fget
self.func_name = fget.__name__... |
#!/usr/bin/env python
# encoding: utf-8
def run(whatweb, pluginname):
whatweb.recog_from_header(pluginname, "django")
| def run(whatweb, pluginname):
whatweb.recog_from_header(pluginname, 'django') |
class AverageMeter:
"""
Class to be an average meter for any average metric like loss, accuracy, etc..
"""
def __init__(self):
self.value = 0
self.avg = 0
self.sum = 0
self.count = 0
self.reset()
def reset(self):
self.value = 0
self.avg = 0
... | class Averagemeter:
"""
Class to be an average meter for any average metric like loss, accuracy, etc..
"""
def __init__(self):
self.value = 0
self.avg = 0
self.sum = 0
self.count = 0
self.reset()
def reset(self):
self.value = 0
self.avg = 0
... |
class Solution:
def checkString(self, s: str) -> bool:
a_indices = [i for i, x in enumerate(s) if x=='a']
try:
if a_indices[-1] > s.index('b'):
return False
except:
pass
return True
| class Solution:
def check_string(self, s: str) -> bool:
a_indices = [i for (i, x) in enumerate(s) if x == 'a']
try:
if a_indices[-1] > s.index('b'):
return False
except:
pass
return True |
"""
99 / 99 test cases passed.
Runtime: 32 ms
Memory Usage: 14.8 MB
"""
class Solution:
def toGoatLatin(self, sentence: str) -> str:
vowel = ['a', 'e', 'i', 'o', 'u']
ans = []
for i, word in enumerate(sentence.split()):
if word[0].lower() in vowel:
ans.append(word... | """
99 / 99 test cases passed.
Runtime: 32 ms
Memory Usage: 14.8 MB
"""
class Solution:
def to_goat_latin(self, sentence: str) -> str:
vowel = ['a', 'e', 'i', 'o', 'u']
ans = []
for (i, word) in enumerate(sentence.split()):
if word[0].lower() in vowel:
ans.appen... |
# -*- coding: utf-8 -*-
"""
Histogram Entities.
@author Hao Song (songhao@vmware.com)
"""
| """
Histogram Entities.
@author Hao Song (songhao@vmware.com)
""" |
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
# Transpose
for i in range(len(matrix)):
for j in range(i+1,len(matrix)):
matrix[j]... | class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
for i in range(len(matrix)):
for j in range(i + 1, len(matrix)):
(matrix[j][i], matrix[i][... |
# [Job Adv] (Lv.30) Way of the Bandit
darkMarble = 4031013
job = "Night Lord"
sm.setSpeakerID(1052001)
if sm.hasItem(darkMarble, 30):
sm.sendNext("I am impressed, you surpassed the test. Only few are talented enough.\r\n"
"You have proven yourself to be worthy, I shall mold your body into a #b... | dark_marble = 4031013
job = 'Night Lord'
sm.setSpeakerID(1052001)
if sm.hasItem(darkMarble, 30):
sm.sendNext('I am impressed, you surpassed the test. Only few are talented enough.\r\nYou have proven yourself to be worthy, I shall mold your body into a #b' + job + '#k.')
else:
sm.sendSayOkay('You have not retrie... |
# -*- coding: utf-8 -*-
"""
db_normalizer.csv_handler
-----------------------------
Folder for the CSV toolbox.
:authors: Bouillon Pierre, Cesari Alexandre.
:licence: MIT, see LICENSE for more details.
""" | """
db_normalizer.csv_handler
-----------------------------
Folder for the CSV toolbox.
:authors: Bouillon Pierre, Cesari Alexandre.
:licence: MIT, see LICENSE for more details.
""" |
INDEX_HEADER_SIZE = 16
INDEX_RECORD_SIZE = 41
META_HEADER_SIZE = 32
kMinMetadataRead = 1024
kChunkSize = 256 * 1024
kMaxElementsSize = 64 * 1024
kAlignSize = 4096 | index_header_size = 16
index_record_size = 41
meta_header_size = 32
k_min_metadata_read = 1024
k_chunk_size = 256 * 1024
k_max_elements_size = 64 * 1024
k_align_size = 4096 |
#!/usr/bin python
dec1 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
enc1 = "EICTDGYIYZKTHNSIRFXYCPFUEOCKRNEICTDGYIYZKTHNSIRFXYCPFUEOCKRNEI"
dec2 = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"
enc2 = "FJDUEHZJZALUIOTJSGYZDQGVFPDLSOFJDUEHZJZALUIOTJSG"
with open("krypton7", 'r') as handle:
... | dec1 = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
enc1 = 'EICTDGYIYZKTHNSIRFXYCPFUEOCKRNEICTDGYIYZKTHNSIRFXYCPFUEOCKRNEI'
dec2 = 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB'
enc2 = 'FJDUEHZJZALUIOTJSGYZDQGVFPDLSOFJDUEHZJZALUIOTJSG'
with open('krypton7', 'r') as handle:
flag = handle.read... |
# -*- coding: utf-8 -*-
class IRI:
MAINNET_COORDINATOR = ''
| class Iri:
mainnet_coordinator = '' |
MAX_FACTOR = 20 # avoid weirdness with python's arbitary integer precision
MAX_WAIT = 60 * 60 # 1 hour
class Backoff():
def __init__(self, initial=None, base=2, exp=2, max=MAX_WAIT, attempts=None):
self._attempts = attempts
self._initial = initial
self._start = base
self._max = m... | max_factor = 20
max_wait = 60 * 60
class Backoff:
def __init__(self, initial=None, base=2, exp=2, max=MAX_WAIT, attempts=None):
self._attempts = attempts
self._initial = initial
self._start = base
self._max = max
self._exp = exp
self._counter = 0
def reset(self... |
def main():
decimal = str(input())
number = float(decimal)
last = int(decimal[-1])
if last == 7:
number += 0.02
elif last % 2 == 1:
number -= 0.09
elif last > 7:
number -= 4
elif last < 4:
number += 6.78
print(f"{number:.2f}")
if __name__ == "__main__... | def main():
decimal = str(input())
number = float(decimal)
last = int(decimal[-1])
if last == 7:
number += 0.02
elif last % 2 == 1:
number -= 0.09
elif last > 7:
number -= 4
elif last < 4:
number += 6.78
print(f'{number:.2f}')
if __name__ == '__main__':
... |
print("Hi, I'm a module!")
raise Exception(
"This module-level exception should also not occur during freeze"
)
| print("Hi, I'm a module!")
raise exception('This module-level exception should also not occur during freeze') |
GENCONF_DIR = 'genconf'
CONFIG_PATH = GENCONF_DIR + '/config.yaml'
SSH_KEY_PATH = GENCONF_DIR + '/ssh_key'
IP_DETECT_PATH = GENCONF_DIR + '/ip-detect'
CLUSTER_PACKAGES_PATH = GENCONF_DIR + '/cluster_packages.json'
SERVE_DIR = GENCONF_DIR + '/serve'
STATE_DIR = GENCONF_DIR + '/state'
BOOTSTRAP_DIR = SERVE_DIR + '/bootst... | genconf_dir = 'genconf'
config_path = GENCONF_DIR + '/config.yaml'
ssh_key_path = GENCONF_DIR + '/ssh_key'
ip_detect_path = GENCONF_DIR + '/ip-detect'
cluster_packages_path = GENCONF_DIR + '/cluster_packages.json'
serve_dir = GENCONF_DIR + '/serve'
state_dir = GENCONF_DIR + '/state'
bootstrap_dir = SERVE_DIR + '/bootst... |
class Solution:
def isStrobogrammatic(self, num: str) -> bool:
rotated = ['0', '1', 'x', 'x', 'x',
'x', '9', 'x', '8', '6']
l = 0
r = len(num) - 1
while l <= r:
if num[l] != rotated[ord(num[r]) - ord('0')]:
return False
l += 1
r -= 1
return True
| class Solution:
def is_strobogrammatic(self, num: str) -> bool:
rotated = ['0', '1', 'x', 'x', 'x', 'x', '9', 'x', '8', '6']
l = 0
r = len(num) - 1
while l <= r:
if num[l] != rotated[ord(num[r]) - ord('0')]:
return False
l += 1
r -... |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 1 16:43:37 2022
@author: LENOVO
"""
list = []
n = 1 #valores del 1 al 100
while n <= 100: #bucle de numeros de 1 al 100
c = 1 # div
x = 0 #contador div
while c <= n:
if n % c == 0:
x = x + 1
c = c + 1
if x == 2:
list... | """
Created on Tue Feb 1 16:43:37 2022
@author: LENOVO
"""
list = []
n = 1
while n <= 100:
c = 1
x = 0
while c <= n:
if n % c == 0:
x = x + 1
c = c + 1
if x == 2:
list.append(n)
n = n + 1
print(' los numeros primos del 1 al 100 son :', list) |
# coding: utf-8
COLORS = {
'green': '\033[22;32m',
'boldblue': '\033[01;34m',
'purple': '\033[22;35m',
'red': '\033[22;31m',
'boldred': '\033[01;31m',
'normal': '\033[0;0m'
}
class Logger:
def __init__(self):
self.verbose = False
@staticmethod
def _print_msg(msg: str, col... | colors = {'green': '\x1b[22;32m', 'boldblue': '\x1b[01;34m', 'purple': '\x1b[22;35m', 'red': '\x1b[22;31m', 'boldred': '\x1b[01;31m', 'normal': '\x1b[0;0m'}
class Logger:
def __init__(self):
self.verbose = False
@staticmethod
def _print_msg(msg: str, color: str=None):
if color is None or ... |
#
# PySNMP MIB module INTELLANDESKSERVERMANAGER-LOCALRESPONSEAMAPPER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/INTELLANDESKSERVERMANAGER-LOCALRESPONSEAMAPPER-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:44:05 2019
# On host DAVWANG4-M-1475 platform Darwin version... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_size_constraint, value_range_constraint, constraints_intersection) ... |
class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
counter = 0
N = len(A) / 2
for a in A:
a_count = A.count(a)
if a_count == N:
return a
counter += a_count
if counter == N:
return A[0]
... | class Solution:
def repeated_n_times(self, A: List[int]) -> int:
counter = 0
n = len(A) / 2
for a in A:
a_count = A.count(a)
if a_count == N:
return a
counter += a_count
if counter == N:
return A[0]
... |
class BitConverter(object):
""" Converts base data types to an array of bytes,and an array of bytes to base data types. """
@staticmethod
def DoubleToInt64Bits(value):
"""
DoubleToInt64Bits(value: float) -> Int64
Converts the specified double-precision floating point number to a... | class Bitconverter(object):
""" Converts base data types to an array of bytes,and an array of bytes to base data types. """
@staticmethod
def double_to_int64_bits(value):
"""
DoubleToInt64Bits(value: float) -> Int64
Converts the specified double-precision floating point number to a 64-bit... |
def extraerVector(matrizPesos, i, dimVect):
vectTemp = []
for j in range(dimVect - 1):
vectTemp.append(matrizPesos[i][j])
return vectTemp | def extraer_vector(matrizPesos, i, dimVect):
vect_temp = []
for j in range(dimVect - 1):
vectTemp.append(matrizPesos[i][j])
return vectTemp |
async def handler(event):
# flush history data
await event.kv.flush()
# string: bit 0
v = await event.kv.setbit('string', 0, 1)
if v != 0:
return {'status': 503, 'body': 'test1 fail!'}
# string: bit 1
v = await event.kv.setbit('string', 0, 1)
if v != 1:
return {'status'... | async def handler(event):
await event.kv.flush()
v = await event.kv.setbit('string', 0, 1)
if v != 0:
return {'status': 503, 'body': 'test1 fail!'}
v = await event.kv.setbit('string', 0, 1)
if v != 1:
return {'status': 503, 'body': 'test2 fail!'}
await event.kv.setbit('string', 7... |
'''
Copyright 2013 CyberPoint International, LLC.
All rights reserved. Use and disclosure prohibited
except as permitted in writing by CyberPoint.
libpgm exception handler
Charlie Cabot
Sept 27 2013
'''
class libpgmError(Exception):
pass
class bntextError(libpgmError):
pass
| """
Copyright 2013 CyberPoint International, LLC.
All rights reserved. Use and disclosure prohibited
except as permitted in writing by CyberPoint.
libpgm exception handler
Charlie Cabot
Sept 27 2013
"""
class Libpgmerror(Exception):
pass
class Bntexterror(libpgmError):
pass |
# In mathematics, the Euclidean algorithm, or Euclid's algorithm, is an efficient method
# for computing the greatest common divisor (GCD) of two integers (numbers), the largest number
# that divides them both without a remainder.
def gcd_by_subtracting(m, n):
"""
Computes the greatest common divisor of two n... | def gcd_by_subtracting(m, n):
"""
Computes the greatest common divisor of two numbers by continuously subtracting the smaller
number from the bigger one till they became equal.
:param int m: First number.
:param int n: Second number.
:returns: GCD as a number.
"""
while m != n:
... |
class CachedLoader(object):
items = {}
@classmethod
def load_compose_definition(cls, loader: callable):
return cls.cached('compose', loader)
@classmethod
def cached(cls, name: str, loader: callable):
if name not in cls.items:
cls.items[name] = loader()
return... | class Cachedloader(object):
items = {}
@classmethod
def load_compose_definition(cls, loader: callable):
return cls.cached('compose', loader)
@classmethod
def cached(cls, name: str, loader: callable):
if name not in cls.items:
cls.items[name] = loader()
return cl... |
print("Welcome to Byeonghoon's Age Calculator. This program provide your or someone's age at the specific date you are enquiring.")
current_day = int(input("Please input the DAY you want to enquire (DD):\n"))
while current_day < 1 or current_day > 31:
print("!", current_day, "is not existing date. Please check your... | print("Welcome to Byeonghoon's Age Calculator. This program provide your or someone's age at the specific date you are enquiring.")
current_day = int(input('Please input the DAY you want to enquire (DD):\n'))
while current_day < 1 or current_day > 31:
print('!', current_day, 'is not existing date. Please check your... |
class AuthSession(object):
def __init__(self, session):
self._session = session
def __enter__(self):
return self._session
def __exit__(self, *args):
self._session.close() | class Authsession(object):
def __init__(self, session):
self._session = session
def __enter__(self):
return self._session
def __exit__(self, *args):
self._session.close() |
"""
Problem 7:
What is the 10 001st prime number?
"""
def is_prime(n):
for i in range(2, n // 2 + 1):
if n % i == 0:
return False
return True
class Prime:
def __init__(self):
self.curr = 1
def __next__(self):
new_next = self.curr + 1
while not is_... | """
Problem 7:
What is the 10 001st prime number?
"""
def is_prime(n):
for i in range(2, n // 2 + 1):
if n % i == 0:
return False
return True
class Prime:
def __init__(self):
self.curr = 1
def __next__(self):
new_next = self.curr + 1
while not is_p... |
# Given the array candies and the integer extraCandies, where candies[i] represents the number of candies that the
# ith kid has.
#
# For each kid check if there is a way to distribute extraCandies among the kids such that he or she can have the
# greatest number of candies among them. Notice that multiple kids can hav... | class Solution:
def kids_with_candies(self, candies, extraCandies):
highest = max(candies)
output_list = []
for i in candies:
total = i + extraCandies
if total >= highest:
output_list.append(True)
else:
output_list.append(F... |
_base_ = './cascade_rcnn_s50_fpn_syncbn-backbone+head_mstrain-range_1x_coco.py'
model = dict(
backbone=dict(
stem_channels=128,
depth=101,
init_cfg=dict(type='Pretrained',
checkpoint='open-mmlab://resnest101')))
| _base_ = './cascade_rcnn_s50_fpn_syncbn-backbone+head_mstrain-range_1x_coco.py'
model = dict(backbone=dict(stem_channels=128, depth=101, init_cfg=dict(type='Pretrained', checkpoint='open-mmlab://resnest101'))) |
description = 'setup for the poller'
group = 'special'
sysconfig = dict(cache = 'mephisto17.office.frm2')
devices = dict(
Poller = device('nicos.services.poller.Poller',
alwayspoll = ['tube_environ', 'pressure'],
blacklist = ['tas']
),
)
| description = 'setup for the poller'
group = 'special'
sysconfig = dict(cache='mephisto17.office.frm2')
devices = dict(Poller=device('nicos.services.poller.Poller', alwayspoll=['tube_environ', 'pressure'], blacklist=['tas'])) |
# Asking Question
print ("How old are you?"),
age = input()
print ("How tall are you?")
height = input()
print ("How much do you weigh?")
weight = input()
print ("So You are %r years old, %r tall and %r heavy."%(age, height , weight)
)
| (print('How old are you?'),)
age = input()
print('How tall are you?')
height = input()
print('How much do you weigh?')
weight = input()
print('So You are %r years old, %r tall and %r heavy.' % (age, height, weight)) |
__copyright__ = 'Copyright (C) 2019, Nokia'
class TestPythonpath2(object):
ROBOT_LIBRARY_SCOPE = "GLOBAL"
def __init__(self):
self.name = 'iina'
self.age = 10
def get_name2(self):
return self.name
| __copyright__ = 'Copyright (C) 2019, Nokia'
class Testpythonpath2(object):
robot_library_scope = 'GLOBAL'
def __init__(self):
self.name = 'iina'
self.age = 10
def get_name2(self):
return self.name |
# -*- coding: utf-8 -*-
"""
Processing a list of power plants in Germany.
SPDX-FileCopyrightText: 2016-2021 Uwe Krien <krien@uni-bremen.de>
SPDX-License-Identifier: MIT
"""
__copyright__ = "Uwe Krien <krien@uni-bremen.de>"
__license__ = "MIT"
# from unittest.mock import MagicMock
# from nose.tools import ok_, eq_
#... | """
Processing a list of power plants in Germany.
SPDX-FileCopyrightText: 2016-2021 Uwe Krien <krien@uni-bremen.de>
SPDX-License-Identifier: MIT
"""
__copyright__ = 'Uwe Krien <krien@uni-bremen.de>'
__license__ = 'MIT' |
class Solution:
"""
@param t: the length of the flight
@param dur: the length of movies
@return: output the lengths of two movies
"""
def aerial_Movie(self, t, dur):
t -= 30
dur.sort()
left = 0
right = len(dur) - 1
longest = 0
longest_pair = None
... | class Solution:
"""
@param t: the length of the flight
@param dur: the length of movies
@return: output the lengths of two movies
"""
def aerial__movie(self, t, dur):
t -= 30
dur.sort()
left = 0
right = len(dur) - 1
longest = 0
longest_pair = None... |
'''
Source : https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
Author : Yuan Wang
Date : 2018-06-02
/**********************************************************************************
*
* Say you have an array for which the ith element is the price of a given stock on day i.
*
* If you were only p... | """
Source : https://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock/
Author : Yuan Wang
Date : 2018-06-02
/**********************************************************************************
*
* Say you have an array for which the ith element is the price of a given stock on day i.
*
* If you were only p... |
# 1. Escreva uma funcao que recebe como entrada as dimensoes M e N e o elemento E de preenchimento
# e retorna uma lista de listas que corresponde a uma matriz MxN contendo o elemento e em todas
# as posicoes. Exemplo:
# >>> cria_matriz(2, 3, 0)
# [[0, 0, 0], [0, 0, 0]]
def f_preencheMatriz(m, n, el):
matrizPreen... | def f_preenche_matriz(m, n, el):
matriz_preenchida = []
for lin in range(m):
matrizPreenchida.append([])
for col in range(n):
matrizPreenchida[lin].append(el)
return matrizPreenchida
def main():
(m, n, el, matriz) = (0, 0, 0, [])
m = int(input('Informe a qtd de linhas da... |
'''
Python program to compute and print sum of two given integers (more than or equal to zero).
If given integers or the sum have more than 80 digits, print "overflow".
'''
print ("Input first integer:")
x = int (input())
print ("Input second integer:")
y = int (input())
if x >= 10 ** 80 or y >= 10 ** 80 or x + y >= ... | """
Python program to compute and print sum of two given integers (more than or equal to zero).
If given integers or the sum have more than 80 digits, print "overflow".
"""
print('Input first integer:')
x = int(input())
print('Input second integer:')
y = int(input())
if x >= 10 ** 80 or y >= 10 ** 80 or x + y >= 10 **... |
### Caesar Cipher - Solution
def caesarCipher(s, rot_count):
for ch in range(len(s)):
if s[ch].isalpha():
first_letter = 'A' if s[ch].isupper() else 'a'
s[ch] = chr(ord(first_letter) + ((ord(s[ch]) - ord(first_letter) + rot_count) % 26))
print(*s, sep='')
n = int(input())
s = l... | def caesar_cipher(s, rot_count):
for ch in range(len(s)):
if s[ch].isalpha():
first_letter = 'A' if s[ch].isupper() else 'a'
s[ch] = chr(ord(first_letter) + (ord(s[ch]) - ord(first_letter) + rot_count) % 26)
print(*s, sep='')
n = int(input())
s = list(input()[:n])
rot_count = int... |
# source: https://github.com/brownie-mix/upgrades-mix/blob/main/scripts/helpful_scripts.py
def encode_function_data(*args, initializer=None):
"""Encodes the function call so we can work with an initializer.
Args:
initializer ([brownie.network.contract.ContractTx], optional):
The initialize... | def encode_function_data(*args, initializer=None):
"""Encodes the function call so we can work with an initializer.
Args:
initializer ([brownie.network.contract.ContractTx], optional):
The initializer function we want to call. Example: `box.store`.
Defaults to None.
args (Any, op... |
# atributos publicos, privados y protegidos
class MiClase:
def __init__(self):
self.atributo_publico = "valor publico"
self._atributo_protegido = "valor protegido"
self.__atributo_privado = "valor privado"
objeto1 = MiClase()
# acceso a los atributos publicos
print(objeto1.atribut... | class Miclase:
def __init__(self):
self.atributo_publico = 'valor publico'
self._atributo_protegido = 'valor protegido'
self.__atributo_privado = 'valor privado'
objeto1 = mi_clase()
print(objeto1.atributo_publico)
objeto1.atributo_publico = 'otro valor'
print(objeto1.atributo_publico)
prin... |
class Schemas:
"""
Class that contains DATABASE schema names.
"""
chemprop_schema = "sbox_rlougee_chemprop"
dsstox_schema = "ro_20191118_dsstox"
qsar_schema = "sbox_mshobair_qsar_snap"
invitrodb_schema = "prod_internal_invitrodb_v3_3"
information_schema = "information_schema"
| class Schemas:
"""
Class that contains DATABASE schema names.
"""
chemprop_schema = 'sbox_rlougee_chemprop'
dsstox_schema = 'ro_20191118_dsstox'
qsar_schema = 'sbox_mshobair_qsar_snap'
invitrodb_schema = 'prod_internal_invitrodb_v3_3'
information_schema = 'information_schema' |
# inheritance - 2 - normal methods
class Person():
def details(self):
print("Can have information specific to the person")
class Student(Person):
def details(self):
super().details()
print("Can have information specific to the student")
s = Student()
s.details()
| class Person:
def details(self):
print('Can have information specific to the person')
class Student(Person):
def details(self):
super().details()
print('Can have information specific to the student')
s = student()
s.details() |
# 255: '11111111'
# 65536: '10000000000000000'
# 16777215: '111111111111111111111111'
d = 0
a = 8307757
while (d != a):
c = d | 0x10000
d = 14070682
while True:
d = (((d + (c & 0xFF)) & 0xFFFFFF) * 65899) & 0xFFFFFF
if 256 > c:
break
c //= 256
print("Program halts")
| d = 0
a = 8307757
while d != a:
c = d | 65536
d = 14070682
while True:
d = (d + (c & 255) & 16777215) * 65899 & 16777215
if 256 > c:
break
c //= 256
print('Program halts') |
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
i... | """
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Node') -> 'Node':
... |
'''
You may have noticed that the medals are ordered according to a lexicographic (dictionary) ordering: Bronze < Gold < Silver. However, you would prefer an ordering consistent with the Olympic rules: Bronze < Silver < Gold.
You can achieve this using Categorical types. In this final exercise, after redefining the 'M... | """
You may have noticed that the medals are ordered according to a lexicographic (dictionary) ordering: Bronze < Gold < Silver. However, you would prefer an ordering consistent with the Olympic rules: Bronze < Silver < Gold.
You can achieve this using Categorical types. In this final exercise, after redefining the 'M... |
class Node(object):
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.value)
class BinaryNode():
d... | class Node(object):
def __init__(self, value):
self.value = value
self.next = None
self.prev = None
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.value)
class Binarynode:
de... |
def getNextPowerof2(num):
power = 1
while(power < num):
power *= 2
return power
def buildWalshTable(wTable, length, i1,i2, j1,j2, isComplement):
if length == 2:
if not isComplement:
wTable[i1][j1] = 1
wTable[i1][j2] = 1
wTable[i2][j1] = 1
... | def get_next_powerof2(num):
power = 1
while power < num:
power *= 2
return power
def build_walsh_table(wTable, length, i1, i2, j1, j2, isComplement):
if length == 2:
if not isComplement:
wTable[i1][j1] = 1
wTable[i1][j2] = 1
wTable[i2][j1] = 1
... |
"""
Number to Words
"""
UP_TO_TWENTY = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten","Eleven",
"Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"]
TENS = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "... | """
Number to Words
"""
up_to_twenty = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninet... |
class Credential:
"""
Class that generates new instances of credentials.
"""
credential_list = [] # Empty credential list
def __init__(self, account_name, account_user_name, account_password):
"""
__init__ method that helps us define properties for our objects.
"""
... | class Credential:
"""
Class that generates new instances of credentials.
"""
credential_list = []
def __init__(self, account_name, account_user_name, account_password):
"""
__init__ method that helps us define properties for our objects.
"""
self.account_name = accou... |
#
# 1021. Remove Outermost Parentheses
#
# Q: https://leetcode.com/problems/remove-outermost-parentheses/
# A: https://leetcode.com/problems/remove-outermost-parentheses/discuss/275804/Javascript-Python3-C%2B%2B-Stack-solutions
#
class Solution:
def removeOuterParentheses(self, parens: str) -> str:
s, x = ... | class Solution:
def remove_outer_parentheses(self, parens: str) -> str:
(s, x) = ([], [])
for c in parens:
if c == ')':
s.pop()
if len(s):
x.append(c)
if c == '(':
s.append(c)
return ''.join(x) |
"""
[2014-12-3] Challenge #191 [Intermediate] Space Probe. Alright Alright Alright.
https://www.reddit.com/r/dailyprogrammer/comments/2o5tb7/2014123_challenge_191_intermediate_space_probe/
#Description:
NASA has contracted you to program the AI of a new probe. This new probe must navigate space from a starting locati... | """
[2014-12-3] Challenge #191 [Intermediate] Space Probe. Alright Alright Alright.
https://www.reddit.com/r/dailyprogrammer/comments/2o5tb7/2014123_challenge_191_intermediate_space_probe/
#Description:
NASA has contracted you to program the AI of a new probe. This new probe must navigate space from a starting locati... |
# QUESTION
"""
Given an array A[] of size n. The task is to find the largest element in it.
Example 1:
Input:
n = 5
A[] = {1, 8, 7, 56, 90}
Output:
90
Explanation:
The largest element of given array is 90.
Example 2:
Input:
n = 7
A[] = {1, 2, 0, 3, 2, 4, 5}
Output:
5
Explanation:
The largest element of given array... | """
Given an array A[] of size n. The task is to find the largest element in it.
Example 1:
Input:
n = 5
A[] = {1, 8, 7, 56, 90}
Output:
90
Explanation:
The largest element of given array is 90.
Example 2:
Input:
n = 7
A[] = {1, 2, 0, 3, 2, 4, 5}
Output:
5
Explanation:
The largest element of given array is 5.
Y... |
{'983ab651-eb86-4471-8361-c97a5015637e': ('eb86', 'gcpuujtn5ydu', 'SW3', 'Chelsea', ['Chelsea'], (51.491239, -0.16875000000000001)),
'83f496df-fcc8-4dcf-8161-a60a75364cf2': ('fcc8', 'gcpuwf1xsv7d', 'SE26', 'Sydenham', ['Sydenham'], (51.428317999999997, -0.052663000000000001)),
'31f90575-7945-4999-b3a7-5045bb860302': ('... | {'983ab651-eb86-4471-8361-c97a5015637e': ('eb86', 'gcpuujtn5ydu', 'SW3', 'Chelsea', ['Chelsea'], (51.491239, -0.16875)), '83f496df-fcc8-4dcf-8161-a60a75364cf2': ('fcc8', 'gcpuwf1xsv7d', 'SE26', 'Sydenham', ['Sydenham'], (51.428318, -0.052663)), '31f90575-7945-4999-b3a7-5045bb860302': ('7945', 'gcpuwqsv468q', 'SE22', 'E... |
"""Hackerrank Problems"""
def staircase(n):
"""Print right justified staircase usings spaces and hashes"""
for row in range(n):
n_hashes = row + 1
n_spaces = n - n_hashes
print(" " * n_spaces, end="")
print("#" * n_hashes)
| """Hackerrank Problems"""
def staircase(n):
"""Print right justified staircase usings spaces and hashes"""
for row in range(n):
n_hashes = row + 1
n_spaces = n - n_hashes
print(' ' * n_spaces, end='')
print('#' * n_hashes) |
"""Specialized mobject base classes.
Modules
=======
.. autosummary::
:toctree: ../reference
~image_mobject
~point_cloud_mobject
~vectorized_mobject
"""
| """Specialized mobject base classes.
Modules
=======
.. autosummary::
:toctree: ../reference
~image_mobject
~point_cloud_mobject
~vectorized_mobject
""" |
def mayor(a,b):
if(a>b):
print("a es mayor que b")
mayor(4,3)
mayor(0,-1)
mayor(9,9) | def mayor(a, b):
if a > b:
print('a es mayor que b')
mayor(4, 3)
mayor(0, -1)
mayor(9, 9) |
class TextureType:
PLAYER = 0
HOUSE_INTERIOR = 1
GROCERY_STORE_INTERIOR = 2
VEHICLE = 3
SINK = 4
SHOPPING_CART = 5
DOG = 6
FOOD = 7
SOAP = 8
HAND_SANITIZER = 9
TOILET_PAPER = 10
MASK = 11
PET_SUPPLIES = 12
AISLE = 13
DOOR = 14
HOUSE_EXTERIOR = 15
STORE_EXTERIOR = 16
SELF_CHECKOUT = 17
CLOSET = 18
C... | class Texturetype:
player = 0
house_interior = 1
grocery_store_interior = 2
vehicle = 3
sink = 4
shopping_cart = 5
dog = 6
food = 7
soap = 8
hand_sanitizer = 9
toilet_paper = 10
mask = 11
pet_supplies = 12
aisle = 13
door = 14
house_exterior = 15
store... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.