content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# Tern
# domain: set of inputs
# co-domain: a set from which the function's output values are chosen.
# image: set of outputs, may smaller than co-domain
# this procedure is a real function in math.
def caesar(plaintext: str):
code = []
for char in plaintext:
code_ = ord(char) + 3
if char in "xyzXYZ":
code_ = code_ - 26
code_ = chr(code_)
code.append(code_)
return "".join(code) | def caesar(plaintext: str):
code = []
for char in plaintext:
code_ = ord(char) + 3
if char in 'xyzXYZ':
code_ = code_ - 26
code_ = chr(code_)
code.append(code_)
return ''.join(code) |
# -*- coding: utf-8 -*-
{
'name': 'Biometric Integration',
'version': '1.0',
'summary': """Integrating Biometric Device With HR Attendance (Face + Thumb)""",
'description': """This module integrates Odoo with the biometric device,odoo15,odoo,hr,attendance""",
'category': 'Generic Modules/Human Resources',
'author': 'progistack, emmanuelprogistack',
'company': 'progistack',
'website': "https://www.progistack.com",
'depends': ['base_setup', 'hr_attendance'],
'data': [
'security/ir.model.access.csv',
'views/date_modification_wizard.xml',
'views/zk_machine_view.xml',
'views/zk_machine_attendance_view.xml',
'views/parametrage_view.xml',
'data/download_data.xml'
],
'images': ['static/description/banner.jpg'],
'license': 'AGPL-3',
'installable': True,
'auto_install': False,
'application': False,
}
| {'name': 'Biometric Integration', 'version': '1.0', 'summary': 'Integrating Biometric Device With HR Attendance (Face + Thumb)', 'description': 'This module integrates Odoo with the biometric device,odoo15,odoo,hr,attendance', 'category': 'Generic Modules/Human Resources', 'author': 'progistack, emmanuelprogistack', 'company': 'progistack', 'website': 'https://www.progistack.com', 'depends': ['base_setup', 'hr_attendance'], 'data': ['security/ir.model.access.csv', 'views/date_modification_wizard.xml', 'views/zk_machine_view.xml', 'views/zk_machine_attendance_view.xml', 'views/parametrage_view.xml', 'data/download_data.xml'], 'images': ['static/description/banner.jpg'], 'license': 'AGPL-3', 'installable': True, 'auto_install': False, 'application': False} |
def get_counting_line(line_position, frame_width, frame_height):
line_positions = ['top', 'bottom', 'left', 'right']
if line_position == None:
line_position = 'bottom'
if line_position not in line_positions:
raise Exception('Invalid line position specified (options: top, bottom, left, right)')
if line_position == 'top':
# counting_line_y = round(1 / 5 * frame_height)
# Hamburg_Hall_080007032018_000,top
# counting_line_y = round(3 / 5 * frame_height)
# Parking1_083915032018_000, top
# counting_line_y = round(13 / 20 * frame_height)
# Hamburg_Hall1_073301102019_000, top
counting_line_y = round(3 / 4 * frame_height)
return [(0, counting_line_y), (frame_width, counting_line_y)]
elif line_position == 'bottom':
# Hamburg_Hall_080007032018_000, bottom
# counting_line_y = round(13 / 20 * frame_height)
# Parking1_083915032018_000, bottom
# counting_line_y = round(2 / 3 * frame_height)
# Hamburg_Hall1_064721092018_020, bottom
# counting_line_y = round(3 / 4 * frame_height)
# Hamburg_Hall1_073301102019_000, bottom
# counting_line_y = round(7 / 8 * frame_height)
# Parking2_050101102019_025, bottom
counting_line_y = round(31 / 128 * frame_height)
# counting_line_y = round(1 / 2 * frame_height)
# counting_line_y = round(31 / 128 * frame_height)
# counting_line_y = round(14 / 16 * frame_height)
return [(0, counting_line_y), (frame_width, counting_line_y)]
elif line_position == 'left':
counting_line_x = round(1 / 5 * frame_width)
return [(counting_line_x, 0), (counting_line_x, frame_height)]
elif line_position == 'right':
counting_line_x = round(4 / 5 * frame_width)
return [(counting_line_x, 0), (counting_line_x, frame_height)]
def is_passed_counting_line(point, counting_line, line_position):
if line_position == 'top':
return point[1] < counting_line[0][1]
elif line_position == 'bottom':
return point[1] > counting_line[0][1]
elif line_position == 'left':
return point[0] < counting_line[0][0]
elif line_position == 'right':
return point[0] > counting_line[0][0] | def get_counting_line(line_position, frame_width, frame_height):
line_positions = ['top', 'bottom', 'left', 'right']
if line_position == None:
line_position = 'bottom'
if line_position not in line_positions:
raise exception('Invalid line position specified (options: top, bottom, left, right)')
if line_position == 'top':
counting_line_y = round(3 / 4 * frame_height)
return [(0, counting_line_y), (frame_width, counting_line_y)]
elif line_position == 'bottom':
counting_line_y = round(31 / 128 * frame_height)
return [(0, counting_line_y), (frame_width, counting_line_y)]
elif line_position == 'left':
counting_line_x = round(1 / 5 * frame_width)
return [(counting_line_x, 0), (counting_line_x, frame_height)]
elif line_position == 'right':
counting_line_x = round(4 / 5 * frame_width)
return [(counting_line_x, 0), (counting_line_x, frame_height)]
def is_passed_counting_line(point, counting_line, line_position):
if line_position == 'top':
return point[1] < counting_line[0][1]
elif line_position == 'bottom':
return point[1] > counting_line[0][1]
elif line_position == 'left':
return point[0] < counting_line[0][0]
elif line_position == 'right':
return point[0] > counting_line[0][0] |
class Timer:
def __init__(self, tempo = "int used in real timer", settings = "obj used in real timer"):
pass
def start_question_timer(self):
self._times_asked = 0
def question_time_up(self):
self._times_asked += 1
return self._times_asked >= 18
def question_hint_1_up(self):
return self._times_asked >= 4
def question_hint_2_up(self):
return self._times_asked >= 8
def wait(self):
pass
| class Timer:
def __init__(self, tempo='int used in real timer', settings='obj used in real timer'):
pass
def start_question_timer(self):
self._times_asked = 0
def question_time_up(self):
self._times_asked += 1
return self._times_asked >= 18
def question_hint_1_up(self):
return self._times_asked >= 4
def question_hint_2_up(self):
return self._times_asked >= 8
def wait(self):
pass |
st="Hello everyone are you enjoying learning Python ?"
st2 = st.split()
print(st2)
print(st.strip())
print(st.replace('o','0'))
print(st.isalpha()) | st = 'Hello everyone are you enjoying learning Python ?'
st2 = st.split()
print(st2)
print(st.strip())
print(st.replace('o', '0'))
print(st.isalpha()) |
class Solution:
def smallestNumber(self, num: int) -> int:
s = sorted(str(abs(num)), reverse=num < 0)
firstNonZeroIndex = next((i for i, c in enumerate(s) if c != '0'), 0)
s[0], s[firstNonZeroIndex] = s[firstNonZeroIndex], s[0]
return int(''.join(s)) * (-1 if num < 0 else 1)
| class Solution:
def smallest_number(self, num: int) -> int:
s = sorted(str(abs(num)), reverse=num < 0)
first_non_zero_index = next((i for (i, c) in enumerate(s) if c != '0'), 0)
(s[0], s[firstNonZeroIndex]) = (s[firstNonZeroIndex], s[0])
return int(''.join(s)) * (-1 if num < 0 else 1) |
def twenty_eighteen():
"""Come up with the most creative expression that evaluates to 2018,
using only numbers and the +, *, and - operators.
>>> twenty_eighteen()
2018
"""
return 8 + 192 + (18 * 100) + 18
| def twenty_eighteen():
"""Come up with the most creative expression that evaluates to 2018,
using only numbers and the +, *, and - operators.
>>> twenty_eighteen()
2018
"""
return 8 + 192 + 18 * 100 + 18 |
""" Your task is to implement the function strstr. The function takes two strings as arguments (s,x)
and locates the occurrence of the string x in the string s.
The function returns and integer denoting the first occurrence of the string x in s (0 based indexing).
Example 1:
Input:
s = GeeksForGeeks, x = Fr
Output: -1
Explanation: Fr is not present in the
string GeeksForGeeks as substring.
Example 2:
Input:
s = GeeksForGeeks, x = For
Output: 5
Explanation: For is present as substring
in GeeksForGeeks from index 5 (0 based
indexing).
Your Task:
You don't have to take any input. Just complete the strstr() function which takes two strings str,
target as an input parameter. The function returns -1 if no match if found else it returns an integer
denoting the first occurrence of the x in the string s.
Expected Time Complexity: O(|s|*|x|)
Expected Auxiliary Space: O(1)
Note : Try to solve the question in constant space complexity.
Constraints:
1 <= |s|,|x| <= 1000 """ | """ Your task is to implement the function strstr. The function takes two strings as arguments (s,x)
and locates the occurrence of the string x in the string s.
The function returns and integer denoting the first occurrence of the string x in s (0 based indexing).
Example 1:
Input:
s = GeeksForGeeks, x = Fr
Output: -1
Explanation: Fr is not present in the
string GeeksForGeeks as substring.
Example 2:
Input:
s = GeeksForGeeks, x = For
Output: 5
Explanation: For is present as substring
in GeeksForGeeks from index 5 (0 based
indexing).
Your Task:
You don't have to take any input. Just complete the strstr() function which takes two strings str,
target as an input parameter. The function returns -1 if no match if found else it returns an integer
denoting the first occurrence of the x in the string s.
Expected Time Complexity: O(|s|*|x|)
Expected Auxiliary Space: O(1)
Note : Try to solve the question in constant space complexity.
Constraints:
1 <= |s|,|x| <= 1000 """ |
'''
EASY 1108. Defanging an IP Address
You are given a license key represented as a string S which consists only alphanumeric character and dashes.
The string is separated into N+1 groups by N dashes.
Given a number K, we would want to reformat the strings such that each group contains exactly K characters,
except for the first group which could be shorter than K, but still must contain at least one character.
Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.
Given a non-empty string S and a number K, format the string according to the rules described above.
Example 1:
Input: S = "5F3Z-2e-9-w", K = 4
Output: "5F3Z-2E9W"
Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
'''
class Solution:
def defangIPaddr(self, address: str) -> str:
separate = address.split('.')
separate = "[.]".join(separate)
#return separate
def anotherVersion():
return "[.]".join(address.split('.'))
def mostEfficient():
return address.replace(".","[.]")
return anotherVersion() | """
EASY 1108. Defanging an IP Address
You are given a license key represented as a string S which consists only alphanumeric character and dashes.
The string is separated into N+1 groups by N dashes.
Given a number K, we would want to reformat the strings such that each group contains exactly K characters,
except for the first group which could be shorter than K, but still must contain at least one character.
Furthermore, there must be a dash inserted between two groups and all lowercase letters should be converted to uppercase.
Given a non-empty string S and a number K, format the string according to the rules described above.
Example 1:
Input: S = "5F3Z-2e-9-w", K = 4
Output: "5F3Z-2E9W"
Explanation: The string S has been split into two parts, each part has 4 characters.
Note that the two extra dashes are not needed and can be removed.
"""
class Solution:
def defang_i_paddr(self, address: str) -> str:
separate = address.split('.')
separate = '[.]'.join(separate)
def another_version():
return '[.]'.join(address.split('.'))
def most_efficient():
return address.replace('.', '[.]')
return another_version() |
#!/usr/bin/env python
f = open('/Users/kosta/dev/advent-of-code-17/day11/input.txt')
steps = f.readline().split(',')
moves = {
'n': (0, 1),
's': (0, -1),
'ne': (1, 0.5),
'nw': (-1, 0.5),
'sw': (-1, -0.5),
'se': (1, -0.5)
}
x_total = 0
y_total = 0
for step in steps:
x_total += moves[step][0]
y_total += moves[step][1]
normalized_x = abs(x_total)
normalized_y = abs(y_total)
total_steps = 0
while(True):
total_steps += 1
normalized_x -= 1
normalized_y -= 0.5
if normalized_x == 0:
total_steps += normalized_y
break
print(total_steps)
| f = open('/Users/kosta/dev/advent-of-code-17/day11/input.txt')
steps = f.readline().split(',')
moves = {'n': (0, 1), 's': (0, -1), 'ne': (1, 0.5), 'nw': (-1, 0.5), 'sw': (-1, -0.5), 'se': (1, -0.5)}
x_total = 0
y_total = 0
for step in steps:
x_total += moves[step][0]
y_total += moves[step][1]
normalized_x = abs(x_total)
normalized_y = abs(y_total)
total_steps = 0
while True:
total_steps += 1
normalized_x -= 1
normalized_y -= 0.5
if normalized_x == 0:
total_steps += normalized_y
break
print(total_steps) |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
class SpecialStrings:
"""Special strings in stringified turn parts.
"""
# an empty value (we need it since some library doesn't like an empty string)
NULL = "__NULL"
# indicates there is a break between the two utterance segments
BREAK = "__BREAK"
# indicates the user is the speaker for the following utterance
SPEAKER_USER = "__User"
# indicates the agent is the speaker for the following utterance
SPEAKER_AGENT = "__Agent"
# start of a program
START_OF_PROGRAM = "__StartOfProgram"
| class Specialstrings:
"""Special strings in stringified turn parts.
"""
null = '__NULL'
break = '__BREAK'
speaker_user = '__User'
speaker_agent = '__Agent'
start_of_program = '__StartOfProgram' |
#
# @lc app=leetcode.cn id=1389 lang=python3
#
# [1389] minimum-moves-to-move-a-box-to-their-target-location
#
None
# @lc code=end | None |
class Post():
def __init__(self, post_json):
self.post_id = post_json["id"]
self.annotations = {}
if "annotations" in post_json:
self.annotations = post_json["annotations"]
self.user_id = post_json["user"]["id"]
self.user_followers_count = post_json["user"]["followers_count"]
self.url = post_json["url"]
self.title = post_json["title"]
self.body = post_json["body"]
self.rendered_body = post_json["rendered_body"]
def quality(self, zero_one=True):
score = 0
if len(self.annotations) == 0:
return -1
for a in self.annotations:
score += int(a["quality"])
if not zero_one:
return score
else:
if score > 1:
return 1
else:
return 0
| class Post:
def __init__(self, post_json):
self.post_id = post_json['id']
self.annotations = {}
if 'annotations' in post_json:
self.annotations = post_json['annotations']
self.user_id = post_json['user']['id']
self.user_followers_count = post_json['user']['followers_count']
self.url = post_json['url']
self.title = post_json['title']
self.body = post_json['body']
self.rendered_body = post_json['rendered_body']
def quality(self, zero_one=True):
score = 0
if len(self.annotations) == 0:
return -1
for a in self.annotations:
score += int(a['quality'])
if not zero_one:
return score
elif score > 1:
return 1
else:
return 0 |
class EntropyException(Exception):
pass
class EntropyHttpUnauthorizedException(EntropyException):
pass
class EntropyHttpMkcolException(EntropyException):
pass
class EntropyHttpPropFindException(EntropyException):
pass
class EntropyHttpNoContentException(EntropyException):
pass
class EntropyHttpPutException(EntropyException):
pass
class EntropyVerifyCodeDirectoryException(EntropyException):
pass
| class Entropyexception(Exception):
pass
class Entropyhttpunauthorizedexception(EntropyException):
pass
class Entropyhttpmkcolexception(EntropyException):
pass
class Entropyhttppropfindexception(EntropyException):
pass
class Entropyhttpnocontentexception(EntropyException):
pass
class Entropyhttpputexception(EntropyException):
pass
class Entropyverifycodedirectoryexception(EntropyException):
pass |
class Dog:
def __init__(self, name):
self.name = name
class Cat:
def __init__(self, age):
self.age = age
def classify(pet):
match pet:
case Cat(age=age):
print("A cat that's {} years old".format(age))
case Dog:
print("A dog named {}".format(pet.name))
def number(x):
match x:
case 1: print("one"),
case 2 | 3: print("two or three"),
case x if x >=4: print("four or bigger"), # range matching not yet possible
case _: print("anything"),
if __name__ == "__main__":
for x in range(0, 6):
number(x)
classify(Dog("Fido"))
classify(Cat(3))
| class Dog:
def __init__(self, name):
self.name = name
class Cat:
def __init__(self, age):
self.age = age
def classify(pet):
match pet:
case Cat(age=age):
print("A cat that's {} years old".format(age))
case Dog:
print('A dog named {}'.format(pet.name))
def number(x):
match x:
case 1:
(print('one'),)
case 2 | 3:
(print('two or three'),)
case x if x >= 4:
(print('four or bigger'),)
case _:
(print('anything'),)
if __name__ == '__main__':
for x in range(0, 6):
number(x)
classify(dog('Fido'))
classify(cat(3)) |
# Exercise 1 and 2, PROGRAMMING AND SCRIPTING
# A program that displays Fibonacci numbers using people's names.
# Exercise 1:
# My name is David, so the fist and last letters of my name (d + d = 4 + 4) give 8.
# Fibonacci number 8 is 21.
# Exercise 2
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
# I have added my understanding of how the program works by way of comments within the code itself:
name = "Sheils" # assigns the string to variable name
first = name[0] # first letter of the string name
last = name[-1] # last letter of the string name
firstno = ord(first) # assigns to firstno the Unicode number of the first letter of name
lastno = ord(last) # assigns the Unicode number of the first letter of name
x = firstno + lastno # assigns to x the sum of firstno and lastno (i.e the sum of the unicode numbers for the first and last letters of the name)
ans = fib(x) # calls function fib on x (see above function definition)
print("My surname is", name)
print("The first letter", first, "is number", firstno)
print("The last letter", last, "is number", lastno)
print("Fibonacci number", x, "is", ans)
# Output of program:
# My surname is Sheils
# The first letter S is number 83
# The last letter s is number 115
# Fibonacci number 198 is 107168651819712326877926895128666735145224
# I have added my understanding of how the program works by way of comments within the code itself:
| def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
(i, j) = (j, i + j)
n = n - 1
return i
name = 'Sheils'
first = name[0]
last = name[-1]
firstno = ord(first)
lastno = ord(last)
x = firstno + lastno
ans = fib(x)
print('My surname is', name)
print('The first letter', first, 'is number', firstno)
print('The last letter', last, 'is number', lastno)
print('Fibonacci number', x, 'is', ans) |
###############EXAMPLE 4: Inputs #################
#input() function waits for an input from the keyboard
salutation = "Hello"
name = input("Tell me your name: ")
complete_salut = salutation + ', ' + name + '!'
print (complete_salut)
weight = input("Enter your weight in lb: ")
weight = int(weight) #what am I doing here???
weight_kg = weight/2.205
print (weight_kg)
###############EXAMPLE 5: Conditionals #################
if (x > y):
print ("x is greater than y")
elif (y < x):
print ("y is greater than x")
else:
print ("they are equal!")
###############EXAMPLE 6: Functions #################
def BMI(weight, height):
bmi = weight / (height ** 2)
return bmi
def convert_lb_to_kg (weight_lb):
weight_kg = weight_lb/2.205
return weight_kg
def convert_ft_in_to_m(feet, inches):
meters = feet*0.305 + inches*0.0254
return meters
print (BMI(convert_lb_to_kg(210),convert_ft_in_to_m(6,0)))
###############EXAMPLE 7: Lists #################
list_of_numbers = [1,2,3,4,5]
len(list_of_numbers)
list_of_numbers[0]
print(list_of_numbers)
list_of_numbers[4]
print(list_of_numbers)
list_of_numbers[-2]
print(list_of_numbers)
#extending it
list_of_numbers.extend([6,7,8])
print(list_of_numbers)
#slicing it
piece = list_of_numbers[:4] #beginning to 4
print (piece)
piece = list_of_numbers[2:6] #from position 2 to 6
print (piece)
#shrinking it
del list_of_numbers [2:5]
print(list_of_numbers)
#merging
list1 = [1,2,3]
list2 = [4,5,6]
list3 = list1 + list2
print(list3)
list1.extend(list2)
print(list1)
#sorting
list1 = [-1,4,0,9,2,7]
list1.sort()
print (list1)
| salutation = 'Hello'
name = input('Tell me your name: ')
complete_salut = salutation + ', ' + name + '!'
print(complete_salut)
weight = input('Enter your weight in lb: ')
weight = int(weight)
weight_kg = weight / 2.205
print(weight_kg)
if x > y:
print('x is greater than y')
elif y < x:
print('y is greater than x')
else:
print('they are equal!')
def bmi(weight, height):
bmi = weight / height ** 2
return bmi
def convert_lb_to_kg(weight_lb):
weight_kg = weight_lb / 2.205
return weight_kg
def convert_ft_in_to_m(feet, inches):
meters = feet * 0.305 + inches * 0.0254
return meters
print(bmi(convert_lb_to_kg(210), convert_ft_in_to_m(6, 0)))
list_of_numbers = [1, 2, 3, 4, 5]
len(list_of_numbers)
list_of_numbers[0]
print(list_of_numbers)
list_of_numbers[4]
print(list_of_numbers)
list_of_numbers[-2]
print(list_of_numbers)
list_of_numbers.extend([6, 7, 8])
print(list_of_numbers)
piece = list_of_numbers[:4]
print(piece)
piece = list_of_numbers[2:6]
print(piece)
del list_of_numbers[2:5]
print(list_of_numbers)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
print(list3)
list1.extend(list2)
print(list1)
list1 = [-1, 4, 0, 9, 2, 7]
list1.sort()
print(list1) |
class LegacyDatabaseRouter(object):
"""
This implements the Django DatabaseRouter protocol though we are using it to know which
role to use for the same db and to turn off migrations.
Though our underlying DB is new. We refer to this as "Legacy" because most of the time
when someone is looking to turn off Django migrations it is because of an old/existing
DB moving to a Django project that can then be managed by migrations. Not being allowed
to change schema, we are the minority. Knowing this will help you google.
The reader/writer roles most closely match a read slave/write master style setup so that
is what you google for that.
See: http://www.mechanicalgirl.com/post/reporting-django-multi-db-support/
For a nice (but dated) example that is similar to what we want for reader/writer.
As an aside, this is also good to know:
http://stackoverflow.com/questions/2628431/in-django-how-to-create-tables-from-an-sql-file-when-syncdb-is-run
"""
def db_for_read(self, model, **hints):
"""Typically for indicating a read slave. We use it to indicate the legacy db"""
return 'legacy'
def db_for_write(self, model, **hints):
"""Typically for indicating a master. We use it to indicate the 'writer' role"""
return 'legacy'
def allow_migrate(self, db, model):
"""This is the legacy bit"""
return False
def allow_relation(self, obj1, obj2, **hints):
"""This is ok as we don't actually have multiple databases"""
return True
| class Legacydatabaserouter(object):
"""
This implements the Django DatabaseRouter protocol though we are using it to know which
role to use for the same db and to turn off migrations.
Though our underlying DB is new. We refer to this as "Legacy" because most of the time
when someone is looking to turn off Django migrations it is because of an old/existing
DB moving to a Django project that can then be managed by migrations. Not being allowed
to change schema, we are the minority. Knowing this will help you google.
The reader/writer roles most closely match a read slave/write master style setup so that
is what you google for that.
See: http://www.mechanicalgirl.com/post/reporting-django-multi-db-support/
For a nice (but dated) example that is similar to what we want for reader/writer.
As an aside, this is also good to know:
http://stackoverflow.com/questions/2628431/in-django-how-to-create-tables-from-an-sql-file-when-syncdb-is-run
"""
def db_for_read(self, model, **hints):
"""Typically for indicating a read slave. We use it to indicate the legacy db"""
return 'legacy'
def db_for_write(self, model, **hints):
"""Typically for indicating a master. We use it to indicate the 'writer' role"""
return 'legacy'
def allow_migrate(self, db, model):
"""This is the legacy bit"""
return False
def allow_relation(self, obj1, obj2, **hints):
"""This is ok as we don't actually have multiple databases"""
return True |
class CachePolicy:
def __init__(self):
self.cache = []
self.cache_size = 5
| class Cachepolicy:
def __init__(self):
self.cache = []
self.cache_size = 5 |
cube = lambda x: x ** 3
def fibonacci(n):
first, second = 0, 1
for i in range(n):
yield first
first, second = second, first + second
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
| cube = lambda x: x ** 3
def fibonacci(n):
(first, second) = (0, 1)
for i in range(n):
yield first
(first, second) = (second, first + second)
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n)))) |
FACE_CASCADE = "C:/openCV/sources/data/haarcascades/haarcascade_frontalface_alt.xml"
EYE_CASCADE = "C:/openCV/sources/data/haarcascades/haarcascade_eye.xml"
DEFAULT_FACE_SIZE = (200, 200)
RECOGNIZER_OUTPUT_FILE = "train_result.out" | face_cascade = 'C:/openCV/sources/data/haarcascades/haarcascade_frontalface_alt.xml'
eye_cascade = 'C:/openCV/sources/data/haarcascades/haarcascade_eye.xml'
default_face_size = (200, 200)
recognizer_output_file = 'train_result.out' |
split = 'exp'
dataset = 'folder'
height = 320
width = 640
disparity_smoothness = 1e-3
scales = [0, 1, 2, 3, 4]
min_depth = 0.1
max_depth = 100.0
frame_ids = [0, -1, 1]
learning_rate = 1e-4
depth_num_layers = 50
pose_num_layers = 18
total_epochs = 45
device_ids = range(8)
depth_pretrained_path = './weights/resnet{}.pth'.format(depth_num_layers)
pose_pretrained_path = './weights/resnet{}.pth'.format(pose_num_layers)
in_path = './datasets/my_dataset/image_undistort'
gt_depth_path = ''
checkpoint_path = '/node01_data5/monodepth2-test/model/refine/smallfigure.pth'
imgs_per_gpu = 2
workers_per_gpu = 4
model = dict(
name = 'mono_fm',# select a model by name
depth_num_layers = depth_num_layers,
pose_num_layers = pose_num_layers,
frame_ids = frame_ids,
imgs_per_gpu = imgs_per_gpu,
height = height,
width = width,
scales = [0, 1, 2, 3],# output different scales of depth maps
min_depth = 0.1, # minimum of predicted depth value
max_depth = 100.0, # maximum of predicted depth value
depth_pretrained_path = './weights/resnet{}.pth'.format(depth_num_layers),# pretrained weights for resnet
pose_pretrained_path = './weights/resnet{}.pth'.format(pose_num_layers),# pretrained weights for resnet
extractor_pretrained_path = './weights/autoencoder.pth', # pretrained weights for autoencoder
automask = False if 's' in frame_ids else True,
disp_norm = False if 's' in frame_ids else True,
perception_weight = 1e-3,
smoothness_weight = 1e-3,
)
validate = False
png = False
scale_invariant = False
plane_fitting = False
finetune = False
perception = False
focus_loss = False
scale_invariant_weight = 0.01
plane_fitting_weight = 0.0001
perceptional_weight = 0.001
optimizer = dict(type='Adam', lr=learning_rate, weight_decay=0)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=1.0 / 3,
step=[15,25,35],
gamma=0.5,
)
checkpoint_config = dict(interval=1)
# yapf:disable
log_config = dict(interval=50,
hooks=[dict(type='TextLoggerHook'),])
# yapf:enable
# runtime settings
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)] | split = 'exp'
dataset = 'folder'
height = 320
width = 640
disparity_smoothness = 0.001
scales = [0, 1, 2, 3, 4]
min_depth = 0.1
max_depth = 100.0
frame_ids = [0, -1, 1]
learning_rate = 0.0001
depth_num_layers = 50
pose_num_layers = 18
total_epochs = 45
device_ids = range(8)
depth_pretrained_path = './weights/resnet{}.pth'.format(depth_num_layers)
pose_pretrained_path = './weights/resnet{}.pth'.format(pose_num_layers)
in_path = './datasets/my_dataset/image_undistort'
gt_depth_path = ''
checkpoint_path = '/node01_data5/monodepth2-test/model/refine/smallfigure.pth'
imgs_per_gpu = 2
workers_per_gpu = 4
model = dict(name='mono_fm', depth_num_layers=depth_num_layers, pose_num_layers=pose_num_layers, frame_ids=frame_ids, imgs_per_gpu=imgs_per_gpu, height=height, width=width, scales=[0, 1, 2, 3], min_depth=0.1, max_depth=100.0, depth_pretrained_path='./weights/resnet{}.pth'.format(depth_num_layers), pose_pretrained_path='./weights/resnet{}.pth'.format(pose_num_layers), extractor_pretrained_path='./weights/autoencoder.pth', automask=False if 's' in frame_ids else True, disp_norm=False if 's' in frame_ids else True, perception_weight=0.001, smoothness_weight=0.001)
validate = False
png = False
scale_invariant = False
plane_fitting = False
finetune = False
perception = False
focus_loss = False
scale_invariant_weight = 0.01
plane_fitting_weight = 0.0001
perceptional_weight = 0.001
optimizer = dict(type='Adam', lr=learning_rate, weight_decay=0)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
lr_config = dict(policy='step', warmup='linear', warmup_iters=500, warmup_ratio=1.0 / 3, step=[15, 25, 35], gamma=0.5)
checkpoint_config = dict(interval=1)
log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook')])
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)] |
def kadane(a):
max_current = max_global = a[0]
for i in range(1, len(a)):
max_current = max(a[i], max_current + a[i])
if max_current > max_global:
max_global = max_current
return max_global
n = int(input())
a = [int(x) for x in input().split()]
print(kadane(a))
| def kadane(a):
max_current = max_global = a[0]
for i in range(1, len(a)):
max_current = max(a[i], max_current + a[i])
if max_current > max_global:
max_global = max_current
return max_global
n = int(input())
a = [int(x) for x in input().split()]
print(kadane(a)) |
#
# @lc app=leetcode id=22 lang=python3
#
# [22] Generate Parentheses
#
class Solution:
def parse(self, acc: str):
nl, nr = 0, 0
for c in acc:
if c == '(':
nl += 1
else:
nr += 1
return nl, nr
def gen(self, n: int, acc: str) -> List[str]:
nl, nr = self.parse(acc)
if nr > nl:
raise RuntimeError('should not reach here')
if nl == n:
acc += ')' * (n - nr)
return [acc]
if nl == nr:
return self.gen(n, acc + '(')
return self.gen(n, acc + '(') + self.gen(n, acc + ')')
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
return []
return self.gen(n, '')
| class Solution:
def parse(self, acc: str):
(nl, nr) = (0, 0)
for c in acc:
if c == '(':
nl += 1
else:
nr += 1
return (nl, nr)
def gen(self, n: int, acc: str) -> List[str]:
(nl, nr) = self.parse(acc)
if nr > nl:
raise runtime_error('should not reach here')
if nl == n:
acc += ')' * (n - nr)
return [acc]
if nl == nr:
return self.gen(n, acc + '(')
return self.gen(n, acc + '(') + self.gen(n, acc + ')')
def generate_parenthesis(self, n: int) -> List[str]:
if n == 0:
return []
return self.gen(n, '') |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: certificate_profile
short_description: Resource module for Certificate Profile
description:
- Manage operations create and update of the resource Certificate Profile.
version_added: '1.0.0'
author: Rafael Campos (@racampos)
options:
allowedAsUserName:
description: AllowedAsUserName flag.
type: bool
certificateAttributeName:
description: Attribute name of the Certificate Profile - used only when CERTIFICATE
is chosen in usernameFrom. Allowed values - SUBJECT_COMMON_NAME - SUBJECT_ALTERNATIVE_NAME
- SUBJECT_SERIAL_NUMBER - SUBJECT - SUBJECT_ALTERNATIVE_NAME_OTHER_NAME - SUBJECT_ALTERNATIVE_NAME_EMAIL
- SUBJECT_ALTERNATIVE_NAME_DNS. - Additional internal value ALL_SUBJECT_AND_ALTERNATIVE_NAMES
is used automatically when usernameFrom=UPN.
type: str
description:
description: Certificate Profile's description.
type: str
externalIdentityStoreName:
description: Referred IDStore name for the Certificate Profile or not applicable
in case no identity store is chosen.
type: str
id:
description: Certificate Profile's id.
type: str
matchMode:
description: Match mode of the Certificate Profile. Allowed values - NEVER - RESOLVE_IDENTITY_AMBIGUITY
- BINARY_COMPARISON.
type: str
name:
description: Certificate Profile's name.
type: str
usernameFrom:
description: The attribute in the certificate where the user name should be taken
from. Allowed values - CERTIFICATE (for a specific attribute as defined in certificateAttributeName)
- UPN (for using any Subject or Alternative Name Attributes in the Certificate
- an option only in AD).
type: str
requirements:
- ciscoisesdk
seealso:
# Reference by Internet resource
- name: Certificate Profile reference
description: Complete reference of the Certificate Profile object model.
link: https://ciscoisesdk.readthedocs.io/en/latest/api/api.html#v3-0-0-summary
"""
EXAMPLES = r"""
- name: Update by id
cisco.ise.certificate_profile:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: present
allowedAsUserName: true
certificateAttributeName: string
description: string
externalIdentityStoreName: string
id: string
matchMode: string
name: string
usernameFrom: string
- name: Create
cisco.ise.certificate_profile:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: present
allowedAsUserName: true
certificateAttributeName: string
description: string
externalIdentityStoreName: string
id: string
matchMode: string
name: string
usernameFrom: string
"""
RETURN = r"""
ise_response:
description: A dictionary or list with the response returned by the Cisco ISE Python SDK
returned: always
type: dict
sample: >
{
"UpdatedFieldsList": {
"updatedField": [
{
"field": "string",
"oldValue": "string",
"newValue": "string"
}
]
}
}
"""
| documentation = "\n---\nmodule: certificate_profile\nshort_description: Resource module for Certificate Profile\ndescription:\n- Manage operations create and update of the resource Certificate Profile.\nversion_added: '1.0.0'\nauthor: Rafael Campos (@racampos)\noptions:\n allowedAsUserName:\n description: AllowedAsUserName flag.\n type: bool\n certificateAttributeName:\n description: Attribute name of the Certificate Profile - used only when CERTIFICATE\n is chosen in usernameFrom. Allowed values - SUBJECT_COMMON_NAME - SUBJECT_ALTERNATIVE_NAME\n - SUBJECT_SERIAL_NUMBER - SUBJECT - SUBJECT_ALTERNATIVE_NAME_OTHER_NAME - SUBJECT_ALTERNATIVE_NAME_EMAIL\n - SUBJECT_ALTERNATIVE_NAME_DNS. - Additional internal value ALL_SUBJECT_AND_ALTERNATIVE_NAMES\n is used automatically when usernameFrom=UPN.\n type: str\n description:\n description: Certificate Profile's description.\n type: str\n externalIdentityStoreName:\n description: Referred IDStore name for the Certificate Profile or not applicable\n in case no identity store is chosen.\n type: str\n id:\n description: Certificate Profile's id.\n type: str\n matchMode:\n description: Match mode of the Certificate Profile. Allowed values - NEVER - RESOLVE_IDENTITY_AMBIGUITY\n - BINARY_COMPARISON.\n type: str\n name:\n description: Certificate Profile's name.\n type: str\n usernameFrom:\n description: The attribute in the certificate where the user name should be taken\n from. Allowed values - CERTIFICATE (for a specific attribute as defined in certificateAttributeName)\n - UPN (for using any Subject or Alternative Name Attributes in the Certificate\n - an option only in AD).\n type: str\nrequirements:\n- ciscoisesdk\nseealso:\n# Reference by Internet resource\n- name: Certificate Profile reference\n description: Complete reference of the Certificate Profile object model.\n link: https://ciscoisesdk.readthedocs.io/en/latest/api/api.html#v3-0-0-summary\n"
examples = '\n- name: Update by id\n cisco.ise.certificate_profile:\n ise_hostname: "{{ise_hostname}}"\n ise_username: "{{ise_username}}"\n ise_password: "{{ise_password}}"\n ise_verify: "{{ise_verify}}"\n state: present\n allowedAsUserName: true\n certificateAttributeName: string\n description: string\n externalIdentityStoreName: string\n id: string\n matchMode: string\n name: string\n usernameFrom: string\n\n- name: Create\n cisco.ise.certificate_profile:\n ise_hostname: "{{ise_hostname}}"\n ise_username: "{{ise_username}}"\n ise_password: "{{ise_password}}"\n ise_verify: "{{ise_verify}}"\n state: present\n allowedAsUserName: true\n certificateAttributeName: string\n description: string\n externalIdentityStoreName: string\n id: string\n matchMode: string\n name: string\n usernameFrom: string\n\n'
return = '\nise_response:\n description: A dictionary or list with the response returned by the Cisco ISE Python SDK\n returned: always\n type: dict\n sample: >\n {\n "UpdatedFieldsList": {\n "updatedField": [\n {\n "field": "string",\n "oldValue": "string",\n "newValue": "string"\n }\n ]\n }\n }\n' |
def math():
test_case = int(input())
for i in range(test_case):
i_put = input()
count = len(i_put)
res = (count/100).__format__('.2f')
print(res)
if __name__ == '__main__':
math()
| def math():
test_case = int(input())
for i in range(test_case):
i_put = input()
count = len(i_put)
res = (count / 100).__format__('.2f')
print(res)
if __name__ == '__main__':
math() |
# Empty Box (2002016) | Treasure Room of Queen (926000010)
reactor.incHitCount()
reactor.increaseState()
if reactor.getHitCount() >= 4:
sm.removeReactor()
| reactor.incHitCount()
reactor.increaseState()
if reactor.getHitCount() >= 4:
sm.removeReactor() |
def on_bluetooth_connected():
basic.show_leds("""
. # # # .
# . . . .
# . . . .
# . . . .
. # # # .
""")
bluetooth.on_bluetooth_connected(on_bluetooth_connected)
def on_bluetooth_disconnected():
basic.show_leds("""
# # # . .
# . . # .
# . . # .
# . . # .
# # # . .
""")
bluetooth.on_bluetooth_disconnected(on_bluetooth_disconnected)
basic.show_leds("""
# . . # #
# . . # #
# # # . .
# . # . .
# # # . .
""")
bluetooth.start_accelerometer_service()
bluetooth.start_button_service()
bluetooth.start_led_service()
bluetooth.start_temperature_service()
| def on_bluetooth_connected():
basic.show_leds('\n . # # # .\n # . . . .\n # . . . .\n # . . . .\n . # # # .\n ')
bluetooth.on_bluetooth_connected(on_bluetooth_connected)
def on_bluetooth_disconnected():
basic.show_leds('\n # # # . .\n # . . # .\n # . . # .\n # . . # .\n # # # . .\n ')
bluetooth.on_bluetooth_disconnected(on_bluetooth_disconnected)
basic.show_leds('\n # . . # #\n # . . # #\n # # # . .\n # . # . .\n # # # . .\n ')
bluetooth.start_accelerometer_service()
bluetooth.start_button_service()
bluetooth.start_led_service()
bluetooth.start_temperature_service() |
NONE_ENUM_INDEX = 0
ACTIVATE_ENUM_INDEX = 1
ABORT_ENUM_INDEX = 2
SUSPEND_ENUM_INDEX = 3
RESUME_ENUM_INDEX = 4
STOP_ENUM_INDEX = 5
TERMINATE_ENUM_INDEX = 6
REMOVE_ENUM_INDEX = 7
| none_enum_index = 0
activate_enum_index = 1
abort_enum_index = 2
suspend_enum_index = 3
resume_enum_index = 4
stop_enum_index = 5
terminate_enum_index = 6
remove_enum_index = 7 |
# -*- coding: utf-8 -*-
def goes_after(word: str, first: str, second: str) -> bool:
if first in word and second in word:
if word.index(second) - word.index(first) == 1:
result = True
else:
result = False
else:
result = False
return result
# another pattern
try:
return word.index(second)-word.index(first) == 1
except ValueError:
return False
if __name__ == '__main__':
print("Example:")
print(goes_after('world', 'w', 'o'))
# These "asserts" are used for self-checking and not for an auto-testing
assert goes_after('world', 'w', 'o') == True
assert goes_after('world', 'w', 'r') == False
assert goes_after('world', 'l', 'o') == False
assert goes_after('panorama', 'a', 'n') == True
assert goes_after('list', 'l', 'o') == False
assert goes_after('', 'l', 'o') == False
assert goes_after('list', 'l', 'l') == False
assert goes_after('world', 'd', 'w') == False
print("Coding complete? Click 'Check' to earn cool rewards!")
| def goes_after(word: str, first: str, second: str) -> bool:
if first in word and second in word:
if word.index(second) - word.index(first) == 1:
result = True
else:
result = False
else:
result = False
return result
try:
return word.index(second) - word.index(first) == 1
except ValueError:
return False
if __name__ == '__main__':
print('Example:')
print(goes_after('world', 'w', 'o'))
assert goes_after('world', 'w', 'o') == True
assert goes_after('world', 'w', 'r') == False
assert goes_after('world', 'l', 'o') == False
assert goes_after('panorama', 'a', 'n') == True
assert goes_after('list', 'l', 'o') == False
assert goes_after('', 'l', 'o') == False
assert goes_after('list', 'l', 'l') == False
assert goes_after('world', 'd', 'w') == False
print("Coding complete? Click 'Check' to earn cool rewards!") |
class Solution(object):
# Time Complexity: O(n)
# Space Complexity: O(1)
@staticmethod
def remove_element(nums, val):
size = len(nums)
j = size -1 # going backwards
i = 0
while i <= j:
if nums[i] == val:
if nums[j] != val:
nums[i] = nums[j]
j -= 1
i += 1
else:
j -= 1
else:
i += 1
return j+1
if __name__ == '__main__':
s = Solution()
val = 2
nums = [0, 1, 2, 2, 3, 0, 4, 2]
| class Solution(object):
@staticmethod
def remove_element(nums, val):
size = len(nums)
j = size - 1
i = 0
while i <= j:
if nums[i] == val:
if nums[j] != val:
nums[i] = nums[j]
j -= 1
i += 1
else:
j -= 1
else:
i += 1
return j + 1
if __name__ == '__main__':
s = solution()
val = 2
nums = [0, 1, 2, 2, 3, 0, 4, 2] |
def strongest(to_assign, pins_to_match, strength):
def matches(segment):
a,b = segment
return a == pins_to_match or b == pins_to_match
compatible_segments = [s for s in to_assign if matches(s)]
if(len(compatible_segments) == 0):
return strength
def next(segment):
a,b = segment
left_to_assign = [s for s in to_assign if s != segment]
next_pin = a if a != pins_to_match else b
return strongest(left_to_assign, next_pin, strength + a + b)
return max(map(next, compatible_segments))
def longest(to_assign, pins_to_match, strength, length):
def matches(segment):
a,b = segment
return a == pins_to_match or b == pins_to_match
compatible_segments = [s for s in to_assign if matches(s)]
if(len(compatible_segments) == 0):
return (strength, length)
def next(segment):
a,b = segment
left_to_assign = [s for s in to_assign if s != segment]
next_pin = a if a != pins_to_match else b
return longest(left_to_assign, next_pin, strength + a + b, length + 1)
max_strenght = 0
max_length = 0
for s, l in map(next, compatible_segments):
if l > max_length:
max_length = l
max_strenght = s
elif l == max_length:
max_strenght = max(max_strenght, s)
return (max_strenght, max_length)
def parse(line):
tokens = line.split("/")
return (int(tokens[0]), int(tokens[1]))
with open("input.txt") as f:
input = list(map(parse, f.readlines()))
print(strongest(input, 0, 0))
print(longest(input, 0, 0, 0))
| def strongest(to_assign, pins_to_match, strength):
def matches(segment):
(a, b) = segment
return a == pins_to_match or b == pins_to_match
compatible_segments = [s for s in to_assign if matches(s)]
if len(compatible_segments) == 0:
return strength
def next(segment):
(a, b) = segment
left_to_assign = [s for s in to_assign if s != segment]
next_pin = a if a != pins_to_match else b
return strongest(left_to_assign, next_pin, strength + a + b)
return max(map(next, compatible_segments))
def longest(to_assign, pins_to_match, strength, length):
def matches(segment):
(a, b) = segment
return a == pins_to_match or b == pins_to_match
compatible_segments = [s for s in to_assign if matches(s)]
if len(compatible_segments) == 0:
return (strength, length)
def next(segment):
(a, b) = segment
left_to_assign = [s for s in to_assign if s != segment]
next_pin = a if a != pins_to_match else b
return longest(left_to_assign, next_pin, strength + a + b, length + 1)
max_strenght = 0
max_length = 0
for (s, l) in map(next, compatible_segments):
if l > max_length:
max_length = l
max_strenght = s
elif l == max_length:
max_strenght = max(max_strenght, s)
return (max_strenght, max_length)
def parse(line):
tokens = line.split('/')
return (int(tokens[0]), int(tokens[1]))
with open('input.txt') as f:
input = list(map(parse, f.readlines()))
print(strongest(input, 0, 0))
print(longest(input, 0, 0, 0)) |
# API messages
MATCH_DOES_NOT_EXIST_ERROR = "Match does not exist"
MATCH_WAS_NOT_FOUND_ERROR = "Match was not found"
MORE_THAN_ONE_MATCH_FOUND_ERROR = "More than one match was found to be similar. Try to increase similarity threshold"
BET_DOES_NOT_EXIST_ERROR = "Bet does not exist" | match_does_not_exist_error = 'Match does not exist'
match_was_not_found_error = 'Match was not found'
more_than_one_match_found_error = 'More than one match was found to be similar. Try to increase similarity threshold'
bet_does_not_exist_error = 'Bet does not exist' |
all_attentions_list = []
for model_name, attentions4players in best_attentions_dict.items():
for player_id, attentions4player in attentions4players.items():
all_attentions_list = all_attentions_list + [attentions4player]#.reshape(15, 1)
# mean_att = np.mean(attention_sum_list_dict['30_300_16_32_2_1_3_prefinal'], axis=0)
mean_att = np.mean(all_attentions_list[::], axis=0)
index_order = np.argsort(mean_att)
mean_att = np.median(all_attentions_list[::], axis=0)
index_order = np.argsort(mean_att)
color_att = 'olivedrab'
color_att = 'olive'
color_att = 'darkslategrey'
color_att = 'darkcyan'
margin = 0.018
fontsize = 14
plt.close()
plt.figure(figsize=(8, 5))
y_ticks = list(range(len(index_order)))
plt.barh(y_ticks, mean_att[index_order], color=color_att)
plt.xlim((mean_att.min() - margin, mean_att.max() + margin * 0.7))
plt.yticks(y_ticks, np.array(features_pretty)[index_order], fontsize=fontsize)
plt.xlabel('Mean Attention', fontsize=fontsize+3)
plt.title('Feature Importance', fontsize=fontsize+6)
plt.tight_layout()
plt.savefig('pic/attention_importance_v0.png')
plt.interactive(True)
plt.barh(mean_att[index_order], np.array(features_pretty)[index_order])
# for time_step in [5, 10, 20, 30, 40, 60, 120]:
# command = f'python TimeseriesFinalPreprocessing.py --TIMESTEP {time_step}'
# os.system(command)
# print('Done')
#
| all_attentions_list = []
for (model_name, attentions4players) in best_attentions_dict.items():
for (player_id, attentions4player) in attentions4players.items():
all_attentions_list = all_attentions_list + [attentions4player]
mean_att = np.mean(all_attentions_list[:], axis=0)
index_order = np.argsort(mean_att)
mean_att = np.median(all_attentions_list[:], axis=0)
index_order = np.argsort(mean_att)
color_att = 'olivedrab'
color_att = 'olive'
color_att = 'darkslategrey'
color_att = 'darkcyan'
margin = 0.018
fontsize = 14
plt.close()
plt.figure(figsize=(8, 5))
y_ticks = list(range(len(index_order)))
plt.barh(y_ticks, mean_att[index_order], color=color_att)
plt.xlim((mean_att.min() - margin, mean_att.max() + margin * 0.7))
plt.yticks(y_ticks, np.array(features_pretty)[index_order], fontsize=fontsize)
plt.xlabel('Mean Attention', fontsize=fontsize + 3)
plt.title('Feature Importance', fontsize=fontsize + 6)
plt.tight_layout()
plt.savefig('pic/attention_importance_v0.png')
plt.interactive(True)
plt.barh(mean_att[index_order], np.array(features_pretty)[index_order]) |
class VggFaceDetector(object):
"""
preform prediction
"""
def __init__(self, model):
super().__init__()
self.model = model
def make_prediction(self, data):
image = data['image']
bbox = self.model.detect_faces(image)
data.update({'predictions': bbox})
return data
| class Vggfacedetector(object):
"""
preform prediction
"""
def __init__(self, model):
super().__init__()
self.model = model
def make_prediction(self, data):
image = data['image']
bbox = self.model.detect_faces(image)
data.update({'predictions': bbox})
return data |
def mult(x, y):
result_mult = 0
i = 0
while i < y: # Here I choose 'y' (witch is the base) to show how many times 'x' going to be sum with itself.
i += 1
result_mult += x
return result_mult
def expo():
base = int(input("Type a base: "))
expo = int(input("Type an exponent: "))
if base < 0 or 0 > expo:
print("Don't type any negative value, please try again.")
else:
result_expo = 1
if expo == 0: # If the exponent is equal 0 the result number going to be '1'.
print(f"{base} ^ {expo} = {result_expo}".format(base,expo,result_expo))
else:
i = 0
while i < expo:
i += 1
result_expo = mult(result_expo, base) # result_expo is being multiplied by the base, it's the same thing as ( result_expo * base )
print(f"{base} ^ {expo} = {result_expo}".format(base,expo,result_expo))
expo()
| def mult(x, y):
result_mult = 0
i = 0
while i < y:
i += 1
result_mult += x
return result_mult
def expo():
base = int(input('Type a base: '))
expo = int(input('Type an exponent: '))
if base < 0 or 0 > expo:
print("Don't type any negative value, please try again.")
else:
result_expo = 1
if expo == 0:
print(f'{base} ^ {expo} = {result_expo}'.format(base, expo, result_expo))
else:
i = 0
while i < expo:
i += 1
result_expo = mult(result_expo, base)
print(f'{base} ^ {expo} = {result_expo}'.format(base, expo, result_expo))
expo() |
# -*- coding: utf-8 -*-
class JsonerException(Exception):
"""
Base Exception class
"""
pass
class JsonEncodingError(JsonerException):
"""
This error occurs if *Jsoner* cannot encode your object to json.
"""
| class Jsonerexception(Exception):
"""
Base Exception class
"""
pass
class Jsonencodingerror(JsonerException):
"""
This error occurs if *Jsoner* cannot encode your object to json.
""" |
def magicalWell(a, b, n):
total = 0
for i in range(n):
total += a * b
a += 1
b += 1
return total
| def magical_well(a, b, n):
total = 0
for i in range(n):
total += a * b
a += 1
b += 1
return total |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
COHORTE Repositories of bundles and component factories
:author: Thomas Calmant
:license: Apache Software License 2.0
..
Copyright 2014 isandlaTech
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.
"""
# Documentation strings format
__docformat__ = "restructuredtext en"
# ------------------------------------------------------------------------------
SERVICE_REPOSITORY_ARTIFACTS = "cohorte.repositories.artifacts"
""" Specification of a repository of artifacts """
SERVICE_REPOSITORY_FACTORIES = "cohorte.repositories.factories"
""" Specification of a repository of component factories """
PROP_REPOSITORY_LANGUAGE = "cohorte.repository.language"
""" Language of implementation of the artifacts handled by the repository """
PROP_FACTORY_MODEL = "cohorte.repository.factory.model"
""" Name of the component model handling the factories """
| """
COHORTE Repositories of bundles and component factories
:author: Thomas Calmant
:license: Apache Software License 2.0
..
Copyright 2014 isandlaTech
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.
"""
__docformat__ = 'restructuredtext en'
service_repository_artifacts = 'cohorte.repositories.artifacts'
' Specification of a repository of artifacts '
service_repository_factories = 'cohorte.repositories.factories'
' Specification of a repository of component factories '
prop_repository_language = 'cohorte.repository.language'
' Language of implementation of the artifacts handled by the repository '
prop_factory_model = 'cohorte.repository.factory.model'
' Name of the component model handling the factories ' |
"""
This Bazel extension contains the set of rule definitions to deal with generic IO.
"""
def _print_files_impl(ctx):
"""
An executable rule to print to the terminal the files passed via the 'srcs' property.
"""
executable = ctx.actions.declare_file(ctx.attr.name)
contents = "cat {}".format(" ".join([src.short_path for src in ctx.files.srcs]))
ctx.actions.write(executable, contents, is_executable = True)
return [DefaultInfo(
executable = executable,
runfiles = ctx.runfiles(files = ctx.files.srcs),
)]
print_files = rule(
implementation = _print_files_impl,
attrs = {
"srcs": attr.label_list(
allow_files = True,
doc = "The list of files to be printed to the terminal",
),
},
executable = True,
)
| """
This Bazel extension contains the set of rule definitions to deal with generic IO.
"""
def _print_files_impl(ctx):
"""
An executable rule to print to the terminal the files passed via the 'srcs' property.
"""
executable = ctx.actions.declare_file(ctx.attr.name)
contents = 'cat {}'.format(' '.join([src.short_path for src in ctx.files.srcs]))
ctx.actions.write(executable, contents, is_executable=True)
return [default_info(executable=executable, runfiles=ctx.runfiles(files=ctx.files.srcs))]
print_files = rule(implementation=_print_files_impl, attrs={'srcs': attr.label_list(allow_files=True, doc='The list of files to be printed to the terminal')}, executable=True) |
# n is not required in this program
# to meet the requirements of STDIN of hackerrank we are using n variable
def soln(a, scores):
scores = sorted(list(dict.fromkeys(scores)))
print(scores[-2])
if __name__ == "__main__":
n = int(input())
arr = map(int, input().split())
soln(n, arr)
| def soln(a, scores):
scores = sorted(list(dict.fromkeys(scores)))
print(scores[-2])
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
soln(n, arr) |
# Copyright (c) 2020. Brendan Johnson. All Rights Reserved.
#import connect
#import config
class ReportTemplates:
def __init__(self, config, connection):
self._config=config
self._connection = connection
##EventBasedTasks
def list(self):
return self._connection.get(url='/reporttemplates')
def search(self, payload):
return self._connection.post(url='/reporttemplates/search', data=payload)
def describe(self, reportID):
return self._connection.get(url='/reporttemplates/{reportTemplateID}'.format(reportTemplateID=reportID))
| class Reporttemplates:
def __init__(self, config, connection):
self._config = config
self._connection = connection
def list(self):
return self._connection.get(url='/reporttemplates')
def search(self, payload):
return self._connection.post(url='/reporttemplates/search', data=payload)
def describe(self, reportID):
return self._connection.get(url='/reporttemplates/{reportTemplateID}'.format(reportTemplateID=reportID)) |
#!/usr/bin/env python
def clamp(low, x, high):
return low if x < low else high if x > high else x
def unwrap(txt):
return ' '.join(( s.strip() for s in txt.strip().splitlines() ))
| def clamp(low, x, high):
return low if x < low else high if x > high else x
def unwrap(txt):
return ' '.join((s.strip() for s in txt.strip().splitlines())) |
class Package:
"""
Data structure for repo packages.
Attributes:
name (str): The name of the package.
version (str): Version number of the package.
size (int): Size of the package.
depends (list): List of dependent package identifiers (conjunct of disjuncts).
conflicts (list): List of conflicting package identifers (conjuncts).
id (str): The ID of the package.
"""
def __init__(self, name, version, size, depends, conflicts):
self.name = name
self.version = version
self.size = size
self.depends = depends
self.conflicts = conflicts
self.id = "{}={}".format(name, version)
def __str__(self):
return self.__repr__()
def __repr__(self):
res = "Package(name={}, version={}, size={}, depends={}, conflicts={})".format(
self.name,
self.version,
self.size,
self.depends,
self.conflicts
)
return res
def within_range(self, op, version_id):
"""Given a version identifier and comparison operation returns True if own version
is within the given range otherwise False."""
if op == None or version_id == None:
return True
elif op == "<=":
if self.compare_version(version_id) in [0, -1]:
return True
elif op == ">=":
if self.compare_version(version_id) in [1, 0]:
return True
elif op == "<":
if self.compare_version(version_id) == -1:
return True
elif op == ">":
if self.compare_version(version_id) == 1:
return True
elif op == "=":
if self.compare_version(version_id) == 0:
return True
return False
def compare_version(self, comparison):
"""Compares own version against paramater provided.
If own version is greater returns '1', if versions are the same '0' and '-1' if lower."""
# Split the two versions into integer lists
# of equal length.
v = [int(item) for item in self.version.split('.')]
c = [int(item) for item in comparison.split('.')]
length = len(v) if len(v) > len(c) else len(c)
v = (v + length * [0])[:length]
c = (c + length * [0])[:length]
# Iterate over lists comparing values.
for i in range(length):
if v[i] == c[i]:
continue
elif v[i] < c[i]:
return -1
elif v[i] > c[i]:
return 1
return 0 | class Package:
"""
Data structure for repo packages.
Attributes:
name (str): The name of the package.
version (str): Version number of the package.
size (int): Size of the package.
depends (list): List of dependent package identifiers (conjunct of disjuncts).
conflicts (list): List of conflicting package identifers (conjuncts).
id (str): The ID of the package.
"""
def __init__(self, name, version, size, depends, conflicts):
self.name = name
self.version = version
self.size = size
self.depends = depends
self.conflicts = conflicts
self.id = '{}={}'.format(name, version)
def __str__(self):
return self.__repr__()
def __repr__(self):
res = 'Package(name={}, version={}, size={}, depends={}, conflicts={})'.format(self.name, self.version, self.size, self.depends, self.conflicts)
return res
def within_range(self, op, version_id):
"""Given a version identifier and comparison operation returns True if own version
is within the given range otherwise False."""
if op == None or version_id == None:
return True
elif op == '<=':
if self.compare_version(version_id) in [0, -1]:
return True
elif op == '>=':
if self.compare_version(version_id) in [1, 0]:
return True
elif op == '<':
if self.compare_version(version_id) == -1:
return True
elif op == '>':
if self.compare_version(version_id) == 1:
return True
elif op == '=':
if self.compare_version(version_id) == 0:
return True
return False
def compare_version(self, comparison):
"""Compares own version against paramater provided.
If own version is greater returns '1', if versions are the same '0' and '-1' if lower."""
v = [int(item) for item in self.version.split('.')]
c = [int(item) for item in comparison.split('.')]
length = len(v) if len(v) > len(c) else len(c)
v = (v + length * [0])[:length]
c = (c + length * [0])[:length]
for i in range(length):
if v[i] == c[i]:
continue
elif v[i] < c[i]:
return -1
elif v[i] > c[i]:
return 1
return 0 |
def get_detail(param: str, field: str, message: str, err: str):
detail = [
{
'loc': [
f'{param}', # ex. body
f'{field}' # ex. title
],
"msg": message, # ex. field required, not found
"type": f"{err}.missing" # ex. value_error
}
]
return detail
class InternalException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class NoSuchElementException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class InvalidArgumentException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class RequestConflictException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class ForbiddenException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class RequestInvalidException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message | def get_detail(param: str, field: str, message: str, err: str):
detail = [{'loc': [f'{param}', f'{field}'], 'msg': message, 'type': f'{err}.missing'}]
return detail
class Internalexception(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class Nosuchelementexception(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class Invalidargumentexception(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class Requestconflictexception(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class Forbiddenexception(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class Requestinvalidexception(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message |
""" Day 07 of the 2021 Advent of Code
https://adventofcode.com/2021/day/7
https://adventofcode.com/2021/day/7/input """
def load_data(path):
data_list = []
with open(path, "r") as file:
for line in file:
data_list = data_list + [int(value.strip()) for value in line.split(",")]
return data_list
def calculate_crab_fuel_needs(data, fuelcomsumption_increases=False):
solution = -1
for target in range(max(data)):
local_score = 0
for start in data:
steps = abs(target - start)
if not fuelcomsumption_increases:
# part 1
local_score = local_score + steps
else:
# part 2
local_score = local_score + sum(list(range(steps + 1)))
# early skip if local score is escalating the pan out
# saves 35s on excecutiontime when solving part 2
if local_score > solution and solution != -1:
break
if local_score < solution or solution == -1:
solution = local_score
return solution
def main():
data = load_data("..//Data//Prod.txt")
data_test = load_data("..//Data//Test.txt")
assert calculate_crab_fuel_needs(data_test, False) == 37
assert calculate_crab_fuel_needs(data, False) == 357353
assert calculate_crab_fuel_needs(data_test, True) == 168
assert calculate_crab_fuel_needs(data, True) == 104822130
if __name__ == "__main__":
main()
| """ Day 07 of the 2021 Advent of Code
https://adventofcode.com/2021/day/7
https://adventofcode.com/2021/day/7/input """
def load_data(path):
data_list = []
with open(path, 'r') as file:
for line in file:
data_list = data_list + [int(value.strip()) for value in line.split(',')]
return data_list
def calculate_crab_fuel_needs(data, fuelcomsumption_increases=False):
solution = -1
for target in range(max(data)):
local_score = 0
for start in data:
steps = abs(target - start)
if not fuelcomsumption_increases:
local_score = local_score + steps
else:
local_score = local_score + sum(list(range(steps + 1)))
if local_score > solution and solution != -1:
break
if local_score < solution or solution == -1:
solution = local_score
return solution
def main():
data = load_data('..//Data//Prod.txt')
data_test = load_data('..//Data//Test.txt')
assert calculate_crab_fuel_needs(data_test, False) == 37
assert calculate_crab_fuel_needs(data, False) == 357353
assert calculate_crab_fuel_needs(data_test, True) == 168
assert calculate_crab_fuel_needs(data, True) == 104822130
if __name__ == '__main__':
main() |
#!/bin/python3
def poisonousPlants(p):
# Complete this function
survives = list()
survives.append(p[0])
dies = list()
num_plants = len(p)
p_killed = [0]*num_plants
killed_day = [0]*num_plants
for i in range(1,num_plants):
if(p[i] > p[i - 1]):
if(p_killed[i - 1] == 1):
if(survives[-1] < p[i] and dies[-1] < p[i]):
killed_day[i] = killed_day[i-1]
elif(survives[-1] < p[i] and dies[-1] > p[i]):
killed_day[i] = 1 + killed_day[i-1]
dies.append(p[i])
p_killed[i] = 1
else:
#survives.append(p[i])
dies.append(p[i])
p_killed[i] = 1
killed_day[i] = 1
elif(p[i] < p[i - 1]):
if(p_killed[i-1] == 1 and (p[i] > survives[-1] or p[i] > dies[-1])):
killed_day[i] = 1 + killed_day[i-1]
dies.append(p[i])
p_killed[i] = 1
else:
survives.append(p[i])
else:
if(p_killed[i-1] == 1):
p_killed[i] = 1
killed_day = killed_day[i-1]
dies.append(p[i])
else:
survives.append(p[i])
days = max(killed_day)
return days
if __name__ == "__main__":
n = int(input().strip())
p = list(map(int, input().strip().split(' ')))
result = poisonousPlants(p)
print(result) | def poisonous_plants(p):
survives = list()
survives.append(p[0])
dies = list()
num_plants = len(p)
p_killed = [0] * num_plants
killed_day = [0] * num_plants
for i in range(1, num_plants):
if p[i] > p[i - 1]:
if p_killed[i - 1] == 1:
if survives[-1] < p[i] and dies[-1] < p[i]:
killed_day[i] = killed_day[i - 1]
elif survives[-1] < p[i] and dies[-1] > p[i]:
killed_day[i] = 1 + killed_day[i - 1]
dies.append(p[i])
p_killed[i] = 1
else:
dies.append(p[i])
p_killed[i] = 1
killed_day[i] = 1
elif p[i] < p[i - 1]:
if p_killed[i - 1] == 1 and (p[i] > survives[-1] or p[i] > dies[-1]):
killed_day[i] = 1 + killed_day[i - 1]
dies.append(p[i])
p_killed[i] = 1
else:
survives.append(p[i])
elif p_killed[i - 1] == 1:
p_killed[i] = 1
killed_day = killed_day[i - 1]
dies.append(p[i])
else:
survives.append(p[i])
days = max(killed_day)
return days
if __name__ == '__main__':
n = int(input().strip())
p = list(map(int, input().strip().split(' ')))
result = poisonous_plants(p)
print(result) |
class FailureDefinitionAccessor(object, IDisposable):
""" A class that provides access to the details of a FailureDefinition after the definition has been defined. """
def Dispose(self):
""" Dispose(self: FailureDefinitionAccessor) """
pass
def GetApplicableResolutionTypes(self):
"""
GetApplicableResolutionTypes(self: FailureDefinitionAccessor) -> IList[FailureResolutionType]
Retrieves a list of resolution types applicable to the failure.
Returns: The list of resolution types applicable to the failure.
"""
pass
def GetDefaultResolutionType(self):
"""
GetDefaultResolutionType(self: FailureDefinitionAccessor) -> FailureResolutionType
Retrieves the default resolution type for the failure.
Returns: The default resolution type for the failure.
"""
pass
def GetDescriptionText(self):
"""
GetDescriptionText(self: FailureDefinitionAccessor) -> str
Retrieves the description text of the failure.
Returns: The description text.
"""
pass
def GetId(self):
"""
GetId(self: FailureDefinitionAccessor) -> FailureDefinitionId
Retrieves the unique identifier of the FailureDefinition.
Returns: The unique identifier of the FailureDefinition.
"""
pass
def GetResolutionCaption(self, type):
"""
GetResolutionCaption(self: FailureDefinitionAccessor,type: FailureResolutionType) -> str
Retrieves the caption for a specific resolution type.
type: The resolution type.
Returns: The caption of the resolution.
"""
pass
def GetSeverity(self):
"""
GetSeverity(self: FailureDefinitionAccessor) -> FailureSeverity
Retrieves severity of the failure.
Returns: The severity of the failure.
"""
pass
def HasResolutions(self):
"""
HasResolutions(self: FailureDefinitionAccessor) -> bool
Checks if the FailureDefinition has at least one resolution.
Returns: True if at least one resolution is defined in the FailureDefinition.
"""
pass
def IsResolutionApplicable(self, type):
"""
IsResolutionApplicable(self: FailureDefinitionAccessor,type: FailureResolutionType) -> bool
Checks if the given resolution type is applicable to the failure.
type: The resolution type to check.
Returns: True if the given resolution type is applicable to the failure,false otherwise.
"""
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: FailureDefinitionAccessor,disposing: bool) """
pass
def SetDefaultResolutionType(self, type):
"""
SetDefaultResolutionType(self: FailureDefinitionAccessor,type: FailureResolutionType)
Sets the default resolution type for the failure.
type: The type of resolution to be used as default.
"""
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
def __repr__(self, *args):
""" __repr__(self: object) -> str """
pass
IsValidObject = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Specifies whether the .NET object represents a valid Revit entity.
Get: IsValidObject(self: FailureDefinitionAccessor) -> bool
"""
| class Failuredefinitionaccessor(object, IDisposable):
""" A class that provides access to the details of a FailureDefinition after the definition has been defined. """
def dispose(self):
""" Dispose(self: FailureDefinitionAccessor) """
pass
def get_applicable_resolution_types(self):
"""
GetApplicableResolutionTypes(self: FailureDefinitionAccessor) -> IList[FailureResolutionType]
Retrieves a list of resolution types applicable to the failure.
Returns: The list of resolution types applicable to the failure.
"""
pass
def get_default_resolution_type(self):
"""
GetDefaultResolutionType(self: FailureDefinitionAccessor) -> FailureResolutionType
Retrieves the default resolution type for the failure.
Returns: The default resolution type for the failure.
"""
pass
def get_description_text(self):
"""
GetDescriptionText(self: FailureDefinitionAccessor) -> str
Retrieves the description text of the failure.
Returns: The description text.
"""
pass
def get_id(self):
"""
GetId(self: FailureDefinitionAccessor) -> FailureDefinitionId
Retrieves the unique identifier of the FailureDefinition.
Returns: The unique identifier of the FailureDefinition.
"""
pass
def get_resolution_caption(self, type):
"""
GetResolutionCaption(self: FailureDefinitionAccessor,type: FailureResolutionType) -> str
Retrieves the caption for a specific resolution type.
type: The resolution type.
Returns: The caption of the resolution.
"""
pass
def get_severity(self):
"""
GetSeverity(self: FailureDefinitionAccessor) -> FailureSeverity
Retrieves severity of the failure.
Returns: The severity of the failure.
"""
pass
def has_resolutions(self):
"""
HasResolutions(self: FailureDefinitionAccessor) -> bool
Checks if the FailureDefinition has at least one resolution.
Returns: True if at least one resolution is defined in the FailureDefinition.
"""
pass
def is_resolution_applicable(self, type):
"""
IsResolutionApplicable(self: FailureDefinitionAccessor,type: FailureResolutionType) -> bool
Checks if the given resolution type is applicable to the failure.
type: The resolution type to check.
Returns: True if the given resolution type is applicable to the failure,false otherwise.
"""
pass
def release_unmanaged_resources(self, *args):
""" ReleaseUnmanagedResources(self: FailureDefinitionAccessor,disposing: bool) """
pass
def set_default_resolution_type(self, type):
"""
SetDefaultResolutionType(self: FailureDefinitionAccessor,type: FailureResolutionType)
Sets the default resolution type for the failure.
type: The type of resolution to be used as default.
"""
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
def __repr__(self, *args):
""" __repr__(self: object) -> str """
pass
is_valid_object = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Specifies whether the .NET object represents a valid Revit entity.\n\n\n\nGet: IsValidObject(self: FailureDefinitionAccessor) -> bool\n\n\n\n' |
def least_rotation(s):
s += s
i, ans = 0, 0
while 2*i < len(s):
ans = i
j, k = i + 1, i
while (2*j < len(s)) and (s[k] <= s[j]):
if s[k] < s[j]:
k = i
else:
k += 1
j += 1
while i <= k:
i += j - k
return s[ans:ans + (len(s) // 2)]
| def least_rotation(s):
s += s
(i, ans) = (0, 0)
while 2 * i < len(s):
ans = i
(j, k) = (i + 1, i)
while 2 * j < len(s) and s[k] <= s[j]:
if s[k] < s[j]:
k = i
else:
k += 1
j += 1
while i <= k:
i += j - k
return s[ans:ans + len(s) // 2] |
'''
Title : Check Strict Superset
Subdomain : Sets
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
'''
a = set(map(int, input().split()))
f = 0
for i in range(int(input())):
b = set(map(int, input().split()))
if len(b.difference(a)) != 0:
f = 1
else:
if len(b) == len(a):
f =1
if f == 0:
print('True')
else:
print('False') | """
Title : Check Strict Superset
Subdomain : Sets
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
"""
a = set(map(int, input().split()))
f = 0
for i in range(int(input())):
b = set(map(int, input().split()))
if len(b.difference(a)) != 0:
f = 1
elif len(b) == len(a):
f = 1
if f == 0:
print('True')
else:
print('False') |
'''
Methods for parsing chromosomic data
'''
def load_breaks(file_location, only_tra=False):
"""
Reads a file, storing the breaks in a dictionary.
Input:
file_location: full path to file, containing breaks in a genome
Output:
breaks_by_chromosome: dictionary {str:[int]}, where keys are chromosome ids
and the corresponding non-empty list contains the breaks in that chromosome (sorted).
list_of_pairs: list[((str,int),(str,int))]. List of breaks, each entry contains
first chromosome and position within, second chromosome and position within.
"""
breaks_by_chromosome = {}
list_of_pairs = []
# Process file by file
with open(file_location) as f:
# Skip the first line, which is a descriptor of fields
f.next()
# Read break by break
for l in f:
if len(l.split('\t')) != 5:
raise Exception("Wrong number of fields (i.e., not 5) in line", l)
chromosome1, chromosome1_pos, chromosome2, chromosome2_pos, break_type = l.split('\t')
if only_tra:
if 'TRA' in break_type:
chromosome1_pos = int(chromosome1_pos)
chromosome2_pos = int(chromosome2_pos)
# If its the first break found in this chromosome, initialize the chromosome list
if chromosome1 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome1] = [chromosome1_pos]
# Otherwise add it to the end
else:
breaks_by_chromosome[chromosome1].append(chromosome1_pos)
# The same for the second chromosome
if chromosome2 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome2] = [chromosome2_pos]
else:
breaks_by_chromosome[chromosome2].append(chromosome2_pos)
# Also update the list of pairs
list_of_pairs.append(((chromosome1, chromosome1_pos),
(chromosome2, chromosome2_pos)))
else:
chromosome1_pos = int(chromosome1_pos)
chromosome2_pos = int(chromosome2_pos)
# If its the first break found in this chromosome, initialize the chromosome list
if chromosome1 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome1] = [chromosome1_pos]
# Otherwise add it to the end
else:
breaks_by_chromosome[chromosome1].append(chromosome1_pos)
# The same for the second chromosome
if chromosome2 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome2] = [chromosome2_pos]
else:
breaks_by_chromosome[chromosome2].append(chromosome2_pos)
# Also update the list of pairs
list_of_pairs.append(((chromosome1, chromosome1_pos),
(chromosome2, chromosome2_pos)))
# Sort the lists
for k in breaks_by_chromosome.keys():
breaks_by_chromosome[k] = sorted(breaks_by_chromosome[k], key=int)
return breaks_by_chromosome, list_of_pairs
| """
Methods for parsing chromosomic data
"""
def load_breaks(file_location, only_tra=False):
"""
Reads a file, storing the breaks in a dictionary.
Input:
file_location: full path to file, containing breaks in a genome
Output:
breaks_by_chromosome: dictionary {str:[int]}, where keys are chromosome ids
and the corresponding non-empty list contains the breaks in that chromosome (sorted).
list_of_pairs: list[((str,int),(str,int))]. List of breaks, each entry contains
first chromosome and position within, second chromosome and position within.
"""
breaks_by_chromosome = {}
list_of_pairs = []
with open(file_location) as f:
f.next()
for l in f:
if len(l.split('\t')) != 5:
raise exception('Wrong number of fields (i.e., not 5) in line', l)
(chromosome1, chromosome1_pos, chromosome2, chromosome2_pos, break_type) = l.split('\t')
if only_tra:
if 'TRA' in break_type:
chromosome1_pos = int(chromosome1_pos)
chromosome2_pos = int(chromosome2_pos)
if chromosome1 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome1] = [chromosome1_pos]
else:
breaks_by_chromosome[chromosome1].append(chromosome1_pos)
if chromosome2 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome2] = [chromosome2_pos]
else:
breaks_by_chromosome[chromosome2].append(chromosome2_pos)
list_of_pairs.append(((chromosome1, chromosome1_pos), (chromosome2, chromosome2_pos)))
else:
chromosome1_pos = int(chromosome1_pos)
chromosome2_pos = int(chromosome2_pos)
if chromosome1 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome1] = [chromosome1_pos]
else:
breaks_by_chromosome[chromosome1].append(chromosome1_pos)
if chromosome2 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome2] = [chromosome2_pos]
else:
breaks_by_chromosome[chromosome2].append(chromosome2_pos)
list_of_pairs.append(((chromosome1, chromosome1_pos), (chromosome2, chromosome2_pos)))
for k in breaks_by_chromosome.keys():
breaks_by_chromosome[k] = sorted(breaks_by_chromosome[k], key=int)
return (breaks_by_chromosome, list_of_pairs) |
# -*- coding: UTF-8 -*-
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: list
:type nums2: list
:rtype : float
"""
# may be wrong
new_nums = sorted(nums1 + nums2)
new_nums_len = len(new_nums)
if new_nums_len % 2 == 0:
return (new_nums[new_nums_len//2-1] + new_nums[new_nums_len//2]) / 2
else:
return new_nums[(new_nums_len)//2]
def main():
nums1 = [1, 3]
nums2 = [2]
result = Solution().findMedianSortedArrays(nums1, nums2)
print(str("%.1f" % result))
if __name__ == '__main__':
main() | class Solution:
def find_median_sorted_arrays(self, nums1, nums2):
"""
:type nums1: list
:type nums2: list
:rtype : float
"""
new_nums = sorted(nums1 + nums2)
new_nums_len = len(new_nums)
if new_nums_len % 2 == 0:
return (new_nums[new_nums_len // 2 - 1] + new_nums[new_nums_len // 2]) / 2
else:
return new_nums[new_nums_len // 2]
def main():
nums1 = [1, 3]
nums2 = [2]
result = solution().findMedianSortedArrays(nums1, nums2)
print(str('%.1f' % result))
if __name__ == '__main__':
main() |
print("I will now count my chickens:") #presents the question
print("Hens", 25 + 30 / 6) #counts the Hens
print("Roosters", 100 - 25 * 3 % 4) #counts the Roosters
print("Now I will count the eggs:") #presents another question
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) #counts the eggs
print("Is it true that 3 + 2 < 5 - 7?") #shows False bevcause this is False
print(3 + 2 < 5 - 7) #counts
print("What is 3 + 2?", 3 + 2) #counts
print("What is 5 - 7?", 5 - 7) #counts
print("Oh, that's why it's False.") #explains why false
print("How about some more.") #presents more
print("Is it greater?", 5 > -2) #shows true because this is true
print("Is it greater or equal?", 5 >= -2) #shows true because this is true
print("Is it less or equal?", 5 <= -2) #shows false because this is false
| print('I will now count my chickens:')
print('Hens', 25 + 30 / 6)
print('Roosters', 100 - 25 * 3 % 4)
print('Now I will count the eggs:')
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print('Is it true that 3 + 2 < 5 - 7?')
print(3 + 2 < 5 - 7)
print('What is 3 + 2?', 3 + 2)
print('What is 5 - 7?', 5 - 7)
print("Oh, that's why it's False.")
print('How about some more.')
print('Is it greater?', 5 > -2)
print('Is it greater or equal?', 5 >= -2)
print('Is it less or equal?', 5 <= -2) |
# -*- coding=utf-8 -*-
'''
'''
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
length=len(temperatures)
result=[i for i in range(0,length)]
for i in range(0,length):
i=length-i-1
if i==length-1:
result[i]=0
continue
return result
temperatures=[73, 74, 75, 71, 69, 72, 76, 73]
A=Solution()
A.dailyTemperatures(temperatures) | """
"""
class Solution(object):
def daily_temperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
length = len(temperatures)
result = [i for i in range(0, length)]
for i in range(0, length):
i = length - i - 1
if i == length - 1:
result[i] = 0
continue
return result
temperatures = [73, 74, 75, 71, 69, 72, 76, 73]
a = solution()
A.dailyTemperatures(temperatures) |
n_lines = int(input("How many lines? "))
counter = 1
while n_lines >= counter:
print("This is line " + str(counter))
counter += 1
# print("This is line " + str(counter))
print()
input("Press return to continue ...")
| n_lines = int(input('How many lines? '))
counter = 1
while n_lines >= counter:
print('This is line ' + str(counter))
counter += 1
print()
input('Press return to continue ...') |
'''
Token class that will hold each encountered lexeme, its associated token type (e.g. TokenType.PLUS), the line number in the file where it was found as well as the actual literal value.
Note that the "literal" argument in most cases when we're creating Tokens will be empty. The only times we will care about the "literal" argument is when we need to extract the actual numeric or string value of our lexeme
'''
class Token:
def __init__(self, token_type, lexeme: str, line : int, literal=""):
self.token_type = token_type
self.lexeme = lexeme
self.line = line
self.literal = literal
def __str__(self):
return str(self.token_type.name + " " + self.lexeme + " " + str(self.literal))
| """
Token class that will hold each encountered lexeme, its associated token type (e.g. TokenType.PLUS), the line number in the file where it was found as well as the actual literal value.
Note that the "literal" argument in most cases when we're creating Tokens will be empty. The only times we will care about the "literal" argument is when we need to extract the actual numeric or string value of our lexeme
"""
class Token:
def __init__(self, token_type, lexeme: str, line: int, literal=''):
self.token_type = token_type
self.lexeme = lexeme
self.line = line
self.literal = literal
def __str__(self):
return str(self.token_type.name + ' ' + self.lexeme + ' ' + str(self.literal)) |
def lonelyinteger(nums):
for i in range(len(nums)):
if nums.count(nums[i]) == 1:
return nums[i]
if __name__ == '__main__':
a = input()
nums = map(int, raw_input().strip().split(" "))
print(lonelyinteger(nums))
| def lonelyinteger(nums):
for i in range(len(nums)):
if nums.count(nums[i]) == 1:
return nums[i]
if __name__ == '__main__':
a = input()
nums = map(int, raw_input().strip().split(' '))
print(lonelyinteger(nums)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
def mirror(pair):
if type(pair) != list and \
type(pair) != str and \
type(pair) != tuple:
raise ValueError("Wrong type.\nPlease provide a str, list or set.")
assert len(pair) >= 2
return pair[0], pair[-1]
#%%
print(mirror("test"))
print(mirror((1, 2, 3, 5)))
print(mirror(5)) | """
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
def mirror(pair):
if type(pair) != list and type(pair) != str and (type(pair) != tuple):
raise value_error('Wrong type.\nPlease provide a str, list or set.')
assert len(pair) >= 2
return (pair[0], pair[-1])
print(mirror('test'))
print(mirror((1, 2, 3, 5)))
print(mirror(5)) |
#%%
"""
- Text Justification
- https://leetcode.com/problems/text-justification/
- Hard
"""
#%%
| """
- Text Justification
- https://leetcode.com/problems/text-justification/
- Hard
""" |
bins_met_px = {"in": "MET_px", "out": "met_px", "bins": dict(nbins=10, low=0, high=100)}
bins_py = {"in": "Jet_Py", "out": "py_leadJet", "bins": dict(edges=[0, 20., 100.], overflow=True), "index": 0}
bins_nmuon = {"in": "NMuon", "out": "nmuon"}
weight_list = ["EventWeight"]
weight_dict = dict(weighted="EventWeight")
| bins_met_px = {'in': 'MET_px', 'out': 'met_px', 'bins': dict(nbins=10, low=0, high=100)}
bins_py = {'in': 'Jet_Py', 'out': 'py_leadJet', 'bins': dict(edges=[0, 20.0, 100.0], overflow=True), 'index': 0}
bins_nmuon = {'in': 'NMuon', 'out': 'nmuon'}
weight_list = ['EventWeight']
weight_dict = dict(weighted='EventWeight') |
mystr = 'TutorialsTeacher'
nums = [1,2,3,4,5,6,7,8,9,10]
portion1 = slice(9)
portion2 = slice(0, -2, None)
print('slice: ', portion1)
print('String value: ', mystr[portion1])
print('List value: ', nums[portion1])
print('slice: ', portion2)
print('String value: ', mystr[portion2])
print('List value: ', nums[portion2])
nums = [1,2,3,4,5,6,7,8,9,10]
odd_portion = slice(0, 10, 2)
print(nums[odd_portion])
even_portion = slice(1, 10, 2)
print(nums[even_portion]) | mystr = 'TutorialsTeacher'
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
portion1 = slice(9)
portion2 = slice(0, -2, None)
print('slice: ', portion1)
print('String value: ', mystr[portion1])
print('List value: ', nums[portion1])
print('slice: ', portion2)
print('String value: ', mystr[portion2])
print('List value: ', nums[portion2])
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
odd_portion = slice(0, 10, 2)
print(nums[odd_portion])
even_portion = slice(1, 10, 2)
print(nums[even_portion]) |
"""
@created_at 2017-08-12
@author Exequiel Fuentes Lettura <efulet@gmail.com>
"""
| """
@created_at 2017-08-12
@author Exequiel Fuentes Lettura <efulet@gmail.com>
""" |
inp = "inH.txt"
oup = "outH.txt"
spl = []
with open(inp, "r") as f:
spl = f.readlines()
with open(oup, "w") as f:
for s in spl:
text = "<tr>\n\t<td>\n"
text += "\t\t{0}\n".format(s[:4])
text += "\t</td>\n\t<td>\n"
text += "\t\t{0}\n".format(s[13:])
text += "\t</td>\n</tr>\n"
f.write(text)
"""
<tr>\n
\t<td>\n
\t\ttext\n
\t</td>\n
\t<td>\n
\t\ttext1\n
\t</td>\n
</tr>\n
""" | inp = 'inH.txt'
oup = 'outH.txt'
spl = []
with open(inp, 'r') as f:
spl = f.readlines()
with open(oup, 'w') as f:
for s in spl:
text = '<tr>\n\t<td>\n'
text += '\t\t{0}\n'.format(s[:4])
text += '\t</td>\n\t<td>\n'
text += '\t\t{0}\n'.format(s[13:])
text += '\t</td>\n</tr>\n'
f.write(text)
'\n<tr>\n\n \t<td>\n\n \t\ttext\n\n \t</td>\n\n \t<td>\n\n \t\ttext1\n\n \t</td>\n\n</tr>\n\n' |
class Guardian:
@staticmethod
def adjust_difficulty(original_difficulty: int, block_height: int):
return original_difficulty // 1000
# TODO: decide on the parameters for mainnet
# if block_height < 1000:
# return original_difficulty // 1000
# if block_height < 10000:
# return original_difficulty // 100
# if block_height < 100000:
# return original_difficulty // 10
# return original_difficulty
| class Guardian:
@staticmethod
def adjust_difficulty(original_difficulty: int, block_height: int):
return original_difficulty // 1000 |
class RepresentMixin:
def __repr__(self):
return repr(self.to_dict())
def to_dict(self):
return {f: getattr(self, f) for f in self.non_empty_fields}
| class Representmixin:
def __repr__(self):
return repr(self.to_dict())
def to_dict(self):
return {f: getattr(self, f) for f in self.non_empty_fields} |
class Profile:
def __init__(self, name, age, xp, time_on_calls):
self.__name = name
self.__age = age
self.__xp = xp
self.__time_on_calls = time_on_calls
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age
@property
def xp(self):
return self.__xp
@property
def level(self):
return self.__xp/1000
@property
def time_on_calls(self):
return self.__time_on_calls
| class Profile:
def __init__(self, name, age, xp, time_on_calls):
self.__name = name
self.__age = age
self.__xp = xp
self.__time_on_calls = time_on_calls
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age
@property
def xp(self):
return self.__xp
@property
def level(self):
return self.__xp / 1000
@property
def time_on_calls(self):
return self.__time_on_calls |
class Solution:
def memLeak(self, memory1: int, memory2: int):
count = 1
while count <= memory1 or count <= memory2:
if memory1 < memory2:
memory2 -= count
else:
memory1 -= count
count += 1
return [count, memory1, memory2]
if __name__ == '__main__':
s = Solution()
r = s.memLeak(8,10)
print(r) | class Solution:
def mem_leak(self, memory1: int, memory2: int):
count = 1
while count <= memory1 or count <= memory2:
if memory1 < memory2:
memory2 -= count
else:
memory1 -= count
count += 1
return [count, memory1, memory2]
if __name__ == '__main__':
s = solution()
r = s.memLeak(8, 10)
print(r) |
def main():
# input
N, M = map(int, input().split())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
# compute
numbers = [0] * (10**3+5)
for i in As:
numbers[i] += 1
for i in Bs:
numbers[i] += 1
anss = []
for i, figure in enumerate(numbers):
if figure == 1:
anss.append(i)
# output
print(*anss)
if __name__ == '__main__':
main()
| def main():
(n, m) = map(int, input().split())
as = list(map(int, input().split()))
bs = list(map(int, input().split()))
numbers = [0] * (10 ** 3 + 5)
for i in As:
numbers[i] += 1
for i in Bs:
numbers[i] += 1
anss = []
for (i, figure) in enumerate(numbers):
if figure == 1:
anss.append(i)
print(*anss)
if __name__ == '__main__':
main() |
# ELEVSTRS
for i in range(int(input())):
n,v1,v2=map(int,input().split())
time=[]
ele=2*n/v2
st=n*(2**(1/2))/v1
if(ele>st):print("Stairs")
else:print("Elevator") | for i in range(int(input())):
(n, v1, v2) = map(int, input().split())
time = []
ele = 2 * n / v2
st = n * 2 ** (1 / 2) / v1
if ele > st:
print('Stairs')
else:
print('Elevator') |
# The MIT License (MIT)
# Copyright (c) 2015 Brian Wray (brian@wrocket.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# This script generates the square/piece score tables. Basically, tables that
# describe the "goodness" of a particular piece being on a particular square.
def write_row(scores):
return '\t' + ', '.join([str(x).rjust(4) for x in scores]) + ','
def add_row_border(ordered_rows):
border = [0] * 12
side = [0] * 2
result = [border, border]
for r in ordered_rows:
result.append(side + r + side)
result.append(border)
result.append(border)
return result
def make_12x12(white_version_map, perspective='white'):
result = []
key_list = list(white_version_map.keys())
if perspective == 'black':
key_list = reversed(key_list)
for k in key_list:
result.append(white_version_map[k])
result = add_row_border(result)
return result
def write_array(name, whiteVersion):
white_name = 'SQ_SCORE_%s_WHITE' % name.upper()
black_name = 'SQ_SCORE_%s_BLACK' % name.upper()
lines = []
lines.append('const int %s[144] = {' % white_name)
for row in make_12x12(whiteVersion, perspective='white'):
lines.append(write_row(row))
lines.append('};')
lines.append('')
lines.append('const int %s[144] = {' % black_name)
for row in make_12x12(whiteVersion, perspective='black'):
lines.append(write_row(row))
lines.append('};')
print('\n'.join(lines))
white_pawn_opening_scores = {
8: [0, 0, 0, 0, 0, 0, 0, 0],
7: [0, 0, 0, 0, 0, 0, 0, 0],
6: [0, 0, 0, 0, 0, 0, 0, 0],
5: [0, 0, 0, 15, 15, 0, 0, 0],
4: [0, 0, 8, 15, 15, 8, 0, 0],
3: [0, 0, 10, 10, 10, 10, 0, 0],
2: [0, 0, -5, -5, -5, -5, 0, 0],
1: [0, 0, 0, 0, 0, 0, 0, 0]
}
write_array('PAWN_OPENING', white_pawn_opening_scores)
white_knight_opening_scores = {
8: [0, 0, 0, 0, 0, 0, 0, 0],
7: [0, 0, 0, 0, 0, 0, 0, 0],
6: [0, 0, 0, 0, 0, 0, 0, 0],
5: [0, 0, 0, 0, 0, 0, 0, 0],
4: [0, 0, 0, 0, 0, 0, 0, 0],
3: [-10, 0, 10, 0, 0, 10, 0, -10],
2: [-10, 0, 0, 5, 0, 5, 0, -10],
1: [-20, -5, 0, 0, 0, 0, -5, -20]
}
write_array('KNIGHT_OPENING', white_knight_opening_scores)
white_queen_opening_scores = {
8: [-10, -10, -10, -10, -10, -10, -10, -10],
7: [-10, -10, -10, -10, -10, -10, -10, -10],
6: [-10, -10, -10, -10, -10, -10, -10, -10],
5: [-10, -10, -10, -10, -10, -10, -10, -10],
4: [-10, -10, -10, -10, -10, -10, -10, -10],
3: [-10, -10, -10, -10, -10, -10, -10, -10],
2: [0, 0, 0, 0, 0, 0, 0, 0],
1: [0, 0, 0, 0, 0, 0, 0, 0],
}
write_array('QUEEN_OPENING', white_queen_opening_scores)
| def write_row(scores):
return '\t' + ', '.join([str(x).rjust(4) for x in scores]) + ','
def add_row_border(ordered_rows):
border = [0] * 12
side = [0] * 2
result = [border, border]
for r in ordered_rows:
result.append(side + r + side)
result.append(border)
result.append(border)
return result
def make_12x12(white_version_map, perspective='white'):
result = []
key_list = list(white_version_map.keys())
if perspective == 'black':
key_list = reversed(key_list)
for k in key_list:
result.append(white_version_map[k])
result = add_row_border(result)
return result
def write_array(name, whiteVersion):
white_name = 'SQ_SCORE_%s_WHITE' % name.upper()
black_name = 'SQ_SCORE_%s_BLACK' % name.upper()
lines = []
lines.append('const int %s[144] = {' % white_name)
for row in make_12x12(whiteVersion, perspective='white'):
lines.append(write_row(row))
lines.append('};')
lines.append('')
lines.append('const int %s[144] = {' % black_name)
for row in make_12x12(whiteVersion, perspective='black'):
lines.append(write_row(row))
lines.append('};')
print('\n'.join(lines))
white_pawn_opening_scores = {8: [0, 0, 0, 0, 0, 0, 0, 0], 7: [0, 0, 0, 0, 0, 0, 0, 0], 6: [0, 0, 0, 0, 0, 0, 0, 0], 5: [0, 0, 0, 15, 15, 0, 0, 0], 4: [0, 0, 8, 15, 15, 8, 0, 0], 3: [0, 0, 10, 10, 10, 10, 0, 0], 2: [0, 0, -5, -5, -5, -5, 0, 0], 1: [0, 0, 0, 0, 0, 0, 0, 0]}
write_array('PAWN_OPENING', white_pawn_opening_scores)
white_knight_opening_scores = {8: [0, 0, 0, 0, 0, 0, 0, 0], 7: [0, 0, 0, 0, 0, 0, 0, 0], 6: [0, 0, 0, 0, 0, 0, 0, 0], 5: [0, 0, 0, 0, 0, 0, 0, 0], 4: [0, 0, 0, 0, 0, 0, 0, 0], 3: [-10, 0, 10, 0, 0, 10, 0, -10], 2: [-10, 0, 0, 5, 0, 5, 0, -10], 1: [-20, -5, 0, 0, 0, 0, -5, -20]}
write_array('KNIGHT_OPENING', white_knight_opening_scores)
white_queen_opening_scores = {8: [-10, -10, -10, -10, -10, -10, -10, -10], 7: [-10, -10, -10, -10, -10, -10, -10, -10], 6: [-10, -10, -10, -10, -10, -10, -10, -10], 5: [-10, -10, -10, -10, -10, -10, -10, -10], 4: [-10, -10, -10, -10, -10, -10, -10, -10], 3: [-10, -10, -10, -10, -10, -10, -10, -10], 2: [0, 0, 0, 0, 0, 0, 0, 0], 1: [0, 0, 0, 0, 0, 0, 0, 0]}
write_array('QUEEN_OPENING', white_queen_opening_scores) |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
newHead = None
left_node = None
cur = head
if cur is not None:
next_node = cur.next
while cur is not None and next_node is not None:
if left_node is not None:
left_node.next = next_node
else:
newHead = next_node
cur.next = next_node.next
next_node.next = cur
left_node = cur
cur = cur.next
if cur is not None:
next_node = cur.next
if newHead is None and cur is not None:
newHead = cur
return newHead
def main():
s = Solution()
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
one.next = two
two.next = three
three.next = four
new_head = s.swapPairs(one)
cur_node = new_head
while cur_node is not None:
print(cur_node.val)
cur_node = cur_node.next
if __name__ == '__main__':
main()
| class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swap_pairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
new_head = None
left_node = None
cur = head
if cur is not None:
next_node = cur.next
while cur is not None and next_node is not None:
if left_node is not None:
left_node.next = next_node
else:
new_head = next_node
cur.next = next_node.next
next_node.next = cur
left_node = cur
cur = cur.next
if cur is not None:
next_node = cur.next
if newHead is None and cur is not None:
new_head = cur
return newHead
def main():
s = solution()
one = list_node(1)
two = list_node(2)
three = list_node(3)
four = list_node(4)
one.next = two
two.next = three
three.next = four
new_head = s.swapPairs(one)
cur_node = new_head
while cur_node is not None:
print(cur_node.val)
cur_node = cur_node.next
if __name__ == '__main__':
main() |
#
# PySNMP MIB module CISCO-DYNAMIC-PORT-VSAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DYNAMIC-PORT-VSAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:56:27 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")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint")
CpsmActivateResult, CpsmDiffDb, CpsmDbActivate, CpsmDiffReason = mibBuilder.importSymbols("CISCO-PSM-MIB", "CpsmActivateResult", "CpsmDiffDb", "CpsmDbActivate", "CpsmDiffReason")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
VsanIndex, FcNameIdOrZero, FcNameId = mibBuilder.importSymbols("CISCO-ST-TC", "VsanIndex", "FcNameIdOrZero", "FcNameId")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
TimeTicks, Counter32, Gauge32, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Unsigned32, iso, Counter64, ModuleIdentity, Bits, Integer32, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Counter32", "Gauge32", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Unsigned32", "iso", "Counter64", "ModuleIdentity", "Bits", "Integer32", "NotificationType")
RowStatus, TextualConvention, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "DisplayString", "TruthValue")
ciscoDpvmMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 421))
ciscoDpvmMIB.setRevisions(('2004-06-22 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoDpvmMIB.setRevisionsDescriptions(('Initial version of this MIB.',))
if mibBuilder.loadTexts: ciscoDpvmMIB.setLastUpdated('200406220000Z')
if mibBuilder.loadTexts: ciscoDpvmMIB.setOrganization('Cisco Systems Inc.')
if mibBuilder.loadTexts: ciscoDpvmMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-san@cisco.com')
if mibBuilder.loadTexts: ciscoDpvmMIB.setDescription('The MIB module for the management of the Dynamic Port Vsan Membership (DPVM) module. DPVM provides the ability to assign (virtual storage area network) VSAN IDs dynamically to switch ports based on the device logging in on the port. The logging-in device can be identified by its port World Wide Name (pWWN) and/or its node World Wide Name (nWWN).')
ciscoDpvmMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 0))
ciscoDpvmMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 1))
ciscoDpvmMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 2))
cdpvmConfiguration = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1))
class CdpvmDevType(TextualConvention, Integer32):
description = 'Represents the type of device. pwwn(1) - Represents the port WWN of the device. nwwn(2) - Represents the node WWN of the device.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("pwwn", 1), ("nwwn", 2))
cdpvmNextAvailIndex = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 16384))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmNextAvailIndex.setStatus('current')
if mibBuilder.loadTexts: cdpvmNextAvailIndex.setDescription('This object contains an appropriate value to be used for cdpvmIndex when creating entries in the cdpvmTable. The value 0 indicates that all entries are assigned. A management application should read this object, get the (non-zero) value and use same for creating an entry in the cdpvmTable. After each retrieval and use, the agent should modify the value to the next unassigned index. After a manager retrieves a value the agent will determine through its local policy when this index value will be made available for reuse. A suggested mechanism is to make an index available when the corresponding entry is deleted.')
cdpvmTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2), )
if mibBuilder.loadTexts: cdpvmTable.setStatus('current')
if mibBuilder.loadTexts: cdpvmTable.setDescription("This table contains the set of all valid bindings of devices to VSANs configured on the local device. A valid binding consists of a pWWN/nWWN bound to a VSAN. If a device is bound to a VSAN, then when that device logs in through a port on the local device, that port is assigned the configured VSAN. Such a VSAN is called a 'dynamic' VSAN. The set of valid bindings configured in this table should be activated by means of the cdpvmActivate object. When activated, these bindings are enforced and all subsequent logins will be subject to these bindings.")
cdpvmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmIndex"))
if mibBuilder.loadTexts: cdpvmEntry.setStatus('current')
if mibBuilder.loadTexts: cdpvmEntry.setDescription('An entry (conceptual row) in this table. Each entry contains the mapping between a device and its dynamic VSAN.')
cdpvmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16384)))
if mibBuilder.loadTexts: cdpvmIndex.setStatus('current')
if mibBuilder.loadTexts: cdpvmIndex.setDescription('Identifies a binding between a device and its dynamic VSAN.')
cdpvmLoginDevType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 2), CdpvmDevType().clone('pwwn')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cdpvmLoginDevType.setStatus('current')
if mibBuilder.loadTexts: cdpvmLoginDevType.setDescription('Specifies the type of the corresponding instance of cdpvmLoginDev object.')
cdpvmLoginDev = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 3), FcNameId()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cdpvmLoginDev.setStatus('current')
if mibBuilder.loadTexts: cdpvmLoginDev.setDescription("Represents the logging-in device. If the value of the corresponding instance of cdpvmLoginDevType is 'pwwn', then this object contains a pWWN. If the value of the corresponding instance of cdpvmLoginDevType is 'nwwn', then this object contains a nWWN. This object MUST be set to a valid value before or concurrently with setting the corresponding instance of cdpvmRowStatus to 'active'. The agent should not allow creation of 2 entries in this table with same values for cdpvmLoginDev and cdpvmLoginDevVsan.")
cdpvmLoginDevVsan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 4), VsanIndex().clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cdpvmLoginDevVsan.setStatus('current')
if mibBuilder.loadTexts: cdpvmLoginDevVsan.setDescription('Represents the VSAN to be associated to the port on the local device on which the device represented by cdpvmLoginDev logs in.')
cdpvmRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cdpvmRowStatus.setStatus('current')
if mibBuilder.loadTexts: cdpvmRowStatus.setDescription("The status of this conceptual row. Before setting this object to 'active', the cdpvmLoginDev object MUST be set to a valid value. Only cdpvmLoginDevVsan object can be modified when the value of this object is 'active'.")
cdpvmActivate = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 3), CpsmDbActivate()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmActivate.setStatus('current')
if mibBuilder.loadTexts: cdpvmActivate.setDescription("This object helps in activating the set of bindings in the cdpvmTable. Setting this object to 'activate(1)' will result in the valid bindings present in cdpvmTable being activated and copied to the cpdvmEnfTable. By default auto learn will be turned 'on' after activation. Before activation is attempted, it should be turned 'off'. Setting this object to 'forceActivate(3)', will result in forced activation, even if there are errors during activation and the activated bindings will be copied to the cdpvmEnfTable. Setting this object to 'deactivate(5)', will result in deactivation of currently activated valid bindings (if any). Currently active entries (if any), which would have been present in the cdpvmEnfTable, will be removed. Setting this object to 'activateWithAutoLearnOff(2)' and 'forceActivateWithAutoLearnOff(4)' is not allowed. Setting this object to 'noop(6)', results in no action. The value of this object when read is always 'noop(6)'. Activation will not be allowed if auto-learn is enabled.")
cdpvmActivateResult = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 4), CpsmActivateResult()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmActivateResult.setStatus('current')
if mibBuilder.loadTexts: cdpvmActivateResult.setDescription('This object indicates the outcome of the activation.')
cdpvmAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 5), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmAutoLearn.setStatus('current')
if mibBuilder.loadTexts: cdpvmAutoLearn.setDescription("This object helps to 'learn' the configuration of devices logged into the local device on all its ports and the VSANs to which they are associated. This information will be populated in the the enforced binding table (cdpvmEnfTable). This mechanism of 'learning' the configuration of devices and their VSAN association over a period of time and populating the configuration is a convenience mechanism for users. If this object is set to 'true(1)' all subsequent logins and their VSAN association will be populated in the enforced binding database, provided it is not in conflict with existing enforced bindings. When this object is set to 'false(2)', the mechanism of learning is stopped. The learned entries will however be in the enforced binding database.")
cdpvmCopyEnfToConfig = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("copy", 1), ("noop", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmCopyEnfToConfig.setStatus('current')
if mibBuilder.loadTexts: cdpvmCopyEnfToConfig.setDescription("This object when set to 'copy(1)', results in the active (enforced) binding database to be copied on to the configuration binding database. Note that the learned entries are also copied. No action is taken if this object is set to 'noop(2)'. The value of this object when read is always 'noop'.")
cdpvmEnfTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7), )
if mibBuilder.loadTexts: cdpvmEnfTable.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfTable.setDescription('This table contains information on all currently enforced bindings on the local device. The enforced set of bindings is the set of valid bindings copied from the configuration binding database (cdpvmTable) at the time they were activated. These entries cannot be modified. The learnt entries are also a part of this table. Entries can get into this table or be deleted from this table only by means of explicit activation/deactivation. Note that this table will be empty when no valid bindings have been activated.')
cdpvmEnfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1), ).setIndexNames((0, "CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmEnfIndex"))
if mibBuilder.loadTexts: cdpvmEnfEntry.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfEntry.setDescription('An entry (conceptual row) in this table.')
cdpvmEnfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16384)))
if mibBuilder.loadTexts: cdpvmEnfIndex.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfIndex.setDescription('The index of this entry.')
cdpvmEnfLoginDevType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 2), CdpvmDevType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmEnfLoginDevType.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfLoginDevType.setDescription('Specifies the type of the corresponding instance of cdpvmEnfLoginDev.')
cdpvmEnfLoginDev = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 3), FcNameId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmEnfLoginDev.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfLoginDev.setDescription('This object represents the logging in device address. This object was copied from the cdpvmLoginDev object in the cdpvmTable at the time when the currently active bindings were activated.')
cdpvmEnfLoginDevVsan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 4), VsanIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmEnfLoginDevVsan.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfLoginDevVsan.setDescription("This object represents the VSAN of the port on the local device thru' which the device represented by cdpvmEnfLoginDev logs in. This object was copied from the cdpvmLoginDevVsan object in the cdpvmTable at the time when the currently active bindings were activated")
cdpvmEnfIsLearnt = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 5), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmEnfIsLearnt.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfIsLearnt.setDescription("This object indicates if this is a learnt entry or not. If the value of this object is 'true', then it is a learnt entry. If the value of this object is 'false', then it is not.")
cdpvmDynPortsTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8), )
if mibBuilder.loadTexts: cdpvmDynPortsTable.setStatus('current')
if mibBuilder.loadTexts: cdpvmDynPortsTable.setDescription('This table contains the set of all ports that are operating with a dynamic VSAN on the local device.')
cdpvmDynPortsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: cdpvmDynPortsEntry.setStatus('current')
if mibBuilder.loadTexts: cdpvmDynPortsEntry.setDescription('An entry (conceptual row) in this table.')
cdpvmDynPortVsan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1, 1), VsanIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDynPortVsan.setStatus('current')
if mibBuilder.loadTexts: cdpvmDynPortVsan.setDescription("The 'dynamic' VSAN of this port on the local device.")
cdpvmDynPortDevPwwn = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1, 2), FcNameId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDynPortDevPwwn.setStatus('current')
if mibBuilder.loadTexts: cdpvmDynPortDevPwwn.setDescription('The pWWN of the device currently logged-in through this port on the local device.')
cdpvmDynPortDevNwwn = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1, 3), FcNameId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDynPortDevNwwn.setStatus('current')
if mibBuilder.loadTexts: cdpvmDynPortDevNwwn.setDescription("The nWWN of the device currently logged-in thru' this port on the local device.")
cdpvmDiffConfig = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 9), CpsmDiffDb()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmDiffConfig.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffConfig.setDescription("The config database represented by cdpvmTable and the enforced database represented by cdpvmEnfTable can be compared to list out the differences. This object specifies the reference database for the comparison. This object when set to 'configDb(1)', compares the configuration database (cdpvmTable) with respect to the enforced database (cdpvmEnfTable). So, the enforced database will be the reference database and the results of comparison operation will be with respect to the enforced database. This object when set to 'activeDb(2)', compares the enforced database with respect to the configuration database. So, the configured database will be the reference database and the results of comparison operation will be with respect to the configuration database. No action will be taken if this object is set to 'noop(3)'. The value of this object when read is always 'noop(3)'.")
cdpvmDiffTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10), )
if mibBuilder.loadTexts: cdpvmDiffTable.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffTable.setDescription('This table contains the result of the compare operation configured by means of the cdpvmDiffConfig object.')
cdpvmDiffEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1), ).setIndexNames((0, "CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffIndex"))
if mibBuilder.loadTexts: cdpvmDiffEntry.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffEntry.setDescription('An entry (conceptual row) in this table.')
cdpvmDiffIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16384)))
if mibBuilder.loadTexts: cdpvmDiffIndex.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffIndex.setDescription('The index of this entry.')
cdpvmDiffReason = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 2), CpsmDiffReason()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDiffReason.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffReason.setDescription('This object indicates the reason for the difference between the databases being compared, for this entry.')
cdpvmDiffLoginDevType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 3), CdpvmDevType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDiffLoginDevType.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffLoginDevType.setDescription('Specifies the type of the corresponding instance of cdpvmDiffLoginDev object.')
cdpvmDiffLoginDev = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 4), FcNameId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDiffLoginDev.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffLoginDev.setDescription('This object represents the logging-in device address. This object was copied from either the cdpvmLoginDev object in the cdpvmTable or from cdpvmEnfLoginDev object in the cdpvmEnfTable at the time when the comparison was done.')
cdpvmDiffLoginDevVsan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 5), VsanIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDiffLoginDevVsan.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffLoginDevVsan.setDescription("This object represents the VSAN of the port on the local device thru' which the device represented by the corresponding instance of cdpvmDiffLoginDev object, logged-in. It was copied from either the cdpvmLoginDevVsan object in the cdpvmTable or from cdpvmEnfLoginDevVsan object in the cdpvmEnfTable at the time when the comparison was done.")
cdpvmClearAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("clear", 1), ("clearOnWwn", 2), ("noop", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmClearAutoLearn.setStatus('current')
if mibBuilder.loadTexts: cdpvmClearAutoLearn.setDescription("This object assists in clearing the auto-learnt entries. Setting this object to 'clear(1)' will result in all auto-learnt entries being cleared. Setting this object to 'clearOnWwn(2)' will result in a particular entry represented by cdpvmClearAutoLearnWwn object being cleared. Before setting this object to 'clearOnWwn(2)', the cpdvmClearAutoLearnWwn object should be set to the pWWN that is to be cleared. Setting this object to 'noop(3)', will result in no action being taken. The value of this object when read is always 'noop'.")
cdpvmClearAutoLearnWwn = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 12), FcNameIdOrZero().clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmClearAutoLearnWwn.setStatus('current')
if mibBuilder.loadTexts: cdpvmClearAutoLearnWwn.setDescription('Represents the port WWN (pWWN) to be used for clearing its corresponding auto-learnt entry.')
cdpvmActivationState = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 13), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmActivationState.setStatus('current')
if mibBuilder.loadTexts: cdpvmActivationState.setDescription("This object indicates the state of activation. If the value of this object is 'true', then an activation has been attempted as the most recent operation. If the value of this object is 'false', then an activation has not been attempted as the most recent operation.")
ciscoDpvmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 1))
ciscoDpvmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2))
ciscoDpvmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 1, 1)).setObjects(("CISCO-DYNAMIC-PORT-VSAN-MIB", "ciscoDpvmConfigGroup"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "ciscoDpvmEnforcedGroup"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "ciscoDpvmAutoLearnGroup"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "ciscoDpvmDiffGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoDpvmMIBCompliance = ciscoDpvmMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: ciscoDpvmMIBCompliance.setDescription('The compliance statement for entities which implement the Dynamic Port VSAN Membership Manager.')
ciscoDpvmConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 1)).setObjects(("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmNextAvailIndex"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmLoginDevType"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmLoginDev"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmLoginDevVsan"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmRowStatus"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmActivate"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmActivateResult"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmCopyEnfToConfig"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDynPortVsan"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDynPortDevPwwn"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDynPortDevNwwn"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmActivationState"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoDpvmConfigGroup = ciscoDpvmConfigGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoDpvmConfigGroup.setDescription('A set of objects for configuration of DPVM bindings.')
ciscoDpvmEnforcedGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 2)).setObjects(("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmEnfLoginDevType"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmEnfLoginDev"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmEnfLoginDevVsan"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmEnfIsLearnt"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoDpvmEnforcedGroup = ciscoDpvmEnforcedGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoDpvmEnforcedGroup.setDescription('A set of objects for displaying enforced DPVM bindings.')
ciscoDpvmAutoLearnGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 3)).setObjects(("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmAutoLearn"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmClearAutoLearn"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmClearAutoLearnWwn"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoDpvmAutoLearnGroup = ciscoDpvmAutoLearnGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoDpvmAutoLearnGroup.setDescription('A set of object(s) for configuring auto-learn of DPVM bindings.')
ciscoDpvmDiffGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 4)).setObjects(("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffConfig"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffReason"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffLoginDevType"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffLoginDev"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffLoginDevVsan"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoDpvmDiffGroup = ciscoDpvmDiffGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoDpvmDiffGroup.setDescription('A set of objects for configuring and displaying database compare operations.')
mibBuilder.exportSymbols("CISCO-DYNAMIC-PORT-VSAN-MIB", cdpvmDynPortDevPwwn=cdpvmDynPortDevPwwn, cdpvmTable=cdpvmTable, ciscoDpvmMIBCompliance=ciscoDpvmMIBCompliance, cdpvmNextAvailIndex=cdpvmNextAvailIndex, cdpvmDynPortsTable=cdpvmDynPortsTable, cdpvmDiffTable=cdpvmDiffTable, ciscoDpvmMIBObjects=ciscoDpvmMIBObjects, cdpvmDiffLoginDev=cdpvmDiffLoginDev, cdpvmLoginDev=cdpvmLoginDev, ciscoDpvmMIBCompliances=ciscoDpvmMIBCompliances, cdpvmDynPortDevNwwn=cdpvmDynPortDevNwwn, cdpvmLoginDevType=cdpvmLoginDevType, cdpvmDiffIndex=cdpvmDiffIndex, cdpvmDiffConfig=cdpvmDiffConfig, ciscoDpvmMIBNotifs=ciscoDpvmMIBNotifs, cdpvmCopyEnfToConfig=cdpvmCopyEnfToConfig, cdpvmActivate=cdpvmActivate, cdpvmActivateResult=cdpvmActivateResult, PYSNMP_MODULE_ID=ciscoDpvmMIB, cdpvmDiffLoginDevType=cdpvmDiffLoginDevType, cdpvmEntry=cdpvmEntry, cdpvmClearAutoLearnWwn=cdpvmClearAutoLearnWwn, cdpvmLoginDevVsan=cdpvmLoginDevVsan, cdpvmEnfEntry=cdpvmEnfEntry, ciscoDpvmMIB=ciscoDpvmMIB, cdpvmEnfLoginDevType=cdpvmEnfLoginDevType, cdpvmAutoLearn=cdpvmAutoLearn, cdpvmEnfLoginDevVsan=cdpvmEnfLoginDevVsan, ciscoDpvmDiffGroup=ciscoDpvmDiffGroup, cdpvmRowStatus=cdpvmRowStatus, cdpvmDiffEntry=cdpvmDiffEntry, cdpvmEnfIsLearnt=cdpvmEnfIsLearnt, ciscoDpvmMIBConform=ciscoDpvmMIBConform, cdpvmDynPortsEntry=cdpvmDynPortsEntry, cdpvmEnfLoginDev=cdpvmEnfLoginDev, cdpvmClearAutoLearn=cdpvmClearAutoLearn, ciscoDpvmEnforcedGroup=ciscoDpvmEnforcedGroup, ciscoDpvmMIBGroups=ciscoDpvmMIBGroups, cdpvmDiffReason=cdpvmDiffReason, cdpvmEnfIndex=cdpvmEnfIndex, cdpvmDiffLoginDevVsan=cdpvmDiffLoginDevVsan, ciscoDpvmAutoLearnGroup=ciscoDpvmAutoLearnGroup, cdpvmConfiguration=cdpvmConfiguration, ciscoDpvmConfigGroup=ciscoDpvmConfigGroup, cdpvmDynPortVsan=cdpvmDynPortVsan, CdpvmDevType=CdpvmDevType, cdpvmActivationState=cdpvmActivationState, cdpvmEnfTable=cdpvmEnfTable, cdpvmIndex=cdpvmIndex)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint')
(cpsm_activate_result, cpsm_diff_db, cpsm_db_activate, cpsm_diff_reason) = mibBuilder.importSymbols('CISCO-PSM-MIB', 'CpsmActivateResult', 'CpsmDiffDb', 'CpsmDbActivate', 'CpsmDiffReason')
(cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt')
(vsan_index, fc_name_id_or_zero, fc_name_id) = mibBuilder.importSymbols('CISCO-ST-TC', 'VsanIndex', 'FcNameIdOrZero', 'FcNameId')
(if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex')
(notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup')
(time_ticks, counter32, gauge32, mib_identifier, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, unsigned32, iso, counter64, module_identity, bits, integer32, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'Counter32', 'Gauge32', 'MibIdentifier', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Unsigned32', 'iso', 'Counter64', 'ModuleIdentity', 'Bits', 'Integer32', 'NotificationType')
(row_status, textual_convention, display_string, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'TextualConvention', 'DisplayString', 'TruthValue')
cisco_dpvm_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 421))
ciscoDpvmMIB.setRevisions(('2004-06-22 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
ciscoDpvmMIB.setRevisionsDescriptions(('Initial version of this MIB.',))
if mibBuilder.loadTexts:
ciscoDpvmMIB.setLastUpdated('200406220000Z')
if mibBuilder.loadTexts:
ciscoDpvmMIB.setOrganization('Cisco Systems Inc.')
if mibBuilder.loadTexts:
ciscoDpvmMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-san@cisco.com')
if mibBuilder.loadTexts:
ciscoDpvmMIB.setDescription('The MIB module for the management of the Dynamic Port Vsan Membership (DPVM) module. DPVM provides the ability to assign (virtual storage area network) VSAN IDs dynamically to switch ports based on the device logging in on the port. The logging-in device can be identified by its port World Wide Name (pWWN) and/or its node World Wide Name (nWWN).')
cisco_dpvm_mib_notifs = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 0))
cisco_dpvm_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 1))
cisco_dpvm_mib_conform = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 2))
cdpvm_configuration = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1))
class Cdpvmdevtype(TextualConvention, Integer32):
description = 'Represents the type of device. pwwn(1) - Represents the port WWN of the device. nwwn(2) - Represents the node WWN of the device.'
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2))
named_values = named_values(('pwwn', 1), ('nwwn', 2))
cdpvm_next_avail_index = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 16384))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmNextAvailIndex.setStatus('current')
if mibBuilder.loadTexts:
cdpvmNextAvailIndex.setDescription('This object contains an appropriate value to be used for cdpvmIndex when creating entries in the cdpvmTable. The value 0 indicates that all entries are assigned. A management application should read this object, get the (non-zero) value and use same for creating an entry in the cdpvmTable. After each retrieval and use, the agent should modify the value to the next unassigned index. After a manager retrieves a value the agent will determine through its local policy when this index value will be made available for reuse. A suggested mechanism is to make an index available when the corresponding entry is deleted.')
cdpvm_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2))
if mibBuilder.loadTexts:
cdpvmTable.setStatus('current')
if mibBuilder.loadTexts:
cdpvmTable.setDescription("This table contains the set of all valid bindings of devices to VSANs configured on the local device. A valid binding consists of a pWWN/nWWN bound to a VSAN. If a device is bound to a VSAN, then when that device logs in through a port on the local device, that port is assigned the configured VSAN. Such a VSAN is called a 'dynamic' VSAN. The set of valid bindings configured in this table should be activated by means of the cdpvmActivate object. When activated, these bindings are enforced and all subsequent logins will be subject to these bindings.")
cdpvm_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1)).setIndexNames((0, 'CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmIndex'))
if mibBuilder.loadTexts:
cdpvmEntry.setStatus('current')
if mibBuilder.loadTexts:
cdpvmEntry.setDescription('An entry (conceptual row) in this table. Each entry contains the mapping between a device and its dynamic VSAN.')
cdpvm_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16384)))
if mibBuilder.loadTexts:
cdpvmIndex.setStatus('current')
if mibBuilder.loadTexts:
cdpvmIndex.setDescription('Identifies a binding between a device and its dynamic VSAN.')
cdpvm_login_dev_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 2), cdpvm_dev_type().clone('pwwn')).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cdpvmLoginDevType.setStatus('current')
if mibBuilder.loadTexts:
cdpvmLoginDevType.setDescription('Specifies the type of the corresponding instance of cdpvmLoginDev object.')
cdpvm_login_dev = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 3), fc_name_id()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cdpvmLoginDev.setStatus('current')
if mibBuilder.loadTexts:
cdpvmLoginDev.setDescription("Represents the logging-in device. If the value of the corresponding instance of cdpvmLoginDevType is 'pwwn', then this object contains a pWWN. If the value of the corresponding instance of cdpvmLoginDevType is 'nwwn', then this object contains a nWWN. This object MUST be set to a valid value before or concurrently with setting the corresponding instance of cdpvmRowStatus to 'active'. The agent should not allow creation of 2 entries in this table with same values for cdpvmLoginDev and cdpvmLoginDevVsan.")
cdpvm_login_dev_vsan = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 4), vsan_index().clone(1)).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cdpvmLoginDevVsan.setStatus('current')
if mibBuilder.loadTexts:
cdpvmLoginDevVsan.setDescription('Represents the VSAN to be associated to the port on the local device on which the device represented by cdpvmLoginDev logs in.')
cdpvm_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 5), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
cdpvmRowStatus.setStatus('current')
if mibBuilder.loadTexts:
cdpvmRowStatus.setDescription("The status of this conceptual row. Before setting this object to 'active', the cdpvmLoginDev object MUST be set to a valid value. Only cdpvmLoginDevVsan object can be modified when the value of this object is 'active'.")
cdpvm_activate = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 3), cpsm_db_activate()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cdpvmActivate.setStatus('current')
if mibBuilder.loadTexts:
cdpvmActivate.setDescription("This object helps in activating the set of bindings in the cdpvmTable. Setting this object to 'activate(1)' will result in the valid bindings present in cdpvmTable being activated and copied to the cpdvmEnfTable. By default auto learn will be turned 'on' after activation. Before activation is attempted, it should be turned 'off'. Setting this object to 'forceActivate(3)', will result in forced activation, even if there are errors during activation and the activated bindings will be copied to the cdpvmEnfTable. Setting this object to 'deactivate(5)', will result in deactivation of currently activated valid bindings (if any). Currently active entries (if any), which would have been present in the cdpvmEnfTable, will be removed. Setting this object to 'activateWithAutoLearnOff(2)' and 'forceActivateWithAutoLearnOff(4)' is not allowed. Setting this object to 'noop(6)', results in no action. The value of this object when read is always 'noop(6)'. Activation will not be allowed if auto-learn is enabled.")
cdpvm_activate_result = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 4), cpsm_activate_result()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmActivateResult.setStatus('current')
if mibBuilder.loadTexts:
cdpvmActivateResult.setDescription('This object indicates the outcome of the activation.')
cdpvm_auto_learn = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 5), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cdpvmAutoLearn.setStatus('current')
if mibBuilder.loadTexts:
cdpvmAutoLearn.setDescription("This object helps to 'learn' the configuration of devices logged into the local device on all its ports and the VSANs to which they are associated. This information will be populated in the the enforced binding table (cdpvmEnfTable). This mechanism of 'learning' the configuration of devices and their VSAN association over a period of time and populating the configuration is a convenience mechanism for users. If this object is set to 'true(1)' all subsequent logins and their VSAN association will be populated in the enforced binding database, provided it is not in conflict with existing enforced bindings. When this object is set to 'false(2)', the mechanism of learning is stopped. The learned entries will however be in the enforced binding database.")
cdpvm_copy_enf_to_config = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('copy', 1), ('noop', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cdpvmCopyEnfToConfig.setStatus('current')
if mibBuilder.loadTexts:
cdpvmCopyEnfToConfig.setDescription("This object when set to 'copy(1)', results in the active (enforced) binding database to be copied on to the configuration binding database. Note that the learned entries are also copied. No action is taken if this object is set to 'noop(2)'. The value of this object when read is always 'noop'.")
cdpvm_enf_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7))
if mibBuilder.loadTexts:
cdpvmEnfTable.setStatus('current')
if mibBuilder.loadTexts:
cdpvmEnfTable.setDescription('This table contains information on all currently enforced bindings on the local device. The enforced set of bindings is the set of valid bindings copied from the configuration binding database (cdpvmTable) at the time they were activated. These entries cannot be modified. The learnt entries are also a part of this table. Entries can get into this table or be deleted from this table only by means of explicit activation/deactivation. Note that this table will be empty when no valid bindings have been activated.')
cdpvm_enf_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1)).setIndexNames((0, 'CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmEnfIndex'))
if mibBuilder.loadTexts:
cdpvmEnfEntry.setStatus('current')
if mibBuilder.loadTexts:
cdpvmEnfEntry.setDescription('An entry (conceptual row) in this table.')
cdpvm_enf_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16384)))
if mibBuilder.loadTexts:
cdpvmEnfIndex.setStatus('current')
if mibBuilder.loadTexts:
cdpvmEnfIndex.setDescription('The index of this entry.')
cdpvm_enf_login_dev_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 2), cdpvm_dev_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmEnfLoginDevType.setStatus('current')
if mibBuilder.loadTexts:
cdpvmEnfLoginDevType.setDescription('Specifies the type of the corresponding instance of cdpvmEnfLoginDev.')
cdpvm_enf_login_dev = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 3), fc_name_id()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmEnfLoginDev.setStatus('current')
if mibBuilder.loadTexts:
cdpvmEnfLoginDev.setDescription('This object represents the logging in device address. This object was copied from the cdpvmLoginDev object in the cdpvmTable at the time when the currently active bindings were activated.')
cdpvm_enf_login_dev_vsan = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 4), vsan_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmEnfLoginDevVsan.setStatus('current')
if mibBuilder.loadTexts:
cdpvmEnfLoginDevVsan.setDescription("This object represents the VSAN of the port on the local device thru' which the device represented by cdpvmEnfLoginDev logs in. This object was copied from the cdpvmLoginDevVsan object in the cdpvmTable at the time when the currently active bindings were activated")
cdpvm_enf_is_learnt = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 5), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmEnfIsLearnt.setStatus('current')
if mibBuilder.loadTexts:
cdpvmEnfIsLearnt.setDescription("This object indicates if this is a learnt entry or not. If the value of this object is 'true', then it is a learnt entry. If the value of this object is 'false', then it is not.")
cdpvm_dyn_ports_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8))
if mibBuilder.loadTexts:
cdpvmDynPortsTable.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDynPortsTable.setDescription('This table contains the set of all ports that are operating with a dynamic VSAN on the local device.')
cdpvm_dyn_ports_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'))
if mibBuilder.loadTexts:
cdpvmDynPortsEntry.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDynPortsEntry.setDescription('An entry (conceptual row) in this table.')
cdpvm_dyn_port_vsan = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1, 1), vsan_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmDynPortVsan.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDynPortVsan.setDescription("The 'dynamic' VSAN of this port on the local device.")
cdpvm_dyn_port_dev_pwwn = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1, 2), fc_name_id()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmDynPortDevPwwn.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDynPortDevPwwn.setDescription('The pWWN of the device currently logged-in through this port on the local device.')
cdpvm_dyn_port_dev_nwwn = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1, 3), fc_name_id()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmDynPortDevNwwn.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDynPortDevNwwn.setDescription("The nWWN of the device currently logged-in thru' this port on the local device.")
cdpvm_diff_config = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 9), cpsm_diff_db()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cdpvmDiffConfig.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDiffConfig.setDescription("The config database represented by cdpvmTable and the enforced database represented by cdpvmEnfTable can be compared to list out the differences. This object specifies the reference database for the comparison. This object when set to 'configDb(1)', compares the configuration database (cdpvmTable) with respect to the enforced database (cdpvmEnfTable). So, the enforced database will be the reference database and the results of comparison operation will be with respect to the enforced database. This object when set to 'activeDb(2)', compares the enforced database with respect to the configuration database. So, the configured database will be the reference database and the results of comparison operation will be with respect to the configuration database. No action will be taken if this object is set to 'noop(3)'. The value of this object when read is always 'noop(3)'.")
cdpvm_diff_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10))
if mibBuilder.loadTexts:
cdpvmDiffTable.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDiffTable.setDescription('This table contains the result of the compare operation configured by means of the cdpvmDiffConfig object.')
cdpvm_diff_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1)).setIndexNames((0, 'CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmDiffIndex'))
if mibBuilder.loadTexts:
cdpvmDiffEntry.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDiffEntry.setDescription('An entry (conceptual row) in this table.')
cdpvm_diff_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16384)))
if mibBuilder.loadTexts:
cdpvmDiffIndex.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDiffIndex.setDescription('The index of this entry.')
cdpvm_diff_reason = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 2), cpsm_diff_reason()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmDiffReason.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDiffReason.setDescription('This object indicates the reason for the difference between the databases being compared, for this entry.')
cdpvm_diff_login_dev_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 3), cdpvm_dev_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmDiffLoginDevType.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDiffLoginDevType.setDescription('Specifies the type of the corresponding instance of cdpvmDiffLoginDev object.')
cdpvm_diff_login_dev = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 4), fc_name_id()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmDiffLoginDev.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDiffLoginDev.setDescription('This object represents the logging-in device address. This object was copied from either the cdpvmLoginDev object in the cdpvmTable or from cdpvmEnfLoginDev object in the cdpvmEnfTable at the time when the comparison was done.')
cdpvm_diff_login_dev_vsan = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 5), vsan_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmDiffLoginDevVsan.setStatus('current')
if mibBuilder.loadTexts:
cdpvmDiffLoginDevVsan.setDescription("This object represents the VSAN of the port on the local device thru' which the device represented by the corresponding instance of cdpvmDiffLoginDev object, logged-in. It was copied from either the cdpvmLoginDevVsan object in the cdpvmTable or from cdpvmEnfLoginDevVsan object in the cdpvmEnfTable at the time when the comparison was done.")
cdpvm_clear_auto_learn = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('clear', 1), ('clearOnWwn', 2), ('noop', 3)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cdpvmClearAutoLearn.setStatus('current')
if mibBuilder.loadTexts:
cdpvmClearAutoLearn.setDescription("This object assists in clearing the auto-learnt entries. Setting this object to 'clear(1)' will result in all auto-learnt entries being cleared. Setting this object to 'clearOnWwn(2)' will result in a particular entry represented by cdpvmClearAutoLearnWwn object being cleared. Before setting this object to 'clearOnWwn(2)', the cpdvmClearAutoLearnWwn object should be set to the pWWN that is to be cleared. Setting this object to 'noop(3)', will result in no action being taken. The value of this object when read is always 'noop'.")
cdpvm_clear_auto_learn_wwn = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 12), fc_name_id_or_zero().clone(hexValue='')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
cdpvmClearAutoLearnWwn.setStatus('current')
if mibBuilder.loadTexts:
cdpvmClearAutoLearnWwn.setDescription('Represents the port WWN (pWWN) to be used for clearing its corresponding auto-learnt entry.')
cdpvm_activation_state = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 13), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cdpvmActivationState.setStatus('current')
if mibBuilder.loadTexts:
cdpvmActivationState.setDescription("This object indicates the state of activation. If the value of this object is 'true', then an activation has been attempted as the most recent operation. If the value of this object is 'false', then an activation has not been attempted as the most recent operation.")
cisco_dpvm_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 1))
cisco_dpvm_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2))
cisco_dpvm_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 1, 1)).setObjects(('CISCO-DYNAMIC-PORT-VSAN-MIB', 'ciscoDpvmConfigGroup'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'ciscoDpvmEnforcedGroup'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'ciscoDpvmAutoLearnGroup'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'ciscoDpvmDiffGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_dpvm_mib_compliance = ciscoDpvmMIBCompliance.setStatus('current')
if mibBuilder.loadTexts:
ciscoDpvmMIBCompliance.setDescription('The compliance statement for entities which implement the Dynamic Port VSAN Membership Manager.')
cisco_dpvm_config_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 1)).setObjects(('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmNextAvailIndex'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmLoginDevType'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmLoginDev'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmLoginDevVsan'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmRowStatus'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmActivate'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmActivateResult'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmCopyEnfToConfig'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmDynPortVsan'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmDynPortDevPwwn'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmDynPortDevNwwn'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmActivationState'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_dpvm_config_group = ciscoDpvmConfigGroup.setStatus('current')
if mibBuilder.loadTexts:
ciscoDpvmConfigGroup.setDescription('A set of objects for configuration of DPVM bindings.')
cisco_dpvm_enforced_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 2)).setObjects(('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmEnfLoginDevType'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmEnfLoginDev'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmEnfLoginDevVsan'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmEnfIsLearnt'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_dpvm_enforced_group = ciscoDpvmEnforcedGroup.setStatus('current')
if mibBuilder.loadTexts:
ciscoDpvmEnforcedGroup.setDescription('A set of objects for displaying enforced DPVM bindings.')
cisco_dpvm_auto_learn_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 3)).setObjects(('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmAutoLearn'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmClearAutoLearn'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmClearAutoLearnWwn'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_dpvm_auto_learn_group = ciscoDpvmAutoLearnGroup.setStatus('current')
if mibBuilder.loadTexts:
ciscoDpvmAutoLearnGroup.setDescription('A set of object(s) for configuring auto-learn of DPVM bindings.')
cisco_dpvm_diff_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 4)).setObjects(('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmDiffConfig'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmDiffReason'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmDiffLoginDevType'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmDiffLoginDev'), ('CISCO-DYNAMIC-PORT-VSAN-MIB', 'cdpvmDiffLoginDevVsan'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
cisco_dpvm_diff_group = ciscoDpvmDiffGroup.setStatus('current')
if mibBuilder.loadTexts:
ciscoDpvmDiffGroup.setDescription('A set of objects for configuring and displaying database compare operations.')
mibBuilder.exportSymbols('CISCO-DYNAMIC-PORT-VSAN-MIB', cdpvmDynPortDevPwwn=cdpvmDynPortDevPwwn, cdpvmTable=cdpvmTable, ciscoDpvmMIBCompliance=ciscoDpvmMIBCompliance, cdpvmNextAvailIndex=cdpvmNextAvailIndex, cdpvmDynPortsTable=cdpvmDynPortsTable, cdpvmDiffTable=cdpvmDiffTable, ciscoDpvmMIBObjects=ciscoDpvmMIBObjects, cdpvmDiffLoginDev=cdpvmDiffLoginDev, cdpvmLoginDev=cdpvmLoginDev, ciscoDpvmMIBCompliances=ciscoDpvmMIBCompliances, cdpvmDynPortDevNwwn=cdpvmDynPortDevNwwn, cdpvmLoginDevType=cdpvmLoginDevType, cdpvmDiffIndex=cdpvmDiffIndex, cdpvmDiffConfig=cdpvmDiffConfig, ciscoDpvmMIBNotifs=ciscoDpvmMIBNotifs, cdpvmCopyEnfToConfig=cdpvmCopyEnfToConfig, cdpvmActivate=cdpvmActivate, cdpvmActivateResult=cdpvmActivateResult, PYSNMP_MODULE_ID=ciscoDpvmMIB, cdpvmDiffLoginDevType=cdpvmDiffLoginDevType, cdpvmEntry=cdpvmEntry, cdpvmClearAutoLearnWwn=cdpvmClearAutoLearnWwn, cdpvmLoginDevVsan=cdpvmLoginDevVsan, cdpvmEnfEntry=cdpvmEnfEntry, ciscoDpvmMIB=ciscoDpvmMIB, cdpvmEnfLoginDevType=cdpvmEnfLoginDevType, cdpvmAutoLearn=cdpvmAutoLearn, cdpvmEnfLoginDevVsan=cdpvmEnfLoginDevVsan, ciscoDpvmDiffGroup=ciscoDpvmDiffGroup, cdpvmRowStatus=cdpvmRowStatus, cdpvmDiffEntry=cdpvmDiffEntry, cdpvmEnfIsLearnt=cdpvmEnfIsLearnt, ciscoDpvmMIBConform=ciscoDpvmMIBConform, cdpvmDynPortsEntry=cdpvmDynPortsEntry, cdpvmEnfLoginDev=cdpvmEnfLoginDev, cdpvmClearAutoLearn=cdpvmClearAutoLearn, ciscoDpvmEnforcedGroup=ciscoDpvmEnforcedGroup, ciscoDpvmMIBGroups=ciscoDpvmMIBGroups, cdpvmDiffReason=cdpvmDiffReason, cdpvmEnfIndex=cdpvmEnfIndex, cdpvmDiffLoginDevVsan=cdpvmDiffLoginDevVsan, ciscoDpvmAutoLearnGroup=ciscoDpvmAutoLearnGroup, cdpvmConfiguration=cdpvmConfiguration, ciscoDpvmConfigGroup=ciscoDpvmConfigGroup, cdpvmDynPortVsan=cdpvmDynPortVsan, CdpvmDevType=CdpvmDevType, cdpvmActivationState=cdpvmActivationState, cdpvmEnfTable=cdpvmEnfTable, cdpvmIndex=cdpvmIndex) |
# Title : Print alphabets from mix string
# Author : Kiran Raj R.
# Date : 04:11:2020
string_to_filter = "he712047070l13212l213*(&(ow76968o172830r%*&$d"
def check_alpha(c):
if c.isalpha():
return c
def check_num(c):
if c.isnumeric():
return c
out = "".join(list(filter(check_alpha, string_to_filter)))
print(out)
out = "".join(list(filter(check_num, string_to_filter)))
print(out) | string_to_filter = 'he712047070l13212l213*(&(ow76968o172830r%*&$d'
def check_alpha(c):
if c.isalpha():
return c
def check_num(c):
if c.isnumeric():
return c
out = ''.join(list(filter(check_alpha, string_to_filter)))
print(out)
out = ''.join(list(filter(check_num, string_to_filter)))
print(out) |
# Create Allergy check code
# [ ] get input for input_test variable
input_test = input("What have you eaten in the last 24hrs: ")
# [ ] print "True" message if "dairy" is in the input or False message if not
print("Your food intake of",input_test,'contains "dairy" =',"dairy".lower() in input_test.lower())
#test works
# [ ] print True message if "nuts" is in the input or False if not
print("Your food intake of",input_test,'contains "Nuts" =',"Nuts".lower() in input_test.lower())
# [ ] Challenge: Check if "seafood" is in the input - print message
print("Your food intake of",input_test,'contains "seafood" =',"seafood".lower() in input_test.lower())
# [ ] Challenge: Check if "chocolate" is in the input - print message
print("Your food intake of",input_test,'contains "chocolate" =',"chocolate".lower() in input_test.lower()) | input_test = input('What have you eaten in the last 24hrs: ')
print('Your food intake of', input_test, 'contains "dairy" =', 'dairy'.lower() in input_test.lower())
print('Your food intake of', input_test, 'contains "Nuts" =', 'Nuts'.lower() in input_test.lower())
print('Your food intake of', input_test, 'contains "seafood" =', 'seafood'.lower() in input_test.lower())
print('Your food intake of', input_test, 'contains "chocolate" =', 'chocolate'.lower() in input_test.lower()) |
def largestComponent(G):
V, E = G;
vertexDeletedIndex = 0;
largestComponent = 0;
component = 0;
colour = [];
for i in range(len(V)):
Vcopy = V;
del Vcopy[i];
for v in V:
colour[v] = "white";
for v in Vcopy:
if colour[v] == "white":
component = DFS(G, v);
if(component > largestComponent):
largestComponent = component;
vertexDeletedIndex = v;
return vertexDeletedIndex, largestComponent;
def DFS(G, v):
pass;
| def largest_component(G):
(v, e) = G
vertex_deleted_index = 0
largest_component = 0
component = 0
colour = []
for i in range(len(V)):
vcopy = V
del Vcopy[i]
for v in V:
colour[v] = 'white'
for v in Vcopy:
if colour[v] == 'white':
component = dfs(G, v)
if component > largestComponent:
largest_component = component
vertex_deleted_index = v
return (vertexDeletedIndex, largestComponent)
def dfs(G, v):
pass |
n = int(input())
s = sum(list(map(int, input().split())))
c = 0
for i in range(1, 6):
if (s+i)%(n+1)!=1:
c += 1
print(c)
| n = int(input())
s = sum(list(map(int, input().split())))
c = 0
for i in range(1, 6):
if (s + i) % (n + 1) != 1:
c += 1
print(c) |
names = ['Christopher', 'Susan']
print(len(names)) # Get the number of items
names.insert(0, 'Bill') # Insert before index
print(names)
| names = ['Christopher', 'Susan']
print(len(names))
names.insert(0, 'Bill')
print(names) |
numBottles=int(input('pleas enter the number of full buttles: '))
numExchange=int(input('pleas enter number of empty bottels to exchange with full bottels: '))
fullbottels=numBottles
result=0
while numBottles>=numExchange or fullbottels>0:
result+=fullbottels
fullbottels=numBottles//numExchange
numBottles%=numExchange
numBottles+=fullbottels
print(result) | num_bottles = int(input('pleas enter the number of full buttles: '))
num_exchange = int(input('pleas enter number of empty bottels to exchange with full bottels: '))
fullbottels = numBottles
result = 0
while numBottles >= numExchange or fullbottels > 0:
result += fullbottels
fullbottels = numBottles // numExchange
num_bottles %= numExchange
num_bottles += fullbottels
print(result) |
detection_data_path = os.path.join('datasets', 'detection')
# training dataset
detection_train_set = DetectionDataset(detection_data_path, mode='train', transforms=get_transform(True))
# validation dataset
detection_valid_set = DetectionDataset(detection_data_path, mode='valid', transforms=get_transform(True))
#testing dataset
detection_test_set = DetectionDataset(detection_data_path, mode='test', transforms=get_transform(False))
detection_classes = detection_train_set.classes
num_detection_classes = len(detection_classes) | detection_data_path = os.path.join('datasets', 'detection')
detection_train_set = detection_dataset(detection_data_path, mode='train', transforms=get_transform(True))
detection_valid_set = detection_dataset(detection_data_path, mode='valid', transforms=get_transform(True))
detection_test_set = detection_dataset(detection_data_path, mode='test', transforms=get_transform(False))
detection_classes = detection_train_set.classes
num_detection_classes = len(detection_classes) |
#######################################
# Accessing Attributes
#######################################
class Employee:
"""Common base class for all employees"""
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
# del emp1.age # Delete 'age' attribute.
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(emp1, 'age') # Delete attribute 'age'
#######################################
# Built-In Class Attributes
#######################################
class Employee:
"""Common base class for all employees"""
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)
print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)
#######################################
# Destroying Objects (Garbage Collection)
#######################################
a = 40 # Create object <40>
b = a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
# class can implement the special method __del__(), called a destructor
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print(class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3)) # prints the ids of the obejcts
del pt1
del pt2
del pt3
#######################################
# Class Inheritance
#######################################
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print("Calling parent constructor")
def parentMethod(self):
print('Calling parent method')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print("Parent attribute :", Parent.parentAttr)
class Child(Parent): # define child class
def __init__(self):
print("Calling child constructor")
def childMethod(self):
print('Calling child method')
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
# Multiple inheritance
class A: # define your class A
"""....."""
class B: # define your class B
"""....."""
class C(A, B): # subclass of A and B
"""....."""
| class Employee:
"""Common base class for all employees"""
emp_count = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def display_count(self):
print('Total Employee %d' % Employee.empCount)
def display_employee(self):
print('Name : ', self.name, ', Salary: ', self.salary)
'This would create first object of Employee class'
emp1 = employee('Zara', 2000)
'This would create second object of Employee class'
emp2 = employee('Manni', 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print('Total Employee %d' % Employee.empCount)
emp1.age = 7
emp1.age = 8
hasattr(emp1, 'age')
getattr(emp1, 'age')
setattr(emp1, 'age', 8)
delattr(emp1, 'age')
class Employee:
"""Common base class for all employees"""
emp_count = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def display_count(self):
print('Total Employee %d' % Employee.empCount)
def display_employee(self):
print('Name : ', self.name, ', Salary: ', self.salary)
print('Employee.__doc__:', Employee.__doc__)
print('Employee.__name__:', Employee.__name__)
print('Employee.__module__:', Employee.__module__)
print('Employee.__bases__:', Employee.__bases__)
print('Employee.__dict__:', Employee.__dict__)
a = 40
b = a
c = [b]
del a
b = 100
c[0] = -1
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print(class_name, 'destroyed')
pt1 = point()
pt2 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3))
del pt1
del pt2
del pt3
class Parent:
parent_attr = 100
def __init__(self):
print('Calling parent constructor')
def parent_method(self):
print('Calling parent method')
def set_attr(self, attr):
Parent.parentAttr = attr
def get_attr(self):
print('Parent attribute :', Parent.parentAttr)
class Child(Parent):
def __init__(self):
print('Calling child constructor')
def child_method(self):
print('Calling child method')
c = child()
c.childMethod()
c.parentMethod()
c.setAttr(200)
c.getAttr()
class A:
"""....."""
class B:
"""....."""
class C(A, B):
""".....""" |
"""
j is the index to insert when a number not equal to val.
j will never catch up i, so j will not mess up the check.
"""
class Solution(object):
def removeElement(self, nums, val):
j = 0
for n in nums:
if n!=val:
nums[j] = n
j += 1
return j | """
j is the index to insert when a number not equal to val.
j will never catch up i, so j will not mess up the check.
"""
class Solution(object):
def remove_element(self, nums, val):
j = 0
for n in nums:
if n != val:
nums[j] = n
j += 1
return j |
# from pynvim import attach
# nvim = attach('socket', path='/tmp/nvim')
# handle = nvim.request("nvim_create_buf",1,0)
# nvim.request("nvim_open_win",2,True,{'relative':'win','width':50,'height':3,'row':3,'col':3})
# maybe get current window's config and based on it? but resizing will make things weird, like fzf
# src = nvim.new_highlight_source()
buf = nvim.current.buffer
# # for i in range(5):
# # # has async parameter
# # buf.add_highlight("String",i,0,-1,src_id=src)
# # # some time later ...
# # buf.clear_namespace(src)
# nvim.command("silent split")
# nvim.command("silent e FilterJump")
# nvim.command("silent setlocal buftype=nofile")
# nvim.command('silent setlocal filetype=FilterJump')
# nvim.current.window.height = 1
# nvim.command("silent CocDisable")
# nvim.command("startinsert")
| buf = nvim.current.buffer |
# Leetcode 323
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
visited = [False] * n
adj_list = [None] * n
for vertex in range(n):
adj_list[vertex] = list()
for edge in edges:
adj_list[edge[0]].append(edge[1])
adj_list[edge[1]].append(edge[0])
# 96 ms, faster than 9x%
def bfs(source):
q = []
q.append(source)
visited[source] = True
while q:
node = q.pop(0)
for neighbor in adj_list[node]:
if not visited[neighbor]:
visited[neighbor] = True
q.append(neighbor)
# 116 ms, faster than 67.25%
def dfs(source):
q = []
q.append(source)
visited[source] = True
while q:
node = q.pop()
for neighbor in adj_list[node]:
if not visited[neighbor]:
visited[neighbor] = True
q.append(neighbor)
components = 0
for vertex in range(n):
if not visited[vertex]:
components += 1
dfs(vertex)
return components
| class Solution:
def count_components(self, n: int, edges: List[List[int]]) -> int:
visited = [False] * n
adj_list = [None] * n
for vertex in range(n):
adj_list[vertex] = list()
for edge in edges:
adj_list[edge[0]].append(edge[1])
adj_list[edge[1]].append(edge[0])
def bfs(source):
q = []
q.append(source)
visited[source] = True
while q:
node = q.pop(0)
for neighbor in adj_list[node]:
if not visited[neighbor]:
visited[neighbor] = True
q.append(neighbor)
def dfs(source):
q = []
q.append(source)
visited[source] = True
while q:
node = q.pop()
for neighbor in adj_list[node]:
if not visited[neighbor]:
visited[neighbor] = True
q.append(neighbor)
components = 0
for vertex in range(n):
if not visited[vertex]:
components += 1
dfs(vertex)
return components |
#
# PySNMP MIB module RTBRICK-SYSLOG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///home/tin/Dev/mibs.snmplabs.com/asn1/RTBRICK-SYSLOG-MIB
# Produced by pysmi-0.3.4 at Fri Jan 31 21:33:01 2020
# On host bier platform Linux version 5.4.0-3-amd64 by user tin
# Using Python version 3.7.6 (default, Jan 19 2020, 22:34:52)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection")
rtbrickSyslogNotifications, rtbrickTraps, rtbrickModules = mibBuilder.importSymbols("RTBRICK-MIB", "rtbrickSyslogNotifications", "rtbrickTraps", "rtbrickModules")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Bits, NotificationType, Counter32, Counter64, MibIdentifier, IpAddress, TimeTicks, Unsigned32, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Gauge32, ModuleIdentity, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "NotificationType", "Counter32", "Counter64", "MibIdentifier", "IpAddress", "TimeTicks", "Unsigned32", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Gauge32", "ModuleIdentity", "ObjectIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
rtBrickSyslogMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 50058, 104, 2))
rtBrickSyslogMIB.setRevisions(('2019-01-04 00:00',))
if mibBuilder.loadTexts: rtBrickSyslogMIB.setLastUpdated('201804140000Z')
if mibBuilder.loadTexts: rtBrickSyslogMIB.setOrganization('RtBrick')
syslogMessage = MibIdentifier((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1))
class SyslogSeverity(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))
namedValues = NamedValues(("emergency", 1), ("alert", 2), ("critical", 3), ("error", 4), ("warning", 5), ("notice", 6), ("info", 7), ("debug", 8))
syslogMsgNumber = MibScalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 1), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: syslogMsgNumber.setStatus('current')
syslogMsgFacility = MibScalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 2), DisplayString()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: syslogMsgFacility.setStatus('current')
syslogMsgSeverity = MibScalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 3), SyslogSeverity()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: syslogMsgSeverity.setStatus('current')
syslogMsgText = MibScalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 4), DisplayString()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: syslogMsgText.setStatus('current')
rtbrickSyslogNotificationPrefix = ObjectIdentity((1, 3, 6, 1, 4, 1, 50058, 103, 1, 0))
if mibBuilder.loadTexts: rtbrickSyslogNotificationPrefix.setStatus('current')
rtbrickSyslogTrap = NotificationType((1, 3, 6, 1, 4, 1, 50058, 103, 1, 0, 1))
if mibBuilder.loadTexts: rtbrickSyslogTrap.setStatus('current')
mibBuilder.exportSymbols("RTBRICK-SYSLOG-MIB", SyslogSeverity=SyslogSeverity, rtbrickSyslogNotificationPrefix=rtbrickSyslogNotificationPrefix, rtbrickSyslogTrap=rtbrickSyslogTrap, syslogMsgFacility=syslogMsgFacility, rtBrickSyslogMIB=rtBrickSyslogMIB, PYSNMP_MODULE_ID=rtBrickSyslogMIB, syslogMsgText=syslogMsgText, syslogMsgSeverity=syslogMsgSeverity, syslogMsgNumber=syslogMsgNumber, syslogMessage=syslogMessage)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection')
(rtbrick_syslog_notifications, rtbrick_traps, rtbrick_modules) = mibBuilder.importSymbols('RTBRICK-MIB', 'rtbrickSyslogNotifications', 'rtbrickTraps', 'rtbrickModules')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(bits, notification_type, counter32, counter64, mib_identifier, ip_address, time_ticks, unsigned32, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, gauge32, module_identity, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'NotificationType', 'Counter32', 'Counter64', 'MibIdentifier', 'IpAddress', 'TimeTicks', 'Unsigned32', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'Gauge32', 'ModuleIdentity', 'ObjectIdentity')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
rt_brick_syslog_mib = module_identity((1, 3, 6, 1, 4, 1, 50058, 104, 2))
rtBrickSyslogMIB.setRevisions(('2019-01-04 00:00',))
if mibBuilder.loadTexts:
rtBrickSyslogMIB.setLastUpdated('201804140000Z')
if mibBuilder.loadTexts:
rtBrickSyslogMIB.setOrganization('RtBrick')
syslog_message = mib_identifier((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1))
class Syslogseverity(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8))
named_values = named_values(('emergency', 1), ('alert', 2), ('critical', 3), ('error', 4), ('warning', 5), ('notice', 6), ('info', 7), ('debug', 8))
syslog_msg_number = mib_scalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 1), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
syslogMsgNumber.setStatus('current')
syslog_msg_facility = mib_scalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 2), display_string()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
syslogMsgFacility.setStatus('current')
syslog_msg_severity = mib_scalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 3), syslog_severity()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
syslogMsgSeverity.setStatus('current')
syslog_msg_text = mib_scalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 4), display_string()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
syslogMsgText.setStatus('current')
rtbrick_syslog_notification_prefix = object_identity((1, 3, 6, 1, 4, 1, 50058, 103, 1, 0))
if mibBuilder.loadTexts:
rtbrickSyslogNotificationPrefix.setStatus('current')
rtbrick_syslog_trap = notification_type((1, 3, 6, 1, 4, 1, 50058, 103, 1, 0, 1))
if mibBuilder.loadTexts:
rtbrickSyslogTrap.setStatus('current')
mibBuilder.exportSymbols('RTBRICK-SYSLOG-MIB', SyslogSeverity=SyslogSeverity, rtbrickSyslogNotificationPrefix=rtbrickSyslogNotificationPrefix, rtbrickSyslogTrap=rtbrickSyslogTrap, syslogMsgFacility=syslogMsgFacility, rtBrickSyslogMIB=rtBrickSyslogMIB, PYSNMP_MODULE_ID=rtBrickSyslogMIB, syslogMsgText=syslogMsgText, syslogMsgSeverity=syslogMsgSeverity, syslogMsgNumber=syslogMsgNumber, syslogMessage=syslogMessage) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
with open("file.txt", 'r') as f:
content = f.read();
print(content)
| if __name__ == '__main__':
with open('file.txt', 'r') as f:
content = f.read()
print(content) |
class Solution(object):
def numIslands(self, grid):
if not grid:
return 0
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
self.dfs(grid, i, j)
count += 1
return count
def dfs(self, grid, i, j):
if i < 0 or i >= len(grid) \
or j < 0 or j >= len(grid[0]) or grid[i][j] != '1':
return
grid[i][j] = '#'
self.dfs(grid, i + 1, j)
self.dfs(grid, i - 1, j)
self.dfs(grid, i, j + 1)
self.dfs(grid, i, j - 1)
def test_num_islands():
s = Solution()
assert 1 == s.numIslands([['1', '1', '1', '1', '0'],
['1', '1', '0', '1', '0'],
['1', '1', '0', '0', '0'],
['0', '0', '0', '0', '0']])
assert 3 == s.numIslands([['1', '1', '0', '0', '0'],
['1', '1', '0', '0', '0'],
['0', '0', '1', '0', '0'],
['0', '0', '0', '1', '1']])
| class Solution(object):
def num_islands(self, grid):
if not grid:
return 0
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
self.dfs(grid, i, j)
count += 1
return count
def dfs(self, grid, i, j):
if i < 0 or i >= len(grid) or j < 0 or (j >= len(grid[0])) or (grid[i][j] != '1'):
return
grid[i][j] = '#'
self.dfs(grid, i + 1, j)
self.dfs(grid, i - 1, j)
self.dfs(grid, i, j + 1)
self.dfs(grid, i, j - 1)
def test_num_islands():
s = solution()
assert 1 == s.numIslands([['1', '1', '1', '1', '0'], ['1', '1', '0', '1', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '0', '0', '0']])
assert 3 == s.numIslands([['1', '1', '0', '0', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '0'], ['0', '0', '0', '1', '1']]) |
class Empty:
""" An empty element. Serves the same function as None, except that it can be used to indicate that JSGNull
and AnyType attributes (which both can legitimately have None values) have not been assigned
"""
def __new__(cls):
return cls | class Empty:
""" An empty element. Serves the same function as None, except that it can be used to indicate that JSGNull
and AnyType attributes (which both can legitimately have None values) have not been assigned
"""
def __new__(cls):
return cls |
print('Insert first string')
string1 = input()
print('Insert second string')
string2 = input()
print(string1 + ' - ' + string2 + ' are anagrams?', sorted(string1) == sorted(string2))
'''
Check whether the strings in input are anagrams or not.
Two strings, a and b, are called anagrams if they contain all the same characters in the same frequencies.
For example, the anagrams of CAT are CAT, ACT, TAC, TCA, ATC, and CTA.
Sample Input:
string1=CAT
string2=ACT
Sample Output:
true
Time complexity : O(N log N)
Space complexity: O(1)
'''
| print('Insert first string')
string1 = input()
print('Insert second string')
string2 = input()
print(string1 + ' - ' + string2 + ' are anagrams?', sorted(string1) == sorted(string2))
'\nCheck whether the strings in input are anagrams or not.\n\nTwo strings, a and b, are called anagrams if they contain all the same characters in the same frequencies. \nFor example, the anagrams of CAT are CAT, ACT, TAC, TCA, ATC, and CTA.\n\nSample Input:\nstring1=CAT\nstring2=ACT\n\nSample Output:\ntrue\n\nTime complexity : O(N log N)\nSpace complexity: O(1)\n' |
class Scaler1D:
def __init__(self) -> None:
self.max_num: float = None
self.min_num: float = None
def transform(self, num_list: list) -> list:
if self.max_num is None:
self.max_num = max(num_list)
if self.min_num is None:
self.min_num = min(num_list)
return [(x - self.min_num) / (self.max_num - self.min_num) for x in num_list]
def inverse_transform(self, num_list: list) -> list:
return [x * (self.max_num - self.min_num) + self.min_num for x in num_list]
class Scaler2D:
def __init__(self) -> None:
self.max_num: float = None
self.min_num: float = None
def transform(self, num_list: list) -> list:
if self.max_num is None:
self.max_num = max([max(x[0], x[1]) for x in num_list])
if self.min_num is None:
self.min_num = min([min(x[0], x[1]) for x in num_list])
return [[(x[0] - self.min_num) / (self.max_num - self.min_num),
(x[1] - self.min_num) / (self.max_num - self.min_num)]
for x in num_list]
def inverse_transform(self, num_list: list) -> list:
return [[x[0] * (self.max_num - self.min_num) + self.min_num,
x[1] * (self.max_num - self.min_num) + self.min_num]
for x in num_list]
| class Scaler1D:
def __init__(self) -> None:
self.max_num: float = None
self.min_num: float = None
def transform(self, num_list: list) -> list:
if self.max_num is None:
self.max_num = max(num_list)
if self.min_num is None:
self.min_num = min(num_list)
return [(x - self.min_num) / (self.max_num - self.min_num) for x in num_list]
def inverse_transform(self, num_list: list) -> list:
return [x * (self.max_num - self.min_num) + self.min_num for x in num_list]
class Scaler2D:
def __init__(self) -> None:
self.max_num: float = None
self.min_num: float = None
def transform(self, num_list: list) -> list:
if self.max_num is None:
self.max_num = max([max(x[0], x[1]) for x in num_list])
if self.min_num is None:
self.min_num = min([min(x[0], x[1]) for x in num_list])
return [[(x[0] - self.min_num) / (self.max_num - self.min_num), (x[1] - self.min_num) / (self.max_num - self.min_num)] for x in num_list]
def inverse_transform(self, num_list: list) -> list:
return [[x[0] * (self.max_num - self.min_num) + self.min_num, x[1] * (self.max_num - self.min_num) + self.min_num] for x in num_list] |
"""This module defines Debian Buster dependencies."""
load("@rules_deb_packages//:deb_packages.bzl", "deb_packages")
def debian_buster_amd64():
deb_packages(
name = "debian_buster_amd64_macro",
arch = "amd64",
urls = [
"http://deb.debian.org/debian/$(package_path)",
"http://deb.debian.org/debian-security/$(package_path)",
"https://snapshot.debian.org/archive/debian/$(timestamp)/$(package_path)", # Needed in case of superseded archive no more available on the mirrors
"https://snapshot.debian.org/archive/debian-security/$(timestamp)/$(package_path)", # Needed in case of superseded archive no more available on the mirrors
],
packages = {
"base-files": "pool/main/b/base-files/base-files_10.3+deb10u8_amd64.deb",
"busybox": "pool/main/b/busybox/busybox_1.30.1-4_amd64.deb",
"ca-certificates": "pool/main/c/ca-certificates/ca-certificates_20200601~deb10u2_all.deb",
"libc6": "pool/main/g/glibc/libc6_2.28-10_amd64.deb",
"libssl1.1": "pool/updates/main/o/openssl/libssl1.1_1.1.1d-0+deb10u5_amd64.deb",
"netbase": "pool/main/n/netbase/netbase_5.6_all.deb",
"openssl": "pool/updates/main/o/openssl/openssl_1.1.1d-0+deb10u5_amd64.deb",
"tzdata": "pool/main/t/tzdata/tzdata_2021a-0+deb10u1_all.deb",
},
packages_sha256 = {
"base-files": "eda9ec7196cae25adfa1cb91be0c9071b26904540fc90bab8529b2a93ece62b1",
"busybox": "1e32ea742bddec4ed5a530ee2f423cdfc297c6280bfbb45c97bf12eecf5c3ec1",
"ca-certificates": "a9e267a24088c793a9cf782455fd344db5fdced714f112a8857c5bfd07179387",
"libc6": "6f703e27185f594f8633159d00180ea1df12d84f152261b6e88af75667195a79",
"libssl1.1": "1741ec08b10caa4d3c8a165768323a14946278a7e6fb9cd56ae59cf4fe1ef970",
"netbase": "baf0872964df0ccb10e464b47d995acbba5a0d12a97afe2646d9a6bb97e8d79d",
"openssl": "f4c32a3f851adeb0145edafb8ea271aed8330ee864de23f155f4141a81dc6e10",
"tzdata": "00da63f221b9afa6bc766742807e398cf183565faba339649bafa3f93375fbcb",
},
sources = [
"http://deb.debian.org/debian buster main",
"http://deb.debian.org/debian buster-updates main",
"http://deb.debian.org/debian-security buster/updates main",
],
timestamp = "20210306T084946Z",
)
| """This module defines Debian Buster dependencies."""
load('@rules_deb_packages//:deb_packages.bzl', 'deb_packages')
def debian_buster_amd64():
deb_packages(name='debian_buster_amd64_macro', arch='amd64', urls=['http://deb.debian.org/debian/$(package_path)', 'http://deb.debian.org/debian-security/$(package_path)', 'https://snapshot.debian.org/archive/debian/$(timestamp)/$(package_path)', 'https://snapshot.debian.org/archive/debian-security/$(timestamp)/$(package_path)'], packages={'base-files': 'pool/main/b/base-files/base-files_10.3+deb10u8_amd64.deb', 'busybox': 'pool/main/b/busybox/busybox_1.30.1-4_amd64.deb', 'ca-certificates': 'pool/main/c/ca-certificates/ca-certificates_20200601~deb10u2_all.deb', 'libc6': 'pool/main/g/glibc/libc6_2.28-10_amd64.deb', 'libssl1.1': 'pool/updates/main/o/openssl/libssl1.1_1.1.1d-0+deb10u5_amd64.deb', 'netbase': 'pool/main/n/netbase/netbase_5.6_all.deb', 'openssl': 'pool/updates/main/o/openssl/openssl_1.1.1d-0+deb10u5_amd64.deb', 'tzdata': 'pool/main/t/tzdata/tzdata_2021a-0+deb10u1_all.deb'}, packages_sha256={'base-files': 'eda9ec7196cae25adfa1cb91be0c9071b26904540fc90bab8529b2a93ece62b1', 'busybox': '1e32ea742bddec4ed5a530ee2f423cdfc297c6280bfbb45c97bf12eecf5c3ec1', 'ca-certificates': 'a9e267a24088c793a9cf782455fd344db5fdced714f112a8857c5bfd07179387', 'libc6': '6f703e27185f594f8633159d00180ea1df12d84f152261b6e88af75667195a79', 'libssl1.1': '1741ec08b10caa4d3c8a165768323a14946278a7e6fb9cd56ae59cf4fe1ef970', 'netbase': 'baf0872964df0ccb10e464b47d995acbba5a0d12a97afe2646d9a6bb97e8d79d', 'openssl': 'f4c32a3f851adeb0145edafb8ea271aed8330ee864de23f155f4141a81dc6e10', 'tzdata': '00da63f221b9afa6bc766742807e398cf183565faba339649bafa3f93375fbcb'}, sources=['http://deb.debian.org/debian buster main', 'http://deb.debian.org/debian buster-updates main', 'http://deb.debian.org/debian-security buster/updates main'], timestamp='20210306T084946Z') |
# SWAPPING THE NUMBERS
a=5
b=2
print(a,b)
a,b=b,a
print(a,b) | a = 5
b = 2
print(a, b)
(a, b) = (b, a)
print(a, b) |
BASE_URL = "https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate?expr"
PAPER_ATTRIBUTES = "AA.DAuN,DN,D,ECC,DFN,J.JN,PB,Y"
AUTHOR_ATTRIBUTES = "Id,DAuN,ECC,LKA.AfN,PC"
STUDY_FIELD_ATTRIBUTES = "Id,PC,FP.FN,ECC,DFN,FC.FN"
PAPER = 'paper'
AUTHOR = 'author'
AFFILIATION = 'affiliation'
STUDY_FIELD = 'study field' | base_url = 'https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate?expr'
paper_attributes = 'AA.DAuN,DN,D,ECC,DFN,J.JN,PB,Y'
author_attributes = 'Id,DAuN,ECC,LKA.AfN,PC'
study_field_attributes = 'Id,PC,FP.FN,ECC,DFN,FC.FN'
paper = 'paper'
author = 'author'
affiliation = 'affiliation'
study_field = 'study field' |
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
row=len(board)
col = len(board[0])
copy = [[0 for i in range(col)]for j in range(row)]
for i in range(row):
for j in range(col):
copy[i][j]=board[i][j]
neighbors=[(-1,-1),(-1,0),(-1,1),(0,1),(0,-1),(1,1),(1,0),(1,-1)]
for i in range(row):
for j in range(col):
live_nei = 0
for nei in neighbors:
r = (i+nei[0])
c = (j+nei[1])
if (r<row and r>=0) and (c<col and c>=0)and(copy[r][c]==1):
live_nei+=1
if copy[i][j]==1 and(live_nei<2 or live_nei>3):
board[i][j]=0
if copy[i][j]==0 and live_nei==3:
board[i][j]=1
| class Solution:
def game_of_life(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
row = len(board)
col = len(board[0])
copy = [[0 for i in range(col)] for j in range(row)]
for i in range(row):
for j in range(col):
copy[i][j] = board[i][j]
neighbors = [(-1, -1), (-1, 0), (-1, 1), (0, 1), (0, -1), (1, 1), (1, 0), (1, -1)]
for i in range(row):
for j in range(col):
live_nei = 0
for nei in neighbors:
r = i + nei[0]
c = j + nei[1]
if (r < row and r >= 0) and (c < col and c >= 0) and (copy[r][c] == 1):
live_nei += 1
if copy[i][j] == 1 and (live_nei < 2 or live_nei > 3):
board[i][j] = 0
if copy[i][j] == 0 and live_nei == 3:
board[i][j] = 1 |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 8 08:54:01 2019
@author: balam
"""
| """
Created on Tue Oct 8 08:54:01 2019
@author: balam
""" |
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr) // 2
leftHalf = arr[:mid] # 56,24,93,17
rightHalf = arr[mid:] # 77,31,44,55,20
mergeSort(leftHalf)
mergeSort(rightHalf)
i = j = k = 0
while i < len(leftHalf) and j < len(rightHalf):
if leftHalf[i] < rightHalf[j]:
arr[k] = leftHalf[i]
i += 1
else:
arr[k] = rightHalf[j]
j += 1
k += 1
while i < len(leftHalf):
arr[k] = leftHalf[i]
i += 1
k += 1
while j < len(rightHalf):
arr[k] = rightHalf[j]
j += 1
k += 1
arr = [56,24,93,17,77,31,44,55,20]
mergeSort(arr)
print(arr) | def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(leftHalf)
merge_sort(rightHalf)
i = j = k = 0
while i < len(leftHalf) and j < len(rightHalf):
if leftHalf[i] < rightHalf[j]:
arr[k] = leftHalf[i]
i += 1
else:
arr[k] = rightHalf[j]
j += 1
k += 1
while i < len(leftHalf):
arr[k] = leftHalf[i]
i += 1
k += 1
while j < len(rightHalf):
arr[k] = rightHalf[j]
j += 1
k += 1
arr = [56, 24, 93, 17, 77, 31, 44, 55, 20]
merge_sort(arr)
print(arr) |
# ask for int, report runnig total / version 1
num = 0
total = 0
while num != -1:
total = total + num
print("total so far = " + str(total))
num = int(input("next int: "))
# ask for int, report runnig total / version 2
total = 0
while True:
num = int(input("next int: "))
if num == -1:
break
total += num
print("total so far = " + str(total))
# check if number is prime
num = int(input("int: "))
total = 0
for x in range(2, num):
if num % x == 0:
print(str(num) + " is NOT prime")
break # we don't need to continue checking
else:
print(str(num) + " is PRIME")
# check multiple numbers
while True:
num = int(input("int: "))
if num == -1:
break
if num < 3:
print("int must be greater than 2")
continue
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(str(num) + " is PRIME")
else:
print(str(num) + " is NOT prime")
# print out primes up to 100
for i in range(3, 101):
is_prime = True
for j in range(2, i-1):
if i % j == 0:
is_prime = False
break
if is_prime:
print(str(i) + " is PRIME")
else:
print(str(i) + " is NOT prime")
# print multilication table
for i in range(1, 11):
for j in range(1, 11):
print("%3d" % (i * j), end=' ')
print()
print()
| num = 0
total = 0
while num != -1:
total = total + num
print('total so far = ' + str(total))
num = int(input('next int: '))
total = 0
while True:
num = int(input('next int: '))
if num == -1:
break
total += num
print('total so far = ' + str(total))
num = int(input('int: '))
total = 0
for x in range(2, num):
if num % x == 0:
print(str(num) + ' is NOT prime')
break
else:
print(str(num) + ' is PRIME')
while True:
num = int(input('int: '))
if num == -1:
break
if num < 3:
print('int must be greater than 2')
continue
is_prime = True
for i in range(2, num):
if num % i == 0:
is_prime = False
break
if is_prime:
print(str(num) + ' is PRIME')
else:
print(str(num) + ' is NOT prime')
for i in range(3, 101):
is_prime = True
for j in range(2, i - 1):
if i % j == 0:
is_prime = False
break
if is_prime:
print(str(i) + ' is PRIME')
else:
print(str(i) + ' is NOT prime')
for i in range(1, 11):
for j in range(1, 11):
print('%3d' % (i * j), end=' ')
print()
print() |
#!/usr/bin/env python3
#################################################################################
# #
# Program purpose: Generate message based on user input. #
# Program Author : Happi Yvan <ivensteinpoker@gmail.com> #
# Creation Date : September 10, 2019 #
# #
#################################################################################
def get_message(info: {}):
basic_info = f"Hi there {info['name']}!, nice knowing you!"
if int(info['age']) < 18:
basic_info += f" You're relatively young at {info['age']}."
if 18 < int(info['age']) < 30:
if info['gender'] == "male":
basic_info += f" Becoming a man, huh!"
else:
basic_info += f" Becoming a woman, hun!"
elif int(info['age']) < 18:
basic_info += " Enjoy your teens"
else:
basic_info += " You're getting old, you know!"
basic_info += f" Living in {info['location']} should be pretty fun!"
return basic_info
if __name__ == "__main__":
name = str(input("Enter your name: "))
gender = str(input("Enter your gender: "))
age = 0
cont = True
while cont:
try:
age = int(input("Enter your age: "))
cont = False
except ValueError as ve:
print(f"[ERROR]: {ve}")
location = str(input("Where do you live: "))
print(get_message({'name': name, 'gender': gender, 'age': age, 'location': location}))
| def get_message(info: {}):
basic_info = f"Hi there {info['name']}!, nice knowing you!"
if int(info['age']) < 18:
basic_info += f" You're relatively young at {info['age']}."
if 18 < int(info['age']) < 30:
if info['gender'] == 'male':
basic_info += f' Becoming a man, huh!'
else:
basic_info += f' Becoming a woman, hun!'
elif int(info['age']) < 18:
basic_info += ' Enjoy your teens'
else:
basic_info += " You're getting old, you know!"
basic_info += f" Living in {info['location']} should be pretty fun!"
return basic_info
if __name__ == '__main__':
name = str(input('Enter your name: '))
gender = str(input('Enter your gender: '))
age = 0
cont = True
while cont:
try:
age = int(input('Enter your age: '))
cont = False
except ValueError as ve:
print(f'[ERROR]: {ve}')
location = str(input('Where do you live: '))
print(get_message({'name': name, 'gender': gender, 'age': age, 'location': location})) |
class Tree:
def __init__(self):
self.left = None
self.right = None
self.data = None
def init_left_child(self):
self.left = Tree()
def init_right_child(self):
self.right = Tree()
def init_both_childs(self):
self.init_left_child()
self.init_right_child()
def init_data(self, data):
self.data = data
def init_both_childs_and_data(self, data):
self.init_both_childs()
self.init_data(data)
def main():
root = Tree()
root.init_both_childs()
| class Tree:
def __init__(self):
self.left = None
self.right = None
self.data = None
def init_left_child(self):
self.left = tree()
def init_right_child(self):
self.right = tree()
def init_both_childs(self):
self.init_left_child()
self.init_right_child()
def init_data(self, data):
self.data = data
def init_both_childs_and_data(self, data):
self.init_both_childs()
self.init_data(data)
def main():
root = tree()
root.init_both_childs() |
'''
Title : Loops
Subdomain : Introduction
Domain : Python
Author : Kalpak Seal
Created : 28 September 2016
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(raw_input())
for i in range(0, n):
print (i ** 2) | """
Title : Loops
Subdomain : Introduction
Domain : Python
Author : Kalpak Seal
Created : 28 September 2016
"""
n = int(raw_input())
for i in range(0, n):
print(i ** 2) |
local_val = 'magical creature'
def square(x):
return x * x
class User:
def __init__(self, name):
self.name = name
def say_hello(self):
return 'Hello'
# This conditional allows us to run certain blocks of code depending on which file they're in
if __name__ == "__main__":
print('the file is being executed directly')
else:
print('the file is being executed because it is imported by another file, this file is called', __name__)
pass
# print(square(5))
# user = User("Luigi")
# print(user.name)
# print(user.say_hello())
# print(__name__)
| local_val = 'magical creature'
def square(x):
return x * x
class User:
def __init__(self, name):
self.name = name
def say_hello(self):
return 'Hello'
if __name__ == '__main__':
print('the file is being executed directly')
else:
print('the file is being executed because it is imported by another file, this file is called', __name__)
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.