فهرست منبع

Merge branch 'master' of http://37.252.12.59/Home/codewars

dtelenkov 1 سال پیش
والد
کامیت
d8a2699bb0

+ 7 - 4
codewars.code-workspace

@@ -1,8 +1,11 @@
 {
 	"folders": [
-		{
-			"path": "."
-		}
-	],
+        {
+            "path": "."
+        },
+        {
+            "path": "../tmp"
+        }
+    ],
 	"settings": {}
 }

BIN
courses/cpp_1/hello_word


+ 29 - 2
courses/cpp_1/hello_word.cpp

@@ -1,19 +1,39 @@
 #include <iostream>
 using namespace std;
 
+#define sqr(x) x * x
+// #define MAX(a, b, c) ((a) >= (b)) ? (c) = (a) : (c) = (b); 
+#define MAX(x, y, r) {typeof(x) _x = x; typeof(y) _y = y; \
+        (r) = (_x >= _y ? _x : _y);}
+
+
 void sum();
 void out_stream();
 void in_stream();
 void in_stream_get();
+int power(int x, unsigned p);
 
 
 int main()
 {
     std::cout << "Hello, World!\n";
+    int c = 0;
     // sum();
     // out_stream();
     // in_stream();
-    in_stream_get();
+    // in_stream_get();
+
+#if 0
+    int ret = power(5, 2);
+    std::cout << "res = " << ret << "\r\n";
+    ret = power(5, 0);
+    std::cout << "res = " << ret << "\r\n";
+#endif
+
+    // std::cout << sqr(3 + 0) << "\r\n";
+    MAX(4, 6, c);
+    std::cout << c << "\r\n";
+
     return 0;
 }
 
@@ -58,4 +78,11 @@ void in_stream_get()
             std::cout << c;
         else break;
     }
-}
+}
+
+int power(int x, unsigned p)
+{
+    return (!p) ? 1 : x * power(x, p - 1);
+}
+
+

+ 247 - 0
courses/python_for_begginers/exam1.py

@@ -0,0 +1,247 @@
+import random
+
+def game_guesse():
+    x = random.randint(1, 101)
+    print(x)
+    print("Добро пожаловать в числовую угадайку")
+    number = int(input())
+    trys = 1
+    while number:
+        if is_valid(number) == False:
+            print('А может быть все-таки введем целое число от 1 до 100?')
+            number = int(input())
+            trys += 1
+            continue
+        if number > x:
+            print('Ваше число больше загаданного, попробуйте еще разок')
+        elif number < x:
+            print('Ваше число меньше загаданного, попробуйте еще разок')
+        else:
+            print('Вы угадали, поздравляем!')
+            print(f'Число попыток: {trys}')
+            print('Спасибо, что играли в числовую угадайку. Еще увидимся...')
+            break
+        number = int(input())
+        trys += 1
+
+def is_valid(num):
+    return 1 <= num <= 100
+
+# game_guesse()
+
+# Шифр Цезаря. Очень плохая реализация.
+def caesar_cipher_1(data: str, rot: int):
+    RU_LEN = 32
+    chipher_date = ''
+    a = ord('а')
+    A = ord('А')
+    low_case_ch = [chr(x) for x in range(a, a + RU_LEN)]
+    low_case = [x for x in range(a, a + RU_LEN)]
+
+    up_case_ch = [chr(x) for x in range(A, A + RU_LEN)]
+    up_case = [x for x in range(A, A + RU_LEN)]
+
+    print(''.join(low_case_ch))
+    # print(up_case, len(up_case))
+
+    if rot > 31:
+        rot = rot%31
+
+    for i in data:
+        code = ord(i)
+        if code in low_case:
+            if rot > (low_case[-1] - code):
+                chipher_date += chr(low_case[0] + rot - (low_case[-1] - code) - 1)
+            else:
+                chipher_date += chr(code + rot)
+        elif code in up_case:
+            if rot > (up_case[-1] - code):
+                chipher_date += chr(up_case[0] + rot - (up_case[-1] - code) - 1)
+            else:
+                chipher_date += chr(code + rot)
+            
+        else:
+            chipher_date += i
+
+    return chipher_date
+
+
+# Шифр Цезаря. Нормальная реализация.
+def caesar_cipher_2(data: str, rot: int, lang='ru'):
+
+    RU_LEN = 31
+    EN_LEN = 25
+
+    chipher_date = ''
+    d = [chr(x) for x in range(ord('а'), ord('я') + 1)]
+    ru_low_case = ''.join(d) * 2
+    d = [chr(x) for x in range(ord('А'), ord('Я') + 1)]
+    ru_up_case = ''.join(d) * 2
+
+    d = [chr(x) for x in range(ord('a'), ord('z') + 1)]
+    en_low_case = ''.join(d) * 2
+    d = [chr(x) for x in range(ord('A'), ord('Z') + 1)]
+    en_up_case = ''.join(d) * 2
+
+    if lang == 'ru':
+        if rot > RU_LEN:
+            rot = rot%RU_LEN
+        for i in data:
+            if i in ru_low_case:
+                chipher_date += ru_low_case[ru_low_case.index(i) + rot]
+            elif i in ru_up_case:
+                chipher_date += ru_up_case[ru_up_case.index(i) + rot]
+            else:
+                chipher_date += i
+    elif lang == 'en':
+        if rot > EN_LEN:
+            rot = rot%EN_LEN
+        for i in data:
+            if i in en_low_case:
+                chipher_date += en_low_case[en_low_case.index(i) + rot]
+            elif i in en_up_case:
+                chipher_date += en_up_case[en_up_case.index(i) + rot]
+            else:
+                chipher_date += i
+    else:
+        return '-1'
+    
+    return chipher_date
+
+
+# Шифр Цезаря. Нормальная реализация.
+def caesar_recipher_2(data: str, rot: int, lang='ru'):
+
+    RU_LEN = 31
+    EN_LEN = 25
+
+    chipher_date = ''
+    d = [chr(x) for x in range(ord('а'), ord('я') + 1)]
+    ru_low_case = ''.join(d) * 2
+    d = [chr(x) for x in range(ord('А'), ord('Я') + 1)]
+    ru_up_case = ''.join(d) * 2
+
+    d = [chr(x) for x in range(ord('a'), ord('z') + 1)]
+    en_low_case = ''.join(d) * 2
+    d = [chr(x) for x in range(ord('A'), ord('Z') + 1)]
+    en_up_case = ''.join(d) * 2
+
+    if lang == 'ru':
+        if rot > RU_LEN:
+            rot = rot%RU_LEN
+        for i in data:
+            if i in ru_low_case:
+                chipher_date += ru_low_case[ru_low_case.index(i) - rot]
+            elif i in ru_up_case:
+                chipher_date += ru_up_case[ru_up_case.index(i) - rot]
+            else:
+                chipher_date += i
+    elif lang == 'en':
+        if rot > EN_LEN:
+            rot = rot%EN_LEN
+        for i in data:
+            if i in en_low_case:
+                chipher_date += en_low_case[en_low_case.index(i) - rot]
+            elif i in en_up_case:
+                chipher_date += en_up_case[en_up_case.index(i) - rot]
+            else:
+                chipher_date += i
+    else:
+        return '-1'
+    
+    return chipher_date
+
+# print(caesar_cipher_2("Блажен, кто верует, тепло ему на свете!", 10, 'ru'))
+# print(caesar_recipher_2("Лхкрпч, фьш мпъэпь, ьпщхш пцэ чк ымпьп!", 10, 'ru'))
+# print(caesar_cipher_2("To be, or not to be, that is the question!", 17, 'en'))
+
+
+def length(data: str):
+    ret = 0
+    for i in data:
+        if i.isalpha():
+            ret += 1
+    return len([x for x in data if x.isalpha()])
+    
+
+def caesar_cipher_test(data: str):
+    l = data.split()
+    ret = ''
+    for sim in l:
+        rot = length(sim)
+        for i in sim:
+            ret += caesar_cipher_2(i, rot, 'en')
+        ret += ' '
+    return ret
+
+# print(caesar_cipher_test("my name is Python!"))
+# print(caesar_cipher_test('Day, mice. "Year" is a mistake!'))
+
+def test(num):
+    bin_num = bin(num)  # 0b1111111
+    oct_num = oct(num)  # 0o177
+    hex_num = hex(num)  # 0x7f
+
+    print(bin_num[2:])  # 1111111
+    print(oct_num[2:])  # 177
+    print(hex_num[2:])  # 7f
+
+# test(124)
+
+def my_range_gen(*args):
+    if len(args) == 1:
+        cnt = 0
+        while cnt != args[0]:
+            yield cnt
+            cnt += 1
+    elif len(args) == 2:
+        cnt = args[0]
+        while cnt < args[1]:
+            yield cnt
+            cnt += 1
+    elif len(args) == 3:
+        if args[2] > 0:
+            cnt = args[0]
+            while cnt < args[1]:
+                yield cnt
+                cnt += args[2]
+        elif args[2] == 0:
+            return
+        else:
+            cnt = args[0]
+            while cnt > args[1]:
+                yield cnt
+                cnt += args[2]
+
+
+for i in my_range_gen(8):
+    print(i)
+
+# for i in my_range_gen(8, 5, -1):
+#     print(i)
+
+# for i in my_range_gen(10, 30, 3):
+#     print(i)
+
+# for i in my_range_gen(30, 1, 0):
+#     print(i)
+
+# for i in my_range_gen(30, 1, -5):
+#     print(i)
+
+# for i in my_range_gen(5):
+#     print(i)
+
+
+# s = my_range_gen(5)
+# print(next(s))
+# print(next(s))
+# print(next(s))
+# print(next(s))
+# print(next(s))
+# print(next(s))
+        
+# def f(*args, **kwargs):
+# 	print(args, kwargs)
+
+# f(5, 4, 5, 6, 1, a = 1, b = 5, c = 6, name = 123)

+ 10 - 1
courses/python_for_begginers/func.py

@@ -744,4 +744,13 @@ def quick_sort(s):
 # print(starts_with("World"))
 
 # average = lambda *args: sum(*args)/len(*args) 
-# print(average((1, 3, 6, 3)))
+# print(average((1, 3, 6, 3)))
+
+def get_days(month):
+	if month in (1, 3, 5, 7, 8, 10, 12):
+		print(31)
+	elif month == 2:
+		print(28)
+	else:
+		print(30)
+	

+ 65 - 0
courses/python_for_begginers/list.py

@@ -136,3 +136,68 @@ def list_12():
 
 # list_12()
 
+def list_13():
+    l1 = list(map(int, input().split()))
+    l2 = list(map(int, input().split()))
+    for i in range(len(l1)):
+        print(l1[i] + l2[i], end = ' ')
+
+# list_13()
+
+def list_14():
+    l1 = list(map(int, input().split()))
+    l2 = []
+    for i in l1:
+        l2.append(i)
+        l2.append('+')
+
+    l2.pop()
+    print(*l2, sep='', end='')
+    print('=', sum(l1), sep='')
+
+# list_14()
+
+# abc-def-hijk или
+# 7-abc-def-hijk
+
+def list_15():
+    l = list(input())
+    flag = True
+    if (l[3] == l[7] == '-') and len(l) == 12:
+        for i in range(len(l)):
+            if (l[i].isdigit() == False) and (l[i] != '-'):
+                flag = False
+    elif (l[1] == l[5] == l[9] == '-') and len(l) == 14:
+        for i in range(len(l)):
+            if (l[i].isdigit() == False) and (l[i] != '-'):
+                flag = False
+    else:
+        flag = False
+
+    if flag == False:
+        print("NO")
+    else:
+        print("YES")
+
+# list_15()
+
+
+def list_16():
+    l = list(input().split())
+    length = [len(word) for word in l]
+    print(max(length))
+
+# list_16()
+    
+def list_17():
+    l = list(input().split())
+    l2 = []
+    new_word = ''
+    for word in l:
+        new_word = word[1:] + word[0] + 'ки'
+        l2.append(new_word)
+
+    print(*l2)
+
+# list_17()    
+

+ 249 - 0
courses/python_for_begginers/misc.py

@@ -610,3 +610,252 @@ print(a, b, c, d)
 
 # pprint(person)
 
+def test_list(l: list, val: int) -> None:
+    l.append(4)
+    val = 8
+
+# a = 7
+# my_list = [1, 2, 3]
+
+# test_list(my_list, a)
+# print(my_list, a)
+    
+def draw_triangle(fill, base):
+    for i in range(1, int(base/2 + 1) + 1):
+        print(fill*i)
+    for i in range(int(base/2), 0, -1):
+        print(fill*i)
+
+# draw_triangle('*', 9)
+        
+def print_info(name, surname, patronymic):
+    string = surname[0] + name[0] + patronymic[0]
+    print(string.upper())
+
+
+def print_digit_sum(num):
+    ret = 0
+    while num:
+        ret += num%10
+        num = num//10
+    print(ret)
+
+# print_digit_sum(1035)
+
+def get_factors(num):
+    l = []
+    for i in range(1, num + 1):
+        if num%i == 0:
+            l.append(i)
+    return l
+
+# print(get_factors(10))
+
+def number_of_factors(num):
+    return len(get_factors(num))
+               
+# print(number_of_factors(10))
+
+def find_all(target, symbol):
+    l = []
+    s = ""
+    for i in range(len(target)):
+        if target[i] == symbol:
+            l.append(i)
+    return l
+
+# print(find_all('sdfwerasdfqfaf', 's'))
+
+def merge(list1, list2):
+    list1.extend(list2)
+    list1.sort()
+    return list1
+
+# print(merge([1, 2, 3], [5, 6, 7, 8]))
+
+def is_prime(num):
+    cnt = 0
+    for i in range(1, num + 1):
+        if num%i == 0:
+            cnt += 1
+    return cnt == 2
+
+def get_next_prime(num):
+    index = 1
+    while is_prime(num + index) == False:
+        index += 1
+    return num + index
+
+# print(get_next_prime(7))
+
+
+# его длина не менее 8 символов; 
+# он содержит как минимум одну заглавную букву (верхний регистр); 
+# он содержит как минимум одну строчную букву (нижний регистр);
+# он содержит хотя бы одну цифру.
+
+def is_password_good(password):
+    up_flag = False
+    low_flag = False
+    dig_flag = False
+    for i in password:
+        if up_flag == False: up_flag = i.istitle()
+        if low_flag == False: low_flag = i.islower()
+        if dig_flag == False: dig_flag = i.isdigit()
+
+    return len(password) >= 8 and up_flag and low_flag and dig_flag
+
+# print(is_password_good("sfasddfDeqwe"))
+
+
+def is_one_away(word1, word2):
+    cnt = 0
+    len_flag = len(word1) == len(word2)
+
+    if len_flag:
+        for i in range(len(word1)):
+            if word1[i] != word2[i]:
+                cnt +=1
+
+    return len_flag and cnt == 1
+    
+# print(is_one_away("aab", "abc"))
+
+
+def is_palindrome(text:str):
+    s = ''
+    flag = True
+    for i in range(len(text)):
+        if text[i].isalpha():
+            s += text[i].lower()
+
+    for i in range(len(s)//2):
+        if s[i] != s[-1 - i]:
+            flag = False
+
+    return flag
+
+
+# print(is_palindrome("BEEGEEK"))
+
+
+
+    # число a – должно быть палиндромом;
+    # число b – должно быть простым;
+    # число c – должно быть четным.
+
+def is_number_palindrome(num):
+    orig = num
+    new = 0
+    while num:
+        num, d = divmod(num, 10)
+        new = new*10 + d
+
+    return new == orig
+
+def is_simple(num: int):
+    cnt = 0
+    for i in range(1, num + 1):
+        if num%i == 0:
+            cnt += 1
+    return cnt == 2
+
+
+def is_valid_password(password: str):
+    if password.count(":") != 2:
+        return False
+    a, b, c = map(int, password.split(":"))
+
+    return is_number_palindrome(a) and is_simple(b) and c%2 == 0
+
+# print(is_valid_password("24422442:181:890000"))
+
+
+# )(())()(()())((()))()(())
+def is_correct_bracket(text: str):
+    index = 0
+    for i in text:
+        if i == '(':
+            index += 1
+        elif i == ')':
+            index -= 1
+        if index < 0: return False
+    return index == 0
+
+# print(is_correct_bracket("()(())()((())((()))()(())"))
+
+
+def convert_to_python_case(text: str):
+    s = text[0].lower()
+    for i in text[1:]:
+        if i.isupper():
+            s = s + '_' + i.lower()
+        else:
+            s += i
+    return s
+
+# print(convert_to_python_case('ThisIsCamelCased'))
+# print(convert_to_python_case('IsPrimeNumber'))
+
+
+def solve(a, b, c):
+    d = b**2 - 4*a*c
+    if d == 0:
+        return -1*b/(2*a), -1*b/(2*a)
+    x1 = (-1*b + d**0.5)/(2*a)
+    x2 = (-1*b - d**0.5)/(2*a)
+    if x1 <= x2:
+        return x1, x2
+    else:
+        return x2, x1
+
+# вызываем функцию
+# x1, x2 = solve(1, 2, 1)
+# print(x1, x2)
+    
+
+def number_to_words(num):
+    d = {1: 'один', 2: 'два', 3: 'три', 4: 'четыре', 5: 'пять', 6: 'шесть', 7: 'семь', 8: 'восемь', 9: 'девять', 10: 'десять', 11: 'одиннадцать', 12: 'двенадцать', 13: 'тринадцать', 14: 'четырнадцать', 15: 'пятнадцать', 16: 'шестнадцать',17: 'семнадцать', 18: 'восемнадцать', 19: 'девятнадцать', 20: 'двадцать', 30: 'тридцать', 40: 'сорок', 50: 'пятьдесят', 60: 'шестьдесят', 70: 'семьдесят', 80: 'восемьдесят', 90: 'девяносто'}
+    ans = ""
+    f, s = num//10, num%10
+    if num > 20:
+        ans = d[f*10] + " "
+        if s:
+            ans += d[s]
+    else:
+        ans = d[num]
+    return ans
+   
+
+def get_month(language, number):
+    lng_ru = ['январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь']
+
+    lng_en = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
+
+    if language == 'ru':
+        return lng_ru[number - 1]
+    else:
+        return lng_en[number - 1]
+    
+# print(get_month('ru', 1))
+
+def is_magic(date):
+    day, month, year = map(int, date.split('.'))
+    year = year%100
+    return day*month == year
+
+# print(is_magic('10.06.1960'))
+
+from string import ascii_lowercase
+
+def is_pangram(text):
+    flag = True
+    text = text.lower()
+    for i in ascii_lowercase:
+        if i not in text:
+            flag = False
+    return flag
+
+# print(is_pangram('Jackdaws love my big sphinx of quartz'))
+# print(is_pangram('The jay pig fox zebra and my wolves quack'))
+# print(is_pangram('Hello world'))

+ 7 - 0
courses/python_for_begginers/project.py

@@ -0,0 +1,7 @@
+from random import *
+
+print(random())
+print(uniform(1.0, 10.0))
+num = randint(1, 118)
+print(num)
+# print(randrange(1.0, 10.0))

+ 100 - 0
courses/python_for_begginers/sort.py

@@ -173,6 +173,7 @@ def sort_2():
 
 # sort_2()
 
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
 
 def sort_3():
     drivers = {}
@@ -199,3 +200,102 @@ def sort_3():
         print(i[0], i[1])
 
 # sort_3()
+
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
+
+# Сортировка пузырьком
+def sort_bubble():
+    a = [1, 7, -3, 9, 0, -67, 34, 12, 45, 1000, 6,  8, -2, 99]
+    n = len(a)
+    flag = True
+
+    for i in range(n - 1):
+        flag = True
+        for j in range(n - i - 1):
+            if a[j] > a[j + 1]:                  # если порядок элементов пары неправильный
+                a[j], a[j + 1] = a[j + 1], a[j]  # меняем элементы пары местами 
+                flag = False
+        if flag == True:
+            break
+
+    print('Отсортированный список:', a)
+
+# sort_bubble()
+    
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
+
+# Сортировка выбором
+def sort_selection():
+    a = [78, -32, 5, 39, 58, -5, -63, 57, 72, 9, 53, -1, 63, -97,
+        -21, -94, -47, 57, -8, 60, -23, -72, -22, -79, 90, 96, -41,
+        -71, -48, 84, 89, -96, 41, -16, 94, -60, -64, -39, 60, -14,
+        -62, -19, -3, 32, 98, 14, 43, 3, -56, 71, -71, -67, 80, 27,
+        92, 92, -64, 0, -77, 2, -26, 41, 3, -31, 48, 39, 20, -30,
+        35, 32, -58, 2, 63, 64, 66, 62, 82, -62, 9, -52, 35, -61,
+        87, 78, 93, -42, 87, -72, -10, -36, 61, -16, 59, 59, 22,
+        -24, -67, 76, -94, 59]
+
+    n = len(a)
+    
+    new_a = []
+
+    for i in range(len(a)):
+        el = min(a)
+        index = a.index(el)
+        a.pop(index)
+        new_a.append(el)
+
+    print(new_a)
+
+# sort_selection()
+
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
+
+# Сортировка простыми вставками
+def sort_simple_insertion():
+    a = [1, 7, -3, 9, 0, -67, 34, 12, 45, 1000, 6,  8, -2, 99]
+    n = len(a)
+
+    for i in range(1, n): 
+        elem = a[i]  # берем первый элемент из неотсортированной части списка
+        j = i
+        
+        # пока элемент слева существует и больше нашего текущего элемента
+        while j >= 1 and a[j - 1] > elem:
+            # смещаем j-й элемент отсортированной части вправо
+            a[j] = a[j - 1]
+            # сами идём влево, дальше ищем место для нашего текущего элемента
+            j -= 1
+
+        # нашли место для нащего текущего элемента из неотсортированной части
+        # и вставляем его на индекс j в отсортированной части
+        a[j] = elem
+
+    for i in range(1, n):
+        elem = a[1] # первый элемент
+        j = i       
+
+
+    print('Отсортированный список:', a)
+    
+# sort_simple_insertion()
+    
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
+
+# Бинарный поиск
+def binary_search(list, key):
+    low = 0
+    high = len(list) - 1
+
+    while low <= high:
+        mid = (low + high) // 2
+        midVal = list[mid]
+        if midVal == key:
+            return mid
+        if midVal > key:
+            high = mid - 1
+        else:
+            low = mid + 1
+    return 'not found :('
+
+

+ 0 - 2
docs/arbiter_ip.txt

@@ -1,2 +0,0 @@
-jsonrpc server:
-	API

+ 3 - 0
go/go.mod

@@ -0,0 +1,3 @@
+module hello
+
+go 1.19

+ 7 - 0
go/test.go

@@ -0,0 +1,7 @@
+package main
+
+import "fmt"
+
+func main() {
+	fmt.Printf("First go example\n")
+}

+ 22 - 0
jsonrpc/arb_test_req.py

@@ -0,0 +1,22 @@
+import jsonrpclib
+from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
+
+
+
+class JSONRPCClient:
+
+    def __init__(self):
+        self.client = jsonrpclib.Server("http://{0}:{1}".format("localhost", 8082))
+
+    def test(self):
+        print self.client.get_changes()
+
+client = JSONRPCClient()
+client.test()
+
+
+
+"""
+00000000-0000-0000-0000-000000000002
+
+"""

+ 25 - 2
jsonrpc/opcua_traffic.py

@@ -4,16 +4,39 @@ j_get_configuration = """{"jsonrpc": "2.0", "result": {"1ae20d4e-537b-443f-a494-
 
 jresp_sensors = """{"jsonrpc": "2.0", "result": {"AI4": [null, null, 0], "AI1": ["offline", 7103887, 192], "AI3": [null, null, 0], "AI2": ["offline", 7103887, 192], "DI8": ["0", 7103887, 192], "DI4": ["0", 7103887, 192], "DI5": ["0", 7103887, 192], "DI6": ["0", 7103887, 192], "DI7": ["0", 7103887, 192], "DI1": ["0", 7103887, 192], "DI2": ["0", 7103887, 192], "DI3": ["0", 7103887, 192]}, "id": 3}"""
 
+j_get_sensor_by_alias = """{'dim': '', 'group': 'Inputs', 'name': 'Digital Input #1', 'entrance_delay': 0, 'enabled': True, 'iface_spec': None, 'has_device': False, 'security_type': 'service', 'hysteresis': 0.0, 'states': [{'caption': 'opened', 'state': 'almaj', 'flag': 0, 'value': '0'}, {'caption': 'closed', 'state': 'norm', 'flag': 1, 'value': '1'}, {'caption': 'offline', 'state': 'offline', 'flag': 1, 'value': 'n/a'}], 'alias': 'DI1', 'prefix': '', 'web_name': u'\u0414\u0438\u0441\u043a\u0440\u0435\u0442\u043d\u044b\u0439 \u0432\u0445\u043e\u0434 #1', 'editable': None, 'hidden': False, 'state_template': {'caption': 'Caption of state', 'state': 'Sate of sensor', 'value': ['(0|1)', 'Binary value of sensor (0/1)']}, 'history': {'syslog': False, 'state': True, 'archive': False, 'value': False}}"""
+
+
 def jpars():
     # get_configuration = json.loads(j_get_configuration)
     
     # with open("req.json", 'w') as file:
     #     json.dump(get_configuration, file, indent=2)
 
-    get_configuration = json.loads(jresp_sensors)
+    get_configuration = json.loads(j_get_sensor_by_alias)
 
     with open("req.json", 'w') as file:
         json.dump(get_configuration, file, indent=2)
 
         
-jpars()
+#jpars()
+        
+def creat_resp_1():
+    r = {'dim': '', 'group': 'Inputs', 'name': 'Digital Input #1', 'entrance_delay': 0, 'enabled': True, 'iface_spec': None, 'has_device': False, 'security_type': 'service', 'hysteresis': 0.0, 'states': [{'caption': 'opened', 'state': 'almaj', 'flag': 0, 'value': '0'}, {'caption': 'closed', 'state': 'norm', 'flag': 1, 'value': '1'}, {'caption': 'offline', 'state': 'offline', 'flag': 1, 'value': 'n/a'}], 'alias': 'DI1', 'prefix': '', 'web_name': u'\u0414\u0438\u0441\u043a\u0440\u0435\u0442\u043d\u044b\u0439 \u0432\u0445\u043e\u0434 #1', 'editable': None, 'hidden': False, 'state_template': {'caption': 'Caption of state', 'state': 'Sate of sensor', 'value': ['(0|1)', 'Binary value of sensor (0/1)']}, 'history': {'syslog': False, 'state': True, 'archive': False, 'value': False}}
+    
+    alarm_0_name = ''
+    alarm_1_name = ''
+
+    for l in r["states"]:
+        value = l["value"]
+        if value == '0':
+            alarm_0_name = l['caption']
+        elif value == '1':
+            alarm_1_name = l['caption']
+
+    return [int(r['enabled']), r['web_name'], alarm_0_name, alarm_1_name]
+
+    # return resp
+    
+
+print(creat_resp_1())

+ 0 - 0
jsonrpc/resp.json


+ 37 - 0
jsonrpc/teplo_api_controller.py

@@ -0,0 +1,37 @@
+
+# Исходный вариант функции
+def get_current_values(self, device_id, subsystem, value_name_list):
+    if device_id != 'gius-controller':
+        return APIBase.get_current_values(self, device_id, subsystem, value_name_list)
+    
+    result = {}
+    for value_name in value_name_list:
+        try:
+            if value_name.startswith("AI"):
+                v = self.get_sensorman().get_sensor_value_by_alias("teploUB.adc%s"%(value_name[-1]))
+            else:
+                v = self.get_sensorman().get_sensor_value_by_alias("DI%s"%(value_name[-1]))
+            result[value_name] = ( v, int(time.time()), OPC_QUALITY_GOOD )
+        except Exception as e:
+            self.logger.exception("get_current_values {0} error {1}".format(device_id, e))
+            result[value_name] = (None, None, OPC_QUALITY_BAD)
+    return result
+
+# Вариант с дополнениями
+def get_current_values(self, device_id, subsystem, value_name_list):
+    if device_id != 'gius-controller':
+        return APIBase.get_current_values(self, device_id, subsystem, value_name_list)
+    
+    result = {}
+    for value_name in value_name_list:
+        try:
+            if value_name.startswith("AI"):
+                v = self.get_sensorman().get_sensor_value_by_alias("teploUB.adc%s"%(value_name[-1]))
+            else:
+                v = self.get_sensorman().get_sensor_value_by_alias("DI%s"%(value_name[-1]))
+            result[value_name] = ( v, int(time.time()), OPC_QUALITY_GOOD, "str_param" )
+        except Exception as e:
+            self.logger.exception("get_current_values {0} error {1}".format(device_id, e))
+            result[value_name] = (None, None, OPC_QUALITY_BAD)
+    return result
+

+ 40 - 0
leetcode.py

@@ -0,0 +1,40 @@
+# Проверка числа на полиндром
+# divmode(a, b) возвращает картеж: (целая часть от деления a на b, остаток)
+def is_polindrom(x: int) -> bool:
+
+    if x < 0:
+        return False
+
+    new = 0
+    orig = x
+    while x:
+        x, d = divmod(x, 10)
+        new = new*10 + d
+
+    return new == orig    
+
+# print(is_polindrom(121))
+
+
+# Быстрое слияние двух отсортированных списков в один
+def quick_merge(list1, list2):
+    result = []
+    p1 = 0 # указатель на первый элемент списка list1
+    p2 = 0 # указатель на первый элемент списка list2
+
+    while p1 < len(list1) and p2 < len(list2):
+        if list1[p1] < list2[p2]:
+            result.append(list1[p1])
+            p1 += 1
+        else:
+            result.append(list2[p2])
+            p2 += 1
+
+    if p1 < len(list1):
+        result += list1[p1:]
+    else:
+        result += list2[p2:]
+
+    return result
+
+

+ 32 - 0
std_lib/log.py

@@ -0,0 +1,32 @@
+import logging
+
+
+logging.basicConfig(level=logging.INFO, filename="py_log.log", filemode="w",
+                    format="%(asctime)s %(levelname)s %(message)s")
+# logging.info("loggin info")
+
+"""
+x = 3
+y = 0
+
+logging.info(f"The value of x and y are {x} and {y}.")
+
+try:
+    x/y
+    logging.info(f"x/y successful with result: {x/y}.")
+except ZeroDivisionError as err:
+    logging.error("ZeroDivisionError", exc_info=True)
+"""
+
+x_vals = [2,3,6,4,10]
+y_vals = [5,7,12,0,1]
+
+for x_val, y_val in zip(x_vals, y_vals):
+    x, y = x_val, y_val
+    logging.info(f"The values of x and y are {x} and {y}.")
+    try:
+        x/y
+        logging.info(f"x/y successful with result: {x/y}.")
+    except ZeroDivisionError as err:
+        logging.exception("ZeroDivisionError")
+        

+ 14 - 0
std_lib/py_log.log

@@ -0,0 +1,14 @@
+2023-12-18 15:05:19,255 INFO The values of x and y are 2 and 5.
+2023-12-18 15:05:19,256 INFO x/y successful with result: 0.4.
+2023-12-18 15:05:19,256 INFO The values of x and y are 3 and 7.
+2023-12-18 15:05:19,256 INFO x/y successful with result: 0.42857142857142855.
+2023-12-18 15:05:19,256 INFO The values of x and y are 6 and 12.
+2023-12-18 15:05:19,256 INFO x/y successful with result: 0.5.
+2023-12-18 15:05:19,256 INFO The values of x and y are 4 and 0.
+2023-12-18 15:05:19,256 ERROR ZeroDivisionError
+Traceback (most recent call last):
+  File "log.py", line 28, in <module>
+    x/y
+ZeroDivisionError: division by zero
+2023-12-18 15:05:19,256 INFO The values of x and y are 10 and 1.
+2023-12-18 15:05:19,256 INFO x/y successful with result: 10.0.