content stringlengths 7 1.05M |
|---|
class Solution(object):
def firstMissingPositive(self, nums):
size = len(nums)
for i in range(size):
v = nums[i]
if v<1 or v > size:
nums[i]=size+10
for i in range(size):
v = abs(nums[i])
if v >0 and v<=size and nums[v-1]>0:
nums[v-1] = -nums[v-1]
for i in range(size):
if nums[i] >=0:
return i+1
return size + 1
def test():
s = Solution()
a=[1,2,7,8,3,9,11,12]
a=[1,2,3]
a=[1,2,3,0]
a=[1,1]
a=[1,2,0]
a=[0,1,2]
a=[1]
print(a)
r = s.firstMissingPositive(a)
print(a)
print(r)
test()
|
# -*- coding: utf-8 -*-
class DbRouter(object):
external_db_models = ['cdr', 'numbers']
def db_for_read(self, model, **hints):
"""
Use original asterisk Db tables for read
"""
if model._meta.model_name.lower() in self.external_db_models:
return 'asterisk'
return None
def db_for_write(self, model, **hints):
if model._meta.model_name.lower() in self.external_db_models:
return 'asterisk'
return None
def allow_relation(self, obj1, obj2, **hints):
return True
def allow_migrate(self, db, app_label, model=None, **hints):
if app_label == 'asterisk':
return db == 'asterisk'
return True
|
a = (2, 5, 4)
b = (5, 8, 1, 2)
c = a + b
d = b + a
print(a)
print(b)
print(c)
print(len(c))
print(c.count(5)) #quantas vezes esta aparecendo o número 5 dentro de c.
print(c.index(8)) #em que posição está o número 8.
print(d) |
{
"targets": [
{
"target_name": "index"
}
]
} |
def countingSort(array):
size = len(array)
output = [0] * size
count = [0] * 10
for i in range(0, size):
count[array[i]] += 1
for j in range(1,10):
count[j] += count[j-1]
a = size-1
while a >= 0:
output[count[array[a]]-1] = array[a]
count[array[a]] -= 1
a -= 1
return output
unsorted_array = [4,2,2,2,8,8,3,3,1,7]
sorted_array=countingSort(unsorted_array)
print('Sorted Array:',sorted_array)
## OUTPUT:
'''
Sorted Array: [1, 2, 2, 2, 3, 3, 4, 7, 8, 8]
''' |
# Uses python3
def calc_fib(n):
fib_nums = []
fib_nums.append(0)
fib_nums.append(1)
for i in range(2, n + 1):
fib_nums.append(fib_nums[i - 1] + fib_nums[i - 2])
return fib_nums[n]
n = int(input())
print(calc_fib(n))
|
# -*- coding: utf-8 -*-
"""
State engine for django models.
Define a state graph for a model and remember the state of each object.
State transitions can be logged for objects.
"""
#: The version list
VERSION = (2, 0, 1)
#: The actual version number, used by python (and shown in sentry)
__version__ = '.'.join(map(str, VERSION))
__all__ = [
'__version__',
]
|
#Narcissistic Number: (find all this kinds of number fromm 100~999)
#example: 153 = 1**3 + 5**3 + 3**3
#................method 1............................
# for x in range(100, 1000):
# digit_3 = x//100
# digit_2 = x%100//10
# digit_1 = x%10
# if x == digit_3**3 + digit_2**3 + digit_1**3:
# print (x)
#................method 2............................
# for x in range(100,1000):
# s=str(x)
# digit_3 = int(s[0])
# digit_2 = int(s[1])
# digit_1 = int(s[2])
# if x == digit_3**3 + digit_2**3 + digit_1**3:
# print (x)
#................method 3............................
for digit_3 in range(1, 10):
for digit_2 in range(10):
for digit_1 in range (10):
x = 100*digit_3 + 10*digit_2 + digit_1
if x == digit_3**3 + digit_2**3 + digit_1**3:
print (x) |
"""
Copyright 2021 - Giovanni (iGio90) Rocca
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
BIG_ENDIAN = 'big endian'
LITTLE_ENDIAN = 'little endian'
DATA_TYPES = [
('byte', 1),
('short', 2),
('int', 4),
('long', 8),
('varInt', 0),
('string', 0),
('array', 0)
]
class DataType:
def __init__(self, data_type, endianness, length_type=None):
self.data_type = data_type
self.endianness = endianness
self.length_type: DataType = length_type
def get_length(self):
return DATA_TYPES[self.data_type][1]
def get_endianness_value(self):
return 'big' if self.endianness == 0 else 'little'
def serialize(self):
obj = {
'data_type': self.data_type,
'endianness': self.endianness,
'length': None
}
if self.length_type is not None:
obj['length'] = self.length_type.serialize()
return obj
|
status = True
print(status)
print(type(status))
status = False
print(status)
print(type(status))
soda = 'coke'
print(soda == 'coke')
print(soda == 'pepsi')
print(soda == 'Coke')
print(soda != 'root beer')
names = ['mike', 'john', 'mary']
mike_status = 'mike' in names
bill_status = 'bill' in names
print(mike_status)
print(bill_status)
not_bill_status = 'bill' not in names
print(not_bill_status) |
def pytest_assertrepr_compare(op, left, right):
# add one more line for "assert ..."
return (
['']
+ ['---']
+ ['> ' + _.text for _ in left]
+ ['---']
+ ['> ' + _.text for _ in right]
)
def pytest_addoption(parser):
parser.addoption('--int', type='int')
def pytest_generate_tests(metafunc):
if 'int_test' in metafunc.fixturenames:
tests = []
count = metafunc.config.getoption('int')
if count:
tests = metafunc.module.int_tests(count)
metafunc.parametrize('int_test', tests)
|
def solution(s):
answer = []
str_idx = 0
for cont in s:
if cont.isalpha() == True:
if str_idx % 2 == 0:
answer.append(cont.upper())
else:
answer.append(cont.lower())
str_idx = str_idx + 1
else:
if cont == ' ':
str_idx = 0
answer.append(cont)
return ''.join(answer) |
MAX_ROWS_DISPLAYABLE = 60
MAX_COLS_DISPLAYABLE = 80
cmap_freq = 'viridis'
cmap_grouping = 'copper' # 'Greys'
grouping_text_color = 'white'
grouping_text_color_background = 'grey'
grouping_fontweight = 'bold'
|
h = int(input("请输入总头数:"))
f = int(input("请输入总脚数:"))
if(f % 2 != 0):
f = int(input("请输入总脚数(必须是偶数):"))
def fun1(h, f):
rabbits = f/2-h
chicken = h-rabbits
if(chicken < 0 or rabbits < 0):
return '无解'
return chicken, rabbits
def fun2(h, f):
for i in range(0, h+1):
if(2*i + 4*(h-i) == f):
return i, h-i
return '无解'
if(h > 0 and f > 0 and f % 2 == 0):
if fun1(h, f) == '无解' and fun2(h, f) == '无解':
print("方法一:无解,请重新运行测试!")
print("方法二:无解,请重新运行测试!")
else:
print("方法一:鸡:{0:0.0f}只,兔:{1:0.0f}只".format(
fun1(h, f)[0], fun1(h, f)[1]))
print("方法二:鸡:{0:0.0f}只,兔:{1:0.0f}只".format(
fun2(h, f)[0], fun2(h, f)[1]))
|
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
for s in [*open(0)][1:]:
n,m=map(int,s.split())
print(0-(-n*m)//2) |
"""
Problem:
Given a non-empty array, return true if there is a place to split the array so
that the sum of the numbers on one side is equal to the
sum of the numbers on the other side.
canBalance([1, 1, 1, 2, 1]) → true
canBalance([2, 1, 1, 2, 1]) → false
canBalance([10, 10]) → true
"""
def canBalance(arr):
"""
Determine if a list of numbers is balance.
Parameter:
arr := list of numbers
Return:
True if a split position can be found in the arr such that
both halves sum of numbers are equal.
False otherwise.
Assuming numbers can be integers or float
"""
show_result = lambda b: print("canBalance({}) = {}".format(arr, b))
# Empty list or None cannot be split
if arr is None or len(arr) == 0:
show_result(False)
return False
total = sum(arr)
half = 0
# Compute if there is a balance half of sum equal to other half.
for x in arr:
if half == total/2:
break
half += x
else:
# Loop complete successfully without break
# Therefore, there isn't any split in the array such that the sum of
# the numbers on one side is equal to the sum of numbers on the other
# side.
show_result(False)
return False
show_result(True)
return True
def canBalance2(arr):
"""
Determine if a list of numbers is balance.
Parameter:
arr := list of numbers
Return:
True if a split position can be found in the arr such that
both halves sum of numbers are equal.
False otherwise.
Assuming numbers can be only integers
"""
show_result = lambda b: print("canBalance2({}) = {}".format(arr, b))
# Empty list or None cannot be split
if arr is None or len(arr) == 0:
show_result(False)
return False
total = sum(arr)
# Since numbers are only integers, there will be no balance for
# odd numbers.
if total % 2 != 0:
show_result(False)
return False
half = 0
# Compute if there is a balance half of sum equal to other half.
for x in arr:
if half == total/2:
break
half += x
else:
# Loop complete successfully without break
# Therefore, there isn't any split in the array such that the sum of
# the numbers on one side is equal to the sum of numbers on the other
# side.
show_result(False)
return False
show_result(True)
return True
if __name__ == "__main__":
canBalance([1, 1, 1, 2, 1])
canBalance([2, 1, 1, 2, 1])
canBalance([10, 10])
print()
canBalance2([1, 1, 1, 2, 1])
canBalance2([2, 1, 1, 2, 1])
canBalance2([10, 10])
|
# Implement division of two positive integers without using the division,
# multiplication, or modulus operators. Return the quotient as an integer,
# ignoring the remainder.
def division(divident, divisor):
quotient = 0
if divident == 0:
return 0
elif divisor == 0:
raise ZeroDivisionError('Divisor cannot be 0.')
tmp = 0
for i in range(31, -1, -1):
if tmp + (divisor << i) <= divident:
tmp += (divisor << i)
quotient |= (1 << i)
return quotient
if __name__ == '__main__':
for x, y in [(0, 2), (4, 2), (1000000, 1), (5, 3), (20, 7), (30, 3), (2, 0)]:
print('{} ÷ {} = {}'.format(x, y, division(x, y))) |
class AccelerationException(Exception):
def __init__(self, message='This is neither acceleration nor deceleration... Go away and program Java, BooN'):
self.message = message
super().__init__(self.message)
class NoMemberException(Exception):
def __init__(self, message='This truck is not a convoy member'):
self.message = message
super().__init__(self.message)
class TruckBrokenException(Exception):
def __init__(self, message='A broken truck can\'t do this'):
self.message = message
super().__init__(self.message)
|
class InvalidValueError(Exception):
pass
class NotFoundError(Exception):
pass
|
numConv = conv = 0
while(conv != 4):
decimal = int(input('Digite o número decimal: '))
print('''
1 - Converter para binário
2 - Converter para hexadecimal
3 - Converter para octal
4 - Sair
''')
conv = int(input('Escolha uma opção: '))
if(conv == 1):
numConv = format(decimal, "b")
print(f'O número {decimal} em binário é {numConv}')
elif(conv == 2):
numConv = format(decimal, "x")
print(f'O número {decimal} em hexadecimal é {numConv}')
elif(conv == 3):
numConv = format(decimal, "o")
print(f'O número {decimal} em octal é {numConv}')
|
c = get_config()
c.ContentsManager.root_dir = "/root/"
c.NotebookApp.allow_root = True
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.open_browser = False
c.NotebookApp.port = 8888
# Comment out this line or first hash your own password
#c.NotebookApp.password = u'sha1:1234567abcdefghi'
c.ContentsManager.allow_hidden = True
|
r,c=map(int,input('enter number of rows and columns of matrix: ').split())
m1=[]
m2=[]
a=[]
print('<<<<< enter element of matrix1 >>>>>')
for i in range(r):
l=[]
for j in range(c):
l.append(int(input(f"enter in m1[{i}][{j}]: ")))
m1.append(l)
print('<<<<< enter element of matrix2 >>>>>')
for i in range(r):
l=[]
for j in range(c):
l.append(int(input(f"enter in m2[{i}][{j}]: ")))
m2.append(l)
#addition of two matrix
print('<<<<< addition of two matrix >>>>>')
for i in range(r):
l=[]
for j in range(c):
l.append(int(m1[i][j])+int(m2[i][j]))
a.append(l)
print(a)
'''
output:
enter number of rows and columns of matrix: 2 2
<<<<< enter element of matrix1 >>>>>
enter in m1[0][0]: 21
enter in m1[0][1]: 22
enter in m1[1][0]: 23
enter in m1[1][1]: 24
<<<<< enter element of matrix2 >>>>>
enter in m2[0][0]: 1
enter in m2[0][1]: 2
enter in m2[1][0]: 3
enter in m2[1][1]: 4
<<<<< addition of two matrix >>>>>
[[22, 24], [26, 28]]
'''
|
## Find peak element in an array
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
## Iterative Binary Search
l, r = 0, len(nums)-1
while l<r:
mid = (l+r)//2
if nums[mid] > nums[mid+1]:
r = mid
else:
l = mid+1
return l
|
class Solution:
def numberOfWeeks(self, milestones: List[int]) -> int:
k = sorted(milestones,reverse = True)
t = sum(k) - k[0]
if k[0] <= t+1:
return sum(k)
else:
return 2*t+ 1 |
# from geometry_msgs.msg import PoseStamped
# from geometry_msgs.msg import TwistStamped
# from autoware_msgs.msg import DetectedObjectArray
# from derived_object_msgs.msg import ObjectArray
# from carla_msgs.msg import CarlaEgoVehicleStatus
# from grid_map_msgs.msg import GridMap
PERCISION = 4
"""
Ego:
pos: (x, y),
heading: (x, y ,z, w),
velocity: (x, y),
accel: (x, y)
GroundTruth:
tag: string,
pos: (x, y),
heading: (x, y, x, w),
velocity: (x, y),
size: (x, y ,z)
Perception:
pos: (x, y),
heading: (x, y, x, w),
velocity: (x, y),
size: (x, y ,z)
"""
class Ego:
def __init__(self, pose_msg, velocity_msg, accel_msg):
self.pos = (pose_msg.pose.position.x, pose_msg.pose.position.y)
self.heading = (pose_msg.pose.orientation.x, pose_msg.pose.orientation.y, pose_msg.pose.orientation.z, pose_msg.pose.orientation.w)
self.velocity=(velocity_msg.twist.linear.x, velocity_msg.twist.linear.y)
self.accel=(accel_msg.acceleration.linear.x, accel_msg.acceleration.linear.y)
def data(self):
return (self.pos, self.heading, self.velocity, self.accel)
class GroundTruth:
# pose_msg indicates position of the ego vehicle
def __init__(self, pose_msg, obj_msg):
obj_msg.pose.position.x -= pose_msg.pose.position.x
obj_msg.pose.position.y -= pose_msg.pose.position.y
self.tag = ""
if(obj_msg.classification == 4):
self.tag = "pedestrian_"
elif(obj_msg.classification >= 5 and obj_msg.classification <= 9):
self.tag = "npc_"
self.tag += str(obj_msg.id)
self.pos = (obj_msg.pose.position.x, obj_msg.pose.position.y)
self.heading=(obj_msg.pose.orientation.x, obj_msg.pose.orientation.y, obj_msg.pose.orientation.z, obj_msg.pose.orientation.w)
self.velocity=(obj_msg.twist.linear.x, obj_msg.twist.linear.y)
self.size = (obj_msg.shape.dimensions[0], obj_msg.shape.dimensions[1], obj_msg.shape.dimensions[2])
def data(self):
return (self.pos, self.heading, self.velocity, self.size)
class Perception:
def __init__(self, obj_msg):
self.tag = str(obj_msg.id)
self.pos = (obj_msg.pose.position.x, obj_msg.pose.position.y)
self.heading=(obj_msg.pose.orientation.x, obj_msg.pose.orientation.y, obj_msg.pose.orientation.z, obj_msg.pose.orientation.w)
self.velocity=(obj_msg.velocity.linear.x, obj_msg.velocity.linear.y)
self.size = (obj_msg.dimensions.x, obj_msg.dimensions.y, obj_msg.dimensions.z)
def data(self):
return (self.pos, self.heading, self.velocity, self.size)
|
class FilterModule(object):
''' Ansible core jinja2 filters '''
def filters(self):
return {
'infer_address' : self.infer_address
}
def infer_address(self, hostname, hostvars):
for t in ('ansible_ssh_host', 'ansible_host', 'inventory_hostname'):
if t in hostvars[hostname]:
return hostvars[hostname][t]
return None
|
def check_log(recognition_log):
pair = recognition_log.split(",")
filename_tested = pair[0].split("/")[-1]
filename_result = pair[1].split("/")[-1]
no_extension_tested = filename_tested.split(".")[0]
no_extension_result = filename_result.split(".")[0]
check = no_extension_tested == no_extension_result
return check
def is_header(recognition_log):
pair = recognition_log.split(",")
is_header = pair[0] == "tolerance"
return is_header
false_pos = -1
true_pos = -1
tolerance = ""
first_time = True
filepath = './result.txt'
with open(filepath) as fp:
for cnt, line in enumerate(fp):
if(is_header(line)):
if first_time:
first_time = False
else:
with open('tolerance_exp.csv', 'a') as the_file:
the_file.write("%s,%i,%i\n" % (tolerance,true_pos,false_pos))
false_pos = 0
true_pos = 0
tolerance = (line.split(",")[1][:-1])
else:
if check_log(line):
true_pos += 1
else:
false_pos += 1
with open('tolerance_exp.csv', 'a') as the_file:
the_file.write("%s,%i,%i\n" % (tolerance,true_pos,false_pos))
|
class ResponseError(Exception):
"""Raised when the bittrex API returns an
error in the message response"""
class RequestError(Exception):
"""Raised when the request towards the bittrex
API is incorrect or fails"""
|
class GetTalk:
def __init__(self, words):
self.words = words
def get_message(self, item):
message = self.words[item]
return message
def get_talk(self, msg, *args):
zero_message = False
for item in self.words:
if item in msg:
message = self.get_message(item)
zero_message = True
return message
if zero_message == False:
message = 'Я не понимаю вас'
return message
|
per_cent = {'ТКБ': 5.6, 'СКБ': 5.9, 'ВТБ': 4.28, 'СБЕР': 4.0}
for k, v in per_cent.items():
per_cent[k] = round(v * m) # умножаем каждое значение из словаря на вводимое число
print("Сумма, которую вы можете заработать: ", list(per_cent.values()))
my_max_val = 0
for k,v in per_cent.items():
if v > my_max_val:
my_max_val=v
my_max_key=k
print("Самый выгодный депозит в банке: ", my_max_key)
print("Сумма самого выгодного депозита: ", my_max_val)
|
def cw_distance(az1: float, az2: float) -> float:
"""
Calculates the 'clockwise' distance between two azimuths, where 0 = North
and the direction of increasing angle is clockwise.
:param az1: Azimuth 1.
:type az1: float
:param az2: Azimuth 2.
:type az2: float
:returns: The angular distance between the azimuths, positive, going
clockwise.
:rtype: float
"""
diff = (az2 - az1) % 360
return diff
|
#!/usr/bin/env python3
def mod_sum(n):
return sum([x for x in range(n) if (x % 3 == 0) or (x % 5 == 0)])
|
class Detector(object):
"""detection algorithm to be implemented by sub class
input parameters: self and frame to be worked with
Must return frame after being processed and radius"""
def __init__(self):
"""init function"""
pass
def detection_algo(self, frame):
"""To be implemented by subclass"""
pass
|
def display(summary, *args):
args = list(args)
usage = ""
example = ""
details = ""
delimiter = "="
try:
usage = args.pop(0)
example = args.pop(0)
details = args.pop(0)
except IndexError:
# End of arg list
pass
for x in range(1, len(summary)):
delimiter = delimiter + "="
print("")
print(summary)
print(delimiter)
if usage:
print("Usage: " + usage)
if example:
print("Example: " + example)
if details:
print("")
print(details)
print("")
|
# -*- coding: utf-8 -*-
'''
Created on Mar 12, 2012
@author: hathcox
Copyright 2012 Root the Box
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, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
class Form(object):
''' Held by FormHandler's to deal with easy validation '''
def __init__(self, *args, **kwargs):
self.form_pieces = []
# Iterate over the dictionary
for name, msg in kwargs.iteritems():
# if we got supplied with a valid pair
if isinstance(name, basestring) and isinstance(msg, basestring):
piece = FormPiece(name, msg)
self.form_pieces.append(piece)
def __get_piece_names__(self):
''' returns peices that are marked with required true '''
required_pieces = []
for piece in self.form_pieces:
required_pieces.append(piece.name)
return required_pieces
def __contains_list__(self, small, big):
'''
Checks to make sure that all of the smaller list in inside of
the bigger list
'''
all_exist = True
for item in small:
if item not in big:
all_exist = False
return all_exist
def __get_piece_by_name__(self, name):
''' returns a FormPiece based on name '''
for piece in self.form_pieces:
if piece.name == name:
return piece
return None
def set_validation(self, argument_name, error_message):
'''
Use this to set the argument's error message and type after
creating a form
'''
piece = self.__get_piece_by_name__(argument_name)
# If we have a piece by that name
if piece is not None:
piece.error_message = error_message
def __get_error_messages__(self, arguments, required_pieces):
''' Returns a list of all applicable error messages '''
self.errors = []
for piece in required_pieces:
# If the peice isn't in our argument list
if piece.name not in arguments:
self.errors.append(piece.error_message)
def validate(self, arguments=None):
'''
This method is used to validate that a form's arguments
are actually existant
'''
if arguments is not None:
self.__get_error_messages__(arguments, self.form_pieces)
return 0 == len(self.errors)
return False
class FormPiece():
''' This is essentialy a wrapper for a given Input html tag '''
def __init__(self, name, error_message="Please Fill Out All Forms"):
'''
name is the argument name, and required is wether
or not we care if we got some entry
'''
self.name = name
self.error_message = error_message
|
print(" _________ _____ ______ _________ ____ ______ ___________ ________ _________ ")
print(" | | | | / \ | | | | | ")
print(" | | | | /______\ | | | | |--------- ")
print(" | __|__ |______ | / \ |______ | |________| |_________ ")
print("\n\n")
print("This is a simple project [tic tac toe game] developed by Mr Ayush ")
lis=[]
for i in range(1,4):
lis.append(['*','*','*'])
def print_pattern(lis):
print(" [1] [2] [3]")
print("[1] %c |%c |%c"%(lis[0][0],lis[0][1],lis[0][2]))
print(" __|__|__")
print("[2] %c |%c |%c"%(lis[1][0],lis[1][1],lis[1][2]))
print(" __|__|__")
print("[3] %c |%c |%c"%(lis[2][0],lis[2][1],lis[2][2]))
print_pattern(lis)
print("\n\nTIC TAC TOE BOARD")
print("\nHERE * REPRESNT THE POSITION WHERE CHARACTER WILL BE PLOTTED\n\n")
name_first,name_second=input("Enter the name of FIRST PLAYER (-_-):="),input("Enter the name of SECOND PLAYER (-_-):=")
ch1,ch2=input("Enter the first character (^_^):= "),input("Enter the second chararcter (^_^):= ")
entry=int(input("Enter 1 if the FIRST turn is given to FIRST PLAYER ELSE the turn will be given to SECOND PLAYER:="))
print("\n\n\n")
print("Let's play!!!!!!!!!!")
def check_the_game_status(lis,x,y):
if lis[x][0]==lis[x][1]==lis[x][2]: #for checking horizontal line
return True
elif lis[0][y]==lis[1][y]==lis[2][y]: #for checking vertical line
return True
elif x==y: # for checking diagonal line
m=x
n=y
x=0
y=0
if lis[x][y]==lis[x+1][y+1]==lis[x+2][y+2]:
return True
elif m==1 and n==1:
x=0
y=2
if lis[x][y]==lis[x+1][y-1]==lis[x+2][y-2]:
return True
else:
return False
else:
return False
elif (x==0 and y==2) or (x==2 and y==0):
x=0
y=2
if lis[x][y]==lis[x+1][y-1]==lis[x+2][y-2]:
return True
else:
return False
lis=[]
for x in range(3):
lis.append([' ',' ',' '])
DATABASE=[] # to store the moves value(x,y) ,,, if someone enter the value which is already filled then it can be checked from here
print("PLEASE INPUT WHEN VALUE OF ROW AND COLUMN NUMBER WHEN ASKED AND INPUT IT WITH SEPARATED BY SINGLE SPACE (*_*)")
print("\n\n")
for m in range(9):
print("Enter the value of ROW and COLUMN number:=",end="")
x,y=list(map(eval,input().split(" ")))
while x>3 or y>3:
print("YOU HAVE ENTERED INVALID ROW-COLUMN VALUE,,PLEASE ENTER AGAIN:=")
x,y=list(map(eval,input().split(" ")))
x-=1
y-=1
while [x,y] in DATABASE:
print("!!!YOU HAVE ENTERED A VALUE ON BOARD WHICH IS ALREADY FILLED")
print("!!!AGAIN ENTER VALUES OF ROW AND COLUMN NUMBER:=")
x,y=list(map(eval,input().split(" ")))
DATABASE.append([x,y])
print("")
if entry==1:
lis[x][y]=ch1
current=name_first
entry=0
else:
lis[x][y]=ch2
current=name_second
entry=1
print_pattern(lis)
if check_the_game_status(lis,x,y):
print(current,"player WINS!!! (0_0) (0_0) (0_0),HOPE YOU ENJOYED(^_^)")
break
else:
print("Game TIED (0_0)!!!!!!!!!!")
|
def Cron_Practice_help():
helpHand = """Hey There
Some useful commands -
fab - To Favorite Questios for Today
tasks - To see the questions that are scheduled for today
compile - To compile the tasks into a CSV File"""
print(helpHand)
def Cron_Practice_invalid():
print("Sorry Invalid Command !")
Cron_Practice_help() |
# Write your code here
n,k = [int(x) for x in input().split()]
l = []
while n > 0 :
a = int(input())
l.append(a)
n -= 1
while(l[0] <= k) :
l.pop(0)
l = l[::-1]
while (l[0] <= k) :
l.pop(0)
#print(l)
print(len(l))
|
numero = int(input('Digite um número: '))
basedec = int(input('Qual base de conversão você deseja? \n 1 - Biário \n 2 - Octal \n 3 - Hexadecimal \n '))
if basedec == 1:
print("A coversão de {} para binario é : {}".format(numero, bin(numero)[2:]))
elif basedec == 2:
print('A conversão de {} para octal é : {}'.format(numero, oct(numero)[2:]))
elif basedec == 3:
print('A conversão de {} para hexadecimal é: {}'.format(numero, hex(numero)[2:]))
else:
print('Número inválido.') |
def find_2020th_number_spoken(starting_numbers):
num_list = []
starting_numbers = [ int(num) for num in starting_numbers.split(',') ]
for i in range(0, 2020):
#print(f'i:{i}, num_list: {num_list}')
if i < len(starting_numbers):
#print(f'Still in starting numbers')
num_list.append(starting_numbers[i])
else:
last_num = num_list[i-1]
found_num = False
for j, num in enumerate(reversed(num_list[0:-1])):
if num == last_num:
#print(f'Found {last_num} at {j+1} numbers back')
num_list.append(j+1)
found_num = True
break
if found_num == False:
#print(f'Didn\'t find {last_num}, add 0 to list')
num_list.append(0)
return num_list[-1]
def find_nth_number_spoken(n, starting_numbers):
num_list = []
starting_numbers = [ int(num) for num in starting_numbers.split(',') ]
for i in range(0, n):
#if i % 10000 == 0:
#print(f'i:{i}, num_list: {num_list}')
if i < len(starting_numbers):
#print(f'Still in starting numbers')
num_list.append(starting_numbers[i])
else:
last_num = num_list[i-1]
found_num = False
for j, num in enumerate(reversed(num_list[0:-1])):
if num == last_num:
#print(f'Found {last_num} at {j+1} numbers back')
num_list.append(j+1)
found_num = True
break
if found_num == False:
#print(f'Didn\'t find {last_num}, add 0 to list')
num_list.append(0)
return num_list[-1]
def find_nth_number_spoken_dict(n, starting_numbers):
num_list = []
num_dict = {}
old_dict = {}
starting_numbers = [ int(num) for num in starting_numbers.split(',') ]
for i in range(0, n):
#if i % 10000 == 0:
# print(f'i:{i}')
#print(f'i:{i}, num_list: {num_list}, num_dict: {num_dict}, old_dict: {old_dict}')
if i < len(starting_numbers):
#print(f'Still in starting numbers')
num = starting_numbers[i]
num_list.append(num)
if num in num_dict:
old_dict[num] = num_dict[num]
num_dict[num] = i
else:
last_num = num_list[i-1]
if last_num in old_dict:
new_num = i - 1 - old_dict[last_num]
#print(f'Found last_num: {last_num} at index: {old_dict[last_num]}. new_num: {new_num}')
num_list.append(new_num)
old_dict[last_num] = num_dict[last_num]
if new_num in num_dict:
old_dict[new_num] = num_dict[new_num]
num_dict[new_num] = i
else:
#print(f'Did not find last_num: {last_num} in old_dict')
if last_num in num_dict:
#print(f'Found last_num: {last_num} in new_dict with value: {num_dict[last_num]}')
if num_dict[last_num] == i - 1:
pass
#print(f'Found it at previous index. Ignore')
else:
#print(f'Found it at other index. Add old_dict entry')
old_dict[num] = num_dict[num]
num_list.append(0)
if 0 in num_dict:
old_dict[0] = num_dict[0]
num_dict[0] = i
else:
print(f'How did this happen?')
return num_list[-1]
if __name__ == '__main__':
filenames = ['input-sample.txt', 'input.txt']
for filename in filenames:
with open(filename, 'r') as f:
starting_numbers_list = f.read().splitlines()
for starting_numbers in starting_numbers_list:
#num = find_2020th_number_spoken(starting_numbers)
#print(f'2020th number: {num}')
num = find_nth_number_spoken(2020, starting_numbers)
print(f'2020th number: {num}')
num = find_nth_number_spoken_dict(2020, starting_numbers)
print(f'2020th number: {num}')
for starting_numbers in starting_numbers_list:
num = find_nth_number_spoken_dict(30000000, starting_numbers)
print(f'30000000th number: {num}')
|
# -*- encoding: utf-8 -*-
{
"name": "合同模块",
"version": "8.0.0.1",
"description": """
总包合同和分包合同
""",
"author": "OSCG",
"website": "http://www.wisebond.net/",
"category": "YD",
'depends': [
'base',
'product',
'purchase',
'workflow_info',
'wise_project',
'sale',
'account',
],
'init_xml': [],
'update_xml': [
'labor_contract_sequence.xml',
'security/ir.model.access.csv',
'labor_contract_view.xml',
'labor_contract_commercial_workflow_view.xml',
'labor_contract_sub_workflow_veiw.xml',
'invoice_view.xml',
'contract_change_workflow.xml',
'contract_change_view.xml',
'labor_contract_menu_view.xml',
],
}
|
# used for template multi_assignment_list_modal
class MultiVideoAssignmentData:
def __init__(self, name, count, video_id, set_id):
self.name = name
self.count = count
self.video_id = video_id
self.set_id = set_id
|
first_number= 1
sec_number= 2
sum= 0
while (first_number < 4000000):
new= first_number + sec_number
first_number= sec_number
sec_number= new
if(first_number % 2== 0):
sum= sum+first_number
print(sum)
|
start_position = {
(1, 2): "y", (1, 3): "", (1, 5): "y'", (1, 6): "y2",
(2, 1): "z' y'", (2, 3): "z'", (2, 4): "z' y", (2, 6): "z' y2",
(3, 1): "x y2", (3, 2): "x y", (3, 4): "x", (3, 5): "x y'",
(4, 2): "z2 y'", (4, 3): "z2", (4, 5): "z2 y", (4, 6): "x2",
(5, 1): "z y", (5, 3): "z", (5, 4): "z y'", (5, 6): "z y2",
(6, 1): "x'", (6, 2): "x' y", (6, 4): "x' y2", (6, 5): "x' y'"
}
sorted_sides = [3, 5, 6, 2, 1, 4]
scramble_board_position = {
5: (1, 0),
4: (2, 1),
1: (1, 1),
6: (1, 2),
2: (0, 1),
3: (3, 1)
} |
sink_db = 'gedcom'
sink_tbl = {
"person": "person",
"family": "family"
}
|
#
# Copyright (c) 2017-2018 Joy Diamond. All rights reserved.
#
@gem('Sapphire.Combine')
def gem():
require_gem('Sapphire.Parse')
require_gem('Sapphire.SymbolTable')
variables = [
0, # 0 = copyright
]
query = variables.__getitem__
write = variables.__setitem__
qc = Method(query, 0)
wc = Method(write, 0)
wc0 = Method(wc, 0)
#
# Tokens
#
empty_indentation__function = conjure_indented_token(empty_indentation, FUNCTION__W)
#def gem():
gem__function_header = conjure_function_header(
empty_indentation__function,
conjure_name('gem'),
conjure_parameters_0(LP, RP),
COLON__LINE_MARKER,
)
class Copyright(Object):
__slots__ = ((
'year', # String+
'author', # String+
))
def __init__(t, year, author):
t.year = year
t.author = author
def write(t, f):
copyright = qc()
if t is not copyright:
if copyright is not 0:
close_copyright(f)
wc(t)
f.blank2()
f.line('#<Copyright (c) %s %s. All rights reserved.>', t.year, t.author)
f.blank_suppress()
Copyright.k1 = Copyright.year
Copyright.k2 = Copyright.author
copyright_cache = {}
conjure_copyright__X__dual = produce_conjure_dual('copyright', Copyright, copyright_cache)
def conjure_copyright(year, author):
return conjure_copyright__X__dual(intern_string(year), intern_string(author))
def close_copyright(f):
if qc() is not 0:
wc0()
f.blank_suppress()
f.line('#</Copyright>')
f.blank2()
class TwigCode(Object):
__slots__ = ((
'path', # String+
'part', # String
'copyright', # Copyright
'twig', # Any
'symbol_table', # GlobalSymbolTable
'transformed_twig', # Any
))
def __init__(t, path, part, copyright, twig, symbol_table, transformed_twig):
t.path = path
t.part = part
t.copyright = copyright
t.twig = twig
t.symbol_table = symbol_table
t.transformed_twig = transformed_twig
def write(t, f, tree = false):
t.copyright.write(f)
f.blank2()
f.line(arrange("#<source %r %s>", t.path, t.part))
if tree:
f2 = create_TokenOutput(f)
with f2.change_prefix('#', '# '):
f2.line()
r = t.twig.dump_token(f2)
f2.line()
assert not r
t.symbol_table.dump_global_symbol_table(f2)
f2.flush()
t.transformed_twig.write(f.write)
f.line('#</source>')
f.blank2()
def create_twig_code(path, part, copyright, twig, vary):
[art, transformed_twig] = build_global_symbol_table(twig, vary)
return TwigCode(path, part, copyright, twig, art, transformed_twig)
class RequireMany(Object):
__slots__ = ((
'vary', # SapphireTransform
'latest_many', # List of String
'_append_latest', # Method
'twig_many', # List of Twig
'_append_twig', # Method
'processed_set', # LiquidSet of String
'_add_processed', # Method
'_contains_processed', # Method
))
def __init__(t, vary):
t.vary = vary
t.latest_many = many = []
t._append_latest = many.append
t.twig_many = many = []
t._append_twig = many.append
t.processed_set = processed = LiquidSet()
t._add_processed = processed.add
t._contains_processed = processed.__contains__
#
# Ignore these file, pretend we already saw them
#
t._add_processed('Gem.Path2')
t._add_processed('Sapphire.Boot')
t._add_processed('Sapphire.Parse2')
def add_require_gem(t, module_name):
assert module_name.is_single_quote
s = module_name.s[1:-1]
if t._contains_processed(s):
return
t._append_latest(s)
def loop(t):
contains_processed = t._contains_processed
latest_many = t.latest_many
process_module = t.process_module
append_latest = t._append_latest
extend_latest = latest_many.extend
length_latest = latest_many.__len__
index_latest = latest_many.__getitem__
delete_latest = latest_many.__delitem__
index_latest_0 = Method(index_latest, 0)
index_latest_1 = Method(index_latest, 1)
delete_latest_0 = Method(delete_latest, 0)
zap_latest = Method(delete_latest, slice_all)
while 7 is 7:
total = length_latest()
if total is 0:
break
first = index_latest_0()
if contains_processed(first):
##line('Already processed %s', first)
delete_latest_0()
continue
line('Total %d - Process %s', total, first)
if total is 1:
zap_latest()
process_module(first)
continue
if total is 2:
other = index_latest_1()
zap_latest()
process_module(first)
append_latest(other)
continue
other = t.latest_many[1:]
zap_latest()
process_module(first)
extend_latest(other)
def process_module(t, module):
t._add_processed(module)
if module.startswith('Gem.'):
parent = '../Gem'
elif module.startswith('Pearl.'):
parent = '../Parser'
elif module.startswith('Sapphire.'):
parent = '../Parser'
elif module.startswith('Tremolite.'):
parent = '../Tremolite'
else:
line('module: %s', module)
path = path_join(parent, arrange('%s.py', module.replace('.', '/')))
gem = extract_gem(module, path, t.vary)
t._append_twig(gem)
gem.twig.find_require_gem(t)
def conjure_gem_decorator_header(module):
#@gem('Gem.Something')
return conjure_decorator_header(
empty_indentation__at_sign,
conjure_call_expression(
conjure_name('gem'),
conjure_arguments_1(LP, conjure_single_quote(portray(module)), RP),
),
LINE_MARKER,
)
def extract_boot(path, tree, index, copyright, vary):
boot_code = tree[index]
#@boot('Boot')
boot_code__decorator_header = conjure_decorator_header(
empty_indentation__at_sign,
conjure_call_expression(
conjure_name('boot'),
conjure_arguments_1(LP, conjure_single_quote("'Boot'"), RP),
),
LINE_MARKER,
)
assert boot_code.is_decorated_definition
assert boot_code.a is boot_code__decorator_header
return create_twig_code(
path,
arrange('[%d]', index),
extract_copyright(tree),
boot_code,
vary,
)
def extract_boot_decorator(function_name, path, tree, copyright, vary = 0):
boot_decorator = tree[0]
#def boot(module_name):
boot_decorator__function_header = conjure_function_header(
empty_indentation__function,
conjure_name(function_name),
conjure_parameters_1(LP, conjure_name('module_name'), RP),
COLON__LINE_MARKER,
)
assert boot_decorator.is_function_definition
assert boot_decorator.a is boot_decorator__function_header
assert boot_decorator.b.is_statement_suite
return create_twig_code(path, '[0]', copyright, boot_decorator, vary)
def extract_copyright(tree):
copyright = tree[0].prefix
if not copyright.is_comment_suite:
dump_token('copyright', copyright)
assert copyright.is_comment_suite
assert length(copyright) is 3
assert copyright[0] == empty_comment_line
assert copyright[1].is_comment_line
assert copyright[2] == empty_comment_line
m = copyright_match(copyright[1])
if m is none:
raise_runtime_error('failed to extract copyright from: %r', copyright[1])
return conjure_copyright(m.group('year'), m.group('author'))
def extract_gem(module, path, vary):
tree = parse_python(path)
assert length(tree) is 1
copyright = extract_copyright(tree)
gem = tree[0]
if gem.a is not conjure_gem_decorator_header(module):
dump_token('gem.a', gem.a)
dump_token('other', conjure_gem_decorator_header(module))
assert gem.is_decorated_definition
assert gem.a is conjure_gem_decorator_header(module)
assert gem.b.is_function_definition
assert gem.b.a is gem__function_header
return create_twig_code(path, '[0]', copyright, gem, vary)
def extract_sardnoyx_boot(vary):
path = path_join(source_path, 'Parser/Sardonyx/Boot.py')
tree = parse_python(path)
assert length(tree) is 1
return extract_boot(path, tree, 0, extract_copyright(tree), vary)
def extract_gem_boot(vary):
module_name = 'Gem.Boot'
path = path_join(source_path, 'Gem/Gem/Boot.py')
#path = 'b2.py'
tree = parse_python(path)
assert length(tree) is 3
copyright = extract_copyright(tree)
#
# [0]
# def boot(module_name):
# ...
#
boot_decorator = extract_boot_decorator('gem', path, tree, copyright)
del boot_decorator # We don't really want this, but just extracted it for testing purposes
#
# [1]: empty lines
#
assert tree[1].is_empty_line_suite
#
# [2]:
# @gem('Gem.Boot')
# def gem():
# ...
#
gem = tree[2]
assert gem.is_decorated_definition
assert gem.a is conjure_gem_decorator_header(module_name)
assert gem.b.is_function_definition
assert gem.b.a is gem__function_header
assert gem.b.b.is_statement_suite
return create_twig_code(path, '[2]', copyright, gem, vary)
def extract_sapphire_main(vary):
module_name = 'Sapphire.Main'
path = path_join(source_path, 'Parser/Sapphire/Main.py')
tree = parse_python(path)
assert length(tree) is 5
copyright = extract_copyright(tree)
#
# [0]:
# def boot(module_name):
# ...
#
boot_decorator = extract_boot_decorator('boot', path, tree, copyright, vary)
#
# [1]: empty lines
#
assert tree[1].is_empty_line_suite
#
# [2]:
# @boot('Boot')
# def boot():
# ...
#
boot = extract_boot(path, tree, 2, copyright, vary)
del boot # We don't really want this, but just extracted it for testing purposes
#
# [3]
#
assert tree[3].is_empty_line_suite
#
# [4]:
# @gem('Sapphire.Main')
# def gem():
# ...
#
main = tree[4]
assert main.is_decorated_definition
assert main.a is conjure_gem_decorator_header(module_name)
assert main.b.is_function_definition
assert main.b.a is gem__function_header
assert main.b.b.is_statement_suite
#
# Result
#
return ((
boot_decorator,
create_twig_code(path, '[4]', copyright, main, vary),
))
@share
def command_combine__X(module_name, vary, tree = true):
[boot_decorator, main_code] = extract_sapphire_main(vary)
sardnoyx_boot_code = extract_sardnoyx_boot(vary)
gem_boot_code = extract_gem_boot(vary)
require_many = RequireMany(vary)
require_many.process_module('Gem.Core')
main_code.twig.find_require_gem(require_many)
require_many.loop()
output_path = path_join(binary_path, arrange('.pyxie/%s.py', module_name))
with create_DelayedFileOutput(output_path) as f:
boot_decorator .write(f, tree)
sardnoyx_boot_code.write(f, tree)
for v in require_many.twig_many:
v.write(f, tree)
gem_boot_code.write(f, tree)
main_code .write(f, tree)
close_copyright(f)
#partial(read_text_from_path(output_path))
#for name in ['cell-function-parameter']:
# print_cache(name)
#print_cache()
|
class Solution(object):
def checkPossibility(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
is_modified = False
for i in xrange(len(nums) - 1):
if nums[i] > nums[i + 1]:
if is_modified:
return False
else:
if i == 0 or nums[i - 1] <= nums[i + 1]:
nums[i] = nums[i + 1]
else:
nums[i + 1] = nums[i]
is_modified = True
return True
|
"""The module's version information."""
__author__ = "Tomás Farías Santana"
__copyright__ = "Copyright 2021 Tomás Farías Santana"
__title__ = "airflow-dbt-python"
__version__ = "0.11.0"
|
def diag(kp):
nk = []
for x in xrange(len(kp)):
l = []
for y in xrange(len(kp)):
l.append(kp[y][x])
nk.append("".join(l))
return tuple(nk)
def parse_line(line):
left, right = line.strip().split(" => ")
a = tuple(left.split("/"))
b = right.split("/")
return a, b
def parse_input(puzzle_input):
rules = {}
for line in puzzle_input:
k, v = parse_line(line)
rules[k] = v
rules[diag(k)] = v
k2 = tuple([s[::-1] for s in k])
rules[k2] = v
rules[diag(k2)] = v
k3 = tuple(s for s in k[::-1])
rules[k3] = v
rules[diag(k3)] = v
k4 = tuple([s[::-1] for s in k3])
rules[k4] = v
rules[diag(k4)] = v
return rules
def num_on(g):
return sum([sum([c == "#" for c in l]) for l in g])
def run(puzzle_input):
rules = parse_input(puzzle_input)
grid = [
".#.",
"..#",
"###",
]
for it in xrange(18):
length = len(grid)
new_grid = []
if length % 2 == 0:
for y in xrange(0, length, 2):
new_lines = [[],[],[]]
for x in xrange(0, length, 2):
k = tuple([grid[y][x:x+2], grid[y+1][x:x+2]])
v = rules[k]
for i, l in enumerate(v):
new_lines[i].extend(list(l))
new_grid.extend(["".join(l) for l in new_lines])
elif length % 3 == 0:
for y in xrange(0, length, 3):
new_lines = [[],[],[],[]]
for x in xrange(0, length, 3):
k = tuple([grid[y][x:x+3], grid[y+1][x:x+3], grid[y+2][x:x+3]])
v = rules[k]
for i, l in enumerate(v):
new_lines[i].extend(list(l))
new_grid.extend(["".join(l) for l in new_lines])
else:
raise "bad dimension"
grid = new_grid
if it == 4:
print(num_on(grid))
print(num_on(grid))
if __name__ == "__main__":
example_input = (
"../.# => ##./#../...",
".#./..#/### => #..#/..../..../#..#",
)
# run(example_input)
# 12
#
run(file("input21.txt"))
# 147
# 1936582
|
EXPECTED_RESPONSE_OF_JWKS_ENDPOINT = {
'keys': [
{
'kty': 'RSA',
'n': 'tSKfSeI0fukRIX38AHlKB1YPpX8PUYN2JdvfM-XjNmLfU1M74N0V'
'mdzIX95sneQGO9kC2xMIE-AIlt52Yf_KgBZggAlS9Y0Vx8DsSL2H'
'vOjguAdXir3vYLvAyyHin_mUisJOqccFKChHKjnk0uXy_38-1r17'
'_cYTp76brKpU1I4kM20M__dbvLBWjfzyw9ehufr74aVwr-0xJfsB'
'Vr2oaQFww_XHGz69Q7yHK6DbxYO4w4q2sIfcC4pT8XTPHo4JZ2M7'
'33Ea8a7HxtZS563_mhhRZLU5aynQpwaVv2U--CL6EvGt8TlNZOke'
'Rv8wz-Rt8B70jzoRpVK36rR-pHKlXhMGT619v82LneTdsqA25Wi2'
'Ld_c0niuul24A6-aaj2u9SWbxA9LmVtFntvNbRaHXE1SLpLPoIp8'
'uppGF02Nz2v3ld8gCnTTWfq_BQ80Qy8e0coRRABECZrjIMzHEg6M'
'loRDy4na0pRQv61VogqRKDU2r3_VezFPQDb3ciYsZjWBr3HpNOkU'
'jTrvLmFyOE9Q5R_qQGmc6BYtfk5rn7iIfXlkJAZHXhBy-ElBuiBM'
'-YSkFM7dH92sSIoZ05V4MP09Xcppx7kdwsJy72Sust9Hnd9B7V35'
'YnVF6W791lVHnenhCJOziRmkH4xLLbPkaST2Ks3IHH7tVltM6NsR'
'k3jNdVM',
'e': 'AQAB',
'alg': 'RS256',
'kid': '02B1174234C29F8EFB69911438F597FF3FFEE6B7',
'use': 'sig'
}
]
}
RESPONSE_OF_JWKS_ENDPOINT_WITH_WRONG_KEY = {
'keys': [
{
'kty': 'RSA',
'n': 'pSKfSeI0fukRIX38AHlKB1YPpX8PUYN2JdvfM-XjNmLfU1M74N0V'
'mdzIX95sneQGO9kC2xMIE-AIlt52Yf_KgBZggAlS9Y0Vx8DsSL2H'
'vOjguAdXir3vYLvAyyHin_mUisJOqccFKChHKjnk0uXy_38-1r17'
'_cYTp76brKpU1I4kM20M__dbvLBWjfzyw9ehufr74aVwr-0xJfsB'
'Vr2oaQFww_XHGz69Q7yHK6DbxYO4w4q2sIfcC4pT8XTPHo4JZ2M7'
'33Ea8a7HxtZS563_mhhRZLU5aynQpwaVv2U--CL6EvGt8TlNZOke'
'Rv8wz-Rt8B70jzoRpVK36rR-pHKlXhMGT619v82LneTdsqA25Wi2'
'Ld_c0niuul24A6-aaj2u9SWbxA9LmVtFntvNbRaHXE1SLpLPoIp8'
'uppGF02Nz2v3ld8gCnTTWfq_BQ80Qy8e0coRRABECZrjIMzHEg6M'
'loRDy4na0pRQv61VogqRKDU2r3_VezFPQDb3ciYsZjWBr3HpNOkU'
'jTrvLmFyOE9Q5R_qQGmc6BYtfk5rn7iIfXlkJAZHXhBy-ElBuiBM'
'-YSkFM7dH92sSIoZ05V4MP09Xcppx7kdwsJy72Sust9Hnd9B7V35'
'YnVF6W791lVHnenhCJOziRmkH4xLLbPkaST2Ks3IHH7tVltM6NsR'
'k3jNdVM',
'e': 'AQAB',
'alg': 'RS256',
'kid': '02B1174234C29F8EFB69911438F597FF3FFEE6B7',
'use': 'sig'
}
]
}
PRIVATE_KEY = """-----BEGIN RSA PRIVATE KEY-----
MIIJKwIBAAKCAgEAtSKfSeI0fukRIX38AHlKB1YPpX8PUYN2JdvfM+XjNmLfU1M7
4N0VmdzIX95sneQGO9kC2xMIE+AIlt52Yf/KgBZggAlS9Y0Vx8DsSL2HvOjguAdX
ir3vYLvAyyHin/mUisJOqccFKChHKjnk0uXy/38+1r17/cYTp76brKpU1I4kM20M
//dbvLBWjfzyw9ehufr74aVwr+0xJfsBVr2oaQFww/XHGz69Q7yHK6DbxYO4w4q2
sIfcC4pT8XTPHo4JZ2M733Ea8a7HxtZS563/mhhRZLU5aynQpwaVv2U++CL6EvGt
8TlNZOkeRv8wz+Rt8B70jzoRpVK36rR+pHKlXhMGT619v82LneTdsqA25Wi2Ld/c
0niuul24A6+aaj2u9SWbxA9LmVtFntvNbRaHXE1SLpLPoIp8uppGF02Nz2v3ld8g
CnTTWfq/BQ80Qy8e0coRRABECZrjIMzHEg6MloRDy4na0pRQv61VogqRKDU2r3/V
ezFPQDb3ciYsZjWBr3HpNOkUjTrvLmFyOE9Q5R/qQGmc6BYtfk5rn7iIfXlkJAZH
XhBy+ElBuiBM+YSkFM7dH92sSIoZ05V4MP09Xcppx7kdwsJy72Sust9Hnd9B7V35
YnVF6W791lVHnenhCJOziRmkH4xLLbPkaST2Ks3IHH7tVltM6NsRk3jNdVMCAwEA
AQKCAgEArx+0JXigDHtFZr4pYEPjwMgCBJ2dr8+L8PptB/4g+LoK9MKqR7M4aTO+
PoILPXPyWvZq/meeDakyZLrcdc8ad1ArKF7baDBpeGEbkRA9JfV5HjNq/ea4gyvD
MCGou8ZPSQCnkRmr8LFQbJDgnM5Za5AYrwEv2aEh67IrTHq53W83rMioIumCNiG+
7TQ7egEGiYsQ745GLrECLZhKKRTgt/T+k1cSk1LLJawme5XgJUw+3D9GddJEepvY
oL+wZ/gnO2ADyPnPdQ7oc2NPcFMXpmIQf29+/g7FflatfQhkIv+eC6bB51DhdMi1
zyp2hOhzKg6jn74ixVX+Hts2/cMiAPu0NaWmU9n8g7HmXWc4+uSO/fssGjI3DLYK
d5xnhrq4a3ZO5oJLeMO9U71+Ykctg23PTHwNAGrsPYdjGcBnJEdtbXa31agI5PAG
6rgGUY3iSoWqHLgBTxrX04TWVvLQi8wbxh7BEF0yasOeZKxdE2IWYg75zGsjluyH
lOnpRa5lSf6KZ6thh9eczFHYtS4DvYBcZ9hZW/g87ie28SkBFxxl0brYt9uKNYJv
uajVG8kT80AC7Wzg2q7Wmnoww3JNJUbNths5dqKyUSlMFMIB/vOePFHLrA6qDfAn
sQHgUb9WHhUrYsH20XKpqR2OjmWU05bV4pSMW/JwG37o+px1yKECggEBANnwx0d7
ksEMvJjeN5plDy3eMLifBI+6SL/o5TXDoFM6rJxF+0UP70uouYJq2dI+DCSA6c/E
sn7WAOirY177adKcBV8biwAtmKHnFnCs/kwAZq8lMvQPtNPJ/vq2n40kO48h8fxb
eGcmyAqFPZ4YKSxrPA4cdbHIuFSt9WyaUcVFmzdTFHVlRP70EXdmXHt84byWNB4C
Heq8zmrNxPNAi65nEkUks7iBQMtuvyV2+aXjDOTBMCd66IhIh2iZq1O7kXUwgh1O
H9hCa7oriHyAdgkKdKCWocmbPPENOETgjraA9wRIXwOYTDb1X5hMvi1mCHo8xjMj
u4szD03xJVi7WrsCggEBANTEblCkxEyhJqaMZF3U3df2Yr/ZtHqsrTr4lwB/MOKk
zmuSrROxheEkKIsxbiV+AxTvtPR1FQrlqbhTJRwy+pw4KPJ7P4fq2R/YBqvXSNBC
amTt6l2XdXqnAk3A++cOEZ2lU9ubfgdeN2Ih8rgdn1LWeOSjCWfExmkoU61/Xe6x
AMeXKQSlHKSnX9voxuE2xINHeU6ZAKy1kGmrJtEiWnI8b8C4s8fTyDtXJ1Lasys0
iHO2Tz2jUhf4IJwb87Lk7Ize2MrI+oPzVDXlmkbjkB4tYyoiRTj8rk8pwBW/HVv0
02pjOLTa4kz1kQ3lsZ/3As4zfNi7mWEhadmEsAIfYkkCggEBANO39r/Yqj5kUyrm
ZXnVxyM2AHq58EJ4I4hbhZ/vRWbVTy4ZRfpXeo4zgNPTXXvCzyT/HyS53vUcjJF7
PfPdpXX2H7m/Fg+8O9S8m64mQHwwv5BSQOecAnzkdJG2q9T/Z+Sqg1w2uAbtQ9QE
kFFvA0ClhBfpSeTGK1wICq3QVLOh5SGf0fYhxR8wl284v4svTFRaTpMAV3Pcq2JS
N4xgHdH1S2hkOTt6RSnbklGg/PFMWxA3JMKVwiPy4aiZ8DhNtQb1ctFpPcJm9CRN
ejAI06IAyD/hVZZ2+oLp5snypHFjY5SDgdoKL7AMOyvHEdEkmAO32ot/oQefOLTt
GOzURVUCggEBALSx5iYi6HtT2SlUzeBKaeWBYDgiwf31LGGKwWMwoem5oX0GYmr5
NwQP20brQeohbKiZMwrxbF+G0G60Xi3mtaN6pnvYZAogTymWI4RJH5OO9CCnVYUK
nkD+GRzDqqt97UP/Joq5MX08bLiwsBvhPG/zqVQzikdQfFjOYNJV+wY92LWpELLb
Lso/Q0/WDyExjA8Z4lH36vTCddTn/91Y2Ytu/FGmCzjICaMrzz+0cLlesgvjZsSo
MY4dskQiEQN7G9I/Z8pAiVEKlBf52N4fYUPfs/oShMty/O5KPNG7L0nrUKlnfr9J
rStC2l/9FK8P7pgEbiD6obY11FlhMMF8udECggEBAIKhvOFtipD1jqDOpjOoR9sK
/lRR5bVVWQfamMDN1AwmjJbVHS8hhtYUM/4sh2p12P6RgoO8fODf1vEcWFh3xxNZ
E1pPCPaICD9i5U+NRvPz2vC900HcraLRrUFaRzwhqOOknYJSBrGzW+Cx3YSeaOCg
nKyI8B5gw4C0G0iL1dSsz2bR1O4GNOVfT3R6joZEXATFo/Kc2L0YAvApBNUYvY0k
bjJ/JfTO5060SsWftf4iw3jrhSn9RwTTYdq/kErGFWvDGJn2MiuhMe2onNfVzIGR
mdUxHwi1ulkspAn/fmY7f0hZpskDwcHyZmbKZuk+NU/FJ8IAcmvk9y7m25nSSc8=
-----END RSA PRIVATE KEY-----"""
EXPECTED_RESPONSE_FROM_GRAYLOG = {
"execution": {
"done": True,
"cancelled": False,
"completed_exceptionally": False
},
"results": {
"60f9b4c461bf9b2a8a999b85": {
"query": {
"id": "query_id",
"timerange": {
"type": "relative",
"range": 12592000
},
"filter": {
"type": "or",
"filters": [
{
"type": "stream",
"filters": None,
"id": "000000000000000000000001",
"title": None
},
{
"type": "stream",
"filters": None,
"id": "60bf6fd4024ad37a05cbb006",
"title": None
}
]
},
"query": {
"type": "elasticsearch",
"query_string": "\"24.141.154.216\""
},
"search_types": [
{
"timerange": None,
"query": None,
"streams": [],
"id": "search_type_id",
"name": None,
"limit": 101,
"offset": 0,
"sort": [
{
"field": "timestamp",
"order": "DESC"
}
],
"decorators": [],
"type": "messages",
"filter": None
}
]
},
"execution_stats": {
"duration": 33,
"timestamp": "2021-07-20T12:37:42.058Z",
"effective_timerange": {
"type": "absolute",
"from": "2021-02-24T18:51:02.091Z",
"to": "2021-07-20T12:37:42.091Z"
}
},
"search_types": {
"60f9b550a09a4d867ecd0169": {
"id": "search_type_id",
"messages": [
{
"highlight_ranges": {},
"message": {
"gl2_accounted_message_size": 221,
"level": 3,
"gl2_remote_ip": "::1",
"gl2_remote_port": 43339,
"streams": [
"000000000000000000000001"
],
"gl2_message_id": "01F7NTA7TRK9Q36QN6Q03PKSJE",
"source": "%ASA-3-710003:",
"message": "%ASA-3-710003: TCP access denied by ACL from 49.143.32.6/4222 to outside:24.141.154.216/23",
"gl2_source_input": "60bf6485024ad37a05cba39c",
"facility_num": 20,
"gl2_source_node": "80fe6cad-d153-489f-91a8-beee65b2e27c",
"_id": "f5999d80-c856-11eb-a871-000c293368b3",
"facility": "local4",
"timestamp": "2021-06-08T12:42:17.816Z"
},
"index": "graylog_0",
"decoration_stats": None
},
{
"highlight_ranges": {},
"message": {
"gl2_accounted_message_size": 222,
"level": 3,
"gl2_remote_ip": "::1",
"gl2_remote_port": 49754,
"streams": [
"000000000000000000000001"
],
"gl2_message_id": "01F7NT94374GXQMJRV7GAH5AKM",
"source": "%ASA-3-710003:",
"message": "%ASA-3-710003: TCP access denied by ACL from 5.34.129.87/62507 to outside:24.141.154.216/23",
"gl2_source_input": "60bf6485024ad37a05cba39c",
"facility_num": 20,
"gl2_source_node": "80fe6cad-d153-489f-91a8-beee65b2e27c",
"_id": "dfc9f770-c856-11eb-a871-000c293368b3",
"facility": "local4",
"timestamp": "2021-06-08T12:41:41.223Z"
},
"index": "graylog_0",
"decoration_stats": None
},
{
"highlight_ranges": {},
"message": {
"gl2_accounted_message_size": 225,
"level": 3,
"gl2_remote_ip": "::1",
"gl2_remote_port": 48544,
"streams": [
"000000000000000000000001"
],
"gl2_message_id": "01F7NT7J8GGPSBNB6RFHH3P31A",
"source": "%ASA-3-710003:",
"message": "%ASA-3-710003: TCP access denied by ACL from 156.96.156.172/50168 to outside:24.141.154.216/80",
"gl2_source_input": "60bf6485024ad37a05cba39c",
"facility_num": 20,
"gl2_source_node": "80fe6cad-d153-489f-91a8-beee65b2e27c",
"_id": "c15f4100-c856-11eb-a871-000c293368b3",
"facility": "local4",
"timestamp": "2021-06-08T12:40:50.192Z"
},
"index": "graylog_0",
"decoration_stats": None
},
{
"highlight_ranges": {},
"message": {
"gl2_accounted_message_size": 223,
"level": 3,
"gl2_remote_ip": "::1",
"gl2_remote_port": 47419,
"streams": [
"000000000000000000000001"
],
"gl2_message_id": "01F7NT4RFEHY8F2Y4VP1RT5T5F",
"source": "ASA-3-710003:",
"message": "ASA-3-710003: TCP access denied by ACL from 156.96.156.172/50168 to outside:24.141.154.216/80",
"gl2_source_input": "60bf6485024ad37a05cba39c",
"facility_num": 20,
"gl2_source_node": "80fe6cad-d153-489f-91a8-beee65b2e27c",
"_id": "8a8cfb90-c856-11eb-a871-000c293368b3",
"facility": "local4",
"timestamp": "2021-06-08T12:39:18.216Z"
},
"index": "graylog_0",
"decoration_stats": None
}
],
"effective_timerange": {
"type": "absolute",
"from": "2021-02-24T18:51:02.091Z",
"to": "2021-07-20T12:37:42.091Z"
},
"total_results": 4,
"type": "messages"
}
},
"errors": [],
"state": "COMPLETED"
}
},
"id": "60f6c39681e5cd7cd5e9ad9a",
"owner": "admin",
"search_id": None
}
EXPECTED_RESPONSE_FROM_RELAY = {
"data": {
"sightings": {
"count": 4,
"docs": [
{
"confidence": "High",
"count": 1,
"data": {
"columns": [
{
"name": "level",
"type": "string"
},
{
"name": "source",
"type": "string"
},
{
"name": "facility_num",
"type": "string"
},
{
"name": "facility",
"type": "string"
}
],
"rows": [
[
"3",
"%ASA-3-710003:",
"20",
"local4"
]
]
},
"description": "```\n%ASA-3-710003: TCP access denied by ACL from 49.143.32.6/4222 to outside:24.141.154.216/23 \n```",
"external_ids": [
"01F7NTA7TRK9Q36QN6Q03PKSJE",
"f5999d80-c856-11eb-a871-000c293368b3"
],
"id": "01F7NTA7TRK9Q36QN6Q03PKSJE",
"internal": True,
"observables": [{
"type": "ip",
"value": "24.141.154.216"
}],
"observed_time": {
"start_time": "2021-06-08T12:42:17.816Z"
},
"schema_version": "1.1.6",
"short_description": "Node 80fe6cad received a log from ::1 containing the observable",
"source": "Graylog",
"source_uri": "https://host/messages/graylog_0/f5999d80-c856-11eb-a871-000c293368b3",
"title": "Log message received by Graylog in last 30 days contains observable",
"type": "sighting"
},
{
"confidence": "High",
"count": 1,
"data": {
"columns": [
{
"name": "level",
"type": "string"
},
{
"name": "source",
"type": "string"
},
{
"name": "facility_num",
"type": "string"
},
{
"name": "facility",
"type": "string"
}
],
"rows": [
[
"3",
"%ASA-3-710003:",
"20",
"local4"
]
]
},
"description": "```\n%ASA-3-710003: TCP access denied by ACL from 5.34.129.87/62507 to outside:24.141.154.216/23 \n```",
"external_ids": [
"01F7NT94374GXQMJRV7GAH5AKM",
"dfc9f770-c856-11eb-a871-000c293368b3"
],
"id": "01F7NT94374GXQMJRV7GAH5AKM",
"internal": True,
"observables": [{
"type": "ip",
"value": "24.141.154.216"
}],
"observed_time": {
"start_time": "2021-06-08T12:41:41.223Z"
},
"schema_version": "1.1.6",
"short_description": "Node 80fe6cad received a log from ::1 containing the observable",
"source": "Graylog",
"source_uri": "https://host/messages/graylog_0/dfc9f770-c856-11eb-a871-000c293368b3",
"title": "Log message received by Graylog in last 30 days contains observable",
"type": "sighting"
},
{
"confidence": "High",
"count": 1,
"data": {
"columns": [
{
"name": "level",
"type": "string"
},
{
"name": "source",
"type": "string"
},
{
"name": "facility_num",
"type": "string"
},
{
"name": "facility",
"type": "string"
}
],
"rows": [
[
"3",
"%ASA-3-710003:",
"20",
"local4"
]
]
},
"description": "```\n%ASA-3-710003: TCP access denied by ACL from 156.96.156.172/50168 to outside:24.141.154.216/80 \n```",
"external_ids": [
"01F7NT7J8GGPSBNB6RFHH3P31A",
"c15f4100-c856-11eb-a871-000c293368b3"
],
"id": "01F7NT7J8GGPSBNB6RFHH3P31A",
"internal": True,
"observables": [{
"type": "ip",
"value": "24.141.154.216"
}],
"observed_time": {
"start_time": "2021-06-08T12:40:50.192Z"
},
"schema_version": "1.1.6",
"short_description": "Node 80fe6cad received a log from ::1 containing the observable",
"source": "Graylog",
"source_uri": "https://host/messages/graylog_0/c15f4100-c856-11eb-a871-000c293368b3",
"title": "Log message received by Graylog in last 30 days contains observable",
"type": "sighting"
},
{
"confidence": "High",
"count": 1,
"data": {
"columns": [
{
"name": "level",
"type": "string"
},
{
"name": "source",
"type": "string"
},
{
"name": "facility_num",
"type": "string"
},
{
"name": "facility",
"type": "string"
}
],
"rows": [
[
"3",
"ASA-3-710003:",
"20",
"local4"
]
]
},
"description": "```\nASA-3-710003: TCP access denied by ACL from 156.96.156.172/50168 to outside:24.141.154.216/80 \n```",
"external_ids": [
"01F7NT4RFEHY8F2Y4VP1RT5T5F",
"8a8cfb90-c856-11eb-a871-000c293368b3"
],
"id": "01F7NT4RFEHY8F2Y4VP1RT5T5F",
"internal": True,
"observables": [{
"type": "ip",
"value": "24.141.154.216"
}],
"observed_time": {
"start_time": "2021-06-08T12:39:18.216Z"
},
"schema_version": "1.1.6",
"short_description": "Node 80fe6cad received a log from ::1 containing the observable",
"source": "Graylog",
"source_uri": "https://host/messages/graylog_0/8a8cfb90-c856-11eb-a871-000c293368b3",
"title": "Log message received by Graylog in last 30 days contains observable",
"type": "sighting"
}
]
}
}
}
EXPECTED_RESPONSE_FROM_RELAY_MORE_MESSAGES_AVAILABLE = {
'data': {
'sightings': {
'count': 4,
'docs': [{
'confidence': 'High',
'count': 1,
'data': {
'columns': [{'name': 'level',
'type': 'string'},
{'name': 'source',
'type': 'string'},
{
'name': 'facility_num',
'type': 'string'},
{
'name': 'facility',
'type': 'string'}],
'rows': [
['3', '%ASA-3-710003:',
'20', 'local4']]},
'description': '```\n%ASA-3-710003: TCP access denied by ACL from 49.143.32.6/4222 to outside:24.141.154.216/23 \n```',
'external_ids': [
'01F7NTA7TRK9Q36QN6Q03PKSJE',
'f5999d80-c856-11eb-a871-000c293368b3'],
'id': '01F7NTA7TRK9Q36QN6Q03PKSJE',
'internal': True,
'observables': [{'type': 'ip',
'value': '24.141.154.216'}],
'observed_time': {
'start_time': '2021-06-08T12:42:17.816Z'},
'schema_version': '1.1.6',
'short_description': 'Node 80fe6cad received a log from ::1 containing the observable',
'source': 'Graylog',
'source_uri': 'https://host/messages/graylog_0/f5999d80-c856-11eb-a871-000c293368b3',
'title': 'Log message received by Graylog in last 30 days contains observable',
'type': 'sighting'},
{'confidence': 'High', 'count': 1,
'data': {'columns': [{'name': 'level',
'type': 'string'},
{'name': 'source',
'type': 'string'},
{
'name': 'facility_num',
'type': 'string'},
{
'name': 'facility',
'type': 'string'}],
'rows': [
['3', '%ASA-3-710003:',
'20', 'local4']]},
'description': '```\n%ASA-3-710003: TCP access denied by ACL from 5.34.129.87/62507 to outside:24.141.154.216/23 \n```',
'external_ids': [
'01F7NT94374GXQMJRV7GAH5AKM',
'dfc9f770-c856-11eb-a871-000c293368b3'],
'id': '01F7NT94374GXQMJRV7GAH5AKM',
'internal': True,
'observables': [{'type': 'ip',
'value': '24.141.154.216'}],
'observed_time': {
'start_time': '2021-06-08T12:41:41.223Z'},
'schema_version': '1.1.6',
'short_description': 'Node 80fe6cad received a log from ::1 containing the observable',
'source': 'Graylog',
'source_uri': 'https://host/messages/graylog_0/dfc9f770-c856-11eb-a871-000c293368b3',
'title': 'Log message received by Graylog in last 30 days contains observable',
'type': 'sighting'},
{'confidence': 'High', 'count': 1,
'data': {'columns': [{'name': 'level',
'type': 'string'},
{'name': 'source',
'type': 'string'},
{
'name': 'facility_num',
'type': 'string'},
{
'name': 'facility',
'type': 'string'}],
'rows': [
['3', '%ASA-3-710003:',
'20', 'local4']]},
'description': '```\n%ASA-3-710003: TCP access denied by ACL from 156.96.156.172/50168 to outside:24.141.154.216/80 \n```',
'external_ids': [
'01F7NT7J8GGPSBNB6RFHH3P31A',
'c15f4100-c856-11eb-a871-000c293368b3'],
'id': '01F7NT7J8GGPSBNB6RFHH3P31A',
'internal': True,
'observables': [{'type': 'ip',
'value': '24.141.154.216'}],
'observed_time': {
'start_time': '2021-06-08T12:40:50.192Z'},
'schema_version': '1.1.6',
'short_description': 'Node 80fe6cad received a log from ::1 containing the observable',
'source': 'Graylog',
'source_uri': 'https://host/messages/graylog_0/c15f4100-c856-11eb-a871-000c293368b3',
'title': 'Log message received by Graylog in last 30 days contains observable',
'type': 'sighting'},
{'confidence': 'High', 'count': 1,
'data': {'columns': [{'name': 'level',
'type': 'string'},
{'name': 'source',
'type': 'string'},
{
'name': 'facility_num',
'type': 'string'},
{
'name': 'facility',
'type': 'string'}],
'rows': [
['3', 'ASA-3-710003:',
'20', 'local4']]},
'description': '```\nASA-3-710003: TCP access denied by ACL from 156.96.156.172/50168 to outside:24.141.154.216/80 \n```',
'external_ids': [
'01F7NT4RFEHY8F2Y4VP1RT5T5F',
'8a8cfb90-c856-11eb-a871-000c293368b3'],
'id': '01F7NT4RFEHY8F2Y4VP1RT5T5F',
'internal': True,
'observables': [{'type': 'ip',
'value': '24.141.154.216'}],
'observed_time': {
'start_time': '2021-06-08T12:39:18.216Z'},
'schema_version': '1.1.6',
'short_description': 'Node 80fe6cad received a log from ::1 containing the observable',
'source': 'Graylog',
'source_uri': 'https://host/messages/graylog_0/8a8cfb90-c856-11eb-a871-000c293368b3',
'title': 'Log message received by Graylog in last 30 days contains observable',
'type': 'sighting'}]}}, 'errors': [
{'code': 'too-many-messages-warning',
'message': 'More messages found in Graylog for 24.141.154.216 than can be rendered. Log in to the Graylog console to see all messages',
'type': 'warning'}]}
EXPECTED_RESPONSE_FROM_REFER_ENDPOINT = {
'data': [
{
'categories': [
'Graylog',
'Search'
],
'description': 'Search for this IP in the Graylog console',
'id': 'ref-graylog-search-ip-24.141.154.216',
'title': 'Search for this IP',
'url': 'https://host/search?rangetype=relative&relative=2592000&q=24.141.154.216'
}
]
}
EXPECTED_RESPONSE_FROM_GRAYLOG_WITH_RELATIONS = {
"execution": {
"done": True,
"cancelled": False,
"completed_exceptionally": False
},
"results": {
"60f9b4c461bf9b2a8a999b85": {
"query": {
"id": "60f9b550a09a4d867ecd0161",
"timerange": {
"type": "relative",
"range": 2592000
},
"filter": {
"type": "or",
"filters": [
{
"type": "stream",
"id": "61034e51d9dadc489abe0055"
},
{
"type": "stream",
"id": "000000000000000000000001"
},
{
"type": "stream",
"id": "61034e51d9dadc489abe00e8"
},
{
"type": "stream",
"id": "6100139fd9dadc489abaa65d"
}
]
},
"query": {
"type": "elasticsearch",
"query_string": "\"188.125.72.73\""
},
"search_types": [
{
"timerange": None,
"query": None,
"streams": [],
"id": "search_type_id",
"name": None,
"limit": 101,
"offset": 0,
"sort": [
{
"field": "timestamp",
"order": "DESC"
}
],
"decorators": [],
"type": "messages",
"filter": None
}
]
},
"execution_stats": {
"duration": 17,
"timestamp": "2021-07-30T08:10:41.731Z",
"effective_timerange": {
"type": "absolute",
"from": "2021-06-30T08:10:41.748Z",
"to": "2021-07-30T08:10:41.748Z"
}
},
"search_types": {
"60f9b550a09a4d867ecd0169": {
"id": "60f9b550a09a4d867ecd0162",
"messages": [
{
"highlight_ranges": {},
"message": {
"destination_port": "51083",
"gl2_remote_ip": "198.18.133.195",
"event_severity_level": "6",
"gl2_remote_port": 57724,
"source": "vFTD",
"gl2_source_input": "60f72a14d9dadc489ab16198",
"network_transport": "tcp",
"vendor_event_action": "blocked",
"source_ip": "188.125.72.73",
"destination_ip": "198.18.133.198",
"event_code": "106015",
"source_port": "25",
"event_outcome": "denied",
"gl2_source_node": "863495ef-c881-4024-ba49-e776020c676c",
"timestamp": "2021-07-30T08:01:14.000Z",
"event_source_product": "CISCO-ASA",
"gl2_accounted_message_size": 561,
"level": 6,
"streams": [
"61034e51d9dadc489abe00e8"
],
"gl2_message_id": "01FBV6X06DZP5N7YKS58DEJHNM",
"message": "vFTD : %FTD-6-106015: Deny TCP (no connection) from 188.125.72.73/25 to 198.18.133.198/51083 flags FIN PSH ACK on interface Outside",
"vendor_event_outcome_reason": "%FTD-6-106015: Deny TCP (no connection)",
"network_interface_in": "Outside",
"facility_num": 20,
"_id": "500812ac-f10c-11eb-9baa-1212395d7875",
"facility": "local4"
},
"index": "graylog_0",
"decoration_stats": None
},
{
"highlight_ranges": {},
"message": {
"destination_port": "51083",
"gl2_remote_ip": "198.18.133.195",
"event_severity_level": "6",
"gl2_remote_port": 40083,
"source": "vFTD",
"gl2_source_input": "60f72a14d9dadc489ab16198",
"network_transport": "tcp",
"vendor_event_action": "blocked",
"source_ip": "188.125.72.73",
"destination_ip": "198.18.133.198",
"event_code": "106015",
"source_port": "25",
"event_outcome": "denied",
"gl2_source_node": "863495ef-c881-4024-ba49-e776020c676c",
"timestamp": "2021-07-30T08:01:14.000Z",
"event_source_product": "CISCO-ASA",
"gl2_accounted_message_size": 561,
"level": 6,
"streams": [
"61034e51d9dadc489abe00e8"
],
"gl2_message_id": "01FBV6X06DPB5KM95W6CPJJ6Y7",
"message": "vFTD : %FTD-6-106015: Deny TCP (no connection) from 188.125.72.73/25 to 198.18.133.198/51083 flags FIN PSH ACK on interface Outside",
"vendor_event_outcome_reason": "%FTD-6-106015: Deny TCP (no connection)",
"network_interface_in": "Outside",
"facility_num": 20,
"_id": "500812af-f10c-11eb-9baa-1212395d7875",
"facility": "local4"
},
"index": "graylog_0",
"decoration_stats": None
}
],
"effective_timerange": {
"type": "absolute",
"from": "2021-06-30T08:10:41.748Z",
"to": "2021-07-30T08:10:41.748Z"
},
"total_results": 2,
"type": "messages"
}
},
"errors": [],
"state": "COMPLETED"
}
},
"id": "6103b401d9dadc489abe6b6a",
"owner": "mstorozh@cisco.com",
"search_id": None
}
EXPECTED_RESPONSE_FROM_RELAY_WITH_RELATIONS = {
'data': {
'sightings': {
'count': 2,
'docs': [
{
'confidence': 'High',
'count': 1,
'data': {
'columns': [
{'name': 'destination_port', 'type': 'string'},
{'name': 'event_severity_level', 'type': 'string'},
{'name': 'source', 'type': 'string'},
{'name': 'network_transport', 'type': 'string'},
{'name': 'vendor_event_action', 'type': 'string'},
{'name': 'source_ip', 'type': 'string'},
{'name': 'destination_ip', 'type': 'string'},
{'name': 'event_code', 'type': 'string'},
{'name': 'source_port', 'type': 'string'},
{'name': 'event_outcome', 'type': 'string'},
{'name': 'event_source_product', 'type': 'string'},
{'name': 'level', 'type': 'string'},
{'name': 'vendor_event_outcome_reason',
'type': 'string'},
{'name': 'network_interface_in', 'type': 'string'},
{'name': 'facility_num', 'type': 'string'},
{'name': 'facility', 'type': 'string'}
],
'rows': [
['51083', '6', 'vFTD', 'tcp',
'blocked', '188.125.72.73',
'198.18.133.198', '106015', '25',
'denied', 'CISCO-ASA', '6',
'%FTD-6-106015: Deny TCP (no connection)',
'Outside', '20', 'local4']]
},
'description': '```\nvFTD : %FTD-6-106015: Deny TCP (no connection) from 188.125.72.73/25 to 198.18.133.198/51083 flags FIN PSH ACK on interface Outside \n```',
'external_ids': [
'01FBV6X06DZP5N7YKS58DEJHNM',
'500812ac-f10c-11eb-9baa-1212395d7875'],
'id': '01FBV6X06DZP5N7YKS58DEJHNM',
'internal': True,
'observables': [
{'type': 'ip', 'value': '188.125.72.73'}],
'observed_time': {
'start_time': '2021-07-30T08:01:14.000Z'},
'relations': [
{'origin': 'vFTD',
'related': {'type': 'ip', 'value': '198.18.133.198'},
'relation': 'Connected_To',
'source': {'type': 'ip', 'value': '188.125.72.73'}}],
'schema_version': '1.1.6',
'short_description': 'Node 863495ef received a log from 198.18.133.195 containing the observable',
'source': 'Graylog',
'source_uri': 'https://host/messages/graylog_0/500812ac-f10c-11eb-9baa-1212395d7875',
'title': 'Log message received by Graylog in last 30 days contains observable',
'type': 'sighting'},
{'confidence': 'High', 'count': 1,
'data': {'columns': [
{'name': 'destination_port',
'type': 'string'},
{'name': 'event_severity_level',
'type': 'string'},
{'name': 'source',
'type': 'string'},
{'name': 'network_transport',
'type': 'string'},
{'name': 'vendor_event_action',
'type': 'string'},
{'name': 'source_ip',
'type': 'string'},
{'name': 'destination_ip',
'type': 'string'},
{'name': 'event_code',
'type': 'string'},
{'name': 'source_port',
'type': 'string'},
{'name': 'event_outcome',
'type': 'string'},
{'name': 'event_source_product',
'type': 'string'},
{'name': 'level',
'type': 'string'}, {
'name': 'vendor_event_outcome_reason',
'type': 'string'},
{'name': 'network_interface_in',
'type': 'string'},
{'name': 'facility_num',
'type': 'string'},
{'name': 'facility',
'type': 'string'}], 'rows': [
['51083', '6', 'vFTD', 'tcp',
'blocked', '188.125.72.73',
'198.18.133.198', '106015', '25',
'denied', 'CISCO-ASA', '6',
'%FTD-6-106015: Deny TCP (no connection)',
'Outside', '20', 'local4']]},
'description': '```\nvFTD : %FTD-6-106015: Deny TCP (no connection) from 188.125.72.73/25 to 198.18.133.198/51083 flags FIN PSH ACK on interface Outside \n```',
'external_ids': [
'01FBV6X06DPB5KM95W6CPJJ6Y7',
'500812af-f10c-11eb-9baa-1212395d7875'],
'id': '01FBV6X06DPB5KM95W6CPJJ6Y7',
'internal': True, 'observables': [
{'type': 'ip',
'value': '188.125.72.73'}],
'observed_time': {
'start_time': '2021-07-30T08:01:14.000Z'},
'relations': [{'origin': 'vFTD',
'related': {
'type': 'ip',
'value': '198.18.133.198'},
'relation': 'Connected_To',
'source': {'type': 'ip',
'value': '188.125.72.73'}}],
'schema_version': '1.1.6',
'short_description': 'Node 863495ef received a log from 198.18.133.195 containing the observable',
'source': 'Graylog',
'source_uri': 'https://host/messages/graylog_0/500812af-f10c-11eb-9baa-1212395d7875',
'title': 'Log message received by Graylog in last 30 days contains observable',
'type': 'sighting'}
]
}
}
}
|
#
# Modify `remove_html_markup` so that it actually works!
#
def remove_html_markup(s):
tag = False
quote = False
quoteSign = '"'
out = ""
for c in s:
# print c, tag, quote
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
tag = False
elif (c == '"' or c == "'") and tag:
if quote == False or (quoteSign == c):
quote = not quote
quoteSign = c
elif not tag:
out = out + c
return out
def test():
assert remove_html_markup('<a href="don' + "'" + 't!">Link</a>') == "Link"
test()
|
features_dict = {
"Name":{
"Description":"String",
"Pre_Action":'''
''',
"Post_Action":'''
''',
"Equip":'''
''',
"Unequip":'''
'''
},
"Dual Wielding":{
"Description":"You can use this weapon in your Off Hand (if available) and attack for -1 AP but with no Techinques. ",
"Pre_Action":'''
weapon = input("Do you want to use your\n" + source.Equipment["Main Hand"] + "\n or your\n" + source.Equipment["Off Hand"])
''',
"Equip":'''
if slot == "Off Hand":
source.Equipment[slot][item]["AP"] -= 1
source.Equipment[slot][item]["Techniques] = {}
source.Pre_Action.update("Dual Wielding" = features_dict["Dual Wielding"]["Pre_Action"])
''',
"Unequip":'''
source.Pre_Action.pop("Dual Wielding")
'''
},
"Dueling":{
"Description":"You can perform Feint, Parry, Riposte, and Disarm for -1 AP/RP respectively. ",
"Pre_Action":'''
if action == "Feint" or "Disarm":
source.AP += 1
''',
"Pre_Reaction":'''
if reaction == "Parry" or "Riposte":
source.RP += 1
''',
"Equip":'''
source.Pre_Action.update(Dueling = features_dict["Dueling"]["Pre_Action"])
source.Pre_Reaction.update(Dueling = features_dict["Dueling"]["Pre_Reaction"])
''',
"Unequip":'''
source.Pre_Action.pop("Dueling")
source.Pre_Reaction.pop("Dueling")
'''
},
"Finesse":{
"Description":"You can Replace your Muscle skill with your Finesse Skill",
"Pre_Action":'''
if action == "Weapon Attack":
source.misc_bonus -= mods(source.Attributes["STR"])
source.misc_bonus -= source.Skills["Muscle"]
source.misc_bonus += mods(source.Attributes["DEX"])
source.misc_bonus += source.Skills["Finesse"]
''',
"Post_Action":'''
if action == "Weapon Attack":
source.misc_bonus -= mods(source.Attributes["DEX"])
source.misc_bonus -= source.Skills["Finesse"]
source.misc_bonus += mods(source.Attributes["STR"])
source.misc_bonus += source.Skills["Muscle"]
''',
"Equip":'''
source.Pre_Action.update(Finesse = features_dict["Finesse"]["Pre_Action"])
source.Post_Action.update(Finesse = features_dict["Finesse"]["Post_Action"])
''',
"Unequip":'''
source.Pre_Action.pop("Finesse")
souce.Post_Action.pop("Finesse")
'''
},
"Grappling":{
"Description":"You can perform Wrestle checks with this weapon against a target",
"Pre_Action":'''
''',
"Post_Action":'''
''',
"Equip":'''
''',
"Unequip":'''
'''
},
"Heavy":{
"Description":"You can use 2 techniques per attack",
"Pre_Action":'''
''',
"Post_Action":'''
''',
"Equip":'''
''',
"Unequip":'''
'''
},
"Light":{
"Description":"Doesn't damage Heavy armors Durability",
"Post_Roll":'''
if action == "Weapon Attack":
target_armor = target.Equipment["Armor"]
if target_armor["Type"] == "Heavy":
target.Equipment["Armor"][target_armor]["Durability"] += 1
''',
"Equip":'''
source.Post_Roll.update(Light = features_dict["Light"][Post_Roll])
''',
"Unequip":'''
source.Post_Roll.pop("Light")
'''
},
"Thrown":{
"Description":"You can add 1 stage of momentum to your impact equation when you attack with this weapon at range.",
"Pre_Action":'''
range = distance(source,target)
if action == "Weapon Attack" and range > 1:
status(source,momentum,1)
''',
"Post_Action":'''
if action == "Weapon Attack" and range > 1:
status(source,momentum,-1)
''',
"Equip":'''
source.Pre_Action.update(Thrown = features_dict["Thrown"]["Pre_Action"])
source.Post_Action.update(Thrown = features_dict["Thrown"]["Post_Action"])
''',
"Unequip":'''
source.Pre_Action.pop("Thrown")
source.Post_Action.pop("Thrown")
'''
},
"Versatile":{
"Description":"You can use the weapon as a Piercing or Slashing weapon.",
"Pre_Action":'''
if action == "Weapon Attack":
choice = input("Do you want to use slashing or piercing?")
if choice == "slashing":
source.Equipment[weapon]["Type"] = "Slashing"
else:
source.Equipment[weapon]["Type"] = "Piercing"
''',
"Equip":'''
source.Pre_Action.update(Versatile = features_dict["Thrown"]["Pre_Action"])
''',
"Unequip":'''
source.Pre_Action.pop("Versatile)
'''
},
}
|
tiles = [
# track example in Marin Headlands, a member of Bay Area Ridge Trail, a regional network
# https://www.openstreetmap.org/way/12188550
# https://www.openstreetmap.org/relation/2684235
[12, 654, 1582]
]
for z, x, y in tiles:
assert_has_feature(
z, x, y, 'roads',
{'highway': 'track'})
|
"""
production_settings.py
~~~~~~~~
生产环境配置项(高优先级)
先根据配置文件需要, 设置环境变量:
e.g.::
cp scripts/etc-profile.d-ffpyadmin.sh /etc/profile.d/ffpyadmin.sh
chmod +x /etc/profile.d/ffpyadmin.sh
source /etc/profile.d/ffpyadmin.sh
:author: Fufu, 2019/9/2
"""
##########
# CORE
##########
# 根据需求, 指定正式环境的域名和端口
SERVER_NAME = 'pyadmin.xunyou.com:777'
|
class Readfile():
def process(self, utils, logger):
filenames = utils.check_input()
words = []
for filename in filenames:
with open(utils.indir + filename, 'r') as f:
for line in f:
words.append(line.strip())
return words
|
# -*- coding: utf-8 -*-
# Copyright (C) 2009-2010, Luis Pedro Coelho <luis@luispedro.org>
# vim: set ts=4 sts=4 sw=4 expandtab smartindent:
# Software Distributed under the MIT License
'''
Value types: An hierarchy of value types.
Hierarchy:
vtype
|- numeric
| |-ordinal
| | |- ordinalrange
| | - boolean
| | - integer
| -continuous
- categorical
- boolean
'''
class vtype(object):
def __init__(self,name):
self.name = name
class numeric(vtype):
def __init__(self,name):
vtype.__init__(self,name)
class continuous(numeric):
def __init__(self,name):
vtype.__init__(self,name)
class ordinal(numeric):
def __init__(self,name):
vtype.__init__(self,name)
class ordinalrange(ordinal):
def __init__(self,name,max,min):
ordinal.__init__(self,name)
self.max = max
self.min = min
class integer(ordinal):
pass
class categorical(vtype):
def __init__(self,name, categories):
vtype.__init__(self,name)
self.categories = categories
class boolean(categorical, ordinal):
def __init__(self,name):
vtype.__init__(self,name)
|
"""Module entrypoint."""
def main() -> None:
"""Execute package entrypoint."""
print("Test")
if __name__ == "__main__":
main()
|
"""
Дан список целых чисел. Требуется “сжать” его, переместив все ненулевые элементы в левую часть списка, не меняя их
порядок, а все нули - в правую часть. Порядок ненулевых элементов изменять нельзя, дополнительный список использовать
нельзя, задачу нужно выполнить за один проход по списку. Распечатайте полученный список.
Формат ввода
Вводится список чисел. Все числа списка находятся на одной строке.
Формат вывода
Выведите ответ на задачу.
"""
myList = list(map(int, input().split()))
i = len(myList) - 1
while i >= 0:
if myList[i] == 0:
myList.pop(i)
myList.append(0)
i -= 1
print(*myList)
|
dis = float(input('Qual é a distância da sua viagem? '))
print('Você está prestes a começar uma viagem de {:.1f}km'.format(dis))
if dis <= 200:
preço = dis * 0.50
print('E o preço da sua passagem será R${:.2f}'.format(preço))
else:
preço = dis * 0.45
print('E o preço da sua passagem será de R${:.2f}'.format(preço))
|
def letter_to_number(letter):
if letter == 'A':
return 10
if letter == 'B':
return 11
if letter == 'C':
return 12
if letter == 'D':
return 13
if letter == 'E':
return 14
if letter == 'F':
return 15
else:
return int(letter)
def int_to_char(integer):
if integer == 15:
return 'F'
if integer == 14:
return 'E'
if integer == 13:
return 'D'
if integer == 12:
return 'C'
if integer == 11:
return 'B'
if integer == 10:
return 'A'
else:
return str(integer)
def base_to_decimal(number, base):
first_index = 1 if number[0] == '-' else 0
power = len(number) - 1 if first_index == 0 else len(number) - 2
decimal = 0
for char in number[first_index:]:
decimal += letter_to_number(char) * pow(base, power)
power -= 1
return decimal
def solution(number, from_base, to_base):
is_negative = number[0] == '-'
decimal = base_to_decimal(number, from_base)
digits = []
while decimal > 0:
current_digit = decimal % to_base
decimal //= to_base
digits.append(int_to_char(current_digit))
return '-' + ''.join(reversed(digits)) if is_negative else ''.join(reversed(digits))
|
def returned(reduction):
if reduction is not None:
return r"""
Returns
-------
torch.Tensor
If `reduction` is left as default {} is taken and single value returned.
Otherwise whatever `reduction` returns.
""".format(
reduction
)
return r"""
Returns
-------
torch.Tensor
Scalar `tensor`
"""
def reduction_parameter(reduction):
if reduction == "mean":
return r"""
reduction: Callable(torch.Tensor) -> Any, optional
One argument callable getting `torch.Tensor` and returning argument
after specified reduction.
Default: `torch.mean` (mean across batch, user can use `torchtraining.savers.Mean`
to get mean across iterations/epochs).
"""
if reduction == "sum":
return r"""
reduction: Callable, optional
One argument callable getting `torch.Tensor` and returning `torch.Tensor`.
Default: `torch.sum` (sum of all elements, user can use `torchtraining.savers.Sum`
to get sum across iterations/epochs).
"""
raise ValueError(
"""reduction argument can be one of ["sum", "mean"], got {}""".format(reduction)
)
|
p = int(input())
total = 0
numbers = []
for i in range(p):
cod, quant = input().split(' ')
cod = int(cod)
quant = int(quant)
if(cod == 1001):
total = quant*1.50
elif(cod==1002):
total = quant*2.50
elif(cod==1003):
total = quant*3.50
elif(cod==1004):
total = quant*4.50
elif(cod==1005):
total = quant*5.50
numbers.append(total)
for i in range(len(numbers)):
numbers[i] = float(numbers[i])
print('{:.2f}'.format(sum(numbers))) |
"""
Code examples for common DevOps tasks
cmd.py : Running comand line utils from python script
archive.py : tar/zip archives management
"""
__author__ = "Oleg Merzlyakov"
__license__ = "MIT"
__email__ = "contact@merzlyakov.me"
|
ENV_NAMES = [
"coinrun",
"starpilot",
"caveflyer",
"dodgeball",
"fruitbot",
"chaser",
"miner",
"jumper",
"leaper",
"maze",
"bigfish",
"heist",
"climber",
"plunder",
"ninja",
"bossfight",
]
HARD_GAME_RANGES = {
'coinrun': [5, 10],
'starpilot': [1.5, 35],
'caveflyer': [2, 13.4],
'dodgeball': [1.5, 19],
'fruitbot': [-.5, 27.2],
'chaser': [.5, 14.2],
'miner': [1.5, 20],
'jumper': [1, 10],
'leaper': [1.5, 10],
'maze': [4, 10],
'bigfish': [0, 40],
'heist': [2, 10],
'climber': [1, 12.6],
'plunder': [3, 30],
'ninja': [2, 10],
'bossfight': [.5, 13],
}
NAME_TO_CASE = {
'coinrun': 'CoinRun',
'starpilot': 'StarPilot',
'caveflyer': 'CaveFlyer',
'dodgeball': 'Dodgeball',
'fruitbot': 'FruitBot',
'chaser': 'Chaser',
'miner': 'Miner',
'jumper': 'Jumper',
'leaper': 'Leaper',
'maze': 'Maze',
'bigfish': 'BigFish',
'heist': 'Heist',
'climber': 'Climber',
'plunder': 'Plunder',
'ninja': 'Ninja',
'bossfight': 'BossFight',
} |
# Use binary search to find the key in the list
def binarySearch(lst, key):
low = 0
high = len(lst) - 1
while high >= low:
mid = (high + low) // 2
if key < lst[mid]:
high = mid - 1
elif key == lst[mid]:
return mid
else:
low = mid + 1
return -low - 1 # Now high < low, key not found
def main():
lst = [2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79]
i = binarySearch(lst, 2)
print(i)
j = binarySearch(lst, 11)
print(j)
k = binarySearch(lst, 12)
print(k)
l = binarySearch(lst, 1)
print(l)
m = binarySearch(lst, 3)
print(m)
main()
|
# https://leetcode.com/problems/partition-to-k-equal-sum-subsets/
# By Jiapeng
# Partition problem using DFS
# Runtime: 132 ms, faster than 47.77% of Python3 online submissions for Partition to K Equal Sum Subsets.
# Memory Usage: 13.8 MB, less than 86.54% of Python3 online submissions for Partition to K Equal Sum Subsets.
# DFS框架参考5:此方法可以作为DFS参考框架
class Solution:
def canPartitionKSubsets(self, nums: List[int], k: int) -> bool:
if k == 1:
return True
add = sum(nums)
if add % k or k > len(nums):
return False
target = add / k
nums.sort(reverse=True)
if nums[0] > target: # pruning, if not implemented, time limit exceeded
return False
def dfs(target, rest, mask, k):
if rest == 0:
k -= 1
rest = target
if k == 0:
return True
for i in range(0, len(nums)):
if mask[i] or nums[i] > rest:
continue
mask[i] = 1
if dfs(target, rest-nums[i], mask, k):
return True
mask[i] = 0
return False
mask = [0] * len(nums)
return dfs(target, target, mask, k)
|
#Alian Colors #2
alian_color = 'green'
if alian_color == 'green' or alian_color == 'yellow' or alian_color == 'red':
print("You just earned 5 points.")
else:
print("You just earned 10 points.") |
# Archivo: objetos_clases.py
# Autor: Javier Garcia Algarra
# Fecha: 25 de enero de 2017
# Descripción: Mini introudccion OOP en Python
class Person:
def __init__(self, name):
self.name = name
def saluda(self):
print('Hola, me llamo', self.name)
def cambia_nombre(self, nuevo_nombre):
self.name = nuevo_nombre
p = Person('Pepe')
p.saluda()
# Cambiamos el atributo nombre
p.cambia_nombre('Juan')
print("Ahora me llamo",p.name)
print()
dummy=input("Ahora vamos a ver como crear listas de nombres")
#Podemos crear listas de nombres
chico = Person('Adán')
chica = Person('Eva')
lista_obj = [chico,chica]
print(lista_obj)
dummy=input("Esto es la lista, con dos objetos")
dummy=input("Ahora vamos a jugar con el contenido de la lista"
)
print(lista_obj[0].name,"y",lista_obj[1].name,"se encontraron en la calle y se miraron...")
dummy=input("")
class Pareja:
def __init__(self):
self.el = ''
self.ella = ''
self.apellido = ''
def flechazo(self,el,ella):
self.el = el
self.ella = ella
print('Flechazo total entre', self.el, "y", self.ella)
def matrimonio(self,apellido):
self.apellido = apellido
self.senyoresde = self.el+" y "+self.ella+" son ahora los "+apellido
print(self.senyoresde)
par = Pareja()
par.flechazo(lista_obj[0].name,lista_obj[1].name)
par.matrimonio("Pérez")
dummy=input() |
class Solution:
# @param {integer[]} nums
# @return {integer}
def removeDuplicates(self, nums):
n = len(nums)
if n <=1:
return n
i= 0
j = 0
while(j < n):
if nums[j]!=nums[i]:
nums[i+1] = nums[j]
i += 1
j +=1
return i+1 |
canMega = [3,6,9,15,18,65,80,94,127,130,142,150,181,208,212,214,229,248,254,257,260,282,302,303,306,308,310,319,323,334,354,359,373,376,380,381,384,428,445,448,460,475,531,719]
megaForms = [6,150]
def findMega(dex):
if dex in canMega:
if dex in megaForms:
return "This Pokemon has multiple Mega Evolutions."
else:
return "This Pokemon can Mega Evolve."
else:
return "This Pokemon cannot mega Evolve." |
alien_color = 'green'
print("alien_color = " + alien_color)
if alien_color == 'green':
print("You earned 5 points!")
elif alien_color == 'yellow':
print("You earned 10 points!")
else:
print("You earned 15 points!")
alien_color = 'yellow'
print("\nalien_color = " + alien_color)
if alien_color == 'green':
print("You earned 5 points!")
elif alien_color == 'yellow':
print("You earned 10 points!")
else:
print("You earned 15 points!")
alien_color = 'red'
print("\nalien_color = " + alien_color)
if alien_color == 'green':
print("You earned 5 points!")
elif alien_color == 'yellow':
print("You earned 10 points!")
else:
print("You earned 15 points!") |
COL_TIME = 0
COL_OPEN = 1
COL_HIGH = 2
COL_LOW = 3
COL_CLOSE = 4
def max_close(candles):
c = [x[COL_CLOSE] for x in candles]
return max(c) |
# Author : Nekyz
# Date : 29/06/2015
# Project Euler Challenge 1
def sum_of_multiple_of_3_and_5(number: int) -> int:
result = 0
for num in range(0, number):
if num % 3 == 0:
result += num
elif num % 5 == 0:
result += num
return result
print("###################################")
print("Project Euler, multiple of 3 and 5.")
print("###################################")
while True:
entered_number = input("Please enter the maximum number: ")
if entered_number.isdigit():
if int(entered_number) > 0:
break
else:
print("Please enter a number greater than 0.");
print("Your number is : ", entered_number)
print("The sum of the multiple of 3 and 5 inferior at your number are: ",
sum_of_multiple_of_3_and_5(int(entered_number)))
|
"""
idx 0 1 2 3 4 5 6 7 n = 8
elm 1 1 2 3 0 0 0 0
i
res 1 0 0 2 3 0 0 4 5 0 0 fake_len = n + zeros
j
"""
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
n = len(arr)
zeros = arr.count(0)
fake_len = n + zeros
j = fake_len - 1
for i in range(n-1, -1, -1):
if arr[i] == 0:
if j < n:
arr[j] = 0
j -= 1
if j < n:
arr[j] = 0
j -= 1
else:
if j < n:
arr[j] = arr[i]
j -= 1 |
def can_build(env, platform):
return True
def configure(env):
pass
def get_doc_classes():
return [
"VoxelBuffer",
"VoxelMap",
"Voxel",
"VoxelLibrary",
"VoxelTerrain",
"VoxelLodTerrain",
"VoxelStream",
"VoxelStreamFile",
"VoxelStreamBlockFiles",
"VoxelStreamRegionFiles",
"VoxelGenerator",
"VoxelGeneratorHeightmap",
"VoxelGeneratorImage",
"VoxelGeneratorNoise",
"VoxelGeneratorNoise2D",
"VoxelGeneratorTest",
"VoxelBoxMover",
"VoxelTool",
"VoxelRaycastResult",
"VoxelMesher",
"VoxelMesherBlocky",
"VoxelMesherTransvoxel",
"VoxelMesherDMC"
]
def get_doc_path():
return "doc/classes"
|
fields = [
["#bEasy#k", 211042402],
["Normal", 211042400],
["#rChaos#k", 211042401]
]
# Zakum door portal
s = "Which difficulty of Zakum do you wish to fight? \r\n"
i = 0
for entry in fields:
s += "#L" + str(i) + "#" + entry[0] + "#l\r\n"
i += 1
answer = sm.sendSay(s)
sm.warp(fields[answer][1])
sm.dispose()
|
class MEAPIUrls:
COLLECTION_STATS = 'https://api-mainnet.magiceden.io/rpc/getCollectionEscrowStats/'
COLLECTION_INFO = 'https://api-mainnet.magiceden.io/collections/'
COLLECTION_LIST = 'https://api-mainnet.magiceden.io/all_collections'
COLLECTION_LIST_STATS = 'https://api-mainnet.magiceden.io/rpc/getAggregatedCollectionMetrics'
class MEResponseConstsCollectionStats:
# STATS
LISTED_COUNT = 'listedCount'
FLOOR_PRICE = 'floorPrice'
LISTED_TOTAL_VALUE = 'listedTotalValue'
DAY_AVG_PRICE = 'avgPrice24hr'
DAY_VOLUME = 'volume24hr'
TOTAL_VOLUME = 'volumeAll'
class MEResponseConstsCollectionInfo:
# INFO
SYMBOL = 'symbol'
NAME = 'name'
IMAGE = 'image'
DESCRIPTION = 'description'
CREATED = 'createdAt'
WEBSITE = 'website'
TWITTER = 'twitter'
DISCORD = 'discord'
HAS_ALL_ITEMS = 'hasAllItems'
SUPPLY = 'totalItems'
class MeResponseConstsCollectionListStats:
SYMBOL = 'symbol'
TOTAL_VOLUME = 'txVolumeME.valueAT'
DAILY_VOLUME = 'txVolumeME.value1d'
WEEKLY_VOLUME = 'txVolumeME.value1d'
MONTHLY_VOLUME = 'txVolumeME.value30d'
PREV_DAILY_VOLUME = 'txVolumeME.prev1d'
PREV_WEEKLY_VOLUME = 'txVolumeME.prev3d'
PREV_MONTHLY_VOLUME = 'txVolumeME.prev30d'
AVG_PRICE = 'avgPrice.valueAT'
DAILY_AVG_PRICE = 'avgPrice.value1d'
WEEKLY_AVG_PRICE = 'avgPrice.value7d'
MONTHLY_AVG_PRICE = 'avgPrice.value30d'
PREV_DAILY_AVG_PRICE = 'avgPrice.prev1d'
PREV_WEEKLY_AVG_PRICE = 'avgPrice.prev7d'
PREV_MONTHLY_AVG_PRICE = 'avgPrice.prev30d'
FLOOR_PRICE = 'floorPrice.valueAT'
PREV_DAILY_FLOOR_PRICE = 'floorPrice.prev1d'
PREV_WEEKLY_FLOOR_PRICE = 'floorPrice.prev7d'
PREV_MONTHLY_FLOOR_PRICE = 'floorPrice.prev30d'
GLOBAL_VOLUME = 'txVolume.valueAT'
GLOBAL_DAILY_VOLUME = 'txVolume.value1d'
GLOBAL_WEEKLY_VOLUME = 'txVolume.value7d'
GLOBAL_MONTHLY_VOLUME = 'txVolume.value30d'
PREV_DAILY_GLOBAL_VOLUME = 'txVolume.prev1d'
PREV_WEEKLY_GLOBAL_VOLUME = 'txVolume.prev7d'
PREV_MONTHLY_GLOBAL_VOLUME = 'txVolume.prev30d'
|
# http://codeforces.com/problemset/problem/318/A
n, k = map(int, input().split())
if k <= (n + 1) / 2:
print(k * 2 - 1)
else:
print(int(k - n / 2) * 2)
|
class Solution:
def isPerfectSquare(self, num: int) -> bool:
i = 1
while i * i < num:
i += 1
return i * i == num
|
'''
import math
r=input(">>")
s=2*r*math.sin(math.pi/5)
Area=5*s*s/(4*math.tan(math.pi/5))
print(Area)
'''
'''
import math
x1,y1,x2,y2=input(">>")
x3,y3,x4,y4=math.radians(x1),math.radians(y1),math.radians(x2),math.radians(y2)
d=6371.01*math.acos(math.sin(x3)*math.sin(x4)+math.cos(x3)*math.cos(x4)*math.cos(y3-y4))
print(d)
'''
'''
import math
s=input(">>")
Area=5*s**2/(4*math.tan(math.pi/5))
print(Area)
'''
'''
import math
n,s=input(">>")
Area=n*s**2/(4*math.tan(math.pi/n))
print(Area)
'''
'''
a=input(">>")
b=chr(a)
print(b)
'''
'''
a=str(raw_input("xingming>>"))
b=input("shijian>>")
c=input("baochou>>")
d=input("lianbangshui>>")
e=input("zhoushui>>")
print(a)
print(b)
print(c)
print(b*c)
print(b*c*d)
print(b*c*e)
print(b*c*(d+e))
print(b*c-b*c*(d+e))
'''
'''
a=input(">>")
while(a!=0):
print(a%10),
a=a/10
'''
'''
import math
a,b,c=input()
if b**2-4*a*c>0:
r1=(-b+math.sqrt(b**2-4*a*c))/2*a
r2=(-b-math.sqrt(b**2-4*a*c))/2*a
print r1,r2
elif b**2-4*a*c==0:
r1=(-b+math.sqrt(b**2-4*a*c))/2*a
print r1
else:
print('The equation has no real roots')
'''
'''
import random
b=random.randint(0,100)
a=random.randint(0,100)
print(a,b)
c=input("lianggeshudehe")
if a+b==c:
print("true")
else:
print("flase")
'''
'''
a,b=input(">>")
c=(a+b)%7
if c==0:
print('Sunday')
elif c==1:
print('Monday')
elif c==2:
print('Tuesday')
elif c==3:
print('Wednesday')
elif c==4:
print('Thursday')
elif c==5:
print('Friday')
elif c==6:
print('Saturday')
'''
'''
a,b,c=input()
t=int()
if a>b:
t=a
a=b
b=t
if a>c:
t=a
a=c
c=t
if b>c:
t=b
b=c
c=t
print(a,b,c)
'''
'''
a,b=input()
c,d=input()
if a*b>c*d:
print(2)
if a*b<c*d:
print(1)
'''
'''
a,b=input()
if a==1:
print('31')
elif a==2:
if b%100==0:
if b%400==0:
print("29")
else:
print("28")
elif b%4==0:
print('29')
else:
print('28')
elif a==3:
print('31')
elif a==4:
print('30')
elif a==5:
print('31')
elif a==6:
print('30')
elif a==7:
print('31')
elif a==8:
print('31')
elif a==9:
print('30')
elif a==10:
print('31')
elif a==11:
print('30')
elif a==12:
print('31')
'''
'''
import random
a=random.randint(0,1)
b=input()
if a==b:
print('Ture')
else:
print('Flase')
'''
'''
import random
a=random.randint(0,2)
print(a)
b=input()
if a-b==1:
print('lose')
elif a==0 and b==2:
print('lose')
elif a-b==0:
print('draw')
else:
print('win')
'''
'''
import random
a=random.choice(['Ace','2','3','4','5','6','7','8','9','Jack','Queen','King'])
b=random.choice(['meihua','hongtao','fangkuai','heitao'])
print(a+' '+'of'+' '+b)
'''
'''
a=int(input(""))
a=str(a)
b=a[::-1]
if(a==b):
print('yes')
else:
print('no')
'''
'''
a,b,c=input()
if a+b>c:
if a+c>b:
if b+c>a:
print(a+b+c)
else:
print('feifa')
else:
print('feifa')
else:
print('feifa')
'''
|
# coding: UTF-8
a = 10
b = 20
print("init value:")
print("a : {} | b : {}".format(a, b))
print("Comparison Symbol:")
print("a == b : {}".format(a == b)) #等于 - 比较对象是否相等
print("a != b : {}".format(a != b)) #不等于 - 比较两个对象是否不相等
#print("a <> b : {}".format(a <> b)) #不等于 - 比较两个对象是否不相等(python 3.x被取消)
print("a > b : {}".format(a > b)) #大于 - 返回x是否大于y
print("a < b : {}".format(a < b)) #小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。
print("a >= b : {}".format(a >= b)) #大于等于 - 返回x是否大于等于y。
print("a <= b : {}".format(a <= b)) #小于等于 - 返回x是否小于等于y。
|
# --------------
# Code starts here
# creating lists
class_1 = [ 'Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio' ]
class_2 = [ 'Hilary Mason', 'Carla Gentry', 'Corinna Cortes' ]
# concatinating lists
new_class = class_1 + class_2
# looking at the resultant list
print(new_class)
# appending 'Peter Warden' to new_class
new_class.append('Peter Warden')
# looking at the resultant list
print(new_class)
# deleting 'Carla Gentry' from list
new_class.remove('Carla Gentry')
# looking at the resultant list
print(new_class)
# Code ends here
# --------------
# Code starts here
# creating courses dictionary
courses = { 'Math':65,
'English':70,
'History':80,
'French':70,
'Science':60 }
# looking at the marks obtained in each subject
print(courses)
# calculating total
total = sum(courses.values())
# looking at the resultant list
print(total)
# calculating %
percentage = (total/500)*100
# printing the percentage
print(percentage)
# Code ends here
# --------------
# Code starts here
# Creating the dictionary
mathematics = { 'Geoffrey Hinton':78, 'Andrew Ng':95, 'Sebastian Raschka':65, 'Yoshua Benjio':50, 'Hilary Mason':70, 'Corinna Cortes':66, 'Peter Warden':75 }
# Calculating max
topper = list(mathematics.keys())[list(mathematics.values()).index(max(mathematics.values()))]
# printing the name of student with maximum marks
print(topper)
# Code ends here
# --------------
# Given string
topper = 'andrew ng'
# Code starts here
# Preparing full name to print in the certificate
last_name = (topper.split()[-1])
first_name = (topper.split()[-2])
full_name = last_name + ' ' + first_name
# preparing certificate_name
certificate_name = full_name.upper()
#looking at the result :)
print(certificate_name)
# Code ends here
|
class OslotsFeature(object):
def __init__(self, api, metaData, data):
self.api = api
self.meta = metaData
self.data = data[0]
self.maxSlot = data[1]
self.maxNode = data[2]
def items(self):
maxSlot = self.maxSlot
data = self.data
maxNode = self.maxNode
shift = maxSlot + 1
for n in range(maxSlot + 1, maxNode + 1):
yield (n, data[n - shift])
def s(self, n):
if n == 0:
return ()
if n < self.maxSlot + 1:
return (n,)
m = n - self.maxSlot
if m <= len(self.data):
return self.data[m - 1]
return ()
|
class Solution:
# Function to remove 2 chars by given index of the first char
def del_substr(i, s):
return s[:i] + s[i+2:]
def romanToInt(self, s: str) -> int:
# Roman numeral mapping
roman = {'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000}
# Special cases mapping
special = {'IV': 4,
'IX': 9,
'XL': 40,
'XC': 90,
'CD': 400,
'CM': 900}
# Output sum
output = 0
# Loop through s to look for special cases
for i in range(len(s)):
for i in range(len(s)):
substr = s[i:i+2]
if substr in special:
# Add special cases to output
output += special[substr]
# Remove found numbers from s
s = Solution.del_substr(i, s)
break
# Loop through the remaining s and add found numbers to output
for i in range(len(s)):
if s[i] in roman:
output += roman[s[i]]
return output |
"""Integration of psycopg2 with coroutine framework
"""
# Copyright (C) 2010-2020 Daniele Varrazzo <daniele.varrazzo@gmail.com>
# All rights reserved. See COPYING file for details.
__version__ = '1.0.2'
|
"""
This is the "fizzbuzz" module.
The module supplies one function, fizzbuzz(), which is the classic coding test looking for factors of 3 and 5.
For example:
>>>fizzbuzz(15)
"FizzBuzz!"
"""
def fizzbuzz(x):
assert int(x), "Must be a number"
assert (x >= 0), 'Number must be greater than or equal to 0'
if x % 3 == 0 and x % 5 == 0:
return "FizzBuzz!"
elif x % 3 == 0:
return "Fizz"
elif x % 5 == 0:
return "Buzz"
else:
return x
|
# Configuration file for jupyter-notebook.
## Whether to allow the user to run the notebook as root.
c.NotebookApp.allow_root = True
## The IP address the notebook server will listen on.
c.NotebookApp.ip = '*'
## Whether to open in a browser after starting. The specific browser used is
# platform dependent and determined by the python standard library `webbrowser`
# module, unless it is overridden using the --browser (NotebookApp.browser)
# configuration option.
c.NotebookApp.open_browser = False
## Hashed password to use for web authentication.
#
# To generate, type in a python/IPython shell:
#
# from notebook.auth import passwd; passwd()
#
# The string should be of the form type:salt:hashed-password.
c.NotebookApp.password = ''
## The port the notebook server will listen on.
c.NotebookApp.port = 8888
## Token used for authenticating first-time connections to the server.
#
# When no password is enabled, the default is to generate a new, random token.
#
# Setting to an empty string disables authentication altogether, which is NOT
# RECOMMENDED.
c.NotebookApp.token = ''
|
'''Desenvolva um programa que leia o primeiro termos e a razao de uma PA.
No final, mostre os 10 primeiros termos dessa progressao. Pesquisar sobre progressao aritmetica.'''
print('=' * 50)
frase = '10 TERMOS DE UMA PA'
print(frase.center(50,' '))
print('=' * 50)
termo = int(input('Primeiro Termo: '))
razao = int(input('Digite a razao: '))
decimo = termo + (10 - 1) * razao #Enesimo termo de uma PA, para encontrar o decimo termo da PA.
for c in range(termo, decimo + razao, razao):
print(c, end=' ⮕ ')
print('Acabou', end=' ')
|
class Solution:
# Built-in function
'''
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return bin(int(a, 2) + int(b, 2))[2:]
'''
# Think binary as decimal way
def addBinary(self, a, b):
"""
:type a: str
:type b: str
"""
res, i, j, c = '', len(a) - 1, len(b) - 1, 0
while i >= 0 or j >=0 or c:
current = (i >= 0 and int(a[i])) + (j >= 0 and int(b[j]))
c, current = divmod(current + c, 2)
res = str(current) + res
i -= 1
j -= 1
return res
|
{
"targets": [
{
"target_name": "node-xed",
"cflags!": ["-fno-exceptions"],
"cflags_cc!": ["-fno-exceptions"],
"sources": [
"cpp/node-xed.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")",
"cpp/include"
],
"conditions": [
["OS in \"linux\"", {
"libraries": [
"../cpp/lib/linux/libxed.a"
],
}],
["OS in \"win\"", {
"libraries": [
"../cpp/lib/win/xed.lib"
],
}],
["OS in \"mac\"", {
"libraries": [
"../cpp/lib/mac/libxed.a"
],
}]
],
"dependencies": [
"<!(node -p \"require('node-addon-api').gyp\")"
],
"defines": ["NAPI_DISABLE_CPP_EXCEPTIONS"]
},
{
"target_name": "action_after_build",
"type": "none",
"dependencies": ["<(module_name)"],
"copies": [
{
"files": ["<(PRODUCT_DIR)/<(module_name).node"],
"destination": "<(module_path)"
}
]
}
]
}
|
# Program to Add Two Integers
def isNumber(num):
if(type(num) == type(1)):
return True
else:
return False
def add(num1, num2):
if(isNumber(num1) & isNumber(num2)):
return num1 + num2
else:
return "we only accept numbers."
# Test cases
print(add(1, 2))
print(add("hola", 1))
|
def is_valid(r: int, c: int):
global n
return (-1 < r < n) and (-1 < c < n)
n = int(input())
matrix = [[int(x) for x in input().split()] for _ in range(n)]
tokens = input()
while tokens != "END":
tokens = tokens.split()
cmd = tokens[0]
row = int(tokens[1])
col = int(tokens[2])
val = int(tokens[3])
if is_valid(row, col):
if cmd == "Add":
matrix[row][col] += val
else:
matrix[row][col] -= val
else:
print("Invalid coordinates")
tokens = input()
[print(" ".join([str(x) for x in i])) for i in matrix]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/9/20 10:02
# @Author : Peter
# @Des :
# @File : Callback
# @Software: PyCharm
def msg(msg, *arg, **kw):
print("---" * 60)
print("callback -------> {}".format(msg))
print("---" * 60)
if __name__ == "__main__":
pass
|
class CounterStat:
new = int
@staticmethod
def apply_diff(x, y):
return x + y
class SetStat:
new = set
class Diff:
def __init__(self, added=set(), removed=set()):
self.added = added
self.removed = removed
def invert(self):
self.added, self.removed = self.removed, self.added
def simplify_for_set(self, s):
self.added -= s
self.removed &= s
def is_null(self):
return len(self.added) + len(self.removed) == 0
@staticmethod
def apply_diff(s, d):
s -= d.removed
s |= d.added
return s
class Stats:
stats = {
"n_connections": CounterStat,
"n_current_connections": CounterStat,
"n_bytes": CounterStat,
"n_msgs": CounterStat,
}
def __init__(self):
for k, stat in type(self).stats.items():
setattr(self, k, stat.new())
def update(self, **kwargs):
for k, v in kwargs.items():
stat = type(self).stats[k]
setattr(self, k, stat.apply_diff(getattr(self, k), v))
class UserStats(Stats):
stats = {
"ips": SetStat,
**Stats.stats
}
class IPStats(Stats):
stats = {
"users": SetStat,
**Stats.stats
}
|
class Solution:
def heightChecker(self, heights: List[int]) -> int:
new_heights = sorted(heights)
count = 0
for i in range(len(heights)):
if heights[i] != new_heights[i]:
count += 1
return count
|
# -*- coding: utf-8 -*-
A_INDEX = 0
B_INDEX = 1
C_INDEX = 2
D_INDEX = 3
def main():
values = input().split()
a = int(values[A_INDEX])
b = int(values[B_INDEX])
c = int(values[C_INDEX])
d = int(values[D_INDEX])
if b > c and d > a and c + d > a + b and c > 0 and d > 0 and a % 2 == 0:
print('Valores aceitos')
else:
print('Valores nao aceitos')
if __name__ == '__main__':
main() |
numero1 = input('digite o primeiro numero: ')
numero2 = input('digite o segundo numero: ')
soma = float(numero1) + float(numero2)
subtrai = float(numero1) - float(numero2)
multiplica = float(numero1) * float(numero2)
dividi = float(numero1) / float(numero2)
print('o resultado da soma é: ' + str(soma))
print('o resultado da subtração é: ' + str(subtrai))
print('o resultado da multiplicação é: ' + str(multiplica))
print('o resultado da divisão é: ' + str(dividi)) |
"""
https://leetcode.com/problems/reverse-words-in-a-string-iii/
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
"""
# time complexity: O(n), space complexity: O(1)
class Solution:
def reverseWords(self, s: str) -> str:
i = 0
s = list(s)
start = None
end = None
while i < len(s):
if s[i] != ' ' and start == None:
start = i
if i == len(s)-1 and s[i] != ' ' or i != len(s)-1 and s[i] != ' ' and s[i+1] == ' ':
end = i
while start is not None and end is not None and start < end:
s[start], s[end] = s[end], s[start]
start += 1
end -= 1
start = None
end = None
i += 1
return ''.join(s) |
# The realm, where users are allowed to login as administrators
SUPERUSER_REALM = ['super', 'administrators']
# Your database mysql://u:p@host/db
SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:Pa55w0rd@localhost:5432/privacy_idea'
# This is used to encrypt the auth_token
SECRET_KEY = 't0p s3cr3t'
# This is used to encrypt the admin passwords
PI_PEPPER = 'Never know...'
# This is used to encrypt the token data and token passwords
PI_ENCFILE = '/opt/conda/envs/privacyidea/lib/python3.7/site-packages/enckey'
# This is used to sign the audit log
PI_AUDIT_KEY_PRIVATE = '/opt/conda/envs/privacyidea/lib/python3.7/site-packages/private.pem'
PI_AUDIT_KEY_PUBLIC = '/opt/conda/envs/privacyidea/lib/python3.7/site-packages/public.pem'
# PI_AUDIT_MODULE = <python audit module>
# PI_AUDIT_SQL_URI = <special audit log DB uri>
# PI_LOGFILE = '....'
# PI_LOGLEVEL = 20
# PI_INIT_CHECK_HOOK = 'your.module.function'
# PI_CSS = '/location/of/theme.css'
# PI_UI_DEACTIVATED = True
|
class Solution(object):
def canCompleteCircuit(self, gas, cost):
"""
:type gas: List[int]
:type cost: List[int]
:rtype: int
"""
# https://discuss.leetcode.com/topic/5088/my-ac-is-o-1-space-o-n-running-time-solution-does-anybody-have-posted-this-solution
ls = len(gas)
begin, end = 0, ls - 1
curr = gas[end] - cost[end]
while begin < end:
if curr >= 0:
curr += gas[begin] - cost[begin]
begin += 1
else:
end -= 1
curr += gas[end] - cost[end]
if curr >= 0:
return end
else:
return -1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.