content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#
# Copyright (c) 2017, Massachusetts Institute of Technology All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list o... | mc = __import__('MARTE2_COMPONENT', globals())
@MC.BUILDER('TestGAM', MC.MARTE2_COMPONENT.MODE_GAM)
class Marte2_Gam(MC.MARTE2_COMPONENT):
inputs = [{'name': 'Input1', 'type': 'int32', 'dimensions': 0, 'parameters': {}}, {'name': 'Input2', 'type': 'int32', 'dimensions': 0, 'parameters': {}}, {'name': 'Input3', 'ty... |
# opaflib/parsetab_pdf_brute_end.py
# This file is automatically generated. Do not edit.
_tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = 'v\xc8s\x99\xa0\x80\x10\xa9\xcbe\x07\xb2\x86\xf3\xc42'
_lr_action_items = {'DOUBLE_GREATER_THAN_SIGN':([5,7,9,11,12,13,14,15,16,17,19,20,21,22,26,],[-17,9,-15,-10,-6,-... | _tabversion = '3.2'
_lr_method = 'LALR'
_lr_signature = 'vÈs\x99\xa0\x80\x10©Ëe\x07²\x86óÄ2'
_lr_action_items = {'DOUBLE_GREATER_THAN_SIGN': ([5, 7, 9, 11, 12, 13, 14, 15, 16, 17, 19, 20, 21, 22, 26], [-17, 9, -15, -10, -6, -13, -7, -16, -8, -12, -14, -11, -9, -5, -2]), 'XREF': ([0], [1]), 'FALSE': ([9, 10, 11, 12, 13,... |
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | def insert_into_sorted_list(new_element, list, less_than_fn=lambda x, y: x < y):
insert_pos = 0
for (i, element) in enumerate(list):
if less_than_fn(new_element, element):
break
insert_pos = i
list.insert(insert_pos, new_element)
prev_item = None
for item in list:
... |
#
# PySNMP MIB module XYLAN-CSM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/XYLAN-CSM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:38:25 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 201... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, single_value_constraint, constraints_union, constraints_intersection, value_range_constraint) ... |
def create_printer():
my_favourite_number = 123
def printer():
print(f"My Favourite Number is {my_favourite_number}")
return printer
# Closure
# As we can see, the output will be 123. Which means my_printer can still access to my_favourite_number which is outer scope.
# this is what Closure is
my... | def create_printer():
my_favourite_number = 123
def printer():
print(f'My Favourite Number is {my_favourite_number}')
return printer
my_printer = create_printer()
my_printer() |
#
# PySNMP MIB module DC-RTM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DC-RTM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:44:32 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, value_size_constraint, constraints_intersection, single_value_constraint) ... |
n = int(input())
ans = 0
cnt = [[0] * 9 for _ in range(9)]
for i in range(1, n + 1):
one = str(i)
if one[-1] == '0':
continue
cnt[int(one[0]) - 1][int(one[-1]) - 1] += 1
for i in range(9):
for j in range(9):
ans += cnt[i][j] * cnt[j][i]
print(ans)
| n = int(input())
ans = 0
cnt = [[0] * 9 for _ in range(9)]
for i in range(1, n + 1):
one = str(i)
if one[-1] == '0':
continue
cnt[int(one[0]) - 1][int(one[-1]) - 1] += 1
for i in range(9):
for j in range(9):
ans += cnt[i][j] * cnt[j][i]
print(ans) |
def overview(bot, c, e, args):
if len(args) >= 1:
command = None
for module in bot.loaded_modules.values():
try:
for comm in module['object'].commands():
if comm[0] == args[0]:
command = comm
except AttributeError:
... | def overview(bot, c, e, args):
if len(args) >= 1:
command = None
for module in bot.loaded_modules.values():
try:
for comm in module['object'].commands():
if comm[0] == args[0]:
command = comm
except AttributeError:
... |
# coding: utf-8
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache LICENSE, Version 2.0 (the
"LICENSE");... | """
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache LICENSE, Version 2.0 (the
"LICENSE"); you may not use... |
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = set()
for num in nums:
if num in res:
res.remove(num)
else:
res.add(num)
return res.pop()
a = Solut... | class Solution(object):
def single_number(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
res = set()
for num in nums:
if num in res:
res.remove(num)
else:
res.add(num)
return res.pop()
a = soluti... |
PARAMS = {
# max length of junction read overlap to consider a target site duplication
"tsd=" : 20
}
| params = {'tsd=': 20} |
class Drawer(object):
"""@brief Acts as a component, but with custom functions that are
defined within the controller and passed into refresh/load.
This allows for z index loading which may have
complex drawing functionality.
"""
def __init__(self, controller, refresh=None, load=None, z=0):
... | class Drawer(object):
"""@brief Acts as a component, but with custom functions that are
defined within the controller and passed into refresh/load.
This allows for z index loading which may have
complex drawing functionality.
"""
def __init__(self, controller, refresh=None, load=None, z=0):
... |
"""
https://www.hackerrank.com/challenges/max-array-sum/problem?isFullScreen=true
Given: a arr of ints
Find subset of non-adjacent els with the max sum.
Return that sum.
Example: arr = [-2, 1,3,-4,5]
possible subsets:
Subset Sum
[-2, 3, 5] 6
[-2, 3] 1
[-2, -4] -6
[-2, 5] 3
[1, -4] -3
[1, 5] ... | """
https://www.hackerrank.com/challenges/max-array-sum/problem?isFullScreen=true
Given: a arr of ints
Find subset of non-adjacent els with the max sum.
Return that sum.
Example: arr = [-2, 1,3,-4,5]
possible subsets:
Subset Sum
[-2, 3, 5] 6
[-2, 3] 1
[-2, -4] -6
[-2, 5] 3
[1, -4] -3
[1, 5] ... |
# -----------------------------------------------------------------------------
# @brief: Define some signals used during parallel
# -----------------------------------------------------------------------------
# it makes the main trpo agent push its weights into the tunnel
START_SIGNAL = 1
# it ends the training
E... | start_signal = 1
end_signal = -1
end_rollout_signal = -2
agent_collect_filter_info = 23
agent_synchronize_filter = 233
agent_set_policy_weights = 2333
agent_evolution_train = 23333
agent_evolution_start = 233333 |
""""""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__title__ = 'PyScenic'
__description__ = 'A Python wrapper around Scenic REST APIs'
__url__ = 'https://github.com/ScenicWeather/pyScenicWeather'
__version__ = "0.0.3"
__author__ = 'Conor Forde'
__author_email__ = 'conor@scenicdata.com'
__license__ = 'MIT'
| """"""
__title__ = 'PyScenic'
__description__ = 'A Python wrapper around Scenic REST APIs'
__url__ = 'https://github.com/ScenicWeather/pyScenicWeather'
__version__ = '0.0.3'
__author__ = 'Conor Forde'
__author_email__ = 'conor@scenicdata.com'
__license__ = 'MIT' |
"""
If you only do what you can do,
You will never be better than you are now.
- Master shifu
""" | """
If you only do what you can do,
You will never be better than you are now.
- Master shifu
""" |
# Time: O(1)
# Space: O(1)
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
return 2 ** (len(bin(num)) - 2) - 1 - num
class Solution2(object):
def findComplement(self, num):
i = 1
while i <= num:
i <... | class Solution(object):
def find_complement(self, num):
"""
:type num: int
:rtype: int
"""
return 2 ** (len(bin(num)) - 2) - 1 - num
class Solution2(object):
def find_complement(self, num):
i = 1
while i <= num:
i <<= 1
return i - 1 ... |
def primes(value):
for num in range(value):
res = True
for k in range(2, num):
if k != 0:
if num % k == 0:
res = False
if res == True:
print(num)
primes(100)
| def primes(value):
for num in range(value):
res = True
for k in range(2, num):
if k != 0:
if num % k == 0:
res = False
if res == True:
print(num)
primes(100) |
#
# PySNMP MIB module IBMIROC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IBMIROC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:51:37 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_size_constraint, single_value_constraint, value_range_constraint) ... |
# Time: O(n)
# Space: O(1)
def read4(buf):
global file_content
i = 0
while i < len(file_content) and i < 4:
buf[i] = file_content[i]
i += 1
if len(file_content) > 4:
file_content = file_content[4:]
else:
file_content = ""
return i
class Solutio... | def read4(buf):
global file_content
i = 0
while i < len(file_content) and i < 4:
buf[i] = file_content[i]
i += 1
if len(file_content) > 4:
file_content = file_content[4:]
else:
file_content = ''
return i
class Solution(object):
def read(self, buf, n):
... |
## Declare file path
STYLE_AURORA= 'static/img/aurora.jpg'
STYLE_CHINESE = 'static/img/chinese.jpg'
STYLE_CHINGMIN = 'static/img/chingmin.jpg'
STYLE_COLORFUL = 'static/img/colorful.jpg'
STYLE_CRYSTAL = 'static/img/crystal.jpg'
STYLE_DES_GLANEUSES = 'static/img/des_glaneuses.jpg'
STYLE_FIRE = 'static/img/fire.jpg'
STYLE... | style_aurora = 'static/img/aurora.jpg'
style_chinese = 'static/img/chinese.jpg'
style_chingmin = 'static/img/chingmin.jpg'
style_colorful = 'static/img/colorful.jpg'
style_crystal = 'static/img/crystal.jpg'
style_des_glaneuses = 'static/img/des_glaneuses.jpg'
style_fire = 'static/img/fire.jpg'
style_jingdo = 'static/im... |
def parallel_play_test(par_env):
obs = par_env.reset()
assert isinstance(obs, dict)
assert set(obs.keys()).issubset(set(par_env.agents))
for i in range(1000):
actions = {agent:space.sample() for agent, space in par_env.action_spaces.items()}
obs, rew, done, info = par_env.step(actions)... | def parallel_play_test(par_env):
obs = par_env.reset()
assert isinstance(obs, dict)
assert set(obs.keys()).issubset(set(par_env.agents))
for i in range(1000):
actions = {agent: space.sample() for (agent, space) in par_env.action_spaces.items()}
(obs, rew, done, info) = par_env.step(actio... |
class BattleshAPIException(Exception):
pass
class GameNotStartedException(BattleshAPIException):
pass
class NotYourTurnException(BattleshAPIException):
pass
class AlreadyRegisteredException(BattleshAPIException):
pass
class ShipInTheWayException(BattleshAPIException):
pass
class Insufficie... | class Battleshapiexception(Exception):
pass
class Gamenotstartedexception(BattleshAPIException):
pass
class Notyourturnexception(BattleshAPIException):
pass
class Alreadyregisteredexception(BattleshAPIException):
pass
class Shipinthewayexception(BattleshAPIException):
pass
class Insufficientfun... |
# -*- coding: utf-8 -*-
#
# Author: Thomas Hangstoerfer
# License: MIT
#
class Screen(object):
"""docstring for Screen"""
def __init__(self):
#super(Screen, self).__init__()
#self.arg = arg
self.isVisible_ = False
pass
def setVisible(self, visible):
# print("Screen... | class Screen(object):
"""docstring for Screen"""
def __init__(self):
self.isVisible_ = False
pass
def set_visible(self, visible):
self.isVisible_ = visible
self.update()
def is_visible(self):
return self.isVisible_
def update(self):
pass
def k... |
games_won = dict(sara=0, bob=1, tim=5, julian=3, jim=1)
def print_game_stats(games=games_won):
"""Loop through games_won's dict (key, value) pairs (dict.items)
printing (print, not return) how many games each person has won,
pluralize 'game' based on number.
Expected output (ignore the docst... | games_won = dict(sara=0, bob=1, tim=5, julian=3, jim=1)
def print_game_stats(games=games_won):
"""Loop through games_won's dict (key, value) pairs (dict.items)
printing (print, not return) how many games each person has won,
pluralize 'game' based on number.
Expected output (ignore the docstr... |
MALE = "male"
FEMALE = "female"
OTHER = "other"
GENDERS = ((MALE, MALE), (FEMALE, FEMALE), (OTHER, OTHER))
MEMBER = "member"
LEADER = "leader"
CO_LEADER = "co-leader"
TREASURER = "treasurer"
RECRUITING = "recruiting"
DEVELOPMENT = "development"
EDITOR = "editor"
RETIREE = "retiree"
MEDIA_RELATIONS = "media_relations"... | male = 'male'
female = 'female'
other = 'other'
genders = ((MALE, MALE), (FEMALE, FEMALE), (OTHER, OTHER))
member = 'member'
leader = 'leader'
co_leader = 'co-leader'
treasurer = 'treasurer'
recruiting = 'recruiting'
development = 'development'
editor = 'editor'
retiree = 'retiree'
media_relations = 'media_relations'
a... |
class ReprMixin:
def __repr__(self) -> str:
"""
This function is used to represent the object.
"""
return f'<{self.__class__.__name__} {self.id}>'
class Hashable(ReprMixin):
def __hash__(self):
"""
This function is used to hash the object.
"""
... | class Reprmixin:
def __repr__(self) -> str:
"""
This function is used to represent the object.
"""
return f'<{self.__class__.__name__} {self.id}>'
class Hashable(ReprMixin):
def __hash__(self):
"""
This function is used to hash the object.
"""
... |
_NO_DEFAULT = object()
class Record(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except TypeError:
return Record({k: dict.__getitem__(self, k) for k in key})
def __setitem__(self, key, value):
try:
dict.__setitem__(self, ... | _no_default = object()
class Record(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except TypeError:
return record({k: dict.__getitem__(self, k) for k in key})
def __setitem__(self, key, value):
try:
dict.__setitem__(self... |
# -*- coding: utf-8 -*-
"""
This module serves the class for wrapping
any known client specific exceptions.
"""
class FullContactException(Exception):
pass
| """
This module serves the class for wrapping
any known client specific exceptions.
"""
class Fullcontactexception(Exception):
pass |
"""
Solution for https://codeforces.com/problemset/problem/236/A
"""
def main():
s = input()
set_s = set(s)
if len(set_s) % 2 == 0:
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
if __name__ == '__main__':
main() | """
Solution for https://codeforces.com/problemset/problem/236/A
"""
def main():
s = input()
set_s = set(s)
if len(set_s) % 2 == 0:
print('CHAT WITH HER!')
else:
print('IGNORE HIM!')
if __name__ == '__main__':
main() |
class Calculation:
def __init__(self):
self.checks = []
self.max_ratio_index = 0
self.show_max_ratio_calc = False
def add_item(self, location, name, check_item, check_force, unit):
self.checks.append([location, name, check_item["result"], check_force,
... | class Calculation:
def __init__(self):
self.checks = []
self.max_ratio_index = 0
self.show_max_ratio_calc = False
def add_item(self, location, name, check_item, check_force, unit):
self.checks.append([location, name, check_item['result'], check_force, check_item['equations'], c... |
"""
Interface for pin class
functionality described in azubot_gpio.py
"""
class IPin:
def __init__(self, pin_no, mode):
raise NotImplementedError
def write(self, value):
raise NotImplementedError
| """
Interface for pin class
functionality described in azubot_gpio.py
"""
class Ipin:
def __init__(self, pin_no, mode):
raise NotImplementedError
def write(self, value):
raise NotImplementedError |
def voting(winners, author, text):
"""
Every author gets to vote once with their vote being text. The text is a
numberic string indicating a voting choice. Each vote is added to a dict of
all other votes.
"""
if author not in winners.keys():
if text.isnumeric():
winners[autho... | def voting(winners, author, text):
"""
Every author gets to vote once with their vote being text. The text is a
numberic string indicating a voting choice. Each vote is added to a dict of
all other votes.
"""
if author not in winners.keys():
if text.isnumeric():
winners[autho... |
for i in range(1,10):
for j in range(1,i+1):
print('{}*{} = {}''\t'.format(i,j,i*j),end = '')
print()
| for i in range(1, 10):
for j in range(1, i + 1):
print('{}*{} = {}\t'.format(i, j, i * j), end='')
print() |
'''
Bayesian machine learning models with sklearn api
=================================================
IMPLEMENTED ALGORITHMS:
-----------------------
** Linear Models
- Type II ML Bayesian Logistic Regression with Laplace Approximation (EBLogisticRegression)
- Type II ML Bayesian... | """
Bayesian machine learning models with sklearn api
=================================================
IMPLEMENTED ALGORITHMS:
-----------------------
** Linear Models
- Type II ML Bayesian Logistic Regression with Laplace Approximation (EBLogisticRegression)
- Type II ML Bayesian... |
#0.04s user 0.02s system 63% cpu 0.086 total
numbers = '731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380... | numbers = '731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749303589072... |
# from pokemon import Pokemon
class Trainer:
def __init__(self, name):
self.name = name
self.pokemon = []
def add_pokemon(self, pokemon):
repeats = [owned_pokemon for owned_pokemon in self.pokemon if pokemon.name == owned_pokemon.name]
if not repeats:
self.pokemon... | class Trainer:
def __init__(self, name):
self.name = name
self.pokemon = []
def add_pokemon(self, pokemon):
repeats = [owned_pokemon for owned_pokemon in self.pokemon if pokemon.name == owned_pokemon.name]
if not repeats:
self.pokemon.append(pokemon)
ret... |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
diffs = {}
for i in range(len(nums)):
if nums[i] in diffs:
return [diffs[nums[i]], i]
diffs.update({
target - nums[i]: i
})
| class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
diffs = {}
for i in range(len(nums)):
if nums[i] in diffs:
return [diffs[nums[i]], i]
diffs.update({target - nums[i]: i}) |
S = input()
d = {}
for c in S:
d.setdefault(c, 0)
d[c] += 1
if all(map(lambda x: x == 1, d.values())):
print('YES')
else:
print('NO')
| s = input()
d = {}
for c in S:
d.setdefault(c, 0)
d[c] += 1
if all(map(lambda x: x == 1, d.values())):
print('YES')
else:
print('NO') |
var = 0
print(var == 0)
print(var == 0.)
var = 1
print(var == 0)
print(var != 1.1)
| var = 0
print(var == 0)
print(var == 0.0)
var = 1
print(var == 0)
print(var != 1.1) |
nome = input("Insira seu nome: ")
nota1 = float(input("Insira sua nota da primeira prova: "))
nota2 = float(input("Insira sua nota da segunda prova: "))
div = (nota1 + nota2) / 2
print(f"a media de {nome} foi {div:.2f} ao final das provas.")
| nome = input('Insira seu nome: ')
nota1 = float(input('Insira sua nota da primeira prova: '))
nota2 = float(input('Insira sua nota da segunda prova: '))
div = (nota1 + nota2) / 2
print(f'a media de {nome} foi {div:.2f} ao final das provas.') |
"""
Ende
====
Personal (En)cryption (De)cryption package with command-line tool
This program provides string, file & whole folder encrytion / decryption.
It may be used either as a importable package or a command-line tool.
- Encryption uses AES-128 CBC mode
- Authentication is signed with a SHA256 HMAC.
- Individua... | """
Ende
====
Personal (En)cryption (De)cryption package with command-line tool
This program provides string, file & whole folder encrytion / decryption.
It may be used either as a importable package or a command-line tool.
- Encryption uses AES-128 CBC mode
- Authentication is signed with a SHA256 HMAC.
- Individua... |
dictionary = dict(
edep = r'$\mathrm{E}_\mathrm{dep}$',
edep_unit = 'MeV',
evis = r'$\mathrm{E}_\mathrm{vis}$',
evis_unit = 'MeV',
eres_sigma_rel = r'$\sigma_E/E$',
eres_sigma_rel_unit = '%',
)
| dictionary = dict(edep='$\\mathrm{E}_\\mathrm{dep}$', edep_unit='MeV', evis='$\\mathrm{E}_\\mathrm{vis}$', evis_unit='MeV', eres_sigma_rel='$\\sigma_E/E$', eres_sigma_rel_unit='%') |
"""pylint option block-disable"""
__revision__ = None
class Child2Class(object):
"""block-disable test"""
def __init__(self):
pass
def meth1OfChild(self, arg):
"""this issues a message"""
print (self)
| """pylint option block-disable"""
__revision__ = None
class Child2Class(object):
"""block-disable test"""
def __init__(self):
pass
def meth1_of_child(self, arg):
"""this issues a message"""
print(self) |
"""
For loops are called count controlled iteration
Unlike while loops that are controlled by a condition
for loops run a certain number of times and then stop.
The i variable after the key word for is the loop variable
Each time the loop executes the loop variable is incremented
The value of the loop variable starts a... | """
For loops are called count controlled iteration
Unlike while loops that are controlled by a condition
for loops run a certain number of times and then stop.
The i variable after the key word for is the loop variable
Each time the loop executes the loop variable is incremented
The value of the loop variable starts a... |
"""
molssi_math.py
A package containing math functions
Handles the primary functions
"""
def mean(my_list):
"""
This function calculates the mean of a list
Parameters
----------
my_list: list
The list of numbers that we want to average
Returns
-------
mean_list : float
... | """
molssi_math.py
A package containing math functions
Handles the primary functions
"""
def mean(my_list):
"""
This function calculates the mean of a list
Parameters
----------
my_list: list
The list of numbers that we want to average
Returns
-------
mean_list : float
... |
class GameWorldMixin():
def __init__(self):
self.init_game = None
self._worlds = None
self.gameworld = None
def add_world(self, world_name, **kwargs):
self._worlds[world_name] = GameWorld(world_name, **kwargs)
self.gameworld.init_gameworld([], callback=self.init_game)
c... | class Gameworldmixin:
def __init__(self):
self.init_game = None
self._worlds = None
self.gameworld = None
def add_world(self, world_name, **kwargs):
self._worlds[world_name] = game_world(world_name, **kwargs)
self.gameworld.init_gameworld([], callback=self.init_game)
c... |
BOT_NAME = 'transparencia'
SPIDER_MODULES = ['transparencia.spiders']
NEWSPIDER_MODULE = 'transparencia.spiders'
USER_AGENT = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0'
ROBOTSTXT_OBEY = False
RETRY_TIMES = 5
RETRY_HTTP_CODES = [500, 502, 503, 504, 522, 524, 403, 404, 408]
| bot_name = 'transparencia'
spider_modules = ['transparencia.spiders']
newspider_module = 'transparencia.spiders'
user_agent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:65.0) Gecko/20100101 Firefox/65.0'
robotstxt_obey = False
retry_times = 5
retry_http_codes = [500, 502, 503, 504, 522, 524, 403, 404, 408] |
#!/usr/bin/python -S
"""Fake get-quantenna-interfaces implementation."""
_INTERFACES = []
def call(*unused_args, **unused_kwargs):
return 0, '\n'.join(_INTERFACES)
def mock(interfaces):
global _INTERFACES
_INTERFACES = list(interfaces)
| """Fake get-quantenna-interfaces implementation."""
_interfaces = []
def call(*unused_args, **unused_kwargs):
return (0, '\n'.join(_INTERFACES))
def mock(interfaces):
global _INTERFACES
_interfaces = list(interfaces) |
def collect_args(obj):
i = 0
items = []
while True:
key = '_{n}'.format(n=i)
if key not in obj:
break
items.append(obj[key])
i += 1
return items
| def collect_args(obj):
i = 0
items = []
while True:
key = '_{n}'.format(n=i)
if key not in obj:
break
items.append(obj[key])
i += 1
return items |
ALL_LAYERS = ('A', 'B', 'C', 'D', 'E', 'F')
def seconds_to_readable_time(seconds):
seconds = seconds if seconds > 0 else 0
return f'{int(seconds // 60)}:{seconds % 60:04.1f}'
| all_layers = ('A', 'B', 'C', 'D', 'E', 'F')
def seconds_to_readable_time(seconds):
seconds = seconds if seconds > 0 else 0
return f'{int(seconds // 60)}:{seconds % 60:04.1f}' |
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
# -------------------------------------------------------------------------
# This is a sample controller
# - index is the default action of any application
# - user is required for authentication and authorization
... | def index():
return dict()
def products():
form = SQLFORM.grid(db.products)
return dict(form=form)
def user():
return dict(form=auth())
@cache.action()
def download():
return response.download(request, db)
def call():
return service() |
class Matrix:
def __init__(self, matrix):
self.matrix = list(matrix)
def number_of_row(self):
return len(self.matrix)
def number_of_column(self):
return len(self.matrix[0])
def __add__(self, other):
if (self.number_of_row() != other.number_of_row() or self.n... | class Matrix:
def __init__(self, matrix):
self.matrix = list(matrix)
def number_of_row(self):
return len(self.matrix)
def number_of_column(self):
return len(self.matrix[0])
def __add__(self, other):
if self.number_of_row() != other.number_of_row() or self.number_of_co... |
# https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/3157/
# O(n)
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = -1
j = 0
for j in range(len(nums)):
... | class Solution:
def move_zeroes(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = -1
j = 0
for j in range(len(nums)):
if nums[j] != 0:
if i < j - 1:
i += 1
... |
destination = 0
new_savings = 0
savings = 0
while destination != "End":
destination = input()
if destination == "End":
break
min_budget = float(input())
while min_budget >= new_savings:
savings = float(input())
new_savings += savings
if new_savings >= min_budget:
... | destination = 0
new_savings = 0
savings = 0
while destination != 'End':
destination = input()
if destination == 'End':
break
min_budget = float(input())
while min_budget >= new_savings:
savings = float(input())
new_savings += savings
if new_savings >= min_budget:
... |
class DefaultConfigEstimator:
def __init__(self, num_cores, # int
total_memory):
self.num_cores = num_cores
self.total_memory = total_memory
def get_min_executor_mem(self):
"""
:return: Returns the minimum executor memory
"""
return int(self.g... | class Defaultconfigestimator:
def __init__(self, num_cores, total_memory):
self.num_cores = num_cores
self.total_memory = total_memory
def get_min_executor_mem(self):
"""
:return: Returns the minimum executor memory
"""
return int(self.get_max_executor_mem() / ... |
class Solution(object):
def multiply(self, num1: str, num2: str) -> str:
# If both number are 0
if num1 == "0" and num2 == "0":
return "0"
# Reverse both numbers
first_number = num1[::-1]
second_number = num2[::-1]
# For each digit in seco... | class Solution(object):
def multiply(self, num1: str, num2: str) -> str:
if num1 == '0' and num2 == '0':
return '0'
first_number = num1[::-1]
second_number = num2[::-1]
results = []
for (index, digit) in enumerate(second_number):
results.append(self.m... |
# pylint: disable=line-too-long,invalid-name,missing-module-docstring
def extend_AllIndexed(self, elements, validate_continuity=False):
"""
Add all elements in list ``elements``, respecting ``@index`` order.
With ``validate_continuity``, check that all new elements come after all old elements
(or raise ... | def extend__all_indexed(self, elements, validate_continuity=False):
"""
Add all elements in list ``elements``, respecting ``@index`` order.
With ``validate_continuity``, check that all new elements come after all old elements
(or raise an exception).
Otherwise, ensure this condition silently (by in... |
# coding: utf-8
n, x = [int(i) for i in input().split()]
current = 1
ans = 0
for i in range(n):
l, r = [int(i) for i in input().split()]
ans += (l-current)%x + (r-l+1)
current = r+1
print(ans)
| (n, x) = [int(i) for i in input().split()]
current = 1
ans = 0
for i in range(n):
(l, r) = [int(i) for i in input().split()]
ans += (l - current) % x + (r - l + 1)
current = r + 1
print(ans) |
#print("Hello World")
print("Hello World")
a= 5
b =5
c = [9, 5,3]
if a == a:
print("Hello")
if a == c :
print("Hello")
if a > b:
print('Hello')
while True :
print ( "Hello" )
break
print ( a + b )
| print('Hello World')
a = 5
b = 5
c = [9, 5, 3]
if a == a:
print('Hello')
if a == c:
print('Hello')
if a > b:
print('Hello')
while True:
print('Hello')
break
print(a + b) |
#!/usr/bin/python3
def add(a, b):
i = a
j = b
return(i + j)
| def add(a, b):
i = a
j = b
return i + j |
#DictExample2.py
employee = {"Name":"Suprit","Age":22,"Company":"Wipro","Location":"Wipro"}
print("---------------------------------------------------")
print("Employee Name : ",employee['Name'])
print("Employee age : ",employee['Age'])
print("Employee Company : ",employee['Company'])
print("Company Locatio... | employee = {'Name': 'Suprit', 'Age': 22, 'Company': 'Wipro', 'Location': 'Wipro'}
print('---------------------------------------------------')
print('Employee Name : ', employee['Name'])
print('Employee age : ', employee['Age'])
print('Employee Company : ', employee['Company'])
print('Company Location : ', employee['Lo... |
#Four Fours
#Zero
print("Zero is ", 44-44)
# One
print("One is ", 4/4 * 4/4)
# Two
print("Two is ", (4*4)/(4+4) )
# Three
print("Three is ", (4 + 4 + 4)/4)
# Four
print("Four is ", (4-4)/4 + 4) | print('Zero is ', 44 - 44)
print('One is ', 4 / 4 * 4 / 4)
print('Two is ', 4 * 4 / (4 + 4))
print('Three is ', (4 + 4 + 4) / 4)
print('Four is ', (4 - 4) / 4 + 4) |
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def singleNumberK(nums, k):
ret = 0
count = [0] * 32
for i in xrange(0, 32):
for num in nums:
if ... | class Solution(object):
def single_number(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
def single_number_k(nums, k):
ret = 0
count = [0] * 32
for i in xrange(0, 32):
for num in nums:
if num & ... |
IMAGES_FOLDER = 'visual_images'
ACTUAL_IMAGE_BASE_FOLDER = 'actual'
DIFF_IMAGE_BASE_FOLDER = 'diff'
BASELINE_IMAGE_BASE_FOLDER = 'baseline'
MODE_TEST = 'test'
MODE_BASELINE = 'baseline'
REPORT_FILE = 'visualReport.html'
REPORT_EXPIRATION_THRESHOLD = 10
IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'bmp', 'raw', 'pdf']
ROBO... | images_folder = 'visual_images'
actual_image_base_folder = 'actual'
diff_image_base_folder = 'diff'
baseline_image_base_folder = 'baseline'
mode_test = 'test'
mode_baseline = 'baseline'
report_file = 'visualReport.html'
report_expiration_threshold = 10
image_extensions = ['png', 'jpg', 'jpeg', 'bmp', 'raw', 'pdf']
robo... |
"""
Triangles
A few functions that determine a points location
relative to a triangle
Author: Jared Siraco
"""
def splitPoints(r,q,testpoint,points): #splits points between points on the same side
if points == []:
return [],[]
if q==testpoint:
testpoint = points[0]
side1 = [] #as testpoint and those not... | """
Triangles
A few functions that determine a points location
relative to a triangle
Author: Jared Siraco
"""
def split_points(r, q, testpoint, points):
if points == []:
return ([], [])
if q == testpoint:
testpoint = points[0]
side1 = []
side2 = []
for p in points:
if same... |
print("a(x**2) + b(x) + c = 0")
print("Enter the values of a,b,c")
a = int(input("Enter the value of a:"))
b = int(input("Enter the value of b:"))
c = int(input("Enter the value of c:"))
d = b**2 - 4*(a*c)
x = (-b - (d**0.5))/(2*a)
y = (-b + (d**0.5))/(2*a)
print("The roots of the equation are :",x,"and", y)
| print('a(x**2) + b(x) + c = 0')
print('Enter the values of a,b,c')
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = int(input('Enter the value of c:'))
d = b ** 2 - 4 * (a * c)
x = (-b - d ** 0.5) / (2 * a)
y = (-b + d ** 0.5) / (2 * a)
print('The roots of the equation are :', x, 'and... |
with open('input.txt') as file:
data = [int(line.strip()) for line in file.readlines()]
# to speed things up a little bit...
data = list(sorted(data))
def part1():
for i in range(len(data)):
for j in range(i + 1, len(data)):
if data[i] + data[j] == 2020:
return data[i] * da... | with open('input.txt') as file:
data = [int(line.strip()) for line in file.readlines()]
data = list(sorted(data))
def part1():
for i in range(len(data)):
for j in range(i + 1, len(data)):
if data[i] + data[j] == 2020:
return data[i] * data[j]
return 0
def part2():
f... |
x = 0
if x < 1000 and x % 3 == 0:
print(x, "is a multiple of 3!")
x += 1
if x < 1000 and x % 3 == 0:
print(x, "is a multiple of 3!")
x += 1
if x < 1000 and x % 3 == 0:
print(x, "is a multiple of 3!")
x += 1
if x < 1000 and x % 3 == 0:
print(x, "is a multiple of 3!")
x += 1
| x = 0
if x < 1000 and x % 3 == 0:
print(x, 'is a multiple of 3!')
x += 1
if x < 1000 and x % 3 == 0:
print(x, 'is a multiple of 3!')
x += 1
if x < 1000 and x % 3 == 0:
print(x, 'is a multiple of 3!')
x += 1
if x < 1000 and x % 3 == 0:
print(x, 'is a multiple of 3!')
x += 1 |
class PythonPackageTemplate(object):
def __unicode__(self):
return "just a template"
@staticmethod
def ping():
return "pong"
| class Pythonpackagetemplate(object):
def __unicode__(self):
return 'just a template'
@staticmethod
def ping():
return 'pong' |
class ageError(Exception):#Creating a new exception class
def __init__(self,message):
Exception.__init__(self,message)
class nameError(Exception):
def __init(self,message):
Exception.__init__(self,message)
class marksError(Exception):
def __init__(self,message):
Exception.__init__(se... | class Ageerror(Exception):
def __init__(self, message):
Exception.__init__(self, message)
class Nameerror(Exception):
def __init(self, message):
Exception.__init__(self, message)
class Markserror(Exception):
def __init__(self, message):
Exception.__init__(self, message)
try:
... |
# https://www.hackerrank.com/challenges/absolute-permutation/problem
def absolutePermutation(n, k):
arr = list(range(1,n+1))
j = 0
l = -1
while(j<n):
l *= -1
for _ in range(max([1,k])):
arr[j] += l*k
j +=1
if(j==n):
break
return st... | def absolute_permutation(n, k):
arr = list(range(1, n + 1))
j = 0
l = -1
while j < n:
l *= -1
for _ in range(max([1, k])):
arr[j] += l * k
j += 1
if j == n:
break
return str(arr).replace(',', '')[1:-1] if sorted(arr) == list(range(1... |
try:
liczba1 = int (input())
except:
print("zjebales")
try:
liczba2 = int (input())
except:
print("zjebales")
try:
print (f"Twoja liczba to: {liczba1+liczba2}")
except:
print("zjebales") | try:
liczba1 = int(input())
except:
print('zjebales')
try:
liczba2 = int(input())
except:
print('zjebales')
try:
print(f'Twoja liczba to: {liczba1 + liczba2}')
except:
print('zjebales') |
class BaseType:
def check_value(self, value):
"""Check if value is good"""
pass
def set(self, value):
"""Check and set value"""
pass
def get(self):
"""Get value"""
pass
def to_save(self):
"""Build a serializable data to save"""
pass
... | class Basetype:
def check_value(self, value):
"""Check if value is good"""
pass
def set(self, value):
"""Check and set value"""
pass
def get(self):
"""Get value"""
pass
def to_save(self):
"""Build a serializable data to save"""
pass
... |
class Problem:
def __init__(self, inp):
self.data = [{}, {}, {}, {}, {}, {}, {}, {}]
for line in inp.read().strip().split("\n"):
for i, char in enumerate(line):
self.data[i][char] = self.data[i].get(char, 0) + 1
def step1(self):
return ''.join(map(lambda m: s... | class Problem:
def __init__(self, inp):
self.data = [{}, {}, {}, {}, {}, {}, {}, {}]
for line in inp.read().strip().split('\n'):
for (i, char) in enumerate(line):
self.data[i][char] = self.data[i].get(char, 0) + 1
def step1(self):
return ''.join(map(lambda m... |
db.define_table(
'di_order',
*bucket_generic_fields
)
db.define_table(
'di_order_outbox',
Field('parent', 'reference di_order'),
*bucket_outbox_generic_fields
)
# IMPORTANT - always set not required fields to default = "", or else != operator in queries will return wrong values
# #http... | db.define_table('di_order', *bucket_generic_fields)
db.define_table('di_order_outbox', field('parent', 'reference di_order'), *bucket_outbox_generic_fields)
db.define_table('di_order_note', field('parent', 'reference di_order'), *bucket_note_generic_fields) |
# -*- coding: utf-8 -*-
i=1
j=60
while j>-1:
print("I=%i J=%i"%(i,j))
i+=3
j-=5 | i = 1
j = 60
while j > -1:
print('I=%i J=%i' % (i, j))
i += 3
j -= 5 |
"""Simple example calling str.format(...) directly."""
name = "Peter"
price = 1.2
print(str.format("Hello {}, do you have ${:0.2f}?", name, price))
| """Simple example calling str.format(...) directly."""
name = 'Peter'
price = 1.2
print(str.format('Hello {}, do you have ${:0.2f}?', name, price)) |
'''
Xldlib/Onstart
______________
Modules to initializes XL Discoverer.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
'''
__all__ = [
'app',
'args',
'check_imports',
'error',
'launch',
'mai... | """
Xldlib/Onstart
______________
Modules to initializes XL Discoverer.
:copyright: (c) 2015 The Regents of the University of California.
:license: GNU GPL, see licenses/GNU GPLv3.txt for more details.
"""
__all__ = ['app', 'args', 'check_imports', 'error', 'launch', 'main', 'process', 'registers'... |
"""
Copyright 2020 Twitter, Inc.
SPDX-License-Identifier: Apache-2.0
"""
development_seed = 1684992425
seeds = [
4258031807,
3829679737,
3706579387,
789594926,
3628091752,
54121625,
825346923,
646393804,
1579300575,
246132812,
2882726575,
970387138,
413984459,
28... | """
Copyright 2020 Twitter, Inc.
SPDX-License-Identifier: Apache-2.0
"""
development_seed = 1684992425
seeds = [4258031807, 3829679737, 3706579387, 789594926, 3628091752, 54121625, 825346923, 646393804, 1579300575, 246132812, 2882726575, 970387138, 413984459, 288449314, 1594895720, 1950255998, 4015021126, 3798842978, 2... |
s = input()
r = input()
t = ""
for i in range(1, len(s) + 1):
t += s[-i]
if r == t:
print("YES")
else:
print("NO")
| s = input()
r = input()
t = ''
for i in range(1, len(s) + 1):
t += s[-i]
if r == t:
print('YES')
else:
print('NO') |
n = int(input('Enter number of levels: '))
for i in range(1, n + 1):
string = "\t" * (n - i)
for j in range(i):
string += '*\t'
print(string)
| n = int(input('Enter number of levels: '))
for i in range(1, n + 1):
string = '\t' * (n - i)
for j in range(i):
string += '*\t'
print(string) |
n = int(input())
my_list = []
is_balanced = True
old_line = ''
for i in range(n):
line = input()
if line == '(' and old_line == '(':
is_balanced = False
my_list.append(line)
old_line = line
if my_list.count('(') == my_list.count(')') and is_balanced:
print('BALANCED')
else:
print('UNBA... | n = int(input())
my_list = []
is_balanced = True
old_line = ''
for i in range(n):
line = input()
if line == '(' and old_line == '(':
is_balanced = False
my_list.append(line)
old_line = line
if my_list.count('(') == my_list.count(')') and is_balanced:
print('BALANCED')
else:
print('UNBALA... |
# Python program to print prime numbers in an interval
def print_primes(lower_limit: int, upper_limit: int) -> None:
# iterating the lower interval till it reaches the upper interval
for i in range(lower_limit, upper_limit + 1):
if lower_limit > 1:
interval = 2
# now as 2 is al... | def print_primes(lower_limit: int, upper_limit: int) -> None:
for i in range(lower_limit, upper_limit + 1):
if lower_limit > 1:
interval = 2
for j in range(interval, i + 1):
if i % j == 0:
break
else:
print(i)
lower = in... |
#!/usr/bin/env python3
# encoding: utf-8
"""
@version: 0.1
@author: lyrichu
@license: Apache Licence
@contact: 919987476@qq.com
@site: http://www.github.com/Lyrichu
@file: pso_config.py
@time: 2018/06/07 23:11
@description:
config settings for PSO
"""
class BASIC_CONFIG:
def __init__(self):
self.c1 = 1.49... | """
@version: 0.1
@author: lyrichu
@license: Apache Licence
@contact: 919987476@qq.com
@site: http://www.github.com/Lyrichu
@file: pso_config.py
@time: 2018/06/07 23:11
@description:
config settings for PSO
"""
class Basic_Config:
def __init__(self):
self.c1 = 1.49445
self.c2 = 1.49445
se... |
class Solution:
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = []
nums.sort()
for i in range(len(nums)-2):
if i and nums[i-1] == nums[i]:
continue
... | class Solution:
def four_sum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = []
nums.sort()
for i in range(len(nums) - 2):
if i and nums[i - 1] == nums[i]:
continue
... |
"""An event's location."""
class EventLocation:
"""An event's location as a textual description and a list of places."""
def __init__(self, description, places):
"""Initialize with the location description and a list of places."""
self.description = description
self.places = places
... | """An event's location."""
class Eventlocation:
"""An event's location as a textual description and a list of places."""
def __init__(self, description, places):
"""Initialize with the location description and a list of places."""
self.description = description
self.places = places
... |
a=0
b=1
input_n = int(input("Enter the number till you want to find fiboncci:"))
print(a,b,end=' ')
for i in range(2,input_n): # Since two numbers are already printed so now we will start range from 2
c= a+b
print(c,end= ' ')
a = b
b =c
print("\n\nFibonacci number of ",input_n," is ",c)
| a = 0
b = 1
input_n = int(input('Enter the number till you want to find fiboncci:'))
print(a, b, end=' ')
for i in range(2, input_n):
c = a + b
print(c, end=' ')
a = b
b = c
print('\n\nFibonacci number of ', input_n, ' is ', c) |
#!/usr/bin/env python3
# GUI
def required_option_not_set(option_name):
readable_name = option_name.replace('_', ' ').title()
return 'Option {0} is required but not set'.format(readable_name)
# Scraping
SCRAPE_INVALID_PLATFORM = 'You must provide a valid platform (emulated system) to enable scraping'
SCRAPE_... | def required_option_not_set(option_name):
readable_name = option_name.replace('_', ' ').title()
return 'Option {0} is required but not set'.format(readable_name)
scrape_invalid_platform = 'You must provide a valid platform (emulated system) to enable scraping'
scrape_invalid_module = 'You must provide a valid s... |
def read_matrix():
matrix_size = int(input())
matrix = []
for _ in range(matrix_size):
matrix.append(input().split())
return matrix
matrix = read_matrix()
symbol = input()
is_found = False
for col in range(len(matrix)):
if symbol in matrix[col][0]:
index, column = matrix[col][0... | def read_matrix():
matrix_size = int(input())
matrix = []
for _ in range(matrix_size):
matrix.append(input().split())
return matrix
matrix = read_matrix()
symbol = input()
is_found = False
for col in range(len(matrix)):
if symbol in matrix[col][0]:
(index, column) = (matrix[col][0].i... |
# my_lambdata/my_mod.py
def enlarge(n):
"""
Param n is a number
Function will enlarge the number
"""
return n * 100
# this code breaks our ability to import enlarge from other files, if left in the global scope:
#
# print("HELLO")
# y = int(input("Please choose a number"))
# print(y, enlarge(y))
... | def enlarge(n):
"""
Param n is a number
Function will enlarge the number
"""
return n * 100
if __name__ == '__main__':
print('HELLO')
y = int(input('Please choose a number'))
print(y, enlarge(y)) |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
d={}
for i,n in enumerate(nums):
d_n=target-n
if d_n in d:
return [d[d_n],i]
d[n]=i
return [None,None]
| class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
d = {}
for (i, n) in enumerate(nums):
d_n = target - n
if d_n in d:
return [d[d_n], i]
d[n] = i
return [None, None] |
"""
Input validation classes.
"""
yn_answers = ['y', 'n', 'yes', 'no']
commands = ['mkfs', 'open', 'ls', 'read', 'write', 'seek', 'close',
'mkdir', 'rmdir', 'tree', 'cd', 'cat', 'import', 'export']
def validate_yes_no(text):
if text:
if text not in yn_answers:
print('This i... | """
Input validation classes.
"""
yn_answers = ['y', 'n', 'yes', 'no']
commands = ['mkfs', 'open', 'ls', 'read', 'write', 'seek', 'close', 'mkdir', 'rmdir', 'tree', 'cd', 'cat', 'import', 'export']
def validate_yes_no(text):
if text:
if text not in yn_answers:
print('This input is not yes, ... |
#!/usr/bin/env python3
def search_insert(nums, target: int) -> int:
start = 0
end = len(nums) - 1
mid = 0
while start <= end:
mid = (start + end) // 2
curr = nums[mid]
if curr == target:
return mid
if target < curr:
end = mid - 1
else:
... | def search_insert(nums, target: int) -> int:
start = 0
end = len(nums) - 1
mid = 0
while start <= end:
mid = (start + end) // 2
curr = nums[mid]
if curr == target:
return mid
if target < curr:
end = mid - 1
else:
start = mid + 1... |
class ProcessorProperty:
def __init__(self, label, default_value, min_value=None, max_value=None):
self.label = label
self.value = default_value
self.default_value = default_value
self._type = type(default_value)
self.min_value = min_value
self.max_value = max_value
... | class Processorproperty:
def __init__(self, label, default_value, min_value=None, max_value=None):
self.label = label
self.value = default_value
self.default_value = default_value
self._type = type(default_value)
self.min_value = min_value
self.max_value = max_value
... |
## Tower of Hanoi
# Given the number of disks and the three towers labels, the program will displays the moves required to solve.
def TowerOfHanoi(numDisks, source, intermediate, destination):
if(numDisks == 1):
print("Move Disk 1 From Pole {} to Pole {}".format(source, destination)) # if there is onl... | def tower_of_hanoi(numDisks, source, intermediate, destination):
if numDisks == 1:
print('Move Disk 1 From Pole {} to Pole {}'.format(source, destination))
return
tower_of_hanoi(numDisks - 1, source, destination, intermediate)
print('Move Disk {} From Pole {} to Pole {}'.format(numDisks, sou... |
a = 1
b = 2
c = a + b
d = '668'
| a = 1
b = 2
c = a + b
d = '668' |
class RowSource(object):
def get_rows(self, start, count):
raise Exception("not implemented")
class FileRowSource(RowSource):
def __init__(self, fileobj):
super().__init__();
self.fileobj = fileobj
def next_page(self, rows):
lines = []
for i in range(rows):
... | class Rowsource(object):
def get_rows(self, start, count):
raise exception('not implemented')
class Filerowsource(RowSource):
def __init__(self, fileobj):
super().__init__()
self.fileobj = fileobj
def next_page(self, rows):
lines = []
for i in range(rows):
... |
"""
Static values about mods and mod actions that generally shouldn't need to change.
"""
BOTS = ["AnimeMod", "AutoModerator"]
ADMINS = ["reddit", "Reddit Legal", "Anti-Evil Operations"]
# There are more types of actions that can be set here, currently used in selecting distinct posts/comments/users.
MOD_ACTIONS_POS... | """
Static values about mods and mod actions that generally shouldn't need to change.
"""
bots = ['AnimeMod', 'AutoModerator']
admins = ['reddit', 'Reddit Legal', 'Anti-Evil Operations']
mod_actions_posts = ['approvelink', 'editflair', 'removelink', 'spamlink', 'spoiler', 'unspoiler']
mod_actions_comments = ['approveco... |
#!/usr/bin/env python3
name = input("what is your name? ")
print("hello", name)
| name = input('what is your name? ')
print('hello', name) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.