content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# This is where all of our model classes are defined
class PhysicalAttributes:
def __init__(self, width=None, height=None, depth=None, dimensions=None, mass=None):
self.width = width
self.height = height
self.depth = depth
self.dimensions = dimensions
self.mass = mass
... | class Physicalattributes:
def __init__(self, width=None, height=None, depth=None, dimensions=None, mass=None):
self.width = width
self.height = height
self.depth = depth
self.dimensions = dimensions
self.mass = mass
def serialize(self):
return {'width': self.wid... |
class Identifier(object):
def __init__(self, name, value, declared=False, id_type=None, constant=False):
self.name = name
self.value = value
self.declared = declared
self.type = id_type
self.constant = constant
def __str__(self):
return self.name | class Identifier(object):
def __init__(self, name, value, declared=False, id_type=None, constant=False):
self.name = name
self.value = value
self.declared = declared
self.type = id_type
self.constant = constant
def __str__(self):
return self.name |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 28 21:34:17 2017
@author: chen
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
# class Solution(object):
# def hasCycle(self, head):
# """
# :type head: ListNod... | """
Created on Thu Dec 28 21:34:17 2017
@author: chen
"""
class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def has_cycle(self, head: ListNode) -> bool:
if head is None:
return False
slow = fast = head
while fast... |
def mostra_adicionais(*args):
telaProduto = args[0]
cursor = args[1]
QtWidgets = args[2]
telaProduto.frame_adc.show()
listaAdc = []
sql1 = ("select * from adcBroto")
cursor.execute(sql1)
dados1 = cursor.fetchall()
sql2 = ("select * from adcSeis ")
cursor.execute(sql2)
dados... | def mostra_adicionais(*args):
tela_produto = args[0]
cursor = args[1]
qt_widgets = args[2]
telaProduto.frame_adc.show()
lista_adc = []
sql1 = 'select * from adcBroto'
cursor.execute(sql1)
dados1 = cursor.fetchall()
sql2 = 'select * from adcSeis '
cursor.execute(sql2)
dados2 =... |
"""
describe all supported datasets.
"""
DATASET_LSUN = 0x00010000
DATASET_LSUN_BEDROOM_TRAINING = DATASET_LSUN + 0x00000000
DATASET_LSUN_BEDROOM_VALIDATION = DATASET_LSUN + 0x00000001
DATASET_LSUN_BRIDGE_TRAINING = DATASET_LSUN + 0x00000002
DATASET_LSUN_BRIDGE_VALIDATION = DATASET_LSUN + 0x00000003
DATASET_LSUN_CHUR... | """
describe all supported datasets.
"""
dataset_lsun = 65536
dataset_lsun_bedroom_training = DATASET_LSUN + 0
dataset_lsun_bedroom_validation = DATASET_LSUN + 1
dataset_lsun_bridge_training = DATASET_LSUN + 2
dataset_lsun_bridge_validation = DATASET_LSUN + 3
dataset_lsun_church_outdoor_training = DATASET_LSUN + 4
data... |
#!/usr/bin/env pyrate
foo_obj = object_file('foo_obj', ['foo.cpp'], compiler_opts = '-O3')
executable('example07.bin', ['test.cpp', foo_obj])
| foo_obj = object_file('foo_obj', ['foo.cpp'], compiler_opts='-O3')
executable('example07.bin', ['test.cpp', foo_obj]) |
#! /usr/bin/python
Ada, C, GUI, SIMULINK, VHDL, OG, RTDS, SYSTEM_C, SCADE6, VDM, CPP = range(11)
thread, passive, unknown = range(3)
PI, RI = range(2)
synch, asynch = range(2)
param_in, param_out = range(2)
UPER, NATIVE, ACN = range(3)
cyclic, sporadic, variator, protected, unprotected = range(5)
enumerated, sequenceo... | (ada, c, gui, simulink, vhdl, og, rtds, system_c, scade6, vdm, cpp) = range(11)
(thread, passive, unknown) = range(3)
(pi, ri) = range(2)
(synch, asynch) = range(2)
(param_in, param_out) = range(2)
(uper, native, acn) = range(3)
(cyclic, sporadic, variator, protected, unprotected) = range(5)
(enumerated, sequenceof, se... |
# Copyright 2019 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
PYTHON_VERSION_COMPATIBILITY = 'PY2+3'
DEPS = [
'futures',
'step',
]
def RunSteps(api):
futures = []
for i in range(10):
def _runne... | python_version_compatibility = 'PY2+3'
deps = ['futures', 'step']
def run_steps(api):
futures = []
for i in range(10):
def _runner(i):
api.step('sleep loop [%d]' % (i + 1), ['python3', '-u', api.resource('sleep_loop.py'), i], cost=api.step.ResourceCost())
return i + 1
f... |
"""
hello module
"""
__version__ = '0.7.0dev'
| """
hello module
"""
__version__ = '0.7.0dev' |
'''Defines the `google_java_format_toolchain` rule.
'''
GoogleJavaFormatToolchainInfo = provider(
fields = {
"google_java_format_deploy_jar": "A JAR `File` containing Google Java Format and all of its run-time dependencies.",
"colordiff_executable": "A `File` pointing to `colordiff` executable (in ... | """Defines the `google_java_format_toolchain` rule.
"""
google_java_format_toolchain_info = provider(fields={'google_java_format_deploy_jar': 'A JAR `File` containing Google Java Format and all of its run-time dependencies.', 'colordiff_executable': 'A `File` pointing to `colordiff` executable (in the host configuratio... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
DOCUMENTATION = """
---
module: lilatomic.api.http
short_description: A nice and friendly HTTP API
description:
- An easy way to use the [requests](https://docs.python-requests.org/en/master/) library to make HTTP requests
- Define connections and re-use them across tasks... | documentation = '\n---\nmodule: lilatomic.api.http\nshort_description: A nice and friendly HTTP API\ndescription:\n - An easy way to use the [requests](https://docs.python-requests.org/en/master/) library to make HTTP requests\n - Define connections and re-use them across tasks\nversion_added: "0.1.0"\noptions:\n co... |
def getScore(savings, monthly, bills, cost, payDay):
score = 0
if cost > savings:
score = 0
elif savings < 1000:
score = savings/pow(cost,1.1)
else:
a = savings/(cost*1.1)
score += (1300*(monthly-bills))/(max(1,a)*pow(cost,1.1)*pow(payDay,0.8)) + (30*savings)/(p... | def get_score(savings, monthly, bills, cost, payDay):
score = 0
if cost > savings:
score = 0
elif savings < 1000:
score = savings / pow(cost, 1.1)
else:
a = savings / (cost * 1.1)
score += 1300 * (monthly - bills) / (max(1, a) * pow(cost, 1.1) * pow(payDay, 0.8)) + 30 * s... |
#!/usr/bin/env python
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the 'License');
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... | """Test instances data."""
fake_api_response1 = [{'kind': 'compute#instance', 'id': '6440513679799924564', 'creationTimestamp': '2017-05-26T22:08:11.094-07:00', 'name': 'iap-ig-79bj', 'tags': {'items': ['iap-tag'], 'fingerprint': 'gilEhx3hEXk='}, 'machineType': 'https://www.googleapis.com/compute/v1/projects/project1/z... |
# coding: utf-8
##########################################################################
# NSAp - Copyright (C) CEA, 2019
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for det... | version_major = 0
version_minor = 0
version_micro = 5
__version__ = '{0}.{1}.{2}'.format(version_major, version_minor, version_micro)
classifiers = ['Development Status :: 1 - Planning', 'Environment :: Console', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Scientific/Engineering']
... |
s=input("Enter string: ")
word=s.split()
word=list(reversed(word))
print("OUTPUT: ",end="")
print(" ".join(word)) | s = input('Enter string: ')
word = s.split()
word = list(reversed(word))
print('OUTPUT: ', end='')
print(' '.join(word)) |
# encoding: utf-8
__author__ = "Patrick Lampe"
__email__ = "uni at lampep.de"
class Point:
def __init__(self, id, location):
self.id = id
self.location = location
def getId(self):
return self.id
def get_distance_in_m(self, snd_node):
return self.get_distance_in_km(snd_n... | __author__ = 'Patrick Lampe'
__email__ = 'uni at lampep.de'
class Point:
def __init__(self, id, location):
self.id = id
self.location = location
def get_id(self):
return self.id
def get_distance_in_m(self, snd_node):
return self.get_distance_in_km(snd_node) * 1000
de... |
"""
Error and Exceptions in the SciTokens library
"""
class MissingKeyException(Exception):
"""
No private key is present.
The SciToken required the use of a public or private key, but
it was not provided by the caller.
"""
pass
class UnsupportedKeyException(Exception):
"""
Key is pre... | """
Error and Exceptions in the SciTokens library
"""
class Missingkeyexception(Exception):
"""
No private key is present.
The SciToken required the use of a public or private key, but
it was not provided by the caller.
"""
pass
class Unsupportedkeyexception(Exception):
"""
Key is pre... |
# Given a linked list, remove the n-th node from the end of list and return its head.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int):
# maintaining dummy to resolve edge cases
... | class Listnode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def remove_nth_from_end(self, head: ListNode, n: int):
dummy = list_node(0)
dummy.next = head
(prev_ptr, next_ptr) = (dummy, dummy)
for i in range(n + 1):
... |
def bmi_calculator(weight, height):
'''
Function calculates bmi according to passed arguments
weight (int or float) = weight of the person; ex: 61 or 61.0 kg
height (float) = height of the person, in meter; ex: 1.7 m
'''
bmi = weight / (height**2)
return bmi | def bmi_calculator(weight, height):
"""
Function calculates bmi according to passed arguments
weight (int or float) = weight of the person; ex: 61 or 61.0 kg
height (float) = height of the person, in meter; ex: 1.7 m
"""
bmi = weight / height ** 2
return bmi |
class VertexWeightProximityModifier:
falloff_type = None
mask_constant = None
mask_tex_map_object = None
mask_tex_mapping = None
mask_tex_use_channel = None
mask_tex_uv_layer = None
mask_texture = None
mask_vertex_group = None
max_dist = None
min_dist = None
proximity_geometr... | class Vertexweightproximitymodifier:
falloff_type = None
mask_constant = None
mask_tex_map_object = None
mask_tex_mapping = None
mask_tex_use_channel = None
mask_tex_uv_layer = None
mask_texture = None
mask_vertex_group = None
max_dist = None
min_dist = None
proximity_geometr... |
class Solution:
def trimMean(self, arr: List[int]) -> float:
count = int(len(arr) * 0.05)
arr = sorted(arr)[count:-count]
return sum(arr) / len(arr)
| class Solution:
def trim_mean(self, arr: List[int]) -> float:
count = int(len(arr) * 0.05)
arr = sorted(arr)[count:-count]
return sum(arr) / len(arr) |
class Solution:
# @return a list of integers
def getRow(self, rowIndex):
row = []
for i in range(rowIndex+1):
n = i+1
tmp = [1]*n
for j in range(1, n-1):
tmp[j] = row[j-1] + row[j]
row = tmp
return row
| class Solution:
def get_row(self, rowIndex):
row = []
for i in range(rowIndex + 1):
n = i + 1
tmp = [1] * n
for j in range(1, n - 1):
tmp[j] = row[j - 1] + row[j]
row = tmp
return row |
def get_twos_sum(result, arr):
i, k = 0, len(arr) - 1
while i < k:
a, b = arr[i], arr[k]
res = a + b
if res == result:
return (a, b)
elif res < result:
i += 1
else:
k -= 1
def get_threes_sum(result, arr):
arr.sort()
for i in r... | def get_twos_sum(result, arr):
(i, k) = (0, len(arr) - 1)
while i < k:
(a, b) = (arr[i], arr[k])
res = a + b
if res == result:
return (a, b)
elif res < result:
i += 1
else:
k -= 1
def get_threes_sum(result, arr):
arr.sort()
for... |
# Skill: Bitwise XOR
#Given an array of integers, arr, where all numbers occur twice except one number which occurs once, find the number. Your solution should ideally be O(n) time and use constant extra space.
#Example:
#Input: arr = [7, 3, 5, 5, 4, 3, 4, 8, 8]
#Output: 7
#Analysis
# Exploit the question of all numbe... | class Solution(object):
def find_single(self, nums):
tmp = 0
for n in nums:
tmp = tmp ^ n
return tmp
if __name__ == '__main__':
nums = [1, 1, 3, 4, 4, 5, 6, 5, 6]
print(solution().findSingle(nums)) |
email = input("What is your email id ").strip()
user_name = email[:email.index('@')]
domain_name = email[email.index('@')+1:]
result = "Your username is '{}' and your domain is '{}'".format(user_name, domain_name)
print(result)
| email = input('What is your email id ').strip()
user_name = email[:email.index('@')]
domain_name = email[email.index('@') + 1:]
result = "Your username is '{}' and your domain is '{}'".format(user_name, domain_name)
print(result) |
def step(part, instruction, pos, dir):
c, n = instruction
if c in "FNEWS":
change = {"N": 1j, "E": 1, "W": -1, "S": -1j, "F": dir}[c] * n
if c == "F" or part == 1:
return pos + change, dir
else:
return pos, dir + change
else:
return pos, dir * (1j - 2j... | def step(part, instruction, pos, dir):
(c, n) = instruction
if c in 'FNEWS':
change = {'N': 1j, 'E': 1, 'W': -1, 'S': -1j, 'F': dir}[c] * n
if c == 'F' or part == 1:
return (pos + change, dir)
else:
return (pos, dir + change)
else:
return (pos, dir * (... |
#!/usr/bin/env python
# coding: utf-8
def mi_funcion():
print("una funcion")
class MiClase:
def __init__(self):
print ("una clase")
print ("un modulo") | def mi_funcion():
print('una funcion')
class Miclase:
def __init__(self):
print('una clase')
print('un modulo') |
NON_RELATION_TAG = "NonRel"
BRAT_REL_TEMPLATE = "R{}\t{} Arg1:{} Arg2:{}"
EN1_START = "[s1]"
EN1_END = "[e1]"
EN2_START = "[s2]"
EN2_END = "[e2]"
SPEC_TAGS = [EN1_START, EN1_END, EN2_START, EN2_END] | non_relation_tag = 'NonRel'
brat_rel_template = 'R{}\t{} Arg1:{} Arg2:{}'
en1_start = '[s1]'
en1_end = '[e1]'
en2_start = '[s2]'
en2_end = '[e2]'
spec_tags = [EN1_START, EN1_END, EN2_START, EN2_END] |
class InvalidEpubException(Exception):
'''Exception class to hold errors that occur during processing of an ePub file'''
archive = None
def __init__(self, *args, **kwargs):
if 'archive' in kwargs:
self.archive = kwargs['archive']
super(InvalidEpubException, self... | class Invalidepubexception(Exception):
"""Exception class to hold errors that occur during processing of an ePub file"""
archive = None
def __init__(self, *args, **kwargs):
if 'archive' in kwargs:
self.archive = kwargs['archive']
super(InvalidEpubException, self).__init__(*args) |
S = input()
if S == 'RRR':
print(3)
elif S.find('RR') != -1:
print(2)
elif S == 'SSS':
print(0)
else:
print(1) | s = input()
if S == 'RRR':
print(3)
elif S.find('RR') != -1:
print(2)
elif S == 'SSS':
print(0)
else:
print(1) |
class SpecialOffer:
""" Represents a special offer that can be done by a supermarket.
Attributes:
count(int): number of items needed to perform the special offer.
price(int): new price for the count of items.
free_item(<StockKeepingUnit>): the special offer instead of a different price... | class Specialoffer:
""" Represents a special offer that can be done by a supermarket.
Attributes:
count(int): number of items needed to perform the special offer.
price(int): new price for the count of items.
free_item(<StockKeepingUnit>): the special offer instead of a different price ... |
"""
Wrappers for the `torch.nn.Module` class, and can be used to parameterize policy
functions, value functions, cost functions, etc. for use in reinforcement
learning and imitation learning algorithms.
To create a custom network, see `BaseNetwork` for more details.
""" | """
Wrappers for the `torch.nn.Module` class, and can be used to parameterize policy
functions, value functions, cost functions, etc. for use in reinforcement
learning and imitation learning algorithms.
To create a custom network, see `BaseNetwork` for more details.
""" |
# These are the compilation flags that will be used in case there's no
# compilation database set.
flags = [
'-Wall',
'-Wextra',
'-std=c++14',
'-stdlib=libc++',
'-x', 'c++',
'-I', '.',
'-I', 'include',
'-isystem', '/usr/include/c++/v1',
'-isystem', '/usr/include'
]
def FlagsForFile... | flags = ['-Wall', '-Wextra', '-std=c++14', '-stdlib=libc++', '-x', 'c++', '-I', '.', '-I', 'include', '-isystem', '/usr/include/c++/v1', '-isystem', '/usr/include']
def flags_for_file(filename):
return {'flags': flags, 'do_cache': True} |
# Link to the problem: http://www.spoj.com/problems/ANARC09A/
def main():
n = input()
count = 1
while n[0] != '-':
o, c, ans = 0, 0, 0
for i in n:
if i == '{':
o += 1
elif i == '}':
if o > 0:
o -= 1
... | def main():
n = input()
count = 1
while n[0] != '-':
(o, c, ans) = (0, 0, 0)
for i in n:
if i == '{':
o += 1
elif i == '}':
if o > 0:
o -= 1
else:
c += 1
ans += o // 2 + c ... |
"""
@author Yuto Watanabe
@version 1.0.0
Copyright (c) 2020 Yuto Watanabe
"""
| """
@author Yuto Watanabe
@version 1.0.0
Copyright (c) 2020 Yuto Watanabe
""" |
class RunResultError(Exception):
"""Exception thrown when running a command fails"""
def __init__(self, runresult):
super(RunResultError, self).__init__(str(runresult))
self.runresult = runresult
class MatchError(Exception):
"""Exception for output match errors"""
def __init__(self, ... | class Runresulterror(Exception):
"""Exception thrown when running a command fails"""
def __init__(self, runresult):
super(RunResultError, self).__init__(str(runresult))
self.runresult = runresult
class Matcherror(Exception):
"""Exception for output match errors"""
def __init__(self, m... |
# Credits:
# 1) https://gist.github.com/evansneath/4650991
# 2) https://www.tutorialspoint.com/How-to-convert-string-to-binary-in-Python
def crc(msg, div, code='000'):
# Append the code to the message. If no code is given, default to '000'
msg = msg + code
# Convert msg and div into list form for easier ... | def crc(msg, div, code='000'):
msg = msg + code
msg = list(msg)
div = list(div)
for i in range(len(msg) - len(code)):
if msg[i] == '1':
for j in range(len(div)):
msg[i + j] = str(int(msg[i + j]) ^ int(div[j]))
return ''.join(msg[-len(code):])
print("Sender's side.... |
class Employee:
"""This class represents employees in a company """
num_of_employees = 0 #public static attribute
# init method or constructor
def __init__(self , first , last , pay):
self._first = first #protected Attribute
self._last = last #protected Attribute
self._pay = pay... | class Employee:
"""This class represents employees in a company """
num_of_employees = 0
def __init__(self, first, last, pay):
self._first = first
self._last = last
self._pay = pay
Employee.num_of_employees += 1
@property
def full_name(self) -> str:
return f... |
class HDateException(Exception):
pass
class HMoneyException(Exception):
pass
class Dict_Exception(Exception):
pass
| class Hdateexception(Exception):
pass
class Hmoneyexception(Exception):
pass
class Dict_Exception(Exception):
pass |
"""
**qecsimext** is an example Python 3 package that extends `qecsim`_ with additional components.
See the README at `qecsimext`_ for details.
.. _qecsim: https://github.com/qecsim/qecsim
.. _qecsimext: https://github.com/qecsim/qecsimext
"""
__version__ = '0.1b9'
| """
**qecsimext** is an example Python 3 package that extends `qecsim`_ with additional components.
See the README at `qecsimext`_ for details.
.. _qecsim: https://github.com/qecsim/qecsim
.. _qecsimext: https://github.com/qecsim/qecsimext
"""
__version__ = '0.1b9' |
# -*- coding: utf-8 -*-
__author__ = 'PCPC'
sumList = [n for n in range(1000) if n%3==0 or n%5==0]
print(sum(sumList)) | __author__ = 'PCPC'
sum_list = [n for n in range(1000) if n % 3 == 0 or n % 5 == 0]
print(sum(sumList)) |
def factory(x):
def fn():
return x
return fn
a1 = factory("foo")
a2 = factory("bar")
print(a1())
print(a2())
| def factory(x):
def fn():
return x
return fn
a1 = factory('foo')
a2 = factory('bar')
print(a1())
print(a2()) |
""" var object
this is for storing system variables
"""
class Var(object):
@classmethod
def fetch(cls,name):
"fetch var with given name"
return cls.list(name=name)[0]
@classmethod
def next(cls,name,advance=True):
"give (and, if advance, then increment) a counter variable"
v=cls.fetch(name)
... | """ var object
this is for storing system variables
"""
class Var(object):
@classmethod
def fetch(cls, name):
"""fetch var with given name"""
return cls.list(name=name)[0]
@classmethod
def next(cls, name, advance=True):
"""give (and, if advance, then increment) a counter var... |
def find_pivot(arr, low, high):
if high < low:
return -1
if high == low:
return low
mid = int((low + high)/2)
if mid < high and arr[mid] > arr[mid + 1]:
return mid
if mid > low and arr[mid] < arr[mid - 1]:
return mid-1
if arr[low] >= arr[mid]:
return fin... | def find_pivot(arr, low, high):
if high < low:
return -1
if high == low:
return low
mid = int((low + high) / 2)
if mid < high and arr[mid] > arr[mid + 1]:
return mid
if mid > low and arr[mid] < arr[mid - 1]:
return mid - 1
if arr[low] >= arr[mid]:
return f... |
_base_ = './pascal_voc12.py'
# dataset settings
data = dict(
train=dict(
ann_dir='SegmentationClassAug',
split=[
'ImageSets/Segmentation/train.txt',
'ImageSets/Segmentation/aug.txt'
]
),
val=dict(
ann_dir='SegmentationClassAug',
),
test=dict(
... | _base_ = './pascal_voc12.py'
data = dict(train=dict(ann_dir='SegmentationClassAug', split=['ImageSets/Segmentation/train.txt', 'ImageSets/Segmentation/aug.txt']), val=dict(ann_dir='SegmentationClassAug'), test=dict(ann_dir='SegmentationClassAug')) |
"""
# Useful git config for working with git submodules in this repo
(
git config status.submodulesummary 1
git config push.recurseSubmodules check
git config diff.submodule log
git config checkout.recurseSubmodules 1
git config alias.sdiff '!'"git diff && git submodule foreach 'git diff'"
git config alias.spush... | """
# Useful git config for working with git submodules in this repo
(
git config status.submodulesummary 1
git config push.recurseSubmodules check
git config diff.submodule log
git config checkout.recurseSubmodules 1
git config alias.sdiff '!'"git diff && git submodule foreach 'git diff'"
git config alias.spush ... |
def out(status, message, padding=0, custom=None):
if status == '?':
return input(
' ' * padding
+ '\033[1;36m'
+ '[?]'
+ '\033[0;0m'
+ ' ' + message
+ ': '
)
elif status == 'I':
print(
' ' * padding
... | def out(status, message, padding=0, custom=None):
if status == '?':
return input(' ' * padding + '\x1b[1;36m' + '[?]' + '\x1b[0;0m' + ' ' + message + ': ')
elif status == 'I':
print(' ' * padding + '\x1b[1;32m[' + (str(custom) if custom != None else 'I') + ']\x1b[0;0m' + ' ' + message)
elif ... |
class Animal(object):
"""docstring for Animal"""
def __init__(self):
super(Animal, self).__init__()
def keu(self):
print("I am an animal")
class Plant(object):
"""docstring for Plant"""
def __init__(self):
super(Plant, self).__init__()
def keu(self):
print("I am a plant")
def qh(self):
print("I am... | class Animal(object):
"""docstring for Animal"""
def __init__(self):
super(Animal, self).__init__()
def keu(self):
print('I am an animal')
class Plant(object):
"""docstring for Plant"""
def __init__(self):
super(Plant, self).__init__()
def keu(self):
print('I... |
description = ''
pages = ['header']
def setup(data):
pass
def test(data):
navigate('http://store.demoqa.com/')
header.verify_product_categories('Accessories, iMacs, iPads, iPhones, iPods, MacBooks')
capture('Verify product categories')
def teardown(data):
pass
| description = ''
pages = ['header']
def setup(data):
pass
def test(data):
navigate('http://store.demoqa.com/')
header.verify_product_categories('Accessories, iMacs, iPads, iPhones, iPods, MacBooks')
capture('Verify product categories')
def teardown(data):
pass |
while True:
e = str(input()).split()
a = int(e[0])
b = int(e[1])
if a == 0 == b: break
print(2 * a - b)
| while True:
e = str(input()).split()
a = int(e[0])
b = int(e[1])
if a == 0 == b:
break
print(2 * a - b) |
#
# PySNMP MIB module CISCO-LWAPP-LINKTEST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-LINKTEST-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:05:43 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, value_size_constraint, constraints_union) ... |
'''Play on numbers with arthitemetic'''
def simple_math_calc():
"""Do simple mathematical calculation"""
num_value1 = 10
num_value2 = 20
num_pi = 22/7
print(num_pi)
print('{0} + {1} = {2}'.format(num_value1, num_value2, num_value1+num_value2))
input1 = input("Enter first number for addition... | """Play on numbers with arthitemetic"""
def simple_math_calc():
"""Do simple mathematical calculation"""
num_value1 = 10
num_value2 = 20
num_pi = 22 / 7
print(num_pi)
print('{0} + {1} = {2}'.format(num_value1, num_value2, num_value1 + num_value2))
input1 = input('Enter first number for addi... |
"""
This folder is modified from https://github.com/sungyubkim/MINE-Mutual-Information-Neural-Estimation-
from mutual information estimation
"""
| """
This folder is modified from https://github.com/sungyubkim/MINE-Mutual-Information-Neural-Estimation-
from mutual information estimation
""" |
#!python
def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
# implement linear_search_iterative and linear_search_recursive below, then
# change this to call your implementation to verify it passes all tests
return linear_search_iterative(array, i... | def linear_search(array, item):
"""return the first index of item in array or None if item is not found"""
return linear_search_iterative(array, item)
def linear_search_iterative(array, item):
for (index, value) in enumerate(array):
if item == value:
return index
return None
def li... |
class BaseTestFunction(object):
r"""Base class for all test functions in optimization.
For more details, please refer to `this Wikipedia page`_.
.. _this Wikipedia page:
https://en.wikipedia.org/wiki/Test_functions_for_optimization
The subclass should implement at least the follo... | class Basetestfunction(object):
"""Base class for all test functions in optimization.
For more details, please refer to `this Wikipedia page`_.
.. _this Wikipedia page:
https://en.wikipedia.org/wiki/Test_functions_for_optimization
The subclass should implement at least the follow... |
# Test that returning of NotImplemented from binary op methods leads to
# TypeError.
try:
NotImplemented
except NameError:
print("SKIP")
raise SystemExit
class C:
def __init__(self, value):
self.value = value
def __str__(self):
return "C({})".format(self.value)
def __add__(sel... | try:
NotImplemented
except NameError:
print('SKIP')
raise SystemExit
class C:
def __init__(self, value):
self.value = value
def __str__(self):
return 'C({})'.format(self.value)
def __add__(self, rhs):
print(self, '+', rhs)
return NotImplemented
def __sub_... |
# POWER OF THREE LEETCODE SOLUTION:
# creating a class.
class Solution(object):
# creating a function to solve the problem.
def isPowerOfThree(self, n):
# creating a variable to track the exponent.
i = 0
# creating a while-loop to iterate until the desired number.
... | class Solution(object):
def is_power_of_three(self, n):
i = 0
while 3 ** i <= n:
if 3 ** i == n:
return True
i += 1
return False |
if False:
print("Really, really false.")
elif False:
print("nested")
else:
if "seems rediculous":
print("it is.")
| if False:
print('Really, really false.')
elif False:
print('nested')
elif 'seems rediculous':
print('it is.') |
nome = str(input('Qual e o seu nome?'))
if nome =='Gustavo':
print('Que nome lindo voce tem!')
else:
print('Seu nome e tao normal!')
print('Bom dia {}!'.format(nome))
| nome = str(input('Qual e o seu nome?'))
if nome == 'Gustavo':
print('Que nome lindo voce tem!')
else:
print('Seu nome e tao normal!')
print('Bom dia {}!'.format(nome)) |
"""
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... | """
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES O... |
class Solution:
def findRestaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
inverse1 = {e: i for i, e in enumerate(list1)}
overlap = collections.defaultdict(list) # stored by index sum
for j, e in en... | class Solution:
def find_restaurant(self, list1, list2):
"""
:type list1: List[str]
:type list2: List[str]
:rtype: List[str]
"""
inverse1 = {e: i for (i, e) in enumerate(list1)}
overlap = collections.defaultdict(list)
for (j, e) in enumerate(list2):
... |
class DescriptorTypesEnum():
_ECFP = "ecfp"
_ECFP_COUNTS = "ecfp_counts"
_MACCS_KEYS = "maccs_keys"
_AVALON = "avalon"
@property
def ECFP(self):
return self._ECFP
@ECFP.setter
def ECFP(self, value):
raise ValueError("Do not assign value to a DescriptorTypesEnum field")
... | class Descriptortypesenum:
_ecfp = 'ecfp'
_ecfp_counts = 'ecfp_counts'
_maccs_keys = 'maccs_keys'
_avalon = 'avalon'
@property
def ecfp(self):
return self._ECFP
@ECFP.setter
def ecfp(self, value):
raise value_error('Do not assign value to a DescriptorTypesEnum field')
... |
day_events_list = input().split("|")
MAX_ENERGY = 100
ORDER_ENERGY = 30
REST_ENERGY = 50
energy = 100
coins = 100
is_not_bankrupt = True
for event in day_events_list:
single_events_list = event.split("-")
name = single_events_list[0]
value = int(single_events_list[1])
if name == "rest":
gaine... | day_events_list = input().split('|')
max_energy = 100
order_energy = 30
rest_energy = 50
energy = 100
coins = 100
is_not_bankrupt = True
for event in day_events_list:
single_events_list = event.split('-')
name = single_events_list[0]
value = int(single_events_list[1])
if name == 'rest':
gained_e... |
class WebpreviewException(Exception):
"""
Base Webpreview Exception.
"""
pass
class EmptyURL(WebpreviewException):
"""
WebpreviewException for empty URL.
"""
pass
class EmptyProperties(WebpreviewException):
"""
WebpreviewException for empty properties.
"""
pass
clas... | class Webpreviewexception(Exception):
"""
Base Webpreview Exception.
"""
pass
class Emptyurl(WebpreviewException):
"""
WebpreviewException for empty URL.
"""
pass
class Emptyproperties(WebpreviewException):
"""
WebpreviewException for empty properties.
"""
pass
class U... |
def main(j, args, params, tags, tasklet):
params.merge(args)
doc = params.doc
# tags = params.tags
actor=j.apps.actorsloader.getActor("system","gridmanager")
organization = args.getTag("organization")
name = args.getTag("jsname")
out = ''
missing = False
for k,v in {'organizatio... | def main(j, args, params, tags, tasklet):
params.merge(args)
doc = params.doc
actor = j.apps.actorsloader.getActor('system', 'gridmanager')
organization = args.getTag('organization')
name = args.getTag('jsname')
out = ''
missing = False
for (k, v) in {'organization': organization, 'name'... |
class color:
black = "\033[30m"
red = "\033[31m"
green = "\033[32m"
yellow = "\033[33m"
blue = "\033[34m"
magenta = "\033[35m"
cyan = "\033[36m"
white = "\033[37m"
class bright:
black_1 = "\033[1;30m"
red_1 = "\033[1;31m"
green_1 = "\033[1;32m"
yellow_1 = "\033[1;33m"
blue_1 = "\033[1;34m"
... | class Color:
black = '\x1b[30m'
red = '\x1b[31m'
green = '\x1b[32m'
yellow = '\x1b[33m'
blue = '\x1b[34m'
magenta = '\x1b[35m'
cyan = '\x1b[36m'
white = '\x1b[37m'
class Bright:
black_1 = '\x1b[1;30m'
red_1 = '\x1b[1;31m'
green_1 = '\x1b[1;32m'
yellow_1 = '\x1b[1;33m'
... |
# -*- coding: utf-8 -*-
"""
dicts contains a number of special-case dictionaries.
.. testsetup:: *
import kutils.dicts as kd
"""
class AttrDict(dict):
"""
AttrDict represents a dictionary where the keys are represented as
attributes.
>>> d = kd.AttrDict(foo='bar')
>>> d.foo
'bar'
>>>... | """
dicts contains a number of special-case dictionaries.
.. testsetup:: *
import kutils.dicts as kd
"""
class Attrdict(dict):
"""
AttrDict represents a dictionary where the keys are represented as
attributes.
>>> d = kd.AttrDict(foo='bar')
>>> d.foo
'bar'
>>> d['foo']
'bar'
"... |
##This does nothing yet...
class Broker(object):
def __init__(self):
self.name = 'ETrade'
self.tradeFee = 4.95
| class Broker(object):
def __init__(self):
self.name = 'ETrade'
self.tradeFee = 4.95 |
def direct_path(string):
"""
Given a Linux Path "/users/john/documents/../desktop/./../"
return the direct equivalent path "/users/john/"
O(n) time
O(n) space
"""
pile = []
for directory in string.split('/'):
if directory:
if directory == '.':
pass
else:
if directory == '..':
pile.pop()
... | def direct_path(string):
"""
Given a Linux Path "/users/john/documents/../desktop/./../"
return the direct equivalent path "/users/john/"
O(n) time
O(n) space
"""
pile = []
for directory in string.split('/'):
if directory:
if directory == '.':
pass
elif d... |
class Neuron(object):
def __init__(self, *args, **kwargs):
super(Neuron, self).__init__() | class Neuron(object):
def __init__(self, *args, **kwargs):
super(Neuron, self).__init__() |
num = int(input('Digite uma numero:'))
b = bin(num)
o = oct(num)
h = hex(num)
print('''Escolha
[1] binario
[2] octal
[3] hex ''')
opcao = int(input('sua Opcao: '))
if opcao == 1:
print('{} convertido {}'.format(num,b[2:]))
elif opcao == 2:
print('{} convertido {}'.format(num,o[2:]))
elif opcao == 3:
print('... | num = int(input('Digite uma numero:'))
b = bin(num)
o = oct(num)
h = hex(num)
print('Escolha\n[1] binario\n[2] octal\n[3] hex ')
opcao = int(input('sua Opcao: '))
if opcao == 1:
print('{} convertido {}'.format(num, b[2:]))
elif opcao == 2:
print('{} convertido {}'.format(num, o[2:]))
elif opcao == 3:
print(... |
############################################################################
#
# Copyright (C) 2016 The Qt Company Ltd.
# Contact: https://www.qt.io/licensing/
#
# This file is part of Qt Creator.
#
# Commercial License Usage
# Licensees holding valid commercial Qt licenses may use this file in
# accordance with the co... | source('../../shared/qtcreator.py')
qml_editor = ':Qt Creator_QmlJSEditor::QmlJSTextEditorWidget'
outline = ':Qt Creator_QmlJSEditor::Internal::QmlJSOutlineTreeView'
treebase = 'keyinteraction.Resources.keyinteraction\\.qrc./keyinteraction.focus.'
def main():
source_example = os.path.join(Qt5Path.examplesPath(Targ... |
def extra_end(str):
if len(str) <= 2:
return (str * 3)
return (str[-2:]*3)
| def extra_end(str):
if len(str) <= 2:
return str * 3
return str[-2:] * 3 |
class Obstacle(object):
def __init__(self, position):
self.position = position
self.positionHistory = [position]
self.ObstaclePotentialForces = [] | class Obstacle(object):
def __init__(self, position):
self.position = position
self.positionHistory = [position]
self.ObstaclePotentialForces = [] |
"""
At_initial_setup module template
Copy this module up one level to /gamesrc/conf, name it what you like
and then use it as a template to modify.
Then edit settings.AT_INITIAL_SETUP_HOOK_MODULE to point to your new
module.
Custom at_initial_setup method. This allows you to hook special
modifications to the initial... | """
At_initial_setup module template
Copy this module up one level to /gamesrc/conf, name it what you like
and then use it as a template to modify.
Then edit settings.AT_INITIAL_SETUP_HOOK_MODULE to point to your new
module.
Custom at_initial_setup method. This allows you to hook special
modifications to the initial... |
#
# PySNMP MIB module CISCO-UNIFIED-COMPUTING-LLDP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-UNIFIED-COMPUTING-LLDP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:16:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... | (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint) ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# input
input_data = []
with open('input.txt', 'r') as f:
lines = f.readlines()
input_data = [l.strip().split(')') for l in lines]
# structures
orbits_down = dict(zip([inp[1] for inp in input_data], [inp[0] for inp in input_data]))
# task 1
to... | input_data = []
with open('input.txt', 'r') as f:
lines = f.readlines()
input_data = [l.strip().split(')') for l in lines]
orbits_down = dict(zip([inp[1] for inp in input_data], [inp[0] for inp in input_data]))
total = 0
all_centers = orbits_down.values()
for (center, satellite) in orbits_down.items():
curr... |
"""
DockCI exceptions
"""
class InvalidOperationError(Exception):
"""
Raised when a call is not valid at the current time
"""
pass
class AlreadyBuiltError(Exception):
"""
Raised when a versioned build already exists in the repository
"""
pass
class AlreadyRunError(InvalidOperationE... | """
DockCI exceptions
"""
class Invalidoperationerror(Exception):
"""
Raised when a call is not valid at the current time
"""
pass
class Alreadybuilterror(Exception):
"""
Raised when a versioned build already exists in the repository
"""
pass
class Alreadyrunerror(InvalidOperationErro... |
def Num14681():
x = int(input())
y = int(input())
result = 0
if x > 0:
if y > 0:
result = 1
else:
result = 4
else:
if y < 0:
result = 3
else:
result = 2
print(str(result))
Num14681() | def num14681():
x = int(input())
y = int(input())
result = 0
if x > 0:
if y > 0:
result = 1
else:
result = 4
elif y < 0:
result = 3
else:
result = 2
print(str(result))
num14681() |
#Given an array of integers, find the one that appears an odd number of times.
#There will always be only one integer that appears an odd number of times.
def find_it(arr):
res = 0
for element in arr:
res = res ^ element
return res
| def find_it(arr):
res = 0
for element in arr:
res = res ^ element
return res |
__author__ = 'samantha'
def checkio(words):
#l = list()
#for word in words.split():
# l.append(word.isalpha())
print(words)
res = False
l = [wd.isalpha() for wd in words.split()]
#r = [l[i:i+3] for i in range(0,len(l)-3) ]
#print ('r=',r)
print ('l=',l)
if len(l)>3:
p... | __author__ = 'samantha'
def checkio(words):
print(words)
res = False
l = [wd.isalpha() for wd in words.split()]
print('l=', l)
if len(l) > 3:
print('len(l)=', len(l))
print('range', range(0, len(l) - 2))
for i in range(0, len(l) - 2):
print('i=', i)
l... |
class FrontendPortTotalThroughput(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_frontend_port_total_iops(idx_name)
class FrontendPortTotalThroughputColumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_frontend_ports()
| class Frontendporttotalthroughput(object):
def read_get(self, name, idx_name, unity_client):
return unity_client.get_frontend_port_total_iops(idx_name)
class Frontendporttotalthroughputcolumn(object):
def get_idx(self, name, idx, unity_client):
return unity_client.get_frontend_ports() |
DEBUG = True
MOLLIE_API_KEY = ''
REDIS_HOST = 'localhost'
COOKIE_NAME = 'Paywall-Voucher'
CSRF_SECRET_KEY = 'NeVeR WoUnD a SnAke KiLl It'
| debug = True
mollie_api_key = ''
redis_host = 'localhost'
cookie_name = 'Paywall-Voucher'
csrf_secret_key = 'NeVeR WoUnD a SnAke KiLl It' |
def field_validator(keys, data_):
"""
Validates the submitted data are POSTed with the required fields
:param keys:
:param data_:
:return:
"""
data = {}
for v in keys:
if v not in data_:
data[v] = ["This field may not be null."]
if len(data) != 0:
return {... | def field_validator(keys, data_):
"""
Validates the submitted data are POSTed with the required fields
:param keys:
:param data_:
:return:
"""
data = {}
for v in keys:
if v not in data_:
data[v] = ['This field may not be null.']
if len(data) != 0:
return {... |
# Copyright 2017 Rice University
#
# 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 writin... | labels = ['swing', 'awt', 'security', 'sql', 'net', 'xml', 'crypto', 'math']
def get_api(config, calls, apiOrNot):
apis = []
for (call, api_bool) in zip(calls, apiOrNot):
if api_bool and call > 0:
api = config.vocab.chars_api[call]
apis.append(api)
apis_ = []
for api in ... |
__all__ = ['VERSION']
VERSION = '7.6.0'
SAVE_PATH = '~/.spotifydl'
SPOTIPY_CLIENT_ID = "4fe3fecfe5334023a1472516cc99d805"
SPOTIPY_CLIENT_SECRET = "0f02b7c483c04257984695007a4a8d5c"
| __all__ = ['VERSION']
version = '7.6.0'
save_path = '~/.spotifydl'
spotipy_client_id = '4fe3fecfe5334023a1472516cc99d805'
spotipy_client_secret = '0f02b7c483c04257984695007a4a8d5c' |
#!/usr/bin/env python3
print("Hello Inderpal Singh!")
print("Welcome to python scripting.")
print("Learning python opens new doors of opportunity.")
| print('Hello Inderpal Singh!')
print('Welcome to python scripting.')
print('Learning python opens new doors of opportunity.') |
while True:
try:
bil = input("masukan bilangan: ")
bil = int(bil)
break
except ValueError:
print("anda salah memasukan bilangan")
print("anda memasukan bilangan %s, data harus angka" % bil )
print("anda memasukan bilangan", bil) | while True:
try:
bil = input('masukan bilangan: ')
bil = int(bil)
break
except ValueError:
print('anda salah memasukan bilangan')
print('anda memasukan bilangan %s, data harus angka' % bil)
print('anda memasukan bilangan', bil) |
class ViewportInfo(object,IDisposable,ISerializable):
"""
Represents a viewing frustum.
ViewportInfo()
ViewportInfo(other: ViewportInfo)
ViewportInfo(rhinoViewport: RhinoViewport)
"""
def ChangeToParallelProjection(self,symmetricFrustum):
"""
ChangeToParallelProjection(self: ViewportInfo,... | class Viewportinfo(object, IDisposable, ISerializable):
"""
Represents a viewing frustum.
ViewportInfo()
ViewportInfo(other: ViewportInfo)
ViewportInfo(rhinoViewport: RhinoViewport)
"""
def change_to_parallel_projection(self, symmetricFrustum):
"""
ChangeToParallelProjection(self: Viewport... |
"""
A selection of job objects used in testing.
"""
EMPTY_JOB = '''\
<?xml version='1.0' encoding='UTF-8'?>
<project>
<actions/>
<description></description>
<keepDependencies>false</keepDependencies>
<properties/>
<scm class="hudson.scm.NullSCM"/>
<canRoam>true</canRoam>
<disabled>false</disabled>
<blo... | """
A selection of job objects used in testing.
"""
empty_job = '<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n<project>\n <actions/>\n <description></description>\n <keepDependencies>false</keepDependencies>\n <properties/>\n <scm class="hudson.scm.NullSCM"/>\n <canRoam>true</canRoam>\n <disabled>false</disabled>... |
# Comma Code
# Say you have a list value like this:
# spam = ['apples', 'bananas', 'tofu', 'cats']
# Write a function that takes a list value as an argument and returns a string wit
# h all the items separated by a comma and a space, with and inserted before the l
# ast item. For example, passing the previous spam list... | spam = ['apples', 'bananas', 'tofu', 'cats']
def comma_code(l):
if len(l) <= 0:
return ''
elif len(l) == 1:
return l[0]
else:
return ', '.join(l[:-1]) + ' and ' + l[-1]
print(comma_code(spam)) |
a = [1, 0, 5, -2, -5, 7]
soma = a[0] + a[1] + a[5]
print(soma)
a[4] = 100
print(a)
for v in a:
print(v)
| a = [1, 0, 5, -2, -5, 7]
soma = a[0] + a[1] + a[5]
print(soma)
a[4] = 100
print(a)
for v in a:
print(v) |
sums_new_methodology = {
"Total revenue": {
"A01",
"A03",
"A09",
"A10",
"A12",
"A16",
"A18",
"A21",
"A36",
"A44",
"A45",
"A50",
"A54",
"A56",
"A59",
"A60",
"A61",
"A80",
... | sums_new_methodology = {'Total revenue': {'A01', 'A03', 'A09', 'A10', 'A12', 'A16', 'A18', 'A21', 'A36', 'A44', 'A45', 'A50', 'A54', 'A56', 'A59', 'A60', 'A61', 'A80', 'A81', 'A87', 'A89', 'A90', 'A91', 'A92', 'A93', 'A94', 'B01', 'B21', 'B22', 'B30', 'B42', 'B43', 'B46', 'B50', 'B54', 'B59', 'B79', 'B80', 'B89', 'B91'... |
class Solution:
def solve(self, nums, k):
nums = [0]+nums
for i in range(1,len(nums)):
nums[i] += nums[i-1]
sums = [[nums[i] - x for x in sorted(nums[:i])[:k]] for i in range(1,len(nums))]
return sorted(sum(sums,[]))[-k:]
| class Solution:
def solve(self, nums, k):
nums = [0] + nums
for i in range(1, len(nums)):
nums[i] += nums[i - 1]
sums = [[nums[i] - x for x in sorted(nums[:i])[:k]] for i in range(1, len(nums))]
return sorted(sum(sums, []))[-k:] |
class MyParser:
def __init__(self, text_1, text_2):
self.text_1 = text_1
self.text_2 = text_2
def parse_text(self, text):
stack = []
for char in text:
if char != '#':
stack.append(char)
else:
if len(stack) > 0:
... | class Myparser:
def __init__(self, text_1, text_2):
self.text_1 = text_1
self.text_2 = text_2
def parse_text(self, text):
stack = []
for char in text:
if char != '#':
stack.append(char)
elif len(stack) > 0:
stack.pop()
... |
# Copyright 2019 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, s... | """Loads dependencies needed to compile Sandboxed API for 3rd-party consumers."""
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
load('@bazel_tools//tools/build_defs/repo:utils.bzl', 'maybe')
load('//sandboxed_api/bazel:repositories.bzl', 'autotools_repository')
def sapi_deps():
"""Loads comm... |
class Solution:
# 1, 2, 3, 4, 5
# n = 5
# Rotate - k = 2 - Left - 4, 5, 1, 2, 3
# Rotate - k = 3 (n - 2) - Right - 4, 5, 1, 2, 3
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void
"""
n = len(nums)
if (n == ... | class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void
"""
n = len(nums)
if n == 1 or k == 0 or n == k:
return
k = k % n
g_c_d = self.gcd(n, k)
for idx in range(g_c_d):
jd... |
#!/usr/bin/python3
# Both the Minimax and the Alpha-beta algorithm represent the players
# as integers 0 and 1. The moves by the two players alternate 0, 1, 0, 1, ...,
# so in the recursive calls you can compute the next player as the subtraction
# 1-player.
# The minimizing player is always 0 and the maximizing 1.
# ... | calls = 0
def minimax(player, state, depthLeft):
"""
Perform recursive min-max search of a game tree rooted in `state`.
Returns the best value in the min-max sense starting from `state` for `player`
using at most `depthLeft` recursive calls.
Gives value of state if depthLeft = 0 or the state has... |
if __name__ == '__main__':
n = int(input())
arr =list(map(int, input().split(" ")))
i = max(arr)
for i in range(0,n):
if max(arr) == i:
arr.remove(max(arr))
arr.sort(reverse=True)
print(arr[0])
| if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split(' ')))
i = max(arr)
for i in range(0, n):
if max(arr) == i:
arr.remove(max(arr))
arr.sort(reverse=True)
print(arr[0]) |
n=int(input())
p=[[int(i)for i in input().split()] for _ in range(n)]
p.sort(key=lambda x: x[2])
a,b,c=p[-1]
for y in range(101):
for x in range(101):
h=c+abs(a-x)+abs(b-y)
if all(k==max(h-abs(i-x)-abs(y-j),0) for i,j,k in p):
print(x,y,h)
exit() | n = int(input())
p = [[int(i) for i in input().split()] for _ in range(n)]
p.sort(key=lambda x: x[2])
(a, b, c) = p[-1]
for y in range(101):
for x in range(101):
h = c + abs(a - x) + abs(b - y)
if all((k == max(h - abs(i - x) - abs(y - j), 0) for (i, j, k) in p)):
print(x, y, h)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.