content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
a,b,c = input().split()
a,b,c = [float(a),float(b),float(c)]
if a+b <= c or b+c <= a or c+a <= b:
print("NAO FORMA TRIANGULO")
else:
if a*a == b*b+c*c or b*b == a*a+c*c or c*c == b*b+a*a:
print("TRIANGULO RETANGULO")
elif a*a > b*b+c*c or b*b > a*a+c*c or c*c > b*b+a*a:
print("TRIANGULO OBTUSANGULO")
else:
print("TRIANGULO ACUTANGULO")
if a == b == c:
print("TRIANGULO EQUILATERO")
elif a == b != c or a == c != b or c == b != a:
print("TRIANGULO ISOSCELES")
| (a, b, c) = input().split()
(a, b, c) = [float(a), float(b), float(c)]
if a + b <= c or b + c <= a or c + a <= b:
print('NAO FORMA TRIANGULO')
else:
if a * a == b * b + c * c or b * b == a * a + c * c or c * c == b * b + a * a:
print('TRIANGULO RETANGULO')
elif a * a > b * b + c * c or b * b > a * a + c * c or c * c > b * b + a * a:
print('TRIANGULO OBTUSANGULO')
else:
print('TRIANGULO ACUTANGULO')
if a == b == c:
print('TRIANGULO EQUILATERO')
elif a == b != c or a == c != b or c == b != a:
print('TRIANGULO ISOSCELES') |
"""
@author: magician
@date: 2019/12/13
@file: exception_demo.py
"""
def divide(a, b):
"""
divide
:param a:
:param b:
:return:
"""
try:
return a / b
except ZeroDivisionError:
return None
def divide1(a, b):
"""
divide1
:param a:
:param b:
:return:
"""
try:
return True, a / b
except ZeroDivisionError:
return False, None
def divide2(a, b):
"""
divide2
:param a:
:param b:
:return:
"""
try:
return a / b
except ZeroDivisionError as e:
raise ValueError('Invalid inputs') from e
if __name__ == '__main__':
x, y = 0, 5
result = divide(x, y)
if not result:
print('Invalid inputs')
success, result = divide1(x, y)
if not success:
print('Invalid inputs')
_, result = divide1(x, y)
if not result:
print('Invalid inputs')
x, y = 5, 2
try:
result = divide(x, y)
except ValueError:
print('Invalid inputs')
else:
print('Result is %.1f' % result)
| """
@author: magician
@date: 2019/12/13
@file: exception_demo.py
"""
def divide(a, b):
"""
divide
:param a:
:param b:
:return:
"""
try:
return a / b
except ZeroDivisionError:
return None
def divide1(a, b):
"""
divide1
:param a:
:param b:
:return:
"""
try:
return (True, a / b)
except ZeroDivisionError:
return (False, None)
def divide2(a, b):
"""
divide2
:param a:
:param b:
:return:
"""
try:
return a / b
except ZeroDivisionError as e:
raise value_error('Invalid inputs') from e
if __name__ == '__main__':
(x, y) = (0, 5)
result = divide(x, y)
if not result:
print('Invalid inputs')
(success, result) = divide1(x, y)
if not success:
print('Invalid inputs')
(_, result) = divide1(x, y)
if not result:
print('Invalid inputs')
(x, y) = (5, 2)
try:
result = divide(x, y)
except ValueError:
print('Invalid inputs')
else:
print('Result is %.1f' % result) |
def print_without_vowels(s):
'''
s: the string to convert
Finds a version of s without vowels and whose characters appear in the
same order they appear in s. Prints this version of s.
Does not return anything
'''
# Your code here
newString = ""
for item in s:
if item not in "aeiouAEIOU":
newString += item
print(newString)
# print(print_without_vowels("a"))
print_without_vowels("a")
| def print_without_vowels(s):
"""
s: the string to convert
Finds a version of s without vowels and whose characters appear in the
same order they appear in s. Prints this version of s.
Does not return anything
"""
new_string = ''
for item in s:
if item not in 'aeiouAEIOU':
new_string += item
print(newString)
print_without_vowels('a') |
expected_1 = ({
'__feature_4': [ 42., 67., 6., 92., 80., 10., 90., 5., 100.,
40., 23., 44., 81., 53., 37., 7., 79., 45., 87.],
'__feature_2': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75.,
77., 98., 71., 95., 4., 83., 70., 33.],
'__feature_3': [ 17., 82., 26., 99., 72., 35., 54., 22., 20., 25., 29.,
94., 66., 84., 55., 12., 43., 1., 16.],
'__feature_0': [ 63., 89., 49., 24., 41., 48., 58., 47., 61., 14., 59.,
96., 88., 65., 19., 74., 97., 50., 57.],
'__feature_1': [ 27., 52., 18., 76., 60., 62., 30., 8., 86., 78., 31.,
39., 93., 2., 28., 46., 85., 3., 73.]}, 19)
expected_2 = ({
'cuatro': [ 17., 82., 26., 99., 72., 35., 54., 22., 20., 25., 29.,
94., 66., 84., 55., 12., 43., 1., 16.],
'dos': [ 27., 52., 18., 76., 60., 62., 30., 8., 86., 78., 31.,
39., 93., 2., 28., 46., 85., 3., 73.],
'tres': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75.,
77., 98., 71., 95., 4., 83., 70., 33.],
'cinco': [ 42., 67., 6., 92., 80., 10., 90., 5., 100.,
40., 23., 44., 81., 53., 37., 7., 79., 45., 87.],
'uno': [ 63., 89., 49., 24., 41., 48., 58., 47., 61., 14., 59.,
96., 88., 65., 19., 74., 97., 50., 57.]}, 19)
expected_3 = ({
'cuatro': [ 17., 82., 26., 99., 72., 35., 54., 22., 20., 25., 29.,
94., 66., 84., 55., 12., 43., 1., 16.],
'tres': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75.,
77., 98., 71., 95., 4., 83., 70., 33.]}, 19)
expected_single_row = {
'single': [ 91., 15., 36., 51., 32., 11., 38., 56., 21., 34., 75.,
77., 98., 71., 95., 4., 83., 70., 33.]} | expected_1 = ({'__feature_4': [42.0, 67.0, 6.0, 92.0, 80.0, 10.0, 90.0, 5.0, 100.0, 40.0, 23.0, 44.0, 81.0, 53.0, 37.0, 7.0, 79.0, 45.0, 87.0], '__feature_2': [91.0, 15.0, 36.0, 51.0, 32.0, 11.0, 38.0, 56.0, 21.0, 34.0, 75.0, 77.0, 98.0, 71.0, 95.0, 4.0, 83.0, 70.0, 33.0], '__feature_3': [17.0, 82.0, 26.0, 99.0, 72.0, 35.0, 54.0, 22.0, 20.0, 25.0, 29.0, 94.0, 66.0, 84.0, 55.0, 12.0, 43.0, 1.0, 16.0], '__feature_0': [63.0, 89.0, 49.0, 24.0, 41.0, 48.0, 58.0, 47.0, 61.0, 14.0, 59.0, 96.0, 88.0, 65.0, 19.0, 74.0, 97.0, 50.0, 57.0], '__feature_1': [27.0, 52.0, 18.0, 76.0, 60.0, 62.0, 30.0, 8.0, 86.0, 78.0, 31.0, 39.0, 93.0, 2.0, 28.0, 46.0, 85.0, 3.0, 73.0]}, 19)
expected_2 = ({'cuatro': [17.0, 82.0, 26.0, 99.0, 72.0, 35.0, 54.0, 22.0, 20.0, 25.0, 29.0, 94.0, 66.0, 84.0, 55.0, 12.0, 43.0, 1.0, 16.0], 'dos': [27.0, 52.0, 18.0, 76.0, 60.0, 62.0, 30.0, 8.0, 86.0, 78.0, 31.0, 39.0, 93.0, 2.0, 28.0, 46.0, 85.0, 3.0, 73.0], 'tres': [91.0, 15.0, 36.0, 51.0, 32.0, 11.0, 38.0, 56.0, 21.0, 34.0, 75.0, 77.0, 98.0, 71.0, 95.0, 4.0, 83.0, 70.0, 33.0], 'cinco': [42.0, 67.0, 6.0, 92.0, 80.0, 10.0, 90.0, 5.0, 100.0, 40.0, 23.0, 44.0, 81.0, 53.0, 37.0, 7.0, 79.0, 45.0, 87.0], 'uno': [63.0, 89.0, 49.0, 24.0, 41.0, 48.0, 58.0, 47.0, 61.0, 14.0, 59.0, 96.0, 88.0, 65.0, 19.0, 74.0, 97.0, 50.0, 57.0]}, 19)
expected_3 = ({'cuatro': [17.0, 82.0, 26.0, 99.0, 72.0, 35.0, 54.0, 22.0, 20.0, 25.0, 29.0, 94.0, 66.0, 84.0, 55.0, 12.0, 43.0, 1.0, 16.0], 'tres': [91.0, 15.0, 36.0, 51.0, 32.0, 11.0, 38.0, 56.0, 21.0, 34.0, 75.0, 77.0, 98.0, 71.0, 95.0, 4.0, 83.0, 70.0, 33.0]}, 19)
expected_single_row = {'single': [91.0, 15.0, 36.0, 51.0, 32.0, 11.0, 38.0, 56.0, 21.0, 34.0, 75.0, 77.0, 98.0, 71.0, 95.0, 4.0, 83.0, 70.0, 33.0]} |
"""
Physical and mathematical constants and conversion functions.
"""
__all__ = 'deg rad eV meV keV nanometer angstrom micrometer millimeter ' \
'meter nm mm energy2wavelength wavelength2energy rad2deg deg2rad'.split()
deg: float = 1.
rad: float = 3.1415926535897932 / 180
# Energy
eV: float = 1.
meV: float = 1.e-3
keV: float = 1.e3
# Lengths
nanometer: float = 1.
nm: float = nanometer
angstrom: float = 1.e-1 * nm
micrometer: float = 1.e+3 * nm
millimeter: float = 1.e+6 * nm
meter: float = 1.e+9 * nm
mm: float = millimeter
# Conversions
def energy2wavelength(energy: float):
return 1239.84193 / energy
def wavelength2energy(wavelength: float):
return 1239.84193 / wavelength
def rad2deg(radian: float):
return radian / rad
def deg2rad(degree: float):
return degree * rad
| """
Physical and mathematical constants and conversion functions.
"""
__all__ = 'deg rad eV meV keV nanometer angstrom micrometer millimeter meter nm mm energy2wavelength wavelength2energy rad2deg deg2rad'.split()
deg: float = 1.0
rad: float = 3.141592653589793 / 180
e_v: float = 1.0
me_v: float = 0.001
ke_v: float = 1000.0
nanometer: float = 1.0
nm: float = nanometer
angstrom: float = 0.1 * nm
micrometer: float = 1000.0 * nm
millimeter: float = 1000000.0 * nm
meter: float = 1000000000.0 * nm
mm: float = millimeter
def energy2wavelength(energy: float):
return 1239.84193 / energy
def wavelength2energy(wavelength: float):
return 1239.84193 / wavelength
def rad2deg(radian: float):
return radian / rad
def deg2rad(degree: float):
return degree * rad |
"""
Class hierarchy for types of people in college campus
"""
class College:
def __init__(self, college):
self.college = college
def __str__(self):
return f"College: {self.college}"
class Department(College):
def __init__(self, college, department, **kwargs):
self.department = department
super().__init__(college, **kwargs)
def __str__(self):
return f"Department of {self.department}"
def current_department(self):
return f"Department of {self.department}"
class Professor(Department):
def __init__(self, college, department, name, age, **kwargs):
super().__init__(college, department)
self.name = name
self.age = age
def __str__(self):
return f"{self.name} in {self.department} department"
def age(self):
return f"{self.age}"
class Student(Department):
def __init__(self, college, department, student_name, student_age, **kwargs):
super().__init__(college, department)
self.student_name = student_name
self.student_age = student_age
def __str__(self):
return f"{self.student_name} from {super().current_department()}"
def main():
professor = Professor('Rice University', 'Arts', 'Ana Mathew', 36)
print(professor)
print(professor.current_department())
student = ('Rice University', 'Computer Science', 'Jane Doe', 22)
print(student)
if __name__ == '__main__':
main()
| """
Class hierarchy for types of people in college campus
"""
class College:
def __init__(self, college):
self.college = college
def __str__(self):
return f'College: {self.college}'
class Department(College):
def __init__(self, college, department, **kwargs):
self.department = department
super().__init__(college, **kwargs)
def __str__(self):
return f'Department of {self.department}'
def current_department(self):
return f'Department of {self.department}'
class Professor(Department):
def __init__(self, college, department, name, age, **kwargs):
super().__init__(college, department)
self.name = name
self.age = age
def __str__(self):
return f'{self.name} in {self.department} department'
def age(self):
return f'{self.age}'
class Student(Department):
def __init__(self, college, department, student_name, student_age, **kwargs):
super().__init__(college, department)
self.student_name = student_name
self.student_age = student_age
def __str__(self):
return f'{self.student_name} from {super().current_department()}'
def main():
professor = professor('Rice University', 'Arts', 'Ana Mathew', 36)
print(professor)
print(professor.current_department())
student = ('Rice University', 'Computer Science', 'Jane Doe', 22)
print(student)
if __name__ == '__main__':
main() |
# inteiros
idade = 22
ano = 2021
# reais
altura = 1.63
saldo = 10.50
# palavras (strings)
nome = 'Luisa'
sobrenome = 'Moura'
| idade = 22
ano = 2021
altura = 1.63
saldo = 10.5
nome = 'Luisa'
sobrenome = 'Moura' |
def example_filter1(string):
return "Example1: " + string
def get_template_filter():
return example_filter1
def returns_string_passed(string):
return string
def title_string(string):
return string.title()
| def example_filter1(string):
return 'Example1: ' + string
def get_template_filter():
return example_filter1
def returns_string_passed(string):
return string
def title_string(string):
return string.title() |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class BotFrameworkSkill:
"""
Registration for a BotFrameworkHttpProtocol based Skill endpoint.
"""
# pylint: disable=invalid-name
def __init__(self, id: str = None, app_id: str = None, skill_endpoint: str = None):
self.id = id
self.app_id = app_id
self.skill_endpoint = skill_endpoint
| class Botframeworkskill:
"""
Registration for a BotFrameworkHttpProtocol based Skill endpoint.
"""
def __init__(self, id: str=None, app_id: str=None, skill_endpoint: str=None):
self.id = id
self.app_id = app_id
self.skill_endpoint = skill_endpoint |
#Programming Part variables
#kinect_add = "./x64/Release/AzureKinectDK.exe"
kinect_add = "C:/Users/User/Desktop/EVCIDNet-master/x64/Release/AzureKinectDK.exe"
result_add = "./AzureKinectDK/output/result.txt"
flag1_add = "./AzureKinectDK/output/flag1.txt" #image capture start flag
flag2_add = "./AzureKinectDK/output/flag2.txt" #image capture finish flag
flag3_add = "./AzureKinectDK/output/flag3.txt" #camera turn off and program terminate flag
flag = [flag1_add, flag2_add, flag3_add]
color_addr = "./AzureKinectDK/output/color.png"
point_addr = "./AzureKinectDK/output/point.png"
json_addr = "./AzureKinectDK/output/demo.json"
json_dict = {"licenses": [{"name": "", "id": 0, "url": ""}],
"info": {"contributor": "", "date_created": "", "description": "", "url": "", "version": "", "year": ""},
"categories": [{"id": 1, "name": "HolePairLeft", "supercategory": ""},
{"id": 2, "name": "HolePairRight", "supercategory": ""},
{"id": 3, "name": "ACHole", "supercategory": ""}],
"images": [], "annotations": []}
Error_coordinate = [[77777 for i in range(3)] for i in range(3)]
#Communication Part variables
regiaddrX1 = 8
regiaddrY1 = 9
regiaddrZ1 = 10
regiaddrX2 = 11
regiaddrY2 = 12
regiaddrZ2 = 13
regiaddrX3 = 14
regiaddrY3 = 15
regiaddrZ3 = 18
regiaddrC = 19
regiaddr = [regiaddrX1,regiaddrY1,regiaddrZ1,regiaddrX2,regiaddrY2,regiaddrZ2,regiaddrX3,regiaddrY3,regiaddrZ3,regiaddrC]
robot_addr = "192.168.137.100"
port_num = 502
offset = 32768 #int 16 max range
flag1_signal = 1
flag3_signal = 0
#confirm_signal = "C"
#terminate_signal = "D" | kinect_add = 'C:/Users/User/Desktop/EVCIDNet-master/x64/Release/AzureKinectDK.exe'
result_add = './AzureKinectDK/output/result.txt'
flag1_add = './AzureKinectDK/output/flag1.txt'
flag2_add = './AzureKinectDK/output/flag2.txt'
flag3_add = './AzureKinectDK/output/flag3.txt'
flag = [flag1_add, flag2_add, flag3_add]
color_addr = './AzureKinectDK/output/color.png'
point_addr = './AzureKinectDK/output/point.png'
json_addr = './AzureKinectDK/output/demo.json'
json_dict = {'licenses': [{'name': '', 'id': 0, 'url': ''}], 'info': {'contributor': '', 'date_created': '', 'description': '', 'url': '', 'version': '', 'year': ''}, 'categories': [{'id': 1, 'name': 'HolePairLeft', 'supercategory': ''}, {'id': 2, 'name': 'HolePairRight', 'supercategory': ''}, {'id': 3, 'name': 'ACHole', 'supercategory': ''}], 'images': [], 'annotations': []}
error_coordinate = [[77777 for i in range(3)] for i in range(3)]
regiaddr_x1 = 8
regiaddr_y1 = 9
regiaddr_z1 = 10
regiaddr_x2 = 11
regiaddr_y2 = 12
regiaddr_z2 = 13
regiaddr_x3 = 14
regiaddr_y3 = 15
regiaddr_z3 = 18
regiaddr_c = 19
regiaddr = [regiaddrX1, regiaddrY1, regiaddrZ1, regiaddrX2, regiaddrY2, regiaddrZ2, regiaddrX3, regiaddrY3, regiaddrZ3, regiaddrC]
robot_addr = '192.168.137.100'
port_num = 502
offset = 32768
flag1_signal = 1
flag3_signal = 0 |
#!/usr/bin/env python
##########################################################################################
##########################################################################################
##########################################################################################
# IF YOU ARE DOING THE NEW STARTER TRAINING
#
# DO NOT COPY THIS CODE, DO NOT "TAKE INSPIRATION FROM THIS CODE"
#
# YOU SHOULD WRITE YOUR OWN CODE AND DEVELOP YOUR OWN ALGORITHM FOR THE CONVERTERS
##########################################################################################
##########################################################################################
##########################################################################################
def to_arabic_number(roman_numeral: str) -> int:
src_roman_numeral = roman_numeral
# print(f"convert to_arabic_number {roman_numeral} into arabic number")
arabic_number = 0
numerals = {
"M": 1000,
"CM": 900,
"D": 500,
"CD": 400,
"C": 100,
"XC": 90,
"L": 50,
"XL": 40,
"X": 10,
"IX": 9,
"V": 5,
"IV": 4,
"I": 1
}
# print(f"1) Check numerals in order of size {numerals}")
for numeral in numerals:
numeral_value = numerals[numeral]
# print(f" 2) Check for repeated {numeral} ({numeral_value})")
while roman_numeral.startswith(numeral):
# print(f" 3) When found {numeral}, add {numeral_value}, remove {numeral} from current str {roman_numeral}")
arabic_number += numeral_value
roman_numeral = roman_numeral[len(numeral):]
# print(f" 4) Current arabic number is {arabic_number}, numeral left to parse is {roman_numeral}")
# print(f"to_arabic_number({src_roman_numeral}) is {arabic_number}")
return arabic_number
def to_roman_numeral(arabic_number: int) -> str:
src_arabic_number = arabic_number
# print(f"convert to_roman_numeral {arabic_number} into roman numeral")
roman_numeral = ""
numerals = {
"M": 1000,
"CM": 900,
"D": 500,
"CD": 400,
"C": 100,
"XC": 90,
"L": 50,
"XL": 40,
"X": 10,
"IX": 9,
"V": 5,
"IV": 4,
"I": 1
}
# print(f"1) Check numerals in order of size {numerals}")
for numeral in numerals:
numeral_value = numerals[numeral]
# print(f" 2) Check for repeated {numeral} ({numeral_value})")
while arabic_number >= numeral_value:
# print(f" 3) When found {numeral}, remove {numeral_value}, add {numeral} to {roman_numeral} from current number {arabic_number}")
roman_numeral += numeral
arabic_number -= numeral_value
# print(f" 4) Current numeral is {roman_numeral}, arabic number left to parse is {arabic_number}")
# print(f"to_roman_numeral({src_arabic_number}) is {roman_numeral}")
return roman_numeral
#
# print("""generating pseudo code for training
# =====================
#
# """)
#
# print("""
# Roman to Arabic Pseudo Code
# =====================================""")
# output = to_arabic_number('MCDIV')
# print(output)
#
# print("""
# Arabic to Roman Pseudo Code
# =====================================""")
# output = to_roman_numeral(2456)
#
# print(output) | def to_arabic_number(roman_numeral: str) -> int:
src_roman_numeral = roman_numeral
arabic_number = 0
numerals = {'M': 1000, 'CM': 900, 'D': 500, 'CD': 400, 'C': 100, 'XC': 90, 'L': 50, 'XL': 40, 'X': 10, 'IX': 9, 'V': 5, 'IV': 4, 'I': 1}
for numeral in numerals:
numeral_value = numerals[numeral]
while roman_numeral.startswith(numeral):
arabic_number += numeral_value
roman_numeral = roman_numeral[len(numeral):]
return arabic_number
def to_roman_numeral(arabic_number: int) -> str:
src_arabic_number = arabic_number
roman_numeral = ''
numerals = {'M': 1000, 'CM': 900, 'D': 500, 'CD': 400, 'C': 100, 'XC': 90, 'L': 50, 'XL': 40, 'X': 10, 'IX': 9, 'V': 5, 'IV': 4, 'I': 1}
for numeral in numerals:
numeral_value = numerals[numeral]
while arabic_number >= numeral_value:
roman_numeral += numeral
arabic_number -= numeral_value
return roman_numeral |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''conftest.py for cpac.
Read more about conftest.py under:
https://pytest.org/latest/plugins.html
'''
# import pytest
def pytest_addoption(parser):
parser.addoption('--platform', action='store', nargs=1, default=[])
parser.addoption('--tag', action='store', nargs=1, default=[])
def pytest_generate_tests(metafunc):
# This is called for every test. Only get/set command line arguments
# if the argument is specified in the list of test 'fixturenames'.
platform = metafunc.config.option.platform
tag = metafunc.config.option.tag
if 'platform' in metafunc.fixturenames:
metafunc.parametrize('platform', platform)
if 'tag' in metafunc.fixturenames:
metafunc.parametrize('tag', tag)
| """conftest.py for cpac.
Read more about conftest.py under:
https://pytest.org/latest/plugins.html
"""
def pytest_addoption(parser):
parser.addoption('--platform', action='store', nargs=1, default=[])
parser.addoption('--tag', action='store', nargs=1, default=[])
def pytest_generate_tests(metafunc):
platform = metafunc.config.option.platform
tag = metafunc.config.option.tag
if 'platform' in metafunc.fixturenames:
metafunc.parametrize('platform', platform)
if 'tag' in metafunc.fixturenames:
metafunc.parametrize('tag', tag) |
# last data structure
# Sets are unorded collection of unique objects
my_set = {1, 2, 4, 4, 5, 5, 5, 4, 3, 3}
print(my_set)
# useful methods
new_set = my_set.copy()
print(new_set)
my_set.add(100)
print(my_set)
| my_set = {1, 2, 4, 4, 5, 5, 5, 4, 3, 3}
print(my_set)
new_set = my_set.copy()
print(new_set)
my_set.add(100)
print(my_set) |
text = "PER"
s = input()
n = 0
d = 0
for i in s:
if n > 2:
n = 0
if i != text[n]:
d += 1
n += 1
print(d) | text = 'PER'
s = input()
n = 0
d = 0
for i in s:
if n > 2:
n = 0
if i != text[n]:
d += 1
n += 1
print(d) |
def sum_list(lst):
my_list = lst
if len(my_list) == 1:
return my_list[0]
return my_list[0] + sum_list(my_list[1:])
lst = [1,2,3,4]
print(sum_list(lst))
| def sum_list(lst):
my_list = lst
if len(my_list) == 1:
return my_list[0]
return my_list[0] + sum_list(my_list[1:])
lst = [1, 2, 3, 4]
print(sum_list(lst)) |
# path to folder with data
BASEPATH = '/home/michal/Develop/oshiftdata/'
# name of the Elasticsearch index
INDEX_NAME = 'pagesbtext'
# type of the Elasticsearch index
INDEX_TYPE = 'page'
# host address of MongoDB
MONGODB_HOST = "127.0.1.1"
# port of MongoDB
MONGODB_PORT = 27017
# name of MongoDB database
MONGODB_DB = "skool"
# name of collection, where bodytexts are saved
MONGODB_COLLECTION = "page"
# username for accessing database
MONGODB_USER = None
# password for accessing database
MONGODB_PASS = None
# ELASTIC_HOST
# ELASTIC_PORT
# url on which classification server will listen
URL = "localhost"
# port on which classification server will listen
PORT = 8001
# connection string to classification server
CSTRING = "http://localhost:8001"
# filenames of files with serialized model
DEFAULT_FILENAMES = {
'CountVectorizer': 'cv',
'TfIdf': 'tfidf',
'Classifier': 'cls',
'MultiLabelBinarizer': 'mlb'
}
| basepath = '/home/michal/Develop/oshiftdata/'
index_name = 'pagesbtext'
index_type = 'page'
mongodb_host = '127.0.1.1'
mongodb_port = 27017
mongodb_db = 'skool'
mongodb_collection = 'page'
mongodb_user = None
mongodb_pass = None
url = 'localhost'
port = 8001
cstring = 'http://localhost:8001'
default_filenames = {'CountVectorizer': 'cv', 'TfIdf': 'tfidf', 'Classifier': 'cls', 'MultiLabelBinarizer': 'mlb'} |
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
res = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 1:
if i == 0:
res += 1
if i == len(grid) - 1:
res += 1
if i > 0 and grid[i - 1][j] == 0:
res += 1
if i < len(grid) - 1 and grid[i + 1][j] == 0:
res += 1
if j == 0:
res += 1
if j == len(grid[i]) - 1:
res += 1
if j > 0 and grid[i][j - 1] == 0:
res += 1
if j < len(grid[i]) - 1 and grid[i][j + 1] == 0:
res += 1
return res
def test_island_perimeter():
assert 16 == Solution().islandPerimeter([[0, 1, 0, 0],
[1, 1, 1, 0],
[0, 1, 0, 0],
[1, 1, 0, 0]])
assert 4 == Solution().islandPerimeter([[1]])
assert 4 == Solution().islandPerimeter([[1, 0]])
| class Solution(object):
def island_perimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
res = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 1:
if i == 0:
res += 1
if i == len(grid) - 1:
res += 1
if i > 0 and grid[i - 1][j] == 0:
res += 1
if i < len(grid) - 1 and grid[i + 1][j] == 0:
res += 1
if j == 0:
res += 1
if j == len(grid[i]) - 1:
res += 1
if j > 0 and grid[i][j - 1] == 0:
res += 1
if j < len(grid[i]) - 1 and grid[i][j + 1] == 0:
res += 1
return res
def test_island_perimeter():
assert 16 == solution().islandPerimeter([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]])
assert 4 == solution().islandPerimeter([[1]])
assert 4 == solution().islandPerimeter([[1, 0]]) |
class Solution:
def uniquePaths(self, m: int, n: int) -> int:
if m <= 0 or n <= 0:
raise Exception("Invalid Matrix Size")
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = 1
elif i == 0 and j != 0:
dp[i][j] = dp[i][j - 1]
elif i != 0 and j == 0:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = dp[i][j - 1] + dp[i - 1][j]
return dp[-1][-1]
| class Solution:
def unique_paths(self, m: int, n: int) -> int:
if m <= 0 or n <= 0:
raise exception('Invalid Matrix Size')
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = 1
elif i == 0 and j != 0:
dp[i][j] = dp[i][j - 1]
elif i != 0 and j == 0:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = dp[i][j - 1] + dp[i - 1][j]
return dp[-1][-1] |
honored_guest = ['YULIU', 'Jim', 'Shi']
print(honored_guest[0] + ' and ' + honored_guest[1] + ' and ' + honored_guest[2] + ' ' + "eat dinner")
print("Shi cannot come here to eat dinner")
honored_guest.sort()
print(honored_guest)
honored_guest.remove('Shi')
print(honored_guest) | honored_guest = ['YULIU', 'Jim', 'Shi']
print(honored_guest[0] + ' and ' + honored_guest[1] + ' and ' + honored_guest[2] + ' ' + 'eat dinner')
print('Shi cannot come here to eat dinner')
honored_guest.sort()
print(honored_guest)
honored_guest.remove('Shi')
print(honored_guest) |
n=[5,6,7] # Atomic valences
nc=[5,6,7] # Atomic valences
l=2 # Orbital angular momentum of the shel
J=0.79 # Slatter integrals F2=J*11.9219653179191 from the atomic physics program, must check this for Fe as I just used Haule's value for Mn here
cx=0.0 # 0.052 # spin-orbit coupling from the atomic physics program
qOCA=1 # OCA diagrams are computes in addition to NCA diagrams
Eoca=1. # If the atomi energy of any state, involved in the diagram, is higher that Eoca from the ground state, the diagram ms is neglected
mOCA=1e-3 # If maxtrix element of OCA diagram is smaller, it is neglected
Ncentral=[6] # OCA diagrams are selected such that central occupancy is in Ncentral
Ex=[0.5,0.5,0.5] # Energy window treated exactly - relevant only in magnetic state
Ep=[3.0,3.0,3.0] # Energy window treated approximately
qatom=0
| n = [5, 6, 7]
nc = [5, 6, 7]
l = 2
j = 0.79
cx = 0.0
q_oca = 1
eoca = 1.0
m_oca = 0.001
ncentral = [6]
ex = [0.5, 0.5, 0.5]
ep = [3.0, 3.0, 3.0]
qatom = 0 |
count_sum_1 = 0
count_sum_2 = 0
with open('input', 'r') as f:
groups = f.read().split('\n\n')
# Part One
for group in groups:
yes_set = set(group.strip())
if '\n' in yes_set:
yes_set.remove('\n')
yes_count = len(yes_set)
# print(f'yes_count = {yes_count}, yes_set = {yes_set}')
count_sum_1 += yes_count
print(f'count_sum_1 = {count_sum_1}')
# Part Two
for group in groups:
group = group.strip().split('\n')
ques_set = set(group[0])
if len(group) == 1:
ques_count = len(ques_set)
else:
for g in group:
ques_set = ques_set.intersection(set(g))
ques_count = len(ques_set)
# print(f'ques_count = {ques_count}, ques_set = {ques_set}')
count_sum_2 += ques_count
print(f'count_sum_2 = {count_sum_2}')
| count_sum_1 = 0
count_sum_2 = 0
with open('input', 'r') as f:
groups = f.read().split('\n\n')
for group in groups:
yes_set = set(group.strip())
if '\n' in yes_set:
yes_set.remove('\n')
yes_count = len(yes_set)
count_sum_1 += yes_count
print(f'count_sum_1 = {count_sum_1}')
for group in groups:
group = group.strip().split('\n')
ques_set = set(group[0])
if len(group) == 1:
ques_count = len(ques_set)
else:
for g in group:
ques_set = ques_set.intersection(set(g))
ques_count = len(ques_set)
count_sum_2 += ques_count
print(f'count_sum_2 = {count_sum_2}') |
def wordPattern(self, pattern: str, str: str) -> bool:
m = {}
words = str.split()
if len(pattern) != len(words):
return False
result = True
for i in range(len(pattern)):
if pattern[i] not in m:
if words[i] in m.values():
return False
m[pattern[i]] = words[i]
elif m[pattern[i]] != words[i]:
result = False
return result | def word_pattern(self, pattern: str, str: str) -> bool:
m = {}
words = str.split()
if len(pattern) != len(words):
return False
result = True
for i in range(len(pattern)):
if pattern[i] not in m:
if words[i] in m.values():
return False
m[pattern[i]] = words[i]
elif m[pattern[i]] != words[i]:
result = False
return result |
class ParseError(RuntimeError):
"""Exception to raise when parsing fails."""
class SyncError(RuntimeError):
"""Error class for general errors relating to the project sync process."""
| class Parseerror(RuntimeError):
"""Exception to raise when parsing fails."""
class Syncerror(RuntimeError):
"""Error class for general errors relating to the project sync process.""" |
# -*- coding: utf-8 -*-
"""
idfy_rest_client.models.file_format_331
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class FileFormat331(object):
"""Implementation of the 'fileFormat331' enum.
TODO: type enum description here.
Attributes:
ENUM_NATIVE: TODO: type description here.
PACKAGED: TODO: type description here.
"""
ENUM_NATIVE = 'native'
PACKAGED = 'packaged'
| """
idfy_rest_client.models.file_format_331
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
class Fileformat331(object):
"""Implementation of the 'fileFormat331' enum.
TODO: type enum description here.
Attributes:
ENUM_NATIVE: TODO: type description here.
PACKAGED: TODO: type description here.
"""
enum_native = 'native'
packaged = 'packaged' |
#!usr/bin/python3.4
#!/usr/bin/python3.4
# Problem Set 0
# Name: xin zhong
# Collaborators:
# Time: 8:58-9:03
#
last_name = input("Enter your last name:\n**")
first_name = input("Enter your first name:\n**")
print(first_name)
print(last_name)
| last_name = input('Enter your last name:\n**')
first_name = input('Enter your first name:\n**')
print(first_name)
print(last_name) |
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
ans = []
cols = [False] * n
diag1 = [False] * (2 * n - 1)
diag2 = [False] * (2 * n - 1)
def dfs(i: int, board: List[int]) -> None:
if i == n:
ans.append(board)
return
for j in range(n):
if cols[j] or diag1[i + j] or diag2[j - i + n - 1]:
continue
cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True
dfs(i + 1, board + ['.' * j + 'Q' + '.' * (n - j - 1)])
cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False
dfs(0, [])
return ans
| class Solution:
def solve_n_queens(self, n: int) -> List[List[str]]:
ans = []
cols = [False] * n
diag1 = [False] * (2 * n - 1)
diag2 = [False] * (2 * n - 1)
def dfs(i: int, board: List[int]) -> None:
if i == n:
ans.append(board)
return
for j in range(n):
if cols[j] or diag1[i + j] or diag2[j - i + n - 1]:
continue
cols[j] = diag1[i + j] = diag2[j - i + n - 1] = True
dfs(i + 1, board + ['.' * j + 'Q' + '.' * (n - j - 1)])
cols[j] = diag1[i + j] = diag2[j - i + n - 1] = False
dfs(0, [])
return ans |
var = 'foo'
def ex2():
var = 'bar'
print('inside the function var is ', var)
ex2()
print('outside the function var is ', var)
# should be bar, foo
| var = 'foo'
def ex2():
var = 'bar'
print('inside the function var is ', var)
ex2()
print('outside the function var is ', var) |
class Hello:
def __init__(self, name):
self.name = name
def greeting(self):
print(f'Hello {self.name}') | class Hello:
def __init__(self, name):
self.name = name
def greeting(self):
print(f'Hello {self.name}') |
listA = [1]
listB = [1, 2, 3, 4, listA]
listC = [1]
listB *= 3
print(listB)
print(listB[9] == listA)
print(listB[4] is listA)
print(listB[9] is listA)
print(listB[9] is listC)
print('-------------------------')
print(listB.count(listA))
print(listB.count(listC))
print(listB.index(listC, 5))
print(listB.index(listC, 5, 10))
print('-------------------------')
listA *= 3
print(listB)
| list_a = [1]
list_b = [1, 2, 3, 4, listA]
list_c = [1]
list_b *= 3
print(listB)
print(listB[9] == listA)
print(listB[4] is listA)
print(listB[9] is listA)
print(listB[9] is listC)
print('-------------------------')
print(listB.count(listA))
print(listB.count(listC))
print(listB.index(listC, 5))
print(listB.index(listC, 5, 10))
print('-------------------------')
list_a *= 3
print(listB) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright SquirrelNetwork
def string_generator(data_incoming):
data = data_incoming.copy()
del data['hash']
keys = sorted(data.keys())
string_arr = []
for key in keys:
string_arr.append(key+'='+data[key])
string_cat = '\n'.join(string_arr)
return string_cat | def string_generator(data_incoming):
data = data_incoming.copy()
del data['hash']
keys = sorted(data.keys())
string_arr = []
for key in keys:
string_arr.append(key + '=' + data[key])
string_cat = '\n'.join(string_arr)
return string_cat |
class UWB (Radio):
"""
Abstracts all communication over UWB
options include:
Ranging frequency | range after message
"""
def __init__(self):
self._name = 'UWB'
pass
# | class Uwb(Radio):
"""
Abstracts all communication over UWB
options include:
Ranging frequency | range after message
"""
def __init__(self):
self._name = 'UWB'
pass |
def fizzbuzz(x):
if x % 3 == 0 and x % 5 != 0:
r = 'Fizz'
elif x % 3 != 0 and x % 5 ==0:
r = 'Buzz'
elif x % 3 == 0 and x % 5 ==0:
r = 'FizzBuzz'
else:
r = x
return r | def fizzbuzz(x):
if x % 3 == 0 and x % 5 != 0:
r = 'Fizz'
elif x % 3 != 0 and x % 5 == 0:
r = 'Buzz'
elif x % 3 == 0 and x % 5 == 0:
r = 'FizzBuzz'
else:
r = x
return r |
class Tile:
def __init__(self):
self.first_visit = True
self.tree_fallen = False
def describe(self):
print("You are walking through the trees. It looks like the path on "
"your west leads to a small wooden hut.\n")
if not self.first_visit and not self.tree_fallen:
print("You saw a tree fall and it didn't make any sound and "
"WOW... that was weird because you were there and "
"observed it!\n")
self.tree_fallen = True
self.first_visit = False
# "If a tree falls in a forest and no one is around to hear it,
# does it make a sound?" is a philosophical thought experiment that
# raises questions regarding observation and knowledge of reality.
def action(self, player, do):
print("Wat?!")
def leave(self, player, direction):
if direction == "s":
print("Careful now! Nasty rocks all over to the south.\n"
"(Meaning you just can't go to that direction. Sorry!)")
return False
else:
return True
| class Tile:
def __init__(self):
self.first_visit = True
self.tree_fallen = False
def describe(self):
print('You are walking through the trees. It looks like the path on your west leads to a small wooden hut.\n')
if not self.first_visit and (not self.tree_fallen):
print("You saw a tree fall and it didn't make any sound and WOW... that was weird because you were there and observed it!\n")
self.tree_fallen = True
self.first_visit = False
def action(self, player, do):
print('Wat?!')
def leave(self, player, direction):
if direction == 's':
print("Careful now! Nasty rocks all over to the south.\n(Meaning you just can't go to that direction. Sorry!)")
return False
else:
return True |
#!/usr/bin/python3
"""matrix multiplication"""
def matrix_mul(m_a, m_b):
"""matrix multiplication"""
if not isinstance(m_a, list):
raise TypeError("m_a must be a list")
elif not isinstance(m_b, list):
raise TypeError("m_b must be a list")
elif not all(isinstance(row, list) for row in m_a):
raise TypeError("m_a must be a list of lists")
elif not all(isinstance(row, list) for row in m_b):
raise TypeError("m_b must be a list of lists")
elif m_a == [] or m_a == [[]]:
raise ValueError("m_a can't be empty")
elif m_b == [] or m_b == [[]]:
raise ValueError("m_b can't be empty")
elif not all((isinstance(ele, int) or isinstance(ele, float))
for ele in [x for row in m_a for x in row]):
raise TypeError("m_a should contain only integers or floats")
elif not all((isinstance(ele, int) or isinstance(ele, float))
for ele in [x for row in m_b for x in row]):
raise TypeError("m_b should contain only integers or floats")
if not all(len(row) == len(m_a[0]) for row in m_a):
raise TypeError("each row of m_a must be of the same size")
if not all(len(row) == len(m_b[0]) for row in m_b):
raise TypeError("each row of m_b must be of the same size")
if len(m_a[0]) != len(m_b):
raise ValueError("m_a and m_b can't be multiplied")
inverted_b = []
for row in range(len(m_b[0])):
new_row = []
for column in range(len(m_b)):
new_row.append(m_b[column][row])
inverted_b.append(new_row)
new_matrix = []
for row in m_a:
new_row = []
for col in inverted_b:
prod = 0
for i in range(len(inverted_b[0])):
prod += row[i] * col[i]
new_row.append(prod)
new_matrix.append(new_row)
return new_matrix
| """matrix multiplication"""
def matrix_mul(m_a, m_b):
"""matrix multiplication"""
if not isinstance(m_a, list):
raise type_error('m_a must be a list')
elif not isinstance(m_b, list):
raise type_error('m_b must be a list')
elif not all((isinstance(row, list) for row in m_a)):
raise type_error('m_a must be a list of lists')
elif not all((isinstance(row, list) for row in m_b)):
raise type_error('m_b must be a list of lists')
elif m_a == [] or m_a == [[]]:
raise value_error("m_a can't be empty")
elif m_b == [] or m_b == [[]]:
raise value_error("m_b can't be empty")
elif not all((isinstance(ele, int) or isinstance(ele, float) for ele in [x for row in m_a for x in row])):
raise type_error('m_a should contain only integers or floats')
elif not all((isinstance(ele, int) or isinstance(ele, float) for ele in [x for row in m_b for x in row])):
raise type_error('m_b should contain only integers or floats')
if not all((len(row) == len(m_a[0]) for row in m_a)):
raise type_error('each row of m_a must be of the same size')
if not all((len(row) == len(m_b[0]) for row in m_b)):
raise type_error('each row of m_b must be of the same size')
if len(m_a[0]) != len(m_b):
raise value_error("m_a and m_b can't be multiplied")
inverted_b = []
for row in range(len(m_b[0])):
new_row = []
for column in range(len(m_b)):
new_row.append(m_b[column][row])
inverted_b.append(new_row)
new_matrix = []
for row in m_a:
new_row = []
for col in inverted_b:
prod = 0
for i in range(len(inverted_b[0])):
prod += row[i] * col[i]
new_row.append(prod)
new_matrix.append(new_row)
return new_matrix |
#!/usr/bin/python3
with open('input.txt') as f:
input = list(map(int, f.read().splitlines()))
PREMABLE_LENGTH = 25
idx = PREMABLE_LENGTH
while idx < len(input):
section = input[idx - PREMABLE_LENGTH:idx]
target = input[idx]
found = False
for i, j in enumerate(section):
if target - j in section[i+1:]:
idx += 1
found = True
break
if not found:
print(target)
break
invalid = input[idx]
section = input[:idx]
start = 0
end = 1
tot = sum(section[start:end])
while tot != invalid:
if tot < invalid:
end += 1
if tot > invalid:
start += 1
tot = sum(section[start:end])
print(min(section[start:end]) + max(section[start:end]))
| with open('input.txt') as f:
input = list(map(int, f.read().splitlines()))
premable_length = 25
idx = PREMABLE_LENGTH
while idx < len(input):
section = input[idx - PREMABLE_LENGTH:idx]
target = input[idx]
found = False
for (i, j) in enumerate(section):
if target - j in section[i + 1:]:
idx += 1
found = True
break
if not found:
print(target)
break
invalid = input[idx]
section = input[:idx]
start = 0
end = 1
tot = sum(section[start:end])
while tot != invalid:
if tot < invalid:
end += 1
if tot > invalid:
start += 1
tot = sum(section[start:end])
print(min(section[start:end]) + max(section[start:end])) |
FRAGMENT_LOG = '''
fragment fragmentLog on Log {
id_
level
message
time
}
'''
| fragment_log = '\nfragment fragmentLog on Log {\n id_\n level\n message\n time\n}\n' |
def LevenshteinDistance(v, w):
v = '-' + v
w = '-' + w
S = [[0 for i in range(len(w))] for j in range(len(v))]
for i in range(1, len(S)):
S[i][0] = S[i - 1][0] + 1
for j in range(1, len(S[0])):
S[0][j] = S[0][j - 1] + 1
for i in range(1, len(v)):
for j in range(1, len(w)):
diag = S[i - 1][j - 1] + (1 if v[i] != w[j] else 0)
down = S[i - 1][j] + 1
right = S[i][j - 1] + 1
S[i][j] = min([down, right, diag])
return S[len(v) - 1][len(w) - 1]
if __name__ == "__main__":
v = input().rstrip()
w = input().rstrip()
print(LevenshteinDistance(v, w)) | def levenshtein_distance(v, w):
v = '-' + v
w = '-' + w
s = [[0 for i in range(len(w))] for j in range(len(v))]
for i in range(1, len(S)):
S[i][0] = S[i - 1][0] + 1
for j in range(1, len(S[0])):
S[0][j] = S[0][j - 1] + 1
for i in range(1, len(v)):
for j in range(1, len(w)):
diag = S[i - 1][j - 1] + (1 if v[i] != w[j] else 0)
down = S[i - 1][j] + 1
right = S[i][j - 1] + 1
S[i][j] = min([down, right, diag])
return S[len(v) - 1][len(w) - 1]
if __name__ == '__main__':
v = input().rstrip()
w = input().rstrip()
print(levenshtein_distance(v, w)) |
"""Collection of small helper functions"""
def create_singleton(name):
"""Helper function to create a singleton class"""
type_dict = {'__slots__': (), '__str__': lambda self: name, '__repr__': lambda self: name}
return type(name, (object,), type_dict)() | """Collection of small helper functions"""
def create_singleton(name):
"""Helper function to create a singleton class"""
type_dict = {'__slots__': (), '__str__': lambda self: name, '__repr__': lambda self: name}
return type(name, (object,), type_dict)() |
DEBUG = False
def set_verbose(value: bool) -> None:
"""Change the DEBUG value to be verbose or not.
Args:
value (bool): Verbosity on or off.
"""
global DEBUG
DEBUG = value
def log(message: str) -> None:
"""Logs the message to stdout if DEBUG is enabled.
Args:
message (str): Message to be logged.
"""
global DEBUG
if DEBUG:
print(message)
| debug = False
def set_verbose(value: bool) -> None:
"""Change the DEBUG value to be verbose or not.
Args:
value (bool): Verbosity on or off.
"""
global DEBUG
debug = value
def log(message: str) -> None:
"""Logs the message to stdout if DEBUG is enabled.
Args:
message (str): Message to be logged.
"""
global DEBUG
if DEBUG:
print(message) |
with open("water.in", "r") as input_file:
input_list = [line.strip() for line in input_file]
with open("water.out", "w") as output_file:
for binary_diameter in input_list:
print(round((2/3 * 3.14 * (int(binary_diameter, 2) ** 3)) / 1000), file=output_file)
| with open('water.in', 'r') as input_file:
input_list = [line.strip() for line in input_file]
with open('water.out', 'w') as output_file:
for binary_diameter in input_list:
print(round(2 / 3 * 3.14 * int(binary_diameter, 2) ** 3 / 1000), file=output_file) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2016 Vobile Inc. All Rights Reserved.
Author: xu_xiaorong
Email: xu_xiaorong@mycompany.cn
Created_at: 2016-08-10 13:46:10
'''
LOG_HANDLER = None # None means stdout, syslog means syslog
LOG_LEVEL = 'INFO'
QUEUE_NAME = "querier_queue"
QUEUE_EXCHANGE = "querier_exchange"
QUEUE_ROUTING_KEY = "querier_routing_key"
MATCH_THRESHOLD = "22 22" #"sample reference"
| """
Copyright (c) 2016 Vobile Inc. All Rights Reserved.
Author: xu_xiaorong
Email: xu_xiaorong@mycompany.cn
Created_at: 2016-08-10 13:46:10
"""
log_handler = None
log_level = 'INFO'
queue_name = 'querier_queue'
queue_exchange = 'querier_exchange'
queue_routing_key = 'querier_routing_key'
match_threshold = '22 22' |
def get_unithash(n: int):
int(n)
if (n == 0):
return 0
elif (n % 9 == 0):
return 9
else:
return n % 9
def set_unithash(num: str, l: int):
sanitation=[]
sanitation[:0]=num
for i in range(0,len(sanitation)):
if (sanitation[i].isdigit())==False:
sanitation[i]=abs(ord(sanitation[i])-96)
num = ''.join([str(j) for j in sanitation])
hash = [(num[i:i+int(l)]) for i in range(0, len(num), int(l))]
final_hash = []
for i in range(0,len(hash)):
final_hash.append(get_unithash(int(hash[i])))
fin_hash = ''.join([str(i) for i in final_hash])
return int(fin_hash)
#l = length of each group after number is broken
#num = the actual number to be hashed | def get_unithash(n: int):
int(n)
if n == 0:
return 0
elif n % 9 == 0:
return 9
else:
return n % 9
def set_unithash(num: str, l: int):
sanitation = []
sanitation[:0] = num
for i in range(0, len(sanitation)):
if sanitation[i].isdigit() == False:
sanitation[i] = abs(ord(sanitation[i]) - 96)
num = ''.join([str(j) for j in sanitation])
hash = [num[i:i + int(l)] for i in range(0, len(num), int(l))]
final_hash = []
for i in range(0, len(hash)):
final_hash.append(get_unithash(int(hash[i])))
fin_hash = ''.join([str(i) for i in final_hash])
return int(fin_hash) |
american_holidays = """1,2012-01-02,New Year Day
2,2012-01-16,Martin Luther King Jr. Day
3,2012-02-20,Presidents Day (Washingtons Birthday)
4,2012-05-28,Memorial Day
5,2012-07-04,Independence Day
6,2012-09-03,Labor Day
7,2012-10-08,Columbus Day
8,2012-11-12,Veterans Day
9,2012-11-22,Thanksgiving Day
10,2012-12-25,Christmas Day
11,2013-01-01,New Year Day
12,2013-01-21,Martin Luther King Jr. Day
13,2013-02-18,Presidents Day (Washingtons Birthday)
14,2013-05-27,Memorial Day
15,2013-07-04,Independence Day
16,2013-09-02,Labor Day
17,2013-10-14,Columbus Day
18,2013-11-11,Veterans Day
19,2013-11-28,Thanksgiving Day
20,2013-12-25,Christmas Day
21,2014-01-01,New Year Day
22,2014-01-20,Martin Luther King Jr. Day
23,2014-02-17,Presidents Day (Washingtons Birthday)
24,2014-05-26,Memorial Day
25,2014-07-04,Independence Day
26,2014-09-01,Labor Day
27,2014-10-13,Columbus Day
28,2014-11-11,Veterans Day
29,2014-11-27,Thanksgiving Day
30,2014-12-25,Christmas Day
31,2015-01-01,New Year Day
32,2015-01-19,Martin Luther King Jr. Day
33,2015-02-16,Presidents Day (Washingtons Birthday)
34,2015-05-25,Memorial Day
35,2015-07-03,Independence Day
36,2015-09-07,Labor Day
37,2015-10-12,Columbus Day
38,2015-11-11,Veterans Day
39,2015-11-26,Thanksgiving Day
40,2015-12-25,Christmas Day
41,2016-01-01,New Year Day
42,2016-01-18,Martin Luther King Jr. Day
43,2016-02-15,Presidents Day (Washingtons Birthday)
44,2016-05-30,Memorial Day
45,2016-07-04,Independence Day
46,2016-09-05,Labor Day
47,2016-10-10,Columbus Day
48,2016-11-11,Veterans Day
49,2016-11-24,Thanksgiving Day
50,2016-12-25,Christmas Day
51,2017-01-02,New Year Day
52,2017-01-16,Martin Luther King Jr. Day
53,2017-02-20,Presidents Day (Washingtons Birthday)
54,2017-05-29,Memorial Day
55,2017-07-04,Independence Day
56,2017-09-04,Labor Day
57,2017-10-09,Columbus Day
58,2017-11-10,Veterans Day
59,2017-11-23,Thanksgiving Day
60,2017-12-25,Christmas Day
61,2018-01-01,New Year Day
62,2018-01-15,Martin Luther King Jr. Day
63,2018-02-19,Presidents Day (Washingtons Birthday)
64,2018-05-28,Memorial Day
65,2018-07-04,Independence Day
66,2018-09-03,Labor Day
67,2018-10-08,Columbus Day
68,2018-11-12,Veterans Day
69,2018-11-22,Thanksgiving Day
70,2018-12-25,Christmas Day
71,2019-01-01,New Year Day
72,2019-01-21,Martin Luther King Jr. Day
73,2019-02-18,Presidents Day (Washingtons Birthday)
74,2019-05-27,Memorial Day
75,2019-07-04,Independence Day
76,2019-09-02,Labor Day
77,2019-10-14,Columbus Day
78,2019-11-11,Veterans Day
79,2019-11-28,Thanksgiving Day
80,2019-12-25,Christmas Day
81,2020-01-01,New Year Day
82,2020-01-20,Martin Luther King Jr. Day
83,2020-02-17,Presidents Day (Washingtons Birthday)
84,2020-05-25,Memorial Day
85,2020-07-03,Independence Day
86,2020-09-07,Labor Day
87,2020-10-12,Columbus Day
88,2020-11-11,Veterans Day
89,2020-11-26,Thanksgiving Day
90,2020-12-25,Christmas Day""" | american_holidays = '1,2012-01-02,New Year Day\n2,2012-01-16,Martin Luther King Jr. Day\n3,2012-02-20,Presidents Day (Washingtons Birthday)\n4,2012-05-28,Memorial Day\n5,2012-07-04,Independence Day\n6,2012-09-03,Labor Day\n7,2012-10-08,Columbus Day\n8,2012-11-12,Veterans Day\n9,2012-11-22,Thanksgiving Day\n10,2012-12-25,Christmas Day\n11,2013-01-01,New Year Day\n12,2013-01-21,Martin Luther King Jr. Day\n13,2013-02-18,Presidents Day (Washingtons Birthday)\n14,2013-05-27,Memorial Day\n15,2013-07-04,Independence Day\n16,2013-09-02,Labor Day\n17,2013-10-14,Columbus Day\n18,2013-11-11,Veterans Day\n19,2013-11-28,Thanksgiving Day\n20,2013-12-25,Christmas Day\n21,2014-01-01,New Year Day\n22,2014-01-20,Martin Luther King Jr. Day\n23,2014-02-17,Presidents Day (Washingtons Birthday)\n24,2014-05-26,Memorial Day\n25,2014-07-04,Independence Day\n26,2014-09-01,Labor Day\n27,2014-10-13,Columbus Day\n28,2014-11-11,Veterans Day\n29,2014-11-27,Thanksgiving Day\n30,2014-12-25,Christmas Day\n31,2015-01-01,New Year Day\n32,2015-01-19,Martin Luther King Jr. Day\n33,2015-02-16,Presidents Day (Washingtons Birthday)\n34,2015-05-25,Memorial Day\n35,2015-07-03,Independence Day\n36,2015-09-07,Labor Day\n37,2015-10-12,Columbus Day\n38,2015-11-11,Veterans Day\n39,2015-11-26,Thanksgiving Day\n40,2015-12-25,Christmas Day\n41,2016-01-01,New Year Day\n42,2016-01-18,Martin Luther King Jr. Day\n43,2016-02-15,Presidents Day (Washingtons Birthday)\n44,2016-05-30,Memorial Day\n45,2016-07-04,Independence Day\n46,2016-09-05,Labor Day\n47,2016-10-10,Columbus Day\n48,2016-11-11,Veterans Day\n49,2016-11-24,Thanksgiving Day\n50,2016-12-25,Christmas Day\n51,2017-01-02,New Year Day\n52,2017-01-16,Martin Luther King Jr. Day\n53,2017-02-20,Presidents Day (Washingtons Birthday)\n54,2017-05-29,Memorial Day\n55,2017-07-04,Independence Day\n56,2017-09-04,Labor Day\n57,2017-10-09,Columbus Day\n58,2017-11-10,Veterans Day\n59,2017-11-23,Thanksgiving Day\n60,2017-12-25,Christmas Day\n61,2018-01-01,New Year Day\n62,2018-01-15,Martin Luther King Jr. Day\n63,2018-02-19,Presidents Day (Washingtons Birthday)\n64,2018-05-28,Memorial Day\n65,2018-07-04,Independence Day\n66,2018-09-03,Labor Day\n67,2018-10-08,Columbus Day\n68,2018-11-12,Veterans Day\n69,2018-11-22,Thanksgiving Day\n70,2018-12-25,Christmas Day\n71,2019-01-01,New Year Day\n72,2019-01-21,Martin Luther King Jr. Day\n73,2019-02-18,Presidents Day (Washingtons Birthday)\n74,2019-05-27,Memorial Day\n75,2019-07-04,Independence Day\n76,2019-09-02,Labor Day\n77,2019-10-14,Columbus Day\n78,2019-11-11,Veterans Day\n79,2019-11-28,Thanksgiving Day\n80,2019-12-25,Christmas Day\n81,2020-01-01,New Year Day\n82,2020-01-20,Martin Luther King Jr. Day\n83,2020-02-17,Presidents Day (Washingtons Birthday)\n84,2020-05-25,Memorial Day\n85,2020-07-03,Independence Day\n86,2020-09-07,Labor Day\n87,2020-10-12,Columbus Day\n88,2020-11-11,Veterans Day\n89,2020-11-26,Thanksgiving Day\n90,2020-12-25,Christmas Day' |
# Base node class
class Node:
"""Master node class."""
def __str__(self):
return f"{type(self).__name__}"
| class Node:
"""Master node class."""
def __str__(self):
return f'{type(self).__name__}' |
class md_description:
def __init__(self, path, prefix_ref, repetion_number, title_output, total_running):
self.path = path
self.prefix_ref = prefix_ref
self.repetion_number = repetion_number
self.title_output = title_output
self.total_running = total_running
# path where MD files are
def get_path(self):
return self.path
# prefix for reference files: md for md.xtc, md.tpr and md.edr
def get_prefix_ref(self):
return self.prefix_ref
# number of MD repetion
def get_repetion_number(self):
return self.repetion_number
# title for output file name
def get_title_output(self):
return self.title_output
# total running time in ps
def get_total_running(self):
return self.total_running
# MD files must be prefix.rep. Ex: md.1, md.2
def get_simulation_prefix(self):
return str(self.get_prefix_ref()) + "." + str(self.get_repetion_number())
| class Md_Description:
def __init__(self, path, prefix_ref, repetion_number, title_output, total_running):
self.path = path
self.prefix_ref = prefix_ref
self.repetion_number = repetion_number
self.title_output = title_output
self.total_running = total_running
def get_path(self):
return self.path
def get_prefix_ref(self):
return self.prefix_ref
def get_repetion_number(self):
return self.repetion_number
def get_title_output(self):
return self.title_output
def get_total_running(self):
return self.total_running
def get_simulation_prefix(self):
return str(self.get_prefix_ref()) + '.' + str(self.get_repetion_number()) |
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
if triangle == []:
return 0
for idx in range(1, len(triangle)):
row = triangle[idx]
prev_row = triangle[idx - 1]
row[0] += prev_row[0]
row[-1] += prev_row[-1]
for idx in range(2, len(triangle)):
row = triangle[idx]
prev_row = triangle[idx - 1]
for col in range(1, len(row) - 1):
row[col] += min(prev_row[col - 1], prev_row[col])
return min(triangle[-1])
| class Solution:
def minimum_total(self, triangle: List[List[int]]) -> int:
if triangle == []:
return 0
for idx in range(1, len(triangle)):
row = triangle[idx]
prev_row = triangle[idx - 1]
row[0] += prev_row[0]
row[-1] += prev_row[-1]
for idx in range(2, len(triangle)):
row = triangle[idx]
prev_row = triangle[idx - 1]
for col in range(1, len(row) - 1):
row[col] += min(prev_row[col - 1], prev_row[col])
return min(triangle[-1]) |
# -*- coding: utf-8 -*-
AMOUNT_INDEX = 0
TYPE_INDEX = 1
RAT_TYPE = 'R'
RABBIT_TYPE = 'C'
FROG_TYPE = 'S'
def main():
n = int(input())
animal_total = 0
rat_total = 0
rabbit_total = 0
frog_total = 0
for i in range(n):
input_line = input().split()
amount = int(input_line[AMOUNT_INDEX])
type = input_line[TYPE_INDEX]
animal_total += amount
if type == RAT_TYPE:
rat_total += amount
elif type == RABBIT_TYPE:
rabbit_total += amount
elif type == FROG_TYPE:
frog_total += amount
print('Total: {:d} cobaias'.format(animal_total))
print('Total de coelhos: {:d}'.format(rabbit_total))
print('Total de ratos: {:d}'.format(rat_total))
print('Total de sapos: {:d}'.format(frog_total))
print('Percentual de coelhos: {:.2f} %'.format((rabbit_total * 100) / animal_total))
print('Percentual de ratos: {:.2f} %'.format((rat_total * 100) / animal_total))
print('Percentual de sapos: {:.2f} %'.format((frog_total * 100) / animal_total))
if __name__ == '__main__':
main() | amount_index = 0
type_index = 1
rat_type = 'R'
rabbit_type = 'C'
frog_type = 'S'
def main():
n = int(input())
animal_total = 0
rat_total = 0
rabbit_total = 0
frog_total = 0
for i in range(n):
input_line = input().split()
amount = int(input_line[AMOUNT_INDEX])
type = input_line[TYPE_INDEX]
animal_total += amount
if type == RAT_TYPE:
rat_total += amount
elif type == RABBIT_TYPE:
rabbit_total += amount
elif type == FROG_TYPE:
frog_total += amount
print('Total: {:d} cobaias'.format(animal_total))
print('Total de coelhos: {:d}'.format(rabbit_total))
print('Total de ratos: {:d}'.format(rat_total))
print('Total de sapos: {:d}'.format(frog_total))
print('Percentual de coelhos: {:.2f} %'.format(rabbit_total * 100 / animal_total))
print('Percentual de ratos: {:.2f} %'.format(rat_total * 100 / animal_total))
print('Percentual de sapos: {:.2f} %'.format(frog_total * 100 / animal_total))
if __name__ == '__main__':
main() |
#
# This is a smaller script to just test the servos in the head
# Start all services
arduino = Runtime.start("arduino","Arduino")
jaw = Runtime.start("jaw","Servo")
rothead = Runtime.start("RotHead","Servo")
leftEyeX = Runtime.start("LeftEyeX","Servo")
rightEyeX = Runtime.start("RightEyeX","Servo")
eyeY = Runtime.start("EyeY","Servo")
#
# Connect the Arduino
arduino.connect("/dev/ttyACM0")
#
# Start of main script
jaw.attach(arduino,9)
jaw.setMinMax(80,120)
# Connect the head turn left and right
rothead.setRest(100)
rothead.attach(arduino,8)
rothead.setVelocity(20)
rothead.rest()
# Connect the left eye
leftEyeX.setMinMax(50,110)
leftEyeX.setRest(80)
leftEyeX.attach(arduino,10)
leftEyeX.rest()
# Connect the right eye
rightEyeX.setMinMax(60,120)
rightEyeX.setRest(90)
rightEyeX.attach(arduino,11)
rightEyeX.rest()
# Make the left eye follow the right
# runtime.subscribe("rightEyeX","publishServoEvent","leftEyeY","MoveTo")
# rightEyeX.eventsEnabled(True)
# Connect eyes up/down
eyeY.setMinMax(60,140)
eyeY.setRest(90)
eyeY.attach(arduino,12)
eyeY.rest()
def lookRight():
rightEyeX.moveTo(120)
def lookLeft():
rightEyeX.moveTo(60)
def lookForward():
rightEyeX.rest()
eyeY.rest()
def lookDown():
EyeY.moveTo(60)
def lookUp():
EyeY.moveTo(140)
def headRight():
rothead.moveTo(70)
def headLeft():
rothead.moveTo(130)
def headForward():
rothead.rest()
lookRight()
sleep(2)
lookLeft()
sleep(2)
lookForward()
sleep(2)
lookUp()
sleep(2)
lookDown()
sleep(2)
lookForward()
sleep(2)
headRight()
sleep(5)
headLeft()
# sleep(5)
# headForward()
# sleep(5)
| arduino = Runtime.start('arduino', 'Arduino')
jaw = Runtime.start('jaw', 'Servo')
rothead = Runtime.start('RotHead', 'Servo')
left_eye_x = Runtime.start('LeftEyeX', 'Servo')
right_eye_x = Runtime.start('RightEyeX', 'Servo')
eye_y = Runtime.start('EyeY', 'Servo')
arduino.connect('/dev/ttyACM0')
jaw.attach(arduino, 9)
jaw.setMinMax(80, 120)
rothead.setRest(100)
rothead.attach(arduino, 8)
rothead.setVelocity(20)
rothead.rest()
leftEyeX.setMinMax(50, 110)
leftEyeX.setRest(80)
leftEyeX.attach(arduino, 10)
leftEyeX.rest()
rightEyeX.setMinMax(60, 120)
rightEyeX.setRest(90)
rightEyeX.attach(arduino, 11)
rightEyeX.rest()
eyeY.setMinMax(60, 140)
eyeY.setRest(90)
eyeY.attach(arduino, 12)
eyeY.rest()
def look_right():
rightEyeX.moveTo(120)
def look_left():
rightEyeX.moveTo(60)
def look_forward():
rightEyeX.rest()
eyeY.rest()
def look_down():
EyeY.moveTo(60)
def look_up():
EyeY.moveTo(140)
def head_right():
rothead.moveTo(70)
def head_left():
rothead.moveTo(130)
def head_forward():
rothead.rest()
look_right()
sleep(2)
look_left()
sleep(2)
look_forward()
sleep(2)
look_up()
sleep(2)
look_down()
sleep(2)
look_forward()
sleep(2)
head_right()
sleep(5)
head_left() |
post1 = {"_id": 2,
'name': {'first': 'Dave', 'last': 'Ellis'},
'contact':
{'address': '510 N Division Street, Carson City, MI 48811',
'phone': '(989) 220-8277',
'location': 'Carson City'},
'position': 'Disciple',
'mentor': 'Seth Roberts',
'status': 'Meeting' #Contacted, Meeting, Interests, Surveys
}
post2 = {"_id": 3,
'name': {'first': 'Steve', 'last': 'Williams'},
'contact':
{'address': '6039 E. Lake Moncalm Road, Edmore, MI 48829',
'phone': '(989) 565-0174',
'location': 'Cedar Lake'},
'position': 'Disciple',
'mentor': 'Seth Roberts',
'status': 'Contacted' #Contacted, Meeting, Interests, Surveys
}
post3 = {"_id": 4,
'name': {'first': 'Nancy', 'last': 'Coon'},
'contact':
{'address': '11960 E. Edgar Road, Vestaburg, MI 48891',
'phone': '(989) 268-1001',
'location': 'Vestaburg'},
'position': 'Disciple',
'mentor': 'Seth Roberts',
'status': 'Contacted' #Contacted, Meeting, Interests, Surveys
}
| post1 = {'_id': 2, 'name': {'first': 'Dave', 'last': 'Ellis'}, 'contact': {'address': '510 N Division Street, Carson City, MI 48811', 'phone': '(989) 220-8277', 'location': 'Carson City'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Meeting'}
post2 = {'_id': 3, 'name': {'first': 'Steve', 'last': 'Williams'}, 'contact': {'address': '6039 E. Lake Moncalm Road, Edmore, MI 48829', 'phone': '(989) 565-0174', 'location': 'Cedar Lake'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Contacted'}
post3 = {'_id': 4, 'name': {'first': 'Nancy', 'last': 'Coon'}, 'contact': {'address': '11960 E. Edgar Road, Vestaburg, MI 48891', 'phone': '(989) 268-1001', 'location': 'Vestaburg'}, 'position': 'Disciple', 'mentor': 'Seth Roberts', 'status': 'Contacted'} |
print ("hello world")
print ("hello again")
print ("I like typing this.")
print("This is fun")
print('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')
| print('hello world')
print('hello again')
print('I like typing this.')
print('This is fun')
print('Yay! Printing.')
print("I'd much rather you 'not'.")
print('I "said" do not touch this.') |
# coding=utf-8
class SelectionSort:
def find_minimum_idx(self, array: list) -> int:
min_element = array[0]
min_idx = 0
for idx in range(1, len(array)):
if array[idx] < min_element:
min_idx = idx
min_element = array[idx]
return min_idx
def sort(self, array: list) -> list:
result = []
for _ in range(len(array)):
min_idx = self.find_minimum_idx(array)
result.append(array.pop(min_idx))
return result
| class Selectionsort:
def find_minimum_idx(self, array: list) -> int:
min_element = array[0]
min_idx = 0
for idx in range(1, len(array)):
if array[idx] < min_element:
min_idx = idx
min_element = array[idx]
return min_idx
def sort(self, array: list) -> list:
result = []
for _ in range(len(array)):
min_idx = self.find_minimum_idx(array)
result.append(array.pop(min_idx))
return result |
def part_1(raw_data):
raw_data.sort()
median = raw_data[len(raw_data)//2]
ans = 0
for val in raw_data:
ans += abs(val - median)
return ans
def part_2(raw_data):
average = int(round(sum(raw_data) / len(raw_data), 0))
adjusted_average = average - 1
ans = 0
for val in raw_data:
distance = abs(val - adjusted_average)
ans += (distance * (distance + 1)) // 2
return ans
def file_reader(file_name):
input_file = open(file_name, 'r')
inputs_raw = input_file.readlines()[0].replace('\n', '').split(',')
return [int(i) for i in inputs_raw]
print(part_1(file_reader('input_07.txt')))
print(part_2(file_reader('input_07.txt')))
| def part_1(raw_data):
raw_data.sort()
median = raw_data[len(raw_data) // 2]
ans = 0
for val in raw_data:
ans += abs(val - median)
return ans
def part_2(raw_data):
average = int(round(sum(raw_data) / len(raw_data), 0))
adjusted_average = average - 1
ans = 0
for val in raw_data:
distance = abs(val - adjusted_average)
ans += distance * (distance + 1) // 2
return ans
def file_reader(file_name):
input_file = open(file_name, 'r')
inputs_raw = input_file.readlines()[0].replace('\n', '').split(',')
return [int(i) for i in inputs_raw]
print(part_1(file_reader('input_07.txt')))
print(part_2(file_reader('input_07.txt'))) |
def h():
print('Wen Chuan')
m = yield 5
print(m)
d = yield 12
print('We are one')
c = h()
next(c)
c.send('Fight')
# next(c)
def h1():
print('Wen Cha')
m = yield 5
print(m)
d = yield 12
print('We are together')
c = h1()
m = next(c)
d = c.send('Fighting')
print('We will never forger the date', m, '.', d)
| def h():
print('Wen Chuan')
m = (yield 5)
print(m)
d = (yield 12)
print('We are one')
c = h()
next(c)
c.send('Fight')
def h1():
print('Wen Cha')
m = (yield 5)
print(m)
d = (yield 12)
print('We are together')
c = h1()
m = next(c)
d = c.send('Fighting')
print('We will never forger the date', m, '.', d) |
test_list = [1, 2, 3, 4, 5, 6, 7]
def rotate_by_one_left(array):
temp = array[0]
for i in range(len(array)-1):
array[i] = array[i+1]
array[-1] = temp
def rotate_list(array, count):
print("Rotate list {} by {}".format(array, count))
for i in range(count):
# rotate_by_one_left(array)
rotate_by_one_right(array)
print("Rotated list {} by {}".format(array, count))
def rotate_by_one_right(array):
temp = array[-1]
for i in range(len(array)-1, 0, -1):
array[i] = array[i-1]
array[0] = temp
# [1,2,3,4,5,6,7] = [7,1,2,3,4,5,6]
if __name__ == "__main__":
rotate_list(test_list, 1)
| test_list = [1, 2, 3, 4, 5, 6, 7]
def rotate_by_one_left(array):
temp = array[0]
for i in range(len(array) - 1):
array[i] = array[i + 1]
array[-1] = temp
def rotate_list(array, count):
print('Rotate list {} by {}'.format(array, count))
for i in range(count):
rotate_by_one_right(array)
print('Rotated list {} by {}'.format(array, count))
def rotate_by_one_right(array):
temp = array[-1]
for i in range(len(array) - 1, 0, -1):
array[i] = array[i - 1]
array[0] = temp
if __name__ == '__main__':
rotate_list(test_list, 1) |
__author__ = "Dariusz Izak, Agnieszka Gromadka IBB PAS"
__version__ = "1.6.3"
__all__ = ["utilities"]
| __author__ = 'Dariusz Izak, Agnieszka Gromadka IBB PAS'
__version__ = '1.6.3'
__all__ = ['utilities'] |
while True:
n = int(input())
if n == 0: break
for q in range(n):
e = str(input()).split()
nome = e[0]
ano = int(e[1])
dif = int(e[2])
if q == 0:
menor = ano - dif
ganha = nome
if menor > ano - dif:
menor = ano - dif
ganha = nome
print(ganha)
| while True:
n = int(input())
if n == 0:
break
for q in range(n):
e = str(input()).split()
nome = e[0]
ano = int(e[1])
dif = int(e[2])
if q == 0:
menor = ano - dif
ganha = nome
if menor > ano - dif:
menor = ano - dif
ganha = nome
print(ganha) |
n = int(input())
narr = list(map(int,input().split()))
mi = narr.index(min(narr))
ma = narr.index(max(narr))
narr[mi] , narr[ma] = narr[ma] , narr[mi]
print(*narr) | n = int(input())
narr = list(map(int, input().split()))
mi = narr.index(min(narr))
ma = narr.index(max(narr))
(narr[mi], narr[ma]) = (narr[ma], narr[mi])
print(*narr) |
class Lcg(object):
def __init__(self, seed):
self.seed = seed
self.st = seed
def cur(self):
return (self.st & 0b1111111111111110000000000000000) >> 16
def adv(self):
self.st = (1103515245 * self.st + 12345) % (0b100000000000000000000000000000000)
def gen(self):
x = self.cur()
self.adv()
return x
| class Lcg(object):
def __init__(self, seed):
self.seed = seed
self.st = seed
def cur(self):
return (self.st & 2147418112) >> 16
def adv(self):
self.st = (1103515245 * self.st + 12345) % 4294967296
def gen(self):
x = self.cur()
self.adv()
return x |
def tournamentWinner(competitions, results):
'''
This fuction takes two arrays one of which contains competitions, another array contains results of the competitions
and returns a string which is the winning team. This implementation has O(n) time complexity where n is the number of competitions,
O(i) space complexity where i is the number of team.
args:
-------------
competitions (list) : nested array. Each element in the outer most list contains two teams.
First one is home team and second one is awy team.
results (list) : contains result of each competition. 0 if away team wins and 1 if home team wins.
output:
-------------
winner (str) : name of the champion of the tournament.
'''
# dictionary 'scores' stores all team scores
scores = {}
#updating scores of each team by iteration over results and competitions.
for i in range(len(results)):
if results[i] == 0:
if competitions[i][1] in scores:
scores[competitions[i][1]] += 3
else:
scores[competitions[i][1]] = 3
else:
if competitions[i][0] in scores:
scores[competitions[i][0]] += 3
else:
scores[competitions[i][0]] = 3
# finding the max scorer from 'scores' dictionary
max_score = 0
winner = ''
for key in scores:
score = scores[key]
if score > max_score:
max_score = score
winner = str(key)
return winner | def tournament_winner(competitions, results):
"""
This fuction takes two arrays one of which contains competitions, another array contains results of the competitions
and returns a string which is the winning team. This implementation has O(n) time complexity where n is the number of competitions,
O(i) space complexity where i is the number of team.
args:
-------------
competitions (list) : nested array. Each element in the outer most list contains two teams.
First one is home team and second one is awy team.
results (list) : contains result of each competition. 0 if away team wins and 1 if home team wins.
output:
-------------
winner (str) : name of the champion of the tournament.
"""
scores = {}
for i in range(len(results)):
if results[i] == 0:
if competitions[i][1] in scores:
scores[competitions[i][1]] += 3
else:
scores[competitions[i][1]] = 3
elif competitions[i][0] in scores:
scores[competitions[i][0]] += 3
else:
scores[competitions[i][0]] = 3
max_score = 0
winner = ''
for key in scores:
score = scores[key]
if score > max_score:
max_score = score
winner = str(key)
return winner |
"""
author: Fang Ren (SSRL)
5/1/2017
""" | """
author: Fang Ren (SSRL)
5/1/2017
""" |
class BlenderAddonManager():
''' Class to manage all workflows around addon
installation and update.
'''
def __init__(self):
pass
def index(self):
''' Indexes all addons and save its metadata
into the addon database.
'''
pass
def poll_remote_sources(self):
''' Polls remote addon sources to gather
recent addon versions.
'''
pass
def download_addon(self):
pass
def install_addon(self):
pass
def remove_addon(self):
pass
| class Blenderaddonmanager:
""" Class to manage all workflows around addon
installation and update.
"""
def __init__(self):
pass
def index(self):
""" Indexes all addons and save its metadata
into the addon database.
"""
pass
def poll_remote_sources(self):
""" Polls remote addon sources to gather
recent addon versions.
"""
pass
def download_addon(self):
pass
def install_addon(self):
pass
def remove_addon(self):
pass |
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = set()
nums.sort()
for i, v in enumerate(nums[:-3]):
for j, vv in enumerate(nums[i + 1:-2]):
t = target - v - vv
d = {}
for x in nums[i + j + 2:]:
if x not in d:
d[t - x] = 1
else:
res.add((v, vv, t - x, x))
return [list(i) for i in res]
def test_four_sum():
s = Solution()
res = s.fourSum([1, 0, -1, 0, -2, 2], 0)
assert 3 == len(res)
assert [-1, 0, 0, 1] in res
assert [-2, -1, 1, 2] in res
assert [-2, 0, 0, 2] in res
res = s.fourSum([-3, -1, 0, 2, 4, 5], 0)
assert [[-3, -1, 0, 4]] == res
| class Solution(object):
def four_sum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
res = set()
nums.sort()
for (i, v) in enumerate(nums[:-3]):
for (j, vv) in enumerate(nums[i + 1:-2]):
t = target - v - vv
d = {}
for x in nums[i + j + 2:]:
if x not in d:
d[t - x] = 1
else:
res.add((v, vv, t - x, x))
return [list(i) for i in res]
def test_four_sum():
s = solution()
res = s.fourSum([1, 0, -1, 0, -2, 2], 0)
assert 3 == len(res)
assert [-1, 0, 0, 1] in res
assert [-2, -1, 1, 2] in res
assert [-2, 0, 0, 2] in res
res = s.fourSum([-3, -1, 0, 2, 4, 5], 0)
assert [[-3, -1, 0, 4]] == res |
input = """acc +17
acc +37
acc -13
jmp +173
nop +100
acc -7
jmp +447
nop +283
acc +41
acc +32
jmp +1
jmp +585
jmp +1
acc -5
nop +71
acc +49
acc -18
jmp +527
jmp +130
jmp +253
acc +11
acc -11
jmp +390
jmp +597
jmp +1
acc +6
acc +0
jmp +588
acc -17
jmp +277
acc +2
nop +163
jmp +558
acc +38
jmp +369
acc +13
jmp +536
acc +38
acc +39
acc +6
jmp +84
acc +11
nop +517
acc +48
acc +47
jmp +1
acc +42
acc +0
acc +2
acc +24
jmp +335
acc +44
acc +47
jmp +446
nop +42
nop +74
acc +45
jmp +548
jmp +66
acc +1
jmp +212
acc +18
jmp +1
acc +4
acc -16
jmp +366
acc +0
jmp +398
acc +45
jmp +93
acc +40
acc +38
acc +21
nop +184
jmp -46
nop -9
jmp +53
acc +46
acc +36
jmp +368
acc +16
acc +8
acc -9
acc -4
jmp +328
acc -15
acc -5
acc +21
jmp +435
acc -5
acc +36
jmp +362
acc +26
jmp +447
jmp +1
jmp +412
acc +11
acc +41
nop -32
acc +17
jmp -63
jmp +1
nop +393
jmp +62
acc +18
acc +30
nop +417
jmp +74
acc +29
acc +23
jmp +455
jmp +396
jmp +395
acc +33
nop +137
nop +42
jmp +57
jmp +396
acc +7
acc +0
jmp +354
acc +15
acc +50
jmp -12
jmp +84
nop +175
acc +5
acc -2
jmp -82
acc +1
acc +26
jmp +288
nop -113
nop +366
acc +45
jmp +388
acc +21
acc +38
jmp +427
acc +33
jmp -94
nop -118
nop +411
jmp +472
nop +231
nop +470
acc +48
jmp -124
jmp +1
acc +5
acc +37
acc +42
jmp +301
acc -11
acc -17
acc +14
jmp +357
acc +6
acc +20
acc +13
jmp +361
jmp -65
acc +29
jmp +26
jmp +329
acc +32
acc +32
acc +17
jmp -102
acc -6
acc +33
acc +9
jmp +189
acc +3
jmp -128
jmp -142
acc +24
acc -5
jmp +403
acc +28
jmp +310
acc +34
acc +4
acc +33
acc +18
jmp +227
acc -8
acc -15
jmp +112
jmp +54
acc +21
acc +23
acc +20
jmp +320
acc +13
jmp -77
acc +15
nop +310
nop +335
jmp +232
acc -3
nop +50
acc +41
jmp +112
nop -10
acc +29
acc +27
jmp +52
acc +40
nop -132
acc -16
acc +27
jmp +309
acc -8
nop +147
acc +20
acc +46
jmp +202
acc +27
jmp -43
jmp +1
acc +33
acc -13
jmp +300
acc +1
jmp -202
acc -17
acc +0
acc +34
jmp -5
nop +335
acc -16
acc -17
jmp -120
acc -19
acc -13
acc +4
jmp +368
jmp +21
acc +39
acc +39
acc -18
jmp -157
nop +280
acc +33
nop -37
jmp +32
acc -16
acc +18
acc +46
jmp -121
acc -19
jmp +195
acc +28
jmp +124
jmp +331
jmp -228
jmp -146
jmp +85
jmp +60
acc +20
acc -9
jmp +303
jmp -122
jmp +111
acc +32
acc +0
acc +39
acc +29
jmp -31
nop +320
jmp -63
jmp +223
nop -149
acc -12
acc -11
acc +32
jmp +309
jmp -13
acc -19
jmp -123
acc +21
acc +18
acc +49
jmp +175
acc -14
nop -129
acc -2
acc +31
jmp +79
acc +23
acc +50
acc +39
acc +7
jmp -235
jmp -166
acc +9
jmp +293
acc -11
jmp +76
acc +44
acc +3
acc +37
jmp +123
nop -104
jmp -157
acc +14
acc +10
acc +28
jmp +25
acc +37
jmp +188
jmp -49
acc -11
jmp -90
acc -8
jmp +197
acc +5
jmp +115
acc +44
jmp -228
nop -2
acc +46
jmp +130
nop +183
nop +106
acc +27
acc +37
jmp -309
acc +28
acc -4
acc -12
acc +38
jmp +93
acc +8
acc +23
acc -9
acc +6
jmp -42
acc +10
acc +35
acc +4
jmp -231
acc +19
acc +7
acc +23
acc +11
jmp -90
acc +0
nop +158
nop -150
acc +33
jmp +107
acc +48
acc -2
jmp -104
acc +6
nop -57
nop +172
acc -11
jmp -7
acc +6
acc +50
acc -9
acc +12
jmp -171
acc +3
jmp +26
acc +42
acc +31
acc +20
acc +32
jmp -48
acc +13
jmp -6
jmp +178
acc +47
jmp -153
acc +28
nop +74
jmp -162
acc -15
nop -104
acc -9
jmp -227
acc +49
acc -19
acc +41
jmp -318
acc +9
acc +12
acc +7
jmp +34
jmp +137
nop -143
acc -8
acc +5
acc +31
jmp -20
jmp -237
acc +39
acc +0
jmp -298
acc +45
acc -19
acc +11
jmp -151
acc +40
acc +27
nop +150
nop -391
jmp -341
acc +1
acc +11
acc +18
nop -234
jmp +77
nop +104
jmp -65
acc +32
jmp -27
nop -317
nop +159
acc +14
acc -10
jmp -348
acc +29
jmp +32
acc +48
acc -19
jmp +17
jmp -201
jmp -224
nop +26
acc -7
acc +23
acc +46
jmp -6
acc +22
acc +39
acc +9
acc +23
jmp -30
jmp -243
acc +47
acc -15
jmp -298
jmp -393
jmp +1
acc +3
nop -24
acc +7
jmp -59
acc -6
acc +26
jmp -102
acc +34
acc +24
jmp -207
acc +36
acc +40
acc +41
jmp +1
jmp -306
jmp +57
jmp +1
nop +99
acc +28
jmp -391
acc +50
jmp -359
acc -5
jmp +9
jmp -355
acc +5
acc +2
jmp -77
acc +40
acc +28
acc +22
jmp -262
nop -287
acc +34
acc -4
nop +112
jmp -195
acc +29
nop -94
nop -418
jmp +24
jmp -190
acc +2
jmp -311
jmp -178
jmp -276
acc -12
acc -18
jmp +62
jmp -174
nop +31
acc +33
nop -158
jmp -417
acc +3
acc +21
acc +47
jmp +87
acc +45
jmp -77
acc +6
acc -10
jmp +1
jmp -240
acc +7
acc +47
jmp -379
acc -14
acc +50
nop -75
acc +30
jmp +70
jmp -392
jmp -430
acc +22
acc -2
jmp -492
jmp +1
acc -6
acc +38
jmp -36
nop -336
jmp -32
jmp +61
acc +20
acc -9
acc +2
jmp -175
acc +21
acc -2
jmp -6
jmp -527
acc +11
acc +16
jmp -262
jmp +1
nop -327
acc +29
jmp -114
acc +11
acc +17
acc +26
nop -104
jmp -428
nop -178
nop -242
acc +29
acc +5
jmp -245
jmp -417
jmp -278
acc +35
acc +21
jmp +1
nop -263
jmp +8
acc +42
jmp -95
nop -312
acc -11
acc +34
acc +0
jmp +19
acc +8
acc -13
acc +32
acc +21
jmp -208
acc +15
acc +39
nop -194
jmp -280
jmp +24
nop -516
acc +21
acc +48
jmp -367
jmp -121
acc +49
acc -16
jmp -136
acc +0
jmp -148
jmp -85
jmp -103
nop -446
jmp -242
acc -12
acc +13
acc +31
acc -1
jmp -435
nop -420
acc +22
acc -5
jmp -567
nop -354
acc +11
acc +33
acc +45
jmp -76
acc -2
acc +0
acc +25
acc +46
jmp -555
acc +0
acc +11
nop -2
jmp -394
jmp -395
acc +8
acc +14
acc +47
acc +22
jmp +1"""
instructions = [i for i in input.split("\n")]
"""one"""
accumulator = 0
executed_instructions = []
def execute(instructions_list, id, executed_list, accumulator):
if id >= len(instructions_list):
return ['end', accumulator]
if id in executed_list:
return ['looped', accumulator]
else:
executed_list.append(id)
instruction = instructions_list[id]
num = int(instruction[5:len(instruction)])
sign = 1 if instruction[4] == '+' else -1
if 'acc' in instruction:
accumulator += num * sign
elif 'jmp' in instruction:
next_id = id + (num * sign)
return execute(instructions_list, next_id, executed_list, accumulator)
return execute(instructions_list, id + 1, executed_list, accumulator)
print(execute(instructions, 0, executed_instructions, 0))
"""two"""
"""It's 1am and I want to sleep, so I'm brute forcing this"""
for i in range(0, len(instructions)):
executed_instructions = []
ins = instructions.copy()
if 'acc' in ins[i]:
continue
elif 'nop' in ins[i]:
ins[i] = ins[i].replace('nop', 'jmp')
else:
ins[i] = ins[i].replace('jmp', 'nop')
res = execute(ins, 0, executed_instructions, 0)
if res[0] == 'end':
print(res[1])
break
| input = 'acc +17\nacc +37\nacc -13\njmp +173\nnop +100\nacc -7\njmp +447\nnop +283\nacc +41\nacc +32\njmp +1\njmp +585\njmp +1\nacc -5\nnop +71\nacc +49\nacc -18\njmp +527\njmp +130\njmp +253\nacc +11\nacc -11\njmp +390\njmp +597\njmp +1\nacc +6\nacc +0\njmp +588\nacc -17\njmp +277\nacc +2\nnop +163\njmp +558\nacc +38\njmp +369\nacc +13\njmp +536\nacc +38\nacc +39\nacc +6\njmp +84\nacc +11\nnop +517\nacc +48\nacc +47\njmp +1\nacc +42\nacc +0\nacc +2\nacc +24\njmp +335\nacc +44\nacc +47\njmp +446\nnop +42\nnop +74\nacc +45\njmp +548\njmp +66\nacc +1\njmp +212\nacc +18\njmp +1\nacc +4\nacc -16\njmp +366\nacc +0\njmp +398\nacc +45\njmp +93\nacc +40\nacc +38\nacc +21\nnop +184\njmp -46\nnop -9\njmp +53\nacc +46\nacc +36\njmp +368\nacc +16\nacc +8\nacc -9\nacc -4\njmp +328\nacc -15\nacc -5\nacc +21\njmp +435\nacc -5\nacc +36\njmp +362\nacc +26\njmp +447\njmp +1\njmp +412\nacc +11\nacc +41\nnop -32\nacc +17\njmp -63\njmp +1\nnop +393\njmp +62\nacc +18\nacc +30\nnop +417\njmp +74\nacc +29\nacc +23\njmp +455\njmp +396\njmp +395\nacc +33\nnop +137\nnop +42\njmp +57\njmp +396\nacc +7\nacc +0\njmp +354\nacc +15\nacc +50\njmp -12\njmp +84\nnop +175\nacc +5\nacc -2\njmp -82\nacc +1\nacc +26\njmp +288\nnop -113\nnop +366\nacc +45\njmp +388\nacc +21\nacc +38\njmp +427\nacc +33\njmp -94\nnop -118\nnop +411\njmp +472\nnop +231\nnop +470\nacc +48\njmp -124\njmp +1\nacc +5\nacc +37\nacc +42\njmp +301\nacc -11\nacc -17\nacc +14\njmp +357\nacc +6\nacc +20\nacc +13\njmp +361\njmp -65\nacc +29\njmp +26\njmp +329\nacc +32\nacc +32\nacc +17\njmp -102\nacc -6\nacc +33\nacc +9\njmp +189\nacc +3\njmp -128\njmp -142\nacc +24\nacc -5\njmp +403\nacc +28\njmp +310\nacc +34\nacc +4\nacc +33\nacc +18\njmp +227\nacc -8\nacc -15\njmp +112\njmp +54\nacc +21\nacc +23\nacc +20\njmp +320\nacc +13\njmp -77\nacc +15\nnop +310\nnop +335\njmp +232\nacc -3\nnop +50\nacc +41\njmp +112\nnop -10\nacc +29\nacc +27\njmp +52\nacc +40\nnop -132\nacc -16\nacc +27\njmp +309\nacc -8\nnop +147\nacc +20\nacc +46\njmp +202\nacc +27\njmp -43\njmp +1\nacc +33\nacc -13\njmp +300\nacc +1\njmp -202\nacc -17\nacc +0\nacc +34\njmp -5\nnop +335\nacc -16\nacc -17\njmp -120\nacc -19\nacc -13\nacc +4\njmp +368\njmp +21\nacc +39\nacc +39\nacc -18\njmp -157\nnop +280\nacc +33\nnop -37\njmp +32\nacc -16\nacc +18\nacc +46\njmp -121\nacc -19\njmp +195\nacc +28\njmp +124\njmp +331\njmp -228\njmp -146\njmp +85\njmp +60\nacc +20\nacc -9\njmp +303\njmp -122\njmp +111\nacc +32\nacc +0\nacc +39\nacc +29\njmp -31\nnop +320\njmp -63\njmp +223\nnop -149\nacc -12\nacc -11\nacc +32\njmp +309\njmp -13\nacc -19\njmp -123\nacc +21\nacc +18\nacc +49\njmp +175\nacc -14\nnop -129\nacc -2\nacc +31\njmp +79\nacc +23\nacc +50\nacc +39\nacc +7\njmp -235\njmp -166\nacc +9\njmp +293\nacc -11\njmp +76\nacc +44\nacc +3\nacc +37\njmp +123\nnop -104\njmp -157\nacc +14\nacc +10\nacc +28\njmp +25\nacc +37\njmp +188\njmp -49\nacc -11\njmp -90\nacc -8\njmp +197\nacc +5\njmp +115\nacc +44\njmp -228\nnop -2\nacc +46\njmp +130\nnop +183\nnop +106\nacc +27\nacc +37\njmp -309\nacc +28\nacc -4\nacc -12\nacc +38\njmp +93\nacc +8\nacc +23\nacc -9\nacc +6\njmp -42\nacc +10\nacc +35\nacc +4\njmp -231\nacc +19\nacc +7\nacc +23\nacc +11\njmp -90\nacc +0\nnop +158\nnop -150\nacc +33\njmp +107\nacc +48\nacc -2\njmp -104\nacc +6\nnop -57\nnop +172\nacc -11\njmp -7\nacc +6\nacc +50\nacc -9\nacc +12\njmp -171\nacc +3\njmp +26\nacc +42\nacc +31\nacc +20\nacc +32\njmp -48\nacc +13\njmp -6\njmp +178\nacc +47\njmp -153\nacc +28\nnop +74\njmp -162\nacc -15\nnop -104\nacc -9\njmp -227\nacc +49\nacc -19\nacc +41\njmp -318\nacc +9\nacc +12\nacc +7\njmp +34\njmp +137\nnop -143\nacc -8\nacc +5\nacc +31\njmp -20\njmp -237\nacc +39\nacc +0\njmp -298\nacc +45\nacc -19\nacc +11\njmp -151\nacc +40\nacc +27\nnop +150\nnop -391\njmp -341\nacc +1\nacc +11\nacc +18\nnop -234\njmp +77\nnop +104\njmp -65\nacc +32\njmp -27\nnop -317\nnop +159\nacc +14\nacc -10\njmp -348\nacc +29\njmp +32\nacc +48\nacc -19\njmp +17\njmp -201\njmp -224\nnop +26\nacc -7\nacc +23\nacc +46\njmp -6\nacc +22\nacc +39\nacc +9\nacc +23\njmp -30\njmp -243\nacc +47\nacc -15\njmp -298\njmp -393\njmp +1\nacc +3\nnop -24\nacc +7\njmp -59\nacc -6\nacc +26\njmp -102\nacc +34\nacc +24\njmp -207\nacc +36\nacc +40\nacc +41\njmp +1\njmp -306\njmp +57\njmp +1\nnop +99\nacc +28\njmp -391\nacc +50\njmp -359\nacc -5\njmp +9\njmp -355\nacc +5\nacc +2\njmp -77\nacc +40\nacc +28\nacc +22\njmp -262\nnop -287\nacc +34\nacc -4\nnop +112\njmp -195\nacc +29\nnop -94\nnop -418\njmp +24\njmp -190\nacc +2\njmp -311\njmp -178\njmp -276\nacc -12\nacc -18\njmp +62\njmp -174\nnop +31\nacc +33\nnop -158\njmp -417\nacc +3\nacc +21\nacc +47\njmp +87\nacc +45\njmp -77\nacc +6\nacc -10\njmp +1\njmp -240\nacc +7\nacc +47\njmp -379\nacc -14\nacc +50\nnop -75\nacc +30\njmp +70\njmp -392\njmp -430\nacc +22\nacc -2\njmp -492\njmp +1\nacc -6\nacc +38\njmp -36\nnop -336\njmp -32\njmp +61\nacc +20\nacc -9\nacc +2\njmp -175\nacc +21\nacc -2\njmp -6\njmp -527\nacc +11\nacc +16\njmp -262\njmp +1\nnop -327\nacc +29\njmp -114\nacc +11\nacc +17\nacc +26\nnop -104\njmp -428\nnop -178\nnop -242\nacc +29\nacc +5\njmp -245\njmp -417\njmp -278\nacc +35\nacc +21\njmp +1\nnop -263\njmp +8\nacc +42\njmp -95\nnop -312\nacc -11\nacc +34\nacc +0\njmp +19\nacc +8\nacc -13\nacc +32\nacc +21\njmp -208\nacc +15\nacc +39\nnop -194\njmp -280\njmp +24\nnop -516\nacc +21\nacc +48\njmp -367\njmp -121\nacc +49\nacc -16\njmp -136\nacc +0\njmp -148\njmp -85\njmp -103\nnop -446\njmp -242\nacc -12\nacc +13\nacc +31\nacc -1\njmp -435\nnop -420\nacc +22\nacc -5\njmp -567\nnop -354\nacc +11\nacc +33\nacc +45\njmp -76\nacc -2\nacc +0\nacc +25\nacc +46\njmp -555\nacc +0\nacc +11\nnop -2\njmp -394\njmp -395\nacc +8\nacc +14\nacc +47\nacc +22\njmp +1'
instructions = [i for i in input.split('\n')]
'one'
accumulator = 0
executed_instructions = []
def execute(instructions_list, id, executed_list, accumulator):
if id >= len(instructions_list):
return ['end', accumulator]
if id in executed_list:
return ['looped', accumulator]
else:
executed_list.append(id)
instruction = instructions_list[id]
num = int(instruction[5:len(instruction)])
sign = 1 if instruction[4] == '+' else -1
if 'acc' in instruction:
accumulator += num * sign
elif 'jmp' in instruction:
next_id = id + num * sign
return execute(instructions_list, next_id, executed_list, accumulator)
return execute(instructions_list, id + 1, executed_list, accumulator)
print(execute(instructions, 0, executed_instructions, 0))
'two'
"It's 1am and I want to sleep, so I'm brute forcing this"
for i in range(0, len(instructions)):
executed_instructions = []
ins = instructions.copy()
if 'acc' in ins[i]:
continue
elif 'nop' in ins[i]:
ins[i] = ins[i].replace('nop', 'jmp')
else:
ins[i] = ins[i].replace('jmp', 'nop')
res = execute(ins, 0, executed_instructions, 0)
if res[0] == 'end':
print(res[1])
break |
"""
The Self-Taught Programmer - Chapter 6 Challenges
Author: Dante Valentine
Date: 1 June, 2021
"""
# CHALLENGE 1
for c in "camus":
print(c)
# CHALLENGE 2
str1 = input("What did you write? ")
str2 = input("Who did you send it to? ")
str3 = "Yesterday I wrote a {}. I sent it to {}!".format(str1, str2)
print(str3)
# CHALLENGE 3
# print("aldous Huxley was born in 1894.".capitalize())
# CHALLENGE 4
str4 = "Where now? Who now? When now?"
questions = str4.split("? ")
for i in range(0,len(questions)-1):
questions[i] += "?"
print(questions)
# CHALLENGE 5
list1 = ["The", "fox", "jumped", "over", "the", "fence", "."]
list1 = " ".join(list1[0:6]) + list1[6]
print(list1)
# CHALLENGE 6
print("A screaming comes across the sky".replace("s","$"))
# CHALLENGE 7
str5 = "Hemingway"
print(str5.index("m"))
# CHALLENGE 8
str6 = "\"That's not fair.\" I wrap my arms around myself. \"I'm fighting, too.\"\n\"Well, seeing as your father created this mess, if I were you, I'd fight a little harder.\""
print(str6)
# CHALLENGE 9
str7 = "three" + " " + "three" + " " + "three"
print(str7)
str8 = "three " * 3
str8 = str8[0:(len(str8)-1)]
print(str8)
# CHALLENGE 10
str8 = "It was a bright cold day in April, abd the clocks were striking thirteen."
sliceindex = str8.index(",")
str9 = str8[0:sliceindex]
print(str9) | """
The Self-Taught Programmer - Chapter 6 Challenges
Author: Dante Valentine
Date: 1 June, 2021
"""
for c in 'camus':
print(c)
str1 = input('What did you write? ')
str2 = input('Who did you send it to? ')
str3 = 'Yesterday I wrote a {}. I sent it to {}!'.format(str1, str2)
print(str3)
str4 = 'Where now? Who now? When now?'
questions = str4.split('? ')
for i in range(0, len(questions) - 1):
questions[i] += '?'
print(questions)
list1 = ['The', 'fox', 'jumped', 'over', 'the', 'fence', '.']
list1 = ' '.join(list1[0:6]) + list1[6]
print(list1)
print('A screaming comes across the sky'.replace('s', '$'))
str5 = 'Hemingway'
print(str5.index('m'))
str6 = '"That\'s not fair." I wrap my arms around myself. "I\'m fighting, too."\n"Well, seeing as your father created this mess, if I were you, I\'d fight a little harder."'
print(str6)
str7 = 'three' + ' ' + 'three' + ' ' + 'three'
print(str7)
str8 = 'three ' * 3
str8 = str8[0:len(str8) - 1]
print(str8)
str8 = 'It was a bright cold day in April, abd the clocks were striking thirteen.'
sliceindex = str8.index(',')
str9 = str8[0:sliceindex]
print(str9) |
class MyClass:
def add(self, a, b):
return a + b
obj = MyClass()
ret = obj.add(3, 4)
print(ret)
| class Myclass:
def add(self, a, b):
return a + b
obj = my_class()
ret = obj.add(3, 4)
print(ret) |
class Solution:
def numUniqueEmails(self, emails: List[str]) -> int:
def f(email):
(localname, domain) = email.split('@')
localname = localname.split('+')[0]
localname = localname.replace('.','')
return localname + "@" + domain
return len(set(map(f, emails)))
| class Solution:
def num_unique_emails(self, emails: List[str]) -> int:
def f(email):
(localname, domain) = email.split('@')
localname = localname.split('+')[0]
localname = localname.replace('.', '')
return localname + '@' + domain
return len(set(map(f, emails))) |
# count from zero to 10
for i in range(0,10):
print (i)
print("")
# count by 2
for i in range(0,10,2):
print(i)
print("")
# count by 5 start at 50 to 100
for i in range(50,100,5):
print(i)
| for i in range(0, 10):
print(i)
print('')
for i in range(0, 10, 2):
print(i)
print('')
for i in range(50, 100, 5):
print(i) |
str_btn_prev = "Previous"
str_btn_next = "Next"
str_btn_download = "Download"
str_btn_reset = "Reset Annotation"
str_btn_delete_bbox = "Delete Bbox"
srt_validation_not_ok = "<b style=\"color:green\">NO ACTION REQUIRED</b>"
srt_validation_ok = "<b style=\"color:RED\">ACTION REQUIRED</b>"
info_new_ds = "New dataset with meta_annotations"
info_missing = "Missing image"
info_no_more_images = "No available images"
info_total = "Total"
info_class = "Class"
info_class_name = "Class name"
info_ann_images = "Annotated images"
info_ann_objects = "Annotated objects"
info_positions = "Positions:"
info_completed = "Completed images:"
info_incomplete = "Incomplete images:"
info_completed_obj = "Completed objects:"
info_incomplete_obj = "Incomplete objects:"
info_ds_output = "Generated dataset will be saved at: "
warn_select_class = "<b style=\"color:RED\">You must assing a class to all bbox before continuing</b>"
warn_skip_wrong = "Skipping wrong annotation"
warn_img_path_not_exits = "Image path does not exists "
warn_task_not_supported = "Task type not supported"
warn_no_images = "No images provided"
warn_little_classes = "At least one class must be provided"
warn_binary_only_two = "Binary datasets contain only 2 classes"
warn_display_function_needed = "Non image data requires the definition of the custom display function"
warn_no_images_criteria = "No images meet the specified criteria"
warn_incorrect_class = "Class not present in dataset"
warn_incorrect_property = "Meta-Annotation not present in dataset" | str_btn_prev = 'Previous'
str_btn_next = 'Next'
str_btn_download = 'Download'
str_btn_reset = 'Reset Annotation'
str_btn_delete_bbox = 'Delete Bbox'
srt_validation_not_ok = '<b style="color:green">NO ACTION REQUIRED</b>'
srt_validation_ok = '<b style="color:RED">ACTION REQUIRED</b>'
info_new_ds = 'New dataset with meta_annotations'
info_missing = 'Missing image'
info_no_more_images = 'No available images'
info_total = 'Total'
info_class = 'Class'
info_class_name = 'Class name'
info_ann_images = 'Annotated images'
info_ann_objects = 'Annotated objects'
info_positions = 'Positions:'
info_completed = 'Completed images:'
info_incomplete = 'Incomplete images:'
info_completed_obj = 'Completed objects:'
info_incomplete_obj = 'Incomplete objects:'
info_ds_output = 'Generated dataset will be saved at: '
warn_select_class = '<b style="color:RED">You must assing a class to all bbox before continuing</b>'
warn_skip_wrong = 'Skipping wrong annotation'
warn_img_path_not_exits = 'Image path does not exists '
warn_task_not_supported = 'Task type not supported'
warn_no_images = 'No images provided'
warn_little_classes = 'At least one class must be provided'
warn_binary_only_two = 'Binary datasets contain only 2 classes'
warn_display_function_needed = 'Non image data requires the definition of the custom display function'
warn_no_images_criteria = 'No images meet the specified criteria'
warn_incorrect_class = 'Class not present in dataset'
warn_incorrect_property = 'Meta-Annotation not present in dataset' |
# User inputs
database = input(f'\nEnter the name of the database you want to create: ')
environment = input(f'\nEnter the name of the environment (DTAP) you want to create: ')
# Setting variables
strdatabase = str(database)
strenvironment = str(environment)
# Composing the code
line10 = ('CREATE ROLE IF NOT EXISTS RL_' + strdatabase + '_' + strenvironment +'_ADMIN;')
line13 = ('GRANT ALL PRIVILEGES ON ACCOUNT TO ROLE RL_' + strdatabase + '_' + strenvironment +'_ADMIN;')
line15 = ('GRANT ROLE RL_' + strdatabase + '_' + strenvironment +'_ADMIN TO USER JOHAN;')
line20 = ('USE ROLE RL_' + strdatabase + '_' + strenvironment +'_ADMIN;')
line30 = ('CREATE DATABASE DB_' + strdatabase + '_' + strenvironment +';')
# Writing the lines to file
file1='V1.1__createdatabase.sql'
with open(file1,'w') as out:
out.write('{}\n{}\n{}\n{}\n{}\n'.format(line10,line13,line15,line20,line30))
# Checking if the data is
# written to file or not
file1 = open('V1.1__createdatabase.sql', 'r')
print(file1.read())
file1.close() | database = input(f'\nEnter the name of the database you want to create: ')
environment = input(f'\nEnter the name of the environment (DTAP) you want to create: ')
strdatabase = str(database)
strenvironment = str(environment)
line10 = 'CREATE ROLE IF NOT EXISTS RL_' + strdatabase + '_' + strenvironment + '_ADMIN;'
line13 = 'GRANT ALL PRIVILEGES ON ACCOUNT TO ROLE RL_' + strdatabase + '_' + strenvironment + '_ADMIN;'
line15 = 'GRANT ROLE RL_' + strdatabase + '_' + strenvironment + '_ADMIN TO USER JOHAN;'
line20 = 'USE ROLE RL_' + strdatabase + '_' + strenvironment + '_ADMIN;'
line30 = 'CREATE DATABASE DB_' + strdatabase + '_' + strenvironment + ';'
file1 = 'V1.1__createdatabase.sql'
with open(file1, 'w') as out:
out.write('{}\n{}\n{}\n{}\n{}\n'.format(line10, line13, line15, line20, line30))
file1 = open('V1.1__createdatabase.sql', 'r')
print(file1.read())
file1.close() |
# twitter hashtag to find
TWITTER_HASHTAG = "#StarWars"
# twitter api credentials (https://apps.twitter.com/)
TWITTER_CONSUMER_KEY = ""
TWITTER_CONSUMER_SECRET = ""
TWITTER_ACCESS_TOKEN = ""
TWITTER_ACCESS_TOKEN_SECRET = ""
# delay in seconds between reading tweets
DELAY_TO_READ_TWEET = 30.0
| twitter_hashtag = '#StarWars'
twitter_consumer_key = ''
twitter_consumer_secret = ''
twitter_access_token = ''
twitter_access_token_secret = ''
delay_to_read_tweet = 30.0 |
# -*- coding: utf-8 -*-
__author__ = 'Michael Odintsov'
__email__ = 'templarrrr@gmail.com'
__version__ = '0.1.0'
| __author__ = 'Michael Odintsov'
__email__ = 'templarrrr@gmail.com'
__version__ = '0.1.0' |
class UnionFind(object):
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, u):
if u != self.parent[u]:
self.parent[u] = self.find(self.parent[u])
return self.parent[u]
def isConnected(self, u, v):
return self.find(u) == self.find(v)
def union(self, u, v):
pu = self.find(u)
pv = self.find(v)
if pu == pv:
return False
if self.rank[pv] > self.rank[pu]:
self.parent[pu] = pv
elif self.rank[pu] > self.rank[pv]:
self.parent[pv] = pu
else:
self.parent[pu] = pv
self.rank[pv] += 1
return True
u = UnionFind(6)
u.union(3, 4)
u.union(2, 3)
u.union(1, 2)
u.union(0, 1) | class Unionfind(object):
def __init__(self, n):
self.parent = list(range(n))
self.rank = [0] * n
def find(self, u):
if u != self.parent[u]:
self.parent[u] = self.find(self.parent[u])
return self.parent[u]
def is_connected(self, u, v):
return self.find(u) == self.find(v)
def union(self, u, v):
pu = self.find(u)
pv = self.find(v)
if pu == pv:
return False
if self.rank[pv] > self.rank[pu]:
self.parent[pu] = pv
elif self.rank[pu] > self.rank[pv]:
self.parent[pv] = pu
else:
self.parent[pu] = pv
self.rank[pv] += 1
return True
u = union_find(6)
u.union(3, 4)
u.union(2, 3)
u.union(1, 2)
u.union(0, 1) |
with open('input') as input:
lines = input.readlines()
number_sequence = lines[0].split(',')
board_numbers = []
called_indexes = []
# Flatten data structure for boards
for i, line in enumerate(lines):
if i == 0:
continue
if line == '\n':
continue
stripped_line = line.strip('\n')
num_list = line.split()
for num in num_list:
board_numbers.append(num)
def checkForWin(board_numbers, called_indexes, num):
for i, space in enumerate(board_numbers):
if space == num:
# print(f"Space at index {i} contains called number {num}")
called_indexes.append(i)
# Check for win based on indexes
board_index = i // 25
row_pos = i % 5
row_start = i - row_pos
col_start = i - (i % 25 - row_pos)
# print(f"X value = {i % 5}")
# print(f"line_start = {line_start}")
horizontal_win = True
for j in range(row_start, row_start+5):
if j not in called_indexes:
horizontal_win = False
vertical_win = True
for j in range(col_start, col_start+25, 5):
if j not in called_indexes:
vertical_win = False
if horizontal_win or vertical_win:
print(f"Winner on board {board_index}")
return board_index
# "Call" numbers and check for winner
winner = None
for num in number_sequence:
winner = checkForWin(board_numbers, called_indexes, num)
if winner != None:
board_start = winner*25
unmarked_sum = 0
for i in range(board_start, board_start+25):
if i not in called_indexes:
unmarked_sum += int(board_numbers[i])
print(f"SOLUTION = {unmarked_sum} * {num} = {int(unmarked_sum) * int(num)}")
break
| with open('input') as input:
lines = input.readlines()
number_sequence = lines[0].split(',')
board_numbers = []
called_indexes = []
for (i, line) in enumerate(lines):
if i == 0:
continue
if line == '\n':
continue
stripped_line = line.strip('\n')
num_list = line.split()
for num in num_list:
board_numbers.append(num)
def check_for_win(board_numbers, called_indexes, num):
for (i, space) in enumerate(board_numbers):
if space == num:
called_indexes.append(i)
board_index = i // 25
row_pos = i % 5
row_start = i - row_pos
col_start = i - (i % 25 - row_pos)
horizontal_win = True
for j in range(row_start, row_start + 5):
if j not in called_indexes:
horizontal_win = False
vertical_win = True
for j in range(col_start, col_start + 25, 5):
if j not in called_indexes:
vertical_win = False
if horizontal_win or vertical_win:
print(f'Winner on board {board_index}')
return board_index
winner = None
for num in number_sequence:
winner = check_for_win(board_numbers, called_indexes, num)
if winner != None:
board_start = winner * 25
unmarked_sum = 0
for i in range(board_start, board_start + 25):
if i not in called_indexes:
unmarked_sum += int(board_numbers[i])
print(f'SOLUTION = {unmarked_sum} * {num} = {int(unmarked_sum) * int(num)}')
break |
"""Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
def collatz_sequence(n):
length = 1
# Implementing this recursively would allow memoization, but Python isn't
# the best language to attempt this in. Doing so causes a RecursionError
# to be raised. Also of note: using a decorator like `functools.lru_cache`
# for memoization causes the recursion limit to be reached more quickly.
# See: http://stackoverflow.com/questions/15239123/maximum-recursion-depth-reached-faster-when-using-functools-lru-cache.
while n > 1:
length += 1
if n%2 == 0:
n /= 2
else:
n = (3 * n) + 1
return length
def longest_collatz_sequence(ceiling):
longest_chain = {
'number': 1,
'length': 1
}
for i in range(ceiling):
length = collatz_sequence(i)
if length > longest_chain['length']:
longest_chain = {
'number': i,
'length': length
}
return longest_chain
| """Longest Collatz sequence
The following iterative sequence is defined for the set of positive integers:
n -> n/2 (n is even)
n -> 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
It can be seen that this sequence (starting at 13 and finishing at 1) contains
10 terms. Although it has not been proved yet (Collatz Problem), it is thought
that all starting numbers finish at 1.
Which starting number, under one million, produces the longest chain?
Note: Once the chain starts, the terms are allowed to go above one million.
"""
def collatz_sequence(n):
length = 1
while n > 1:
length += 1
if n % 2 == 0:
n /= 2
else:
n = 3 * n + 1
return length
def longest_collatz_sequence(ceiling):
longest_chain = {'number': 1, 'length': 1}
for i in range(ceiling):
length = collatz_sequence(i)
if length > longest_chain['length']:
longest_chain = {'number': i, 'length': length}
return longest_chain |
class AchievementDigest(object):
ID = 0
SERIAL_NUM_READS = "c1"
SERIAL_NUM_PUBLISH = "c2"
SERIAL_NUM_REUSES = "c3"
SERIAL_LAST_READS = "u1"
SERIAL_LAST_PUBLISH = "u2"
SERIAL_LAST_REUSES = "u3"
def __init__(self):
self.num_reads = 0
self.num_publish = 0
self.num_reuses = 0
self._last_reads = []
self._last_published = []
self._last_reuses = []
@staticmethod
def deserialize(doc):
digest = AchievementDigest()
digest.num_reads = doc.get(AchievementDigest.SERIAL_NUM_READS, 0)
digest.num_publish = doc.get(AchievementDigest.SERIAL_NUM_PUBLISH, 0)
digest.num_reuses = doc.get(AchievementDigest.SERIAL_NUM_REUSES, 0)
digest._last_reads = doc.get(AchievementDigest.SERIAL_LAST_READS, [])
digest._last_published = doc.get(AchievementDigest.SERIAL_LAST_PUBLISH, [])
digest._last_reuses = doc.get(AchievementDigest.SERIAL_LAST_REUSES, [])
return digest
@property
def last_reads(self):
tmp = [el for el in self._last_reads] # copy
tmp.reverse()
return tmp
@property
def last_published(self):
tmp = [el for el in self._last_published] # copy
tmp.reverse()
return tmp
@property
def last_reuses(self):
tmp = [el for el in self._last_reuses] # copy
tmp.reverse()
return tmp
class AchievementDigestMongoStore(object):
COLLECTION = "achievement_digest"
DOCUMENT_ID = 1
COUNTERS_DOC_KEY = "c"
def __init__(self, mongo_server_store):
self.server_store = mongo_server_store
def read_achievement_digest(self):
dbcol = self.server_store.db[self.COLLECTION]
doc = dbcol.find_one({"_id": self.DOCUMENT_ID})
return AchievementDigest.deserialize(doc) if doc else None
def increment_total_read_counter(self, brl_user):
"""brl_user has readed from biicode for the first time, store it"""
self._increment_counter(AchievementDigest.SERIAL_NUM_READS,
AchievementDigest.SERIAL_LAST_READS,
brl_user)
def increment_total_publish_counter(self, brl_user):
"""brl_user has published from biicode for the first time, store it"""
self._increment_counter(AchievementDigest.SERIAL_NUM_PUBLISH,
AchievementDigest.SERIAL_LAST_PUBLISH,
brl_user)
def increment_total_reuse_counter(self, brl_user):
"""brl_user has published from biicode for the first time, store it"""
self._increment_counter(AchievementDigest.SERIAL_NUM_REUSES,
AchievementDigest.SERIAL_LAST_REUSES,
brl_user)
def _increment_counter(self, counter_field_name, user_list_field_name, brl_user):
query = {"_id": self.DOCUMENT_ID}
set_q = {"$inc": {counter_field_name: 1},
"$push": {user_list_field_name: brl_user}}
self.server_store._update_collection(self.COLLECTION, query, set_q, True, None)
| class Achievementdigest(object):
id = 0
serial_num_reads = 'c1'
serial_num_publish = 'c2'
serial_num_reuses = 'c3'
serial_last_reads = 'u1'
serial_last_publish = 'u2'
serial_last_reuses = 'u3'
def __init__(self):
self.num_reads = 0
self.num_publish = 0
self.num_reuses = 0
self._last_reads = []
self._last_published = []
self._last_reuses = []
@staticmethod
def deserialize(doc):
digest = achievement_digest()
digest.num_reads = doc.get(AchievementDigest.SERIAL_NUM_READS, 0)
digest.num_publish = doc.get(AchievementDigest.SERIAL_NUM_PUBLISH, 0)
digest.num_reuses = doc.get(AchievementDigest.SERIAL_NUM_REUSES, 0)
digest._last_reads = doc.get(AchievementDigest.SERIAL_LAST_READS, [])
digest._last_published = doc.get(AchievementDigest.SERIAL_LAST_PUBLISH, [])
digest._last_reuses = doc.get(AchievementDigest.SERIAL_LAST_REUSES, [])
return digest
@property
def last_reads(self):
tmp = [el for el in self._last_reads]
tmp.reverse()
return tmp
@property
def last_published(self):
tmp = [el for el in self._last_published]
tmp.reverse()
return tmp
@property
def last_reuses(self):
tmp = [el for el in self._last_reuses]
tmp.reverse()
return tmp
class Achievementdigestmongostore(object):
collection = 'achievement_digest'
document_id = 1
counters_doc_key = 'c'
def __init__(self, mongo_server_store):
self.server_store = mongo_server_store
def read_achievement_digest(self):
dbcol = self.server_store.db[self.COLLECTION]
doc = dbcol.find_one({'_id': self.DOCUMENT_ID})
return AchievementDigest.deserialize(doc) if doc else None
def increment_total_read_counter(self, brl_user):
"""brl_user has readed from biicode for the first time, store it"""
self._increment_counter(AchievementDigest.SERIAL_NUM_READS, AchievementDigest.SERIAL_LAST_READS, brl_user)
def increment_total_publish_counter(self, brl_user):
"""brl_user has published from biicode for the first time, store it"""
self._increment_counter(AchievementDigest.SERIAL_NUM_PUBLISH, AchievementDigest.SERIAL_LAST_PUBLISH, brl_user)
def increment_total_reuse_counter(self, brl_user):
"""brl_user has published from biicode for the first time, store it"""
self._increment_counter(AchievementDigest.SERIAL_NUM_REUSES, AchievementDigest.SERIAL_LAST_REUSES, brl_user)
def _increment_counter(self, counter_field_name, user_list_field_name, brl_user):
query = {'_id': self.DOCUMENT_ID}
set_q = {'$inc': {counter_field_name: 1}, '$push': {user_list_field_name: brl_user}}
self.server_store._update_collection(self.COLLECTION, query, set_q, True, None) |
# Found here:
# https://github.com/gabtremblay/pysrec/
# srecutils.py
#
# Copyright (C) 2011 Gabriel Tremblay - initnull hat gmail.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
Motorola S-Record utis
- Kudos to Montreal CISSP Groupies
"""
# Address len in bytes for S* types
# http://www.amelek.gda.pl/avr/uisp/srecord.htm
__ADDR_LEN = {'S0' : 2,
'S1' : 2,
'S2' : 3,
'S3' : 4,
'S5' : 2,
'S7' : 4,
'S8' : 3,
'S9' : 2}
def int_to_padded_hex_byte(integer):
"""
Convert an int to a 0-padded hex byte string
example: 65 == 41, 10 == 0A
Returns: The hex byte as string (ex: "0C")
"""
to_hex = hex(integer)
xpos = to_hex.find('x')
hex_byte = to_hex[xpos+1 : len(to_hex)].upper()
if len(hex_byte) == 1:
hex_byte = ''.join(['0', hex_byte])
return hex_byte
def compute_srec_checksum(srec):
"""
Compute the checksum byte of a given S-Record
Returns: The checksum as a string hex byte (ex: "0C")
"""
# Get the summable data from srec
# start at 2 to remove the S* record entry
data = srec[2:len(srec)]
sum = 0
# For each byte, convert to int and add.
# (step each two character to form a byte)
for position in range(0, len(data), 2):
current_byte = data[position : position+2]
int_value = int(current_byte, 16)
sum += int_value
# Extract the Least significant byte from the hex form
hex_sum = hex(sum)
least_significant_byte = hex_sum[len(hex_sum)-2:]
least_significant_byte = least_significant_byte.replace('x', '0')
# turn back to int and find the 8-bit one's complement
int_lsb = int(least_significant_byte, 16)
computed_checksum = (~int_lsb) & 0xff
return computed_checksum
def validate_srec_checksum(srec):
"""
Validate if the checksum of the supplied s-record is valid
Returns: True if valid, False if not
"""
checksum = srec[len(srec)-2:]
# Strip the original checksum and compare with the computed one
if compute_srec_checksum(srec[:len(srec) - 2]) == int(checksum, 16):
return True
else:
return False
def get_readable_string(integer):
r"""
Convert an integer to a readable 2-character representation. This is useful for reversing
examples: 41 == ".A", 13 == "\n", 20 (space) == "__"
Returns a readable 2-char representation of an int.
"""
if integer == 9: #\t
readable_string = "\\t"
elif integer == 10: #\r
readable_string = "\\r"
elif integer == 13: #\n
readable_string = "\\n"
elif integer == 32: # space
readable_string = '__'
elif integer >= 33 and integer <= 126: # Readable ascii
readable_string = ''.join([chr(integer), '.'])
else: # rest
readable_string = int_to_padded_hex_byte(integer)
return readable_string
def offset_byte_in_data(target_data, offset, target_byte_pos, readable = False, wraparound = False):
"""
Offset a given byte in the provided data payload (kind of rot(x))
readable will return a human-readable representation of the byte+offset
wraparound will wrap around 255 to 0 (ex: 257 = 2)
Returns: the offseted byte
"""
byte_pos = target_byte_pos * 2
prefix = target_data[:byte_pos]
suffix = target_data[byte_pos+2:]
target_byte = target_data[byte_pos:byte_pos+2]
int_value = int(target_byte, 16)
int_value += offset
# Wraparound
if int_value > 255 and wraparound:
int_value -= 256
# Extract readable char for analysis
if readable:
if int_value < 256 and int_value > 0:
offset_byte = get_readable_string(int_value)
else:
offset_byte = int_to_padded_hex_byte(int_value)
else:
offset_byte = int_to_padded_hex_byte(int_value)
return ''.join([prefix, offset_byte, suffix])
# offset can be from -255 to 255
def offset_data(data_section, offset, readable = False, wraparound = False):
"""
Offset the whole data section.
see offset_byte_in_data for more information
Returns: the entire data section + offset on each byte
"""
for pos in range(0, len(data_section)/2):
data_section = offset_byte_in_data(data_section, offset, pos, readable, wraparound)
return data_section
def parse_srec(srec):
"""
Extract the data portion of a given S-Record (without checksum)
Returns: the record type, the lenght of the data section, the write address, the data itself and the checksum
"""
record_type = srec[0:2]
data_len = srec[2:4]
addr_len = __ADDR_LEN.get(record_type) * 2
addr = srec[4:4 + addr_len]
data = srec[4 + addr_len:len(srec)-2]
checksum = srec[len(srec) - 2:]
return record_type, data_len, addr, data, checksum | """
Motorola S-Record utis
- Kudos to Montreal CISSP Groupies
"""
__addr_len = {'S0': 2, 'S1': 2, 'S2': 3, 'S3': 4, 'S5': 2, 'S7': 4, 'S8': 3, 'S9': 2}
def int_to_padded_hex_byte(integer):
"""
Convert an int to a 0-padded hex byte string
example: 65 == 41, 10 == 0A
Returns: The hex byte as string (ex: "0C")
"""
to_hex = hex(integer)
xpos = to_hex.find('x')
hex_byte = to_hex[xpos + 1:len(to_hex)].upper()
if len(hex_byte) == 1:
hex_byte = ''.join(['0', hex_byte])
return hex_byte
def compute_srec_checksum(srec):
"""
Compute the checksum byte of a given S-Record
Returns: The checksum as a string hex byte (ex: "0C")
"""
data = srec[2:len(srec)]
sum = 0
for position in range(0, len(data), 2):
current_byte = data[position:position + 2]
int_value = int(current_byte, 16)
sum += int_value
hex_sum = hex(sum)
least_significant_byte = hex_sum[len(hex_sum) - 2:]
least_significant_byte = least_significant_byte.replace('x', '0')
int_lsb = int(least_significant_byte, 16)
computed_checksum = ~int_lsb & 255
return computed_checksum
def validate_srec_checksum(srec):
"""
Validate if the checksum of the supplied s-record is valid
Returns: True if valid, False if not
"""
checksum = srec[len(srec) - 2:]
if compute_srec_checksum(srec[:len(srec) - 2]) == int(checksum, 16):
return True
else:
return False
def get_readable_string(integer):
"""
Convert an integer to a readable 2-character representation. This is useful for reversing
examples: 41 == ".A", 13 == "\\n", 20 (space) == "__"
Returns a readable 2-char representation of an int.
"""
if integer == 9:
readable_string = '\\t'
elif integer == 10:
readable_string = '\\r'
elif integer == 13:
readable_string = '\\n'
elif integer == 32:
readable_string = '__'
elif integer >= 33 and integer <= 126:
readable_string = ''.join([chr(integer), '.'])
else:
readable_string = int_to_padded_hex_byte(integer)
return readable_string
def offset_byte_in_data(target_data, offset, target_byte_pos, readable=False, wraparound=False):
"""
Offset a given byte in the provided data payload (kind of rot(x))
readable will return a human-readable representation of the byte+offset
wraparound will wrap around 255 to 0 (ex: 257 = 2)
Returns: the offseted byte
"""
byte_pos = target_byte_pos * 2
prefix = target_data[:byte_pos]
suffix = target_data[byte_pos + 2:]
target_byte = target_data[byte_pos:byte_pos + 2]
int_value = int(target_byte, 16)
int_value += offset
if int_value > 255 and wraparound:
int_value -= 256
if readable:
if int_value < 256 and int_value > 0:
offset_byte = get_readable_string(int_value)
else:
offset_byte = int_to_padded_hex_byte(int_value)
else:
offset_byte = int_to_padded_hex_byte(int_value)
return ''.join([prefix, offset_byte, suffix])
def offset_data(data_section, offset, readable=False, wraparound=False):
"""
Offset the whole data section.
see offset_byte_in_data for more information
Returns: the entire data section + offset on each byte
"""
for pos in range(0, len(data_section) / 2):
data_section = offset_byte_in_data(data_section, offset, pos, readable, wraparound)
return data_section
def parse_srec(srec):
"""
Extract the data portion of a given S-Record (without checksum)
Returns: the record type, the lenght of the data section, the write address, the data itself and the checksum
"""
record_type = srec[0:2]
data_len = srec[2:4]
addr_len = __ADDR_LEN.get(record_type) * 2
addr = srec[4:4 + addr_len]
data = srec[4 + addr_len:len(srec) - 2]
checksum = srec[len(srec) - 2:]
return (record_type, data_len, addr, data, checksum) |
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print ("Wait there's not 10 things in that list, let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print ("Adding: ", next_one)
stuff.append(next_one)
print ("There's %d items now." % len(stuff))
print ("There we go: ", stuff)
print ("Let's do some things with stuff.")
print (stuff[1])
print (stuff[-1]) # whoa! fancy
print (stuff.pop())
print (' '.join(stuff)) # what? cool
print ('#'.join(stuff[3:5])) # super stellar!
| ten_things = 'Apples Oranges Crows Telephone Light Sugar'
print("Wait there's not 10 things in that list, let's fix that.")
stuff = ten_things.split(' ')
more_stuff = ['Day', 'Night', 'Song', 'Frisbee', 'Corn', 'Banana', 'Girl', 'Boy']
while len(stuff) != 10:
next_one = more_stuff.pop()
print('Adding: ', next_one)
stuff.append(next_one)
print("There's %d items now." % len(stuff))
print('There we go: ', stuff)
print("Let's do some things with stuff.")
print(stuff[1])
print(stuff[-1])
print(stuff.pop())
print(' '.join(stuff))
print('#'.join(stuff[3:5])) |
# "Common block" loaded by the cfi and the cfg to communicate egmID parameters
electronVetoId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-veto'
electronLooseId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-loose'
electronMediumId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-medium'
electronTightId = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-tight'
electronHLTId = 'egmGsfElectronIDs:cutBasedElectronHLTPreselection-Summer16-V1'
electronMVAWP90 = 'egmGsfElectronIDs:mvaEleID-Spring16-GeneralPurpose-V1-wp90'
electronMVAWP80 = 'egmGsfElectronIDs:mvaEleID-Spring16-GeneralPurpose-V1-wp80'
electronCombIsoEA = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_80X.txt'
electronEcalIsoEA = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_HLT_ecalPFClusterIso.txt'
electronHcalIsoEA = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_HLT_hcalPFClusterIso.txt'
photonLooseId = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-loose'
photonMediumId = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-medium'
photonTightId = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-tight'
photonCHIsoEA = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfChargedHadrons_90percentBased.txt'
photonNHIsoEA = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfNeutralHadrons_90percentBased.txt'
photonPhIsoEA = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfPhotons_90percentBased.txt'
# https://twiki.cern.ch/twiki/bin/view/CMS/EGMSmearer#Energy_smearing_and_scale_correc
# https://github.com/ECALELFS/ScalesSmearings/tree/Moriond17_23Jan_v2
electronSmearingData = {
"Prompt2015":"SUEPProd/Producer/data/ScalesSmearings/74X_Prompt_2015",
"76XReReco" :"SUEPProd/Producer/data/ScalesSmearings/76X_16DecRereco_2015_Etunc",
"80Xapproval" : "SUEPProd/Producer/data/ScalesSmearings/80X_ichepV1_2016_ele",
"Moriond2017_JEC" : "SUEPProd/Producer/data/ScalesSmearings/Winter_2016_reReco_v1_ele" #only to derive JEC corrections
}
photonSmearingData = {
"Prompt2015":"SUEPProd/Producer/data/ScalesSmearings/74X_Prompt_2015",
"76XReReco" :"SUEPProd/Producer/data/ScalesSmearings/76X_16DecRereco_2015_Etunc",
"80Xapproval" : "SUEPProd/Producer/data/ScalesSmearings/80X_ichepV2_2016_pho",
"Moriond2017_JEC" : "SUEPProd/Producer/data/ScalesSmearings/Winter_2016_reReco_v1_ele" #only to derive JEC correctionsb
}
| electron_veto_id = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-veto'
electron_loose_id = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-loose'
electron_medium_id = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-medium'
electron_tight_id = 'egmGsfElectronIDs:cutBasedElectronID-Summer16-80X-V1-tight'
electron_hlt_id = 'egmGsfElectronIDs:cutBasedElectronHLTPreselection-Summer16-V1'
electron_mvawp90 = 'egmGsfElectronIDs:mvaEleID-Spring16-GeneralPurpose-V1-wp90'
electron_mvawp80 = 'egmGsfElectronIDs:mvaEleID-Spring16-GeneralPurpose-V1-wp80'
electron_comb_iso_ea = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_cone03_pfNeuHadronsAndPhotons_80X.txt'
electron_ecal_iso_ea = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_HLT_ecalPFClusterIso.txt'
electron_hcal_iso_ea = 'RecoEgamma/ElectronIdentification/data/Summer16/effAreaElectrons_HLT_hcalPFClusterIso.txt'
photon_loose_id = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-loose'
photon_medium_id = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-medium'
photon_tight_id = 'egmPhotonIDs:cutBasedPhotonID-Spring16-V2p2-tight'
photon_ch_iso_ea = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfChargedHadrons_90percentBased.txt'
photon_nh_iso_ea = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfNeutralHadrons_90percentBased.txt'
photon_ph_iso_ea = 'RecoEgamma/PhotonIdentification/data/Spring16/effAreaPhotons_cone03_pfPhotons_90percentBased.txt'
electron_smearing_data = {'Prompt2015': 'SUEPProd/Producer/data/ScalesSmearings/74X_Prompt_2015', '76XReReco': 'SUEPProd/Producer/data/ScalesSmearings/76X_16DecRereco_2015_Etunc', '80Xapproval': 'SUEPProd/Producer/data/ScalesSmearings/80X_ichepV1_2016_ele', 'Moriond2017_JEC': 'SUEPProd/Producer/data/ScalesSmearings/Winter_2016_reReco_v1_ele'}
photon_smearing_data = {'Prompt2015': 'SUEPProd/Producer/data/ScalesSmearings/74X_Prompt_2015', '76XReReco': 'SUEPProd/Producer/data/ScalesSmearings/76X_16DecRereco_2015_Etunc', '80Xapproval': 'SUEPProd/Producer/data/ScalesSmearings/80X_ichepV2_2016_pho', 'Moriond2017_JEC': 'SUEPProd/Producer/data/ScalesSmearings/Winter_2016_reReco_v1_ele'} |
#!/usr/bin/env python
# @file levenshtein.py
# @author Michael Foukarakis
# @version 0.1
# @date Created: Thu Oct 16, 2014 10:57 EEST
# Last Update: Thu Oct 16, 2014 11:01 EEST
#------------------------------------------------------------------------
# Description: Levenshtein string distance implementation
#------------------------------------------------------------------------
# History: <+history+>
# TODO: <+missing features+>
#------------------------------------------------------------------------
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------
def levenshtein(s1, s2):
"""Returns the Levenshtein distance of S1 and S2.
>>> levenshtein('aabcadcdbaba', 'aabacbaaadb')
6
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
if not s1:
return len(s2)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer
deletions = current_row[j] + 1 # than s2
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1]
| def levenshtein(s1, s2):
"""Returns the Levenshtein distance of S1 and S2.
>>> levenshtein('aabcadcdbaba', 'aabacbaaadb')
6
"""
if len(s1) < len(s2):
return levenshtein(s2, s1)
if not s1:
return len(s2)
previous_row = range(len(s2) + 1)
for (i, c1) in enumerate(s1):
current_row = [i + 1]
for (j, c2) in enumerate(s2):
insertions = previous_row[j + 1] + 1
deletions = current_row[j] + 1
substitutions = previous_row[j] + (c1 != c2)
current_row.append(min(insertions, deletions, substitutions))
previous_row = current_row
return previous_row[-1] |
class Plugin(object):
def __init__(self, myarg):
self.myarg = myarg
def do_it(self):
print("doing it with myarg={} inside plugin1".format(self.myarg))
| class Plugin(object):
def __init__(self, myarg):
self.myarg = myarg
def do_it(self):
print('doing it with myarg={} inside plugin1'.format(self.myarg)) |
load("//:packages.bzl", "CDK_PACKAGES")
# Base rollup globals for dependencies and the root entry-point.
CDK_ROLLUP_GLOBALS = {
'tslib': 'tslib',
'@angular/cdk': 'ng.cdk',
}
# Rollup globals for subpackages in the form of, e.g., {"@angular/cdk/table": "ng.cdk.table"}
CDK_ROLLUP_GLOBALS.update({
"@angular/cdk/%s" % p: "ng.cdk.%s" % p for p in CDK_PACKAGES
})
| load('//:packages.bzl', 'CDK_PACKAGES')
cdk_rollup_globals = {'tslib': 'tslib', '@angular/cdk': 'ng.cdk'}
CDK_ROLLUP_GLOBALS.update({'@angular/cdk/%s' % p: 'ng.cdk.%s' % p for p in CDK_PACKAGES}) |
# https://leetcode.com/problems/peeking-iterator/
class PeekingIterator:
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self.seen = deque()
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if not self.seen:
self.seen.append(self.iterator.next())
return self.seen[0]
def next(self):
"""
:rtype: int
"""
if self.seen:
return self.seen.popleft()
return self.iterator.next()
def hasNext(self):
"""
:rtype: bool
"""
if self.seen:
return True
return self.iterator.hasNext()
# Efficient
class PeekingIterator:
def __init__(self, iterator):
self.iter = iterator
self.buffer = self.iter.next() if self.iter.hasNext() else None
def peek(self):
return self.buffer
def next(self):
ret = self.buffer
self.buffer = self.iter.next() if self.iter.hasNext() else None
return ret
def hasNext(self):
return self.buffer is not None
| class Peekingiterator:
def __init__(self, iterator):
"""
Initialize your data structure here.
:type iterator: Iterator
"""
self.iterator = iterator
self.seen = deque()
def peek(self):
"""
Returns the next element in the iteration without advancing the iterator.
:rtype: int
"""
if not self.seen:
self.seen.append(self.iterator.next())
return self.seen[0]
def next(self):
"""
:rtype: int
"""
if self.seen:
return self.seen.popleft()
return self.iterator.next()
def has_next(self):
"""
:rtype: bool
"""
if self.seen:
return True
return self.iterator.hasNext()
class Peekingiterator:
def __init__(self, iterator):
self.iter = iterator
self.buffer = self.iter.next() if self.iter.hasNext() else None
def peek(self):
return self.buffer
def next(self):
ret = self.buffer
self.buffer = self.iter.next() if self.iter.hasNext() else None
return ret
def has_next(self):
return self.buffer is not None |
res = client.get_smtp_servers() # The SMTP properties are related to alert routing
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items))
# Valid fields: continuation_token, filter, ids, limit, names, offset, sort
# See section "Common Fields" for examples
| res = client.get_smtp_servers()
print(res)
if type(res) == pypureclient.responses.ValidResponse:
print(list(res.items)) |
mimic_tables_dir = './mimic_tables/' # location of the metadata tables of the mimic-cxr dataset. Inside this folder:'mimic-cxr-2.0.0-chexpert.csv' and 'mimic-cxr-2.0.0-split.csv'
jpg_path = './dataset_mimic_jpg/' # location of the full mimic-cxr-jpg dataset. Inside this folder: "physionet.org" folder
dicom_path = './dataset_mimic/' # location of the dicom images of the mimic-cxr dataset that were included in the eyetracking dataset. Inside this folder: "physionet.org" folder
h5_path = '/scratch/' # folder where to save hdf5 files containing the full resized mimic dataset to speed up training
eyetracking_dataset_path = './dataset_et/main_data/' # location of the eye-tracking dataset. Inside this folder: metadata csv and all cases folders
segmentation_model_path = './segmentation_model/' #Inside this folder: trained_model.hdf5, from https://github.com/imlab-uiip/lung-segmentation-2d | mimic_tables_dir = './mimic_tables/'
jpg_path = './dataset_mimic_jpg/'
dicom_path = './dataset_mimic/'
h5_path = '/scratch/'
eyetracking_dataset_path = './dataset_et/main_data/'
segmentation_model_path = './segmentation_model/' |
class SpriteHandler:
"""draws the sprites for all objects with updated position, rotation and
scale each draw step"""
def __init__(self):
self.sprite_scale_factor = 0.03750000000000002
self.rotation_factor = 0.0000000
self.debug_draw = 1
def toggle_debug_draw(self):
self.debug_draw += 1
if self.debug_draw > 2:
self.debug_draw = 0
print(f"debug_draw: {self.debug_draw}")
def change_scale_factor(self, value):
"""modifies the sprite scale factor used for sprite drawing"""
self.sprite_scale_factor += value
if self.sprite_scale_factor < 0.02:
self.sprite_scale_factor = 0.02
if self.sprite_scale_factor > 0.06:
self.sprite_scale_factor = 0.06
print(f"scale_factor: {self.sprite_scale_factor}")
def change_rotation_factor(self, value):
"""modifies the sprite rotation factor used for sprite drawing"""
self.rotation_factor += value
print(f"rotation_factor: {self.rotation_factor}")
def draw(self, object_list, batch):
# update all the sprite values and then draw them as a batch
if self.debug_draw == 1:
for object in object_list:
object.update_sprite(
self.sprite_scale_factor, self.rotation_factor
)
batch.draw()
| class Spritehandler:
"""draws the sprites for all objects with updated position, rotation and
scale each draw step"""
def __init__(self):
self.sprite_scale_factor = 0.03750000000000002
self.rotation_factor = 0.0
self.debug_draw = 1
def toggle_debug_draw(self):
self.debug_draw += 1
if self.debug_draw > 2:
self.debug_draw = 0
print(f'debug_draw: {self.debug_draw}')
def change_scale_factor(self, value):
"""modifies the sprite scale factor used for sprite drawing"""
self.sprite_scale_factor += value
if self.sprite_scale_factor < 0.02:
self.sprite_scale_factor = 0.02
if self.sprite_scale_factor > 0.06:
self.sprite_scale_factor = 0.06
print(f'scale_factor: {self.sprite_scale_factor}')
def change_rotation_factor(self, value):
"""modifies the sprite rotation factor used for sprite drawing"""
self.rotation_factor += value
print(f'rotation_factor: {self.rotation_factor}')
def draw(self, object_list, batch):
if self.debug_draw == 1:
for object in object_list:
object.update_sprite(self.sprite_scale_factor, self.rotation_factor)
batch.draw() |
"""
[easy] challenge #14
Source / Reddit Post - https://www.reddit.com/r/dailyprogrammer/comments/q2v2k/2232012_challenge_14_easy/
"""
a = [1, 2, 3, 4, 5, 6, 7, 8]
k = 2
print([x for i in range(0, len(a), k) for x in a[i:i+k][::-1]])
| """
[easy] challenge #14
Source / Reddit Post - https://www.reddit.com/r/dailyprogrammer/comments/q2v2k/2232012_challenge_14_easy/
"""
a = [1, 2, 3, 4, 5, 6, 7, 8]
k = 2
print([x for i in range(0, len(a), k) for x in a[i:i + k][::-1]]) |
class bufferPair:
# a ping-pong buffer for gpu computation
def __init__(self, cur, nxt):
self.cur = cur
self.nxt = nxt
def swap(self):
self.cur, self.nxt = self.nxt, self.cur
class MultiBufferPair:
"""
Specifically designed for FaceGrid
"""
def __init__(self, cur, nxt):
"""
:param cur: one FaceGrid
:param nxt: another
"""
assert(len(cur.fields) == len(nxt.fields))
self.cur = cur
self.nxt = nxt
def swap(self):
for w_c, w_n in zip(self.cur.fields, self.nxt.fields):
w_c, w_n = w_n, w_c
self.cur, self.nxt = self.nxt, self.cur | class Bufferpair:
def __init__(self, cur, nxt):
self.cur = cur
self.nxt = nxt
def swap(self):
(self.cur, self.nxt) = (self.nxt, self.cur)
class Multibufferpair:
"""
Specifically designed for FaceGrid
"""
def __init__(self, cur, nxt):
"""
:param cur: one FaceGrid
:param nxt: another
"""
assert len(cur.fields) == len(nxt.fields)
self.cur = cur
self.nxt = nxt
def swap(self):
for (w_c, w_n) in zip(self.cur.fields, self.nxt.fields):
(w_c, w_n) = (w_n, w_c)
(self.cur, self.nxt) = (self.nxt, self.cur) |
"""Factories for the mobileapps_store app."""
# import factory
# from ..models import YourModel
| """Factories for the mobileapps_store app.""" |
class GCode(object):
def comment(self):
return ""
def __str__(self) -> str:
return f"{self.code()}{self.comment()}"
class G0(GCode):
def __init__(self, x=None, y=None, z=None) -> None:
if (x is None and y is None and z is None):
raise TypeError("G0 needs at least one axis")
self.x = x
self.y = y
self.z = z
def coordinate(self):
result = []
if self.x is not None:
result.append(f"X{self.x}")
if self.y is not None:
result.append(f"Y{self.y:.4f}")
if self.z is not None:
result.append(f"Z{self.z}")
return result
def code(self):
return f"G0 {' '.join(self.coordinate())}"
class G1(GCode):
def __init__(self, x=None, y=None, z=None, feedrate=None) -> None:
if (x is None and y is None and z is None and feedrate is None):
raise TypeError("G1 needs at least one axis, or a feedrate")
self.x = x
self.y = y
self.z = z
self.feedrate = feedrate
def coordinate(self):
result = []
if self.x is not None:
result.append(f"X{self.x}")
if self.y is not None:
result.append(f"Y{self.y:.4f}")
if self.z is not None:
result.append(f"Z{self.z}")
return result
def comment(self):
return f"; Set feedrate to {self.feedrate} mm/min" if self.feedrate else ""
def code(self):
attributes = self.coordinate()
if self.feedrate:
attributes.append(f"F{self.feedrate}")
return f"G1 {' '.join(attributes)}"
class G4(GCode):
def __init__(self, duration) -> None:
self.duration = duration
def comment(self):
return f"; Wait for {self.duration} seconds"
def code(self):
return f"G4 P{self.duration}"
class G21(GCode):
def comment(self):
return f"; mm-mode"
def code(self):
return f"G21"
class G54(GCode):
def comment(self):
return f"; Work Coordinates"
def code(self):
return f"G54"
class G90(GCode):
def comment(self):
return f"; Absolute Positioning"
def code(self):
return f"G90"
class G91(GCode):
def comment(self):
return f"; Relative Positioning"
def code(self):
return f"G91"
class M3(GCode):
def __init__(self, spindle_speed) -> None:
self.spindle_speed = spindle_speed
def comment(self):
return f"; Spindle on to {self.spindle_speed} RPM"
def code(self):
return f"M3 S{self.spindle_speed}"
class M5(GCode):
def comment(self):
return f"; Stop spindle"
def code(self):
return f"M5 S0"
| class Gcode(object):
def comment(self):
return ''
def __str__(self) -> str:
return f'{self.code()}{self.comment()}'
class G0(GCode):
def __init__(self, x=None, y=None, z=None) -> None:
if x is None and y is None and (z is None):
raise type_error('G0 needs at least one axis')
self.x = x
self.y = y
self.z = z
def coordinate(self):
result = []
if self.x is not None:
result.append(f'X{self.x}')
if self.y is not None:
result.append(f'Y{self.y:.4f}')
if self.z is not None:
result.append(f'Z{self.z}')
return result
def code(self):
return f"G0 {' '.join(self.coordinate())}"
class G1(GCode):
def __init__(self, x=None, y=None, z=None, feedrate=None) -> None:
if x is None and y is None and (z is None) and (feedrate is None):
raise type_error('G1 needs at least one axis, or a feedrate')
self.x = x
self.y = y
self.z = z
self.feedrate = feedrate
def coordinate(self):
result = []
if self.x is not None:
result.append(f'X{self.x}')
if self.y is not None:
result.append(f'Y{self.y:.4f}')
if self.z is not None:
result.append(f'Z{self.z}')
return result
def comment(self):
return f'; Set feedrate to {self.feedrate} mm/min' if self.feedrate else ''
def code(self):
attributes = self.coordinate()
if self.feedrate:
attributes.append(f'F{self.feedrate}')
return f"G1 {' '.join(attributes)}"
class G4(GCode):
def __init__(self, duration) -> None:
self.duration = duration
def comment(self):
return f'; Wait for {self.duration} seconds'
def code(self):
return f'G4 P{self.duration}'
class G21(GCode):
def comment(self):
return f'; mm-mode'
def code(self):
return f'G21'
class G54(GCode):
def comment(self):
return f'; Work Coordinates'
def code(self):
return f'G54'
class G90(GCode):
def comment(self):
return f'; Absolute Positioning'
def code(self):
return f'G90'
class G91(GCode):
def comment(self):
return f'; Relative Positioning'
def code(self):
return f'G91'
class M3(GCode):
def __init__(self, spindle_speed) -> None:
self.spindle_speed = spindle_speed
def comment(self):
return f'; Spindle on to {self.spindle_speed} RPM'
def code(self):
return f'M3 S{self.spindle_speed}'
class M5(GCode):
def comment(self):
return f'; Stop spindle'
def code(self):
return f'M5 S0' |
class ListNode:
def __init__(self, data):
self.data= data
self.next= None
class Solution:
def delete_nth_from_last(self, head: ListNode, n: int) -> ListNode:
ans= ListNode(0)
ans.next= head
first= ans
second= ans
for i in range(1, n+2):
first= first.next
while(first is not None):
first= first.next
second= second.next
second.next= second.next.next
return ans.next
def print_list(self, head: ListNode) -> None:
while (head):
print(head.data)
head = head.next
s= Solution()
ll_1= ListNode(1)
ll_2= ListNode(2)
ll_3= ListNode(3)
ll_4= ListNode(4)
ll_5= ListNode(5)
ll_1.next= ll_2
ll_2.next= ll_3
ll_3.next= ll_4
ll_4.next= ll_5
s.print_list(ll_1)
new_head= s.delete_nth_from_last(ll_1,2)
print()
s.print_list(new_head) | class Listnode:
def __init__(self, data):
self.data = data
self.next = None
class Solution:
def delete_nth_from_last(self, head: ListNode, n: int) -> ListNode:
ans = list_node(0)
ans.next = head
first = ans
second = ans
for i in range(1, n + 2):
first = first.next
while first is not None:
first = first.next
second = second.next
second.next = second.next.next
return ans.next
def print_list(self, head: ListNode) -> None:
while head:
print(head.data)
head = head.next
s = solution()
ll_1 = list_node(1)
ll_2 = list_node(2)
ll_3 = list_node(3)
ll_4 = list_node(4)
ll_5 = list_node(5)
ll_1.next = ll_2
ll_2.next = ll_3
ll_3.next = ll_4
ll_4.next = ll_5
s.print_list(ll_1)
new_head = s.delete_nth_from_last(ll_1, 2)
print()
s.print_list(new_head) |
#functions with output
def format_name(f_name, l_name):
if f_name == '' or l_name == '':
return "You didn't privide valid inputs"
formated_f_name = f_name.title()
formated_l_name = l_name.title()
#print(f'{formated_f_name} {formated_l_name}')
return f'{formated_f_name} {formated_l_name}'
#formated_string = format_name('eDgar', 'CanRo')
#print(formated_string)
#print(format_name('eDgar', 'CanRo'))
#output = len('Edgar')
print(format_name(input('What is you firts name?: '),
input('What is your last name?: '))) | def format_name(f_name, l_name):
if f_name == '' or l_name == '':
return "You didn't privide valid inputs"
formated_f_name = f_name.title()
formated_l_name = l_name.title()
return f'{formated_f_name} {formated_l_name}'
print(format_name(input('What is you firts name?: '), input('What is your last name?: '))) |
marks=[]
passed=[]
fail=[]
s1=int(input("what did you score?"))
marks.append(s1)
s2=int(input("what did you score?"))
marks.append(s2)
s3=int(input("what did you score?"))
marks.append(s3)
s4=int(input("what did you score?"))
marks.append(s4)
s5=int(input("what did you score?"))
marks.append(s5)
s6=int(input("what did you score?"))
marks.append(s6)
s7=int(input("what did you score?"))
marks.append(s7)
s8=int(input("what did you score?"))
marks.append(s8)
s9=int(input("what did you score?"))
marks.append(s9)
s10=int(input("what did you score?"))
marks.append(s10)
#print(marks)
for mark in marks:
if mark>50:
passed.append(mark)
else:
fail.append(mark)
"""
print(passed)
print(fail)
"""
list_which_failed=int(len(fail))
list_which_passed=int(len(passed))
"""
print()
print(list_which_passed)"""
print("The list of students who failed is " + list_which_failed)
print("The list of students who passed is " + list_which_passed) | marks = []
passed = []
fail = []
s1 = int(input('what did you score?'))
marks.append(s1)
s2 = int(input('what did you score?'))
marks.append(s2)
s3 = int(input('what did you score?'))
marks.append(s3)
s4 = int(input('what did you score?'))
marks.append(s4)
s5 = int(input('what did you score?'))
marks.append(s5)
s6 = int(input('what did you score?'))
marks.append(s6)
s7 = int(input('what did you score?'))
marks.append(s7)
s8 = int(input('what did you score?'))
marks.append(s8)
s9 = int(input('what did you score?'))
marks.append(s9)
s10 = int(input('what did you score?'))
marks.append(s10)
for mark in marks:
if mark > 50:
passed.append(mark)
else:
fail.append(mark)
' \nprint(passed)\nprint(fail)\n'
list_which_failed = int(len(fail))
list_which_passed = int(len(passed))
'\nprint()\nprint(list_which_passed)'
print('The list of students who failed is ' + list_which_failed)
print('The list of students who passed is ' + list_which_passed) |
def Sum(value1, value2=200, value3=300):
return value1 + value2 + value3
print(Sum(10))
print(Sum(10, 20))
print(Sum(10, 20, 30))
print(Sum(10, value2=20))
print(Sum(10, value3=30))
print(Sum(10, value2=20, value3=30))
| def sum(value1, value2=200, value3=300):
return value1 + value2 + value3
print(sum(10))
print(sum(10, 20))
print(sum(10, 20, 30))
print(sum(10, value2=20))
print(sum(10, value3=30))
print(sum(10, value2=20, value3=30)) |
liste = []
entiers = 0
somme = 0
isZero = False
while not isZero:
number = float(input("Entrez un nombre: "))
if number == 0: isZero = True
elif number - int(number) == 0:
entiers += 1
somme += number
liste += [number]
print("Liste:", liste)
print("Nombre d'entiers:", entiers)
print("Somme des entiers:", somme)
| liste = []
entiers = 0
somme = 0
is_zero = False
while not isZero:
number = float(input('Entrez un nombre: '))
if number == 0:
is_zero = True
elif number - int(number) == 0:
entiers += 1
somme += number
liste += [number]
print('Liste:', liste)
print("Nombre d'entiers:", entiers)
print('Somme des entiers:', somme) |
# -*- coding:utf-8 -*-
# author: lyl
def get_age():
age = 18
name = 'Alex'
return age
print() | def get_age():
age = 18
name = 'Alex'
return age
print() |
#!/usr/bin/env python3
pwd=os.walk(os.getcwd())
for a,b,c in pwd:
for i in c:
if re.search('.*\.txt$',i):
file_FullPath=os.path.join(a,i)
file_open=open(file_FullPath,'r',encoding='gbk')
file_read=file_open.read()
file_open.close()
file_write=open(file_FullPath,'w',encoding='utf-8')
file_write.write(file_read)
file_write.close()
| pwd = os.walk(os.getcwd())
for (a, b, c) in pwd:
for i in c:
if re.search('.*\\.txt$', i):
file__full_path = os.path.join(a, i)
file_open = open(file_FullPath, 'r', encoding='gbk')
file_read = file_open.read()
file_open.close()
file_write = open(file_FullPath, 'w', encoding='utf-8')
file_write.write(file_read)
file_write.close() |
"""
Copyright (c) 2018, Ankit R Gadiya
BSD 3-Clause License
Project Euler
Problem 1: Multiples of 3 and 5
Q. If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def sumAP(x, l):
n = int(l / x)
return int((x * n * (n + 1)) / 2)
if __name__ == "__main__":
result = sumAP(3, 999) + sumAP(5, 999) - sumAP(15, 999)
print(result)
| """
Copyright (c) 2018, Ankit R Gadiya
BSD 3-Clause License
Project Euler
Problem 1: Multiples of 3 and 5
Q. If we list all the natural numbers below 10 that are multiples of 3 or 5, we
get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
"""
def sum_ap(x, l):
n = int(l / x)
return int(x * n * (n + 1) / 2)
if __name__ == '__main__':
result = sum_ap(3, 999) + sum_ap(5, 999) - sum_ap(15, 999)
print(result) |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 1 23:41:54 2017
@author: Roberto Piga
Version 1
Recursive method
Failed because test parser can not call a function
"""
# define starting variables
balance = a = 5000
annualInterestRate = b = 0.18
monthlyPaymentRate = c = 0.02
month = m = 0
def balancer(balance, annualInterestRate, monthlyPaymentRate, month = 0):
# base case
# 12th month print remaining balance and exit
if month == 12:
print("Remaining balance:",round(balance, 2))
return True
else:
# calculate unpaid balance as balance minus the minimum payment
unpaidBalance = balance - (balance * monthlyPaymentRate)
# add monthly interest to calculate remaining balance
remainBalance = unpaidBalance + (annualInterestRate/12.0 * unpaidBalance)
# loop to the next month
return balancer(remainBalance, annualInterestRate, monthlyPaymentRate, month + 1)
balancer(a, b, c) | """
Created on Wed Feb 1 23:41:54 2017
@author: Roberto Piga
Version 1
Recursive method
Failed because test parser can not call a function
"""
balance = a = 5000
annual_interest_rate = b = 0.18
monthly_payment_rate = c = 0.02
month = m = 0
def balancer(balance, annualInterestRate, monthlyPaymentRate, month=0):
if month == 12:
print('Remaining balance:', round(balance, 2))
return True
else:
unpaid_balance = balance - balance * monthlyPaymentRate
remain_balance = unpaidBalance + annualInterestRate / 12.0 * unpaidBalance
return balancer(remainBalance, annualInterestRate, monthlyPaymentRate, month + 1)
balancer(a, b, c) |
class ValidationError(Exception):
def __init__(self, message):
super().__init__(message)
class FieldError(Exception):
def __init__(self, field_name, available_fields):
msg = (f"The field '{field_name}' is not present on your model. "
f"Available fields are: {', '.join(available_fields)}")
super().__init__(msg)
class ParserError(Exception):
def __init__(self):
msg = (f"You should provide one of html_document, html_tag or HTMLResponse "
"object to the model in order to resolve fields with a "
"value from the HTML document")
super().__init__(msg)
class ProjectExistsError(FileExistsError):
def __init__(self):
super().__init__('The project path does not exist.')
class ProjectNotConfiguredError(Exception):
def __init__(self):
super().__init__(("You are trying to run a functionnality that requires "
"you project to be fully configured via your settings file."))
class ModelNotImplementedError(Exception):
def __init__(self, message: str=None):
super().__init__(("Conditional (When), aggregate (Add, Substract, Multiply, Divide)"
f" functions should point to a model. {message}"))
class ModelExistsError(Exception):
def __init__(self, name: str):
super().__init__((f"Model '{name}' is already registered."))
class ImproperlyConfiguredError(Exception):
def __init__(self):
super().__init__('Your project is not properly configured.')
class SpiderExistsError(Exception):
def __init__(self, name: str):
super().__init__(f"'{name}' does not exist in the registry. "
f"Did you create '{name}' in your spiders module?")
class ResponseFailedError(Exception):
def __init__(self):
super().__init__("Zineb will not be able to generate a BeautifulSoup object from the response. "
"This is due to a response with a fail status code or being None.")
class RequestAborted(Exception):
pass
class ModelConstrainError(Exception):
def __init__(self, field_name, value):
super().__init__(f"Constraint not respected on '{field_name}'. '{value}' already present in the model.")
| class Validationerror(Exception):
def __init__(self, message):
super().__init__(message)
class Fielderror(Exception):
def __init__(self, field_name, available_fields):
msg = f"The field '{field_name}' is not present on your model. Available fields are: {', '.join(available_fields)}"
super().__init__(msg)
class Parsererror(Exception):
def __init__(self):
msg = f'You should provide one of html_document, html_tag or HTMLResponse object to the model in order to resolve fields with a value from the HTML document'
super().__init__(msg)
class Projectexistserror(FileExistsError):
def __init__(self):
super().__init__('The project path does not exist.')
class Projectnotconfigurederror(Exception):
def __init__(self):
super().__init__('You are trying to run a functionnality that requires you project to be fully configured via your settings file.')
class Modelnotimplementederror(Exception):
def __init__(self, message: str=None):
super().__init__(f'Conditional (When), aggregate (Add, Substract, Multiply, Divide) functions should point to a model. {message}')
class Modelexistserror(Exception):
def __init__(self, name: str):
super().__init__(f"Model '{name}' is already registered.")
class Improperlyconfigurederror(Exception):
def __init__(self):
super().__init__('Your project is not properly configured.')
class Spiderexistserror(Exception):
def __init__(self, name: str):
super().__init__(f"'{name}' does not exist in the registry. Did you create '{name}' in your spiders module?")
class Responsefailederror(Exception):
def __init__(self):
super().__init__('Zineb will not be able to generate a BeautifulSoup object from the response. This is due to a response with a fail status code or being None.')
class Requestaborted(Exception):
pass
class Modelconstrainerror(Exception):
def __init__(self, field_name, value):
super().__init__(f"Constraint not respected on '{field_name}'. '{value}' already present in the model.") |
a = int(input())
if a > 0:
print(1)
elif a== 0:
print(0)
else:
print(-1) | a = int(input())
if a > 0:
print(1)
elif a == 0:
print(0)
else:
print(-1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.